forked from aaslun/Scissors-Continued-Yet-Again
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscissors.php
More file actions
1694 lines (1492 loc) · 65.5 KB
/
scissors.php
File metadata and controls
1694 lines (1492 loc) · 65.5 KB
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: Scissors Continued
Plugin URI: http://dev.huiz.net
Description: Scissors Continued enhances WordPress' handling of images by introducing cropping, resizing, rotating, and watermarking functionality. Works from WordPress v2.9 and up.
Version: 2.1
Author: A. Huizinga
Author URI: http://www.huiz.net/
Original Plugin Name: Scissors
Original Plugin URI: http://vimeo.com/7363026
Original Version: 1.3.7
Original Author: Stephan Reiter
Original Author URI: http://stephanreiter.info/
Copyright (C) 2008 Stephan Reiter <stephan.reiter@gmail.com>
Copyright (C) 2011 A. Huizinga <anton@huiz.net>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if(version_compare($wp_version, '2.9', '<')) // integration check begin
{
// Sorry, WordPress 2.8 and lower are not supported!
// You need Scissors v1.3.7 or you could upgrade WordPress.
// Anton, February 2011
}
else
{
function scissors_set_memory_limit()
{
@ini_set('memory_limit', '256M');
//@ini_set('memory_limit', WP_MEMORY_LIMIT);
}
$scissors_dirname = plugin_basename(dirname(__FILE__));
$scissors_locale_dir = PLUGINDIR . '/' . $scissors_dirname . '/languages';
load_plugin_textdomain('scissors', false, $scissors_locale_dir);
function scissors_create_image($width, $height)
{
if($width <= 0 || $height <= 0)
return FALSE;
$image = imagecreatetruecolor($width, $height);
if(is_resource($image))
{
// set default alpha-blending mode
imagealphablending($image, false);
imagesavealpha($image, true);
}
return $image;
}
function scissors_get_file_mime_type($filename)
{
if(!file_exists($filename)) return '';
$size = getimagesize($filename);
return isset($size['mime']) ? $size['mime'] : '';
}
function scissors_supports_imagetype($mime_type)
{
if(function_exists('imagetypes'))
{
switch($mime_type)
{
case 'image/jpeg': return (imagetypes() & IMG_JPG) != 0;
case 'image/png': return (imagetypes() & IMG_PNG) != 0;
case 'image/gif': return (imagetypes() & IMG_GIF) != 0;
default: return FALSE;
}
}
else
{
switch($mime_type)
{
case 'image/jpeg': return function_exists('imagecreatefromjpeg');
case 'image/png': return function_exists('imagecreatefrompng');
case 'image/gif': return function_exists('imagecreatefromgif');
default: return FALSE;
}
}
}
function scissors_load_image($filename, $mime_type)
{
if(!file_exists($filename))
return FALSE;
if(!scissors_supports_imagetype($mime_type))
return FALSE;
switch($mime_type)
{
case 'image/jpeg': $image = imagecreatefromjpeg($filename); break;
case 'image/png': $image = imagecreatefrompng($filename); break;
case 'image/gif': $image = imagecreatefromgif($filename); break;
default: $image = FALSE; break;
}
if(is_resource($image))
{
// set default alpha-blending mode
imagealphablending($image, false);
imagesavealpha($image, true);
}
return $image;
}
function scissors_save_image($image, $filename, $mime_type)
{
if(!scissors_supports_imagetype($mime_type))
return FALSE;
// set default alpha-blending mode
imagealphablending($image, false);
imagesavealpha($image, true);
switch($mime_type)
{
case 'image/jpeg': return imagejpeg($image, $filename, 90);
case 'image/png': return imagepng($image, $filename);
case 'image/gif': return imagegif($image, $filename);
default: return FALSE;
}
}
// Automatic resizing functionality -------------------------------------------
function scissors_get_fullpath_from_metadata($metadata)
{
$upload_path = trim(get_option('upload_path'));
if(empty($upload_path)) $upload_path = WP_CONTENT_DIR . '/uploads';
$upload_path = path_join(ABSPATH, $upload_path);
$filename = path_join($upload_path, $metadata['file']);
return file_exists($filename) ? $filename : FALSE;
}
function scissors_resize_auto($metadata)
{
if( empty($metadata['width']) || empty($metadata['height']) ) {
return $metadata;
}
$srcW = intval($metadata['width']);
$srcH = intval($metadata['height']);
// skip full if temporarily disabled
if(array_key_exists('scissorsSkipFullResize', $_REQUEST) && intval($_REQUEST['scissorsSkipFullResize']) != 0)
$sizes = array('large', 'medium');
else
$sizes = array('full', 'large', 'medium');
$filename = FALSE; $src = NULL; $src_mime_type = '';
foreach($sizes as $size)
{
$adaptive = (get_option("{$size}_adaptive") == '1');
if($size != 'full')
{
if(!$adaptive) continue; // skip, standard intermediate images have already been created ...
if(!is_array($metadata) || !isset($metadata['sizes']) || !isset($metadata['sizes'][$size])) continue; // not available
}
// calculate scaled image dimensions
$dstW = $srcW; $dstH = $srcH;
$maxW = intval(get_option("{$size}_size_w"));
$maxH = intval(get_option("{$size}_size_h"));
$scaleW = (!$adaptive || $srcW >= $srcH);
$scaleH = (!$adaptive || $srcH >= $srcW);
if($scaleW && $maxW > 0 && $dstW > $maxW)
{
$dstH = $dstH * ($maxW / $dstW);
$dstW = $maxW;
}
if($scaleH && $maxH > 0 && $dstH > $maxH)
{
$dstW = $dstW * ($maxH / $dstH);
$dstH = $maxH;
}
if($dstW == $srcW && $dstH == $srcH)
continue; // no need to resize the image
if(!$filename)
{
$filename = scissors_get_fullpath_from_metadata($metadata);
if(!$filename) return $metadata; // failed to locate the file
scissors_set_memory_limit();
// load the full size image
$src_mime_type = scissors_get_file_mime_type($filename);
$src = scissors_load_image($filename, $src_mime_type);
if(!is_resource($src)) return $metadata; // failed to load the file
}
// create a resized copy, overwrite the intermediate file and update the metadata
$dst = scissors_create_image($dstW, $dstH);
if(is_resource($dst))
{
if(imagecopyresampled($dst, $src, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH))
{
if($size == 'full')
{
if(scissors_save_image($dst, $filename, $src_mime_type))
{
$metadata['width'] = $dstW; $metadata['height'] = $dstH;
list($uwidth, $uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height']);
$metadata['hwstring_small'] = "height='$uheight' width='$uwidth'";
}
}
else
{
$fname = path_join(dirname($filename), $metadata['sizes'][$size]['file']);
if(scissors_save_image($dst, $fname, $src_mime_type))
{
$metadata['sizes'][$size]['width'] = $dstW;
$metadata['sizes'][$size]['height'] = $dstH;
}
}
}
imagedestroy($dst);
}
}
if(is_resource($src)) imagedestroy($src);
return $metadata;
}
add_filter('wp_generate_attachment_metadata', 'scissors_resize_auto');
function scissors_fullsize_fields()
{
?><fieldset><legend class="hidden"><?php _e('Full size', 'scissors') ?></legend>
<label for="full_size_w"><?php _e('Max Width'); ?></label>
<input name="full_size_w" type="text" id="full_size_w" value="<?php form_option('full_size_w'); ?>" class="small-text" />
<label for="full_size_h"><?php _e('Max Height'); ?></label>
<input name="full_size_h" type="text" id="full_size_h" value="<?php form_option('full_size_h'); ?>" class="small-text" />
<span class="setting-description"><?php _e('Specify 0 to disable resizing in a particular dimension.', 'scissors') ?></span><br />
<input name="full_adaptive" type="checkbox" id="full_adaptive" value="1" <?php checked('1', get_option('full_adaptive')); ?>/>
<label for="full_adaptive"><?php _e('Adaptive mode: Limit width of landscape images and height of portrait images.', 'scissors') ?></label>
</fieldset>
<script type="text/javascript">
function extendWithCropCheckbox(size, checked, desc) {
var cur = jQuery('#'+size+'_size_h').parent('fieldset').html();
var txt = '<br/><input name="'+size+'_crop" type="checkbox" id="'+size+'_crop" value="1" ' + (checked ? 'checked="checked"' : '') + '/>';
txt += ' <label for="'+size+'_crop">'+desc+'</label>';
jQuery('#'+size+'_size_h').parent('fieldset').html(cur+txt);
}
extendWithCropCheckbox('medium', <?php echo (get_option('medium_crop') == '1') ? 'true' : 'false'; ?>,
"<?php _e('Crop medium images to exact dimensions (normally medium images are proportional)', 'scissors'); ?>");
extendWithCropCheckbox('large', <?php echo (get_option('large_crop') == '1') ? 'true' : 'false'; ?>,
"<?php _e('Crop large images to exact dimensions (normally large images are proportional)', 'scissors'); ?>");
function extendWithAdaptiveCheckbox(size, checked) {
var desc = "<?php _e('Adaptive mode: Limit width of landscape images and height of portrait images.', 'scissors') ?>";
var cur = jQuery('#'+size+'_size_h').parent('fieldset').html();
var txt = '<br/><input name="'+size+'_adaptive" type="checkbox" id="'+size+'_adaptive" value="1" ' + (checked ? 'checked="checked"' : '') + '/>';
txt += ' <label for="'+size+'_adaptive">'+desc+'</label>';
jQuery('#'+size+'_size_h').parent('fieldset').html(cur+txt);
}
extendWithAdaptiveCheckbox('medium', <?php echo (get_option('medium_adaptive') == '1') ? 'true' : 'false'; ?>);
extendWithAdaptiveCheckbox('large', <?php echo (get_option('large_adaptive') == '1') ? 'true' : 'false'; ?>);
</script><?php
}
function scissors_autosize_activation()
{
add_option('full_size_w', '0');
add_option('full_size_h', '0');
add_option('full_adaptive', '0');
add_option('medium_crop', '0');
add_option('medium_adaptive', '0');
add_option('large_crop', '0');
add_option('large_adaptive', '0');
}
function scissors_autosize_add_settings()
{
register_setting('media', 'full_size_w', 'intval');
register_setting('media', 'full_size_h', 'intval');
register_setting('media', 'full_adaptive', 'intval');
register_setting('media', 'medium_crop', 'intval');
register_setting('media', 'medium_adaptive', 'intval');
register_setting('media', 'large_crop', 'intval');
register_setting('media', 'large_adaptive', 'intval');
add_settings_field('scissors_fullsize_fields', __('Full size', 'scissors'), 'scissors_fullsize_fields', 'media', 'default');
}
add_action('admin_init', 'scissors_autosize_add_settings');
register_activation_hook(__FILE__, 'scissors_autosize_activation');
function scissors_cropping()
{
?><p><?php _e('The Scissors image cropping functionality can be configured here ...', 'scissors') ?></p><?php
}
function scissors_cropping_aspectmode()
{
?><fieldset><legend class="hidden"><?php _e('Default aspect ratio', 'scissors') ?></legend>
<input id="scissors_crop_defaultaspect_image" type="radio" value="0" name="scissors_crop_defaultaspect" <?php checked('0', get_option('scissors_crop_defaultaspect')); ?>/>
<label for="scissors_crop_defaultaspect_image"><?php _e('Maintain original aspect ratio.', 'scissors'); ?></label><br />
<input id="scissors_crop_defaultaspect_user" type="radio" value="1" name="scissors_crop_defaultaspect" <?php checked('1', get_option('scissors_crop_defaultaspect')); ?>/>
<?php
$field = "<input style='width:2em;text-align:center;' class='small-text' type='text' name='scissors_crop_useraspectx' value='" . attribute_escape(get_option('scissors_crop_useraspectx')) . "' />:<input style='width:2em;text-align:center;' class='small-text' type='text' name='scissors_crop_useraspecty' value='" . attribute_escape(get_option('scissors_crop_useraspecty')) . "' />";
echo sprintf(__('Lock aspect ratio to %s.', 'scissors'), $field);
?><br />
<input id="scissors_crop_defaultaspect_none" type="radio" value="2" name="scissors_crop_defaultaspect" <?php checked('2', get_option('scissors_crop_defaultaspect')); ?>/>
<label for="scissors_crop_defaultaspect_none"><?php _e('Do not lock aspect ratio.', 'scissors'); ?></label>
</fieldset><?php
}
function scissors_cropping_reir()
{
?><fieldset><legend class="hidden"><?php _e('Default REIR state', 'scissors') ?></legend>
<input id="scissors_crop_defaultreir" type="checkbox" value="1" name="scissors_crop_defaultreir" <?php checked('1', get_option('scissors_crop_defaultreir')); ?>/>
<label for="scissors_crop_defaultreir"><?php _e('enabled', 'scissors'); ?></label>
</fieldset><?php
}
function scissors_cropping_activation()
{
add_option('scissors_crop_defaultaspect', '0'); // 0 ... image, 1 ... user-supplied, 2 ... disabled
add_option('scissors_crop_useraspectx', '4');
add_option('scissors_crop_useraspecty', '3');
add_option('scissors_crop_defaultreir', '0'); // 0 ... disabled, 1 ... enabled
}
function scissors_cropping_add_settings()
{
register_setting('media', 'scissors_crop_defaultaspect', 'intval');
register_setting('media', 'scissors_crop_useraspectx', 'intval');
register_setting('media', 'scissors_crop_useraspecty', 'intval');
register_setting('media', 'scissors_crop_defaultreir', 'intval');
add_settings_section('cropping', __('Cropping', 'scissors'), 'scissors_cropping', 'media');
add_settings_field('scissors_cropping_aspectmode', __('Default aspect ratio', 'scissors'), 'scissors_cropping_aspectmode', 'media', 'cropping');
add_settings_field('scissors_cropping_reir', __('Default REIR state', 'scissors') . " <a href=\"http://www.useit.com/alertbox/9611.html\" target=\"_blank\">[?]</a>", 'scissors_cropping_reir', 'media', 'cropping');
}
add_action('admin_init', 'scissors_cropping_add_settings');
register_activation_hook(__FILE__, 'scissors_cropping_activation');
// Watermarking support -------------------------------------------------------
function scissors_get_global_watermarking_path()
{
if(is_dir(WP_CONTENT_DIR . '/mu-plugins'))
{
$upload_path = trim(get_option('upload_path'));
if(empty($upload_path)) $upload_path = WP_CONTENT_DIR . '/uploads';
$upload_path = path_join(ABSPATH, $upload_path);
return path_join($upload_path, get_option('scissors_watermark_path'));
}
else
return path_join(ABSPATH, get_option('scissors_watermark_path'));
}
function scissors_get_watermark_configuration()
{
$filename = scissors_get_global_watermarking_path();
list($ww, $wh) = file_exists($filename) ? getimagesize($filename) : array(0, 0);
return array('ver' => 1, // NOTE: increment this if features are added and add appropriate checks to load_configuration
'ww' => $ww, 'wh' => $wh,
'doscale' => get_option('scissors_watermark_size'),
'scale' => get_option('scissors_watermark_size_relative'),
'horz' => get_option('scissors_watermark_halign'),
'vert' => get_option('scissors_watermark_valign'));
}
function scissors_get_relative_filepath($filename)
{
$upload_path = trim(get_option('upload_path'));
if(empty($upload_path)) $upload_path = WP_CONTENT_DIR . '/uploads';
$upload_path = path_join(ABSPATH, $upload_path);
return str_replace($upload_path . '/', '', $filename);
}
function scissors_get_absolute_filepath($filename)
{
$upload_path = trim(get_option('upload_path'));
if(empty($upload_path)) $upload_path = WP_CONTENT_DIR . '/uploads';
$upload_path = path_join(ABSPATH, $upload_path);
return path_join($upload_path, $filename);
}
function scissors_get_postid_from_fullfilename($filename)
{
global $wpdb;
$relfile = scissors_get_relative_filepath($filename);
$post = $wpdb->get_row($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s LIMIT 1", $relfile));
return ($post != null) ? $post->post_id : FALSE;
}
function scissors_save_watermark_configuration($filename, $rectfilename)
{
$postId = scissors_get_postid_from_fullfilename($filename);
if(!$postId) return FALSE;
$config = scissors_get_watermark_configuration();
$config['rectfilename'] = addslashes(scissors_get_relative_filepath($rectfilename));
return add_post_meta($postId, "_scissors_watermarking", $config, true) or
update_post_meta($postId, "_scissors_watermarking", $config);
}
function scissors_load_watermark_configuration($postId)
{
$config = get_post_meta($postId, '_scissors_watermarking', true);
if($config == '') return FALSE;
$config['rectfilename'] = scissors_get_absolute_filepath($config['rectfilename']);
return $config;
}
function scissors_get_watermarking_state($postId = '')
{
if($postId != '')
{
$state = get_post_meta($postId, '_scissors_watermarking_state', true);
if($state == 'disabled') $state = '0'; // legacy value handling
if($state != '') return $state;
}
return get_option('scissors_watermark_enabled'); // global configuration
}
function scissors_set_watermarking_state($postId, $state)
{
return add_post_meta($postId, '_scissors_watermarking_state', $state, true) or
update_post_meta($postId, '_scissors_watermarking_state', $state);
}
function scissors_is_watermarking_enabled($size = '*', $postId = '', $checkFile = FALSE)
{
if($size == '*' || $size == '+')
{
if($postId != '')
{
$sizes = array();
$metadata = wp_get_attachment_metadata($postId);
if(is_array($metadata) && isset($metadata['sizes']) && count($metadata['sizes']) > 0)
{
foreach($metadata['sizes'] as $s => $value)
$sizes[] = $s;
}
}
else
$sizes = apply_filters('intermediate_image_sizes', array('large', 'medium', 'thumbnail'));
$sizes[] = 'full';
if($size == '*') $sizes[] = 'custom'; // '+' ignores custom
foreach($sizes as $s)
{
if(scissors_is_watermarking_enabled($s, $postId, $checkFile))
return TRUE;
}
return FALSE;
}
$str = scissors_get_watermarking_state($postId);
$enabled = (strlen($str) > 0 && $str[0] == '1'); // legacy value handling (was 0 for none, 1 for all).
$enabled |= strstr($str, "+$size") != FALSE; // size added?
$enabled &= strstr($str, "-$size") == FALSE; // size not removed?
if(!$enabled || !$checkFile) return $enabled;
$filename = scissors_get_global_watermarking_path();
list($ww, $wh) = file_exists($filename) ? getimagesize($filename) : array(0, 0);
return ($ww > 0 && $wh > 0); // make sure the watermark image is valid!
}
function scissors_find_rect_filename($filename)
{
$rectfilename = FALSE;
if(file_exists($filename))
{
$path_parts = pathinfo($filename);
$sansext = substr($path_parts['basename'], 0, -(strlen($path_parts['extension']) + 1)); // +1 for the dot
$pattern = '!' . preg_quote($sansext) . '-[0-9]+-rect' . preg_quote('.' . $path_parts['extension']) . '$!';
$dir = opendir($path_parts['dirname']);
while($file = readdir($dir))
{
if(preg_match($pattern, $file) == 1)
{
$rectfilename = $path_parts['dirname'] . '/' . $file;
break;
}
}
closedir($dir);
}
return $rectfilename;
}
function scissors_delete_watermark_meta($filename)
{
$postId = scissors_get_postid_from_fullfilename($filename);
$config = $postId ? get_post_meta($postId, '_scissors_watermarking', true) : '';
if($config != '') @unlink(scissors_get_absolute_filepath($config['rectfilename']));
if($postId) delete_post_meta($postId, '_scissors_watermarking');
if($config == '')
{
// try to find the file manually ... it seems that the
// metadata in the db is already gone when delete_file is invoked
$rectfilename = scissors_find_rect_filename($filename);
if($rectfilename) @unlink($rectfilename);
}
return $filename; // needs this to support WP filter chain
}
function scissors_place_watermark($image, $config = '')
{
if($config == '')
$config = scissors_get_watermark_configuration();
$iw = imagesx($image); $ih = imagesy($image);
$ww = $config['ww']; $wh = $config['wh'];
// scale down the watermark to occupy the desired area if requested
if($config['doscale'] == 1)
{
$desiredarea = $iw * $ih * ($config['scale'] / 100.0);
// ($ww * $s) * ($wh * $s) = $desiredArea;
$s = sqrt($desiredarea / ($ww * $wh));
if($s < 1) { $ww = $ww * $s; $wh = $wh * $s; }
}
// make sure that the watermark fits onto the original image, scale it down if necessary
if($ww > $iw) { $wh = $wh * ($iw / $ww); $ww = $iw; }
if($wh > $ih) { $ww = $ww * ($ih / $wh); $wh = $ih; }
switch($config['horz'])
{
default: case 0: $l = 0; break; // left
case 1: $l = ($iw - $ww) / 2; break; // center
case 2: $l = $iw - $ww; break; // right
}
switch($config['vert'])
{
default: case 0: $t = 0; break; // top
case 1: $t = ($ih - $wh) / 2; break; // middle
case 2: $t = $ih - $wh; break; // bottom
}
return array($l, $t, $ww, $wh);
}
function scissors_build_rect_filename($filename)
{
$path_parts = pathinfo($filename);
$sansext = substr($path_parts['basename'], 0, -(strlen($path_parts['extension']) + 1)); // +1 for the dot
$randid = time(); // add a random number to make access to the rect more difficult (would allow watermark-removal)
$path_parts['basename'] = "{$sansext}-{$randid}-rect." . $path_parts['extension'];
return $path_parts["dirname"] . '/' . $path_parts['basename'];
}
// the following functions are referenced by the resampling and resizing/cropping functionality ---
function scissors_remove_watermark($image, $postId)
{
$config = scissors_load_watermark_configuration($postId);
if($config)
{
$mime_type = scissors_get_file_mime_type($config['rectfilename']);
$rect = scissors_load_image($config['rectfilename'], $mime_type);
if(is_resource($rect))
{
imagealphablending($image, false);
imagesavealpha($image, true);
list($left, $top, $width, $height) = scissors_place_watermark($image, $config);
imagecopy($image, $rect, $left, $top, 0, 0, $width, $height);
imagedestroy($rect);
}
}
}
function scissors_watermark_image($image)
{
$result = FALSE;
$watermark_path = scissors_get_global_watermarking_path();
$watermark_mime_type = scissors_get_file_mime_type($watermark_path);
$watermark = scissors_load_image($watermark_path, $watermark_mime_type);
if(is_resource($watermark))
{
imagesavealpha($image, false);
imagealphablending($image, true);
list($l, $t, $ww, $wh) = scissors_place_watermark($image);
$result = imagecopyresampled($image, $watermark, $l, $t, 0, 0, $ww, $wh, imagesx($watermark), imagesy($watermark));
imagedestroy($watermark);
}
return $result;
}
function scissors_watermark_file($filename)
{
$result = FALSE;
$mime_type = scissors_get_file_mime_type($filename);
$image = scissors_load_image($filename, $mime_type);
if(is_resource($image))
{
if(scissors_watermark_image($image))
$result = scissors_save_image($image, $filename, $mime_type);
imagedestroy($image);
}
return $result;
}
function scissors_rebuild_watermark_meta($image, $mime_type, $postId)
{
$fullfilename = get_attached_file($postId);
$done = FALSE;
if(scissors_is_watermarking_enabled('full', $postId, TRUE)) // only need meta if full image is modified, because all image operations use it as the base
{
// determine the place and the size of the watermark if applied to this image
list($left, $top, $width, $height) = scissors_place_watermark($image);
// back up the part of the image that will be overlaid with the watermark
$rect = scissors_create_image($width, $height);
if(is_resource($rect))
{
if(imagecopy($rect, $image, 0, 0, $left, $top, $width, $height))
{
$oldconfig = scissors_load_watermark_configuration($postId);
$rectfilename = ($oldconfig == FALSE) ? scissors_build_rect_filename($fullfilename) : $oldconfig['rectfilename'];
if(scissors_save_image($rect, $rectfilename, $mime_type))
$done = scissors_save_watermark_configuration($fullfilename, $rectfilename);
}
imagedestroy($rect);
}
}
if(!$done)
scissors_delete_watermark_meta($fullfilename);
}
// ------------------------------------------------------------------------------------------------
function scissors_get_postid_from_metadata($metadata)
{
if( empty($metadata) )
return false;
global $wpdb;
$post = $wpdb->get_row($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s LIMIT 1", $metadata['file']));
return ($post != null) ? $post->post_id : FALSE;
}
function scissors_apply_initial_watermarks($metadata)
{
// skip if temporarily disabled
if(array_key_exists('scissorsSkipWatermarking', $_REQUEST) && intval($_REQUEST['scissorsSkipWatermarking']) != 0)
return $metadata;
$postId = scissors_get_postid_from_metadata($metadata);
if($postId)
{
$fullfilename = get_attached_file($postId);
if($fullfilename && file_exists($fullfilename))
{
scissors_set_watermarking_state($postId, scissors_get_watermarking_state()); // initialize local watermarking state
if(scissors_is_watermarking_enabled('*', $postId, TRUE))
{
// load the full size image
scissors_set_memory_limit();
$mime_type = scissors_get_file_mime_type($fullfilename);
$image = scissors_load_image($fullfilename, $mime_type);
if(is_resource($image))
{
scissors_rebuild_watermark_meta($image, $mime_type, $postId);
// apply the watermark to the full size image
if(scissors_is_watermarking_enabled('full', $postId, TRUE))
{
if(scissors_watermark_image($image))
scissors_save_image($image, $fullfilename, $mime_type);
}
imagedestroy($image);
// apply the watermark to the intermediate images
if(is_array($metadata) && isset($metadata['sizes']) && count($metadata['sizes']) > 0)
{
foreach($metadata['sizes'] as $size => $data)
{
if(scissors_is_watermarking_enabled($size, $postId, TRUE))
{
$filename = path_join(dirname($fullfilename), $data['file']);
$mime_type = scissors_get_file_mime_type($filename);
$image = scissors_load_image($filename, $mime_type);
if(is_resource($image))
{
if(scissors_watermark_image($image))
scissors_save_image($image, $filename, $mime_type);
imagedestroy($image);
}
}
}
}
}
}
}
}
return $metadata;
}
add_filter('wp_generate_attachment_metadata', 'scissors_apply_initial_watermarks');
add_filter('wp_delete_file', 'scissors_delete_watermark_meta');
function scissors_watermarking()
{
?><p><?php _e('The Scissors plugin supports automatic watermarking of images. Please configure this feature here ...', 'scissors') ?></p><?php
}
// never called, used to make sure that image sizes show up in localization tools
function scissors_dummy()
{
__('large', 'scissors');
__('medium', 'scissors');
__('thumbnail', 'scissors');
__('full', 'scissors');
__('custom', 'scissors');
}
function scissors_watermarking_switch()
{
$enabled = get_option('scissors_watermark_enabled');
echo "<input name='scissors_watermark_enabled' id='scissors_watermark_enabled' type='hidden' value='$enabled'/>";
$sizes = apply_filters('intermediate_image_sizes', array('large', 'medium', 'thumbnail'));
$sizes[] = 'full'; $sizes[] = 'custom';
foreach($sizes as $size)
{
$checked = scissors_is_watermarking_enabled($size) ? "checked" : "";
echo " <input type='checkbox' id='scissors_watermark_target_$size' $checked";
echo " onchange=\"scissorsConfigEnableChanged('$size')\"";
echo "> <label class='align_watermark' for='scissors_watermark_target_$size'>" . __($size, 'scissors') . "</label>";
}
}
function scissors_watermarking_path()
{
?><fieldset><legend class="hidden"><?php _e('Image', 'scissors') ?></legend>
<input name="scissors_watermark_path" type="text" id="scissors_watermark_path" value="<?php form_option('scissors_watermark_path'); ?>" class="regular-text code" />
<input type="button" class="button" value="<?php _e('Select Image', 'scissors') ?>" onclick="tb_show('', 'media-upload.php?type=image&TB_iframe=true');"/>
<br /><span class="setting-description"><?php _e('Click the button, pick an image in the opening dialog, and use "Insert into Post" to make the selection.', 'scissors') ?></span>
</fieldset><?php
}
function scissors_watermarking_size()
{
?><fieldset><legend class="hidden"><?php _e('Size', 'scissors') ?></legend>
<input id="scissors_watermark_size_absolute" type="radio" value="0" name="scissors_watermark_size" <?php checked('0', get_option('scissors_watermark_size')); ?>/>
<label for="scissors_watermark_size_absolute"><?php _e('Do not resize the watermark.', 'scissors'); ?></label><br />
<input id="scissors_watermark_size_relative" type="radio" value="1" name="scissors_watermark_size" <?php checked('1', get_option('scissors_watermark_size')); ?>/>
<?php
$field = '<input name="scissors_watermark_size_relative" type="text" value="' . attribute_escape(get_option('scissors_watermark_size_relative')) . '" class="small-text" />';
echo sprintf(__('Limit the watermark to %s percent of the destination image area.', 'scissors'), $field);
?>
</fieldset><?php
}
function scissors_watermarking_halign()
{
?><fieldset><legend class="hidden"><?php _e('Horizontal alignment', 'scissors') ?></legend>
<input id="scissors_watermark_halign_left" type="radio" value="0" name="scissors_watermark_halign" <?php checked('0', get_option('scissors_watermark_halign')); ?> />
<label class="align_watermark" for="scissors_watermark_halign_left"><?php _e('Left'); ?></label>
<input id="scissors_watermark_halign_center" type="radio" value="1" name="scissors_watermark_halign" <?php checked('1', get_option('scissors_watermark_halign')); ?> />
<label class="align_watermark" for="scissors_watermark_halign_center"><?php _e('Center'); ?></label>
<input id="scissors_watermark_halign_right" type="radio" value="2" name="scissors_watermark_halign" <?php checked('2', get_option('scissors_watermark_halign')); ?> />
<label class="align_watermark" for="scissors_watermark_halign_right"><?php _e('Right'); ?></label>
</fieldset><?php
}
function scissors_watermarking_valign()
{
?><input id="scissors_watermark_valign_top" type="radio" value="0" name="scissors_watermark_valign" <?php checked('0', get_option('scissors_watermark_valign')); ?> />
<label class="align_watermark" for="scissors_watermark_valign_top"><?php _e('Top'); ?></label>
<input id="scissors_watermark_valign_middle" type="radio" value="1" name="scissors_watermark_valign" <?php checked('1', get_option('scissors_watermark_valign')); ?> />
<label class="align_watermark" for="scissors_watermark_valign_middle"><?php _e('Middle'); ?></label>
<input id="scissors_watermark_valign_bottom" type="radio" value="2" name="scissors_watermark_valign" <?php checked('2', get_option('scissors_watermark_valign')); ?> />
<label class="align_watermark" for="scissors_watermark_valign_bottom"><?php _e('Bottom'); ?></label>
</fieldset><?php
}
function scissors_admin_head_watermark()
{
global $scissors_dirname;
if(strstr($_SERVER['REQUEST_URI'], 'options-media'))
{
$wpurl = get_bloginfo('wpurl');
if(is_dir(WP_CONTENT_DIR . '/mu-plugins')) $wpurl .= 'files/'; // special treatment of WPMU installations
echo "<!-- JS loaded for Scissors in options-media -->\n";
echo "<script type='text/javascript'>\n/* <![CDATA[ */\n";
echo "scissors2 = {\n";
echo "wpUrl: '$wpurl/'\n";
echo "}\n";
echo "/* ]]> */\n</script>\n";
echo "<!-- End of JS loaded for Scissors in options-media -->\n";
wp_enqueue_script('thickbox');
wp_enqueue_script('scissors_watermark_select_js', '/' . PLUGINDIR . '/'.$scissors_dirname.'/js/watermark-select.js', array('jquery') );
}
}
function scissors_watermarking_activation()
{
add_option('scissors_watermark_enabled', '0');
add_option('scissors_watermark_path', '');
add_option('scissors_watermark_size', '1');
add_option('scissors_watermark_size_relative', '20');
add_option('scissors_watermark_halign', '2');
add_option('scissors_watermark_valign', '2');
}
function scissors_watermarking_add_settings()
{
register_setting('media', 'scissors_watermark_enabled');
register_setting('media', 'scissors_watermark_path', 'trim');
register_setting('media', 'scissors_watermark_size');
register_setting('media', 'scissors_watermark_size_relative', 'intval');
register_setting('media', 'scissors_watermark_halign');
register_setting('media', 'scissors_watermark_valign');
add_settings_section('watermarking', __('Watermarking', 'scissors'), 'scissors_watermarking', 'media');
add_settings_field('scissors_watermarking_switch', __('Enable', 'scissors'), 'scissors_watermarking_switch', 'media', 'watermarking');
add_settings_field('scissors_watermarking_path', __('Image', 'scissors'), 'scissors_watermarking_path', 'media', 'watermarking');
add_settings_field('scissors_watermarking_size', __('Size', 'scissors'), 'scissors_watermarking_size', 'media', 'watermarking');
add_settings_field('scissors_watermarking_halign', __('Horizontal alignment', 'scissors'), 'scissors_watermarking_halign', 'media', 'watermarking');
add_settings_field('scissors_watermarking_valign', __('Vertical alignment', 'scissors'), 'scissors_watermarking_valign', 'media', 'watermarking');
}
add_action('admin_print_scripts', 'scissors_admin_head_watermark');
add_action('admin_init', 'scissors_watermarking_add_settings');
register_activation_hook(__FILE__, 'scissors_watermarking_activation');
function scissors_plugin_settings_link($links)
{
$settings_link = '<a href="options-media.php">' . __('Settings') . '</a>';
array_unshift($links, $settings_link);
return $links;
}
$plugin = plugin_basename(__FILE__);
add_filter("plugin_action_links_$plugin", 'scissors_plugin_settings_link' );
function scissors_post_upload_ui()
{
$watermarking = scissors_is_watermarking_enabled('+');
$fullresizing = (intval(get_option("full_size_w")) > 0 || intval(get_option("full_size_h")) > 0);
if(!$watermarking && !$fullresizing)
return;
echo '<div style="padding:4px 0px">';
if($watermarking) {
?>
<input name="scissorsSkipWatermarking" id="scissorsSkipWatermarking" type="checkbox" value="1" onchange="updateSwfuPostParams(swfu, 'scissorsSkipWatermarking');" /><label style="display:inline;font-size:12px" for="scissorsSkipWatermarking"><?php _e('Skip watermarking of images', 'scissors'); ?></label>
<?php }
if($watermarking && $fullresizing) echo "<br />";
if($fullresizing) {
?>
<input name="scissorsSkipFullResize" id="scissorsSkipFullResize" type="checkbox" value="1" onchange="updateSwfuPostParams(swfu, 'scissorsSkipFullResize');" /><label style="display:inline;font-size:12px" for="scissorsSkipFullResize"><?php _e('Skip scaling of full-size images', 'scissors'); ?></label>
<?php }
echo "</div>";
}
add_action('post-flash-upload-ui', 'scissors_post_upload_ui');
add_action('post-html-upload-ui', 'scissors_post_upload_ui');
// Manual cropping and resizing functionality ---------------------------------
function scissors_admin_head($hook) {
if( defined('PREVENT_SCISSORS_JS') )
return;
if(($hook == 'post.php') || ($hook == 'post-new.php'))
{
global $scissors_dirname;
wp_enqueue_script('scissors_crop', '/' . PLUGINDIR . '/'.$scissors_dirname.'/js/jquery.Jcrop.js', array('jquery') );
wp_enqueue_script('scissors_js', '/' . PLUGINDIR . '/'.$scissors_dirname.'/js/scissors.js' );
$thisUrl = admin_url('admin-ajax.php');
echo "<!-- JS loaded for Scissors in media library -->\n";
echo "<script type='text/javascript'>\n/* <![CDATA[ */\n";
echo "scissors = {\n";
echo "ajaxUrl: '$thisUrl'";
foreach(array('large', 'medium', 'thumbnail') as $size)
{
$width = intval(get_option("{$size}_size_w"));
$height = intval(get_option("{$size}_size_h"));
$aspectRatio = max(1, $width) / max(1, $height);
if(!get_option("{$size}_crop")) $aspectRatio = 0;
echo ",\n{$size}AspectRatio: $aspectRatio";
}
echo "\n}\n";
echo "/* ]]> */\n</script>\n";
echo "<!-- End of JS loaded for Scissors in media library -->\n";
}
}
function scissors_styles()
{
global $scissors_dirname;
wp_register_style('jcrop_style', plugins_url( "css/jquery.Jcrop.css", __FILE__ ) );
wp_register_style('scissors_style', plugins_url( "css/scissors.css", __FILE__ ) );
wp_enqueue_style('jcrop_style');
wp_enqueue_style('scissors_style');
wp_enqueue_style('thickbox');
}
function gcd($a, $b)
{
if ($a == 0 || $b == 0)
return 0;
else if ($a == $b)
return $a;
else
{
do
{
$r = $a % $b;
$a = $b; $b = $r;
} while($r != 0);
return $a;
}
}
function scissors_media_meta($string, $post)
{
// From v2.9 the media box is different, there is one table cell more
global $wp_version;
if(version_compare($wp_version, '2.9', '>='))
{
$scissors_extra_cell = "</tr><tr>";
$scissors_hide_editbutton = "<style type='text/css'>input#imgedit-open-btn-".$post->ID."{display:none;}</style>";
}
else
{
$scissors_extra_cell = "";
$scissors_hide_editbutton = "";
}
$errstr = "";
if(!scissors_supports_imagetype($post->post_mime_type))
$errstr = sprintf(__('Failed to load image. Image type %s not supported.', 'scissors'), $post->post_mime_type);
{
$postId = $post->ID;
$filename = get_attached_file($postId);
if(!$filename || !file_exists($filename))
$errstr = __('Failed to load image. File not found.', 'scissors');
else
{
list($width, $height) = getimagesize($filename);
if($width <= 0 || $height <= 0)
$errstr = __('Failed to load image. Invalid image dimensions.', 'scissors');
}
}
if($errstr != "")
{
$string .= "</td></tr>\n\t\t<tr>";
$string .= "<th valign='top' scope='row' class='label'><label>Scissors</label></th><td class='field'>";
$string .= "<p class='help'>$errstr</p>";
}
else
{
$text_crop = __('Crop', 'scissors');
$text_resize = __('Resize', 'scissors');
$text_rotate = __('Rotate', 'scissors');
$text_watermarks = __('Watermarks', 'scissors');
$text_apply = __('Apply', 'scissors');
$text_abort = __('Abort', 'scissors');
$text_crop2 = __('Crop %s.', 'scissors');
$text_crop3 = __('Lock aspect ratio to %s.', 'scissors');
$text_width = __('width', 'scissors');
$text_height = __('height', 'scissors');
$text_longside = __('long side', 'scissors');
$text_shortside = __('short side', 'scissors');
$text_reir = __('Use automatic relevance-enhanced image reduction.', 'scissors');