-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathimage-watermark.php
1505 lines (1238 loc) · 50.9 KB
/
image-watermark.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
Plugin Name: Image Watermark
Description: Image Watermark allows you to automatically watermark images uploaded to the WordPress Media Library and bulk watermark previously uploaded images.
Version: 1.7.4
Author: dFactory
Author URI: http://www.dfactory.co/
Plugin URI: http://www.dfactory.co/products/image-watermark/
License: MIT License
License URI: http://opensource.org/licenses/MIT
Text Domain: image-watermark
Domain Path: /languages
Image Watermark
Copyright (C) 2013-2023, Digital Factory - info@digitalfactory.pl
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// exit if accessed directly
if ( ! defined( 'ABSPATH' ) )
exit;
/**
* Image Watermark class.
*
* @class Image_Watermark
* @version 1.7.4
*/
final class Image_Watermark {
private static $instance;
private $is_admin = true;
private $extension = false;
private $allowed_mime_types = [
'image/jpeg',
'image/pjpeg',
'image/png'
];
private $is_watermarked_metakey = 'iw-is-watermarked';
public $is_backup_folder_writable = null;
public $extensions;
public $defaults = [
'options' => [
'watermark_on' => [],
'watermark_cpt_on' => [ 'everywhere' ],
'watermark_image' => [
'extension' => '',
'url' => 0,
'width' => 80,
'plugin_off' => 0,
'frontend_active' => false,
'manual_watermarking' => 0,
'position' => 'bottom_right',
'watermark_size_type' => 2,
'offset_unit' => 'pixels',
'offset_width' => 0,
'offset_height' => 0,
'absolute_width' => 0,
'absolute_height' => 0,
'transparent' => 50,
'quality' => 90,
'jpeg_format' => 'baseline',
'deactivation_delete' => false,
'media_library_notice' => true
],
'image_protection' => [
'rightclick' => 0,
'draganddrop' => 0,
'forlogged' => 0
],
'backup' => [
'backup_image' => true,
'backup_quality' => 90
]
],
'version' => '1.7.4'
];
public $options = [];
/**
* Class constructor.
*
* @return void
*/
public function __construct() {
// define plugin constants
$this->define_constants();
// activation hooks
register_activation_hook( __FILE__, [ $this, 'activate_watermark' ] );
register_deactivation_hook( __FILE__, [ $this, 'deactivate_watermark' ] );
// settings
$options = get_option( 'image_watermark_options', $this->defaults['options'] );
$this->options = array_merge( $this->defaults['options'], $options );
$this->options['watermark_image'] = array_merge( $this->defaults['options']['watermark_image'], $options['watermark_image'] );
$this->options['image_protection'] = array_merge( $this->defaults['options']['image_protection'], $options['image_protection'] );
$this->options['backup'] = array_merge( $this->defaults['options']['backup'], isset( $options['backup'] ) ? $options['backup'] : [] );
include_once( IMAGE_WATERMARK_PATH . 'includes/class-update.php' );
include_once( IMAGE_WATERMARK_PATH . 'includes/class-settings.php' );
// actions
add_action( 'init', [ $this, 'load_textdomain' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
add_action( 'wp_enqueue_media', [ $this, 'wp_enqueue_media' ] );
add_action( 'wp_enqueue_scripts', [ $this, 'wp_enqueue_scripts' ] );
add_action( 'load-upload.php', [ $this, 'watermark_bulk_action' ] );
add_action( 'admin_init', [ $this, 'update_plugin' ] );
add_action( 'admin_init', [ $this, 'check_extensions' ] );
add_action( 'admin_notices', [ $this, 'bulk_admin_notices' ] );
add_action( 'delete_attachment', [ $this, 'delete_attachment' ] );
add_action( 'wp_ajax_iw_watermark_bulk_action', [ $this, 'watermark_action_ajax' ] );
// filters
add_filter( 'plugin_action_links_' . IMAGE_WATERMARK_BASENAME, [ $this, 'plugin_settings_link' ] );
add_filter( 'plugin_row_meta', [ $this, 'plugin_extend_links' ], 10, 2 );
add_filter( 'wp_handle_upload', [ $this, 'handle_upload_files' ] );
add_filter( 'attachment_fields_to_edit', [ $this, 'attachment_fields_to_edit' ], 10, 2 );
// define our backup location
$upload_dir = wp_upload_dir();
define( 'IMAGE_WATERMARK_BACKUP_DIR', apply_filters( 'image_watermark_backup_dir', $upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'iw-backup' ) );
// create backup folder and security if enabled
if ( $this->options['backup']['backup_image'] ) {
if ( is_writable( $upload_dir['basedir'] ) ) {
$this->is_backup_folder_writable = true;
// create backup folder ( if it exists this returns true: https://codex.wordpress.org/Function_Reference/wp_mkdir_p )
$backup_folder_created = wp_mkdir_p( IMAGE_WATERMARK_BACKUP_DIR );
// check if the folder exists and is writable
if ( $backup_folder_created && is_writable( IMAGE_WATERMARK_BACKUP_DIR ) ) {
// check if the htaccess file exists
if ( ! file_exists( IMAGE_WATERMARK_BACKUP_DIR . DIRECTORY_SEPARATOR . '.htaccess' ) ) {
// htaccess security
file_put_contents( IMAGE_WATERMARK_BACKUP_DIR . DIRECTORY_SEPARATOR . '.htaccess', 'deny from all' );
}
} else
$this->is_backup_folder_writable = false;
} else
$this->is_backup_folder_writable = false;
if ( $this->is_backup_folder_writable !== true ) {
// disable backup setting
$this->options['backup']['backup_image'] = false;
update_option( 'image_watermark_options', $this->options );
}
add_action( 'admin_notices', [ $this, 'folder_writable_admin_notice' ] );
}
}
/**
* Disable object cloning.
*
* @return void
*/
public function __clone() {}
/**
* Disable unserializing of the class.
*
* @return void
*/
public function __wakeup() {}
/**
* Main plugin instance, insures that only one instance of the plugin exists in memory at one time.
*
* @return object
*/
public static function instance() {
if ( self::$instance === null )
self::$instance = new self();
return self::$instance;
}
/**
* Setup plugin constants.
*
* @return void
*/
private function define_constants() {
define( 'IMAGE_WATERMARK_URL', plugins_url( '', __FILE__ ) );
define( 'IMAGE_WATERMARK_PATH', plugin_dir_path( __FILE__ ) );
define( 'IMAGE_WATERMARK_BASENAME', plugin_basename( __FILE__ ) );
define( 'IMAGE_WATERMARK_REL_PATH', dirname( IMAGE_WATERMARK_BASENAME ) );
}
/**
* Plugin activation.
*
* @return void
*/
public function activate_watermark() {
// add default options
add_option( 'image_watermark_options', $this->defaults['options'], null, false );
add_option( 'image_watermark_version', $this->defaults['version'], null, false );
}
/**
* Plugin deactivation.
*
* @return void
*/
public function deactivate_watermark() {
// remove options from database?
if ( $this->options['watermark_image']['deactivation_delete'] )
delete_option( 'image_watermark_options' );
}
/**
* Plugin update, fix for version < 1.5.0.
*
* @return void
*/
public function update_plugin() {
if ( ! current_user_can( 'install_plugins' ) )
return;
$db_version = get_option( 'image_watermark_version' );
$db_version = ! ( $db_version ) && ( get_option( 'df_watermark_installed' ) != false ) ? get_option( 'version' ) : $db_version;
if ( $db_version != false ) {
if ( version_compare( $db_version, '1.5.0', '<' ) ) {
$options = [];
$old_new = [
'df_watermark_on' => 'watermark_on',
'df_watermark_cpt_on' => 'watermark_cpt_on',
'df_watermark_image' => 'watermark_image',
'df_image_protection' => 'image_protection',
'df_watermark_installed' => '',
'version' => '',
'image_watermark_version' => '',
];
foreach ( $old_new as $old => $new ) {
if ( $new )
$options[$new] = get_option( $old );
delete_option( $old );
}
add_option( 'image_watermark_options', $options, null, false );
add_option( 'image_watermark_version', $this->defaults['version'], null, false );
}
}
}
/**
* Load textdomain.
*
* @return void
*/
public function load_textdomain() {
load_plugin_textdomain( 'image-watermark', false, IMAGE_WATERMARK_REL_PATH . '/languages/' );
}
/**
* Enqueue admin scripts and styles.
*
* @return void
*/
public function wp_enqueue_media( $page ) {
wp_enqueue_style( 'watermark-style', IMAGE_WATERMARK_URL . '/css/image-watermark.css', [], $this->defaults['version'] );
}
/**
* Enqueue admin scripts and styles.
*
* @global $pagenow
* @return void
*/
public function admin_enqueue_scripts( $page ) {
global $pagenow;
wp_register_style( 'watermark-style', IMAGE_WATERMARK_URL . '/css/image-watermark.css', [], $this->defaults['version'] );
if ( $page === 'settings_page_watermark-options' ) {
wp_enqueue_media();
wp_enqueue_script( 'image-watermark-upload-manager', IMAGE_WATERMARK_URL . '/js/admin-upload.js', [], $this->defaults['version'] );
// prepare script data
$script_data = [
'title' => __( 'Select watermark', 'image-watermark' ),
'originalSize' => __( 'Original size', 'image-watermark' ),
'noSelectedImg' => __( 'Watermak has not been selected yet.', 'image-watermark' ),
'notAllowedImg' => __( 'This image is not supported as watermark. Use JPEG, PNG or GIF.', 'image-watermark' ),
'px' => __( 'px', 'image-watermark' ),
'frame' => 'select',
'button' => [ 'text' => __( 'Add watermark', 'image-watermark' ) ],
'multiple' => false
];
wp_add_inline_script( 'image-watermark-upload-manager', 'var iwArgsUpload = ' . wp_json_encode( $script_data ) . ";\n", 'before' );
wp_enqueue_script( 'image-watermark-admin-settings', IMAGE_WATERMARK_URL . '/js/admin-settings.js', [ 'jquery', 'jquery-ui-core', 'jquery-ui-button', 'jquery-ui-slider' ], $this->defaults['version'] );
// prepare script data
$script_data = [
'resetToDefaults' => __( 'Are you sure you want to reset settings to defaults?', 'image-watermark' )
];
wp_add_inline_script( 'image-watermark-admin-settings', 'var iwArgsSettings = ' . wp_json_encode( $script_data ) . ";\n", 'before' );
wp_enqueue_style( 'wp-like-ui-theme', IMAGE_WATERMARK_URL . '/css/wp-like-ui-theme.css', [], $this->defaults['version'] );
wp_enqueue_style( 'watermark-style' );
wp_enqueue_script( 'postbox' );
}
if ( $pagenow === 'upload.php' ) {
if ( $this->options['watermark_image']['manual_watermarking'] == 1 && current_user_can( 'upload_files' ) ) {
wp_enqueue_script( 'image-watermark-admin-media', IMAGE_WATERMARK_URL . '/js/admin-media.js', [ 'jquery' ], $this->defaults['version'], false );
// prepare script data
$script_data = [
'backupImage' => (bool) $this->options['backup']['backup_image'],
'applyWatermark' => __( 'Apply watermark', 'image-watermark' ),
'removeWatermark' => __( 'Remove watermark', 'image-watermark' )
];
wp_add_inline_script( 'image-watermark-admin-media', 'var iwArgsMedia = ' . wp_json_encode( $script_data ) . ";\n", 'before' );
}
wp_enqueue_style( 'watermark-style' );
}
// image modal could be loaded in various places
if ( $this->options['watermark_image']['manual_watermarking'] == 1 ) {
wp_enqueue_script( 'image-watermark-admin-image-actions', IMAGE_WATERMARK_URL . '/js/admin-image-actions.js', [ 'jquery' ], $this->defaults['version'], true );
// prepare script data
$script_data = [
'backup_image' => (bool) $this->options['backup']['backup_image'],
'_nonce' => wp_create_nonce( 'image-watermark' ),
'__applied_none' => __( 'Watermark could not be applied to selected files or no valid images (JPEG, PNG) were selected.', 'image-watermark' ),
'__applied_one' => __( 'Watermark was successfully applied to 1 image.', 'image-watermark' ),
'__applied_multi' => __( 'Watermark was successfully applied to %s images.', 'image-watermark' ),
'__removed_none' => __( 'Watermark could not be removed from selected files or no valid images (JPEG, PNG) were selected.', 'image-watermark' ),
'__removed_one' => __( 'Watermark was successfully removed from 1 image.', 'image-watermark' ),
'__removed_multi' => __( 'Watermark was successfully removed from %s images.', 'image-watermark' ),
'__skipped' => __( 'Skipped files', 'image-watermark' ),
'__running' => __( 'Bulk action is currently running, please wait.', 'image-watermark' ),
'__dismiss' => __( 'Dismiss this notice.' ) // WordPress default string
];
wp_add_inline_script( 'image-watermark-admin-image-actions', 'var iwArgsImageActions = ' . wp_json_encode( $script_data ) . ";\n", 'before' );
}
}
/**
* Enqueue frontend script with 'no right click' and 'drag and drop' functions.
*
* @return void
*/
public function wp_enqueue_scripts() {
$right_click = true;
if ( ( $this->options['image_protection']['forlogged'] == 0 && is_user_logged_in() ) || ( $this->options['image_protection']['draganddrop'] == 0 && $this->options['image_protection']['rightclick'] == 0 ) )
$right_click = false;
if ( apply_filters( 'iw_block_right_click', (bool) $right_click ) === true ) {
wp_enqueue_script( 'image-watermark-no-right-click', IMAGE_WATERMARK_URL . '/js/no-right-click.js', [], $this->defaults['version'] );
// prepare script data
$script_data = [
'rightclick' => ( $this->options['image_protection']['rightclick'] == 1 ? 'Y' : 'N' ),
'draganddrop' => ( $this->options['image_protection']['draganddrop'] == 1 ? 'Y' : 'N' )
];
wp_add_inline_script( 'image-watermark-no-right-click', 'var iwArgsNoRightClick = ' . wp_json_encode( $script_data ) . ";\n", 'before' );
}
}
/**
* Check which extension is available and set it.
*
* @return void
*/
public function check_extensions() {
$ext = null;
if ( $this->check_imagick() ) {
$this->extensions['imagick'] = 'ImageMagick';
$ext = 'imagick';
}
if ( $this->check_gd() ) {
$this->extensions['gd'] = 'GD';
if ( is_null( $ext ) )
$ext = 'gd';
}
if ( isset( $this->options['watermark_image']['extension'] ) ) {
if ( $this->options['watermark_image']['extension'] === 'imagick' && isset( $this->extensions['imagick'] ) )
$this->extension = 'imagick';
elseif ( $this->options['watermark_image']['extension'] === 'gd' && isset( $this->extensions['gd'] ) )
$this->extension = 'gd';
else
$this->extension = $ext;
} else
$this->extension = $ext;
}
/**
* Apply watermark everywhere or for specific post types.
*
* @param resource $file
* @return resource
*/
public function handle_upload_files( $file ) {
// is extension available?
if ( $this->extension ) {
// determine ajax frontend or backend request
$script_filename = isset( $_SERVER['SCRIPT_FILENAME'] ) ? $_SERVER['SCRIPT_FILENAME'] : '';
// try to figure out if frontend AJAX request... if we are DOING_AJAX; let's look closer
if ( ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
// from wp-includes/functions.php, wp_get_referer() function.
// required to fix: https://core.trac.wordpress.org/ticket/25294
$ref = '';
if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
$ref = wp_unslash( $_REQUEST['_wp_http_referer'] );
elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) )
$ref = wp_unslash( $_SERVER['HTTP_REFERER'] );
// if referer does not contain admin URL and we are using the admin-ajax.php endpoint, this is likely a frontend AJAX request
if ( ( ( strpos( $ref, admin_url() ) === false ) && ( basename( $script_filename ) === 'admin-ajax.php' ) ) )
$this->is_admin = false;
else
$this->is_admin = true;
// not an AJAX request, simple here
} else {
if ( is_admin() )
$this->is_admin = true;
else
$this->is_admin = false;
}
// admin
if ( $this->is_admin === true ) {
if ( $this->options['watermark_image']['plugin_off'] == 1 && wp_attachment_is_image( $this->options['watermark_image']['url'] ) && in_array( $file['type'], $this->allowed_mime_types ) )
add_filter( 'wp_generate_attachment_metadata', [ $this, 'apply_watermark' ], 10, 2 );
// frontend
} else {
if ( $this->options['watermark_image']['frontend_active'] == 1 && wp_attachment_is_image( $this->options['watermark_image']['url'] ) && in_array( $file['type'], $this->allowed_mime_types ) )
add_filter( 'wp_generate_attachment_metadata', [ $this, 'apply_watermark' ], 10, 2 );
}
}
return $file;
}
/**
* Add watermark buttons on attachment image locations.
*
* @param array $form_fields
* @param object $post
* return array
*/
public function attachment_fields_to_edit( $form_fields, $post ) {
if ( $this->options['watermark_image']['manual_watermarking'] == 1 && $this->options['backup']['backup_image'] ) {
$data = wp_get_attachment_metadata( $post->ID, false );
// is this really an image?
if ( in_array( get_post_mime_type( $post->ID ), $this->allowed_mime_types ) && is_array( $data ) ) {
$form_fields['image_watermark'] = [
'show_in_edit' => false,
'tr' => '
<div id="image_watermark_buttons"' . ( get_post_meta( $post->ID, $this->is_watermarked_metakey, true ) ? ' class="watermarked"' : '' ) . ' data-id="' . $post->ID . '" style="display: none;">
<label class="setting">
<span class="name">' . __( 'Image Watermark', 'image-watermark' ) . '</span>
<span class="value" style="width: 63%"><a href="#" class="iw-watermark-action" data-action="applywatermark" data-id="' . $post->ID . '">' . __( 'Apply watermark', 'image-watermark' ) . '</a> | <a href="#" class="iw-watermark-action delete-watermark" data-action="removewatermark" data-id="' . $post->ID . '">' . __( 'Remove watermark', 'image-watermark' ) . '</a></span>
</label>
<div class="clear"></div>
</div>
<script>
jQuery( function() {
if ( typeof watermarkImageActions !== "undefined" )
jQuery( "#image_watermark_buttons" ).show();
} );
</script>'
];
}
}
return $form_fields;
}
/**
* Apply watermark for selected images on media page.
*
* @return void
*/
public function watermark_action_ajax() {
// Security & data check
if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || ! isset( $_POST['_iw_nonce'] ) || ! isset( $_POST['iw-action'] ) || ! isset( $_POST['attachment_id'] ) || ! is_numeric( $_POST['attachment_id'] ) || ! wp_verify_nonce( $_POST['_iw_nonce'], 'image-watermark' ) || ! current_user_can( 'upload_files' ) )
wp_send_json_error( __( 'Cheatin uh?', 'image-watermark' ) );
// cast post id
$post_id = (int) $_POST['attachment_id'];
// sanitize action name
$action = sanitize_key( $_POST['iw-action'] );
$action = in_array( $action, [ 'applywatermark', 'removewatermark' ], true ) ? $action : false;
// only if manual watermarking is turned and we have a valid action
// if the action is NOT "removewatermark" we also require a watermark image to be set
if ( $post_id > 0 && $action && $this->options['watermark_image']['manual_watermarking'] == 1 && ( wp_attachment_is_image( $this->options['watermark_image']['url'] ) || $action == 'removewatermark' ) ) {
$data = wp_get_attachment_metadata( $post_id, false );
// is this really an image?
if ( in_array( get_post_mime_type( $post_id ), $this->allowed_mime_types ) && is_array( $data ) ) {
if ( $action === 'applywatermark' ) {
$success = $this->apply_watermark( $data, $post_id, 'manual' );
if ( ! empty( $success['error'] ) )
wp_send_json_success( $success['error'] );
else
wp_send_json_success( 'watermarked' );
} elseif ( $action === 'removewatermark' ) {
$success = $this->remove_watermark( $data, $post_id, 'manual' );
if ( $success )
wp_send_json_success( 'watermarkremoved' );
else
wp_send_json_success( 'skipped' );
}
} else
wp_send_json_success( 'skipped' );
}
wp_send_json_error( __( 'Cheatin uh?', 'image-watermark' ) );
}
/**
* Apply watermark for selected images on media page.
*
* @return void
*/
public function watermark_bulk_action() {
global $pagenow;
if ( $pagenow == 'upload.php' && $this->extension ) {
$wp_list_table = _get_list_table( 'WP_Media_List_Table' );
$action = $wp_list_table->current_action();
$action = in_array( $action, [ 'applywatermark', 'removewatermark' ], true ) ? $action : false;
// only if manual watermarking is turned and we have a valid action
// if the action is NOT "removewatermark" we also require a watermark image to be set
if ( $action && $this->options['watermark_image']['manual_watermarking'] == 1 && ( wp_attachment_is_image( $this->options['watermark_image']['url'] ) || $action == 'removewatermark' ) ) {
// security check
check_admin_referer( 'bulk-media' );
$location = esc_url( remove_query_arg( [ 'watermarked', 'watermarkremoved', 'skipped', 'trashed', 'untrashed', 'deleted', 'message', 'ids', 'posted' ], wp_get_referer() ) );
if ( ! $location )
$location = 'upload.php';
$location = esc_url( add_query_arg( 'paged', $wp_list_table->get_pagenum(), $location ) );
// make sure ids are submitted. depending on the resource type, this may be 'media' or 'ids'
if ( isset( $_REQUEST['media'] ) )
$post_ids = array_map( 'intval', $_REQUEST['media'] );
// do we have selected attachments?
if ( $post_ids ) {
$watermarked = $watermarkremoved = $skipped = 0;
$messages = [];
foreach ( $post_ids as $post_id ) {
$data = wp_get_attachment_metadata( $post_id, false );
// is this really an image?
if ( in_array( get_post_mime_type( $post_id ), $this->allowed_mime_types ) && is_array( $data ) ) {
if ( $action === 'applywatermark' ) {
$success = $this->apply_watermark( $data, $post_id, 'manual' );
if ( ! empty( $success['error'] ) )
$messages[] = $success['error'];
else {
$watermarked++;
$watermarkremoved = -1;
}
} elseif ( $action === 'removewatermark' ) {
$success = $this->remove_watermark( $data, $post_id, 'manual' );
if ( $success )
$watermarkremoved++;
else
$skipped++;
$watermarked = -1;
}
} else
$skipped++;
}
$location = esc_url( add_query_arg( [ 'watermarked' => $watermarked, 'watermarkremoved' => $watermarkremoved, 'skipped' => $skipped, 'messages' => $messages ], $location ), null, '' );
}
wp_redirect( $location );
exit();
} else
return;
}
}
/**
* Display admin notices.
*
* @return void
*/
public function bulk_admin_notices() {
global $post_type, $pagenow;
if ( $pagenow === 'upload.php' ) {
if ( ! current_user_can( 'upload_files' ) )
return;
// hide media library notice
if ( isset( $_GET['iw_action'] ) && $_GET['iw_action'] == 'hide_library_notice' ) {
$this->options['watermark_image']['media_library_notice'] = false;
update_option( 'image_watermark_options', $this->options );
}
// check if manual watermarking is enabled
if ( ! empty( $this->options['watermark_image']['manual_watermarking'] ) && ( ! isset( $this->options['watermark_image']['media_library_notice'] ) || $this->options['watermark_image']['media_library_notice'] === true ) ) {
$mode = get_user_option( 'media_library_mode', get_current_user_id() ) ? get_user_option( 'media_library_mode', get_current_user_id() ) : 'grid';
if ( isset( $_GET['mode'] ) && in_array( $_GET['mode'], [ 'grid', 'list' ] ) )
$mode = $_GET['mode'];
// display notice in grid mode only
if ( $mode === 'grid' ) {
// get current admin url
$query_string = [];
parse_str( $_SERVER['QUERY_STRING'], $query_string );
$current_url = esc_url( add_query_arg( array_merge( (array) $query_string, [ 'iw_action' => 'hide_library_notice' ] ), '', admin_url( trailingslashit( $pagenow ) ) ) );
echo '<div class="error notice"><p>' . sprintf( __( '<strong>Image Watermark:</strong> Bulk watermarking is available in list mode only, under <em>Bulk Actions</em> dropdown. <a href="%1$s">Got to List Mode</a> or <a href="%2$s">Hide this notice</a>', 'image-watermark' ), esc_url( admin_url( 'upload.php?mode=list' ) ), esc_url( $current_url ) ) . '</p></div>';
}
}
if ( isset( $_REQUEST['watermarked'], $_REQUEST['watermarkremoved'], $_REQUEST['skipped'] ) && $post_type === 'attachment' ) {
$watermarked = (int) $_REQUEST['watermarked'];
$watermarkremoved = (int) $_REQUEST['watermarkremoved'];
$skipped = (int) $_REQUEST['skipped'];
if ( $watermarked === 0 )
echo '<div class="error"><p>' . __( 'Watermark could not be applied to selected files or no valid images (JPEG, PNG) were selected.', 'image-watermark' ) . ($skipped > 0 ? ' ' . __( 'Images skipped', 'image-watermark' ) . ': ' . $skipped . '.' : '') . '</p></div>';
elseif ( $watermarked > 0 )
echo '<div class="updated"><p>' . sprintf( _n( 'Watermark was successfully applied to 1 image.', 'Watermark was successfully applied to %s images.', $watermarked, 'image-watermark' ), number_format_i18n( $watermarked ) ) . ($skipped > 0 ? ' ' . __( 'Skipped files', 'image-watermark' ) . ': ' . $skipped . '.' : '') . '</p></div>';
if ( $watermarkremoved === 0 )
echo '<div class="error"><p>' . __( 'Watermark could not be removed from selected files or no valid images (JPEG, PNG) were selected.', 'image-watermark' ) . ($skipped > 0 ? ' ' . __( 'Images skipped', 'image-watermark' ) . ': ' . $skipped . '.' : '') . '</p></div>';
elseif ( $watermarkremoved > 0 )
echo '<div class="updated"><p>' . sprintf( _n( 'Watermark was successfully removed from 1 image.', 'Watermark was successfully removed from %s images.', $watermarkremoved, 'image-watermark' ), number_format_i18n( $watermarkremoved ) ) . ($skipped > 0 ? ' ' . __( 'Skipped files', 'image-watermark' ) . ': ' . $skipped . '.' : '') . '</p></div>';
$_SERVER['REQUEST_URI'] = esc_url( remove_query_arg( [ 'watermarked', 'skipped' ], $_SERVER['REQUEST_URI'] ) );
}
}
}
/**
* Check whether ImageMagick extension is available.
*
* @return bool
*/
public function check_imagick() {
// check Imagick's extension and classes
if ( ! extension_loaded( 'imagick' ) || ! class_exists( 'Imagick', false ) || ! class_exists( 'ImagickPixel', false ) )
return false;
// check version
if ( version_compare( phpversion( 'imagick' ), '2.2.0', '<' ) )
return false;
// check for deep requirements within Imagick
if ( ! defined( 'imagick::COMPRESSION_JPEG' ) || ! defined( 'imagick::COMPOSITE_OVERLAY' ) || ! defined( 'Imagick::INTERLACE_PLANE' ) || ! defined( 'imagick::FILTER_CATROM' ) || ! defined( 'Imagick::CHANNEL_ALL' ) )
return false;
// check methods
if ( array_diff( [ 'clear', 'destroy', 'valid', 'getimage', 'writeimage', 'getimagegeometry', 'getimageformat', 'setimageformat', 'setimagecompression', 'setimagecompressionquality', 'scaleimage' ], get_class_methods( 'Imagick' ) ) )
return false;
return true;
}
/**
* Check whether GD extension is available.
*
* @return bool
*/
public function check_gd( $args = [] ) {
// check extension
if ( ! extension_loaded( 'gd' ) || ! function_exists( 'gd_info' ) )
return false;
return true;
}
/**
* Apply watermark to selected image sizes.
*
* @param array $data
* @param int|string $attachment_id Attachment ID
* @param string $method
* @return array
*/
public function apply_watermark( $data, $attachment_id, $method = '' ) {
$attachment_id = (int) $attachment_id;
$post = get_post( $attachment_id );
$post_id = ( ! empty( $post ) ? (int) $post->post_parent : 0 );
if ( $attachment_id === (int) $this->options['watermark_image']['url'] ) {
// this is the current watermark, do not apply
return [ 'error' => __( 'Watermark prevented, this is your selected watermark image', 'image-watermark' ) ];
}
// something went wrong or is it automatic mode?
if ( $method !== 'manual' && ( $this->is_admin === true && ! ( ( isset( $this->options['watermark_cpt_on'][0] ) && $this->options['watermark_cpt_on'][0] === 'everywhere' ) || ( $post_id > 0 && in_array( get_post_type( $post_id ), array_keys( $this->options['watermark_cpt_on'] ) ) === true ) ) ) )
return $data;
if ( apply_filters( 'iw_watermark_display', $attachment_id ) === false )
return $data;
// get upload dir data
$upload_dir = wp_upload_dir();
// assign original (full) file
$original_file = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . $data['file'];
// is this really an image?
if ( getimagesize( $original_file, $original_image_info ) !== false ) {
$metadata = $this->get_image_metadata( $original_image_info );
// remove the watermark if this image was already watermarked
if ( (int) get_post_meta( $attachment_id, $this->is_watermarked_metakey, true ) === 1 )
$this->remove_watermark( $data, $attachment_id, 'manual' );
// create a backup if this is enabled
if ( $this->options['backup']['backup_image'] )
$this->do_backup( $data, $upload_dir, $attachment_id );
// loop through active image sizes
foreach ( $this->options['watermark_on'] as $image_size => $active_size ) {
if ( $active_size === 1 ) {
switch ( $image_size ) {
case 'full':
$filepath = $original_file;
break;
default:
if ( ! empty( $data['sizes'] ) && array_key_exists( $image_size, $data['sizes'] ) )
$filepath = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . dirname( $data['file'] ) . DIRECTORY_SEPARATOR . $data['sizes'][$image_size]['file'];
else
// early getaway
continue 2;
}
do_action( 'iw_before_apply_watermark', $attachment_id, $image_size );
// apply watermark
$this->do_watermark( $attachment_id, $filepath, $image_size, $upload_dir, $metadata );
// save metadata
$this->save_image_metadata( $metadata, $filepath );
do_action( 'iw_after_apply_watermark', $attachment_id, $image_size );
}
}
// update watermark status
update_post_meta( $attachment_id, $this->is_watermarked_metakey, 1 );
}
// pass forward attachment metadata
return $data;
}
/**
* Remove watermark from selected image sizes.
*
* @param array $data
* @param int|string $attachment_id Attachment ID
* @param string $method
* @return array
*/
private function remove_watermark( $data, $attachment_id, $method = '' ) {
if ( $method !== 'manual' )
return $data;
$upload_dir = wp_upload_dir();
// is this really an image?
if ( getimagesize( $upload_dir['basedir'] . DIRECTORY_SEPARATOR . $data['file'] ) !== false ) {
// live file path (probably watermarked)
$filepath = get_attached_file( $attachment_id );
// backup file path (not watermarked)
$backup_filepath = $this->get_image_backup_filepath( get_post_meta( $attachment_id, '_wp_attached_file', true ) );
// replace the image in uploads with our backup if one exists
if ( file_exists( $backup_filepath ) ) {
if ( ! copy( $backup_filepath, $filepath ) ) {
// Failed to copy
}
}
// if no backup exists, use the current full-size image to regenerate
// if the "full" size is enabled for watermarks and no backup has been made the removal of watermarks can't be done
// regenerate metadata (and thumbs)
$metadata = wp_generate_attachment_metadata( $attachment_id, $filepath );
// update attachment metadata with new metadata
wp_update_attachment_metadata( $attachment_id, $metadata );
// update watermark status
update_post_meta( $attachment_id, $this->is_watermarked_metakey, 0 );
// ureturn the attachment metadata
return wp_get_attachment_metadata( $attachment_id );
}
return false;
}
/**
* Get image metadata.
*
* @param array $imageinfo
* @return array
*/
public function get_image_metadata( $imageinfo ) {
$metadata = [
'exif' => null,
'iptc' => null
];
if ( is_array( $imageinfo ) ) {
// prepare EXIF data bytes from source file
$exifdata = key_exists( 'APP1', $imageinfo ) ? $imageinfo['APP1'] : null;
if ( $exifdata ) {
$exiflength = strlen( $exifdata ) + 2;
// construct EXIF segment
if ( $exiflength > 0xFFFF ) {
return $metadata;
} else
$metadata['exif'] = chr( 0xFF ) . chr( 0xE1 ) . chr( ( $exiflength >> 8 ) & 0xFF ) . chr( $exiflength & 0xFF ) . $exifdata;
}
// prepare IPTC data bytes from source file
$iptcdata = key_exists( 'APP13', $imageinfo ) ? $imageinfo['APP13'] : null;
if ( $iptcdata ) {
$iptclength = strlen( $iptcdata ) + 2;
// construct IPTC segment
if ( $iptclength > 0xFFFF ) {
return $metadata;
} else
$metadata['iptc'] = chr( 0xFF ) . chr( 0xED ) . chr( ( $iptclength >> 8 ) & 0xFF ) . chr( $iptclength & 0xFF ) . $iptcdata;
}
}
return $metadata;
}
/**
* Save EXIF and IPTC metadata from one image to another.
*
* @param array $metadata
* @param string $file
* @return bool|int
*/
public function save_image_metadata( $metadata, $file ) {
$mime = wp_check_filetype( $file );
if ( file_exists( $file ) && $mime['type'] !== 'image/png' ) {
$exifdata = $metadata['exif'];
$iptcdata = $metadata['iptc'];
$destfilecontent = @file_get_contents( $file );
if ( ! $destfilecontent )
return false;
if ( strlen( $destfilecontent ) > 0 ) {
$destfilecontent = substr( $destfilecontent, 2 );
// variable accumulates new & original IPTC application segments
$portiontoadd = chr( 0xFF ) . chr( 0xD8 );
$exifadded = ! $exifdata;
$iptcadded = ! $iptcdata;
while ( ( $this->get_safe_chunk( substr( $destfilecontent, 0, 2 ) ) & 0xFFF0 ) === 0xFFE0 ) {
$segmentlen = ( $this->get_safe_chunk( substr( $destfilecontent, 2, 2 ) ) & 0xFFFF );
// last 4 bits of second byte is IPTC segment
$iptcsegmentnumber = ( $this->get_safe_chunk( substr( $destfilecontent, 1, 1 ) ) & 0x0F );
if ( $segmentlen <= 2 )
return false;
$thisexistingsegment = substr( $destfilecontent, 0, $segmentlen + 2 );
if ( ( $iptcsegmentnumber >= 1 ) && ( ! $exifadded ) ) {
$portiontoadd .= $exifdata;
$exifadded = true;
if ( $iptcsegmentnumber === 1 )
$thisexistingsegment = '';
}
if ( ( $iptcsegmentnumber >= 13 ) && ( ! $iptcadded ) ) {
$portiontoadd .= $iptcdata;
$iptcadded = true;
if ( $iptcsegmentnumber === 13 )
$thisexistingsegment = '';
}
$portiontoadd .= $thisexistingsegment;
$destfilecontent = substr( $destfilecontent, $segmentlen + 2 );
}
// add EXIF data if not added already
if ( ! $exifadded )
$portiontoadd .= $exifdata;
// add IPTC data if not added already
if ( ! $iptcadded )
$portiontoadd .= $iptcdata;
$outputfile = fopen( $file, 'w' );
if ( $outputfile )
return fwrite( $outputfile, $portiontoadd . $destfilecontent );
else
return false;
} else
return false;
} else
return false;
}
/**
* Get integer value of binary chunk.
*
* @param bin $value Binary data
* @return int
*/
private function get_safe_chunk( $value ) {
// check for numeric value
if ( is_numeric( $value ) ) {
// cast to integer to do bitwise AND operation
return (int) $value;
} else
return 0;
}
/**
* Apply watermark to image.
*
* @param int $attachment_id Attachment ID
* @param string $image_path Path to the file
* @param string $image_size Image size
* @param array $upload_dir Upload media data
* @param array $metadata EXIF and ITPC metadata
* @return void
*/
public function do_watermark( $attachment_id, $image_path, $image_size, $upload_dir, $metadata = [] ) {
$options = apply_filters( 'iw_watermark_options', $this->options );
// get image mime type
$mime = wp_check_filetype( $image_path );