Repository navigation
Expand file tree
/
Copy pathSquareImages.module.php
More file actions
999 lines (865 loc) · 28.2 KB
/
Copy pathSquareImages.module.php
File metadata and controls
999 lines (865 loc) · 28.2 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
<?php namespace ProcessWire;
/**
* SquareImages
*
* Creates square thumbnails while maintaining aspect ratio with white/transparent background
* Adds new methods that don't interfere with ProcessWire core functionality
*
* Born from the real-world need to display vertical product images (like Coca-Cola bottles)
* uniformly in grids and galleries.
*
* Usage:
* - $image->square(500);
* - $image->squareWidth(500);
* - $image->squareHeight(500);
* - $image->getSquareURL(500);
* - $page->getSquareGallery(500, 700);
*
* @author Maxim Semenov <maxim@smnv.org> (smnv.org)
* @version 1.3.5
* @see https://smnv.org
* @license MIT
*
*/
class SquareImages extends WireData implements Module, ConfigurableModule {
/**
* Module information
*/
public static function getModuleInfo() {
return [
'title' => 'Square Images',
'summary' => 'Creates perfect square images from any source format with smart cropping',
'version' => 135,
'author' => 'Maxim Semenov',
'href' => 'https://smnv.org',
'icon' => 'crop',
'autoload' => true,
'singular' => true,
'requires' => 'ProcessWire>=3.0.0',
];
}
/**
* Default configuration
*/
public function __construct() {
parent::__construct();
$this->set('defaultSize', 512);
$this->set('maxSize', 5120);
$this->set('maxFileSizeMB', 10); // Store in MB, convert when using
$this->set('jpegQuality', 95);
$this->set('pngCompression', 9);
$this->set('skipAnimatedGifs', 0);
$this->set('placeholderImage', '/site/templates/images/1x1.png');
$this->set('enableLogging', 0);
}
/**
* Get property - handle checkbox empty strings
*/
public function __get($key) {
$value = parent::__get($key);
// Convert checkbox empty strings to false
if (($key === 'skipAnimatedGifs' || $key === 'enableLogging') && $value === '') {
return false;
}
return $value;
}
/**
* Initialize the module
*/
public function init() {
// Add new square() method - SAFE, no conflicts with core
$this->addHook('Pageimage::square', $this, 'hookSquare');
// Add convenient alias methods
$this->addHook('Pageimage::squareWidth', $this, 'hookSquareWidth');
$this->addHook('Pageimage::squareHeight', $this, 'hookSquareHeight');
// Add helper method for getting square URL directly
$this->addHook('Pageimage::getSquareURL', $this, 'hookGetSquareURL');
// Add gallery helper method
$this->addHook('Page::getSquareGallery', $this, 'hookGetSquareGallery');
}
/**
* Release a GD handle without calling deprecated imagedestroy() on PHP 8.5+.
*/
protected function releaseGDImage(&$image) {
if ($image && PHP_VERSION_ID < 80500) {
@imagedestroy($image);
}
$image = null;
}
/**
* Hook: Pageimage::square($size, $options)
* Main method for creating square images
*
* @param HookEvent $event
*/
public function hookSquare(HookEvent $event) {
$image = $event->object;
$size = $this->validateSize($event->arguments(0));
$options = $event->arguments(1) ?: [];
if (!is_array($options)) {
$options = [];
}
if (!$image || !$image instanceof Pageimage) {
$event->return = null;
return;
}
// Return null on failure so callers can distinguish a failed variation
// from a valid square image.
$event->return = $this->createSquareImage($image, $size, $options);
}
/**
* Hook: Pageimage::squareWidth($pixels)
* Alias for square() method
*/
public function hookSquareWidth(HookEvent $event) {
$size = $this->validateSize($event->arguments(0));
$options = $event->arguments(1) ?: [];
if (!is_array($options)) {
$options = [];
}
$event->arguments = [$size, $options];
$this->hookSquare($event);
}
/**
* Hook: Pageimage::squareHeight($pixels)
* Alias for square() method
*/
public function hookSquareHeight(HookEvent $event) {
$size = $this->validateSize($event->arguments(0));
$options = $event->arguments(1) ?: [];
if (!is_array($options)) {
$options = [];
}
$event->arguments = [$size, $options];
$this->hookSquare($event);
}
/**
* Validate and sanitize size parameter
*
* @param mixed $size
* @return int
*/
protected function validateSize($size) {
// Strict numeric validation - prevent type juggling exploits
if (!is_numeric($size) || is_array($size) || is_object($size)) {
$size = $this->defaultSize;
}
$size = (int) $size;
// Enforce minimum and maximum
if ($size < 1) $size = $this->defaultSize;
if ($size > $this->maxSize) $size = $this->maxSize;
return $size;
}
/**
* Parse a CSS-style hex background color.
*
* @param mixed $value
* @return array|null
*/
protected function parseBackgroundColor($value) {
if (!is_string($value)) return null;
$hex = strtolower(ltrim(trim($value), '#'));
if (preg_match('/^[0-9a-f]{3}$/', $hex)) {
$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
}
if (!preg_match('/^[0-9a-f]{6}$/', $hex)) return null;
return [
'red' => hexdec(substr($hex, 0, 2)),
'green' => hexdec(substr($hex, 2, 2)),
'blue' => hexdec(substr($hex, 4, 2)),
'hex' => $hex,
];
}
/**
* Creates a square image with centered crop by default.
*
* @param Pageimage $image The source image
* @param int $targetSize Size of the square
* @param array $options Additional options
* @return Pageimage|null
*/
protected function createSquareImage($image, $targetSize, $options = []) {
// Get paths
$originalPath = $image->filename;
$originalDir = dirname($originalPath);
$originalExtension = strtolower(pathinfo($originalPath, PATHINFO_EXTENSION));
$mode = isset($options['mode']) ? strtolower((string) $options['mode']) : 'crop';
if (!in_array($mode, ['crop', 'contain'], true)) {
$mode = 'crop';
}
$flatten = !empty($options['flatten']);
$background = $this->parseBackgroundColor($options['background'] ?? null);
if ($background !== null) {
$flatten = true;
} elseif ($flatten) {
$background = ['red' => 255, 'green' => 255, 'blue' => 255, 'hex' => 'ffffff'];
}
// Check file size limit (security)
$fileSize = @filesize($originalPath);
if ($fileSize === false) {
$this->error("Could not determine file size: {$originalPath}");
return null;
}
// Convert MB to bytes for comparison
$maxFileSizeBytes = ((int) $this->maxFileSizeMB) * 1024 * 1024;
// Safety: minimum 1MB
if ($maxFileSizeBytes < 1048576) {
$maxFileSizeBytes = 52428800; // 50MB default
}
if ($fileSize > $maxFileSizeBytes) {
$sizeInMB = round($fileSize / 1024 / 1024, 2);
$maxInMB = round($maxFileSizeBytes / 1024 / 1024, 2);
$this->error("Image file too large: {$sizeInMB}MB (max: {$maxInMB}MB)");
return null;
}
// Validate the payload independently from the filename. Legacy imports can
// contain a supported image whose extension does not match its bytes.
$sourceExtension = $this->detectImageExtension($originalPath, $originalExtension);
if ($sourceExtension === null) {
$this->error("Invalid or unsupported image format: {$originalPath}");
return null;
}
// Check for animated GIF
if ($sourceExtension === 'gif' && $this->isAnimatedGif($originalPath)) {
if ($this->skipAnimatedGifs) {
if ($this->enableLogging) {
$this->log("Skipping animated GIF: " . basename($originalPath));
}
return null;
} else {
if ($this->enableLogging) {
$this->log("Animated GIF detected, processing first frame only: " . basename($originalPath));
}
}
}
// Get clean base name (without existing variations)
$basename = $image->basename(false); // Gets original name without variations
$nameWithoutExt = pathinfo($basename, PATHINFO_FILENAME);
// Determine actual extension (WebP might fallback to JPG)
$actualExtension = $originalExtension;
if ($originalExtension === 'webp' && !function_exists('imagecreatefromwebp')) {
$this->error("WebP read support is not available: {$originalPath}");
return null;
}
if ($originalExtension === 'webp' && !function_exists('imagewebp')) {
$actualExtension = 'jpg';
if ($this->enableLogging) {
$this->log("WebP not supported, will save as JPEG");
}
}
// Create cached filename with ACTUAL extension
$modeSuffix = $mode === 'contain' ? 'contain' : 'crop';
$backgroundSuffix = $flatten ? "-flat-{$background['hex']}" : '';
$cachedName = "{$nameWithoutExt}.{$targetSize}x{$targetSize}sq-{$modeSuffix}{$backgroundSuffix}.{$actualExtension}";
$cachedPath = "{$originalDir}/{$cachedName}";
// Early exit if cached version exists
if (file_exists($cachedPath)) {
if ($this->enableLogging) {
$this->log("Using cached square image: {$cachedName}");
}
// Return Pageimage object from cache
return $this->getPageimageFromPath($image, $cachedPath);
}
// CRITICAL: Use file locking to prevent race condition
// Multiple simultaneous requests for same image could corrupt the file
$lockFile = $cachedPath . '.lock';
$lockHandle = @fopen($lockFile, 'w');
if ($lockHandle === false) {
$this->error("Cannot create lock file: {$lockFile}");
return null;
}
// Try to get exclusive lock (non-blocking)
if (!flock($lockHandle, LOCK_EX | LOCK_NB)) {
// Another process is creating this image, wait for it
if ($this->enableLogging) {
$this->log("Waiting for another process to create: {$cachedName}");
}
// Wait for shared lock (blocks until other process finishes)
flock($lockHandle, LOCK_SH);
flock($lockHandle, LOCK_UN);
fclose($lockHandle);
// Check if file was created successfully
if (file_exists($cachedPath)) {
if ($this->enableLogging) {
$this->log("Using cached square image created by another process: {$cachedName}");
}
return $this->getPageimageFromPath($image, $cachedPath);
}
// File still doesn't exist, something went wrong
$this->error("Race condition: file not created by other process");
return null;
}
// We have exclusive lock, proceed with creation
// Check directory is writable
if (!is_writable($originalDir)) {
$this->error("Directory not writable: {$originalDir}");
// Release lock if we have it
if (isset($lockHandle) && $lockHandle) {
flock($lockHandle, LOCK_UN);
fclose($lockHandle);
@unlink($lockFile);
}
return null;
}
// SECURITY: Prevent symlink attacks
// Ensure the cached path is within the assets directory
$realCachedDir = realpath($originalDir);
$realAssetsPath = realpath($this->wire('config')->paths->assets);
if (!$this->isPathWithin($realCachedDir, $realAssetsPath)) {
$this->error("Security: Invalid path detected");
// Release lock
$this->releaseLock($lockHandle, $lockFile);
return null;
}
// Sanitize filename to prevent directory traversal
$safeCachedName = basename($cachedName);
$safeCachedName = str_replace(["\0", '..'], '', $safeCachedName);
$cachedPath = $realCachedDir . DIRECTORY_SEPARATOR . $safeCachedName;
// Create GD resource based on format
$src = $this->createGDResource($originalPath, $sourceExtension);
if (!$src) {
$this->error("Failed to create GD resource from: {$originalPath}");
// Release lock
$this->releaseLock($lockHandle, $lockFile);
return null;
}
$src = $this->applyExifOrientation($src, $originalPath, $sourceExtension);
// Get actual dimensions
$srcWidth = imagesx($src);
$srcHeight = imagesy($src);
// Validate dimensions (check for false, zero, negative, or unreasonably large)
if ($srcWidth === false || $srcHeight === false ||
$srcWidth < 1 || $srcHeight < 1 ||
$srcWidth > 100000 || $srcHeight > 100000) {
$this->releaseGDImage($src);
$this->releaseLock($lockHandle, $lockFile);
$this->error("Invalid image dimensions: {$srcWidth}x{$srcHeight}");
return null;
}
// Calculate proportional dimensions. Crop fills the square, contain pads it.
if ($mode === 'contain') {
$scale = min($targetSize / $srcWidth, $targetSize / $srcHeight);
$newWidth = (int) round($srcWidth * $scale);
$newHeight = (int) round($srcHeight * $scale);
$srcX = 0;
$srcY = 0;
$copySrcWidth = $srcWidth;
$copySrcHeight = $srcHeight;
$dstX = (int) round(($targetSize - $newWidth) / 2);
$dstY = (int) round(($targetSize - $newHeight) / 2);
} else {
$cropSize = min($srcWidth, $srcHeight);
$srcX = (int) floor(($srcWidth - $cropSize) / 2);
$srcY = (int) floor(($srcHeight - $cropSize) / 2);
$copySrcWidth = $cropSize;
$copySrcHeight = $cropSize;
$newWidth = $targetSize;
$newHeight = $targetSize;
$dstX = 0;
$dstY = 0;
}
// Ensure dimensions are valid after calculation
if ($newWidth < 1 || $newHeight < 1 || $newWidth > $targetSize || $newHeight > $targetSize) {
$this->releaseGDImage($src);
$this->releaseLock($lockHandle, $lockFile);
$this->error("Calculated dimensions invalid: {$newWidth}x{$newHeight}");
return null;
}
// Create destination image
$dst = imagecreatetruecolor($targetSize, $targetSize);
if ($dst === false) {
$this->releaseGDImage($src);
$this->error("Failed to create destination image");
// Release lock
$this->releaseLock($lockHandle, $lockFile);
return null;
}
// Flatten transparent sources onto an opaque background when requested.
if ($flatten) {
imagealphablending($dst, true);
imagesavealpha($dst, false);
$backgroundColor = imagecolorallocate(
$dst,
$background['red'],
$background['green'],
$background['blue']
);
imagefill($dst, 0, 0, $backgroundColor);
// Otherwise preserve transparency based on format.
} elseif ($actualExtension === 'png' || $actualExtension === 'webp') {
// Alpha channel transparency (PNG, WebP)
imagealphablending($dst, false);
imagesavealpha($dst, true);
$transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);
imagefill($dst, 0, 0, $transparent);
} elseif ($actualExtension === 'gif') {
// Indexed transparency (GIF)
$transparentIndex = imagecolortransparent($src);
if ($transparentIndex >= 0) {
// Get the transparent color
$transparentColor = imagecolorsforindex($src, $transparentIndex);
// Validate color array (imagecolorsforindex can return false or incomplete array)
if ($transparentColor !== false &&
isset($transparentColor['red'], $transparentColor['green'], $transparentColor['blue'])) {
// Allocate same color in destination
$transparentNew = imagecolorallocate($dst,
$transparentColor['red'],
$transparentColor['green'],
$transparentColor['blue']
);
if ($transparentNew !== false) {
// Fill background and set as transparent
imagefill($dst, 0, 0, $transparentNew);
imagecolortransparent($dst, $transparentNew);
} else {
// Fallback to white if color allocation failed
$white = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst, 0, 0, $white);
}
} else {
// Invalid transparent color, use white background
$white = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst, 0, 0, $white);
}
} else {
// No transparency - white background
$white = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst, 0, 0, $white);
}
} else {
// White background for JPEG and others
$white = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst, 0, 0, $white);
}
// Resample and copy
$resampled = imagecopyresampled(
$dst, $src,
$dstX, $dstY,
$srcX, $srcY,
$newWidth, $newHeight,
$copySrcWidth, $copySrcHeight
);
if (!$resampled) {
$this->releaseGDImage($src);
$this->releaseGDImage($dst);
$this->releaseLock($lockHandle, $lockFile);
$this->error("Failed to resample image: {$originalPath}");
return null;
}
// Save the image based on format (use actual extension, not original)
$saved = $this->saveGDImage($dst, $cachedPath, $actualExtension, !$flatten);
// Clean up GD resources
$this->releaseGDImage($src);
$this->releaseGDImage($dst);
// Release lock and remove lock file
$this->releaseLock($lockHandle, $lockFile);
if (!$saved) {
$this->error("Failed to save square image: {$cachedPath}");
return null;
}
if ($this->enableLogging) {
$this->log("Created square image: {$cachedName}");
}
// Return as Pageimage object
return $this->getPageimageFromPath($image, $cachedPath);
}
/**
* Release an image generation lock and remove its marker file.
*
* @param resource|null $lockHandle
* @param string $lockFile
*/
protected function releaseLock($lockHandle, $lockFile) {
if ($lockHandle) {
flock($lockHandle, LOCK_UN);
fclose($lockHandle);
}
if ($lockFile) {
@unlink($lockFile);
}
}
/**
* Confirm a path is inside the configured ProcessWire assets directory.
*
* @param string|false $path
* @param string|false $parent
* @return bool
*/
protected function isPathWithin($path, $parent) {
if ($path === false || $parent === false) {
return false;
}
$path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$parent = rtrim($parent, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
return strpos($path, $parent) === 0;
}
/**
* Apply EXIF orientation for JPEG sources before resizing.
*
* @param resource $src
* @param string $path
* @param string $extension
* @return resource
*/
protected function applyExifOrientation($src, $path, $extension) {
if (!in_array($extension, ['jpg', 'jpeg'], true) || !function_exists('exif_read_data')) {
return $src;
}
$exif = @exif_read_data($path);
$orientation = isset($exif['Orientation']) ? (int) $exif['Orientation'] : 1;
$rotated = null;
switch ($orientation) {
case 3:
$rotated = imagerotate($src, 180, 0);
break;
case 6:
$rotated = imagerotate($src, -90, 0);
break;
case 8:
$rotated = imagerotate($src, 90, 0);
break;
}
if ($rotated) {
$this->releaseGDImage($src);
return $rotated;
}
return $src;
}
/**
* Create GD resource from file based on type
*
* @param string $path
* @param string $extension
* @return resource|false
*/
protected function createGDResource($path, $extension) {
switch ($extension) {
case 'jpg':
case 'jpeg':
return @imagecreatefromjpeg($path);
case 'png':
return @imagecreatefrompng($path);
case 'gif':
return @imagecreatefromgif($path);
case 'webp':
if (function_exists('imagecreatefromwebp')) {
return @imagecreatefromwebp($path);
}
break;
}
return false;
}
/**
* Save GD image based on format
*
* @param resource $image
* @param string $path
* @param string $extension
* @param bool $preserveAlpha
* @return bool
*/
protected function saveGDImage($image, $path, $extension, $preserveAlpha = true) {
// Enable progressive/interlaced for better loading
if ($extension === 'jpg' || $extension === 'jpeg' || $extension === 'png') {
imageinterlace($image, 1);
}
switch ($extension) {
case 'jpg':
case 'jpeg':
return imagejpeg($image, $path, $this->jpegQuality);
case 'png':
imagesavealpha($image, $preserveAlpha);
return imagepng($image, $path, $this->pngCompression);
case 'gif':
return imagegif($image, $path);
case 'webp':
// WebP support checked earlier, this should only be called if supported
if (function_exists('imagewebp')) {
imagesavealpha($image, $preserveAlpha);
return imagewebp($image, $path, $this->jpegQuality);
}
// Fallback shouldn't reach here (handled in createSquareImage)
$this->error("WebP save called but not supported");
return false;
}
return false;
}
/**
* Validate image format matches extension
*
* @param string $path File path
* @param string $extension Expected extension
* @return string|null Verified decoder extension, or null for invalid input.
*/
protected function detectImageExtension($path, $extension) {
$info = @getimagesize($path);
if (!$info) {
return null;
}
// Map extensions to image types
$typeMap = [
'jpg' => IMAGETYPE_JPEG,
'jpeg' => IMAGETYPE_JPEG,
'png' => IMAGETYPE_PNG,
'gif' => IMAGETYPE_GIF,
'webp' => defined('IMAGETYPE_WEBP') ? IMAGETYPE_WEBP : 18,
];
if (!isset($typeMap[$extension])) {
return null;
}
$extensionByType = array_flip($typeMap);
$detectedExtension = $extensionByType[$info[2]] ?? null;
if ($detectedExtension === null) {
return null;
}
if ($detectedExtension === 'jpeg') {
$detectedExtension = 'jpg';
}
if ($info[2] !== $typeMap[$extension]) {
if ($this->enableLogging) {
$this->log("Format mismatch: expected {$extension}, detected {$detectedExtension}; decoding verified payload");
}
}
// Additional check for CMYK JPEG (not supported by GD)
if ($detectedExtension === 'jpg') {
if (isset($info['channels']) && $info['channels'] == 4) {
$this->error("CMYK JPEG not supported: {$path}");
return null;
}
}
return $detectedExtension;
}
/**
* Check if GIF is animated
*
* @param string $path Path to GIF file
* @return bool
*/
protected function isAnimatedGif($path) {
if (!($fh = @fopen($path, 'rb'))) {
return false;
}
$count = 0;
// Read file in smaller chunks for better performance
while (!feof($fh) && $count < 2) {
$chunk = fread($fh, 1024 * 10); // 10KB chunks (faster than 100KB)
if ($chunk === false) break; // Error reading
$count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00[\x2C\x21]#s', $chunk, $matches);
// Early exit once we know it's animated
if ($count >= 2) break;
}
fclose($fh);
return $count > 1;
}
/**
* Get Pageimage object from file path
* Uses ProcessWire's proper method to create Pageimage
*
* @param Pageimage $original
* @param string $path
* @return Pageimage|null
*/
protected function getPageimageFromPath($original, $path) {
// Get the page and field that owns this image
$page = $original->page;
$field = $original->field;
if (!$page || !$field) return null;
// Get the Pageimages object
$pageimages = $page->getUnformatted($field->name);
if (!$pageimages) return null;
// Get just the filename
$filename = basename($path);
// Find or create the Pageimage
foreach ($pageimages as $img) {
if (basename($img->filename) === $filename) {
return $img;
}
}
// If not found, try to create new Pageimage with the path
// This works for variations
$basename = $original->basename();
$variation = str_replace($basename, $filename, $original->filename);
if (file_exists($variation)) {
// Clone the original and update its filename
$new = clone $original;
$new->setFilename($variation);
$new->setOriginal($original);
return $new;
}
return null;
}
/**
* Hook: Pageimage::getSquareURL($size, $options)
* Returns URL of square image (creates if needed)
*/
public function hookGetSquareURL(HookEvent $event) {
$image = $event->object;
$size = $this->validateSize($event->arguments(0));
$options = $event->arguments(1) ?: [];
if (!is_array($options)) {
$options = [];
}
if (!$image || !$image instanceof Pageimage) {
$event->return = $this->placeholderImage;
return;
}
// Use the new square() method - NO core conflicts
$squareImage = $image->square($size, $options);
$event->return = $squareImage ? $squareImage->url : $image->url;
}
/**
* Hook: Page::getSquareGallery($thumbSize, $largeSize, $fieldName)
* Returns JSON-encoded gallery data
*/
public function hookGetSquareGallery(HookEvent $event) {
$page = $event->object;
$thumbSize = $this->validateSize($event->arguments(0));
$largeSize = $this->validateSize($event->arguments(1));
$fieldName = $event->arguments(2) ?: 'images';
$images = $page->get($fieldName);
if ($images instanceof Pageimage) {
$images = [$images];
}
if (!$images || !is_iterable($images)) {
$event->return = json_encode([]);
return;
}
if (is_countable($images) && !count($images)) {
$event->return = json_encode([]);
return;
}
$galleryData = [];
foreach ($images as $image) {
if (!$image instanceof Pageimage) {
continue;
}
// Skip very small images (use smaller of the two sizes as threshold)
$minSize = min($thumbSize, $largeSize);
if ($image->width <= $minSize && $image->height <= $minSize) {
continue;
}
// Create square versions with error handling
$thumb = $image->square($thumbSize);
$large = $image->square($largeSize);
// Skip if either failed
if (!$thumb || !$large) {
if ($this->enableLogging) {
$this->log("Skipped image in gallery: failed to create square versions");
}
continue;
}
$galleryData[] = [
'photo' => $large->url,
'thumbnail' => $thumb->url,
'alt' => $page->title,
'description' => $page->title
];
}
$event->return = json_encode($galleryData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
/**
* Module configuration
*/
public function getModuleConfigInputfields(InputfieldWrapper $inputfields) {
$fieldset = $this->modules->get('InputfieldFieldset');
$fieldset->label = 'Size Settings';
$fieldset->icon = 'arrows';
$f = $this->modules->get('InputfieldInteger');
$f->name = 'defaultSize';
$f->label = 'Default Size';
$f->description = 'Default square size when not specified';
$f->value = $this->defaultSize;
$f->min = 1;
$f->columnWidth = 50;
$fieldset->add($f);
$f = $this->modules->get('InputfieldInteger');
$f->name = 'maxSize';
$f->label = 'Maximum Size';
$f->description = 'Maximum allowed square size (security limit)';
$f->value = $this->maxSize;
$f->min = 100;
$f->max = 10000;
$f->columnWidth = 50;
$fieldset->add($f);
$f = $this->modules->get('InputfieldInteger');
$f->name = 'maxFileSizeMB';
$f->label = 'Maximum File Size (MB)';
$f->description = 'Maximum source image file size in megabytes';
$f->notes = 'Prevents processing of extremely large files (security limit)';
$f->value = $this->maxFileSizeMB;
$f->min = 1;
$f->max = 500;
$f->columnWidth = 50;
$fieldset->add($f);
$inputfields->add($fieldset);
$fieldset = $this->modules->get('InputfieldFieldset');
$fieldset->label = 'Image Quality Settings';
$fieldset->icon = 'sliders';
$f = $this->modules->get('InputfieldInteger');
$f->name = 'jpegQuality';
$f->label = 'JPEG Quality';
$f->description = 'Quality for JPEG/WebP images (0-100)';
$f->value = $this->jpegQuality;
$f->min = 0;
$f->max = 100;
$f->columnWidth = 33;
$fieldset->add($f);
$f = $this->modules->get('InputfieldInteger');
$f->name = 'pngCompression';
$f->label = 'PNG Compression';
$f->description = 'Compression level for PNG (0-9)';
$f->value = $this->pngCompression;
$f->min = 0;
$f->max = 9;
$f->columnWidth = 34;
$f->notes = 'Higher values = smaller files, slower processing';
$fieldset->add($f);
$inputfields->add($fieldset);
$fieldset = $this->modules->get('InputfieldFieldset');
$fieldset->label = 'GIF Options';
$fieldset->icon = 'file-image-o';
$f = $this->modules->get('InputfieldCheckbox');
$f->name = 'skipAnimatedGifs';
$f->label = 'Skip Animated GIFs';
$f->description = 'Do not process animated GIF files (return null instead)';
$f->notes = 'When disabled, only first frame is processed';
if ((bool) $this->skipAnimatedGifs) $f->attr('checked', 'checked');
$fieldset->add($f);
$inputfields->add($fieldset);
$fieldset = $this->modules->get('InputfieldFieldset');
$fieldset->label = 'Advanced Options';
$fieldset->icon = 'cog';
$fieldset->collapsed = Inputfield::collapsedYes;
$f = $this->modules->get('InputfieldText');
$f->name = 'placeholderImage';
$f->label = 'Placeholder Image';
$f->description = 'Path to default placeholder image when image is missing';
$f->value = $this->placeholderImage;
$fieldset->add($f);
$f = $this->modules->get('InputfieldCheckbox');
$f->name = 'enableLogging';
$f->label = 'Enable Logging';
$f->description = 'Log square image creation (for debugging)';
if ((bool) $this->enableLogging) $f->attr('checked', 'checked');
$fieldset->add($f);
$inputfields->add($fieldset);
return $inputfields;
}
/**
* Called when module is installed
*/
public function ___install() {
// Check GD library
if (!extension_loaded('gd')) {
throw new WireException('GD library is required but not installed');
}
$this->message('SquareImages module installed successfully');
}
/**
* Called when module is uninstalled
*/
public function ___uninstall() {
// Module uninstalled
$this->message('SquareImages module uninstalled');
}
}