-
Notifications
You must be signed in to change notification settings - Fork 1
/
timthumb.php
761 lines (555 loc) · 18.2 KB
/
timthumb.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
<?php
/**
* TimThumb script created by Tim McDaniels and Darren Hoyt with tweaks by Ben Gillbanks
* http://code.google.com/p/timthumb/
*
* GNU General Public License, version 2
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Examples and documentation available on the project homepage
* http://www.binarymoon.co.uk/projects/timthumb/
*
*/
define ('CACHE_SIZE', 250); // number of files to store before clearing cache
define ('CACHE_CLEAR', 5); // maximum number of files to delete on each cache clear
define ('CACHE_USE', FALSE); // use the cache files? (mostly for testing)
define ('VERSION', '1.16'); // version number (to force a cache refresh)
define ('DIRECTORY_CACHE', '../../../cache'); // cache directory
define ('DIRECTORY_TEMP', '../../../temp'); // temp directory
define ('MAX_WIDTH', 1000); // maximum image width
define ('MAX_HEIGHT', 1000); // maximum image height
// external domains that are allowed to be displayed on your website
$allowedSites = array (
'flickr.com',
'picasa.com',
'blogger.com',
'wordpress.com',
'img.youtube.com',
'hmu030146.chinaw3.com',
'www.google.com',
);
// STOP MODIFYING HERE!
// --------------------
// check to see if GD function exist
if (!function_exists('imagecreatetruecolor')) {
display_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),
);
}
// sort out image source
$src = get_request ('src', '');
if ($src == '' || strlen ($src) <= 3) {
display_error ('no image specified');
}
// clean params before use
$src = clean_source ($src);
// last modified time (for caching)
$lastModified = filemtime ($src);
// get standard input properties
$new_width = preg_replace ("/[^0-9]+/", '', get_request('w', 0));
$new_height = preg_replace ("/[^0-9]+/", '', get_request('h', 0));
$zoom_crop = preg_replace ("/[^0-9]+/", '', get_request('zc', 1));
$quality = preg_replace ("/[^0-9]+/", '', get_request('q', 90));
$align = get_request ('a', 'c');
$filters = get_request ('f', '');
$sharpen = get_request ('s', 0);
// set default width and height if neither are set already
if ($new_width == 0 && $new_height == 0) {
$new_width = 100;
$new_height = 100;
}
// ensure size limits can not be abused
if ($new_width > MAX_WIDTH) {
$new_width = MAX_WIDTH;
}
if ($new_height > MAX_HEIGHT) {
$new_height = MAX_HEIGHT;
}
// get mime type of src
$mime_type = mime_type ($src);
// check to see if this image is in the cache already
check_cache ($mime_type);
// if not in cache then clear some space and generate a new file
clean_cache();
// set memory limit to be able to have enough space to resize larger images
ini_set ('memory_limit', '50M');
if (strlen ($src) && file_exists ($src)) {
// open the existing image
$image = open_image ($mime_type, $src);
if ($image === false) {
display_error ('Unable to open image : ' . $src);
}
// Get original width and height
$width = imagesx ($image);
$height = imagesy ($image);
// generate new w/h if not provided
if ($new_width && !$new_height) {
$new_height = $height * ($new_width / $width);
} elseif ($new_height && !$new_width) {
$new_width = $width * ($new_height / $height);
} elseif (!$new_width && !$new_height) {
$new_width = $width;
$new_height = $height;
}
// create a new true color image
$canvas = imagecreatetruecolor ($new_width, $new_height);
imagealphablending ($canvas, false);
// Create a new transparent color for image
$color = imagecolorallocatealpha ($canvas, 0, 0, 0, 127);
// Completely fill the background of the new image with allocated color.
imagefill ($canvas, 0, 0, $color);
// Restore transparency blending
imagesavealpha ($canvas, true);
if ($zoom_crop) {
$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;
$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;
// calculate x or y coordinate and width or height of source
if ($cmp_x > $cmp_y) {
$src_w = round (($width / $cmp_x * $cmp_y));
$src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
} elseif ($cmp_y > $cmp_x) {
$src_h = round (($height / $cmp_y * $cmp_x));
$src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
}
// positional cropping!
switch ($align) {
case 't':
case 'tl':
case 'lr':
case 'tr':
case 'rt':
$src_y = 0;
break;
case 'b':
case 'bl':
case 'lb':
case 'br':
case 'rb':
$src_y = $height - $src_h;
break;
case 'l':
case 'tl':
case 'lt':
case 'bl':
case 'lb':
$src_x = 0;
break;
case 'r':
case 'tr':
case 'rt':
case 'br':
case 'rb':
$src_x = $width - $new_width;
$src_x = $width - $src_w;
break;
default:
break;
}
imagecopyresampled ($canvas, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
} else {
// copy and resize part of an image with resampling
imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
}
if ($filters != '' && function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
// apply filters to image
$filterList = explode ('|', $filters);
foreach ($filterList as $fl) {
$filterSettings = explode (',', $fl);
if (isset ($imageFilters[$filterSettings[0]])) {
for ($i = 0; $i < 4; $i ++) {
if (!isset ($filterSettings[$i])) {
$filterSettings[$i] = null;
} else {
$filterSettings[$i] = (int) $filterSettings[$i];
}
}
switch ($imageFilters[$filterSettings[0]][1]) {
case 1:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
break;
case 2:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
break;
case 3:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
break;
case 4:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3], $filterSettings[4]);
break;
default:
imagefilter ($canvas, $imageFilters[$filterSettings[0]][0]);
break;
}
}
}
}
if ($sharpen > 0 && function_exists ('imageconvolution')) {
$sharpenMatrix = array (
array (-1,-1,-1),
array (-1,16,-1),
array (-1,-1,-1),
);
$divisor = 8;
$offset = 0;
imageconvolution ($canvas, $sharpenMatrix, $divisor, $offset);
}
// output image to browser based on mime type
show_image ($mime_type, $canvas);
// remove image from memory
imagedestroy ($canvas);
} else {
if (strlen ($src)) {
display_error ('image ' . $src . ' not found');
} else {
display_error ('no source specified');
}
}
/**
*
* @global <type> $quality
* @param <type> $mime_type
* @param <type> $image_resized
*/
function show_image ($mime_type, $image_resized) {
global $quality;
// check to see if we can write to the cache directory
$is_writable = 0;
$cache_file = get_cache_file ($mime_type);
if (touch ($cache_file)) {
// give 666 permissions so that the developer
// can overwrite web server user
chmod ($cache_file, 0666);
$is_writable = 1;
} else {
$cache_file = NULL;
header ('Content-type: ' . $mime_type);
}
if (stristr ($mime_type, 'jpeg')) {
imagejpeg ($image_resized, $cache_file, $quality);
} else {
imagepng ($image_resized, $cache_file, floor ($quality * 0.09));
}
if ($is_writable) {
show_cache_file ($mime_type);
}
}
/**
*
* @param <type> $property
* @param <type> $default
* @return <type>
*/
function get_request ($property, $default = 0) {
if (isset($_GET[$property])) {
return $_GET[$property];
} else {
return $default;
}
}
/**
*
* @param <type> $mime_type
* @param <type> $src
* @return <type>
*/
function open_image ($mime_type, $src) {
$mime_type = strtolower ($mime_type);
if (stristr ($mime_type, 'gif')) {
$image = imagecreatefromgif($src);
} elseif (stristr ($mime_type, 'jpeg')) {
$image = imagecreatefromjpeg($src);
} elseif (stristr ($mime_type, 'png')) {
$image = imagecreatefrompng($src);
}
return $image;
}
/**
* clean out old files from the cache
* you can change the number of files to store and to delete per loop in the defines at the top of the code
*
* @return <type>
*/
function clean_cache() {
// add an escape
// Reduces the amount of cache clearing to save some processor speed
if (rand (1, 100) > 10) {
return true;
}
$files = glob (DIRECTORY_CACHE . '/*', GLOB_BRACE);
if (count($files) > CACHE_SIZE) {
$yesterday = time () - (24 * 60 * 60);
usort ($files, 'filemtime_compare');
$i = 0;
foreach ($files as $file) {
$i ++;
if ($i >= CACHE_CLEAR) {
return;
}
if (@filemtime ($file) > $yesterday) {
return;
}
if (file_exists ($file)) {
unlink ($file);
}
}
}
}
/**
* compare the file time of two files
*
* @param <type> $a
* @param <type> $b
* @return <type>
*/
function filemtime_compare($a, $b) {
$break = explode ('/', $_SERVER['SCRIPT_FILENAME']);
$filename = $break[count($break) - 1];
$filepath = str_replace ($filename, '', $_SERVER['SCRIPT_FILENAME']);
$file_a = realpath ($filepath . $a);
$file_b = realpath ($filepath . $b);
return filemtime ($file_a) - filemtime ($file_b);
}
/**
* determine the file mime type
*
* @param <type> $file
* @return <type>
*/
function mime_type ($file) {
$file_infos = getimagesize ($file);
$mime_type = $file_infos['mime'];
// use mime_type to determine mime type
if (!preg_match ("/jpg|jpeg|gif|png/i", $mime_type)) {
display_error ('Invalid src mime type: ' . $mime_type);
}
return $mime_type;
}
/**
*
* @param <type> $mime_type
*/
function check_cache ($mime_type) {
if (CACHE_USE) {
// make sure cache dir exists
if (!file_exists (DIRECTORY_CACHE)) {
// give 777 permissions so that developer can overwrite
// files created by web server user
mkdir (DIRECTORY_CACHE);
chmod (DIRECTORY_CACHE, 0777);
}
show_cache_file ($mime_type);
}
}
/**
*
* @param <type> $mime_type
*/
function show_cache_file ($mime_type) {
$cache_file = get_cache_file ($mime_type);
if (file_exists ($cache_file)) {
// use browser cache if available to speed up page load
if (isset ($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
if (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) < strtotime('now')) {
header ('HTTP/1.1 304 Not Modified');
die();
}
}
clearstatcache ();
$fileSize = filesize ($cache_file);
// change the modified headers
$gmdate_expires = gmdate("D, d M Y H:i:s", time() + 315360000) . ' GMT';
$gmdate_modified = gmdate('D, d M Y H:i:s') . ' GMT';
// send content headers then display image
header ('Content-Type: ' . $mime_type);
header ('Accept-Ranges: bytes');
header ('Last-Modified: ' . $gmdate_modified);
header ('Content-Length: ' . $fileSize);
header ('Cache-Control: max-age=315360000, public');
header ('Expires: ' . $gmdate_expires);
if (!@readfile ($cache_file)) {
$content = file_get_contents ($cache_file);
if ($content != FALSE) {
echo $content;
} else {
display_error ('cache file could not be loaded');
}
}
// we've shown the image so stop processing
die();
}
}
/**
*
* @global <type> $lastModified
* @staticvar string $cache_file
* @param <type> $mime_type
* @return string
*/
function get_cache_file ($mime_type) {
global $lastModified;
static $cache_file;
$file_type = '.png';
if (stristr ($mime_type, 'jpeg')) {
$file_type = '.jpg';
}
if (!$cache_file) {
$cache_file = DIRECTORY_CACHE . '/' . md5 ($_SERVER ['QUERY_STRING'] . VERSION . $lastModified) . $file_type;
}
return $cache_file;
}
/**
*
* @global array $allowedSites
* @param string $src
* @return string
*/
function check_external ($src) {
global $allowedSites;
if (preg_match ('/http:\/\//', $src) == true) {
$url_info = parse_url ($src);
$isAllowedSite = false;
foreach ($allowedSites as $site) {
$site = '/' . addslashes ($site) . '/';
if (preg_match ($site, $url_info['host']) == true) {
$isAllowedSite = true;
}
}
if ($isAllowedSite) {
$fileDetails = pathinfo ($src);
$ext = strtolower ($fileDetails['extension']);
$filename = md5 ($src);
$local_filepath = DIRECTORY_TEMP . '/' . $filename . '.' . $ext;
if (!file_exists ($local_filepath)) {
if (function_exists ('curl_init')) {
$fh = fopen ($local_filepath, 'w');
$ch = curl_init ($src);
curl_setopt ($ch, CURLOPT_URL, $src);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
curl_setopt ($ch, CURLOPT_FILE, $fh);
if (curl_exec ($ch) === FALSE) {
if (file_exists ($local_filepath)) {
unlink ($local_filepath);
}
display_error ('error reading file ' . $src . ' from remote host: ' . curl_error($ch));
}
curl_close ($ch);
fclose ($fh);
} else {
if (!$img = file_get_contents($src)) {
display_error('remote file for ' . $src . ' can not be accessed. It is likely that the file permissions are restricted');
}
if (file_put_contents ($local_filepath, $img) == FALSE) {
display_error ('error writing temporary file');
}
}
if (!file_exists($local_filepath)) {
display_error('local file for ' . $src . ' can not be created');
}
}
$src = $local_filepath;
} else {
display_error('remote host "' . $url_info['host'] . '" not allowed');
}
}
return $src;
}
/**
* tidy up the image source url
*
* @param <type> $src
* @return string
*/
function clean_source ($src) {
$host = str_replace ('www.', '', $_SERVER['HTTP_HOST']);
$regex = "/^((ht|f)tp(s|):\/\/)(www\.|)" . $host . "/i";
$src = preg_replace ($regex, '', $src);
$src = strip_tags ($src);
$src = check_external ($src);
// remove slash from start of string
if (strpos ($src, '/') === 0) {
$src = substr ($src, -(strlen ($src) - 1));
}
// don't allow users the ability to use '../'
// in order to gain access to files below document root
$src = preg_replace ("/\.\.+\//", "", $src);
// get path to image on file system
$src = get_document_root ($src) . '/' . $src;
return $src;
}
/**
*
* @param <type> $src
* @return string
*/
function get_document_root ($src) {
// check for unix servers
if (file_exists ($_SERVER['DOCUMENT_ROOT'] . '/' . $src)) {
return $_SERVER['DOCUMENT_ROOT'];
}
// check from script filename (to get all directories to timthumb location)
$parts = array_diff (explode ('/', $_SERVER['SCRIPT_FILENAME']), explode('/', $_SERVER['DOCUMENT_ROOT']));
$path = $_SERVER['DOCUMENT_ROOT'];
foreach ($parts as $part) {
$path .= '/' . $part;
if (file_exists($path . '/' . $src)) {
return $path;
}
}
// the relative paths below are useful if timthumb is moved outside of document root
// specifically if installed in wordpress themes like mimbo pro:
// /wp-content/themes/mimbopro/scripts/timthumb.php
$paths = array (
".",
"..",
"../..",
"../../..",
"../../../..",
"../../../../.."
);
foreach ($paths as $path) {
if (file_exists($path . '/' . $src)) {
return $path;
}
}
// special check for microsoft servers
if (!isset ($_SERVER['DOCUMENT_ROOT'])) {
$path = str_replace ("/", "\\", $_SERVER['ORIG_PATH_INFO']);
$path = str_replace ($path, "", $_SERVER['SCRIPT_FILENAME']);
if (file_exists ($path . '/' . $src)) {
return $path;
}
}
display_error ('file not found ' . $src, ENT_QUOTES);
}
/**
* generic error message
*
* @param <type> $errorString
*/
function display_error ($errorString = '') {
header ('HTTP/1.1 400 Bad Request');
echo '<pre>' . htmlentities($errorString);
echo '<br />Query String : ' . htmlentities($_SERVER['QUERY_STRING']);
echo '<br />TimThumb version : ' . VERSION . '</pre>';
die();
}
?>