-
Notifications
You must be signed in to change notification settings - Fork 97
/
phpthumb.class.php
4606 lines (4086 loc) · 209 KB
/
phpthumb.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
//////////////////////////////////////////////////////////////
// phpThumb() by James Heinrich <[email protected]> //
// available at http://phpthumb.sourceforge.net //
// and/or https://github.com/JamesHeinrich/phpThumb //
//////////////////////////////////////////////////////////////
/// //
// See: phpthumb.readme.txt for usage instructions //
// ///
//////////////////////////////////////////////////////////////
if (!class_exists('phpthumb_functions', false)) {
ob_start();
if (!include_once __DIR__ . '/phpthumb.functions.php') {
ob_end_flush();
die('failed to include_once("' . __DIR__ . '/phpthumb.functions.php")');
}
ob_end_clean();
}
// make sure all image type constants are defined, even in older PHP versions that don't natively support them
$predefined_IMG_constants = array(
'IMG_GIF' => 1,
'IMG_JPG' => 2, // not a typo, both IMG_JPG and IMG_JPEG have a value of "2"
'IMG_JPEG' => 2, // not a typo, both IMG_JPG and IMG_JPEG have a value of "2"
'IMG_PNG' => 4,
'IMG_WBMP' => 8,
'IMG_XPM' => 16,
'IMG_WEBP' => 32, // PHP 7.0.10
'IMG_BMP' => 64, // PHP 7.2.0
'IMG_WEBP_LOSSLESS' => 101, // PHP 8.1.0
'IMG_AVIF' => 256, // PHP 8.1.0
);
$predefined_IMAGETYPE_constants = array(
'IMAGETYPE_GIF' => 1,
'IMAGETYPE_JPEG' => 2,
'IMAGETYPE_PNG' => 3,
'IMAGETYPE_SWF' => 4,
'IMAGETYPE_PSD' => 5,
'IMAGETYPE_BMP' => 6,
'IMAGETYPE_TIFF_II' => 7,
'IMAGETYPE_TIFF_MM' => 8,
'IMAGETYPE_JPC' => 9,
'IMAGETYPE_JP2' => 10,
'IMAGETYPE_JPX' => 11,
'IMAGETYPE_JB2' => 12,
'IMAGETYPE_SWC' => 13,
'IMAGETYPE_IFF' => 14,
'IMAGETYPE_WBMP' => 15,
'IMAGETYPE_XBM' => 16,
'IMAGETYPE_ICO' => 17,
'IMAGETYPE_WEBP' => 18, // PHP 7.0.10
'IMAGETYPE_AVIF' => 19, // PHP 8.1.0
);
foreach ($predefined_IMG_constants as $PHP_constant_name => $PHP_constant_value) {
if (!defined($PHP_constant_name)) {
define($PHP_constant_name, $PHP_constant_value);
}
}
foreach ($predefined_IMAGETYPE_constants as $PHP_constant_name => $PHP_constant_value) {
if (!defined($PHP_constant_name)) {
define($PHP_constant_name, $PHP_constant_value);
}
}
unset($predefined_IMG_constants, $predefined_IMAGETYPE_constants, $PHP_constant_name, $PHP_constant_value);
class phpthumb {
// public:
// START PARAMETERS (for object mode and phpThumb.php)
// See phpthumb.readme.txt for descriptions of what each of these values are
public $src = null; // SouRCe filename
public $new = null; // NEW image (phpThumb.php only)
public $w = null; // Width
public $h = null; // Height
public $wp = null; // Width (Portrait Images Only)
public $hp = null; // Height (Portrait Images Only)
public $wl = null; // Width (Landscape Images Only)
public $hl = null; // Height (Landscape Images Only)
public $ws = null; // Width (Square Images Only)
public $hs = null; // Height (Square Images Only)
public $f = null; // output image Format
public $q = -1; // jpeg output Quality
public $sx = null; // Source crop top-left X position
public $sy = null; // Source crop top-left Y position
public $sw = null; // Source crop Width
public $sh = null; // Source crop Height
public $zc = null; // Zoom Crop
public $ica = null; // Image Crop Auto
public $bc = null; // Border Color
public $bg = null; // BackGround color
public $fltr = array(); // FiLTeRs
public $goto = null; // GO TO url after processing
public $err = null; // default ERRor image filename
public $xto = null; // extract eXif Thumbnail Only
public $ra = null; // Rotate by Angle
public $ar = null; // Auto Rotate
public $aoe = null; // Allow Output Enlargement
public $far = null; // Fixed Aspect Ratio
public $iar = null; // Ignore Aspect Ratio
public $maxb = null; // MAXimum Bytes
public $down = null; // DOWNload thumbnail filename
public $md5s = null; // MD5 hash of Source image
public $sfn = 0; // Source Frame Number
public $dpi = 150; // Dots Per Inch for vector source formats
public $sia = null; // Save Image As filename
public $file = null; // >>>deprecated, DO NOT USE, will be removed in future versions<<<
public $phpThumbDebug = null;
// END PARAMETERS
// public:
// START CONFIGURATION OPTIONS (for object mode only)
// See phpThumb.config.php for descriptions of what each of these settings do
// * Directory Configuration
public $config_cache_directory = null;
public $config_cache_directory_depth = 0;
public $config_cache_disable_warning = true;
public $config_cache_source_enabled = false;
public $config_cache_source_directory = null;
public $config_temp_directory = null;
public $config_document_root = null;
// * Default output configuration:
public $config_output_format = 'jpeg';
public $config_output_maxwidth = 0;
public $config_output_maxheight = 0;
public $config_output_interlace = true;
// * Error message configuration
public $config_error_image_width = 400;
public $config_error_image_height = 100;
public $config_error_message_image_default = '';
public $config_error_bgcolor = 'CCCCFF';
public $config_error_textcolor = 'FF0000';
public $config_error_fontsize = 1;
public $config_error_die_on_error = false;
public $config_error_silent_die_on_error = false;
public $config_error_die_on_source_failure = true;
// * Anti-Hotlink Configuration:
public $config_nohotlink_enabled = true;
public $config_nohotlink_valid_domains = array();
public $config_nohotlink_erase_image = true;
public $config_nohotlink_text_message = 'Off-server thumbnailing is not allowed';
// * Off-server Linking Configuration:
public $config_nooffsitelink_enabled = false;
public $config_nooffsitelink_valid_domains = array();
public $config_nooffsitelink_require_refer = false;
public $config_nooffsitelink_erase_image = true;
public $config_nooffsitelink_watermark_src = '';
public $config_nooffsitelink_text_message = 'Off-server linking is not allowed';
// * Border & Background default colors
public $config_border_hexcolor = '000000';
public $config_background_hexcolor = 'FFFFFF';
// * TrueType Fonts
public $config_ttf_directory = './fonts';
public $config_max_source_pixels = null;
public $config_use_exif_thumbnail_for_speed = false;
public $config_allow_local_http_src = false;
public $config_imagemagick_path = null;
public $config_prefer_imagemagick = true;
public $config_imagemagick_use_thumbnail = true;
public $config_cache_maxage = null;
public $config_cache_maxsize = null;
public $config_cache_maxfiles = null;
public $config_cache_source_filemtime_ignore_local = false;
public $config_cache_source_filemtime_ignore_remote = true;
public $config_cache_default_only_suffix = false;
public $config_cache_force_passthru = true;
public $config_cache_prefix = ''; // default value set in the constructor below
// * MySQL
public $config_mysql_extension = null;
public $config_mysql_query = null;
public $config_mysql_hostname = null;
public $config_mysql_username = null;
public $config_mysql_password = null;
public $config_mysql_database = null;
// * Security
public $config_high_security_enabled = true;
public $config_high_security_password = null;
public $config_high_security_url_separator = '&';
public $config_disable_debug = true;
public $config_allow_src_above_docroot = false;
public $config_allow_src_above_phpthumb = true;
public $config_auto_allow_symlinks = true; // allow symlink target directories without explicitly whitelisting them
public $config_additional_allowed_dirs = array(); // additional directories to allow source images to be read from
public $config_file_create_mask = 0755;
public $config_dir_create_mask = 0755;
// * HTTP fopen
public $config_http_fopen_timeout = 10;
public $config_http_follow_redirect = true;
// * Compatability
public $config_disable_pathinfo_parsing = false;
public $config_disable_imagecopyresampled = false;
public $config_disable_onlycreateable_passthru = false;
public $config_disable_realpath = false;
public $config_http_user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7';
// END CONFIGURATION OPTIONS
// public: error messages (read-only; persistant)
public $debugmessages = array();
public $debugtiming = array();
public $fatalerror = null;
// private: (should not be modified directly)
public $thumbnailQuality = -1;
public $thumbnailFormat = null;
public $sourceFilename = null;
public $rawImageData = null;
public $IMresizedData = null;
public $outputImageData = null;
public $useRawIMoutput = false;
public $gdimg_output = null;
public $gdimg_source = null;
public $getimagesizeinfo = null;
public $source_width = null;
public $source_height = null;
public $thumbnailCropX = null;
public $thumbnailCropY = null;
public $thumbnailCropW = null;
public $thumbnailCropH = null;
public $exif_thumbnail_width = null;
public $exif_thumbnail_height = null;
public $exif_thumbnail_type = null;
public $exif_thumbnail_data = null;
public $exif_raw_data = null;
public $thumbnail_width = null;
public $thumbnail_height = null;
public $thumbnail_image_width = null;
public $thumbnail_image_height = null;
public $tempFilesToDelete = array();
public $cache_filename = null;
public $AlphaCapableFormats = array( 'png', 'ico', 'gif', 'webp', 'avif');
public $is_alpha = false;
public $iswindows = null;
public $issafemode = null;
public $php_memory_limit = null;
public $phpthumb_version = '1.7.22-202408102120';
//////////////////////////////////////////////////////////////////////
// public: constructor
public function __construct() {
$this->phpThumb();
}
public function phpThumb() {
$this->DebugTimingMessage('phpThumb() constructor', __FILE__, __LINE__);
$this->DebugMessage('phpThumb() v'.$this->phpthumb_version, __FILE__, __LINE__);
foreach (array(ini_get('memory_limit'), get_cfg_var('memory_limit')) as $php_config_memory_limit) {
if (!empty($php_config_memory_limit)) {
if (strtoupper($php_config_memory_limit[ strlen($php_config_memory_limit) - 1 ]) == 'G') { // PHP memory limit expressed in Gigabytes
$php_config_memory_limit = (int) substr($php_config_memory_limit, 0, -1) * 1073741824;
} elseif (strtoupper($php_config_memory_limit[ strlen($php_config_memory_limit) - 1 ]) == 'M') { // PHP memory limit expressed in Megabytes
$php_config_memory_limit = (int) substr($php_config_memory_limit, 0, -1) * 1048576;
}
$this->php_memory_limit = max($this->php_memory_limit, $php_config_memory_limit);
}
}
if ($this->php_memory_limit > 0) { // could be "-1" for "no limit"
$this->config_max_source_pixels = round($this->php_memory_limit * 0.20); // 20% of memory_limit
}
$this->iswindows = (bool) (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN');
$this->issafemode = (bool) preg_match('#(1|ON)#i', ini_get('safe_mode'));
$this->config_document_root = (!empty($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : $this->config_document_root);
$this->config_cache_prefix = ( isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'].'_' : '');
$this->purgeTempFiles(); // purge existing temp files if re-initializing object
$php_sapi_name = strtolower(function_exists('php_sapi_name') ? PHP_SAPI : '');
if ($php_sapi_name == 'cli') {
$this->config_allow_src_above_docroot = true;
}
if (!$this->config_disable_debug) {
// if debug mode is enabled, force phpThumbDebug output, do not allow normal thumbnails to be generated
$this->phpThumbDebug = (null === $this->phpThumbDebug ? 9 : max(1, (int) $this->phpThumbDebug));
}
}
public function __destruct() {
$this->purgeTempFiles();
}
public function __set(string $name, $value): void {
}
// public:
public function purgeTempFiles() {
foreach ($this->tempFilesToDelete as $tempFileToDelete) {
if (file_exists($tempFileToDelete)) {
$this->DebugMessage('Deleting temp file "'.$tempFileToDelete.'"', __FILE__, __LINE__);
@unlink($tempFileToDelete);
}
}
$this->tempFilesToDelete = array();
return true;
}
// public:
public function setSourceFilename($sourceFilename) {
//$this->resetObject();
//$this->rawImageData = null;
$this->sourceFilename = $sourceFilename;
$this->src = $sourceFilename;
if (null === $this->config_output_format) {
$sourceFileExtension = strtolower(substr(strrchr($sourceFilename, '.'), 1));
if (preg_match('#^[a-z]{3,4}$#', $sourceFileExtension)) {
$this->config_output_format = $sourceFileExtension;
$this->DebugMessage('setSourceFilename('.$sourceFilename.') set $this->config_output_format to "'.$sourceFileExtension.'"', __FILE__, __LINE__);
} else {
$this->DebugMessage('setSourceFilename('.$sourceFilename.') did NOT set $this->config_output_format to "'.$sourceFileExtension.'" because it did not seem like an appropriate image format', __FILE__, __LINE__);
}
}
$this->DebugMessage('setSourceFilename('.$sourceFilename.') set $this->sourceFilename to "'.$this->sourceFilename.'"', __FILE__, __LINE__);
return true;
}
// public:
public function setSourceData($rawImageData, $sourceFilename='') {
//$this->resetObject();
//$this->sourceFilename = null;
$this->rawImageData = $rawImageData;
$this->DebugMessage('setSourceData() setting $this->rawImageData ('.strlen($this->rawImageData).' bytes; magic="'.substr($this->rawImageData, 0, 4).'" ('.phpthumb_functions::HexCharDisplay(substr($this->rawImageData, 0, 4)).'))', __FILE__, __LINE__);
if ($this->config_cache_source_enabled) {
$sourceFilename = ($sourceFilename ? $sourceFilename : md5($rawImageData));
if (!is_dir($this->config_cache_source_directory)) {
$this->ErrorImage('$this->config_cache_source_directory ('.$this->config_cache_source_directory.') is not a directory');
} elseif (!@is_writable($this->config_cache_source_directory)) {
$this->ErrorImage('$this->config_cache_source_directory ('.$this->config_cache_source_directory.') is not writable');
}
$this->DebugMessage('setSourceData() attempting to save source image to "'.$this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename).'"', __FILE__, __LINE__);
if ($fp = @fopen($this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename), 'wb')) {
fwrite($fp, $rawImageData);
fclose($fp);
} elseif (!$this->phpThumbDebug) {
$this->ErrorImage('setSourceData() failed to write to source cache ('.$this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename).')');
}
}
return true;
}
// public:
public function setSourceImageResource($gdimg) {
//$this->resetObject();
$this->gdimg_source = $gdimg;
return true;
}
// public:
public function setParameter($param, $value) {
if ($param == 'src') {
$this->setSourceFilename($this->ResolveFilenameToAbsolute($value));
} elseif (isset($this->$param) && is_array($this->$param)) {
if (is_array($value)) {
foreach ($value as $arraykey => $arrayvalue) {
array_push($this->$param, $arrayvalue);
}
} else {
array_push($this->$param, $value);
}
} else {
$this->$param = $value;
}
return true;
}
// public:
public function getParameter($param) {
//if (property_exists('phpThumb', $param)) {
return $this->$param;
//}
//$this->DebugMessage('setParameter() attempting to get non-existant parameter "'.$param.'"', __FILE__, __LINE__);
//return false;
}
// public:
public function GenerateThumbnail() {
$this->setOutputFormat();
$this->phpThumbDebug('8a');
$this->ResolveSource();
$this->phpThumbDebug('8b');
$this->SetCacheFilename();
$this->phpThumbDebug('8c');
$this->ExtractEXIFgetImageSize();
$this->phpThumbDebug('8d');
if ($this->useRawIMoutput) {
$this->DebugMessage('Skipping rest of GenerateThumbnail() because ($this->useRawIMoutput == true)', __FILE__, __LINE__);
return true;
}
$this->phpThumbDebug('8e');
if (!$this->SourceImageToGD()) {
$this->DebugMessage('SourceImageToGD() failed', __FILE__, __LINE__);
return false;
}
$this->phpThumbDebug('8f');
$this->ImageCropAuto();
$this->phpThumbDebug('8h');
$this->Rotate();
$this->phpThumbDebug('8h');
$this->CreateGDoutput();
$this->phpThumbDebug('8i');
// default values, also applicable for far="C"
$destination_offset_x = round(($this->thumbnail_width - $this->thumbnail_image_width) / 2);
$destination_offset_y = round(($this->thumbnail_height - $this->thumbnail_image_height) / 2);
if (($this->far == 'L') || ($this->far == 'TL') || ($this->far == 'BL')) {
$destination_offset_x = 0;
}
if (($this->far == 'R') || ($this->far == 'TR') || ($this->far == 'BR')) {
$destination_offset_x = round($this->thumbnail_width - $this->thumbnail_image_width);
}
if (($this->far == 'T') || ($this->far == 'TL') || ($this->far == 'TR')) {
$destination_offset_y = 0;
}
if (($this->far == 'B') || ($this->far == 'BL') || ($this->far == 'BR')) {
$destination_offset_y = round($this->thumbnail_height - $this->thumbnail_image_height);
}
// // copy/resize image to appropriate dimensions
// $borderThickness = 0;
// if (!empty($this->fltr)) {
// foreach ($this->fltr as $key => $value) {
// if (preg_match('#^bord\|([0-9]+)#', $value, $matches)) {
// $borderThickness = $matches[1];
// break;
// }
// }
// }
// if ($borderThickness > 0) {
// //$this->DebugMessage('Skipping ImageResizeFunction() because BorderThickness="'.$borderThickness.'"', __FILE__, __LINE__);
// $this->thumbnail_image_height /= 2;
// }
$this->ImageResizeFunction(
$this->gdimg_output,
$this->gdimg_source,
$destination_offset_x,
$destination_offset_y,
$this->thumbnailCropX,
$this->thumbnailCropY,
$this->thumbnail_image_width,
$this->thumbnail_image_height,
$this->thumbnailCropW,
$this->thumbnailCropH
);
$this->DebugMessage('memory_get_usage() after copy-resize = '.(function_exists('memory_get_usage') ? @memory_get_usage() : 'n/a'), __FILE__, __LINE__);
imagedestroy($this->gdimg_source);
$this->DebugMessage('memory_get_usage() after imagedestroy = '.(function_exists('memory_get_usage') ? @memory_get_usage() : 'n/a'), __FILE__, __LINE__);
$this->phpThumbDebug('8i');
$this->AntiOffsiteLinking();
$this->phpThumbDebug('8j');
$this->ApplyFilters();
$this->phpThumbDebug('8k');
$this->AlphaChannelFlatten();
$this->phpThumbDebug('8l');
$this->MaxFileSize();
$this->phpThumbDebug('8m');
$this->DebugMessage('GenerateThumbnail() completed successfully', __FILE__, __LINE__);
return true;
}
// public:
public function RenderOutput() {
if (!$this->useRawIMoutput && !(is_resource($this->gdimg_output) || (is_object($this->gdimg_source) && $this->gdimg_source instanceOf \GdImage))) {
$this->DebugMessage('RenderOutput() failed because !is_resource($this->gdimg_output)', __FILE__, __LINE__);
return false;
}
if (!$this->thumbnailFormat) {
$this->DebugMessage('RenderOutput() failed because $this->thumbnailFormat is empty', __FILE__, __LINE__);
return false;
}
if ($this->useRawIMoutput) {
$this->DebugMessage('RenderOutput copying $this->IMresizedData ('.strlen($this->IMresizedData).' bytes) to $this->outputImage', __FILE__, __LINE__);
$this->outputImageData = $this->IMresizedData;
return true;
}
$builtin_formats = array();
if (function_exists('imagetypes')) {
$imagetypes = imagetypes();
$builtin_formats['wbmp'] = (bool) ($imagetypes & IMG_WBMP);
$builtin_formats['jpg'] = (bool) ($imagetypes & IMG_JPG);
$builtin_formats['gif'] = (bool) ($imagetypes & IMG_GIF);
$builtin_formats['png'] = (bool) ($imagetypes & IMG_PNG);
$builtin_formats['webp'] = (bool) ($imagetypes & IMG_WEBP); // PHP 7.0.10
$builtin_formats['bmp'] = (bool) ($imagetypes & IMG_BMP); // PHP 7.2.0
$builtin_formats['avif'] = (bool) ($imagetypes & IMG_AVIF); // PHP 8.1.0
}
$this->DebugMessage('imageinterlace($this->gdimg_output, '. (int) $this->config_output_interlace .')', __FILE__, __LINE__);
imageinterlace($this->gdimg_output, (int) $this->config_output_interlace);
$this->DebugMessage('RenderOutput() attempting image'.strtolower(@$this->thumbnailFormat).'($this->gdimg_output)', __FILE__, __LINE__);
ob_start();
switch ($this->thumbnailFormat) {
case 'wbmp':
if (empty($builtin_formats['wbmp'])) {
$this->DebugMessage('GD does not have required built-in support for WBMP output', __FILE__, __LINE__);
ob_end_clean();
return false;
}
imagewbmp($this->gdimg_output, null, $this->thumbnailQuality);
$this->outputImageData = ob_get_contents();
break;
case 'jpeg':
case 'jpg': // should be "jpeg" not "jpg" but just in case...
if (empty($builtin_formats['jpg'])) {
$this->DebugMessage('GD does not have required built-in support for JPEG output', __FILE__, __LINE__);
ob_end_clean();
return false;
}
imagejpeg($this->gdimg_output, null, $this->thumbnailQuality);
$this->outputImageData = ob_get_contents();
break;
case 'png':
if (empty($builtin_formats['png'])) {
$this->DebugMessage('GD does not have required built-in support for PNG output', __FILE__, __LINE__);
ob_end_clean();
return false;
}
if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.1.2', '>=')) {
// https://github.com/JamesHeinrich/phpThumb/issues/24
/* http://php.net/manual/en/function.imagepng.php:
from php source (gd.h):
2.0.12: Compression level: 0-9 or -1, where 0 is NO COMPRESSION at all,
:: 1 is FASTEST but produces larger files, 9 provides the best
:: compression (smallest files) but takes a long time to compress, and
:: -1 selects the default compiled into the zlib library.
Conclusion: Based on the Zlib manual (http://www.zlib.net/manual.html) the default compression level is set to 6.
*/
if (($this->thumbnailQuality >= -1) && ($this->thumbnailQuality <= 9)) {
$PNGquality = $this->thumbnailQuality;
} else {
$this->DebugMessage('Specified thumbnailQuality "'.$this->thumbnailQuality.'" is outside the accepted range (0-9, or -1). Using -1 as default value.', __FILE__, __LINE__);
$PNGquality = -1;
}
imagepng($this->gdimg_output, null, $PNGquality);
} else {
imagepng($this->gdimg_output);
}
$this->outputImageData = ob_get_contents();
break;
case 'gif':
if (empty($builtin_formats['gif'])) {
$this->DebugMessage('GD does not have required built-in support for GIF output', __FILE__, __LINE__);
ob_end_clean();
return false;
}
imagegif($this->gdimg_output);
$this->outputImageData = ob_get_contents();
break;
case 'webp':
if (empty($builtin_formats['webp'])) {
$this->DebugMessage('GD does not have required built-in support for WebP output', __FILE__, __LINE__);
ob_end_clean();
return false;
}
imagewebp($this->gdimg_output, null, $this->thumbnailQuality);
$this->outputImageData = ob_get_contents();
break;
case 'avif':
if (empty($builtin_formats['avif'])) {
$this->DebugMessage('GD does not have required built-in support for AVIF output', __FILE__, __LINE__);
ob_end_clean();
return false;
}
imageavif($this->gdimg_output, null, $this->thumbnailQuality);
$this->outputImageData = ob_get_contents();
break;
case 'bmp':
if (!empty($builtin_formats['bmp'])) {
imagebmp($this->gdimg_output);
$this->outputImageData = ob_get_contents();
break;
}
$this->DebugMessage('GD does not have required built-in support for BMP output', __FILE__, __LINE__);
if (!@include_once __DIR__ .'/phpthumb.bmp.php' ) {
$this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.bmp.php" which is required for BMP format output', __FILE__, __LINE__);
ob_end_clean();
return false;
}
$phpthumb_bmp = new phpthumb_bmp();
$this->outputImageData = $phpthumb_bmp->GD2BMPstring($this->gdimg_output);
unset($phpthumb_bmp);
break;
case 'ico':
if (!@include_once __DIR__ .'/phpthumb.ico.php' ) {
$this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.ico.php" which is required for ICO format output', __FILE__, __LINE__);
ob_end_clean();
return false;
}
$phpthumb_ico = new phpthumb_ico();
$arrayOfOutputImages = array($this->gdimg_output);
$this->outputImageData = $phpthumb_ico->GD2ICOstring($arrayOfOutputImages);
unset($phpthumb_ico);
break;
default:
$this->DebugMessage('RenderOutput failed because $this->thumbnailFormat "'.$this->thumbnailFormat.'" is not valid', __FILE__, __LINE__);
ob_end_clean();
return false;
}
ob_end_clean();
if (!$this->outputImageData) {
$this->DebugMessage('RenderOutput() for "'.$this->thumbnailFormat.'" failed', __FILE__, __LINE__);
ob_end_clean();
return false;
}
$this->DebugMessage('RenderOutput() completing with $this->outputImageData = '.strlen($this->outputImageData).' bytes', __FILE__, __LINE__);
return true;
}
// public:
public function RenderToFile($filename) {
if (preg_match('#^[a-z0-9]+://#i', $filename)) {
$this->DebugMessage('RenderToFile() failed because $filename ('.$filename.') is a URL', __FILE__, __LINE__);
return false;
}
// render thumbnail to this file only, do not cache, do not output to browser
//$renderfilename = $this->ResolveFilenameToAbsolute(dirname($filename)).DIRECTORY_SEPARATOR.basename($filename);
$renderfilename = $filename;
if (($filename[0] != '/') && ($filename[0] != '\\') && ($filename[1] != ':')) {
$renderfilename = $this->ResolveFilenameToAbsolute($renderfilename);
}
if (!@is_writable(dirname($renderfilename))) {
$this->DebugMessage('RenderToFile() failed because "'.dirname($renderfilename).'/" is not writable', __FILE__, __LINE__);
return false;
}
if (@is_file($renderfilename) && !@is_writable($renderfilename)) {
$this->DebugMessage('RenderToFile() failed because "'.$renderfilename.'" is not writable', __FILE__, __LINE__);
return false;
}
if ($this->RenderOutput()) {
if (file_put_contents($renderfilename, $this->outputImageData)) {
@chmod($renderfilename, $this->getParameter('config_file_create_mask'));
$this->DebugMessage('RenderToFile('.$renderfilename.') succeeded', __FILE__, __LINE__);
return true;
}
if (!@file_exists($renderfilename)) {
$this->DebugMessage('RenderOutput ['.$this->thumbnailFormat.'('.$renderfilename.')] did not appear to fail, but the output image does not exist either...', __FILE__, __LINE__);
}
} else {
$this->DebugMessage('RenderOutput ['.$this->thumbnailFormat.'('.$renderfilename.')] failed', __FILE__, __LINE__);
}
return false;
}
// public:
public function OutputThumbnail() {
$this->purgeTempFiles();
if (!$this->useRawIMoutput && !(is_resource($this->gdimg_output) || (is_object($this->gdimg_source) && $this->gdimg_source instanceOf \GdImage))) {
$this->DebugMessage('OutputThumbnail() failed because !is_resource($this->gdimg_output)', __FILE__, __LINE__);
return false;
}
if (headers_sent()) {
return $this->ErrorImage('OutputThumbnail() failed - headers already sent');
}
$downloadfilename = phpthumb_functions::SanitizeFilename(is_string($this->sia) ? $this->sia : ($this->down ? $this->down : 'phpThumb_generated_thumbnail'.'.'.$this->thumbnailFormat));
$this->DebugMessage('Content-Disposition header filename set to "'.$downloadfilename.'"', __FILE__, __LINE__);
if ($downloadfilename) {
header('Content-Disposition: '.($this->down ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"');
} else {
$this->DebugMessage('failed to send Content-Disposition header because $downloadfilename is empty', __FILE__, __LINE__);
}
if ($this->useRawIMoutput) {
header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
echo $this->IMresizedData;
} else {
$this->DebugMessage('imageinterlace($this->gdimg_output, '. (int) $this->config_output_interlace .')', __FILE__, __LINE__);
imageinterlace($this->gdimg_output, (int) $this->config_output_interlace);
switch ($this->thumbnailFormat) {
case 'gif':
case 'jpeg':
case 'png':
case 'webp':
case 'avif':
$ImageOutFunction = 'image'.$this->thumbnailFormat;
if (!function_exists($ImageOutFunction)) {
$this->DebugMessage($ImageOutFunction.' is not available', __FILE__, __LINE__);
return false;
}
header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
if ($this->thumbnailFormat == 'gif') {
@$ImageOutFunction($this->gdimg_output);
} else {
@$ImageOutFunction($this->gdimg_output, null, $this->thumbnailQuality);
}
break;
case 'bmp':
if (function_exists('imagebmp')) {
header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
imagebmp($this->gdimg_output);
break;
}
if (!@include_once __DIR__ .'/phpthumb.bmp.php' ) {
$this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.bmp.php" which is required for BMP format output', __FILE__, __LINE__);
return false;
}
$phpthumb_bmp = new phpthumb_bmp();
if (is_object($phpthumb_bmp)) {
$bmp_data = $phpthumb_bmp->GD2BMPstring($this->gdimg_output);
unset($phpthumb_bmp);
if (!$bmp_data) {
$this->DebugMessage('$phpthumb_bmp->GD2BMPstring() failed', __FILE__, __LINE__);
return false;
}
header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
echo $bmp_data;
} else {
$this->DebugMessage('new phpthumb_bmp() failed', __FILE__, __LINE__);
return false;
}
break;
case 'ico':
if (!@include_once __DIR__ .'/phpthumb.ico.php' ) {
$this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.ico.php" which is required for ICO format output', __FILE__, __LINE__);
return false;
}
$phpthumb_ico = new phpthumb_ico();
if (is_object($phpthumb_ico)) {
$arrayOfOutputImages = array($this->gdimg_output);
$ico_data = $phpthumb_ico->GD2ICOstring($arrayOfOutputImages);
unset($phpthumb_ico);
if (!$ico_data) {
$this->DebugMessage('$phpthumb_ico->GD2ICOstring() failed', __FILE__, __LINE__);
return false;
}
header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
echo $ico_data;
} else {
$this->DebugMessage('new phpthumb_ico() failed', __FILE__, __LINE__);
return false;
}
break;
default:
$this->DebugMessage('OutputThumbnail failed because $this->thumbnailFormat "'.$this->thumbnailFormat.'" is not valid', __FILE__, __LINE__);
return false;
break;
}
}
return true;
}
// public:
public function CleanUpCacheDirectory() {
$this->DebugMessage('CleanUpCacheDirectory() set to purge ('.(null === $this->config_cache_maxage ? 'NULL' : number_format($this->config_cache_maxage / 86400, 1)).' days; '.(null === $this->config_cache_maxsize ? 'NULL' : number_format($this->config_cache_maxsize / 1048576, 2)).' MB; '.(null === $this->config_cache_maxfiles ? 'NULL' : number_format($this->config_cache_maxfiles)).' files)', __FILE__, __LINE__);
if (!is_writable($this->config_cache_directory)) {
$this->DebugMessage('CleanUpCacheDirectory() skipped because "'.$this->config_cache_directory.'" is not writable', __FILE__, __LINE__);
return true;
}
// cache status of cache directory for 1 hour to avoid hammering the filesystem functions
$phpThumbCacheStats_filename = $this->config_cache_directory.DIRECTORY_SEPARATOR.'phpThumbCacheStats.txt';
if (file_exists($phpThumbCacheStats_filename) && is_readable($phpThumbCacheStats_filename) && (filemtime($phpThumbCacheStats_filename) >= (time() - 3600))) {
$this->DebugMessage('CleanUpCacheDirectory() skipped because "'.$phpThumbCacheStats_filename.'" is recently modified', __FILE__, __LINE__);
return true;
}
if (!@touch($phpThumbCacheStats_filename)) {
$this->DebugMessage('touch('.$phpThumbCacheStats_filename.') failed', __FILE__, __LINE__);
}
$DeletedKeys = array();
$AllFilesInCacheDirectory = array();
if (($this->config_cache_maxage > 0) || ($this->config_cache_maxsize > 0) || ($this->config_cache_maxfiles > 0)) {
$CacheDirOldFilesAge = array();
$CacheDirOldFilesSize = array();
$AllFilesInCacheDirectory = phpthumb_functions::GetAllFilesInSubfolders($this->config_cache_directory);
foreach ($AllFilesInCacheDirectory as $fullfilename) {
if (preg_match('#'.preg_quote($this->config_cache_prefix).'#i', $fullfilename) && file_exists($fullfilename)) {
$CacheDirOldFilesAge[$fullfilename] = @fileatime($fullfilename);
if ($CacheDirOldFilesAge[$fullfilename] == 0) {
$CacheDirOldFilesAge[$fullfilename] = @filemtime($fullfilename);
}
$CacheDirOldFilesSize[$fullfilename] = @filesize($fullfilename);
}
}
if (empty($CacheDirOldFilesSize)) {
$this->DebugMessage('CleanUpCacheDirectory() skipped because $CacheDirOldFilesSize is empty (phpthumb_functions::GetAllFilesInSubfolders('.$this->config_cache_directory.') found no files)', __FILE__, __LINE__);
return true;
}
$DeletedKeys['zerobyte'] = array();
foreach ($CacheDirOldFilesSize as $fullfilename => $filesize) {
// purge all zero-size files more than an hour old (to prevent trying to delete just-created and/or in-use files)
$cutofftime = time() - 3600;
if (($filesize == 0) && ($CacheDirOldFilesAge[$fullfilename] < $cutofftime)) {
$this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__);
if (@unlink($fullfilename)) {
$DeletedKeys['zerobyte'][] = $fullfilename;
unset($CacheDirOldFilesSize[$fullfilename]);
unset($CacheDirOldFilesAge[$fullfilename]);
}
}
}
$this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['zerobyte']).' zero-byte files', __FILE__, __LINE__);
asort($CacheDirOldFilesAge);
if ($this->config_cache_maxfiles > 0) {
$TotalCachedFiles = count($CacheDirOldFilesAge);
$DeletedKeys['maxfiles'] = array();
foreach ($CacheDirOldFilesAge as $fullfilename => $filedate) {
if ($TotalCachedFiles > $this->config_cache_maxfiles) {
$this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__);
if (@unlink($fullfilename)) {
$TotalCachedFiles--;
$DeletedKeys['maxfiles'][] = $fullfilename;
}
} else {
// there are few enough files to keep the rest
break;
}
}
$this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['maxfiles']).' files based on (config_cache_maxfiles='.$this->config_cache_maxfiles.')', __FILE__, __LINE__);
foreach ($DeletedKeys['maxfiles'] as $fullfilename) {
unset($CacheDirOldFilesAge[$fullfilename]);
unset($CacheDirOldFilesSize[$fullfilename]);
}
}
if ($this->config_cache_maxage > 0) {
$mindate = time() - $this->config_cache_maxage;
$DeletedKeys['maxage'] = array();
foreach ($CacheDirOldFilesAge as $fullfilename => $filedate) {
if ($filedate > 0) {
if ($filedate < $mindate) {
$this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__);
if (@unlink($fullfilename)) {
$DeletedKeys['maxage'][] = $fullfilename;
}
} else {
// the rest of the files are new enough to keep
break;
}
}
}
$this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['maxage']).' files based on (config_cache_maxage='.$this->config_cache_maxage.')', __FILE__, __LINE__);
foreach ($DeletedKeys['maxage'] as $fullfilename) {
unset($CacheDirOldFilesAge[$fullfilename]);
unset($CacheDirOldFilesSize[$fullfilename]);
}
}
if ($this->config_cache_maxsize > 0) {
$TotalCachedFileSize = array_sum($CacheDirOldFilesSize);
$DeletedKeys['maxsize'] = array();
foreach ($CacheDirOldFilesAge as $fullfilename => $filedate) {
if ($TotalCachedFileSize > $this->config_cache_maxsize) {
$this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__);
if (@unlink($fullfilename)) {
$TotalCachedFileSize -= $CacheDirOldFilesSize[$fullfilename];
$DeletedKeys['maxsize'][] = $fullfilename;
}
} else {
// the total filesizes are small enough to keep the rest of the files
break;
}
}
$this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['maxsize']).' files based on (config_cache_maxsize='.$this->config_cache_maxsize.')', __FILE__, __LINE__);
foreach ($DeletedKeys['maxsize'] as $fullfilename) {
unset($CacheDirOldFilesAge[$fullfilename]);
unset($CacheDirOldFilesSize[$fullfilename]);
}
}
} else {
$this->DebugMessage('skipping CleanUpCacheDirectory() because config set to not use it', __FILE__, __LINE__);
}
$totalpurged = 0;
foreach ($DeletedKeys as $key => $value) {
$totalpurged += count($value);
}
$this->DebugMessage('CleanUpCacheDirectory() purged '.$totalpurged.' files (from '.count($AllFilesInCacheDirectory).') based on config settings', __FILE__, __LINE__);
if ($totalpurged > 0) {
$empty_dirs = array();
foreach ($AllFilesInCacheDirectory as $fullfilename) {
if (is_dir($fullfilename)) {
$empty_dirs[$this->realPathSafe($fullfilename)] = 1;
} else {
unset($empty_dirs[$this->realPathSafe(dirname($fullfilename))]);
}
}
krsort($empty_dirs);
$totalpurgeddirs = 0;
foreach ($empty_dirs as $empty_dir => $dummy) {
if ($empty_dir == $this->config_cache_directory) {
// shouldn't happen, but just in case, don't let it delete actual cache directory
continue;
} elseif (@rmdir($empty_dir)) {
$totalpurgeddirs++;
} else {
$this->DebugMessage('failed to rmdir('.$empty_dir.')', __FILE__, __LINE__);
}
}
$this->DebugMessage('purged '.$totalpurgeddirs.' empty directories', __FILE__, __LINE__);
}
return true;
}
//////////////////////////////////////////////////////////////////////
// private: re-initializator (call between rendering multiple images with one object)
public function resetObject() {
$class_vars = get_class_vars(get_class($this));
foreach ($class_vars as $key => $value) {
// do not clobber debug or config info
if (!preg_match('#^(config_|debug|fatalerror)#i', $key)) {
$this->$key = $value;
}
}
$this->phpThumb(); // re-initialize some class variables
return true;
}
//////////////////////////////////////////////////////////////////////
public function ResolveSource() {
if (is_resource($this->gdimg_source) || (is_object($this->gdimg_source) && $this->gdimg_source instanceOf \GdImage)) {
$this->DebugMessage('ResolveSource() exiting because is_resource($this->gdimg_source)', __FILE__, __LINE__);
return true;
}
if ($this->rawImageData) {
$this->sourceFilename = null;
$this->DebugMessage('ResolveSource() exiting because $this->rawImageData is set ('.number_format(strlen($this->rawImageData)).' bytes)', __FILE__, __LINE__);
return true;
}
if ($this->sourceFilename) {
$this->sourceFilename = $this->ResolveFilenameToAbsolute($this->sourceFilename);
$this->DebugMessage('$this->sourceFilename set to "'.$this->sourceFilename.'"', __FILE__, __LINE__);
} elseif ($this->src) {
$this->sourceFilename = $this->ResolveFilenameToAbsolute($this->src);
$this->DebugMessage('$this->sourceFilename set to "'.$this->sourceFilename.'" from $this->src ('.$this->src.')', __FILE__, __LINE__);
} else {
return $this->ErrorImage('$this->sourceFilename and $this->src are both empty');
}
if ($this->iswindows && ((substr($this->sourceFilename, 0, 2) == '//') || (substr($this->sourceFilename, 0, 2) == '\\\\'))) {
// Windows \\share\filename.ext
} elseif (preg_match('#^[a-z0-9]+://#i', $this->sourceFilename, $protocol_matches)) {
if (preg_match('#^(f|ht)tps?\://#i', $this->sourceFilename)) {
// URL
if ($this->config_http_user_agent) {