forked from mindsharelabs/mthumb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmthumb.php
1752 lines (1552 loc) · 63 KB
/
mthumb.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
/*
mThumb
URI: https://github.com/mindsharestudios/mthumb
Description: A secure PHP image resize script.
Version: 3.0.1
Author: Mindshare Studios, Inc.
Author URI: https://mind.sh/are/
License: GNU General Public License
License URI: LICENSE
*/
/**
*
* @created 12/21/13 2:02 PM
* @author Mindshare Studios, Inc.
* @copyright Copyright (c) 2013-2015
* @link https://mindsharelabs.com/
*
* Copyright 2013-2016 Mindshare Studios, Inc. (https://mind.sh/are/)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Credits: based on TimThumb by Ben Gillbanks, Mark Maunder, Tim McDaniels and Darren Hoyt
*
*/
/*
* --- mThumb CONFIGURATION ---
* To edit the configs it is best to create a file called mthumb-config.php
* and define variables you want to customize in there. It will automatically be
* loaded by mthumb. This will save you having to re-edit these variables
* every time you download a new version.
*/
namespace Buttjer;
/**
* Version of this script *
*/
define('VERSION', '3.0.1');
// -------------- STOP EDITING CONFIGURATION HERE --------------
if (!class_exists('mthumb')) : /**
* Class mthumb
*/ {
class mthumb
{
/**
* @var mixed|string
*/
protected $src = "";
/**
* @var bool
*/
protected $is404 = false;
/**
* @var string
*/
protected $docRoot = "";
/**
* @var bool
*/
protected $lastURLError = false;
/**
* @var bool|string
*/
protected $localImage = "";
/**
* @var int
*/
protected $localImageMTime = 0;
/**
* @var bool|mixed
*/
protected $url = false;
/**
* @var mixed|string
*/
protected $myHost = "";
/**
* @var bool
*/
protected $isURL = false;
/**
* @var string
*/
protected $cachefile = '';
/**
* @var array
*/
protected $errors = array();
/**
* @var array
*/
protected $toDeletes = array();
/**
* @var string
*/
protected $cacheDirectory = '';
/**
* @var int|mixed
*/
protected $startTime = 0;
/**
* @var int
*/
protected $lastBenchTime = 0;
/**
* @var bool
*/
protected $cropTop = false;
/**
* @var string
*/
protected $salt = "";
/**
* Generally if mthumb.php is modified (upgraded) then the salt changes and all cache files are recreated. This is a backup mechanism to force regen.
*
* @var int
*/
protected $fileCacheVersion = 1;
/**
*
* Designed to have three letter mime type, space, question mark and greater than symbol appended. 6 bytes total.
*
* @var string
*/
protected $filePrependSecurityBlock = "<?php die('Execution denied!'); //";
/**
* @var int
*/
protected static $curlDataWritten = 0;
/**
* @var bool
*/
protected static $curlFH = false;
/**
*
*/
public static function start()
{
$mthumb = new mthumb();
$mthumb->handleErrors();
if ($mthumb->tryBrowserCache()) {
exit(0);
}
$mthumb->handleErrors();
if (FILE_CACHE_ENABLED && $mthumb->tryServerCache()) {
exit(0);
}
$mthumb->handleErrors();
$mthumb->run();
$mthumb->handleErrors();
exit(0);
}
/**
*
*/
public function __construct()
{
//Load a config file if it exists. Otherwise, use the values below
if (file_exists(dirname(__FILE__) . '/mthumb-config.php')) {
require_once('mthumb-config.php');
}
if (!defined('DEBUG_ON')) {
/**
* Enable debug logging to web server error log (STDERR)
*/
define('DEBUG_ON', false);
}
if (!defined('DEBUG_LEVEL')) {
/**
* Debug level 1 is less noisy and 3 is the most noisy
*
*/
define('DEBUG_LEVEL', 1);
}
if (!defined('DISPLAY_ERROR_MESSAGES')) {
/**
* Display error messages. Set to false to turn off errors (good for production websites)
*/
define('DISPLAY_ERROR_MESSAGES', true);
}
if (!defined('ALLOW_EXTERNAL')) {
/**
* Allow image fetching from external websites. Will check against ALLOWED_SITES always. *
*/
define('ALLOW_EXTERNAL', false);
}
if (!isset($ALLOWED_SITES)) {
/**
* If ALLOW_EXTERNAL is true then external images will only be fetched from these domains and their subdomains.
*/
$ALLOWED_SITES = array(
'flickr.com',
'staticflickr.com',
'img.youtube.com',
'upload.wikimedia.org',
'imgur.com',
'imageshack.us',
'tinypic.com',
);
}
if (!defined('FILE_CACHE_ENABLED')) {
/**
* Should we store resized/modified images on disk to speed things up?
*/
define('FILE_CACHE_ENABLED', true);
}
if (!defined('DAY_IN_SECONDS')) {
define('DAY_IN_SECONDS', 24 * 60 * 60);
}
if (!defined('FILE_CACHE_TIME_BETWEEN_CLEANS')) {
/**
* How often the cache is cleaned
*/
define('FILE_CACHE_TIME_BETWEEN_CLEANS', DAY_IN_SECONDS * 30);
}
if (!defined('FILE_CACHE_MAX_FILE_AGE')) {
/**
* How old does a file have to be to be deleted from the cache
*/
define('FILE_CACHE_MAX_FILE_AGE', DAY_IN_SECONDS * 60);
}
if (!defined('FILE_CACHE_SUFFIX')) {
/**
* What to put at the end of all files in the cache directory so we can identify them
*/
define('FILE_CACHE_SUFFIX', '.txt');
}
if (!defined('FILE_CACHE_PREFIX')) {
/**
* What to put at the beg of all files in the cache directory so we can identify them
*/
define('FILE_CACHE_PREFIX', 'mthumb');
}
if (!defined('FILE_CACHE_DIRECTORY')) {
/**
* Directory where images are cached. Left blank it will use the system temporary directory (which is better for security)
*
*/
//define ('FILE_CACHE_DIRECTORY', './cache');
define('FILE_CACHE_DIRECTORY', false); // @todo test on more deployments
}
if (!defined('TEN_MB_IN_BTYES')) {
define('TEN_MB_IN_BTYES', 10485760);
}
//
if (!defined('MAX_FILE_SIZE')) {
/**
* This is the max internal or external file size that we'll process.
*/
define('MAX_FILE_SIZE', TEN_MB_IN_BTYES * 2);
}
if (!defined('CURL_TIMEOUT')) {
/**
* Timeout duration for Curl. This only applies if you have Curl installed and aren't using PHP's default URL fetching mechanism.
*
*/
define('CURL_TIMEOUT', 20);
}
if (!defined('WAIT_BETWEEN_FETCH_ERRORS')) {
/**
* Time to wait between errors fetching remote file
*/
define('WAIT_BETWEEN_FETCH_ERRORS', 3600);
}
if (!defined('BROWSER_CACHE_MAX_AGE')) {
/**
* Time to cache in the browser
*
*/
define('BROWSER_CACHE_MAX_AGE', DAY_IN_SECONDS * 30);
}
if (!defined('BROWSER_CACHE_DISABLE')) {
/**
* Use for testing if you want to disable all browser caching
*/
define('BROWSER_CACHE_DISABLE', false);
}
if (!defined('MAX_WIDTH')) {
define('MAX_WIDTH', 3200);
}
if (!defined('MAX_HEIGHT')) {
define('MAX_HEIGHT', 3200);
}
if (!defined('PNG_IS_TRANSPARENT')) {
/**
* Define if a png image should have a transparent background color. Use False value if you want to display a custom coloured canvas_colour
*
*/
define('PNG_IS_TRANSPARENT', true);
}
if (!defined('DEFAULT_Q')) {
/**
* Default image quality. Allows override in mthumb-config.php
*
*/
define('DEFAULT_Q', 85);
}
if (!defined('DEFAULT_ZC')) {
/**
* Default zoom/crop setting. Allows override in mthumb-config.php
*/
define('DEFAULT_ZC', 1);
}
if (!defined('DEFAULT_F')) {
/**
* Default image filters. Allows override in mthumb-config.php
*/
define('DEFAULT_F', '');
}
//
if (!defined('DEFAULT_S')) {
/**
* Default sharpen value. Allows override in mthumb-config.php
*/
define('DEFAULT_S', 0);
}
if (!defined('DEFAULT_CC')) {
/**
* Default canvas colour. Allows override in mthumb-config.php
*/
define('DEFAULT_CC', 'ffffff');
}
if (!defined('DEFAULT_WIDTH')) {
/**
* Default thumbnail width. Allows override in mthumb-config.php
*/
define('DEFAULT_WIDTH', 125);
}
if (!defined('DEFAULT_HEIGHT')) {
/**
* Default thumbnail height. Allows override in mthumb-config.php
*/
define('DEFAULT_HEIGHT', 125);
}
/**
* Additional Parameters:
* LOCAL_FILE_BASE_DIRECTORY = Override the DOCUMENT_ROOT. This is best used in mthumb-config.php
*/
if (!defined('OPTIPNG_ENABLED')) {
/**
* Image compression is enabled if either of these point to valid paths. They only work for PNGs. GIFs and JPEGs are not affected.
*/
define('OPTIPNG_ENABLED', true);
}
if (!defined('OPTIPNG_PATH')) {
/**
* This will run first because it gives better compression than pngcrush.
*
*/
define('OPTIPNG_PATH', '/usr/bin/optipng');
}
if (!defined('PNGCRUSH_ENABLED')) {
define('PNGCRUSH_ENABLED', true);
}
if (!defined('PNGCRUSH_PATH')) {
/**
* This will only run if OPTIPNG_PATH is not set or is not valid
*/
define('PNGCRUSH_PATH', '/usr/bin/pngcrush');
}
global $ALLOWED_SITES;
$this->startTime = microtime(true);
date_default_timezone_set('UTC');
if (isset($_SERVER['REQUEST_URI'])) {
$this->debug(1, "Starting new request from " . $this->getIP() . " to " . $_SERVER['REQUEST_URI']);
}
$this->calcDocRoot();
//On windows systems I'm assuming fileinode returns an empty string or a number that doesn't change. Check this.
$this->salt = @filemtime(__FILE__) . '-' . @fileinode(__FILE__);
$this->debug(3, "Salt is: " . $this->salt);
if (FILE_CACHE_DIRECTORY) {
if (!is_dir(FILE_CACHE_DIRECTORY)) {
@mkdir(FILE_CACHE_DIRECTORY);
if (!is_dir(FILE_CACHE_DIRECTORY)) {
$this->error("Could not create the file cache directory.");
return false;
}
}
$this->cacheDirectory = FILE_CACHE_DIRECTORY;
if (!touch($this->cacheDirectory . '/index.html')) {
$this->error("Could not create the index.html file - to fix this create an empty file named index.html file in the cache directory.");
}
}
else {
$this->cacheDirectory = sys_get_temp_dir();
}
// Clean the cache before we do anything because we don't want the first visitor after FILE_CACHE_TIME_BETWEEN_CLEANS expires to get a stale image.
$this->cleanCache();
if (isset($_SERVER['HTTP_HOST'])) {
$this->myHost = preg_replace('/^www\./i', '', $_SERVER['HTTP_HOST']);
}
// start mindshare fix for tilde's, check if tilde is found in src
if (strstr($this->param('src'), '~')) {
$url_parts = explode('/', $this->param('src'));
foreach ($url_parts as $url_part) {
//do not include any part with a ~ when building new url
if (!strstr($url_part, '~')) {
$new_dev_url .= $url_part . '/';
}
}
//remove trailing slash
$new_dev_url = substr($new_dev_url, 0, -1);
$this->src = $new_dev_url;
}
else {
$this->src = $this->param('src');
}
// end mindshare fix for tilde's
$this->url = parse_url($this->src);
$this->src = preg_replace('/https?:\/\/(?:www\.)?' . $this->myHost . '/i', '', $this->src);
if (strlen($this->src) <= 3) {
$this->error("No image specified");
return false;
}
// Always block external sites from using this script
if (array_key_exists('HTTP_REFERER',
$_SERVER) && (!preg_match('/^https?:\/\/(?:www\.)?' . $this->myHost . '(?:$|\/)/i',
$_SERVER['HTTP_REFERER']))
) {
// base64 encoded red image that says 'no hotlinkers' nothing to worry about! :)
$imgData = base64_decode("R0lGODlhUAAMAIAAAP8AAP///yH5BAAHAP8ALAAAAABQAAwAAAJpjI+py+0Po5y0OgAMjjv01YUZ\nOGplhWXfNa6JCLnWkXplrcBmW+spbwvaVr/cDyg7IoFC2KbYVC2NQ5MQ4ZNao9Ynzjl9ScNYpneb\nDULB3RP6JuPuaGfuuV4fumf8PuvqFyhYtjdoeFgAADs=");
header('Content-Type: image/gif');
header('Content-Length: ' . strlen($imgData));
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header("Pragma: no-cache");
header('Expires: ' . gmdate('D, d M Y H:i:s', time()));
echo $imgData;
return false;
exit(0);
}
if (preg_match('/^https?:\/\/[^\/]+/i', $this->src)) {
$this->debug(2, "Is a request for an external URL: " . $this->src);
$this->isURL = true;
}
else {
$this->debug(2, "Is a request for an internal file: " . $this->src);
}
if ($this->isURL && (!ALLOW_EXTERNAL)) {
$this->error("You are not allowed to fetch images from an external website.");
return false;
}
if ($this->isURL) {
$this->debug(2, "Fetching only from selected external sites is enabled.");
$allowed = false;
foreach ($ALLOWED_SITES as $site) {
if ((strtolower(substr($this->url['host'],
-strlen($site) - 1)) === strtolower(".$site")) || (strtolower($this->url['host']) === strtolower($site))
) {
$this->debug(3, "URL hostname {$this->url['host']} matches $site so allowing.");
$allowed = true;
}
}
if (!$allowed) {
return $this->error("You may not fetch images from that site. To enable this site in mthumb, you can either add it to \$ALLOWED_SITES and set ALLOW_EXTERNAL=true.");
}
}
$cachePrefix = ($this->isURL ? '_ext_' : '_int_');
if ($this->isURL) {
$arr = explode('&', $_SERVER ['QUERY_STRING']);
asort($arr);
$this->cachefile = $this->cacheDirectory . '/' . FILE_CACHE_PREFIX . $cachePrefix . md5($this->salt . implode('',
$arr) . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
}
else {
$this->localImage = $this->getLocalImagePath($this->src);
if (!$this->localImage) {
$this->debug(1, "Could not find the local image: {$this->localImage}");
$this->error("Could not find the internal image you specified.");
$this->set404();
return false;
}
$this->debug(1, "Local image path is {$this->localImage}");
$this->localImageMTime = @filemtime($this->localImage);
//We include the mtime of the local file in case in changes on disk.
$this->cachefile = $this->cacheDirectory . '/' . FILE_CACHE_PREFIX . $cachePrefix . md5($this->salt . $this->localImageMTime . $_SERVER ['QUERY_STRING'] . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
}
$this->debug(2, "Cache file is: " . $this->cachefile);
return true;
}
/**
*
*/
public function __destruct()
{
foreach ($this->toDeletes as $del) {
$this->debug(2, "Deleting temp file $del");
@unlink($del);
}
}
/**
* @return bool
*/
public function run()
{
if ($this->isURL) {
if (!ALLOW_EXTERNAL) {
$this->debug(1,
"Got a request for an external image but ALLOW_EXTERNAL is disabled so returning error msg.");
$this->error("You are not allowed to fetch images from an external website.");
return false;
}
$this->debug(3, "Got request for external image. Starting serveExternalImage.");
$this->serveExternalImage();
}
else {
$this->debug(3, "Got request for internal image. Starting serveInternalImage");
$this->serveInternalImage();
}
return true;
}
/**
* @return bool
*/
protected function handleErrors()
{
if ($this->haveErrors()) {
$this->serveErrors();
exit(0);
}
return false;
}
/**
* @return bool
*/
protected function tryBrowserCache()
{
if (BROWSER_CACHE_DISABLE) {
$this->debug(3, "Browser caching is disabled");
return false;
}
if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
$this->debug(3, "Got a conditional get");
$mtime = false;
//We've already checked if the real file exists in the constructor
if (!is_file($this->cachefile)) {
//If we don't have something cached, regenerate the cached image.
return false;
}
if ($this->localImageMTime) {
$mtime = $this->localImageMTime;
$this->debug(3, "Local real file's modification time is $mtime");
}
else {
if (is_file($this->cachefile)) { //If it's not a local request then use the mtime of the cached file to determine the 304
$mtime = @filemtime($this->cachefile);
$this->debug(3, "Cached file's modification time is $mtime");
}
}
if (!$mtime) {
return false;
}
$iftime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
$this->debug(3, "The conditional get's if-modified-since unixtime is $iftime");
if ($iftime < 1) {
$this->debug(3, "Got an invalid conditional get modified since time. Returning false.");
return false;
}
// Real file or cache file has been modified since last request, so force refetch.
if ($iftime < $mtime) {
$this->debug(3, "File has been modified since last fetch.");
return false;
}
else { //Otherwise serve a 304
$this->debug(3, "File has not been modified since last get, so serving a 304.");
header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
$this->debug(1, "Returning 304 not modified");
return true;
}
}
return false;
}
/**
* @return bool
*/
protected function tryServerCache()
{
$this->debug(3, "Trying server cache");
if (file_exists($this->cachefile)) {
$this->debug(3, "Cachefile {$this->cachefile} exists");
if ($this->isURL) {
$this->debug(3,
"This is an external request, so checking if the cachefile is empty which means the request failed previously.");
if (filesize($this->cachefile) < 1) {
$this->debug(3,
"Found an empty cachefile indicating a failed earlier request. Checking how old it is.");
//Fetching error occured previously
if (time() - @filemtime($this->cachefile) > WAIT_BETWEEN_FETCH_ERRORS) {
$this->debug(3,
"File is older than " . WAIT_BETWEEN_FETCH_ERRORS . " seconds. Deleting and returning false so app can try and load file.");
@unlink($this->cachefile);
return false; //to indicate we didn't serve from cache and app should try and load
}
else {
$this->debug(3,
"Empty cachefile is still fresh so returning message saying we had an error fetching this image from remote host.");
$this->set404();
$this->error("An error occured fetching image.");
return false;
}
}
}
else {
$this->debug(3, "Trying to serve cachefile {$this->cachefile}");
}
if ($this->serveCacheFile()) {
$this->debug(3, "Succesfully served cachefile {$this->cachefile}");
return true;
}
else {
$this->debug(3, "Failed to serve cachefile {$this->cachefile} - Deleting it from cache.");
//Image serving failed. We can't retry at this point, but lets remove it from cache so the next request recreates it
@unlink($this->cachefile);
return true;
}
}
}
/**
* @param $err
*
* @return bool
*/
protected function error($err)
{
$this->debug(3, "Adding error message: $err");
$this->errors[] = $err;
return false;
}
/**
* @return bool
*/
protected function haveErrors()
{
if (sizeof($this->errors) > 0) {
return true;
}
return false;
}
/**
*
*/
protected function serveErrors()
{
if (!DISPLAY_ERROR_MESSAGES) {
return;
}
header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
$html = '<ul>';
foreach ($this->errors as $err) {
$html .= '<li>' . htmlentities($err) . '</li>';
}
$html .= '</ul>';
echo '<h1>An error has occured</h1>The following error(s) occured:<br />' . $html . '<br />';
echo '<br />Query String: ' . htmlentities($_SERVER['QUERY_STRING'], ENT_QUOTES);
}
/**
* @return bool
*/
protected function serveInternalImage()
{
$this->debug(3, "Local image path is $this->localImage");
if (!$this->localImage) {
$this->sanityFail("localImage not set after verifying it earlier in the code.");
return false;
}
$fileSize = filesize($this->localImage);
if ($fileSize > MAX_FILE_SIZE) {
$this->error("The file you specified is greater than the maximum allowed file size.");
return false;
}
if ($fileSize <= 0) {
$this->error("The file you specified is <= 0 bytes.");
return false;
}
$this->debug(3, "Calling processImageAndWriteToCache() for local image.");
if ($this->processImageAndWriteToCache($this->localImage)) {
$this->serveCacheFile();
return true;
}
else {
return false;
}
}
/**
* @return bool
*/
protected function serveExternalImage()
{
if (!preg_match('/^https?:\/\/[a-zA-Z0-9\-\.]+/i', $this->src)) {
$this->error("Invalid URL supplied.");
return false;
}
$tempfile = tempnam($this->cacheDirectory, 'mthumb');
$this->debug(3, "Fetching external image into temporary file $tempfile");
$this->toDelete($tempfile);
// fetch file here
if (!$this->getURL($this->src, $tempfile)) {
@unlink($this->cachefile);
touch($this->cachefile);
$this->debug(3, "Error fetching URL: " . $this->lastURLError);
$this->error("Error reading the URL you specified from remote host." . $this->lastURLError);
return false;
}
$mimeType = $this->getMimeType($tempfile);
if (!preg_match("/^image\/(?:jpg|jpeg|gif|png)$/i", $mimeType)) {
$this->debug(3, "Remote file has invalid mime type: $mimeType");
@unlink($this->cachefile);
touch($this->cachefile);
$this->error("The remote file is not a valid image. Mimetype = '" . $mimeType . "'" . $tempfile);
return false;
}
if ($this->processImageAndWriteToCache($tempfile)) {
$this->debug(3, "Image processed succesfully. Serving from cache");
return $this->serveCacheFile();
}
else {
return false;
}
}
/**
* @return bool
*/
protected function cleanCache()
{
if (FILE_CACHE_TIME_BETWEEN_CLEANS < 0) {
return;
}
$this->debug(3, "cleanCache() called");
$lastCleanFile = $this->cacheDirectory . '/mthumb_cacheLastCleanTime.touch';
// If the cache dir isn't writable, exit
if (!is_writable($lastCleanFile)) {
return;
}
//If this is a new mthumb installation we need to create the file
if (!is_file($lastCleanFile)) {
$this->debug(1, "File tracking last clean doesn't exist. Creating $lastCleanFile");
if (!touch($lastCleanFile)) {
$this->error("Could not create cache clean timestamp file.");
}
return;
}
if (@filemtime($lastCleanFile) < (time() - FILE_CACHE_TIME_BETWEEN_CLEANS)) { //Cache was last cleaned more than 1 day ago
$this->debug(1,
"Cache was last cleaned more than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago. Cleaning now.");
// Very slight race condition here, but worst case we'll have 2 or 3 servers cleaning the cache simultaneously once a day.
if (!touch($lastCleanFile)) {
$this->error("Could not create cache clean timestamp file.");
}
$files = glob($this->cacheDirectory . '/*' . FILE_CACHE_SUFFIX);
if ($files) {
$timeAgo = time() - FILE_CACHE_MAX_FILE_AGE;
foreach ($files as $file) {
if (@filemtime($file) < $timeAgo) {
$this->debug(3,
"Deleting cache file $file older than max age: " . FILE_CACHE_MAX_FILE_AGE . " seconds");
@unlink($file);
}
}
}
return true;
}
else {
$this->debug(3,
"Cache was cleaned less than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago so no cleaning needed.");
}
return false;
}
/**
* @param $localImage
*
* @return bool
*/
protected function processImageAndWriteToCache($localImage)
{
$sData = getimagesize($localImage);
$origType = $sData[2];
$mimeType = $sData['mime'];
$this->debug(3, "Mime type of image is $mimeType");
if (!preg_match('/^image\/(?:gif|jpg|jpeg|png)$/i', $mimeType)) {
return $this->error("The image being resized is not a valid gif, jpg or png.");
}
if (!function_exists('imagecreatetruecolor')) {
return $this->error('GD Library Error: imagecreatetruecolor does not exist - please contact your webhost and ask them to install the GD library');
}
if (function_exists('imagefilter') && defined('IMG_FILTER_NEGATE')) {
$imageFilters = array(
1 => array(IMG_FILTER_NEGATE, 0),
2 => array(IMG_FILTER_GRAYSCALE, 0),
3 => array(IMG_FILTER_BRIGHTNESS, 1),
4 => array(IMG_FILTER_CONTRAST, 1),
5 => array(IMG_FILTER_COLORIZE, 4),
6 => array(IMG_FILTER_EDGEDETECT, 0),
7 => array(IMG_FILTER_EMBOSS, 0),
8 => array(IMG_FILTER_GAUSSIAN_BLUR, 0),
9 => array(IMG_FILTER_SELECTIVE_BLUR, 0),
10 => array(IMG_FILTER_MEAN_REMOVAL, 0),
11 => array(IMG_FILTER_SMOOTH, 0),
);
}
// get standard input properties
$new_width = (int)abs($this->param('w', 0));
$new_height = (int)abs($this->param('h', 0));
$zoom_crop = (int)$this->param('zc', DEFAULT_ZC);
$quality = (int)abs($this->param('q', DEFAULT_Q));
$align = $this->cropTop ? 't' : $this->param('a', 'c');
$filters = $this->param('f', DEFAULT_F);
$sharpen = (bool)$this->param('s', DEFAULT_S);
$canvas_color = $this->param('cc', DEFAULT_CC);
$canvas_trans = (bool)$this->param('ct', '1');
// set default width and height if neither are set already
if ($new_width == 0 && $new_height == 0) {
$new_width = (int)DEFAULT_WIDTH;
$new_height = (int)DEFAULT_HEIGHT;
}
// ensure size limits can not be abused
$new_width = min($new_width, MAX_WIDTH);
$new_height = min($new_height, MAX_HEIGHT);
// open the existing image
$image = $this->openImage($mimeType, $localImage);
if ($image === false) {
return $this->error('Unable to open image.');
}
// Get original width and height
$width = imagesx($image);
$height = imagesy($image);
$origin_x = 0;
$origin_y = 0;
// generate new w/h if not provided
if ($new_width && !$new_height) {
$new_height = floor($height * ($new_width / $width));
}
else {
if ($new_height && !$new_width) {
$new_width = floor($width * ($new_height / $height));
}
}
// scale down and add borders
if ($zoom_crop == 3) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$new_width = $width * ($new_height / $height);
}
else {
$new_height = $final_height;
}
}
// create a new true color image
$canvas = imagecreatetruecolor($new_width, $new_height);
imagealphablending($canvas, false);
if (strlen($canvas_color) == 3) { //if is 3-char notation, edit string into 6-char notation
$canvas_color = str_repeat(substr($canvas_color, 0, 1), 2) . str_repeat(substr($canvas_color, 1, 1),
2) . str_repeat(substr($canvas_color, 2, 1), 2);
}
else {
if (strlen($canvas_color) != 6) {
$canvas_color = DEFAULT_CC; // on error return default canvas color
}
}
$canvas_color_R = hexdec(substr($canvas_color, 0, 2));
$canvas_color_G = hexdec(substr($canvas_color, 2, 2));
$canvas_color_B = hexdec(substr($canvas_color, 4, 2));
// Create a new transparent color for image
// If is a png and PNG_IS_TRANSPARENT is false then remove the alpha transparency
// (and if is set a canvas color show it in the background)
if (preg_match('/^image\/png$/i', $mimeType) && !PNG_IS_TRANSPARENT && $canvas_trans) {
$color = imagecolorallocatealpha($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
}
else {
$color = imagecolorallocatealpha($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 0);
}
// Completely fill the background of the new image with allocated color.
imagefill($canvas, 0, 0, $color);
// scale down and add borders
if ($zoom_crop == 2) {
$final_height = $height * ($new_width / $width);