-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththumb.php
5107 lines (3924 loc) · 138 KB
/
thumb.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
/**
* Resize and crop images on the fly, store generated images in a cache.
*
* This version is a all-in-one version of img.php, it is not dependant an any other file
* so you can simply copy it to any place you want it.
*
* @author Mikael Roos mos@dbwebb.se
* @example http://dbwebb.se/opensource/cimage
* @link /~https://github.com/mosbth/cimage
*
*/
/**
* Change configuration details in the array below or create a separate file
* where you store the configuration details.
*
* The configuration file should be named the same name as this file and then
* add '_config.php'. If this file is named 'img.php' then name the
* config file should be named 'img_config.php'.
*
* The settings below are only a few of the available ones. Check the file in
* webroot/img_config.php for a complete list of configuration options.
*/
$config = array(
'mode' => 'development', // 'production', 'development', 'strict'
'image_path' => __DIR__ . '/images/',
'cache_path' => __DIR__ . '/cache/',
//'alias_path' => __DIR__ . '/img/alias/',
//'remote_allow' => true,
//'password' => false, // "secret-password",
);
/**
* Get a image from a remote server using HTTP GET and If-Modified-Since.
*
*/
class CHttpGet
{
private $request = array();
private $response = array();
/**
* Constructor
*
*/
public function __construct()
{
$this->request['header'] = array();
}
/**
* Build an encoded url.
*
* @param string $baseUrl This is the original url which will be merged.
* @param string $merge Thse parts should be merged into the baseUrl,
* the format is as parse_url.
*
* @return string $url as the modified url.
*/
public function buildUrl($baseUrl, $merge)
{
$parts = parse_url($baseUrl);
$parts = array_merge($parts, $merge);
$url = $parts['scheme'];
$url .= "://";
$url .= $parts['host'];
$url .= isset($parts['port'])
? ":" . $parts['port']
: "" ;
$url .= $parts['path'];
return $url;
}
/**
* Set the url for the request.
*
* @param string $url
*
* @return $this
*/
public function setUrl($url)
{
$parts = parse_url($url);
$path = "";
if (isset($parts['path'])) {
$pathParts = explode('/', $parts['path']);
unset($pathParts[0]);
foreach ($pathParts as $value) {
$path .= "/" . rawurlencode($value);
}
}
$url = $this->buildUrl($url, array("path" => $path));
$this->request['url'] = $url;
return $this;
}
/**
* Set custom header field for the request.
*
* @param string $field
* @param string $value
*
* @return $this
*/
public function setHeader($field, $value)
{
$this->request['header'][] = "$field: $value";
return $this;
}
/**
* Set header fields for the request.
*
* @param string $field
* @param string $value
*
* @return $this
*/
public function parseHeader()
{
//$header = explode("\r\n", rtrim($this->response['headerRaw'], "\r\n"));
$rawHeaders = rtrim($this->response['headerRaw'], "\r\n");
# Handle multiple responses e.g. with redirections (proxies too)
$headerGroups = explode("\r\n\r\n", $rawHeaders);
# We're only interested in the last one
$header = explode("\r\n", end($headerGroups));
$output = array();
if ('HTTP' === substr($header[0], 0, 4)) {
list($output['version'], $output['status']) = explode(' ', $header[0]);
unset($header[0]);
}
foreach ($header as $entry) {
$pos = strpos($entry, ':');
$output[trim(substr($entry, 0, $pos))] = trim(substr($entry, $pos + 1));
}
$this->response['header'] = $output;
return $this;
}
/**
* Perform the request.
*
* @param boolean $debug set to true to dump headers.
*
* @throws Exception when curl fails to retrieve url.
*
* @return boolean
*/
public function doGet($debug = false)
{
$options = array(
CURLOPT_URL => $this->request['url'],
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => $this->request['header'],
CURLOPT_AUTOREFERER => true,
CURLOPT_RETURNTRANSFER => true,
CURLINFO_HEADER_OUT => $debug,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 5,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 2,
);
$ch = curl_init();
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
if (!$response) {
throw new Exception("Failed retrieving url, details follows: " . curl_error($ch));
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$this->response['headerRaw'] = substr($response, 0, $headerSize);
$this->response['body'] = substr($response, $headerSize);
$this->parseHeader();
if ($debug) {
$info = curl_getinfo($ch);
echo "Request header<br><pre>", var_dump($info['request_header']), "</pre>";
echo "Response header (raw)<br><pre>", var_dump($this->response['headerRaw']), "</pre>";
echo "Response header (parsed)<br><pre>", var_dump($this->response['header']), "</pre>";
}
curl_close($ch);
return true;
}
/**
* Get HTTP code of response.
*
* @return integer as HTTP status code or null if not available.
*/
public function getStatus()
{
return isset($this->response['header']['status'])
? (int) $this->response['header']['status']
: null;
}
/**
* Get file modification time of response.
*
* @return int as timestamp.
*/
public function getLastModified()
{
return isset($this->response['header']['Last-Modified'])
? strtotime($this->response['header']['Last-Modified'])
: null;
}
/**
* Get content type.
*
* @return string as the content type or null if not existing or invalid.
*/
public function getContentType()
{
$type = isset($this->response['header']['Content-Type'])
? $this->response['header']['Content-Type']
: null;
return preg_match('#[a-z]+/[a-z]+#', $type)
? $type
: null;
}
/**
* Get file modification time of response.
*
* @param mixed $default as default value (int seconds) if date is
* missing in response header.
*
* @return int as timestamp or $default if Date is missing in
* response header.
*/
public function getDate($default = false)
{
return isset($this->response['header']['Date'])
? strtotime($this->response['header']['Date'])
: $default;
}
/**
* Get max age of cachable item.
*
* @param mixed $default as default value if date is missing in response
* header.
*
* @return int as timestamp or false if not available.
*/
public function getMaxAge($default = false)
{
$cacheControl = isset($this->response['header']['Cache-Control'])
? $this->response['header']['Cache-Control']
: null;
$maxAge = null;
if ($cacheControl) {
// max-age=2592000
$part = explode('=', $cacheControl);
$maxAge = ($part[0] == "max-age")
? (int) $part[1]
: null;
}
if ($maxAge) {
return $maxAge;
}
$expire = isset($this->response['header']['Expires'])
? strtotime($this->response['header']['Expires'])
: null;
return $expire ? $expire : $default;
}
/**
* Get body of response.
*
* @return string as body.
*/
public function getBody()
{
return $this->response['body'];
}
}
/**
* Get a image from a remote server using HTTP GET and If-Modified-Since.
*
*/
class CRemoteImage
{
/**
* Path to cache files.
*/
private $saveFolder = null;
/**
* Use cache or not.
*/
private $useCache = true;
/**
* HTTP object to aid in download file.
*/
private $http;
/**
* Status of the HTTP request.
*/
private $status;
/**
* Defalt age for cached items 60*60*24*7.
*/
private $defaultMaxAge = 604800;
/**
* Url of downloaded item.
*/
private $url;
/**
* Base name of cache file for downloaded item and name of image.
*/
private $fileName;
/**
* Filename for json-file with details of cached item.
*/
private $fileJson;
/**
* Cache details loaded from file.
*/
private $cache;
/**
* Get status of last HTTP request.
*
* @return int as status
*/
public function getStatus()
{
return $this->status;
}
/**
* Get JSON details for cache item.
*
* @return array with json details on cache.
*/
public function getDetails()
{
return $this->cache;
}
/**
* Set the path to the cache directory.
*
* @param boolean $use true to use the cache and false to ignore cache.
*
* @return $this
*/
public function setCache($path)
{
$this->saveFolder = rtrim($path, "/") . "/";
return $this;
}
/**
* Check if cache is writable or throw exception.
*
* @return $this
*
* @throws Exception if cahce folder is not writable.
*/
public function isCacheWritable()
{
if (!is_writable($this->saveFolder)) {
throw new Exception("Cache folder is not writable for downloaded files.");
}
return $this;
}
/**
* Decide if the cache should be used or not before trying to download
* a remote file.
*
* @param boolean $use true to use the cache and false to ignore cache.
*
* @return $this
*/
public function useCache($use = true)
{
$this->useCache = $use;
return $this;
}
/**
* Set header fields.
*
* @return $this
*/
public function setHeaderFields()
{
$cimageVersion = "CImage";
if (defined("CIMAGE_USER_AGENT")) {
$cimageVersion = CIMAGE_USER_AGENT;
}
$this->http->setHeader("User-Agent", "$cimageVersion (PHP/". phpversion() . " cURL)");
$this->http->setHeader("Accept", "image/jpeg,image/png,image/gif");
if ($this->useCache) {
$this->http->setHeader("Cache-Control", "max-age=0");
} else {
$this->http->setHeader("Cache-Control", "no-cache");
$this->http->setHeader("Pragma", "no-cache");
}
}
/**
* Save downloaded resource to cache.
*
* @return string as path to saved file or false if not saved.
*/
public function save()
{
$this->cache = array();
$date = $this->http->getDate(time());
$maxAge = $this->http->getMaxAge($this->defaultMaxAge);
$lastModified = $this->http->getLastModified();
$type = $this->http->getContentType();
$this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date);
$this->cache['Max-Age'] = $maxAge;
$this->cache['Content-Type'] = $type;
$this->cache['Url'] = $this->url;
if ($lastModified) {
$this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
}
// Save only if body is a valid image
$body = $this->http->getBody();
$img = imagecreatefromstring($body);
if ($img !== false) {
file_put_contents($this->fileName, $body);
file_put_contents($this->fileJson, json_encode($this->cache));
return $this->fileName;
}
return false;
}
/**
* Got a 304 and updates cache with new age.
*
* @return string as path to cached file.
*/
public function updateCacheDetails()
{
$date = $this->http->getDate(time());
$maxAge = $this->http->getMaxAge($this->defaultMaxAge);
$lastModified = $this->http->getLastModified();
$this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date);
$this->cache['Max-Age'] = $maxAge;
if ($lastModified) {
$this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified);
}
file_put_contents($this->fileJson, json_encode($this->cache));
return $this->fileName;
}
/**
* Download a remote file and keep a cache of downloaded files.
*
* @param string $url a remote url.
*
* @throws Exception when status code does not match 200 or 304.
*
* @return string as path to downloaded file or false if failed.
*/
public function download($url)
{
$this->http = new CHttpGet();
$this->url = $url;
// First check if the cache is valid and can be used
$this->loadCacheDetails();
if ($this->useCache) {
$src = $this->getCachedSource();
if ($src) {
$this->status = 1;
return $src;
}
}
// Do a HTTP request to download item
$this->setHeaderFields();
$this->http->setUrl($this->url);
$this->http->doGet();
$this->status = $this->http->getStatus();
if ($this->status === 200) {
$this->isCacheWritable();
return $this->save();
} elseif ($this->status === 304) {
$this->isCacheWritable();
return $this->updateCacheDetails();
}
throw new Exception("Unknown statuscode when downloading remote image: " . $this->status);
}
/**
* Get the path to the cached image file if the cache is valid.
*
* @return $this
*/
public function loadCacheDetails()
{
$cacheFile = md5($this->url);
$this->fileName = $this->saveFolder . $cacheFile;
$this->fileJson = $this->fileName . ".json";
if (is_readable($this->fileJson)) {
$this->cache = json_decode(file_get_contents($this->fileJson), true);
}
}
/**
* Get the path to the cached image file if the cache is valid.
*
* @return string as the path ot the image file or false if no cache.
*/
public function getCachedSource()
{
$imageExists = is_readable($this->fileName);
// Is cache valid?
$date = strtotime($this->cache['Date']);
$maxAge = $this->cache['Max-Age'];
$now = time();
if ($imageExists && $date + $maxAge > $now) {
return $this->fileName;
}
// Prepare for a 304 if available
if ($imageExists && isset($this->cache['Last-Modified'])) {
$this->http->setHeader("If-Modified-Since", $this->cache['Last-Modified']);
}
return false;
}
}
/**
* Act as whitelist (or blacklist).
*
*/
class CWhitelist
{
/**
* Array to contain the whitelist options.
*/
private $whitelist = array();
/**
* Set the whitelist from an array of strings, each item in the
* whitelist should be a regexp without the surrounding / or #.
*
* @param array $whitelist with all valid options,
* default is to clear the whitelist.
*
* @return $this
*/
public function set($whitelist = array())
{
if (!is_array($whitelist)) {
throw new Exception("Whitelist is not of a supported format.");
}
$this->whitelist = $whitelist;
return $this;
}
/**
* Check if item exists in the whitelist.
*
* @param string $item string to check.
* @param array $whitelist optional with all valid options, default is null.
*
* @return boolean true if item is in whitelist, else false.
*/
public function check($item, $whitelist = null)
{
if ($whitelist !== null) {
$this->set($whitelist);
}
if (empty($item) or empty($this->whitelist)) {
return false;
}
foreach ($this->whitelist as $regexp) {
if (preg_match("#$regexp#", $item)) {
return true;
}
}
return false;
}
}
/**
* Create an ASCII version of an image.
*
*/
class CAsciiArt
{
/**
* Character set to use.
*/
private $characterSet = array(
'one' => "#0XT|:,.' ",
'two' => "@%#*+=-:. ",
'three' => "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
);
/**
* Current character set.
*/
private $characters = null;
/**
* Length of current character set.
*/
private $charCount = null;
/**
* Scale of the area to swap to a character.
*/
private $scale = null;
/**
* Strategy to calculate luminance.
*/
private $luminanceStrategy = null;
/**
* Constructor which sets default options.
*/
public function __construct()
{
$this->setOptions();
}
/**
* Add a custom character set.
*
* @param string $key for the character set.
* @param string $value for the character set.
*
* @return $this
*/
public function addCharacterSet($key, $value)
{
$this->characterSet[$key] = $value;
return $this;
}
/**
* Set options for processing, defaults are available.
*
* @param array $options to use as default settings.
*
* @return $this
*/
public function setOptions($options = array())
{
$default = array(
"characterSet" => 'two',
"scale" => 14,
"luminanceStrategy" => 3,
"customCharacterSet" => null,
);
$default = array_merge($default, $options);
if (!is_null($default['customCharacterSet'])) {
$this->addCharacterSet('custom', $default['customCharacterSet']);
$default['characterSet'] = 'custom';
}
$this->scale = $default['scale'];
$this->characters = $this->characterSet[$default['characterSet']];
$this->charCount = strlen($this->characters);
$this->luminanceStrategy = $default['luminanceStrategy'];
return $this;
}
/**
* Create an Ascii image from an image file.
*
* @param string $filename of the image to use.
*
* @return string $ascii with the ASCII image.
*/
public function createFromFile($filename)
{
$img = imagecreatefromstring(file_get_contents($filename));
list($width, $height) = getimagesize($filename);
$ascii = null;
$incY = $this->scale;
$incX = $this->scale / 2;
for ($y = 0; $y < $height - 1; $y += $incY) {
for ($x = 0; $x < $width - 1; $x += $incX) {
$toX = min($x + $this->scale / 2, $width - 1);
$toY = min($y + $this->scale, $height - 1);
$luminance = $this->luminanceAreaAverage($img, $x, $y, $toX, $toY);
$ascii .= $this->luminance2character($luminance);
}
$ascii .= PHP_EOL;
}
return $ascii;
}
/**
* Get the luminance from a region of an image using average color value.
*
* @param string $img the image.
* @param integer $x1 the area to get pixels from.
* @param integer $y1 the area to get pixels from.
* @param integer $x2 the area to get pixels from.
* @param integer $y2 the area to get pixels from.
*
* @return integer $luminance with a value between 0 and 100.
*/
public function luminanceAreaAverage($img, $x1, $y1, $x2, $y2)
{
$numPixels = ($x2 - $x1 + 1) * ($y2 - $y1 + 1);
$luminance = 0;
for ($x = $x1; $x <= $x2; $x++) {
for ($y = $y1; $y <= $y2; $y++) {
$rgb = imagecolorat($img, $x, $y);
$red = (($rgb >> 16) & 0xFF);
$green = (($rgb >> 8) & 0xFF);
$blue = ($rgb & 0xFF);
$luminance += $this->getLuminance($red, $green, $blue);
}
}
return $luminance / $numPixels;
}
/**
* Calculate luminance value with different strategies.
*
* @param integer $red The color red.
* @param integer $green The color green.
* @param integer $blue The color blue.
*
* @return float $luminance with a value between 0 and 1.
*/
public function getLuminance($red, $green, $blue)
{
switch ($this->luminanceStrategy) {
case 1:
$luminance = ($red * 0.2126 + $green * 0.7152 + $blue * 0.0722) / 255;
break;
case 2:
$luminance = ($red * 0.299 + $green * 0.587 + $blue * 0.114) / 255;
break;
case 3:
$luminance = sqrt(0.299 * pow($red, 2) + 0.587 * pow($green, 2) + 0.114 * pow($blue, 2)) / 255;
break;
case 0:
default:
$luminance = ($red + $green + $blue) / (255 * 3);
}
return $luminance;
}
/**
* Translate the luminance value to a character.
*
* @param string $position a value between 0-100 representing the
* luminance.
*
* @return string with the ascii character.
*/
public function luminance2character($luminance)
{
$position = (int) round($luminance * ($this->charCount - 1));
$char = $this->characters[$position];
return $char;
}
}
/**
* Resize and crop images on the fly, store generated images in a cache.
*
* @author Mikael Roos mos@dbwebb.se
* @example http://dbwebb.se/opensource/cimage
* @link /~https://github.com/mosbth/cimage
*/
class CImage
{
/**
* Constants type of PNG image
*/
const PNG_GREYSCALE = 0;
const PNG_RGB = 2;
const PNG_RGB_PALETTE = 3;
const PNG_GREYSCALE_ALPHA = 4;
const PNG_RGB_ALPHA = 6;
/**
* Constant for default image quality when not set
*/
const JPEG_QUALITY_DEFAULT = 60;
/**
* Quality level for JPEG images.
*/
private $quality;
/**
* Is the quality level set from external use (true) or is it default (false)?
*/
private $useQuality = false;
/**
* Constant for default image quality when not set
*/
const PNG_COMPRESSION_DEFAULT = -1;
/**
* Compression level for PNG images.
*/
private $compress;
/**
* Is the compress level set from external use (true) or is it default (false)?
*/
private $useCompress = false;
/**
* Add HTTP headers for outputing image.
*/
private $HTTPHeader = array();
/**
* Default background color, red, green, blue, alpha.
*
* @todo remake when upgrading to PHP 5.5