-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutoSmush.module
1579 lines (1352 loc) · 57 KB
/
AutoSmush.module
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
require_once /*NoCompile*/__DIR__ . '/ImageOptimizer.php';
/**
* AutoSmush
* Optimize images
*
* @version 1.1.6
* @author Roland Toth (tpr)
* @author Matjaz Potocnik (matjazp)
* @link https://github.com/matjazpotocnik/AutoSmush
*
* ProcessWire 2.x/3.x, Copyright 2011 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE
* https://processwire.com
*
*/
class AutoSmush extends FieldtypeImage implements Module, ConfigurableModule {
/**
* Module info
*
* @return array
*
*/
public static function getModuleInfo() {
return array(
'title' => 'Auto Smush',
'class' => 'AutoSmush',
'author' => 'Roland Toth, Matjaž Potočnik',
'version' => '1.1.6',
'summary' => 'Optimize/compress images automatically on upload, resize and crop, ' .
'manually by clicking the button or link for each image or variation, ' .
'and in bulk mode for all images sitewide.',
'href' => 'https://processwire.com/talk/topic/14818-auto-smush/',
'requires' => 'ProcessWire>=2.5.5, PHP>=5.4.0',
'icon' => 'leaf',
'singular' => true,
'autoload' => true
);
}
/**
* Module configuraton values
*
*/
const WEBSERVICE = 'http://api.resmush.it/ws.php?exif=true&img=';
const WEBSERVICE_NOEXIF = 'http://api.resmush.it/ws.php?img=';
const API_SIZELIMIT = 5242880; // 5 MB limit
const API_ALLOWED_EXTENSIONS = 'png, jpg, jpeg, gif';
const JPG_QUALITY_DEFAULT = '90';
const CONNECTION_TIMEOUT = 30; // for large images and slow connection 30 sec might not be enough
const JPG_QUALITY_THRESHOLD = 5; // no optimization if gain is less than 5%, only for jpegoptim, should prevent reoptmizing
/**
* Array of messages reported by this module
* @var array
*/
private $msgs = array();
/**
* Array of settings for image-optimizer
* @var array
*/
protected $optimizeSettings = array();
/**
* Array of all optimizers
* @var array
*/
protected $optimizers = array();
/**
* Array of additional paths to look for optimizers executable
* @var array
*/
protected $optimizersExtraPaths = array();
/**
* Array of allowed extensions for images
* @var array
*/
protected $allowedExtensions = array();
/**
* Array of error codes returned by reSmush.it web service
* @var array
*/
private $apiErrorCodes = array();
/**
* Indicator if image needs to be optimized
* @var boolean
*/
private $isOptimizeNeeded = false;
/**
* Indicator if image was optimized on upload
* @var boolean
*/
private $isOptimizedOnUpload = false;
/**
* This module config data
* @var array
*/
protected $configData = array();
/**
* This module default config data
* @var array
*/
protected $configDataDefault = array();
/**
* PW FileLog object
* @var array
*/
private $log;
/**
* Construct and set default configuration
*
*/
public function __construct() {
$this->msgs = array(
'start' => $this->_('Starting...'),
'complete' => $this->_('All done'),
'error' => $this->_('ERROR:'),
'save_first' => $this->_('Module settings have been modified, please save first'),
'confirm' => $this->_('Are you sure to continue?'),
'canceled' => $this->_('Canceled'),
'canceling' => $this->_('Canceling...'),
'filelist' => $this->_('Generating list of images'),
'filelistnum' => $this->_('Number of images: '),
'actions' => $this->_('Actions'),
'engine' => $this->_('Engine'),
'eng_resmushit' => $this->_('Use reShmush.it online service'),
'eng_localtools' => $this->_('Use optimization tools available on web server'),
'jpg_quality' => $this->_('JPG quality'),
'demo' => $this->_('Optimization disabled in demo mode!'),
);
$this->optimizers = array(
'jpegtran' => '',
'jpegoptim' => '',
'pngquant' => '',
'optipng' => '',
'pngcrush' => '',
'pngout' => '',
'advpng' => '',
'gifsicle' => '',
'svgo' => ''
);
// currently only jpegoptim is used for jpegs, I modified OptimizerFactory.php
// pngs are chained in this order: pngquant, optipng, pngcrush, advpng
$this->optimizeSettings = array(
'ignore_errors' => false, // in production could be set to true
'execute_first' => true, // true: execute just first optimizer in chain, false: execute all optimizers in chain
'jpegtran_options' => array('-optimize', '-progressive', '-copy', 'all'),
'jpegoptim_options' => array('--preserve', '--all-progressive', '--strip-none', '-T' . self::JPG_QUALITY_THRESHOLD),
'optipng_options' => array('-i0', '-o2', '-quiet', '-preserve'),
'advpng_options' => array('-z', '-3', '-q'),
'svgo_options' => array('--disable=cleanupIDs')
);
$this->allowedExtensions = array_map('trim', explode(',', self::API_ALLOWED_EXTENSIONS . ', svg'));
// http://resmush.it/api
$this->apiErrorCodes = array(
'400' => $this->_('no url of image provided'),
'401' => $this->_('impossible to fetch the image from URL (usually a local URL)'),
'402' => $this->_('impossible to fetch the image from $_FILES (usually a local URL)'),
'403' => $this->_('forbidden file format provided, works strictly with jpg, png, gif, tif and bmp files.'),
'404' => $this->_('request timeout from reSmush.it'),
'501' => $this->_('internal error, cannot create a local copy'),
'502' => $this->_('image provided too large (must be below 5MB)'),
'503' => $this->_('internal error, could not reach remote reSmush.it servers for image optimization'),
'504' => $this->_('internal error, could not fetch image from remote reSmush.it servers')
);
$this->configDataDefault = array(
'optAutoEngine' => 'resmushit',
'optAutoAction' => array(),
'optAutoQuality' => self::JPG_QUALITY_DEFAULT,
'optApiEngine' => 'resmushit',
'optApiAction' => array(),
'optApiQuality' => self::JPG_QUALITY_DEFAULT,
'optManualEngine' => 'resmushit',
'optManualAction' => array('optimize_originals', 'optimize_variations'),
'optManualQuality' => self::JPG_QUALITY_DEFAULT,
'optBulkEngine' => 'resmushit',
'optBulkAction' => array(),
'optBulkQuality' => self::JPG_QUALITY_DEFAULT,
'optChain' => '',
'optNoExif' => ''
);
}
/**
* Initialize log file
*
*/
public function init() {
$cls = strtolower(__CLASS__);
$log = $this->wire('log');
// pruneBytes returns error in PW prior to 3.0.13 if file does not exist
if(!file_exists($log->getFilename($cls))) {
$log->save($cls, 'log file created', array('showUser' => false, 'showURL' => false));
}
$this->log = new FileLog($log->getFilename($cls));
method_exists($this->log, __CLASS__) ? $this->log->pruneBytes(20000) : $this->log->prune(20000);
$paths = $this->wire('config')->paths;
$this->optimizersExtraPaths = array(
realpath($paths->siteModules . __CLASS__ . '/windows_binaries'),
realpath($paths->root),
realpath($paths->templates),
realpath($paths->assets)
);
}
/**
* Main entry point
* Set hooks and handle ajax requests
*
*/
public function ready() {
$this->configData = array_merge($this->configDataDefault, $this->wire('modules')->getModuleConfigData($this));
$config = $this->wire('config');
$input = $this->wire('input');
$page = $this->wire('page');
$this->checkOptimizers();
foreach($this->optimizers as $optimizer => $path) $this->optimizeSettings[$optimizer . '_bin'] = $path;
if($this->configData['optChain'] == 1) $this->optimizeSettings['execute_first'] = false;
// handle ajax optimization calls
if($input->get('name') === __CLASS__) {
// optimize images in bulk mode on button click
// this method halts execution
if($input->get('mode') === 'bulk') $this->bulkOptimize();
// optimize images in manual mode on clicking optimize button/link or on image variations modal
// this method halts execution
if($input->get('mode') === 'optimize') $this->onclickOptimize(($input->get('var') == 1)); // &var=1 => process variation
// add assets
$this->wire('modules')->get('JqueryMagnific');
$config->scripts->add($config->urls->siteModules . __CLASS__ . '/' . __CLASS__ . '.js');//?v=' . time());
$config->styles->add($config->urls->siteModules . __CLASS__ . '/' . __CLASS__ . '.css');//?v=' . time());
}
// add optimize button/link in manual mode on page/image edit
if($page->process == 'ProcessPageEdit' || $page->process == 'ProcessPageEditImageSelect') {
if(in_array('optimize_originals', $this->configData['optManualAction'])) {
// add link/button
//$this->log->save("addhookafter InputfieldImage::renderItem in admin");
$this->addHookAfter('InputfieldImage::renderItem', $this, 'addOptButton');
}
if(in_array('optimize_variations', $this->configData['optManualAction'])) {
// add button on variations page
// for new image field introduced after 3.0.17 we could hook after InputfieldImage::renderButtons
//$this->log->save("addhookafter ProcessPageEditImageSelect::executeVariations in admin");
$this->addHookAfter('ProcessPageEditImageSelect::executeVariations', $this, 'addOptButtonVariations');
}
if(in_array('optimize_originals', $this->configData['optManualAction']) ||
in_array('optimize_variations', $this->configData['optManualAction'])) {
$config->scripts->add($config->urls->siteModules . __CLASS__ . '/' . __CLASS__ . 'PageEdit.js');//?v=' . time());
}
}
// disable automatic mode when site is in demo mode
if($config->demo) return;
// is this check enough?
$isAdmin = ($page->template == 'admin');
// optimize images in auto mode on resize in admin
if($isAdmin &&
(in_array('optimize_variations', $this->configData['optAutoAction']) || in_array('optimize_variationsCI3', $this->configData['optAutoAction']))) {
//$this->log->save("addhookafter ImageSizer::resize and Pageimage::size in admin");
$this->addHookAfter('ImageSizer::resize', $this, 'checkOptimizeNeeded');
$this->addHookAfter('Pageimage::size', $this, 'optimizeOnResize');
if($this->wire('modules')->isInstalled('FieldtypeCroppableImage3') && in_array('optimize_variationsCI3', $this->configData['optAutoAction'])) {
//$this->log->save("addhookafter ProcessCroppableImage3::executeSave and Pageimage::getCrop in admin");
$this->addHookAfter('ProcessCroppableImage3::executeSave', $this, 'optimizeOnResizeCI3'); //optimize on save in CI3 modal
$this->addHookAfter('Pageimage::getCrop', $this, 'optimizeOnResize'); //optimize on CI3 crop generation, should that be on upload/add????
}
}
// optimize images in auto mode on pageimage->size() method in templates
if(!$isAdmin &&
in_array('optimize_variations', $this->configData['optApiAction'])) {
//$this->log->save("addhookafter ImageSizer::resize and Pageimage::size in templates");
$this->addHookAfter('ImageSizer::resize', $this, 'checkOptimizeNeeded');
$this->addHookAfter('Pageimage::size', $this, 'optimizeOnResizeAPI');
/*if($this->wire('modules')->isInstalled('FieldtypeCroppableImage3') && in_array('optimize_variationsCI3', $this->configData['optAutoAction'])) {
$this->log->save("addhookafter ImageSizer::resize and Pageimage::size in admin");
$this->addHookAfter('ProcessCroppableImage3::executeSave', $this, 'optimizeOnResizeCI3'); //optimize on save in CI3 modal
$this->addHookAfter('Pageimage::getCrop', $this, 'optimizeOnResize'); //optimize on CI3 crop generation, should that be on upload/add????
}*/
}
// optimize images in auto mode on upload in admin
// should I hook only in ProcessPageEdit?
if($isAdmin && in_array('optimize_originals', $this->configData['optAutoAction'])) {
//$this->log->save("addhookbefore InputfieldFile::fileAdded in admin");
$this->addHookBefore('InputfieldFile::fileAdded', $this, 'optimizeOnUpload', array('priority'=>200)); //in admin
$config->js('AutoSmush', $this->_('Optimizing'));
// delete backup copy - maybe this should run in all cases?
if(in_array('backup', $this->configData['optAutoAction'])) {
$this->addHookAfter('InputfieldFile::processInputDeleteFile', $this, 'deleteBackup');
}
}
// optimize images in auto mode on pageimage->add() method in templates
if(!$isAdmin && in_array('optimize_originals', $this->configData['optApiAction'])) {
//$this->log->save("addhookafter Pagefile::install in templates");
$this->addHookAfter('Pagefile::install', $this, 'optimizeOnAdd', array('priority'=>200)); //in templates
// delete backup copy - maybe this should run in all cases?
//if(in_array('backup', $this->configData['optAutoAction'])) {
// $this->addHookAfter('InputfieldFile::processInputDeleteFile', $this, 'deleteBackup');
//}
}
// optimize images in auto mode on pageimage->url() method in templates
if(!$isAdmin && in_array('optimize_auto', $this->configData['optApiAction'])) {
//$this->log->save("addhookafter Pagefile::url in templates");
$this->addHookAfter('Pageimage::url', $this, 'optimizeOnUrl', array('priority'=>201));
}
}
/**
* Hook after ImageSizer::resize in auto mode
* Just set the flag that image is resized and it will be optimized if needed
*
*/
public function checkOptimizeNeeded(/*$event*/) {
//$imagesizer = $event->object;
//$imagesizer->filename
$this->isOptimizeNeeded = true;
}
/**
* Hook after Pageimage::size in auto mode
* Optimize image on resize/crop
*
* @param HookEvent $event
*
*/
public function optimizeOnResize($event) {
$thumb = $event->return;
$this->optimize($thumb, false, 'auto');
$this->isOptimizeNeeded = false;
$event->return = $thumb;
}
/**
* Hook after Pageimage::size in API mode
* Optimize image on resize/crop
*
* @param HookEvent $event
*
*/
public function optimizeOnResizeAPI($event) {
$thumb = $event->return;
$this->optimize($thumb, false, 'api');
$this->isOptimizeNeeded = false;
$event->return = $thumb;
}
/**
* Hook after ProcessCroppableImage3::executeSave in auto mode
* Optimize image on crop when FieldtypeCroppableImage3 is installed
*
* @param HookEvent $event
*
*/
public function optimizeOnResizeCI3($event) {
// get page-id from post, sanitize, validate page and edit permission
$id = intval($this->input->post->pages_id);
$page = wire('pages')->get($id);
if(!$page->id) throw new WireException('Invalid page');
$editable = $page instanceof RepeaterPage ? $page->getForPage()->editable() : $page->editable();
if(!$editable) throw new WirePermissionException('Not Editable');
// get fieldname from post, sanitize and validate
$field = wire('sanitizer')->fieldName($this->input->post->field);
// UGLY WORKAROUND HERE TO GET A FIELDNAME WITH UPPERCASE LETTERS
foreach($page->fields as $f) {
if(mb_strtolower($f->name) != $field) continue;
$fieldName = $f->name;
break;
}
$fieldValue = $page->get($fieldName);
if(!$fieldValue || !$fieldValue instanceof Pagefiles) throw new WireException('Invalid field');
$field = $fieldValue;
unset($fieldValue);
// get filename from post, sanitize and validate
$filename = wire('sanitizer')->name($this->input->post->filename);
// $img is not variation
$img = $field->get('name=' . $filename);
if(!$img) throw new WireException('Invalid filename');
// get suffix from post, sanitize and validate
$suffix = wire('sanitizer')->name($this->input->post->suffix);
if(!$suffix || strlen($suffix) == 0) throw new WireException('No suffix');
// build the file
$file = basename($img->basename, '.' . $img->ext) . '.-' . strtolower($suffix) . '.' . $img->ext;
// get the variation
$myimage = $img->getVariations()->get($file);
if(!$myimage) throw new WireException('Invalid filename');
$this->optimize($myimage, false, 'auto');
$this->isOptimizeNeeded = false;
}
/**
* Hook before InputfieldFile::fileAdded in auto mode
* Optimize image on upload in admin interface
*
* @param HookEvent $event
*
*/
public function optimizeOnUpload($event) {
$img = $event->argumentsByName('pagefile');
// ensure only images are optimized
if(!$img instanceof Pageimage) return;
// resmushit doesn't support svg
if($img->ext == 'svg' && ($this->optimizers['svgo'] == "" || $this->configData["optAutoEngine"] == 'resmushit')) {
$this->wire('config')->js('AutoSmush', '');
return;
}
// ensure only images with allowed extensions are optimized
if(!in_array($img->ext, $this->allowedExtensions)) return;
// make a backup
if(in_array('backup', $this->configData['optAutoAction'])) {
//@copy($img->filename, $img->filename . '.autosmush');
$backup = rtrim($img->filename, $img->ext) . '-autosmush_original.' . $img->ext;
@copy($img->filename, $backup);
}
// optimize
if($this->optimize($img, true, 'auto') !== false) $this->isOptimizedOnUpload = true;
}
/**
* Hook after Pageimage::install in auto mode
* Optimize image on API $page->add() call
*
* @param HookEvent $event
*
*/
public function optimizeOnAdd($event) {
$img = $event->object;
// ensure only images are optimized
if(!$img instanceof Pageimage) return;
// resmushit doesn't support svg
if($img->ext == 'svg' && ($this->optimizers['svgo'] == "" || $this->configData['optApiEngine'] == 'resmushit')) return;
// ensure only images with allowed extensions are optimized
if(!in_array($img->ext, $this->allowedExtensions)) return;
// make a backup
if(in_array('backup', $this->configData['optApiAction'])) {
//@copy($img->filename, $img->filename . '.autosmush');
$backup = rtrim($img->filename, $img->ext) . '-autosmush_original.' . $img->ext;
@copy($img->filename, $backup);
}
// optimize
if($this->optimize($img, true, 'api') !== false) $this->isOptimizedOnUpload = true;
}
/**
* Hook after InputfieldImage::renderItem in manual mode
* Add optimize link/button to the image markup
*
* @param HookEvent $event
*
*/
public function addOptButton($event) {
// $event->object = InputfieldFile
// $event->object->value = Pagefiles
// $event->arguments[0] or $event->argumentsByName('pagefile') = Pagefile
$img = $event->argumentsByName('pagefile');
// resmushit doesn't support svg, also check if optimizer is present
if($img->ext == 'svg'
&& ($this->optimizers['svgo'] == "" || $this->configData["optManualEngine"] == 'resmushit')) return;
// ensure only images are optimized
if(!in_array($img->ext, $this->allowedExtensions)) return;
$id = $img->page->id;
$url = $this->wire('config')->urls->admin . 'module/edit?name=' . __CLASS__ .
"&mode=optimize&id=$id&file=$id,{$img->basename}";
$optimizing = $this->_('Optimizing');
$title = $this->_('Optimize image');
$text = $this->_('Optimize');
if($this->isOptimizedOnUpload) $text = $this->_('Optimized on upload');
if(stripos($event->return, 'InputfieldFileName') !== false) {
// InputfieldFileName class found, used in PW versions up to 3.0.17
$link = "<a href='$url' data-optimizing='$optimizing' class='InputfieldImageOptimize' title='$title'>$text</a>";
if(stripos($event->return, '</p>') !== false) { // insert link right before </p>
$event->return = str_replace('</p>', $link . '</p>', $event->return);
}
} else if(stripos($event->return, 'InputfieldImageEdit__buttons') !== false) {
// InputfieldImageEdit__buttons class found, used in PW versions after 3.0.17
// there is also InputfieldImage::renderButtons hook that could be used
$link = "<a href='$url&var=1' title='$title'>$text</a>";
$adminTheme = $this->wire('user')->admin_theme ? $this->wire('user')->admin_theme : $this->wire('config')->defaultAdminTheme;
if($adminTheme == 'AdminThemeUikit') {
$b = "<button type='button' data-href='$url' data-optimizing='$optimizing' class='InputfieldImageOptimize1 uk-button uk-button-small uk-button-text uk-margin-small-right'>";
} else {
$b = "<button type='button' data-href='$url' data-optimizing='$optimizing' class='InputfieldImageOptimize1 ui-button ui-corner-all ui-state-default'>";
}
$b .= "<span class='ui-button-text'><span class='fa fa-leaf'></span><span> $text</span></span></button>";
if(stripos($event->return, '</small>') !== false) { // insert button right before </small> as the last (third) button, after Crop and Variations buttons
$event->return = str_replace('</small>', $b . '</small>', $event->return);
}
} else {
$this->log->save('addOptButton: class InputfieldFileName/InputfieldImageedit__buttons not found');
}
}
/**
* Hook after ProcessPageEditImageSelect::executeVariations in manual mode
* Add optimize button to the variations page
*
* @param HookEvent $event
*
*/
public function addOptButtonVariations($event) {
$opturl = $this->wire('config')->urls->admin . 'module/edit?name=' . __CLASS__ . '&mode=optimize&var=1';
$b = $this->wire('modules')->get('InputfieldButton');
$b->attr('id', 'optimizeVariants');
$b->attr('data-href', $opturl);
$b->attr('value', $this->_('Optimize Checked'));
$b->attr('data-optimizing', $this->_('Optimizing'));
$b->attr('data-check', $this->_('No variation checked!'));
$b->icon = 'leaf';
$b->addClass('InputfieldOptimizeVariants');
$b->attr('style', 'display:none');
$needle = "<ul class='Inputfields'>";
// if there's only the default admin theme, $user->admin_theme is not available
$adminTheme = $this->wire('user')->admin_theme ? $this->wire('user')->admin_theme : $this->wire('config')->defaultAdminTheme;
//if($adminTheme == 'AdminThemeUikit') $needle = "<ul class='Inputfields uk-grid-collapse' uk-grid>";
if($adminTheme == 'AdminThemeUikit') $needle = "<ul class='Inputfields uk-grid-collapse uk-grid-match' uk-grid uk-height-match='target: > .Inputfield:not(.InputfieldStateCollapsed) > .InputfieldContent'>";
if(stripos($event->return, $needle) !== false) {
$event->return = str_replace($needle, $needle . $b->render(), $event->return);
}
}
/**
* Hook after InputfieldFile::processInputDeleteFile deletes original uploaded file
*
* @param HookEvent $event
*
*/
public function deleteBackup($event) {
$img = $event->argumentsByName('pagefile');
$backup = rtrim($img->filename, $img->ext) . '-autosmush_original.' . $img->ext;
//@unlink($img->filename . '.autosmush');
@unlink($backup);
}
/**
* Hook after Pageimage::url to return url with optimized image
* Create a variation image, optimize it and return url to this optimized variation
* /site/assets/files/1234/img.jpg -> /site/assets/files/1234/img.-autosmush.jpg
*
* @param HookEvent $event
*
*/
public function optimizeOnUrl($event) {
// DO NOT attempt to dump Pageimage object or access its urls methods as recursion occurs!!!
$url = $event->return;
//$this->log->save("optimizeOnAccess, url=$url");
// replace , with |
$exts = str_replace(array(', ', ','), '|', self::API_ALLOWED_EXTENSIONS . ', svg');
//$f = str_replace($this->wire('config')->urls->files, '', $url);
//$pageid = explode('/', $f)[0]; //sanitize
// extract page id from url
//0 => "/site/assets/files/1234/img.jpg"
//1 => "1234"
//2 => "img.jpg"
//3 => "jpg"
if(! preg_match('~' . $this->wire('config')->urls->files .'(\d+)/([^/]+\.(' . $exts . '))$~i', $url, $match)) {
$this->log->save("Invalid image url $url");
return;
}
$pid = $match[1];
$filename = $this->wire('sanitizer')->filename($match[2]);
if(stripos($filename, '-autosmush.')) return; // bypass if it contains this string, as image is already optimized
$p = $this->wire('pages')->get($pid);
if(!$p->id) {
$this->log->save("Invalid image url $url");
return;
}
$pfm = new PagefilesManager($p);
// heads up: even you ask for a variation, you get the original
// https://processwire.com/talk/topic/18230-retrieving-wrong-non-croped-file-with-filesmanager/
$img = $pfm->getFile($filename); // this is slower: $img = $pfm->getFile($url);
if(!$img instanceof Pageimage) return;
// to get a variation:
// $variation = $img->getVariations()->get($filename);
// if($variation) $img = $variation;
// do not attempt to optimize variation
//if($img->isVariation($varBasename)) return;
if($this->isVariation($img->basename, $filename)) return; //this is faster
// resmushit doesn't support svg
if($img->ext == 'svg' && ($this->optimizers['svgo'] == "" || $this->configData["optApiEngine"] == 'resmushit')) {
//$this->log->save("Unsupported extension svg"); //disabled to reduce log size, requested by Adrian
return;
}
// ensure only images with allowed extensions are optimized
if(!in_array($img->ext, $this->allowedExtensions)) {
$this->log->save("Unsupported extension " . $img->ext);
return;
}
// construct variation filename eg. C:/inetpub/wwwroot/site/assets/files/1234/img.-autosmush.jpg
$varFilename = rtrim($img->filename, $img->ext) . '-autosmush.' . $img->ext;
// construct variation basename eg. img.-autosmush.jpg
$varBasename = rtrim($img->basename, $img->ext) . '-autosmush.' . $img->ext;
// if variation doesn't exist, copy source file to variation file and optimize it
if(!file_exists($varFilename)) {
if(@copy($img->filename, $varFilename)) {
$vimg = $img->getVariations()->get($varBasename);
if($this->optimize($vimg, true, 'api') !== false) $this->isOptimizedOnUpload = true;
}
}
//$optimized = str_replace($match[2], '', $url) . $varBasename;
$optimized = str_replace($filename, '', $url) . $varBasename;
// return url with optimized variation image
$event->return = $optimized;
}
/**
* Process image optimize via ajax request when optimize link/button is clicked
* or in bulk mode
*
* @param bool $getVariations true when optimizing variation, false if original
* @return string|json
*
*/
public function onclickOptimize($getVariations = false) {
$err = "<i style='color:red' class='fa fa-times-circle'></i>";
$input = $this->wire('input');
$status = array(
'error' => null, // various errors
'error_api' => null, // erros from reSmush.it
'percentNew' => '0', // reduction percentage
'file' => '', // image name
'basedir' => '', // page id where image is eg. 1234
'url' => '#' // full url to the image
);
$file = $input->get('file'); // 1234,image.jpg
$id = (int) $input->get('id'); // could also get id from file var
$bulk = $input->get('bulk');
$m = ($bulk == 1) ? 'bulkOptimize: ' : 'onclickOptimize: ';
// $file = $this->wire('sanitizer')->pageNameUTF8($input->get('file'));
if($this->wire('config')->demo) {
$msg = $this->msgs['demo'];
$this->log->save($m . $msg);
if($bulk == 1) {
$status['error'] = $msg;
header('Content-Type: application/json');
echo json_encode($status);
} else {
echo $getVariations ? $err : $msg;
}
exit(0);
}
$page = $this->wire('pages')->get($id);
if(!$id || !$file || !$page->id) {
$msg = 'Invalid data!';
$this->log->save($m . $msg);
if($bulk == 1) {
$status['error'] = 'invalid data';
header('Content-Type: application/json');
echo json_encode($status);
} else {
echo $getVariations ? $err : $msg;
}
exit(0);
}
$status['file'] = $this->wire('config')->urls->files . $id . '/' . explode(',', $file)[1]; // fake image name
$status['basedir'] = $id; // page id where image is eg. 1234
// this doesn't work with CroppableImage3
//$img = wire('modules')->get('ProcessPageEditImageSelect')->getPageImage($getVariations);
// old version
/*$myimage = null;
$page = $this->wire('pages')->get($id);
$file = explode(',', $file)[1];
$imgs = $this->wire('modules')->get('ProcessPageEditImageSelect')->getImages($page);
foreach($imgs as $img) {
if($img->basename == $file) {
// original found
$myimage = $img;
break;
}
$myimage = $img->getVariations()->get($file);
if($myimage) {
// variation found
break;
}
}*/
// new version
$myimage = $this->getPageImage($page, true);
if(!$myimage) {
$file = explode(',', $file)[1];
$msg = ' not found!';
$this->log->save($m . $file . $msg);
if($bulk == 1) {
$status['error'] = 'image not found';
if(pathinfo($file, PATHINFO_EXTENSION) == 'webp') $status['error'] = 'unsupported image type';
header('Content-Type: application/json');
echo json_encode($status);
} else {
echo $getVariations ? $err : $msg;
}
exit(0);
}
$img = $myimage;
$src_size = (int) @filesize($img->filename);
if($src_size == 0) {
// this shouldn't happen but who knows
if($bulk == 1) {
$status['error'] = 'zero file size';
header('Content-Type: application/json');
echo json_encode($status);
} else {
echo 'Zero file size!';
}
exit(0);
}
if($bulk == 1) {
$status = $this->optimize($img, true, 'bulk');
header('Content-Type: application/json');
echo json_encode($status);
exit(0);
} else {
$status = $this->optimize($img, true, 'manual');
if($status['error'] !== null) {
$msg = $this->_('Not optimized, check log!');
// errors are already logged by optimize method
echo $getVariations ? $err : $msg;
exit(0);
}
}
@clearstatcache(true, $img->filename);
$dest_size = @filesize($img->filename);
if($getVariations) {
echo wireBytesStr($dest_size);
} else {
//$percentNew = 100 - (int) ($dest_size / $src_size * 100);
//printf($this->x_x('Optimized, reduced by %1$d%%'), $percentNew);
echo $this->_('Optimized, new size:') . ' ' . wireBytesStr($dest_size);
}
exit(0);
}
/**
* Create a list of images to be optimized and echo them in JSON format.
* Called from this module settings in bulk mode, on button click
*
*/
public function bulkOptimize() {
// check if engine is selected
if(!isset($this->configData['optBulkEngine'])) {
$this->log->save('No engine selected (bulk).');
$status = array(
'error' => 'No engine selected.',
'numImages' => 0
);
header('Content-Type: application/json');
echo json_encode($status);
exit(0);
}
$processOriginals = in_array('optimize_originals', $this->configData['optBulkAction']);
$processVariations = in_array('optimize_variations', $this->configData['optBulkAction']);
// get all fields of type FieldtypeImage or FieldtypeCroppableImage3
$selector = 'type=FieldtypeImage';
if(wire('modules')->isInstalled('FieldtypeCroppableImage3')) $selector .= '|FieldtypeCroppableImage3';
$imageFields = wire('fields')->find($selector);
// get total number of pages with images
$numPagesWithImages = 0;
foreach ($imageFields as $f) $numPagesWithImages += wire('pages')->count("$f>0, include=all");
$allImages = array();
$limit = 1;
$start = abs((int) wire('input')->get('start'));
if($start >= $numPagesWithImages) $start = $numPagesWithImages;
// get all images from pages that have image fields
foreach ($imageFields as $f) {
foreach (wire('pages')->find("$f>0, include=all, start=$start, limit=$limit") as $p) {
$images = $p->getUnformatted($f->name);
$id = $p->id;
$filesArray = false;
foreach ($images as $i) {
if($processOriginals) $allImages[] = "$id,{$i->basename}";
if($processVariations) {
// create array of files in pagefiles folder eg. /site/assest/files/1234/
if($filesArray === false) {
$filesArray = array_diff(@scandir($i->pagefiles->path), array('.', '..', $i->basename)); // array_diff removes ., .. and self
}
// iterate over array of files and check if file is variation of current image
foreach($filesArray as $file) {
//TODO: exclude file.-autosmush.jpg variations?
if($this->isVariation($i->basename, $file)) $allImages[] = "$id,$file";
}
}
}
}
}
$totalImages = $this->count($allImages);
$a = array();
if($start < $numPagesWithImages) {
$a["counter"] = sprintf($this->_('Processing page %1$d out of %2$d - {%3$d}%% complete'), // {} is placeholder, must be present
$start+1, $numPagesWithImages, (int) ($start / $numPagesWithImages * 100));
} else {
$a["counter"] = sprintf($this->_('All done - {100}%% complete'));
}
$a["numBatches"] = $numPagesWithImages;
$a["numImages"] = $totalImages;
$a["images"] = $allImages;
header('Content-Type: application/json');
echo json_encode($a);
exit(0);
}
/**
* Optimize image
*
* @param Pageimage $img Pageimage object
* @param boolean $force true, when you want to force optimize the image
* @param string $mode 'auto', 'api', 'manual' or 'bulk'
* @return array
*
*/
public function optimize($img, $force = false, $mode = 'auto') {
// note: optimized file overwrites original!
// todo: test with $config->pagefileExtendedPaths = true
// todo: clean up this method, shorten it,
// make optimizers as separate methods that takes just filename, no need for pageimage object
$demo = $this->wire('config')->demo;
$status = array(
'error' => null, // various errors
'error_api' => null, // errors from reSmush.it
'percentNew' => '0', // reduction percentage
'file' => $img->basename, // image name
'basedir' => basename(dirname($img->filename)), // page id where image is eg. 1234
//'url' => $img->httpUrl // full url to the image - commented because of hook after Pageimage::url
'url' => ''
);
// force is only used in optimizeOnUpload
if(!$force && !$this->isOptimizeNeeded) return false; // todo: return array?
if(!in_array($img->ext, $this->allowedExtensions)) {
$error = "($mode): Error optimizing " . $img->filename . ": unsupported extension";
$this->log->save($error);
$status['error'] = 'unsupported extension';
return $status;
}
$percentNew = 0;
$opt = $src_size = $dest_size = '';//$q = '';
$mode1 = ucfirst(strtolower($mode)); // must match config settings: Auto, Api, Manual, Bulk
$q = $this->configData["opt{$mode1}Quality"];
array_push($this->optimizeSettings['jpegoptim_options'], '-m' . $q);
$this->optimizeSettings['jpegoptim_options'] = array_unique($this->optimizeSettings['jpegoptim_options']);
if($this->configData["opt{$mode1}Engine"] == 'resmushit') {
// use resmush.it web service
$opt = "reSmush.it ($mode): ";
if($img->filesize >= self::API_SIZELIMIT) {
$error = 'Error optimizing ' . $img->filename . ', file larger then ' . self::API_SIZELIMIT . ' bytes';
$this->log->save($opt . $error);
$status['error'] = 'file to large';
return $status;
}
// upload image using curl
/*
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::WEBSERVICE . '&qlty=' . $q);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, self::CONNECTION_TIMEOUT);
curl_setopt($ch, CURLOPT_POST, true);
if(version_compare(PHP_VERSION, '5.5') >= 0) {
$postfields = array ('files' => new CURLFile($img->filename, 'image/' . $img->ext, $img->basename));
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
} else {
$postfields = array ('files' => '@'.$img->filename);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$data = curl_exec($ch);
if($data === false || curl_errno($ch)) {
$error = 'Error optimizing ' . $img->filename . ': cURL error: ' . curl_error($ch);
$this->log->save($error);
$status['error'] = curl_error($ch);
return $status;
}
curl_close($ch);
*/
// upload image using WireHttp class
$http = new WireHttp();
$http->setTimeout(self::CONNECTION_TIMEOUT); // important!!! default is 4.5 sec and that is to low
$eol = "\r\n";
$content = '';
$boundary = strtolower(md5(time()));
$content .= '--' . $boundary . $eol;