This repository was archived by the owner on Jul 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProcessImageMinimize.module
967 lines (827 loc) · 34 KB
/
ProcessImageMinimize.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
<?php
class ProcessImageMinimize extends WireData implements Module, ConfigurableModule
{
public static function getModuleInfo()
{
return array(
'title' => 'ProcessImageMinimize / minimize.pw',
'author' => 'Conclurer GbR',
'summary' => 'Uses minimize.pw to compress your images on the fly, increasing your site load performance.',
'version' => 102,
'href' => 'https://minimize.pw',
'autoload' => true
);
}
private $internalQueue = array(); # Internal queue for storing images to be minimized in the database
private $internalQueueItemsReplaceForced = array();
private $log;
private static $instance = null;
const mz_version = '1.0.2';
const base_url = 'https://minimize.pw/';
const service_url = 'https://minimize.pw/';
const table_name = 'process_image_minimize';
public function init()
{
$this->addHook('Pageimage::minimize', $this, 'getMinimizedPicture');
$this->addHook('Pageimage::mz', $this, 'getMinimizedPicture');
$this->addHook('Pageimages::delete', $this, 'deleteMinimizedPicture');
$this->addHookAfter('InputfieldFile::fileAdded', $this, 'minimizeUploadedImage');
$this->addHookAfter('Page::render', $this, 'pageLoadedHandler');
if (class_exists('FieldtypeCropImage')) {
$this->addHook('Pageimage::getMinimizedThumb', $this, 'CropImage_minimizeThumb');
$this->addHook('Pageimage::getMzThumb', $this, 'CropImage_minimizeThumb');
if ($this->auto_replace_crop_images == 1) $this->addHook('Pageimage::getThumb', $this, 'CropImage_importAllThumbs');
}
$this->verifyLicenseKey();
}
public function __construct()
{
$this->licence_valid = 0;
$this->backup_licence_key = '';
$this->licence_key = '';
$this->limit_reached_till = -1;
$this->replace_images = 0;
$this->auto_mz_images = 0;
$this->auto_replace_crop_images = 0;
$this->no_local_minimizing = 0;
$this->log = new FileLog(wire('config')->paths->logs . 'minimize.log.txt');
if (self::$instance == null) self::$instance = $this;
}
public function ___install()
{
if (!ini_get('allow_url_fopen')) {
throw new WireException("Your PHP has allow_url_fopen disabled, which is required by minimize.pw.");
}
$sql = array("CREATE TABLE " . self::table_name . " (image_id VARCHAR(255) NOT NULL PRIMARY KEY, reference VARCHAR(24), state INT(2) NOT NULL, processed VARCHAR(255), force_replace INT(1), created_at INT(11) UNSIGNED NOT NULL, updated_at INT(11) UNSIGNED NOT NULL)", "CREATE UNIQUE INDEX minimize_api_reference
ON " . self::table_name . " (reference) USING BTREE", "CREATE INDEX minimize_api_state
ON " . self::table_name . " (state) USING BTREE");
foreach ($sql as $s) wire('db')->query($s);
}
public function ___uninstall()
{
try {
wire('db')->query("DROP TABLE " . self::table_name);
} catch (Exception $e) {
}
}
/**
* Verifies the entered license key
*/
public function verifyLicenseKey()
{
if ($this->backup_licence_key != $this->licence_key) {
if ($this->licence_key == '') {
$this->backup_licence_key = '';
$this->licence_valid = 0;
} else {
# Verify new license key
$x = $this->apiCall('queue/license_valid', array('license' => $this->licence_key));
if ($x['valid']) {
$this->backup_licence_key = $this->licence_key;
$this->licence_valid = 1;
} else {
$this->licence_key = '';
$this->licence_valid = 0;
}
}
$this->save_configuration();
}
}
/**
* Adds the uploaded image to the local queue
* @param HookEvent $event
*/
public function minimizeUploadedImage(HookEvent $event)
{
if ($this->auto_mz_images != 1) return;
$image = $event->argumentsByName("pagefile");
$this->minimizePageimage($image);
}
/**
* Returns true if the ProcessWire instance is able to perform API calls
* @return bool
*/
public function is_able_to_perform_api_calls()
{
return ($this->ini_get_bool('allow_url_fopen'));
}
/**
* Returns true if the ProcessWire instance is able to submit images to the minimize.pw API
* @return bool
*/
public function is_able_to_convert_images()
{
return ($this->is_able_to_perform_api_calls() && $this->licence_valid == 1 && $this->limit_reached_till < time());
}
/**
* Pushes a image to the local queue
* @param $image_id
* @param bool $replaceForced
*/
protected function pushToMinimizedQueue($image_id, $replaceForced = false)
{
if (!in_array($image_id, $this->internalQueue)) {
array_push($this->internalQueue, $image_id);
$this->internalQueueItemsReplaceForced[$image_id] = ($replaceForced) ? 1 : 0;
}
}
/**
* Returns a Pageimage's image id
* @param Pageimage $img
* @return string
*/
protected function getImageIdByPageimage(Pageimage $img)
{
return $img->page->id . '-' . $img->name;
}
/**
* Returns a image_id by the path submitted
* @param $path
* @return string
*/
protected function getImageIdByPath($path)
{
$info = pathinfo($path);
$dirs = explode('/', $info['dirname']);
$page_id = end($dirs);
return $page_id . '-' . $info['basename'];
}
/**
* Returns true if the path is a path to a minimize version of a image
* @param $path
* @return bool
*/
protected function isMinimizedVariation($path)
{
$info = pathinfo($path);
$nameSegments = explode('.', $info['filename']);
return (end($nameSegments) == 'mz');
}
/**
* Performs one task per page load
*/
public function pageLoadedHandler()
{
if (count($this->internalQueue) > 0) {
# Remove items from queue which are already stored in the database
$mk = implode("', '", $this->internalQueue);
$result = wire('db')->query("SELECT image_id FROM " . self::table_name . " WHERE image_id IN ('$mk')");
while ($row = $result->fetch_row()) {
list($id) = $row;
$this->internalQueue = array_diff($this->internalQueue, array($id));
}
# Save images in queue to database table
if (count($this->internalQueue) > 0) {
foreach ($this->internalQueue as $item) {
$time = time();
$force_replace = $this->internalQueueItemsReplaceForced[$item];
wire('db')->query("INSERT INTO " . self::table_name . " (image_id, state, force_replace, created_at, updated_at) VALUES ('$item', 0, $force_replace, $time, $time)");
# create .mz-processing file
$this->addMzProcessingFile($item);
}
return;
}
}
# Only push images to queue if able to push
if ($this->is_able_to_convert_images()) {
if ($this->pushToMinimizeQueue()) return;
}
if ($this->getStateFromMinimizeQueue()) return;
if ($this->pullMinimizedImages()) return;
if ($this->removeTemporaryMinimizedImages()) return;
$this->removeOldDatabaseEntries();
}
/**
* Pushes local image URLs to the minimize.pw queue
* @return bool
*/
protected function pushToMinimizeQueue()
{
# Get non-transmitted images
$result = wire('db')->query("SELECT image_id FROM " . self::table_name . " WHERE state = 0 ORDER BY updated_at ASC LIMIT 50");
$images = array();
while ($row = $result->fetch_row()) {
list($id) = $row;
$images[] = $id;
}
$http = (wire('config')->https) ? 'https://' : 'http://';
$p = array();
$urls = array();
foreach ($images as $image) {
$mx = explode('-', $image, 2);
if (!file_exists(wire('config')->paths->files . $mx[0] . '/' . $mx[1])) {
# File does not exist, drop from database
wire('db')->query("DELETE FROM " . self::table_name . " WHERE image_id = '$image'");
continue;
}
$p[$http . wire('config')->httpHost . wire('config')->urls->files . $mx[0] . '/' . $mx[1]] = $image;
$urls[] = $http . wire('config')->httpHost . wire('config')->urls->files . $mx[0] . '/' . $mx[1];
}
# Push images to minimize.pw queue
if (count($urls) > 0) {
$r = $this->apiCall('queue/push', array('urls' => $urls, 'license' => $this->licence_key));
if (!$r['error']) {
foreach ($r['items'] as $item) {
if ($item['added']) {
$id = $p[$item['source']];
$reference = $item['reference'];
if (empty($reference)) continue;
$now = time();
try {
wire('db')->query("UPDATE " . self::table_name . " SET reference = '$reference', state = 1, updated_at = $now WHERE image_id = '$id'");
} catch (Exception $e) { }
} else {
if ($item['message'] == 'No credits left') {
// Set timeout to 1 hour, because the user has no credits left
$this->limit_reached_till = time() + 3600;
$this->save_configuration();
return true;
}
}
}
}
return true;
}
return false;
}
/**
* Fetches the state for the images that are longer than 100 seconds in the minimize.pw queue
* @return bool
*/
protected function getStateFromMinimizeQueue()
{
# Get images, which are in queue for more than 100 seconds
$before_x_minutes = time() - 100;
$result = wire('db')->query("SELECT reference, image_id FROM " . self::table_name . " WHERE state = 1 AND updated_at < $before_x_minutes ORDER BY updated_at ASC LIMIT 50");
$references = array();
$associated_images = array();
while ($row = $result->fetch_row()) {
list($reference, $image_id) = $row;
$references[] = $reference;
$associated_images[$reference] = $image_id;
}
if (count($references) > 0) {
$items = $this->apiCall('queue/state', array('references' => implode(',', $references)));
foreach ($items as $item) {
$reference = $item['reference'];
$now = time();
if ($item['valid']) {
switch ($item['state']) {
case 0:
case 1:
continue;
case 2:
# Object finished
$target_url = $item['processed'];
wire('db')->query("UPDATE " . self::table_name . " SET state = 2, updated_at = $now, processed = '$target_url' WHERE reference = '$reference'");
break;
case 3:
# Error occurred
$message = $item['message'];
wire('db')->query("UPDATE " . self::table_name . " SET state = 4, updated_at = $now, processed = '$message' WHERE reference = '$reference'");
# Remove .mz-processing file, add .mz-excluded file
$this->addMzExcludedFile($associated_images[$reference]);
break;
}
} else {
# Reference not found on Minimize.pw, restarting
wire('db')->query("UPDATE " . self::table_name . " SET state = 0, reference = null, updated_at = $now WHERE reference = '$reference'");
}
}
return true;
}
return false;
}
/**
* Downloads images from minimize.pw that are ready to be fetched.
* @return bool
*/
protected function pullMinimizedImages()
{
# Get images that are ready to be pulled
$result = wire('db')->query("SELECT image_id, processed, force_replace FROM " . self::table_name . " WHERE state = 2 ORDER BY updated_at ASC LIMIT 5");
$target_urls = array();
$associated_images = array();
$replace_settings = array();
while ($row = $result->fetch_row()) {
list($image_id, $target_url, $force_replace) = $row;
$target_urls[] = $target_url;
$associated_images[$target_url] = $image_id;
$replace_settings[$target_url] = $force_replace;
}
if (count($target_urls) > 0) {
foreach ($target_urls as $target_url) {
$image_id = $associated_images[$target_url];
$now = time();
if (!file_exists($this->getImageIdPath($image_id))) {
# If image is deleted on website, cancel process
wire('db')->query("DELETE FROM " . self::table_name . " WHERE image_id = '$image_id'");
continue;
}
try {
# If image is not stored on the server anymore
if ($this->get_http_response_code($target_url) != '200') throw new Exception();
# Save image to disk
if ($this->replace_images == 1 || $replace_settings[$target_url] == 1) {
file_put_contents($this->getImageIdPath($image_id), file_get_contents($target_url));
$this->addMzReplacedFile($image_id);
} else {
file_put_contents($this->getMinimizedPath($image_id), file_get_contents($target_url));
}
$this->removeMzProcessingFile($image_id);
# Update database
wire('db')->query("UPDATE " . self::table_name . " SET state = 3, updated_at = $now, processed = '$target_url' WHERE image_id = '$image_id'");
} catch (Exception $e) {
$this->log->save("Image with id $image_id not found on minimize.pw. Restarting process.");
# Image not found - restart minimize process
wire('db')->query("UPDATE " . self::table_name . " SET state = 0, updated_at = $now, processed = '', reference = '' WHERE image_id = '$image_id'");
}
}
return true;
}
return false;
}
/**
* Removes the locally compressed images (cleaning up)
*/
protected function removeTemporaryMinimizedImages()
{
$result = wire('db')->query("SELECT image_id, force_replace FROM " . self::table_name . " WHERE state = 3 ORDER BY updated_at ASC LIMIT 10");
$ids = array();
$replace_forced = array();
while ($row = $result->fetch_row()) {
list($image_id, $force_replace) = $row;
$ids[] = $image_id;
$replace_forced[$image_id] = $force_replace;
}
if (count($ids) > 0) {
foreach ($ids as $id) {
try {
# Remove temporary minimized images
$this->removeTemporaryVariations($id, ($replace_forced[$id] == 1));
} catch (Exception $e) {
$this->log->save("Unable to remove temporary files for image $id.");
}
# Update Database
$now = time();
wire('db')->query("UPDATE " . self::table_name . " SET state = 5, updated_at = $now WHERE image_id = '$id'");
}
return true;
}
return false;
}
protected function removeOldDatabaseEntries() {
$last_5_days = time()-5*24*60*60;
wire('db')->query("DELETE FROM " . self::table_name . " WHERE state >= 4 AND updated_at < $last_5_days");
return true;
}
/**
* Returns the path to the image with a given image id
* @param $image_id
* @return string
*/
protected function getImageIdPath($image_id)
{
$mx = explode('-', $image_id, 2);
return wire('config')->paths->files . $mx[0] . '/' . $mx[1];
}
/**
* Returns the path to the image's helper files with a given image id
* @param $image_id
* @return string
*/
protected function getImageHelperFilePath($image_id)
{
$mx = explode('-', $image_id, 2);
return wire('config')->paths->files . $mx[0] . '/mz/' . $mx[1];
}
/**
* Generates a .mz-excluded file
* @param $image_id
*/
protected function addMzExcludedFile($image_id)
{
$this->addHelperDirUnlessExists($image_id);
$this->removeMzProcessingFile($image_id);
try {
touch($this->getImageHelperFilePath($image_id) . '.mz-excluded');
} catch (Exception $e) {
$this->log->save(".mz-excluded file could not be created for image $image_id.");
}
}
/**
* Generates a .mz-processing file
* @param $image_id
*/
protected function addMzProcessingFile($image_id)
{
$this->addHelperDirUnlessExists($image_id);
try {
touch($this->getImageHelperFilePath($image_id) . '.mz-processing');
} catch (Exception $e) {
$this->log->save(".mz-processing file could not be created for image $image_id.");
}
}
/**
* Generates a .mz-replaced file
* @param $image_id
*/
protected function addMzReplacedFile($image_id)
{
$this->addHelperDirUnlessExists($image_id);
try {
touch($this->getImageHelperFilePath($image_id) . '.mz-replaced');
} catch (Exception $e) {
$this->log->save(".mz-replaced file could not be created for image $image_id.");
}
}
/**
* Removes a .mz-processing file
* @param $image_id
*/
protected function removeMzProcessingFile($image_id)
{
$this->addHelperDirUnlessExists($image_id);
try {
unlink($this->getImageHelperFilePath($image_id) . '.mz-processing');
} catch (Exception $e) {
$this->log->save(".mz-processing file could not be removed for image $image_id.");
}
}
/**
* Removes a .mz-temporary file
* @param $image_id
*/
protected function addMzTemporaryFile($image_id)
{
$this->addHelperDirUnlessExists($image_id);
try {
touch($this->getImageHelperFilePath($image_id) . '.mz-temporary');
} catch (Exception $e) {
$this->log->save(".mz-temporary file could not be created for image $image_id.");
}
}
/**
* Returns the path to the minimized version's file of a given image
* @param $image_id
* @return string
*/
protected function getMinimizedPath($image_id)
{
# Get path information
$info = pathinfo($this->getImageIdPath($image_id));
return $info['dirname'] . '/' . $info['filename'] . '.mz.' . $info['extension'];
}
/**
* Adds the helper file's directory unless it already exists
* @param $image_id
*/
protected function addHelperDirUnlessExists($image_id)
{
$info = pathinfo($this->getImageHelperFilePath($image_id));
if (!is_dir($info['dirname'])) {
mkdir($info['dirname']);
}
}
/**
* Removes all temporary variations for a given image
* @param $image_id
* @param bool $replaceForced
*/
protected function removeTemporaryVariations($image_id, $replaceForced = false)
{
$info = pathinfo($this->getImageIdPath($image_id));
if ($this->replace_images == 1 || $replaceForced) {
# Remove all variations to be recreated
$variations = glob($info['dirname'] . '/' . $info['filename'] . '*');
foreach ($variations as $variation) {
# Skip main file
if ($variation == $this->getImageIdPath($image_id)) continue;
# Skip if file already minimized or being processed
$helperBasePath = $this->getImageHelperFilePath($this->getImageIdByPath($variation));
if (file_exists($helperBasePath . '.mz-processing') || file_exists($helperBasePath . '.mz-replaced') || $this->isMinimizedVariation($variation)) continue;
try {
unlink($variation);
} catch (Exception $e) {
$this->log->save("Temporary images couldn't be removed for $image_id.");
}
}
} else {
# Remove only .mz-temporary variations
$temporary_variations = glob($info['dirname'] . '/mz/' . $info['filename'] . "*.mz-temporary");
foreach ($temporary_variations as $variation) {
try {
unlink($variation);
} catch (Exception $e) {
$this->log->save(".mz-temporary files couldn't be removed for $image_id.");
}
$k = str_replace(array('/mz/', '.mz-temporary'), array('/', ''), $variation);
try {
unlink($k);
} catch (Exception $e) {
$this->log->save("Temporary images couldn't be removed for $image_id.");
}
}
}
}
/**
* Writes the configuration settings array
*/
private function save_configuration()
{
wire('modules')->saveModuleConfigData($this, array(
'backup_licence_key' => $this->backup_licence_key,
'licence_valid' => $this->licence_valid,
'licence_key' => $this->licence_key,
'limit_reached_till' => $this->limit_reached_till,
'replace_images' => $this->replace_images,
'auto_mz_images' => $this->auto_mz_images,
'auto_replace_crop_images' => $this->auto_replace_crop_images,
'no_local_minimizing' => $this->no_local_minimizing
));
}
public static function getModuleConfigInputFields(array $data)
{
$fields = new InputfieldWrapper();
$field = wire('modules')->get('InputfieldText');
$field->name = 'licence_key';
$field->label = 'License Key';
if (isset($data['licence_key'])) $field->value = $data['licence_key'];
$fields->add($field);
if ($data['licence_key'] == '') {
$field = wire('modules')->get('InputfieldMarkup');
$field->label = 'Get a License Key';
$field->description = 'Please register your mail address at minimize.pw to get a <b>free</b> license key';
$button = wire('modules')->get('InputfieldButton');
$button->value = 'Get a License';
$button->href = 'https://minimize.pw';
$field->add($button);
$fields->add($field);
} else {
$field = wire('modules')->get('InputfieldMarkup');
$field->columnWidth = 100;
$field->label = 'Manage your License';
if ($data['limit_reached_till'] < time())
$field->description = 'Increase your volume and view statistics of your license.';
else
$field->description = '<b>Minimize.pw is unable to compress any more images</b><br>Please buy more credits.';
$button = wire('modules')->get('InputfieldButton');
$button->value = 'Dashboard';
$button->href = 'https://minimize.pw/login?license=' . $data['licence_key'];
$field->add($button);
$fields->add($field);
$field = wire('modules')->get('InputfieldCheckbox');
$field->columnWidth = 100;
$field->name = 'auto_mz_images';
$field->label = 'Automatically minimize new Images';
$field->description = "If checked, minimize.pw will automatically minimize every new image being uploaded. In this case you don't have to use the mz() API method.";
if (!empty($data['auto_mz_images'])) $field->set('checked', 'checked');
$fields->add($field);
$field = wire('modules')->get('InputfieldCheckbox');
$field->columnWidth = 100;
$field->name = 'no_local_minimizing';
$field->label = 'Disable temporary Images';
$field->description = "If checked, no temporary images will be created, while the images are in minimize.pw's queue. Recommended if you have large galleries.";
if (!empty($data['no_local_minimizing'])) $field->set('checked', 'checked');
$fields->add($field);
if ($data['replace_images'] == 1 || $data['auto_replace_crop_images'] == 1) {
$field = wire('modules')->get('InputfieldMarkup');
$field->label = 'Warning';
$field->description = '<span style="color: #f14b51"><b>Please be careful! You have enabled replacing images. Existing images might be overwritten!</b></span>';
$fields->add($field);
}
$field = wire('modules')->get('InputfieldCheckbox');
$field->columnWidth = 50;
$field->name = 'replace_images';
$field->label = 'Replace original Images';
$field->description = 'If checked, minimize.pw will replace the original image file with the minimized version, rather than adding a ".mz" variation.';
if (!empty($data['replace_images'])) $field->set('checked', 'checked');
$fields->add($field);
if (class_exists('FieldtypeCropImage')) {
$field = wire('modules')->get('InputfieldCheckbox');
$field->columnWidth = 50;
$field->name = 'auto_replace_crop_images';
$field->label = 'Automatically replace CropImages';
$field->description = 'If checked, minimize.pw will automatically replace every image file generated by CropImage with a minimized version.';
if (!empty($data['auto_replace_crop_images'])) $field->set('checked', 'checked');
$fields->add($field);
}
}
return $fields;
}
/**
* Removes the minimized version of a given picture
* @param HookEvent $event
*/
public function deleteMinimizedPicture(HookEvent $event)
{
$images = $event->object;
$image = $event->arguments[0];
if (is_string($image)) $image = $images->get($image);
if (!$image) return;
$image_id = $this->getImageIdByPageimage($image);
# Remove all associated helper files
foreach ($this->getAssociatedHelpers($image_id) as $helper) {
try {
unlink($helper);
} catch (Exception $e) {
$this->log->save(".mz-* helper files couldn't be removed for $image_id.");
}
}
# Remove all minimized image variations
$image_files = $this->getAssociatedImages($image_id);
foreach ($image_files as $image_file) {
# Remove file
try {
unlink($image_file);
} catch (Exception $e) {
$this->log->save("Associated images couldn't be removed for $image_id.");
}
}
# Delete images from database
$ids = array();
foreach ($image_files as $img) {
# Skip minimized images
if ($this->isMinimizedVariation($img)) continue;
$ids[] = $this->getImageIdByPath($img);
}
$length = count($ids);
$ids = implode("', '", $ids);
wire('db')->query("DELETE FROM " . self::table_name . " WHERE image_id IN ('$ids')");
# Send message
$this->message("Removed $length minimized image(s)", Notice::debug);
}
/**
* Returns all associated image files
* @param $image_id
* @return array
*/
protected function getAssociatedImages($image_id)
{
$info = pathinfo($this->getImageIdPath($image_id));
return glob($info['dirname'] . '/' . $info['filename'] . "*");
}
/**
* Returns all associated image helper files
* @param $image_id
* @return array
*/
protected function getAssociatedHelpers($image_id)
{
$info = pathinfo($this->getImageIdPath($image_id));
return glob($info['dirname'] . '/mz/' . $info['filename'] . "*");
}
/**
* Returns the minimized version of a given picture
* @param HookEvent $event
*/
public function getMinimizedPicture(HookEvent $event)
{
$event->return = $this->minimizePageimage($event->object);
}
protected function minimizePageimage($img)
{
if (get_class($img) != 'Pageimage') return;
$image_id = $this->getImageIdByPageimage($img);
$filename = $this->getMinimizedPath($image_id);
$helperBasePath = $this->getImageHelperFilePath($image_id);
//If cached minimize version isn't available, put image to queue
if (!is_file($filename)) {
# Add only to queue if file is not currently processed, excluded, replaced or temporary
if (!is_file($helperBasePath . '.mz-processing') && !is_file($helperBasePath . '.mz-excluded') && !is_file($helperBasePath . '.mz-replaced') && !is_file($helperBasePath . '.mz-temporary')) $this->pushToMinimizedQueue($image_id);
# Temporary create locally reduced file unless replaceForced
if ($this->no_local_minimizing != 1) {
$minimized_image = $img->size($img->width, $img->height, array('quality' => 77));
$this->addMzTemporaryFile($this->getImageIdByPageimage($minimized_image));
}
} else {
//Load cached image
$minimized_image = clone $img;
$minimized_image->setFilename($filename);
$minimized_image->setOriginal($img);
}
if (!isset($minimized_image)) {
$minimized_image = $img;
}
return $minimized_image;
}
/**
* Adds a image represented by a file path to the local queue
* @param $path
*/
public function minimizeImageByPath($path)
{
$image_id = $this->getImageIdByPath($path);
$helperBasePath = $this->getImageHelperFilePath($image_id);
if (!is_file($helperBasePath . '.mz-processing') && !is_file($helperBasePath . '.mz-excluded') && !is_file($helperBasePath . '.mz-replaced') && !is_file($helperBasePath . '.mz-temporary')) $this->pushToMinimizedQueue($image_id, true);
}
/**
* Returns the stream context info array
* @param array $post_data
* @param bool $post
* @return array
*/
private function generateStreamContextInfo($post_data = array(), $post = true)
{
$version = wire('config')->version;
$content = http_build_query($post_data);
return array(
'http' => array(
'method' => ($post) ? 'POST' : 'GET',
'header' => array(
"Host: minimize.pw",
'Content-type: application/x-www-form-urlencoded',
// Additional information for licence validating / quality improvement purposes
// For privacy information, please read our terms and conditions.
"Referer: " . $_SERVER['SERVER_NAME'] . "," . $_SERVER['SERVER_ADDR'],
"User-Agent: ProcessWire/$version/" . self::mz_version
),
'content' => $content
)
);
}
/**
* Performs a call to the minimize.pw API
* @param $node
* @param array $data
* @param bool $post
* @param bool $json
* @return mixed|string
*/
private function apiCall($node, $data = array(), $post = true, $json = true)
{
$context = stream_context_create($this->generateStreamContextInfo($data, $post));
$result = file_get_contents(self::service_url . $node, false, $context);
if ($json) {
$result = json_decode($result, true);
}
return $result;
}
/**
* Returns true or false for a PHP configuration
* @param $a
* @return bool
*/
private function ini_get_bool($a)
{
$b = ini_get($a);
switch (strtolower($b)) {
case 'on':
case 'yes':
case 'true':
return 'assert.active' !== $a;
case 'stdout':
case 'stderr':
return 'display_errors' === $a;
default:
return (bool)(int)$b;
}
}
/**
* Returns the HTTP response code for a certain URL
* @param $url
* @return string
*/
private function get_http_response_code($url)
{
$headers = get_headers($url);
return substr($headers[0], 9, 3);
}
/*
* Additional methods for compatibility
*/
/**
* Minimizes a CropImage and returns the URL
* @param HookEvent $event
*/
public function CropImage_minimizeThumb(HookEvent $event)
{
$image = $event->object;
$thumb = $event->arguments[0];
$path = $image->getThumb($thumb);
$this->minimizeImageByPath($path);
$event->return = $path;
}
/**
* Automatically imports all CropImages into the local queue
* @param HookEvent $event
*/
public function CropImage_importAllThumbs(HookEvent $event)
{
$image = $event->object;
$thumb = $event->arguments[0];
$stop = $event->arguments[1];
if ($stop != 1) {
$path = $image->getThumb($thumb, 1);
$this->minimizeImageByPath($path);
}
}
/**
* Adds a image represented by a file path to the local queue
* @param $path
*/
public static function pushImagePath($path)
{
self::$instance->minimizeImageByPath($path);
}
}