Gallery Bank: WordPress Photo Gallery Plugin - Version 1.8.7

Version Description

  • Timbthumb Thumbnails Issue fixed.
Download this release

Release Info

Developer Gallery-Bank
Plugin Icon 128x128 Gallery Bank: WordPress Photo Gallery Plugin
Version 1.8.7
Comparing to
See all releases

Code changes from version 1.8.6 to 1.8.7

gallery-bank.php CHANGED
@@ -4,7 +4,7 @@
4
  Plugin URI: http://gallery-bank.com
5
  Description: Gallery Bank is an interactive WordPress photo gallery plugin, best fit for creative and corporate portfolio websites.
6
  Author: Gallery-Bank
7
- Version: 1.8.6
8
  Author URI: http://gallery-bank.com
9
  */
10
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
4
  Plugin URI: http://gallery-bank.com
5
  Description: Gallery Bank is an interactive WordPress photo gallery plugin, best fit for creative and corporate portfolio websites.
6
  Author: Gallery-Bank
7
+ Version: 1.8.7
8
  Author URI: http://gallery-bank.com
9
  */
10
  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
lib/cache/desktop.ini ADDED
@@ -0,0 +1,4 @@
 
 
 
 
1
+ [ViewState]
2
+ Mode=
3
+ Vid=
4
+ FolderType=Generic
lib/class.jpeg_icc.php DELETED
@@ -1,566 +0,0 @@
1
- <?php
2
- /**
3
- * PHP JPEG ICC profile manipulator class
4
- *
5
- * @author Richard Toth aka risko (risko@risko.org)
6
- * @version 0.1
7
- */
8
- class JPEG_ICC
9
- {
10
- /**
11
- * ICC header size in APP2 segment
12
- *
13
- * 'ICC_PROFILE' 0x00 chunk_no chunk_cnt
14
- */
15
- const ICC_HEADER_LEN = 14;
16
-
17
- /**
18
- * maximum data len of a JPEG marker
19
- */
20
- const MAX_BYTES_IN_MARKER = 65533;
21
-
22
- /**
23
- * ICC header marker
24
- */
25
- const ICC_MARKER = "ICC_PROFILE\x00";
26
-
27
- /**
28
- * Rendering intent field (Bytes 64 to 67 in ICC profile data)
29
- */
30
- const ICC_RI_PERCEPTUAL = 0x00000000;
31
- const ICC_RI_RELATIVE_COLORIMETRIC = 0x00000001;
32
- const ICC_RI_SATURATION = 0x00000002;
33
- const ICC_RI_ABSOLUTE_COLORIMETRIC = 0x00000003;
34
-
35
- /**
36
- * ICC profile data
37
- * @var string
38
- */
39
- private $icc_profile = '';
40
-
41
- /**
42
- * ICC profile data size
43
- * @var int
44
- */
45
- private $icc_size = 0;
46
- /**
47
- * ICC profile data chunks count
48
- * @var int
49
- */
50
- private $icc_chunks = 0;
51
-
52
-
53
- /**
54
- * Class contructor
55
- */
56
- public function __construct()
57
- {
58
- }
59
-
60
- /**
61
- * Load ICC profile from JPEG file.
62
- *
63
- * Returns true if profile successfully loaded, false otherwise.
64
- *
65
- * @param string file name
66
- * @return bool
67
- */
68
- public function LoadFromJPEG($fname)
69
- {
70
- $f = file_get_contents($fname);
71
- $len = strlen($f);
72
- $pos = 0;
73
- $counter = 0;
74
- $profile_chunks = array(); // tu su ulozene jednotlive casti profilu
75
-
76
- while ($pos < $len && $counter < 1000)
77
- {
78
- $pos = strpos($f, "\xff", $pos);
79
- if ($pos === false) break; // dalsie 0xFF sa uz nenaslo - koniec vyhladavania
80
-
81
- $type = $this->getJPEGSegmentType($f, $pos);
82
- switch ($type)
83
- {
84
- case 0xe2: // APP2
85
- //echo "APP2 ";
86
- $size = $this->getJPEGSegmentSize($f, $pos);
87
- //echo "Size: $size\n";
88
-
89
- if ($this->getJPEGSegmentContainsICC($f, $pos, $size))
90
- {
91
- //echo "+ ICC Profile: YES\n";
92
- list($chunk_no, $chunk_cnt) = $this->getJPEGSegmentICCChunkInfo($f, $pos);
93
- //echo "+ ICC Profile chunk number: $chunk_no\n";
94
- //echo "+ ICC Profile chunks count: $chunk_cnt\n";
95
-
96
- if ($chunk_no <= $chunk_cnt)
97
- {
98
- $profile_chunks[$chunk_no] = $this->getJPEGSegmentICCChunk($f, $pos);
99
-
100
- if ($chunk_no == $chunk_cnt) // posledny kusok
101
- {
102
- ksort($profile_chunks);
103
- $this->SetProfile(implode('', $profile_chunks));
104
- return true;
105
- }
106
- }
107
- }
108
- $pos += $size + 2; // size of segment data + 2B size of segment marker
109
- break;
110
-
111
- case 0xe0: // APP0
112
- case 0xe1: // APP1
113
- case 0xe3: // APP3
114
- case 0xe4: // APP4
115
- case 0xe5: // APP5
116
- case 0xe6: // APP6
117
- case 0xe7: // APP7
118
- case 0xe8: // APP8
119
- case 0xe9: // APP9
120
- case 0xea: // APP10
121
- case 0xeb: // APP11
122
- case 0xec: // APP12
123
- case 0xed: // APP13
124
- case 0xee: // APP14
125
- case 0xef: // APP15
126
- case 0xc0: // SOF0
127
- case 0xc2: // SOF2
128
- case 0xc4: // DHT
129
- case 0xdb: // DQT
130
- case 0xda: // SOS
131
- case 0xfe: // COM
132
- $size = $this->getJPEGSegmentSize($f, $pos);
133
- $pos += $size + 2; // size of segment data + 2B size of segment marker
134
- break;
135
-
136
- case 0xd8: // SOI
137
- case 0xdd: // DRI
138
- case 0xd9: // EOI
139
- case 0xd0: // RST0
140
- case 0xd1: // RST1
141
- case 0xd2: // RST2
142
- case 0xd3: // RST3
143
- case 0xd4: // RST4
144
- case 0xd5: // RST5
145
- case 0xd6: // RST6
146
- case 0xd7: // RST7
147
- default:
148
- $pos += 2;
149
- break;
150
- }
151
- $counter++;
152
- }
153
-
154
- return false;
155
- }
156
-
157
- public function SaveToJPEG($fname)
158
- {
159
- if ($this->icc_profile == '') throw new Exception("No profile loaded.\n");
160
-
161
- if (!file_exists($fname)) throw new Exception("File $fname doesn't exist.\n");
162
- if (!is_readable($fname)) throw new Exception("File $fname isn't readable.\n");
163
- $dir = realpath($fname);
164
- if (!is_writable($dir)) throw new Exception("Directory $fname isn't writeable.\n");
165
-
166
- $f = file_get_contents($fname);
167
- if ($this->insertProfile($f))
168
- {
169
- $fsize = strlen($f);
170
- $ret = file_put_contents($fname, $f);
171
- if ($ret === false || $ret < $fsize) throw new Exception ("Write failed.\n");
172
- }
173
- }
174
-
175
- /**
176
- * Load profile from ICC file.
177
- *
178
- * @param string file name
179
- */
180
- public function LoadFromICC($fname)
181
- {
182
- if (!file_exists($fname)) throw new Exception("File $fname doesn't exist.\n");
183
- if (!is_readable($fname)) throw new Exception("File $fname isn't readable.\n");
184
-
185
- $this->SetProfile(file_get_contents($fname));
186
- }
187
-
188
- /**
189
- * Save profile to ICC file.
190
- *
191
- * @param string file name
192
- * @param bool [force overwrite]
193
- */
194
- public function SaveToICC($fname, $force_overwrite = false)
195
- {
196
- if ($this->icc_profile == '') throw new Exception("No profile loaded.\n");
197
- $dir = realpath($fname);
198
- if (!is_writable($dir)) throw new Exception("Directory $fname isn't writeable.\n");
199
- if (!$force_overwrite && file_exists($fname)) throw new Exception("File $fname exists.\n");
200
-
201
- $ret = file_put_contents($fname, $this->icc_profile);
202
- if ($ret === false || $ret < $this->icc_size) throw new Exception ("Write failed.\n");
203
- }
204
-
205
- /**
206
- * Remove profile from JPEG file and save it as a new file.
207
- * Overwriting destination file can be forced
208
- *
209
- * @param string source file
210
- * @param string destination file
211
- * @param bool [force overwrite]
212
- * @return bool
213
- */
214
- public function RemoveFromJPEG($input, $output, $force_overwrite = false)
215
- {
216
- if (!file_exists($input)) throw new Exception("File $input doesn't exist.\n");
217
- if (!is_readable($input)) throw new Exception("File $input isn't readable.\n");
218
- $dir = realpath($output);
219
- if (!is_writable($dir)) throw new Exception("Directory $output isn't writeable.\n");
220
- if (!$force_overwrite && file_exists($output)) throw new Exception("File $output exists.\n");
221
-
222
- $f = file_get_contents($input);
223
- $this->removeProfile($f);
224
- $fsize = strlen($f);
225
- $ret = file_put_contents($output, $f);
226
- if ($ret === false || $ret < $fsize) throw new Exception ("Write failed.\n");
227
-
228
- return true; // any other error throws exception
229
- }
230
-
231
- /**
232
- * Set profile directly
233
- *
234
- * @param string profile data
235
- */
236
- public function SetProfile($data)
237
- {
238
- $this->icc_profile = $data;
239
- $this->icc_size = strlen($data);
240
- $this->countChunks();
241
- }
242
-
243
- /**
244
- * Get profile directly
245
- *
246
- * @return string
247
- */
248
- public function GetProfile()
249
- {
250
- return $this->icc_profile;
251
- }
252
-
253
- /**
254
- * Count in how many chunks we need to divide the profile to store it in JPEG APP2 segments
255
- */
256
- private function countChunks()
257
- {
258
- $this->icc_chunks = ceil($this->icc_size / ((float) (self::MAX_BYTES_IN_MARKER - self::ICC_HEADER_LEN)));
259
- }
260
-
261
- /**
262
- * Set Rendering Intent of the profile.
263
- *
264
- * Possilbe values are ICC_RI_PERCEPTUAL, ICC_RI_RELATIVE_COLORIMETRIC, ICC_RI_SATURATION or ICC_RI_ABSOLUTE_COLORIMETRIC.
265
- *
266
- * @param int rendering intent
267
- */
268
- private function setRenderingIntent($newRI)
269
- {
270
- if ($this->icc_size >= 68)
271
- {
272
- substr_replace($this->icc_profile, pack('N', $newRI), 64, 4);
273
- }
274
- }
275
-
276
- /**
277
- * Get value of Rendering Intent field in ICC profile
278
- *
279
- * @return int
280
- */
281
- private function getRenderingIntent()
282
- {
283
- if ($this->icc_size >= 68)
284
- {
285
- $arr = unpack('Nint', substr($this->icc_profile, 64, 4));
286
- return $arr['int'];
287
- }
288
-
289
- return null;
290
- }
291
-
292
- /**
293
- * Size of JPEG segment
294
- *
295
- * @param string file data
296
- * @param int start of segment
297
- * @return int
298
- */
299
- private function getJPEGSegmentSize(&$f, $pos)
300
- {
301
- $arr = unpack('nint', substr($f, $pos + 2, 2)); // segment size has offset 2 and length 2B
302
- return $arr['int'];
303
- }
304
-
305
- /**
306
- * Type of JPEG segment
307
- *
308
- * @param string file data
309
- * @param int start of segment
310
- * @return int
311
- */
312
- private function getJPEGSegmentType(&$f, $pos)
313
- {
314
- $arr = unpack('Cchar', substr($f, $pos + 1, 1)); // segment type has offset 1 and length 1B
315
- return $arr['char'];
316
- }
317
-
318
- /**
319
- * Check if segment contains ICC profile marker
320
- *
321
- * @param string file data
322
- * @param int position of segment data
323
- * @param int size of segment data (without 2 bytes of size field)
324
- * @return bool
325
- */
326
- private function getJPEGSegmentContainsICC(&$f, $pos, $size)
327
- {
328
- if ($size < self::ICC_HEADER_LEN) return false; // ICC_PROFILE 0x00 Marker_no Marker_cnt
329
-
330
- return (bool) (substr($f, $pos + 4, self::ICC_HEADER_LEN - 2) == self::ICC_MARKER); // 4B offset in segment data = 2B segment marker + 2B segment size data
331
- }
332
-
333
- /**
334
- * Get ICC segment chunk info
335
- *
336
- * @param string file data
337
- * @param int position of segment data
338
- * @return array {chunk_no, chunk_cnt}
339
- */
340
- private function getJPEGSegmentICCChunkInfo(&$f, $pos)
341
- {
342
- $a = unpack('Cchunk_no/Cchunk_count', substr($f, $pos + 16, 2)); // 16B offset to data = 2B segment marker + 2B segment size + 'ICC_PROFILE' + 0x00, 1. byte chunk number, 2. byte chunks count
343
- return array_values($a);
344
- }
345
-
346
- /**
347
- * Returns chunk of ICC profile data from segment.
348
- *
349
- * @param string &data
350
- * @param int current position
351
- * @return string
352
- */
353
- private function getJPEGSegmentICCChunk(&$f, $pos)
354
- {
355
- $data_offset = $pos + 4 + self::ICC_HEADER_LEN; // 4B JPEG APP offset + 14B ICC header offset
356
- $size = $this->getJPEGSegmentSize($f, $pos);
357
- $data_size = $size - self::ICC_HEADER_LEN - 2; // 14B ICC header - 2B of size data
358
- return substr($f, $data_offset, $data_size);
359
- }
360
-
361
- /**
362
- * Get data of given chunk
363
- *
364
- * @param int chunk number
365
- * @return string
366
- */
367
- private function getChunk($chunk_no)
368
- {
369
- if ($chunk_no > $this->icc_chunks) return '';
370
-
371
- $max_chunk_size = self::MAX_BYTES_IN_MARKER - self::ICC_HEADER_LEN;
372
- $from = ($chunk_no - 1) * $max_chunk_size;
373
- $bytes = ($chunk_no < $this->icc_chunks) ? $max_chunk_size : $this->icc_size % $max_chunk_size;
374
-
375
- return substr($this->icc_profile, $from, $bytes);
376
- }
377
-
378
- private function prepareJPEGProfileData()
379
- {
380
- $data = '';
381
-
382
- for ($i = 1; $i <= $this->icc_chunks; $i++)
383
- {
384
- $chunk = $this->getChunk($i);
385
- $chunk_size = strlen($chunk);
386
- $data .= "\xff\xe2" . pack('n', $chunk_size + 2 + self::ICC_HEADER_LEN); // APP2 segment marker + size field
387
- $data .= self::ICC_MARKER . pack('CC', $i, $this->icc_chunks); // profile marker inside segment
388
- $data .= $chunk;
389
- }
390
-
391
- return $data;
392
- }
393
-
394
- /**
395
- * Removes profile from JPEG data
396
- *
397
- * @param string &data
398
- * @return bool
399
- */
400
- private function removeProfile(&$jpeg_data)
401
- {
402
- $len = strlen($jpeg_data);
403
- $pos = 0;
404
- $counter = 0; // ehm...
405
- $chunks_to_go = -1;
406
-
407
- while ($pos < $len && $counter < 100)
408
- {
409
- $pos = strpos($jpeg_data, "\xff", $pos);
410
- if ($pos === false) break; // no more 0xFF - we can end up with search
411
-
412
- // analyze next segment
413
- $type = $this->getJPEGSegmentType($jpeg_data, $pos);
414
-
415
- switch ($type)
416
- {
417
- case 0xe2: // APP2
418
- $size = $this->getJPEGSegmentSize($jpeg_data, $pos);
419
-
420
- if ($this->getJPEGSegmentContainsICC($jpeg_data, $pos, $size))
421
- {
422
- list($chunk_no, $chunk_cnt) = $this->getJPEGSegmentICCChunkInfo($jpeg_data, $pos);
423
- if ($chunks_to_go == -1) $chunks_to_go = $chunk_cnt; // first time save chunks count
424
-
425
- $jpeg_data = substr_replace($jpeg_data, '', $pos, $size + 2); // remove this APP segment from dataset (segment size + 2B app marker)
426
- $len -= $size + 2; // shorten the size
427
-
428
- if (--$chunks_to_go == 0) return true; // no more icc profile chunks, store file
429
-
430
- break; // go out without changing the position
431
- }
432
- $pos += $size + 2; // size of segment data + 2B size of segment marker
433
- break;
434
-
435
- case 0xe0: // APP0
436
- case 0xe1: // APP1
437
- case 0xe3: // APP3
438
- case 0xe4: // APP4
439
- case 0xe5: // APP5
440
- case 0xe6: // APP6
441
- case 0xe7: // APP7
442
- case 0xe8: // APP8
443
- case 0xe9: // APP9
444
- case 0xea: // APP10
445
- case 0xeb: // APP11
446
- case 0xec: // APP12
447
- case 0xed: // APP13
448
- case 0xee: // APP14
449
- case 0xef: // APP15
450
- case 0xc0: // SOF0
451
- case 0xc2: // SOF2
452
- case 0xc4: // DHT
453
- case 0xdb: // DQT
454
- case 0xda: // SOS
455
- case 0xfe: // COM
456
- $size = $this->getJPEGSegmentSize($jpeg_data, $pos);
457
- $pos += $size + 2; // size of segment data + 2B size of segment marker
458
- break;
459
-
460
- case 0xd8: // SOI
461
- case 0xdd: // DRI
462
- case 0xd9: // EOI
463
- case 0xd0: // RST0
464
- case 0xd1: // RST1
465
- case 0xd2: // RST2
466
- case 0xd3: // RST3
467
- case 0xd4: // RST4
468
- case 0xd5: // RST5
469
- case 0xd6: // RST6
470
- case 0xd7: // RST7
471
- default:
472
- $pos += 2;
473
- break;
474
- }
475
- $counter++;
476
- }
477
-
478
- return false;
479
- }
480
-
481
- /**
482
- * Inserts profile to JPEG data.
483
- *
484
- * Inserts profile immediately after SOI section
485
- *
486
- * @param string &data
487
- * @return bool
488
- */
489
- private function insertProfile(&$jpeg_data)
490
- {
491
- $len = strlen($jpeg_data);
492
- $pos = 0;
493
- $counter = 0; // ehm...
494
- $chunks_to_go = -1;
495
-
496
- while ($pos < $len && $counter < 100)
497
- {
498
- $pos = strpos($jpeg_data, "\xff", $pos);
499
- if ($pos === false) break; // no more 0xFF - we can end up with search
500
-
501
- // analyze next segment
502
- $type = $this->getJPEGSegmentType($jpeg_data, $pos);
503
-
504
- switch ($type)
505
- {
506
- case 0xd8: // SOI
507
- $pos += 2;
508
-
509
- $p_data = $this->prepareJPEGProfileData();
510
- if ($p_data != '')
511
- {
512
- $before = substr($jpeg_data, 0, $pos);
513
- $after = substr($jpeg_data, $pos);
514
- $jpeg_data = $before . $p_data . $after;
515
- return true;
516
- }
517
- return false;
518
- //break;
519
-
520
- case 0xe0: // APP0
521
- case 0xe1: // APP1
522
- case 0xe2: // APP2
523
- case 0xe3: // APP3
524
- case 0xe4: // APP4
525
- case 0xe5: // APP5
526
- case 0xe6: // APP6
527
- case 0xe7: // APP7
528
- case 0xe8: // APP8
529
- case 0xe9: // APP9
530
- case 0xea: // APP10
531
- case 0xeb: // APP11
532
- case 0xec: // APP12
533
- case 0xed: // APP13
534
- case 0xee: // APP14
535
- case 0xef: // APP15
536
- case 0xc0: // SOF0
537
- case 0xc2: // SOF2
538
- case 0xc4: // DHT
539
- case 0xdb: // DQT
540
- case 0xda: // SOS
541
- case 0xfe: // COM
542
- $size = $this->getJPEGSegmentSize($jpeg_data, $pos);
543
- $pos += $size + 2; // size of segment data + 2B size of segment marker
544
- break;
545
-
546
- case 0xdd: // DRI
547
- case 0xd9: // EOI
548
- case 0xd0: // RST0
549
- case 0xd1: // RST1
550
- case 0xd2: // RST2
551
- case 0xd3: // RST3
552
- case 0xd4: // RST4
553
- case 0xd5: // RST5
554
- case 0xd6: // RST6
555
- case 0xd7: // RST7
556
- default:
557
- $pos += 2;
558
- break;
559
- }
560
- $counter++;
561
- }
562
-
563
- return false;
564
- }
565
- }
566
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
lib/in-srgb.jpg DELETED
Binary file
lib/timthumb.php CHANGED
@@ -1,1202 +1,1251 @@
1
- <?php
2
- /**
3
- * TimThumb by Ben Gillbanks and Mark Maunder
4
- * Based on work done by Tim McDaniels and Darren Hoyt
5
- * http://code.google.com/p/timthumb/
6
- *
7
- * GNU General Public License, version 2
8
- * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
9
- *
10
- * Examples and documentation available on the project homepage
11
- * http://www.binarymoon.co.uk/projects/timthumb/
12
- */
13
-
14
- /*
15
- -----TimThumb CONFIGURATION-----
16
- You can either edit the configuration variables manually here, or you can
17
- create a file called timthumb-config.php and define variables you want
18
- to customize in there. It will automatically be loaded by timthumb.
19
- This will save you having to re-edit these variables everytime you download
20
- a new version of timthumb.
21
-
22
- */
23
- require_once 'class.jpeg_icc.php';
24
- define ('VERSION', '2.8.2'); // Version of this script
25
- //Load a config file if it exists. Otherwise, use the values below
26
- if( file_exists(dirname(__FILE__) . '/timthumb-config.php')) require_once('timthumb-config.php');
27
- if(! defined('DEBUG_ON') ) define ('DEBUG_ON', false); // Enable debug logging to web server error log (STDERR)
28
- if(! defined('DEBUG_LEVEL') ) define ('DEBUG_LEVEL', 1); // Debug level 1 is less noisy and 3 is the most noisy
29
- if(! defined('MEMORY_LIMIT') ) define ('MEMORY_LIMIT', '30M'); // Set PHP memory limit
30
- if(! defined('BLOCK_EXTERNAL_LEECHERS') ) define ('BLOCK_EXTERNAL_LEECHERS', false); // If the image or webshot is being loaded on an external site, display a red "No Hotlinking" gif.
31
-
32
- //Image fetching and caching
33
- if(! defined('ALLOW_EXTERNAL') ) define ('ALLOW_EXTERNAL', TRUE); // Allow image fetching from external websites. Will check against ALLOWED_SITES if ALLOW_ALL_EXTERNAL_SITES is false
34
- if(! defined('ALLOW_ALL_EXTERNAL_SITES') ) define ('ALLOW_ALL_EXTERNAL_SITES', false); // Less secure.
35
- if(! defined('FILE_CACHE_ENABLED') ) define ('FILE_CACHE_ENABLED', TRUE); // Should we store resized/modified images on disk to speed things up?
36
- if(! defined('FILE_CACHE_TIME_BETWEEN_CLEANS')) define ('FILE_CACHE_TIME_BETWEEN_CLEANS', 86400); // How often the cache is cleaned
37
- if(! defined('FILE_CACHE_MAX_FILE_AGE') ) define ('FILE_CACHE_MAX_FILE_AGE', 86400); // How old does a file have to be to be deleted from the cache
38
- if(! defined('FILE_CACHE_SUFFIX') ) define ('FILE_CACHE_SUFFIX', '.timthumb.txt'); // What to put at the end of all files in the cache directory so we can identify them
39
- if(! defined('FILE_CACHE_DIRECTORY') ) define ('FILE_CACHE_DIRECTORY', './cache'); // Directory where images are cached. Left blank it will use the system temporary directory (which is better for security)
40
- if(! defined('MAX_FILE_SIZE') ) define ('MAX_FILE_SIZE', 10485760); // 10 Megs is 10485760. This is the max internal or external file size that we'll process.
41
- if(! defined('CURL_TIMEOUT') ) define ('CURL_TIMEOUT', 20); // Timeout duration for Curl. This only applies if you have Curl installed and aren't using PHP's default URL fetching mechanism.
42
- if(! defined('WAIT_BETWEEN_FETCH_ERRORS') ) define ('WAIT_BETWEEN_FETCH_ERRORS', 3600); //Time to wait between errors fetching remote file
43
- //Browser caching
44
- if(! defined('BROWSER_CACHE_MAX_AGE') ) define ('BROWSER_CACHE_MAX_AGE', 864000); // Time to cache in the browser
45
- if(! defined('BROWSER_CACHE_DISABLE') ) define ('BROWSER_CACHE_DISABLE', false); // Use for testing if you want to disable all browser caching
46
-
47
- //Image size and defaults
48
- if(! defined('MAX_WIDTH') ) define ('MAX_WIDTH', 1500); // Maximum image width
49
- if(! defined('MAX_HEIGHT') ) define ('MAX_HEIGHT', 1500); // Maximum image height
50
- if(! defined('NOT_FOUND_IMAGE') ) define ('NOT_FOUND_IMAGE', ''); //Image to serve if any 404 occurs
51
- if(! defined('ERROR_IMAGE') ) define ('ERROR_IMAGE', ''); //Image to serve if an error occurs instead of showing error message
52
-
53
- //Image compression is enabled if either of these point to valid paths
54
-
55
- //These are now disabled by default because the file sizes of PNGs (and GIFs) are much smaller than we used to generate.
56
- //They only work for PNGs. GIFs and JPEGs are not affected.
57
- if(! defined('OPTIPNG_ENABLED') ) define ('OPTIPNG_ENABLED', false);
58
- if(! defined('OPTIPNG_PATH') ) define ('OPTIPNG_PATH', '/usr/bin/optipng'); //This will run first because it gives better compression than pngcrush.
59
- if(! defined('PNGCRUSH_ENABLED') ) define ('PNGCRUSH_ENABLED', false);
60
- if(! defined('PNGCRUSH_PATH') ) define ('PNGCRUSH_PATH', '/usr/bin/pngcrush'); //This will only run if OPTIPNG_PATH is not set or is not valid
61
-
62
- /*
63
- -------====Website Screenshots configuration - BETA====-------
64
-
65
- If you just want image thumbnails and don't want website screenshots, you can safely leave this as is.
66
-
67
- If you would like to get website screenshots set up, you will need root access to your own server.
68
-
69
- Enable ALLOW_ALL_EXTERNAL_SITES so you can fetch any external web page. This is more secure now that we're using a non-web folder for cache.
70
- Enable BLOCK_EXTERNAL_LEECHERS so that your site doesn't generate thumbnails for the whole Internet.
71
-
72
- Instructions to get website screenshots enabled on Ubuntu Linux:
73
-
74
- 1. Install Xvfb with the following command: sudo apt-get install subversion libqt4-webkit libqt4-dev g++ xvfb
75
- 2. Go to a directory where you can download some code
76
- 3. Check-out the latest version of CutyCapt with the following command: svn co https://cutycapt.svn.sourceforge.net/svnroot/cutycapt
77
- 4. Compile CutyCapt by doing: cd cutycapt/CutyCapt
78
- 5. qmake
79
- 6. make
80
- 7. cp CutyCapt /usr/local/bin/
81
- 8. Test it by running: xvfb-run --server-args="-screen 0, 1024x768x24" CutyCapt --url="http://markmaunder.com/" --out=test.png
82
- 9. If you get a file called test.png with something in it, it probably worked. Now test the script by accessing it as follows:
83
- 10. http://yoursite.com/path/to/timthumb.php?src=http://markmaunder.com/&webshot=1
84
-
85
- Notes on performance:
86
- The first time a webshot loads, it will take a few seconds.
87
- From then on it uses the regular timthumb caching mechanism with the configurable options above
88
- and loading will be very fast.
89
-
90
- --ADVANCED USERS ONLY--
91
- If you'd like a slight speedup (about 25%) and you know Linux, you can run the following command which will keep Xvfb running in the background.
92
- nohup Xvfb :100 -ac -nolisten tcp -screen 0, 1024x768x24 > /dev/null 2>&1 &
93
- Then set WEBSHOT_XVFB_RUNNING = true below. This will save your server having to fire off a new Xvfb server and shut it down every time a new shot is generated.
94
- You will need to take responsibility for keeping Xvfb running in case it crashes. (It seems pretty stable)
95
- You will also need to take responsibility for server security if you're running Xvfb as root.
96
-
97
-
98
- */
99
- if(! defined('WEBSHOT_ENABLED') ) define ('WEBSHOT_ENABLED', false); //Beta feature. Adding webshot=1 to your query string will cause the script to return a browser screenshot rather than try to fetch an image.
100
- if(! defined('WEBSHOT_CUTYCAPT') ) define ('WEBSHOT_CUTYCAPT', '/usr/local/bin/CutyCapt'); //The path to CutyCapt.
101
- if(! defined('WEBSHOT_XVFB') ) define ('WEBSHOT_XVFB', '/usr/bin/xvfb-run'); //The path to the Xvfb server
102
- if(! defined('WEBSHOT_SCREEN_X') ) define ('WEBSHOT_SCREEN_X', '1024'); //1024 works ok
103
- if(! defined('WEBSHOT_SCREEN_Y') ) define ('WEBSHOT_SCREEN_Y', '768'); //768 works ok
104
- if(! defined('WEBSHOT_COLOR_DEPTH') ) define ('WEBSHOT_COLOR_DEPTH', '24'); //I haven't tested anything besides 24
105
- if(! defined('WEBSHOT_IMAGE_FORMAT') ) define ('WEBSHOT_IMAGE_FORMAT', 'png'); //png is about 2.5 times the size of jpg but is a LOT better quality
106
- if(! defined('WEBSHOT_TIMEOUT') ) define ('WEBSHOT_TIMEOUT', '20'); //Seconds to wait for a webshot
107
- if(! defined('WEBSHOT_USER_AGENT') ) define ('WEBSHOT_USER_AGENT', "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18"); //I hate to do this, but a non-browser robot user agent might not show what humans see. So we pretend to be Firefox
108
- if(! defined('WEBSHOT_JAVASCRIPT_ON') ) define ('WEBSHOT_JAVASCRIPT_ON', true); //Setting to false might give you a slight speedup and block ads. But it could cause other issues.
109
- if(! defined('WEBSHOT_JAVA_ON') ) define ('WEBSHOT_JAVA_ON', false); //Have only tested this as fase
110
- if(! defined('WEBSHOT_PLUGINS_ON') ) define ('WEBSHOT_PLUGINS_ON', true); //Enable flash and other plugins
111
- if(! defined('WEBSHOT_PROXY') ) define ('WEBSHOT_PROXY', ''); //In case you're behind a proxy server.
112
- if(! defined('WEBSHOT_XVFB_RUNNING') ) define ('WEBSHOT_XVFB_RUNNING', false); //ADVANCED: Enable this if you've got Xvfb running in the background.
113
-
114
-
115
- // If ALLOW_EXTERNAL is true and ALLOW_ALL_EXTERNAL_SITES is false, then external images will only be fetched from these domains and their subdomains.
116
- if(! isset($ALLOWED_SITES)){
117
- $ALLOWED_SITES = array ();
118
- }
119
- // -------------------------------------------------------------
120
- // -------------- STOP EDITING CONFIGURATION HERE --------------
121
- // -------------------------------------------------------------
122
-
123
- timthumb::start();
124
-
125
- class timthumb {
126
- protected $src = "";
127
- protected $is404 = false;
128
- protected $docRoot = "";
129
- protected $lastURLError = false;
130
- protected $localImage = "";
131
- protected $localImageMTime = 0;
132
- protected $url = false;
133
- protected $myHost = "";
134
- protected $isURL = false;
135
- protected $cachefile = '';
136
- protected $errors = array();
137
- protected $toDeletes = array();
138
- protected $cacheDirectory = '';
139
- protected $startTime = 0;
140
- protected $lastBenchTime = 0;
141
- protected $cropTop = false;
142
- protected $salt = "";
143
- protected $fileCacheVersion = 1; //Generally if timthumb.php is modifed (upgraded) then the salt changes and all cache files are recreated. This is a backup mechanism to force regen.
144
- protected $filePrependSecurityBlock = "<?php die('Execution denied!'); //"; //Designed to have three letter mime type, space, question mark and greater than symbol appended. 6 bytes total.
145
- protected static $curlDataWritten = 0;
146
- protected static $curlFH = false;
147
- public static function start(){
148
- $tim = new timthumb();
149
- $tim->handleErrors();
150
- $tim->securityChecks();
151
- if($tim->tryBrowserCache()){
152
- exit(0);
153
- }
154
- $tim->handleErrors();
155
- if(FILE_CACHE_ENABLED && $tim->tryServerCache()){
156
- exit(0);
157
- }
158
- $tim->handleErrors();
159
- $tim->run();
160
- $tim->handleErrors();
161
- exit(0);
162
- }
163
- public function __construct(){
164
- global $ALLOWED_SITES;
165
- $this->startTime = microtime(true);
166
- date_default_timezone_set('UTC');
167
- $this->debug(1, "Starting new request from " . $this->getIP() . " to " . $_SERVER['REQUEST_URI']);
168
- $this->calcDocRoot();
169
- //On windows systems I'm assuming fileinode returns an empty string or a number that doesn't change. Check this.
170
- $this->salt = @filemtime(__FILE__) . '-' . @fileinode(__FILE__);
171
- $this->debug(3, "Salt is: " . $this->salt);
172
- if(FILE_CACHE_DIRECTORY){
173
- if(! is_dir(FILE_CACHE_DIRECTORY)){
174
- @mkdir(FILE_CACHE_DIRECTORY);
175
- if(! is_dir(FILE_CACHE_DIRECTORY)){
176
- $this->error("Could not create the file cache directory.");
177
- return false;
178
- }
179
- }
180
- $this->cacheDirectory = FILE_CACHE_DIRECTORY;
181
- if (!touch($this->cacheDirectory . '/index.html')) {
182
- $this->error("Could note create the index.html file.");
183
- }
184
- } else {
185
- $this->cacheDirectory = sys_get_temp_dir();
186
- }
187
- //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.
188
- $this->cleanCache();
189
-
190
- $this->myHost = preg_replace('/^www\./i', '', $_SERVER['HTTP_HOST']);
191
- $this->src = $this->param('src');
192
- $this->url = parse_url($this->src);
193
- if(strlen($this->src) <= 3){
194
- $this->error("No image specified");
195
- return false;
196
- }
197
- if(BLOCK_EXTERNAL_LEECHERS && array_key_exists('HTTP_REFERER', $_SERVER) && (! preg_match('/^https?:\/\/(?:www\.)?' . $this->myHost . '(?:$|\/)/i', $_SERVER['HTTP_REFERER']))){
198
- // base64 encoded red image that says 'no hotlinkers'
199
- // nothing to worry about! :)
200
- $imgData = base64_decode("R0lGODlhUAAMAIAAAP8AAP///yH5BAAHAP8ALAAAAABQAAwAAAJpjI+py+0Po5y0OgAMjjv01YUZ\nOGplhWXfNa6JCLnWkXplrcBmW+spbwvaVr/cDyg7IoFC2KbYVC2NQ5MQ4ZNao9Ynzjl9ScNYpneb\nDULB3RP6JuPuaGfuuV4fumf8PuvqFyhYtjdoeFgAADs=");
201
- header('Content-Type: image/gif');
202
- header('Content-Length: ' . sizeof($imgData));
203
- header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
204
- header("Pragma: no-cache");
205
- header('Expires: ' . gmdate ('D, d M Y H:i:s', time()));
206
- echo $imgData;
207
- return false;
208
- exit(0);
209
- }
210
- if(preg_match('/https?:\/\/(?:www\.)?' . $this->myHost . '(?:$|\/)/i', $this->src)){
211
- $this->src = preg_replace('/https?:\/\/(?:www\.)?' . $this->myHost . '/i', '', $this->src);
212
- }
213
- if(preg_match('/^https?:\/\/[^\/]+/i', $this->src)){
214
- $this->debug(2, "Is a request for an external URL: " . $this->src);
215
- $this->isURL = true;
216
- } else {
217
- $this->debug(2, "Is a request for an internal file: " . $this->src);
218
- }
219
- if($this->isURL && (! ALLOW_EXTERNAL)){
220
- $this->error("You are not allowed to fetch images from an external website.");
221
- return false;
222
- }
223
- if($this->isURL){
224
- if(ALLOW_ALL_EXTERNAL_SITES){
225
- $this->debug(2, "Fetching from all external sites is enabled.");
226
- } else {
227
- $this->debug(2, "Fetching only from selected external sites is enabled.");
228
- $allowed = false;
229
- foreach($ALLOWED_SITES as $site){
230
- if ((strtolower(substr($this->url['host'],-strlen($site)-1)) === strtolower(".$site")) || (strtolower($this->url['host'])===strtolower($site))) {
231
- $this->debug(3, "URL hostname {$this->url['host']} matches $site so allowing.");
232
- $allowed = true;
233
- }
234
- }
235
- if(! $allowed){
236
- return $this->error("You may not fetch images from that site. To enable this site in timthumb, you can either add it to \$ALLOWED_SITES and set ALLOW_EXTERNAL=true. Or you can set ALLOW_ALL_EXTERNAL_SITES=true, depending on your security needs.");
237
- }
238
- }
239
- }
240
-
241
- $cachePrefix = ($this->isURL ? 'timthumb_ext_' : 'timthumb_int_');
242
- if($this->isURL){
243
- $this->cachefile = $this->cacheDirectory . '/' . $cachePrefix . md5($this->salt . $_SERVER ['QUERY_STRING'] . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
244
- } else {
245
- $this->localImage = $this->getLocalImagePath($this->src);
246
- if(! $this->localImage){
247
- $this->debug(1, "Could not find the local image: {$this->localImage}");
248
- $this->error("Could not find the internal image you specified.");
249
- $this->set404();
250
- return false;
251
- }
252
- $this->debug(1, "Local image path is {$this->localImage}");
253
- $this->localImageMTime = @filemtime($this->localImage);
254
- //We include the mtime of the local file in case in changes on disk.
255
- $this->cachefile = $this->cacheDirectory . '/' . $cachePrefix . md5($this->salt . $this->localImageMTime . $_SERVER ['QUERY_STRING'] . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
256
- }
257
- $this->debug(2, "Cache file is: " . $this->cachefile);
258
-
259
- return true;
260
- }
261
- public function __destruct(){
262
- foreach($this->toDeletes as $del){
263
- $this->debug(2, "Deleting temp file $del");
264
- @unlink($del);
265
- }
266
- }
267
- public function run(){
268
- if($this->isURL){
269
- if(! ALLOW_EXTERNAL){
270
- $this->debug(1, "Got a request for an external image but ALLOW_EXTERNAL is disabled so returning error msg.");
271
- $this->error("You are not allowed to fetch images from an external website.");
272
- return false;
273
- }
274
- $this->debug(3, "Got request for external image. Starting serveExternalImage.");
275
- if($this->param('webshot')){
276
- if(WEBSHOT_ENABLED){
277
- $this->debug(3, "webshot param is set, so we're going to take a webshot.");
278
- $this->serveWebshot();
279
- } else {
280
- $this->error("You added the webshot parameter but webshots are disabled on this server. You need to set WEBSHOT_ENABLED == true to enable webshots.");
281
- }
282
- } else {
283
- $this->debug(3, "webshot is NOT set so we're going to try to fetch a regular image.");
284
- $this->serveExternalImage();
285
-
286
- }
287
- } else {
288
- $this->debug(3, "Got request for internal image. Starting serveInternalImage()");
289
- $this->serveInternalImage();
290
- }
291
- return true;
292
- }
293
- protected function handleErrors(){
294
- if($this->haveErrors()){
295
- if(NOT_FOUND_IMAGE && $this->is404()){
296
- if($this->serveImg(NOT_FOUND_IMAGE)){
297
- exit(0);
298
- } else {
299
- $this->error("Additionally, the 404 image that is configured could not be found or there was an error serving it.");
300
- }
301
- }
302
- if(ERROR_IMAGE){
303
- if($this->serveImg(ERROR_IMAGE)){
304
- exit(0);
305
- } else {
306
- $this->error("Additionally, the error image that is configured could not be found or there was an error serving it.");
307
- }
308
- }
309
-
310
- $this->serveErrors();
311
- exit(0);
312
- }
313
- return false;
314
- }
315
- protected function tryBrowserCache(){
316
- if(BROWSER_CACHE_DISABLE){ $this->debug(3, "Browser caching is disabled"); return false; }
317
- if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ){
318
- $this->debug(3, "Got a conditional get");
319
- $mtime = false;
320
- //We've already checked if the real file exists in the constructor
321
- if(! is_file($this->cachefile)){
322
- //If we don't have something cached, regenerate the cached image.
323
- return false;
324
- }
325
- if($this->localImageMTime){
326
- $mtime = $this->localImageMTime;
327
- $this->debug(3, "Local real file's modification time is $mtime");
328
- } 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
329
- $mtime = @filemtime($this->cachefile);
330
- $this->debug(3, "Cached file's modification time is $mtime");
331
- }
332
- if(! $mtime){ return false; }
333
-
334
- $iftime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
335
- $this->debug(3, "The conditional get's if-modified-since unixtime is $iftime");
336
- if($iftime < 1){
337
- $this->debug(3, "Got an invalid conditional get modified since time. Returning false.");
338
- return false;
339
- }
340
- if($iftime < $mtime){ //Real file or cache file has been modified since last request, so force refetch.
341
- $this->debug(3, "File has been modified since last fetch.");
342
- return false;
343
- } else { //Otherwise serve a 304
344
- $this->debug(3, "File has not been modified since last get, so serving a 304.");
345
- header ($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
346
- $this->debug(1, "Returning 304 not modified");
347
- return true;
348
- }
349
- }
350
- return false;
351
- }
352
- protected function tryServerCache(){
353
- $this->debug(3, "Trying server cache");
354
- if(file_exists($this->cachefile)){
355
- $this->debug(3, "Cachefile {$this->cachefile} exists");
356
- if($this->isURL){
357
- $this->debug(3, "This is an external request, so checking if the cachefile is empty which means the request failed previously.");
358
- if(filesize($this->cachefile) < 1){
359
- $this->debug(3, "Found an empty cachefile indicating a failed earlier request. Checking how old it is.");
360
- //Fetching error occured previously
361
- if(time() - @filemtime($this->cachefile) > WAIT_BETWEEN_FETCH_ERRORS){
362
- $this->debug(3, "File is older than " . WAIT_BETWEEN_FETCH_ERRORS . " seconds. Deleting and returning false so app can try and load file.");
363
- @unlink($this->cachefile);
364
- return false; //to indicate we didn't serve from cache and app should try and load
365
- } else {
366
- $this->debug(3, "Empty cachefile is still fresh so returning message saying we had an error fetching this image from remote host.");
367
- $this->set404();
368
- $this->error("An error occured fetching image.");
369
- return false;
370
- }
371
- }
372
- } else {
373
- $this->debug(3, "Trying to serve cachefile {$this->cachefile}");
374
- }
375
- if($this->serveCacheFile()){
376
- $this->debug(3, "Succesfully served cachefile {$this->cachefile}");
377
- return true;
378
- } else {
379
- $this->debug(3, "Failed to serve cachefile {$this->cachefile} - Deleting it from cache.");
380
- //Image serving failed. We can't retry at this point, but lets remove it from cache so the next request recreates it
381
- @unlink($this->cachefile);
382
- return true;
383
- }
384
- }
385
- }
386
- protected function error($err){
387
- $this->debug(3, "Adding error message: $err");
388
- $this->errors[] = $err;
389
- return false;
390
-
391
- }
392
- protected function haveErrors(){
393
- if(sizeof($this->errors) > 0){
394
- return true;
395
- }
396
- return false;
397
- }
398
- protected function serveErrors(){
399
- $html = '<ul>';
400
- foreach($this->errors as $err){
401
- $html .= '<li>' . htmlentities($err) . '</li>';
402
- }
403
- $html .= '</ul>';
404
- header ($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
405
- echo '<h1>A TimThumb error has occured</h1>The following error(s) occured:<br />' . $html . '<br />';
406
- echo '<br />Query String : ' . htmlentities ($_SERVER['QUERY_STRING']);
407
- echo '<br />TimThumb version : ' . VERSION . '</pre>';
408
- }
409
- protected function serveInternalImage(){
410
- $this->debug(3, "Local image path is $this->localImage");
411
- if(! $this->localImage){
412
- $this->sanityFail("localImage not set after verifying it earlier in the code.");
413
- return false;
414
- }
415
- $fileSize = filesize($this->localImage);
416
- if($fileSize > MAX_FILE_SIZE){
417
- $this->error("The file you specified is greater than the maximum allowed file size.");
418
- return false;
419
- }
420
- if($fileSize <= 0){
421
- $this->error("The file you specified is <= 0 bytes.");
422
- return false;
423
- }
424
- $this->debug(3, "Calling processImageAndWriteToCache() for local image.");
425
- if($this->processImageAndWriteToCache($this->localImage)){
426
- $this->serveCacheFile();
427
- return true;
428
- } else {
429
- return false;
430
- }
431
- }
432
- protected function cleanCache(){
433
- $this->debug(3, "cleanCache() called");
434
- $lastCleanFile = $this->cacheDirectory . '/timthumb_cacheLastCleanTime.touch';
435
-
436
- //If this is a new timthumb installation we need to create the file
437
- if(! is_file($lastCleanFile)){
438
- $this->debug(1, "File tracking last clean doesn't exist. Creating $lastCleanFile");
439
- if (!touch($lastCleanFile)) {
440
- $this->error("Could note create cache clean timestamp file.");
441
- }
442
- return;
443
- }
444
- if(@filemtime($lastCleanFile) < (time() - FILE_CACHE_TIME_BETWEEN_CLEANS) ){ //Cache was last cleaned more than 1 day ago
445
- $this->debug(1, "Cache was last cleaned more than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago. Cleaning now.");
446
- // Very slight race condition here, but worst case we'll have 2 or 3 servers cleaning the cache simultaneously once a day.
447
- if (!touch($lastCleanFile)) {
448
- $this->error("Could note create cache clean timestamp file.");
449
- }
450
- $files = glob($this->cacheDirectory . '/*' . FILE_CACHE_SUFFIX);
451
- $timeAgo = time() - FILE_CACHE_MAX_FILE_AGE;
452
- foreach($files as $file){
453
- if(@filemtime($file) < $timeAgo){
454
- $this->debug(3, "Deleting cache file $file older than max age: " . FILE_CACHE_MAX_FILE_AGE . " seconds");
455
- @unlink($file);
456
- }
457
- }
458
- return true;
459
- } else {
460
- $this->debug(3, "Cache was cleaned less than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago so no cleaning needed.");
461
- }
462
- return false;
463
- }
464
- protected function processImageAndWriteToCache($localImage){
465
- $sData = getimagesize($localImage);
466
- $origType = $sData[2];
467
- $mimeType = $sData['mime'];
468
-
469
- $this->debug(3, "Mime type of image is $mimeType");
470
- if(! preg_match('/^image\/(?:gif|jpg|jpeg|png)$/i', $mimeType)){
471
- return $this->error("The image being resized is not a valid gif, jpg or png.");
472
- }
473
-
474
- if (!function_exists ('imagecreatetruecolor')) {
475
- return $this->error('GD Library Error: imagecreatetruecolor does not exist - please contact your webhost and ask them to install the GD library');
476
- }
477
-
478
- if (function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
479
- $imageFilters = array (
480
- 1 => array (IMG_FILTER_NEGATE, 0),
481
- 2 => array (IMG_FILTER_GRAYSCALE, 0),
482
- 3 => array (IMG_FILTER_BRIGHTNESS, 1),
483
- 4 => array (IMG_FILTER_CONTRAST, 1),
484
- 5 => array (IMG_FILTER_COLORIZE, 4),
485
- 6 => array (IMG_FILTER_EDGEDETECT, 0),
486
- 7 => array (IMG_FILTER_EMBOSS, 0),
487
- 8 => array (IMG_FILTER_GAUSSIAN_BLUR, 0),
488
- 9 => array (IMG_FILTER_SELECTIVE_BLUR, 0),
489
- 10 => array (IMG_FILTER_MEAN_REMOVAL, 0),
490
- 11 => array (IMG_FILTER_SMOOTH, 0),
491
- );
492
- }
493
-
494
- // get standard input properties
495
- $new_width = (int) abs ($this->param('w', 0));
496
- $new_height = (int) abs ($this->param('h', 0));
497
- $zoom_crop = (int) $this->param('zc', 1);
498
- $quality = (int) abs ($this->param('q', 90));
499
- $align = $this->cropTop ? 't' : $this->param('a', 'c');
500
- $filters = $this->param('f', '');
501
- $sharpen = (bool) $this->param('s', 0);
502
- $canvas_color = $this->param('cc', 'ffffff');
503
-
504
- // set default width and height if neither are set already
505
- if ($new_width == 0 && $new_height == 0) {
506
- $new_width = 100;
507
- $new_height = 100;
508
- }
509
-
510
- // ensure size limits can not be abused
511
- $new_width = min ($new_width, MAX_WIDTH);
512
- $new_height = min ($new_height, MAX_HEIGHT);
513
-
514
- // set memory limit to be able to have enough space to resize larger images
515
- $this->setMemoryLimit();
516
-
517
- // open the existing image
518
- $image = $this->openImage ($mimeType, $localImage);
519
- if ($image === false) {
520
- return $this->error('Unable to open image.');
521
- }
522
-
523
- // Get original width and height
524
- $width = imagesx ($image);
525
- $height = imagesy ($image);
526
- $origin_x = 0;
527
- $origin_y = 0;
528
-
529
- // generate new w/h if not provided
530
- if ($new_width && !$new_height) {
531
- $new_height = floor ($height * ($new_width / $width));
532
- } else if ($new_height && !$new_width) {
533
- $new_width = floor ($width * ($new_height / $height));
534
- }
535
-
536
- // scale down and add borders
537
- if ($zoom_crop == 3) {
538
-
539
- $final_height = $height * ($new_width / $width);
540
-
541
- if ($final_height > $new_height) {
542
- $new_width = $width * ($new_height / $height);
543
- } else {
544
- $new_height = $final_height;
545
- }
546
-
547
- }
548
-
549
- // create a new true color image
550
- $canvas = imagecreatetruecolor ($new_width, $new_height);
551
- imagealphablending ($canvas, false);
552
-
553
- if (strlen ($canvas_color) < 6) {
554
- $canvas_color = 'ffffff';
555
- }
556
-
557
- $canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
558
- $canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
559
- $canvas_color_B = hexdec (substr ($canvas_color, 2, 2));
560
-
561
- // Create a new transparent color for image
562
- $color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
563
-
564
- // Completely fill the background of the new image with allocated color.
565
- imagefill ($canvas, 0, 0, $color);
566
-
567
- // scale down and add borders
568
- if ($zoom_crop == 2) {
569
-
570
- $final_height = $height * ($new_width / $width);
571
-
572
- if ($final_height > $new_height) {
573
-
574
- $origin_x = $new_width / 2;
575
- $new_width = $width * ($new_height / $height);
576
- $origin_x = round ($origin_x - ($new_width / 2));
577
-
578
- } else {
579
-
580
- $origin_y = $new_height / 2;
581
- $new_height = $final_height;
582
- $origin_y = round ($origin_y - ($new_height / 2));
583
-
584
- }
585
-
586
- }
587
-
588
- // Restore transparency blending
589
- imagesavealpha ($canvas, true);
590
-
591
- if ($zoom_crop > 0) {
592
-
593
- $src_x = $src_y = 0;
594
- $src_w = $width;
595
- $src_h = $height;
596
-
597
- $cmp_x = $width / $new_width;
598
- $cmp_y = $height / $new_height;
599
-
600
- // calculate x or y coordinate and width or height of source
601
- if ($cmp_x > $cmp_y) {
602
-
603
- $src_w = round ($width / $cmp_x * $cmp_y);
604
- $src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
605
-
606
- } else if ($cmp_y > $cmp_x) {
607
-
608
- $src_h = round ($height / $cmp_y * $cmp_x);
609
- $src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
610
-
611
- }
612
-
613
- // positional cropping!
614
- if ($align) {
615
- if (strpos ($align, 't') !== false) {
616
- $src_y = 0;
617
- }
618
- if (strpos ($align, 'b') !== false) {
619
- $src_y = $height - $src_h;
620
- }
621
- if (strpos ($align, 'l') !== false) {
622
- $src_x = 0;
623
- }
624
- if (strpos ($align, 'r') !== false) {
625
- $src_x = $width - $src_w;
626
- }
627
- }
628
-
629
- imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
630
-
631
- } else {
632
-
633
- // copy and resize part of an image with resampling
634
- imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
635
-
636
- }
637
-
638
- if ($filters != '' && function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
639
- // apply filters to image
640
- $filterList = explode ('|', $filters);
641
- foreach ($filterList as $fl) {
642
-
643
- $filterSettings = explode (',', $fl);
644
- if (isset ($imageFilters[$filterSettings[0]])) {
645
-
646
- for ($i = 0; $i < 4; $i ++) {
647
- if (!isset ($filterSettings[$i])) {
648
- $filterSettings[$i] = null;
649
- } else {
650
- $filterSettings[$i] = (int) $filterSettings[$i];
651
- }
652
- }
653
-
654
- switch ($imageFilters[$filterSettings[0]][1]) {
655
-
656
- case 1:
657
-
658
- imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
659
- break;
660
-
661
- case 2:
662
-
663
- imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
664
- break;
665
-
666
- case 3:
667
-
668
- imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
669
- break;
670
-
671
- case 4:
672
-
673
- imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3], $filterSettings[4]);
674
- break;
675
-
676
- default:
677
-
678
- imagefilter ($canvas, $imageFilters[$filterSettings[0]][0]);
679
- break;
680
-
681
- }
682
- }
683
- }
684
- }
685
-
686
- // sharpen image
687
- if ($sharpen && function_exists ('imageconvolution')) {
688
-
689
- $sharpenMatrix = array (
690
- array (-1,-1,-1),
691
- array (-1,16,-1),
692
- array (-1,-1,-1),
693
- );
694
-
695
- $divisor = 8;
696
- $offset = 0;
697
-
698
- imageconvolution ($canvas, $sharpenMatrix, $divisor, $offset);
699
-
700
- }
701
- //Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
702
- if ( (IMAGETYPE_PNG == $origType || IMAGETYPE_GIF == $origType) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
703
- imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
704
- }
705
-
706
- $imgType = "";
707
- $tempfile = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
708
- if(preg_match('/^image\/(?:jpg|jpeg)$/i', $mimeType)){
709
- $imgType = 'jpg';
710
- imagejpeg($canvas, $tempfile, $quality);
711
-
712
- // Add sRGB ICC profile
713
- $icc = new JPEG_ICC();
714
- $icc->LoadFromJPEG('in-srgb.jpg');
715
- $icc->SaveToJPEG($tempfile);
716
-
717
- } else if(preg_match('/^image\/png$/i', $mimeType)){
718
- $imgType = 'png';
719
- imagepng($canvas, $tempfile, floor($quality * 0.09));
720
- } else if(preg_match('/^image\/gif$/i', $mimeType)){
721
- $imgType = 'gif';
722
- imagegif($canvas, $tempfile);
723
- } else {
724
- return $this->sanityFail("Could not match mime type after verifying it previously.");
725
- }
726
-
727
- if($imgType == 'png' && OPTIPNG_ENABLED && OPTIPNG_PATH && @is_file(OPTIPNG_PATH)){
728
- $exec = OPTIPNG_PATH;
729
- $this->debug(3, "optipng'ing $tempfile");
730
- $presize = filesize($tempfile);
731
- $out = `$exec -o1 $tempfile`; //you can use up to -o7 but it really slows things down
732
- clearstatcache();
733
- $aftersize = filesize($tempfile);
734
- $sizeDrop = $presize - $aftersize;
735
- if($sizeDrop > 0){
736
- $this->debug(1, "optipng reduced size by $sizeDrop");
737
- } else if($sizeDrop < 0){
738
- $this->debug(1, "optipng increased size! Difference was: $sizeDrop");
739
- } else {
740
- $this->debug(1, "optipng did not change image size.");
741
- }
742
- } else if($imgType == 'png' && PNGCRUSH_ENABLED && PNGCRUSH_PATH && @is_file(PNGCRUSH_PATH)){
743
- $exec = PNGCRUSH_PATH;
744
- $tempfile2 = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
745
- $this->debug(3, "pngcrush'ing $tempfile to $tempfile2");
746
- $out = `$exec $tempfile $tempfile2`;
747
- $todel = "";
748
- if(is_file($tempfile2)){
749
- $sizeDrop = filesize($tempfile) - filesize($tempfile2);
750
- if($sizeDrop > 0){
751
- $this->debug(1, "pngcrush was succesful and gave a $sizeDrop byte size reduction");
752
- $todel = $tempfile;
753
- $tempfile = $tempfile2;
754
- } else {
755
- $this->debug(1, "pngcrush did not reduce file size. Difference was $sizeDrop bytes.");
756
- $todel = $tempfile2;
757
- }
758
- } else {
759
- $this->debug(3, "pngcrush failed with output: $out");
760
- $todel = $tempfile2;
761
- }
762
- @unlink($todel);
763
- }
764
-
765
- $this->debug(3, "Rewriting image with security header.");
766
- $tempfile4 = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
767
- $context = stream_context_create ();
768
- $fp = fopen($tempfile,'r',0,$context);
769
- file_put_contents($tempfile4, $this->filePrependSecurityBlock . $imgType . ' ?' . '>'); //6 extra bytes, first 3 being image type
770
- file_put_contents($tempfile4, $fp, FILE_APPEND);
771
- fclose($fp);
772
- @unlink($tempfile);
773
- $this->debug(3, "Locking and replacing cache file.");
774
- $lockFile = $this->cachefile . '.lock';
775
- $fh = fopen($lockFile, 'w');
776
- if(! $fh){
777
- return $this->error("Could not open the lockfile for writing an image.");
778
- }
779
- if(flock($fh, LOCK_EX)){
780
- @unlink($this->cachefile); //rename generally overwrites, but doing this in case of platform specific quirks. File might not exist yet.
781
- rename($tempfile4, $this->cachefile);
782
- flock($fh, LOCK_UN);
783
- fclose($fh);
784
- @unlink($lockFile);
785
- } else {
786
- fclose($fh);
787
- @unlink($lockFile);
788
- @unlink($tempfile4);
789
- return $this->error("Could not get a lock for writing.");
790
- }
791
- $this->debug(3, "Done image replace with security header. Cleaning up and running cleanCache()");
792
- imagedestroy($canvas);
793
- imagedestroy($image);
794
- return true;
795
- }
796
- protected function calcDocRoot(){
797
- $docRoot = @$_SERVER['DOCUMENT_ROOT'];
798
- if(!isset($docRoot)){
799
- $this->debug(3, "DOCUMENT_ROOT is not set. This is probably windows. Starting search 1.");
800
- if(isset($_SERVER['SCRIPT_FILENAME'])){
801
- $docRoot = str_replace( '\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF'])));
802
- $this->debug(3, "Generated docRoot using SCRIPT_FILENAME and PHP_SELF as: $docRoot");
803
- }
804
- }
805
- if(!isset($docRoot)){
806
- $this->debug(3, "DOCUMENT_ROOT still is not set. Starting search 2.");
807
- if(isset($_SERVER['PATH_TRANSLATED'])){
808
- $docRoot = str_replace( '\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0-strlen($_SERVER['PHP_SELF'])));
809
- $this->debug(3, "Generated docRoot using PATH_TRANSLATED and PHP_SELF as: $docRoot");
810
- }
811
- }
812
- if($docRoot && $_SERVER['DOCUMENT_ROOT'] != '/'){ $docRoot = preg_replace('/\/$/', '', $docRoot); }
813
- $this->debug(3, "Doc root is: " . $docRoot);
814
- $this->docRoot = $docRoot;
815
-
816
- }
817
- protected function getLocalImagePath($src){
818
- $src = preg_replace('/^\//', '', $src); //strip off the leading '/'
819
- $realDocRoot = realpath($this->docRoot);
820
- if(! $this->docRoot){
821
- $this->debug(3, "We have no document root set, so as a last resort, lets check if the image is in the current dir and serve that.");
822
- //We don't support serving images outside the current dir if we don't have a doc root for security reasons.
823
- $file = preg_replace('/^.*?([^\/\\\\]+)$/', '$1', $src); //strip off any path info and just leave the filename.
824
- if(is_file($file)){
825
- return realpath($file);
826
- }
827
- return $this->error("Could not find your website document root and the file specified doesn't exist in timthumbs directory. We don't support serving files outside timthumb's directory without a document root for security reasons.");
828
- } //Do not go past this point without docRoot set
829
-
830
- //Try src under docRoot
831
- if(file_exists ($this->docRoot . '/' . $src)) {
832
- $this->debug(3, "Found file as " . $this->docRoot . '/' . $src);
833
- $real = realpath($this->docRoot . '/' . $src);
834
- if(stripos($real, $realDocRoot) === 0){
835
- return $real;
836
- } else {
837
- $this->debug(1, "Security block: The file specified occurs outside the document root.");
838
- //allow search to continue
839
- }
840
- }
841
- //Check absolute paths and then verify the real path is under doc root
842
- $absolute = realpath('/' . $src);
843
- if($absolute && file_exists($absolute)){ //realpath does file_exists check, so can probably skip the exists check here
844
- $this->debug(3, "Found absolute path: $absolute");
845
- if(! $this->docRoot){ $this->sanityFail("docRoot not set when checking absolute path."); }
846
- if(stripos($absolute, $realDocRoot) === 0){
847
- return $absolute;
848
- } else {
849
- $this->debug(1, "Security block: The file specified occurs outside the document root.");
850
- //and continue search
851
- }
852
- }
853
-
854
- $base = $this->docRoot;
855
-
856
- // account for Windows directory structure
857
- if (strstr($_SERVER['SCRIPT_FILENAME'],':')) {
858
- $sub_directories = explode('\\', str_replace($this->docRoot, '', $_SERVER['SCRIPT_FILENAME']));
859
- } else {
860
- $sub_directories = explode('/', str_replace($this->docRoot, '', $_SERVER['SCRIPT_FILENAME']));
861
- }
862
-
863
- foreach ($sub_directories as $sub){
864
- $base .= $sub . '/';
865
- $this->debug(3, "Trying file as: " . $base . $src);
866
- if(file_exists($base . $src)){
867
- $this->debug(3, "Found file as: " . $base . $src);
868
- $real = realpath($base . $src);
869
- if(stripos($real, $realDocRoot) === 0){
870
- return $real;
871
- } else {
872
- $this->debug(1, "Security block: The file specified occurs outside the document root.");
873
- //And continue search
874
- }
875
- }
876
- }
877
- return false;
878
- }
879
- protected function toDelete($name){
880
- $this->debug(3, "Scheduling file $name to delete on destruct.");
881
- $this->toDeletes[] = $name;
882
- }
883
- protected function serveWebshot(){
884
- $this->debug(3, "Starting serveWebshot");
885
- $instr = "Please follow the instructions at http://code.google.com/p/timthumb/ to set your server up for taking website screenshots.";
886
- if(! is_file(WEBSHOT_CUTYCAPT)){
887
- return $this->error("CutyCapt is not installed. $instr");
888
- }
889
- if(! is_file(WEBSHOT_XVFB)){
890
- return $this->Error("Xvfb is not installed. $instr");
891
- }
892
- $cuty = WEBSHOT_CUTYCAPT;
893
- $xv = WEBSHOT_XVFB;
894
- $screenX = WEBSHOT_SCREEN_X;
895
- $screenY = WEBSHOT_SCREEN_Y;
896
- $colDepth = WEBSHOT_COLOR_DEPTH;
897
- $format = WEBSHOT_IMAGE_FORMAT;
898
- $timeout = WEBSHOT_TIMEOUT * 1000;
899
- $ua = WEBSHOT_USER_AGENT;
900
- $jsOn = WEBSHOT_JAVASCRIPT_ON ? 'on' : 'off';
901
- $javaOn = WEBSHOT_JAVA_ON ? 'on' : 'off';
902
- $pluginsOn = WEBSHOT_PLUGINS_ON ? 'on' : 'off';
903
- $proxy = WEBSHOT_PROXY ? ' --http-proxy=' . WEBSHOT_PROXY : '';
904
- $tempfile = tempnam($this->cacheDirectory, 'timthumb_webshot');
905
- $url = $this->src;
906
- if(! preg_match('/^https?:\/\/[a-zA-Z0-9\.\-]+/i', $url)){
907
- return $this->error("Invalid URL supplied.");
908
- }
909
- $url = preg_replace('/[^A-Za-z0-9\-\.\_\~:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]+/', '', $url); //RFC 3986
910
- //Very important we don't allow injection of shell commands here. URL is between quotes and we are only allowing through chars allowed by a the RFC
911
- // which AFAIKT can't be used for shell injection.
912
- if(WEBSHOT_XVFB_RUNNING){
913
- putenv('DISPLAY=:100.0');
914
- $command = "$cuty $proxy --max-wait=$timeout --user-agent=\"$ua\" --javascript=$jsOn --java=$javaOn --plugins=$pluginsOn --js-can-open-windows=off --url=\"$url\" --out-format=$format --out=$tempfile";
915
- } else {
916
- $command = "$xv --server-args=\"-screen 0, {$screenX}x{$screenY}x{$colDepth}\" $cuty $proxy --max-wait=$timeout --user-agent=\"$ua\" --javascript=$jsOn --java=$javaOn --plugins=$pluginsOn --js-can-open-windows=off --url=\"$url\" --out-format=$format --out=$tempfile";
917
- }
918
- $this->debug(3, "Executing command: $command");
919
- $out = `$command`;
920
- $this->debug(3, "Received output: $out");
921
- if(! is_file($tempfile)){
922
- $this->set404();
923
- return $this->error("The command to create a thumbnail failed.");
924
- }
925
- $this->cropTop = true;
926
- if($this->processImageAndWriteToCache($tempfile)){
927
- $this->debug(3, "Image processed succesfully. Serving from cache");
928
- return $this->serveCacheFile();
929
- } else {
930
- return false;
931
- }
932
- }
933
- protected function serveExternalImage(){
934
- if(! preg_match('/^https?:\/\/[a-zA-Z0-9\-\.]+/i', $this->src)){
935
- $this->error("Invalid URL supplied.");
936
- return false;
937
- }
938
- $tempfile = tempnam($this->cacheDirectory, 'timthumb');
939
- $this->debug(3, "Fetching external image into temporary file $tempfile");
940
- $this->toDelete($tempfile);
941
- #fetch file here
942
- if(! $this->getURL($this->src, $tempfile)){
943
- @unlink($this->cachefile);
944
- touch($this->cachefile);
945
- $this->debug(3, "Error fetching URL: " . $this->lastURLError);
946
- $this->error("Error reading the URL you specified from remote host." . $this->lastURLError);
947
- return false;
948
- }
949
-
950
- $mimeType = $this->getMimeType($tempfile);
951
- if(! preg_match("/^image\/(?:jpg|jpeg|gif|png)$/i", $mimeType)){
952
- $this->debug(3, "Remote file has invalid mime type: $mimeType");
953
- @unlink($this->cachefile);
954
- touch($this->cachefile);
955
- $this->error("The remote file is not a valid image.");
956
- return false;
957
- }
958
- if($this->processImageAndWriteToCache($tempfile)){
959
- $this->debug(3, "Image processed succesfully. Serving from cache");
960
- return $this->serveCacheFile();
961
- } else {
962
- return false;
963
- }
964
- }
965
- public static function curlWrite($h, $d){
966
- fwrite(self::$curlFH, $d);
967
- self::$curlDataWritten += strlen($d);
968
- if(self::$curlDataWritten > MAX_FILE_SIZE){
969
- return 0;
970
- } else {
971
- return strlen($d);
972
- }
973
- }
974
- protected function serveCacheFile(){
975
- $this->debug(3, "Serving {$this->cachefile}");
976
- if(! is_file($this->cachefile)){
977
- $this->error("serveCacheFile called in timthumb but we couldn't find the cached file.");
978
- return false;
979
- }
980
- $fp = fopen($this->cachefile, 'rb');
981
- if(! $fp){ return $this->error("Could not open cachefile."); }
982
- fseek($fp, strlen($this->filePrependSecurityBlock), SEEK_SET);
983
- $imgType = fread($fp, 3);
984
- fseek($fp, 3, SEEK_CUR);
985
- if(ftell($fp) != strlen($this->filePrependSecurityBlock) + 6){
986
- @unlink($this->cachefile);
987
- return $this->error("The cached image file seems to be corrupt.");
988
- }
989
- $imageDataSize = filesize($this->cachefile) - (strlen($this->filePrependSecurityBlock) + 6);
990
- $this->sendImageHeaders($imgType, $imageDataSize);
991
- $bytesSent = @fpassthru($fp);
992
- fclose($fp);
993
- if($bytesSent > 0){
994
- return true;
995
- }
996
- $content = file_get_contents ($this->cachefile);
997
- if ($content != FALSE) {
998
- $content = substr($content, strlen($this->filePrependSecurityBlock) + 6);
999
- echo $content;
1000
- $this->debug(3, "Served using file_get_contents and echo");
1001
- return true;
1002
- } else {
1003
- $this->error("Cache file could not be loaded.");
1004
- return false;
1005
- }
1006
- }
1007
- protected function sendImageHeaders($mimeType, $dataSize){
1008
- if(! preg_match('/^image\//i', $mimeType)){
1009
- $mimeType = 'image/' . $mimeType;
1010
- }
1011
- if(strtolower($mimeType) == 'image/jpg'){
1012
- $mimeType = 'image/jpeg';
1013
- }
1014
- $gmdate_expires = gmdate ('D, d M Y H:i:s', strtotime ('now +10 days')) . ' GMT';
1015
- $gmdate_modified = gmdate ('D, d M Y H:i:s') . ' GMT';
1016
- // send content headers then display image
1017
- header ('Content-Type: ' . $mimeType);
1018
- header ('Accept-Ranges: none'); //Changed this because we don't accept range requests
1019
- header ('Last-Modified: ' . $gmdate_modified);
1020
- header ('Content-Length: ' . $dataSize);
1021
- if(BROWSER_CACHE_DISABLE){
1022
- $this->debug(3, "Browser cache is disabled so setting non-caching headers.");
1023
- header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
1024
- header("Pragma: no-cache");
1025
- header('Expires: ' . gmdate ('D, d M Y H:i:s', time()));
1026
- } else {
1027
- $this->debug(3, "Browser caching is enabled");
1028
- header('Cache-Control: max-age=' . BROWSER_CACHE_MAX_AGE . ', must-revalidate');
1029
- header('Expires: ' . $gmdate_expires);
1030
- }
1031
- return true;
1032
- }
1033
- protected function securityChecks(){
1034
- }
1035
- protected function param($property, $default = ''){
1036
- if (isset ($_GET[$property])) {
1037
- return $_GET[$property];
1038
- } else {
1039
- return $default;
1040
- }
1041
- }
1042
- protected function openImage($mimeType, $src){
1043
- switch ($mimeType) {
1044
- case 'image/jpg': //This isn't a valid mime type so we should probably remove it
1045
- case 'image/jpeg':
1046
- $image = imagecreatefromjpeg ($src);
1047
- break;
1048
-
1049
- case 'image/png':
1050
- $image = imagecreatefrompng ($src);
1051
- break;
1052
-
1053
- case 'image/gif':
1054
- $image = imagecreatefromgif ($src);
1055
- break;
1056
- }
1057
-
1058
- return $image;
1059
- }
1060
- protected function getIP(){
1061
- $rem = @$_SERVER["REMOTE_ADDR"];
1062
- $ff = @$_SERVER["HTTP_X_FORWARDED_FOR"];
1063
- $ci = @$_SERVER["HTTP_CLIENT_IP"];
1064
- if(preg_match('/^(?:192\.168|172\.16|10\.|127\.)/', $rem)){
1065
- if($ff){ return $ff; }
1066
- if($ci){ return $ci; }
1067
- return $rem;
1068
- } else {
1069
- if($rem){ return $rem; }
1070
- if($ff){ return $ff; }
1071
- if($ci){ return $ci; }
1072
- return "UNKNOWN";
1073
- }
1074
- }
1075
- protected function debug($level, $msg){
1076
- if(DEBUG_ON && $level <= DEBUG_LEVEL){
1077
- $execTime = sprintf('%.6f', microtime(true) - $this->startTime);
1078
- $tick = sprintf('%.6f', 0);
1079
- if($this->lastBenchTime > 0){
1080
- $tick = sprintf('%.6f', microtime(true) - $this->lastBenchTime);
1081
- }
1082
- $this->lastBenchTime = microtime(true);
1083
- error_log("TimThumb Debug line " . __LINE__ . " [$execTime : $tick]: $msg");
1084
- }
1085
- }
1086
- protected function sanityFail($msg){
1087
- return $this->error("There is a problem in the timthumb code. Message: Please report this error at <a href='http://code.google.com/p/timthumb/issues/list'>timthumb's bug tracking page</a>: $msg");
1088
- }
1089
- protected function getMimeType($file){
1090
- $info = getimagesize($file);
1091
- if(is_array($info) && $info['mime']){
1092
- return $info['mime'];
1093
- }
1094
- return '';
1095
- }
1096
- protected function setMemoryLimit(){
1097
- $inimem = ini_get('memory_limit');
1098
- $inibytes = timthumb::returnBytes($inimem);
1099
- $ourbytes = timthumb::returnBytes(MEMORY_LIMIT);
1100
- if($inibytes < $ourbytes){
1101
- ini_set ('memory_limit', MEMORY_LIMIT);
1102
- $this->debug(3, "Increased memory from $inimem to " . MEMORY_LIMIT);
1103
- } else {
1104
- $this->debug(3, "Not adjusting memory size because the current setting is " . $inimem . " and our size of " . MEMORY_LIMIT . " is smaller.");
1105
- }
1106
- }
1107
- protected static function returnBytes($size_str){
1108
- switch (substr ($size_str, -1))
1109
- {
1110
- case 'M': case 'm': return (int)$size_str * 1048576;
1111
- case 'K': case 'k': return (int)$size_str * 1024;
1112
- case 'G': case 'g': return (int)$size_str * 1073741824;
1113
- default: return $size_str;
1114
- }
1115
- }
1116
- protected function getURL($url, $tempfile){
1117
- $this->lastURLError = false;
1118
- $url = preg_replace('/ /', '%20', $url);
1119
- if(function_exists('curl_init')){
1120
- $this->debug(3, "Curl is installed so using it to fetch URL.");
1121
- self::$curlFH = fopen($tempfile, 'w');
1122
- if(! self::$curlFH){
1123
- $this->error("Could not open $tempfile for writing.");
1124
- return false;
1125
- }
1126
- self::$curlDataWritten = 0;
1127
- $this->debug(3, "Fetching url with curl: $url");
1128
- $curl = curl_init($url);
1129
- curl_setopt ($curl, CURLOPT_TIMEOUT, CURL_TIMEOUT);
1130
- curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30");
1131
- curl_setopt ($curl, CURLOPT_RETURNTRANSFER, TRUE);
1132
- curl_setopt ($curl, CURLOPT_HEADER, 0);
1133
- curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
1134
- curl_setopt ($curl, CURLOPT_WRITEFUNCTION, 'timthumb::curlWrite');
1135
- @curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, true);
1136
- @curl_setopt ($curl, CURLOPT_MAXREDIRS, 10);
1137
-
1138
- $curlResult = curl_exec($curl);
1139
- fclose(self::$curlFH);
1140
- $httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
1141
- if($httpStatus == 404){
1142
- $this->set404();
1143
- }
1144
- if($curlResult){
1145
- curl_close($curl);
1146
- return true;
1147
- } else {
1148
- $this->lastURLError = curl_error($curl);
1149
- curl_close($curl);
1150
- return false;
1151
- }
1152
- } else {
1153
- $img = @file_get_contents ($url);
1154
- if($img === false){
1155
- $err = error_get_last();
1156
- if(is_array($err) && $err['message']){
1157
- $this->lastURLError = $err['message'];
1158
- } else {
1159
- $this->lastURLError = $err;
1160
- }
1161
- if(preg_match('/404/', $this->lastURLError)){
1162
- $this->set404();
1163
- }
1164
-
1165
- return false;
1166
- }
1167
- if(! file_put_contents($tempfile, $img)){
1168
- $this->error("Could not write to $tempfile.");
1169
- return false;
1170
- }
1171
- return true;
1172
- }
1173
-
1174
- }
1175
- protected function serveImg($file){
1176
- $s = getimagesize($file);
1177
- if(! ($s && $s['mime'])){
1178
- return false;
1179
- }
1180
- header ('Content-Type: ' . $s['mime']);
1181
- header ('Content-Length: ' . filesize($file) );
1182
- header ('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
1183
- header ("Pragma: no-cache");
1184
- $bytes = @readfile($file);
1185
- if($bytes > 0){
1186
- return true;
1187
- }
1188
- $content = @file_get_contents ($file);
1189
- if ($content != FALSE){
1190
- echo $content;
1191
- return true;
1192
- }
1193
- return false;
1194
-
1195
- }
1196
- protected function set404(){
1197
- $this->is404 = true;
1198
- }
1199
- protected function is404(){
1200
- return $this->is404;
1201
- }
1202
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * TimThumb by Ben Gillbanks and Mark Maunder
4
+ * Based on work done by Tim McDaniels and Darren Hoyt
5
+ * http://code.google.com/p/timthumb/
6
+ *
7
+ * GNU General Public License, version 2
8
+ * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
9
+ *
10
+ * Examples and documentation available on the project homepage
11
+ * http://www.binarymoon.co.uk/projects/timthumb/
12
+ *
13
+ * $Rev$
14
+ */
15
+
16
+ /*
17
+ * --- TimThumb CONFIGURATION ---
18
+ * To edit the configs it is best to create a file called timthumb-config.php
19
+ * and define variables you want to customize in there. It will automatically be
20
+ * loaded by timthumb. This will save you having to re-edit these variables
21
+ * everytime you download a new version
22
+ */
23
+ define ('VERSION', '2.8.11'); // Version of this script
24
+ //Load a config file if it exists. Otherwise, use the values below
25
+ if( file_exists(dirname(__FILE__) . '/timthumb-config.php')) require_once('timthumb-config.php');
26
+ if(! defined('DEBUG_ON') ) define ('DEBUG_ON', false); // Enable debug logging to web server error log (STDERR)
27
+ if(! defined('DEBUG_LEVEL') ) define ('DEBUG_LEVEL', 1); // Debug level 1 is less noisy and 3 is the most noisy
28
+ if(! defined('MEMORY_LIMIT') ) define ('MEMORY_LIMIT', '30M'); // Set PHP memory limit
29
+ if(! defined('BLOCK_EXTERNAL_LEECHERS') ) define ('BLOCK_EXTERNAL_LEECHERS', false); // If the image or webshot is being loaded on an external site, display a red "No Hotlinking" gif.
30
+
31
+ //Image fetching and caching
32
+ if(! defined('ALLOW_EXTERNAL') ) define ('ALLOW_EXTERNAL', TRUE); // Allow image fetching from external websites. Will check against ALLOWED_SITES if ALLOW_ALL_EXTERNAL_SITES is false
33
+ if(! defined('ALLOW_ALL_EXTERNAL_SITES') ) define ('ALLOW_ALL_EXTERNAL_SITES', false); // Less secure.
34
+ if(! defined('FILE_CACHE_ENABLED') ) define ('FILE_CACHE_ENABLED', TRUE); // Should we store resized/modified images on disk to speed things up?
35
+ if(! defined('FILE_CACHE_TIME_BETWEEN_CLEANS')) define ('FILE_CACHE_TIME_BETWEEN_CLEANS', 86400); // How often the cache is cleaned
36
+
37
+ if(! defined('FILE_CACHE_MAX_FILE_AGE') ) define ('FILE_CACHE_MAX_FILE_AGE', 86400); // How old does a file have to be to be deleted from the cache
38
+ if(! defined('FILE_CACHE_SUFFIX') ) define ('FILE_CACHE_SUFFIX', '.timthumb.txt'); // What to put at the end of all files in the cache directory so we can identify them
39
+ if(! defined('FILE_CACHE_PREFIX') ) define ('FILE_CACHE_PREFIX', 'timthumb'); // What to put at the beg of all files in the cache directory so we can identify them
40
+ if(! defined('FILE_CACHE_DIRECTORY') ) define ('FILE_CACHE_DIRECTORY', './cache'); // Directory where images are cached. Left blank it will use the system temporary directory (which is better for security)
41
+ if(! defined('MAX_FILE_SIZE') ) define ('MAX_FILE_SIZE', 10485760); // 10 Megs is 10485760. This is the max internal or external file size that we'll process.
42
+ if(! defined('CURL_TIMEOUT') ) define ('CURL_TIMEOUT', 20); // Timeout duration for Curl. This only applies if you have Curl installed and aren't using PHP's default URL fetching mechanism.
43
+ if(! defined('WAIT_BETWEEN_FETCH_ERRORS') ) define ('WAIT_BETWEEN_FETCH_ERRORS', 3600); // Time to wait between errors fetching remote file
44
+
45
+ //Browser caching
46
+ if(! defined('BROWSER_CACHE_MAX_AGE') ) define ('BROWSER_CACHE_MAX_AGE', 864000); // Time to cache in the browser
47
+ if(! defined('BROWSER_CACHE_DISABLE') ) define ('BROWSER_CACHE_DISABLE', false); // Use for testing if you want to disable all browser caching
48
+
49
+ //Image size and defaults
50
+ if(! defined('MAX_WIDTH') ) define ('MAX_WIDTH', 1500); // Maximum image width
51
+ if(! defined('MAX_HEIGHT') ) define ('MAX_HEIGHT', 1500); // Maximum image height
52
+ if(! defined('NOT_FOUND_IMAGE') ) define ('NOT_FOUND_IMAGE', ''); // Image to serve if any 404 occurs
53
+ if(! defined('ERROR_IMAGE') ) define ('ERROR_IMAGE', ''); // Image to serve if an error occurs instead of showing error message
54
+ if(! defined('PNG_IS_TRANSPARENT') ) define ('PNG_IS_TRANSPARENT', FALSE); // Define if a png image should have a transparent background color. Use False value if you want to display a custom coloured canvas_colour
55
+ if(! defined('DEFAULT_Q') ) define ('DEFAULT_Q', 90); // Default image quality. Allows overrid in timthumb-config.php
56
+ if(! defined('DEFAULT_ZC') ) define ('DEFAULT_ZC', 1); // Default zoom/crop setting. Allows overrid in timthumb-config.php
57
+ if(! defined('DEFAULT_F') ) define ('DEFAULT_F', ''); // Default image filters. Allows overrid in timthumb-config.php
58
+ if(! defined('DEFAULT_S') ) define ('DEFAULT_S', 0); // Default sharpen value. Allows overrid in timthumb-config.php
59
+ if(! defined('DEFAULT_CC') ) define ('DEFAULT_CC', 'ffffff'); // Default canvas colour. Allows overrid in timthumb-config.php
60
+
61
+
62
+ //Image compression is enabled if either of these point to valid paths
63
+
64
+ //These are now disabled by default because the file sizes of PNGs (and GIFs) are much smaller than we used to generate.
65
+ //They only work for PNGs. GIFs and JPEGs are not affected.
66
+ if(! defined('OPTIPNG_ENABLED') ) define ('OPTIPNG_ENABLED', false);
67
+ if(! defined('OPTIPNG_PATH') ) define ('OPTIPNG_PATH', '/usr/bin/optipng'); //This will run first because it gives better compression than pngcrush.
68
+ if(! defined('PNGCRUSH_ENABLED') ) define ('PNGCRUSH_ENABLED', false);
69
+ if(! defined('PNGCRUSH_PATH') ) define ('PNGCRUSH_PATH', '/usr/bin/pngcrush'); //This will only run if OPTIPNG_PATH is not set or is not valid
70
+
71
+ /*
72
+ -------====Website Screenshots configuration - BETA====-------
73
+
74
+ If you just want image thumbnails and don't want website screenshots, you can safely leave this as is.
75
+
76
+ If you would like to get website screenshots set up, you will need root access to your own server.
77
+
78
+ Enable ALLOW_ALL_EXTERNAL_SITES so you can fetch any external web page. This is more secure now that we're using a non-web folder for cache.
79
+ Enable BLOCK_EXTERNAL_LEECHERS so that your site doesn't generate thumbnails for the whole Internet.
80
+
81
+ Instructions to get website screenshots enabled on Ubuntu Linux:
82
+
83
+ 1. Install Xvfb with the following command: sudo apt-get install subversion libqt4-webkit libqt4-dev g++ xvfb
84
+ 2. Go to a directory where you can download some code
85
+ 3. Check-out the latest version of CutyCapt with the following command: svn co https://cutycapt.svn.sourceforge.net/svnroot/cutycapt
86
+ 4. Compile CutyCapt by doing: cd cutycapt/CutyCapt
87
+ 5. qmake
88
+ 6. make
89
+ 7. cp CutyCapt /usr/local/bin/
90
+ 8. Test it by running: xvfb-run --server-args="-screen 0, 1024x768x24" CutyCapt --url="http://markmaunder.com/" --out=test.png
91
+ 9. If you get a file called test.png with something in it, it probably worked. Now test the script by accessing it as follows:
92
+ 10. http://yoursite.com/path/to/timthumb.php?src=http://markmaunder.com/&webshot=1
93
+
94
+ Notes on performance:
95
+ The first time a webshot loads, it will take a few seconds.
96
+ From then on it uses the regular timthumb caching mechanism with the configurable options above
97
+ and loading will be very fast.
98
+
99
+ --ADVANCED USERS ONLY--
100
+ If you'd like a slight speedup (about 25%) and you know Linux, you can run the following command which will keep Xvfb running in the background.
101
+ nohup Xvfb :100 -ac -nolisten tcp -screen 0, 1024x768x24 > /dev/null 2>&1 &
102
+ Then set WEBSHOT_XVFB_RUNNING = true below. This will save your server having to fire off a new Xvfb server and shut it down every time a new shot is generated.
103
+ You will need to take responsibility for keeping Xvfb running in case it crashes. (It seems pretty stable)
104
+ You will also need to take responsibility for server security if you're running Xvfb as root.
105
+
106
+
107
+ */
108
+ if(! defined('WEBSHOT_ENABLED') ) define ('WEBSHOT_ENABLED', false); //Beta feature. Adding webshot=1 to your query string will cause the script to return a browser screenshot rather than try to fetch an image.
109
+ if(! defined('WEBSHOT_CUTYCAPT') ) define ('WEBSHOT_CUTYCAPT', '/usr/local/bin/CutyCapt'); //The path to CutyCapt.
110
+ if(! defined('WEBSHOT_XVFB') ) define ('WEBSHOT_XVFB', '/usr/bin/xvfb-run'); //The path to the Xvfb server
111
+ if(! defined('WEBSHOT_SCREEN_X') ) define ('WEBSHOT_SCREEN_X', '1024'); //1024 works ok
112
+ if(! defined('WEBSHOT_SCREEN_Y') ) define ('WEBSHOT_SCREEN_Y', '768'); //768 works ok
113
+ if(! defined('WEBSHOT_COLOR_DEPTH') ) define ('WEBSHOT_COLOR_DEPTH', '24'); //I haven't tested anything besides 24
114
+ if(! defined('WEBSHOT_IMAGE_FORMAT') ) define ('WEBSHOT_IMAGE_FORMAT', 'png'); //png is about 2.5 times the size of jpg but is a LOT better quality
115
+ if(! defined('WEBSHOT_TIMEOUT') ) define ('WEBSHOT_TIMEOUT', '20'); //Seconds to wait for a webshot
116
+ if(! defined('WEBSHOT_USER_AGENT') ) define ('WEBSHOT_USER_AGENT', "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18"); //I hate to do this, but a non-browser robot user agent might not show what humans see. So we pretend to be Firefox
117
+ if(! defined('WEBSHOT_JAVASCRIPT_ON') ) define ('WEBSHOT_JAVASCRIPT_ON', true); //Setting to false might give you a slight speedup and block ads. But it could cause other issues.
118
+ if(! defined('WEBSHOT_JAVA_ON') ) define ('WEBSHOT_JAVA_ON', false); //Have only tested this as fase
119
+ if(! defined('WEBSHOT_PLUGINS_ON') ) define ('WEBSHOT_PLUGINS_ON', true); //Enable flash and other plugins
120
+ if(! defined('WEBSHOT_PROXY') ) define ('WEBSHOT_PROXY', ''); //In case you're behind a proxy server.
121
+ if(! defined('WEBSHOT_XVFB_RUNNING') ) define ('WEBSHOT_XVFB_RUNNING', false); //ADVANCED: Enable this if you've got Xvfb running in the background.
122
+
123
+
124
+ // If ALLOW_EXTERNAL is true and ALLOW_ALL_EXTERNAL_SITES is false, then external images will only be fetched from these domains and their subdomains.
125
+ if(! isset($ALLOWED_SITES)){
126
+ $ALLOWED_SITES = array (
127
+ 'flickr.com',
128
+ 'staticflickr.com',
129
+ 'picasa.com',
130
+ 'img.youtube.com',
131
+ 'upload.wikimedia.org',
132
+ 'photobucket.com',
133
+ 'imgur.com',
134
+ 'imageshack.us',
135
+ 'tinypic.com',
136
+ );
137
+ }
138
+ // -------------------------------------------------------------
139
+ // -------------- STOP EDITING CONFIGURATION HERE --------------
140
+ // -------------------------------------------------------------
141
+
142
+ timthumb::start();
143
+
144
+ class timthumb {
145
+ protected $src = "";
146
+ protected $is404 = false;
147
+ protected $docRoot = "";
148
+ protected $lastURLError = false;
149
+ protected $localImage = "";
150
+ protected $localImageMTime = 0;
151
+ protected $url = false;
152
+ protected $myHost = "";
153
+ protected $isURL = false;
154
+ protected $cachefile = '';
155
+ protected $errors = array();
156
+ protected $toDeletes = array();
157
+ protected $cacheDirectory = '';
158
+ protected $startTime = 0;
159
+ protected $lastBenchTime = 0;
160
+ protected $cropTop = false;
161
+ protected $salt = "";
162
+ protected $fileCacheVersion = 1; //Generally if timthumb.php is modifed (upgraded) then the salt changes and all cache files are recreated. This is a backup mechanism to force regen.
163
+ protected $filePrependSecurityBlock = "<?php die('Execution denied!'); //"; //Designed to have three letter mime type, space, question mark and greater than symbol appended. 6 bytes total.
164
+ protected static $curlDataWritten = 0;
165
+ protected static $curlFH = false;
166
+ public static function start(){
167
+ $tim = new timthumb();
168
+ $tim->handleErrors();
169
+ $tim->securityChecks();
170
+ if($tim->tryBrowserCache()){
171
+ exit(0);
172
+ }
173
+ $tim->handleErrors();
174
+ if(FILE_CACHE_ENABLED && $tim->tryServerCache()){
175
+ exit(0);
176
+ }
177
+ $tim->handleErrors();
178
+ $tim->run();
179
+ $tim->handleErrors();
180
+ exit(0);
181
+ }
182
+ public function __construct(){
183
+ global $ALLOWED_SITES;
184
+ $this->startTime = microtime(true);
185
+ date_default_timezone_set('UTC');
186
+ $this->debug(1, "Starting new request from " . $this->getIP() . " to " . $_SERVER['REQUEST_URI']);
187
+ $this->calcDocRoot();
188
+ //On windows systems I'm assuming fileinode returns an empty string or a number that doesn't change. Check this.
189
+ $this->salt = @filemtime(__FILE__) . '-' . @fileinode(__FILE__);
190
+ $this->debug(3, "Salt is: " . $this->salt);
191
+ if(FILE_CACHE_DIRECTORY){
192
+ if(! is_dir(FILE_CACHE_DIRECTORY)){
193
+ @mkdir(FILE_CACHE_DIRECTORY);
194
+ if(! is_dir(FILE_CACHE_DIRECTORY)){
195
+ $this->error("Could not create the file cache directory.");
196
+ return false;
197
+ }
198
+ }
199
+ $this->cacheDirectory = FILE_CACHE_DIRECTORY;
200
+ if (!touch($this->cacheDirectory . '/index.html')) {
201
+ $this->error("Could not create the index.html file - to fix this create an empty file named index.html file in the cache directory.");
202
+ }
203
+ } else {
204
+ $this->cacheDirectory = sys_get_temp_dir();
205
+ }
206
+ //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.
207
+ $this->cleanCache();
208
+
209
+ $this->myHost = preg_replace('/^www\./i', '', $_SERVER['HTTP_HOST']);
210
+ $this->src = $this->param('src');
211
+ $this->url = parse_url($this->src);
212
+ $this->src = preg_replace('/https?:\/\/(?:www\.)?' . $this->myHost . '/i', '', $this->src);
213
+
214
+ if(strlen($this->src) <= 3){
215
+ $this->error("No image specified");
216
+ return false;
217
+ }
218
+ if(BLOCK_EXTERNAL_LEECHERS && array_key_exists('HTTP_REFERER', $_SERVER) && (! preg_match('/^https?:\/\/(?:www\.)?' . $this->myHost . '(?:$|\/)/i', $_SERVER['HTTP_REFERER']))){
219
+ // base64 encoded red image that says 'no hotlinkers'
220
+ // nothing to worry about! :)
221
+ $imgData = base64_decode("R0lGODlhUAAMAIAAAP8AAP///yH5BAAHAP8ALAAAAABQAAwAAAJpjI+py+0Po5y0OgAMjjv01YUZ\nOGplhWXfNa6JCLnWkXplrcBmW+spbwvaVr/cDyg7IoFC2KbYVC2NQ5MQ4ZNao9Ynzjl9ScNYpneb\nDULB3RP6JuPuaGfuuV4fumf8PuvqFyhYtjdoeFgAADs=");
222
+ header('Content-Type: image/gif');
223
+ header('Content-Length: ' . sizeof($imgData));
224
+ header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
225
+ header("Pragma: no-cache");
226
+ header('Expires: ' . gmdate ('D, d M Y H:i:s', time()));
227
+ echo $imgData;
228
+ return false;
229
+ exit(0);
230
+ }
231
+ if(preg_match('/^https?:\/\/[^\/]+/i', $this->src)){
232
+ $this->debug(2, "Is a request for an external URL: " . $this->src);
233
+ $this->isURL = true;
234
+ } else {
235
+ $this->debug(2, "Is a request for an internal file: " . $this->src);
236
+ }
237
+ if($this->isURL && (! ALLOW_EXTERNAL)){
238
+ $this->error("You are not allowed to fetch images from an external website.");
239
+ return false;
240
+ }
241
+ if($this->isURL){
242
+ if(ALLOW_ALL_EXTERNAL_SITES){
243
+ $this->debug(2, "Fetching from all external sites is enabled.");
244
+ } else {
245
+ $this->debug(2, "Fetching only from selected external sites is enabled.");
246
+ $allowed = false;
247
+ foreach($ALLOWED_SITES as $site){
248
+ if ((strtolower(substr($this->url['host'],-strlen($site)-1)) === strtolower(".$site")) || (strtolower($this->url['host'])===strtolower($site))) {
249
+ $this->debug(3, "URL hostname {$this->url['host']} matches $site so allowing.");
250
+ $allowed = true;
251
+ }
252
+ }
253
+ if(! $allowed){
254
+ return $this->error("You may not fetch images from that site. To enable this site in timthumb, you can either add it to \$ALLOWED_SITES and set ALLOW_EXTERNAL=true. Or you can set ALLOW_ALL_EXTERNAL_SITES=true, depending on your security needs.");
255
+ }
256
+ }
257
+ }
258
+
259
+ $cachePrefix = ($this->isURL ? '_ext_' : '_int_');
260
+ if($this->isURL){
261
+ $arr = explode('&', $_SERVER ['QUERY_STRING']);
262
+ asort($arr);
263
+ $this->cachefile = $this->cacheDirectory . '/' . FILE_CACHE_PREFIX . $cachePrefix . md5($this->salt . implode('', $arr) . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
264
+ } else {
265
+ $this->localImage = $this->getLocalImagePath($this->src);
266
+ if(! $this->localImage){
267
+ $this->debug(1, "Could not find the local image: {$this->localImage}");
268
+ $this->error("Could not find the internal image you specified.");
269
+ $this->set404();
270
+ return false;
271
+ }
272
+ $this->debug(1, "Local image path is {$this->localImage}");
273
+ $this->localImageMTime = @filemtime($this->localImage);
274
+ //We include the mtime of the local file in case in changes on disk.
275
+ $this->cachefile = $this->cacheDirectory . '/' . FILE_CACHE_PREFIX . $cachePrefix . md5($this->salt . $this->localImageMTime . $_SERVER ['QUERY_STRING'] . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
276
+ }
277
+ $this->debug(2, "Cache file is: " . $this->cachefile);
278
+
279
+ return true;
280
+ }
281
+ public function __destruct(){
282
+ foreach($this->toDeletes as $del){
283
+ $this->debug(2, "Deleting temp file $del");
284
+ @unlink($del);
285
+ }
286
+ }
287
+ public function run(){
288
+ if($this->isURL){
289
+ if(! ALLOW_EXTERNAL){
290
+ $this->debug(1, "Got a request for an external image but ALLOW_EXTERNAL is disabled so returning error msg.");
291
+ $this->error("You are not allowed to fetch images from an external website.");
292
+ return false;
293
+ }
294
+ $this->debug(3, "Got request for external image. Starting serveExternalImage.");
295
+ if($this->param('webshot')){
296
+ if(WEBSHOT_ENABLED){
297
+ $this->debug(3, "webshot param is set, so we're going to take a webshot.");
298
+ $this->serveWebshot();
299
+ } else {
300
+ $this->error("You added the webshot parameter but webshots are disabled on this server. You need to set WEBSHOT_ENABLED == true to enable webshots.");
301
+ }
302
+ } else {
303
+ $this->debug(3, "webshot is NOT set so we're going to try to fetch a regular image.");
304
+ $this->serveExternalImage();
305
+
306
+ }
307
+ } else {
308
+ $this->debug(3, "Got request for internal image. Starting serveInternalImage()");
309
+ $this->serveInternalImage();
310
+ }
311
+ return true;
312
+ }
313
+ protected function handleErrors(){
314
+ if($this->haveErrors()){
315
+ if(NOT_FOUND_IMAGE && $this->is404()){
316
+ if($this->serveImg(NOT_FOUND_IMAGE)){
317
+ exit(0);
318
+ } else {
319
+ $this->error("Additionally, the 404 image that is configured could not be found or there was an error serving it.");
320
+ }
321
+ }
322
+ if(ERROR_IMAGE){
323
+ if($this->serveImg(ERROR_IMAGE)){
324
+ exit(0);
325
+ } else {
326
+ $this->error("Additionally, the error image that is configured could not be found or there was an error serving it.");
327
+ }
328
+ }
329
+ $this->serveErrors();
330
+ exit(0);
331
+ }
332
+ return false;
333
+ }
334
+ protected function tryBrowserCache(){
335
+ if(BROWSER_CACHE_DISABLE){ $this->debug(3, "Browser caching is disabled"); return false; }
336
+ if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ){
337
+ $this->debug(3, "Got a conditional get");
338
+ $mtime = false;
339
+ //We've already checked if the real file exists in the constructor
340
+ if(! is_file($this->cachefile)){
341
+ //If we don't have something cached, regenerate the cached image.
342
+ return false;
343
+ }
344
+ if($this->localImageMTime){
345
+ $mtime = $this->localImageMTime;
346
+ $this->debug(3, "Local real file's modification time is $mtime");
347
+ } 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
348
+ $mtime = @filemtime($this->cachefile);
349
+ $this->debug(3, "Cached file's modification time is $mtime");
350
+ }
351
+ if(! $mtime){ return false; }
352
+
353
+ $iftime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
354
+ $this->debug(3, "The conditional get's if-modified-since unixtime is $iftime");
355
+ if($iftime < 1){
356
+ $this->debug(3, "Got an invalid conditional get modified since time. Returning false.");
357
+ return false;
358
+ }
359
+ if($iftime < $mtime){ //Real file or cache file has been modified since last request, so force refetch.
360
+ $this->debug(3, "File has been modified since last fetch.");
361
+ return false;
362
+ } else { //Otherwise serve a 304
363
+ $this->debug(3, "File has not been modified since last get, so serving a 304.");
364
+ header ($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
365
+ $this->debug(1, "Returning 304 not modified");
366
+ return true;
367
+ }
368
+ }
369
+ return false;
370
+ }
371
+ protected function tryServerCache(){
372
+ $this->debug(3, "Trying server cache");
373
+ if(file_exists($this->cachefile)){
374
+ $this->debug(3, "Cachefile {$this->cachefile} exists");
375
+ if($this->isURL){
376
+ $this->debug(3, "This is an external request, so checking if the cachefile is empty which means the request failed previously.");
377
+ if(filesize($this->cachefile) < 1){
378
+ $this->debug(3, "Found an empty cachefile indicating a failed earlier request. Checking how old it is.");
379
+ //Fetching error occured previously
380
+ if(time() - @filemtime($this->cachefile) > WAIT_BETWEEN_FETCH_ERRORS){
381
+ $this->debug(3, "File is older than " . WAIT_BETWEEN_FETCH_ERRORS . " seconds. Deleting and returning false so app can try and load file.");
382
+ @unlink($this->cachefile);
383
+ return false; //to indicate we didn't serve from cache and app should try and load
384
+ } else {
385
+ $this->debug(3, "Empty cachefile is still fresh so returning message saying we had an error fetching this image from remote host.");
386
+ $this->set404();
387
+ $this->error("An error occured fetching image.");
388
+ return false;
389
+ }
390
+ }
391
+ } else {
392
+ $this->debug(3, "Trying to serve cachefile {$this->cachefile}");
393
+ }
394
+ if($this->serveCacheFile()){
395
+ $this->debug(3, "Succesfully served cachefile {$this->cachefile}");
396
+ return true;
397
+ } else {
398
+ $this->debug(3, "Failed to serve cachefile {$this->cachefile} - Deleting it from cache.");
399
+ //Image serving failed. We can't retry at this point, but lets remove it from cache so the next request recreates it
400
+ @unlink($this->cachefile);
401
+ return true;
402
+ }
403
+ }
404
+ }
405
+ protected function error($err){
406
+ $this->debug(3, "Adding error message: $err");
407
+ $this->errors[] = $err;
408
+ return false;
409
+
410
+ }
411
+ protected function haveErrors(){
412
+ if(sizeof($this->errors) > 0){
413
+ return true;
414
+ }
415
+ return false;
416
+ }
417
+ protected function serveErrors(){
418
+ header ($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
419
+ $html = '<ul>';
420
+ foreach($this->errors as $err){
421
+ $html .= '<li>' . htmlentities($err) . '</li>';
422
+ }
423
+ $html .= '</ul>';
424
+ echo '<h1>A TimThumb error has occured</h1>The following error(s) occured:<br />' . $html . '<br />';
425
+ echo '<br />Query String : ' . htmlentities ($_SERVER['QUERY_STRING']);
426
+ echo '<br />TimThumb version : ' . VERSION . '</pre>';
427
+ }
428
+ protected function serveInternalImage(){
429
+ $this->debug(3, "Local image path is $this->localImage");
430
+ if(! $this->localImage){
431
+ $this->sanityFail("localImage not set after verifying it earlier in the code.");
432
+ return false;
433
+ }
434
+ $fileSize = filesize($this->localImage);
435
+ if($fileSize > MAX_FILE_SIZE){
436
+ $this->error("The file you specified is greater than the maximum allowed file size.");
437
+ return false;
438
+ }
439
+ if($fileSize <= 0){
440
+ $this->error("The file you specified is <= 0 bytes.");
441
+ return false;
442
+ }
443
+ $this->debug(3, "Calling processImageAndWriteToCache() for local image.");
444
+ if($this->processImageAndWriteToCache($this->localImage)){
445
+ $this->serveCacheFile();
446
+ return true;
447
+ } else {
448
+ return false;
449
+ }
450
+ }
451
+ protected function cleanCache(){
452
+ if (FILE_CACHE_TIME_BETWEEN_CLEANS < 0) {
453
+ return;
454
+ }
455
+ $this->debug(3, "cleanCache() called");
456
+ $lastCleanFile = $this->cacheDirectory . '/timthumb_cacheLastCleanTime.touch';
457
+
458
+ //If this is a new timthumb installation we need to create the file
459
+ if(! is_file($lastCleanFile)){
460
+ $this->debug(1, "File tracking last clean doesn't exist. Creating $lastCleanFile");
461
+ if (!touch($lastCleanFile)) {
462
+ $this->error("Could not create cache clean timestamp file.");
463
+ }
464
+ return;
465
+ }
466
+ if(@filemtime($lastCleanFile) < (time() - FILE_CACHE_TIME_BETWEEN_CLEANS) ){ //Cache was last cleaned more than 1 day ago
467
+ $this->debug(1, "Cache was last cleaned more than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago. Cleaning now.");
468
+ // Very slight race condition here, but worst case we'll have 2 or 3 servers cleaning the cache simultaneously once a day.
469
+ if (!touch($lastCleanFile)) {
470
+ $this->error("Could not create cache clean timestamp file.");
471
+ }
472
+ $files = glob($this->cacheDirectory . '/*' . FILE_CACHE_SUFFIX);
473
+ if ($files) {
474
+ $timeAgo = time() - FILE_CACHE_MAX_FILE_AGE;
475
+ foreach($files as $file){
476
+ if(@filemtime($file) < $timeAgo){
477
+ $this->debug(3, "Deleting cache file $file older than max age: " . FILE_CACHE_MAX_FILE_AGE . " seconds");
478
+ @unlink($file);
479
+ }
480
+ }
481
+ }
482
+ return true;
483
+ } else {
484
+ $this->debug(3, "Cache was cleaned less than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago so no cleaning needed.");
485
+ }
486
+ return false;
487
+ }
488
+ protected function processImageAndWriteToCache($localImage){
489
+ $sData = getimagesize($localImage);
490
+ $origType = $sData[2];
491
+ $mimeType = $sData['mime'];
492
+
493
+ $this->debug(3, "Mime type of image is $mimeType");
494
+ if(! preg_match('/^image\/(?:gif|jpg|jpeg|png)$/i', $mimeType)){
495
+ return $this->error("The image being resized is not a valid gif, jpg or png.");
496
+ }
497
+
498
+ if (!function_exists ('imagecreatetruecolor')) {
499
+ return $this->error('GD Library Error: imagecreatetruecolor does not exist - please contact your webhost and ask them to install the GD library');
500
+ }
501
+
502
+ if (function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
503
+ $imageFilters = array (
504
+ 1 => array (IMG_FILTER_NEGATE, 0),
505
+ 2 => array (IMG_FILTER_GRAYSCALE, 0),
506
+ 3 => array (IMG_FILTER_BRIGHTNESS, 1),
507
+ 4 => array (IMG_FILTER_CONTRAST, 1),
508
+ 5 => array (IMG_FILTER_COLORIZE, 4),
509
+ 6 => array (IMG_FILTER_EDGEDETECT, 0),
510
+ 7 => array (IMG_FILTER_EMBOSS, 0),
511
+ 8 => array (IMG_FILTER_GAUSSIAN_BLUR, 0),
512
+ 9 => array (IMG_FILTER_SELECTIVE_BLUR, 0),
513
+ 10 => array (IMG_FILTER_MEAN_REMOVAL, 0),
514
+ 11 => array (IMG_FILTER_SMOOTH, 0),
515
+ );
516
+ }
517
+
518
+ // get standard input properties
519
+ $new_width = (int) abs ($this->param('w', 0));
520
+ $new_height = (int) abs ($this->param('h', 0));
521
+ $zoom_crop = (int) $this->param('zc', DEFAULT_ZC);
522
+ $quality = (int) abs ($this->param('q', DEFAULT_Q));
523
+ $align = $this->cropTop ? 't' : $this->param('a', 'c');
524
+ $filters = $this->param('f', DEFAULT_F);
525
+ $sharpen = (bool) $this->param('s', DEFAULT_S);
526
+ $canvas_color = $this->param('cc', DEFAULT_CC);
527
+ $canvas_trans = (bool) $this->param('ct', '1');
528
+
529
+ // set default width and height if neither are set already
530
+ if ($new_width == 0 && $new_height == 0) {
531
+ $new_width = 100;
532
+ $new_height = 100;
533
+ }
534
+
535
+ // ensure size limits can not be abused
536
+ $new_width = min ($new_width, MAX_WIDTH);
537
+ $new_height = min ($new_height, MAX_HEIGHT);
538
+
539
+ // set memory limit to be able to have enough space to resize larger images
540
+ $this->setMemoryLimit();
541
+
542
+ // open the existing image
543
+ $image = $this->openImage ($mimeType, $localImage);
544
+ if ($image === false) {
545
+ return $this->error('Unable to open image.');
546
+ }
547
+
548
+ // Get original width and height
549
+ $width = imagesx ($image);
550
+ $height = imagesy ($image);
551
+ $origin_x = 0;
552
+ $origin_y = 0;
553
+
554
+ // generate new w/h if not provided
555
+ if ($new_width && !$new_height) {
556
+ $new_height = floor ($height * ($new_width / $width));
557
+ } else if ($new_height && !$new_width) {
558
+ $new_width = floor ($width * ($new_height / $height));
559
+ }
560
+
561
+ // scale down and add borders
562
+ if ($zoom_crop == 3) {
563
+
564
+ $final_height = $height * ($new_width / $width);
565
+
566
+ if ($final_height > $new_height) {
567
+ $new_width = $width * ($new_height / $height);
568
+ } else {
569
+ $new_height = $final_height;
570
+ }
571
+
572
+ }
573
+
574
+ // create a new true color image
575
+ $canvas = imagecreatetruecolor ($new_width, $new_height);
576
+ imagealphablending ($canvas, false);
577
+
578
+ if (strlen($canvas_color) == 3) { //if is 3-char notation, edit string into 6-char notation
579
+ $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);
580
+ } else if (strlen($canvas_color) != 6) {
581
+ $canvas_color = DEFAULT_CC; // on error return default canvas color
582
+ }
583
+
584
+ $canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
585
+ $canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
586
+ $canvas_color_B = hexdec (substr ($canvas_color, 4, 2));
587
+
588
+ // Create a new transparent color for image
589
+ // If is a png and PNG_IS_TRANSPARENT is false then remove the alpha transparency
590
+ // (and if is set a canvas color show it in the background)
591
+ if(preg_match('/^image\/png$/i', $mimeType) && !PNG_IS_TRANSPARENT && $canvas_trans){
592
+ $color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
593
+ }else{
594
+ $color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 0);
595
+ }
596
+
597
+
598
+ // Completely fill the background of the new image with allocated color.
599
+ imagefill ($canvas, 0, 0, $color);
600
+
601
+ // scale down and add borders
602
+ if ($zoom_crop == 2) {
603
+
604
+ $final_height = $height * ($new_width / $width);
605
+
606
+ if ($final_height > $new_height) {
607
+
608
+ $origin_x = $new_width / 2;
609
+ $new_width = $width * ($new_height / $height);
610
+ $origin_x = round ($origin_x - ($new_width / 2));
611
+
612
+ } else {
613
+
614
+ $origin_y = $new_height / 2;
615
+ $new_height = $final_height;
616
+ $origin_y = round ($origin_y - ($new_height / 2));
617
+
618
+ }
619
+
620
+ }
621
+
622
+ // Restore transparency blending
623
+ imagesavealpha ($canvas, true);
624
+
625
+ if ($zoom_crop > 0) {
626
+
627
+ $src_x = $src_y = 0;
628
+ $src_w = $width;
629
+ $src_h = $height;
630
+
631
+ $cmp_x = $width / $new_width;
632
+ $cmp_y = $height / $new_height;
633
+
634
+ // calculate x or y coordinate and width or height of source
635
+ if ($cmp_x > $cmp_y) {
636
+
637
+ $src_w = round ($width / $cmp_x * $cmp_y);
638
+ $src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
639
+
640
+ } else if ($cmp_y > $cmp_x) {
641
+
642
+ $src_h = round ($height / $cmp_y * $cmp_x);
643
+ $src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
644
+
645
+ }
646
+
647
+ // positional cropping!
648
+ if ($align) {
649
+ if (strpos ($align, 't') !== false) {
650
+ $src_y = 0;
651
+ }
652
+ if (strpos ($align, 'b') !== false) {
653
+ $src_y = $height - $src_h;
654
+ }
655
+ if (strpos ($align, 'l') !== false) {
656
+ $src_x = 0;
657
+ }
658
+ if (strpos ($align, 'r') !== false) {
659
+ $src_x = $width - $src_w;
660
+ }
661
+ }
662
+
663
+ imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
664
+
665
+ } else {
666
+
667
+ // copy and resize part of an image with resampling
668
+ imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
669
+
670
+ }
671
+
672
+ if ($filters != '' && function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
673
+ // apply filters to image
674
+ $filterList = explode ('|', $filters);
675
+ foreach ($filterList as $fl) {
676
+
677
+ $filterSettings = explode (',', $fl);
678
+ if (isset ($imageFilters[$filterSettings[0]])) {
679
+
680
+ for ($i = 0; $i < 4; $i ++) {
681
+ if (!isset ($filterSettings[$i])) {
682
+ $filterSettings[$i] = null;
683
+ } else {
684
+ $filterSettings[$i] = (int) $filterSettings[$i];
685
+ }
686
+ }
687
+
688
+ switch ($imageFilters[$filterSettings[0]][1]) {
689
+
690
+ case 1:
691
+
692
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
693
+ break;
694
+
695
+ case 2:
696
+
697
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
698
+ break;
699
+
700
+ case 3:
701
+
702
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
703
+ break;
704
+
705
+ case 4:
706
+
707
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3], $filterSettings[4]);
708
+ break;
709
+
710
+ default:
711
+
712
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0]);
713
+ break;
714
+
715
+ }
716
+ }
717
+ }
718
+ }
719
+
720
+ // sharpen image
721
+ if ($sharpen && function_exists ('imageconvolution')) {
722
+
723
+ $sharpenMatrix = array (
724
+ array (-1,-1,-1),
725
+ array (-1,16,-1),
726
+ array (-1,-1,-1),
727
+ );
728
+
729
+ $divisor = 8;
730
+ $offset = 0;
731
+
732
+ imageconvolution ($canvas, $sharpenMatrix, $divisor, $offset);
733
+
734
+ }
735
+ //Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
736
+ if ( (IMAGETYPE_PNG == $origType || IMAGETYPE_GIF == $origType) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
737
+ imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
738
+ }
739
+
740
+ $imgType = "";
741
+ $tempfile = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
742
+ if(preg_match('/^image\/(?:jpg|jpeg)$/i', $mimeType)){
743
+ $imgType = 'jpg';
744
+ imagejpeg($canvas, $tempfile, $quality);
745
+ } else if(preg_match('/^image\/png$/i', $mimeType)){
746
+ $imgType = 'png';
747
+ imagepng($canvas, $tempfile, floor($quality * 0.09));
748
+ } else if(preg_match('/^image\/gif$/i', $mimeType)){
749
+ $imgType = 'gif';
750
+ imagegif($canvas, $tempfile);
751
+ } else {
752
+ return $this->sanityFail("Could not match mime type after verifying it previously.");
753
+ }
754
+
755
+ if($imgType == 'png' && OPTIPNG_ENABLED && OPTIPNG_PATH && @is_file(OPTIPNG_PATH)){
756
+ $exec = OPTIPNG_PATH;
757
+ $this->debug(3, "optipng'ing $tempfile");
758
+ $presize = filesize($tempfile);
759
+ $out = `$exec -o1 $tempfile`; //you can use up to -o7 but it really slows things down
760
+ clearstatcache();
761
+ $aftersize = filesize($tempfile);
762
+ $sizeDrop = $presize - $aftersize;
763
+ if($sizeDrop > 0){
764
+ $this->debug(1, "optipng reduced size by $sizeDrop");
765
+ } else if($sizeDrop < 0){
766
+ $this->debug(1, "optipng increased size! Difference was: $sizeDrop");
767
+ } else {
768
+ $this->debug(1, "optipng did not change image size.");
769
+ }
770
+ } else if($imgType == 'png' && PNGCRUSH_ENABLED && PNGCRUSH_PATH && @is_file(PNGCRUSH_PATH)){
771
+ $exec = PNGCRUSH_PATH;
772
+ $tempfile2 = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
773
+ $this->debug(3, "pngcrush'ing $tempfile to $tempfile2");
774
+ $out = `$exec $tempfile $tempfile2`;
775
+ $todel = "";
776
+ if(is_file($tempfile2)){
777
+ $sizeDrop = filesize($tempfile) - filesize($tempfile2);
778
+ if($sizeDrop > 0){
779
+ $this->debug(1, "pngcrush was succesful and gave a $sizeDrop byte size reduction");
780
+ $todel = $tempfile;
781
+ $tempfile = $tempfile2;
782
+ } else {
783
+ $this->debug(1, "pngcrush did not reduce file size. Difference was $sizeDrop bytes.");
784
+ $todel = $tempfile2;
785
+ }
786
+ } else {
787
+ $this->debug(3, "pngcrush failed with output: $out");
788
+ $todel = $tempfile2;
789
+ }
790
+ @unlink($todel);
791
+ }
792
+
793
+ $this->debug(3, "Rewriting image with security header.");
794
+ $tempfile4 = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
795
+ $context = stream_context_create ();
796
+ $fp = fopen($tempfile,'r',0,$context);
797
+ file_put_contents($tempfile4, $this->filePrependSecurityBlock . $imgType . ' ?' . '>'); //6 extra bytes, first 3 being image type
798
+ file_put_contents($tempfile4, $fp, FILE_APPEND);
799
+ fclose($fp);
800
+ @unlink($tempfile);
801
+ $this->debug(3, "Locking and replacing cache file.");
802
+ $lockFile = $this->cachefile . '.lock';
803
+ $fh = fopen($lockFile, 'w');
804
+ if(! $fh){
805
+ return $this->error("Could not open the lockfile for writing an image.");
806
+ }
807
+ if(flock($fh, LOCK_EX)){
808
+ @unlink($this->cachefile); //rename generally overwrites, but doing this in case of platform specific quirks. File might not exist yet.
809
+ rename($tempfile4, $this->cachefile);
810
+ flock($fh, LOCK_UN);
811
+ fclose($fh);
812
+ @unlink($lockFile);
813
+ } else {
814
+ fclose($fh);
815
+ @unlink($lockFile);
816
+ @unlink($tempfile4);
817
+ return $this->error("Could not get a lock for writing.");
818
+ }
819
+ $this->debug(3, "Done image replace with security header. Cleaning up and running cleanCache()");
820
+ imagedestroy($canvas);
821
+ imagedestroy($image);
822
+ return true;
823
+ }
824
+ protected function calcDocRoot(){
825
+ $docRoot = @$_SERVER['DOCUMENT_ROOT'];
826
+ if (defined('LOCAL_FILE_BASE_DIRECTORY')) {
827
+ $docRoot = LOCAL_FILE_BASE_DIRECTORY;
828
+ }
829
+ if(!isset($docRoot)){
830
+ $this->debug(3, "DOCUMENT_ROOT is not set. This is probably windows. Starting search 1.");
831
+ if(isset($_SERVER['SCRIPT_FILENAME'])){
832
+ $docRoot = str_replace( '\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF'])));
833
+ $this->debug(3, "Generated docRoot using SCRIPT_FILENAME and PHP_SELF as: $docRoot");
834
+ }
835
+ }
836
+ if(!isset($docRoot)){
837
+ $this->debug(3, "DOCUMENT_ROOT still is not set. Starting search 2.");
838
+ if(isset($_SERVER['PATH_TRANSLATED'])){
839
+ $docRoot = str_replace( '\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0-strlen($_SERVER['PHP_SELF'])));
840
+ $this->debug(3, "Generated docRoot using PATH_TRANSLATED and PHP_SELF as: $docRoot");
841
+ }
842
+ }
843
+ if($docRoot && $_SERVER['DOCUMENT_ROOT'] != '/'){ $docRoot = preg_replace('/\/$/', '', $docRoot); }
844
+ $this->debug(3, "Doc root is: " . $docRoot);
845
+ $this->docRoot = $docRoot;
846
+
847
+ }
848
+ protected function getLocalImagePath($src){
849
+ $src = ltrim($src, '/'); //strip off the leading '/'
850
+ if(! $this->docRoot){
851
+ $this->debug(3, "We have no document root set, so as a last resort, lets check if the image is in the current dir and serve that.");
852
+ //We don't support serving images outside the current dir if we don't have a doc root for security reasons.
853
+ $file = preg_replace('/^.*?([^\/\\\\]+)$/', '$1', $src); //strip off any path info and just leave the filename.
854
+ if(is_file($file)){
855
+ return $this->realpath($file);
856
+ }
857
+ return $this->error("Could not find your website document root and the file specified doesn't exist in timthumbs directory. We don't support serving files outside timthumb's directory without a document root for security reasons.");
858
+ } //Do not go past this point without docRoot set
859
+
860
+ //Try src under docRoot
861
+ if(file_exists ($this->docRoot . '/' . $src)) {
862
+ $this->debug(3, "Found file as " . $this->docRoot . '/' . $src);
863
+ $real = $this->realpath($this->docRoot . '/' . $src);
864
+ if(stripos($real, $this->docRoot) === 0){
865
+ return $real;
866
+ } else {
867
+ $this->debug(1, "Security block: The file specified occurs outside the document root.");
868
+ //allow search to continue
869
+ }
870
+ }
871
+ //Check absolute paths and then verify the real path is under doc root
872
+ $absolute = $this->realpath('/' . $src);
873
+ if($absolute && file_exists($absolute)){ //realpath does file_exists check, so can probably skip the exists check here
874
+ $this->debug(3, "Found absolute path: $absolute");
875
+ if(! $this->docRoot){ $this->sanityFail("docRoot not set when checking absolute path."); }
876
+ if(stripos($absolute, $this->docRoot) === 0){
877
+ return $absolute;
878
+ } else {
879
+ $this->debug(1, "Security block: The file specified occurs outside the document root.");
880
+ //and continue search
881
+ }
882
+ }
883
+
884
+ $base = $this->docRoot;
885
+
886
+ // account for Windows directory structure
887
+ if (strstr($_SERVER['SCRIPT_FILENAME'],':')) {
888
+ $sub_directories = explode('\\', str_replace($this->docRoot, '', $_SERVER['SCRIPT_FILENAME']));
889
+ } else {
890
+ $sub_directories = explode('/', str_replace($this->docRoot, '', $_SERVER['SCRIPT_FILENAME']));
891
+ }
892
+
893
+ foreach ($sub_directories as $sub){
894
+ $base .= $sub . '/';
895
+ $this->debug(3, "Trying file as: " . $base . $src);
896
+ if(file_exists($base . $src)){
897
+ $this->debug(3, "Found file as: " . $base . $src);
898
+ $real = $this->realpath($base . $src);
899
+ if(stripos($real, $this->realpath($this->docRoot)) === 0){
900
+ return $real;
901
+ } else {
902
+ $this->debug(1, "Security block: The file specified occurs outside the document root.");
903
+ //And continue search
904
+ }
905
+ }
906
+ }
907
+ return false;
908
+ }
909
+ protected function realpath($path){
910
+ //try to remove any relative paths
911
+ $remove_relatives = '/\w+\/\.\.\//';
912
+ while(preg_match($remove_relatives,$path)){
913
+ $path = preg_replace($remove_relatives, '', $path);
914
+ }
915
+ //if any remain use PHP realpath to strip them out, otherwise return $path
916
+ //if using realpath, any symlinks will also be resolved
917
+ return preg_match('#^\.\./|/\.\./#', $path) ? realpath($path) : $path;
918
+ }
919
+ protected function toDelete($name){
920
+ $this->debug(3, "Scheduling file $name to delete on destruct.");
921
+ $this->toDeletes[] = $name;
922
+ }
923
+ protected function serveWebshot(){
924
+ $this->debug(3, "Starting serveWebshot");
925
+ $instr = "Please follow the instructions at http://code.google.com/p/timthumb/ to set your server up for taking website screenshots.";
926
+ if(! is_file(WEBSHOT_CUTYCAPT)){
927
+ return $this->error("CutyCapt is not installed. $instr");
928
+ }
929
+ if(! is_file(WEBSHOT_XVFB)){
930
+ return $this->Error("Xvfb is not installed. $instr");
931
+ }
932
+ $cuty = WEBSHOT_CUTYCAPT;
933
+ $xv = WEBSHOT_XVFB;
934
+ $screenX = WEBSHOT_SCREEN_X;
935
+ $screenY = WEBSHOT_SCREEN_Y;
936
+ $colDepth = WEBSHOT_COLOR_DEPTH;
937
+ $format = WEBSHOT_IMAGE_FORMAT;
938
+ $timeout = WEBSHOT_TIMEOUT * 1000;
939
+ $ua = WEBSHOT_USER_AGENT;
940
+ $jsOn = WEBSHOT_JAVASCRIPT_ON ? 'on' : 'off';
941
+ $javaOn = WEBSHOT_JAVA_ON ? 'on' : 'off';
942
+ $pluginsOn = WEBSHOT_PLUGINS_ON ? 'on' : 'off';
943
+ $proxy = WEBSHOT_PROXY ? ' --http-proxy=' . WEBSHOT_PROXY : '';
944
+ $tempfile = tempnam($this->cacheDirectory, 'timthumb_webshot');
945
+ $url = $this->src;
946
+ if(! preg_match('/^https?:\/\/[a-zA-Z0-9\.\-]+/i', $url)){
947
+ return $this->error("Invalid URL supplied.");
948
+ }
949
+ $url = preg_replace('/[^A-Za-z0-9\-\.\_\~:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]+/', '', $url); //RFC 3986
950
+ //Very important we don't allow injection of shell commands here. URL is between quotes and we are only allowing through chars allowed by a the RFC
951
+ // which AFAIKT can't be used for shell injection.
952
+ if(WEBSHOT_XVFB_RUNNING){
953
+ putenv('DISPLAY=:100.0');
954
+ $command = "$cuty $proxy --max-wait=$timeout --user-agent=\"$ua\" --javascript=$jsOn --java=$javaOn --plugins=$pluginsOn --js-can-open-windows=off --url=\"$url\" --out-format=$format --out=$tempfile";
955
+ } else {
956
+ $command = "$xv --server-args=\"-screen 0, {$screenX}x{$screenY}x{$colDepth}\" $cuty $proxy --max-wait=$timeout --user-agent=\"$ua\" --javascript=$jsOn --java=$javaOn --plugins=$pluginsOn --js-can-open-windows=off --url=\"$url\" --out-format=$format --out=$tempfile";
957
+ }
958
+ $this->debug(3, "Executing command: $command");
959
+ $out = `$command`;
960
+ $this->debug(3, "Received output: $out");
961
+ if(! is_file($tempfile)){
962
+ $this->set404();
963
+ return $this->error("The command to create a thumbnail failed.");
964
+ }
965
+ $this->cropTop = true;
966
+ if($this->processImageAndWriteToCache($tempfile)){
967
+ $this->debug(3, "Image processed succesfully. Serving from cache");
968
+ return $this->serveCacheFile();
969
+ } else {
970
+ return false;
971
+ }
972
+ }
973
+ protected function serveExternalImage(){
974
+ if(! preg_match('/^https?:\/\/[a-zA-Z0-9\-\.]+/i', $this->src)){
975
+ $this->error("Invalid URL supplied.");
976
+ return false;
977
+ }
978
+ $tempfile = tempnam($this->cacheDirectory, 'timthumb');
979
+ $this->debug(3, "Fetching external image into temporary file $tempfile");
980
+ $this->toDelete($tempfile);
981
+ #fetch file here
982
+ if(! $this->getURL($this->src, $tempfile)){
983
+ @unlink($this->cachefile);
984
+ touch($this->cachefile);
985
+ $this->debug(3, "Error fetching URL: " . $this->lastURLError);
986
+ $this->error("Error reading the URL you specified from remote host." . $this->lastURLError);
987
+ return false;
988
+ }
989
+
990
+ $mimeType = $this->getMimeType($tempfile);
991
+ if(! preg_match("/^image\/(?:jpg|jpeg|gif|png)$/i", $mimeType)){
992
+ $this->debug(3, "Remote file has invalid mime type: $mimeType");
993
+ @unlink($this->cachefile);
994
+ touch($this->cachefile);
995
+ $this->error("The remote file is not a valid image. Mimetype = '" . $mimeType . "'" . $tempfile);
996
+ return false;
997
+ }
998
+ if($this->processImageAndWriteToCache($tempfile)){
999
+ $this->debug(3, "Image processed succesfully. Serving from cache");
1000
+ return $this->serveCacheFile();
1001
+ } else {
1002
+ return false;
1003
+ }
1004
+ }
1005
+ public static function curlWrite($h, $d){
1006
+ fwrite(self::$curlFH, $d);
1007
+ self::$curlDataWritten += strlen($d);
1008
+ if(self::$curlDataWritten > MAX_FILE_SIZE){
1009
+ return 0;
1010
+ } else {
1011
+ return strlen($d);
1012
+ }
1013
+ }
1014
+ protected function serveCacheFile(){
1015
+ $this->debug(3, "Serving {$this->cachefile}");
1016
+ if(! is_file($this->cachefile)){
1017
+ $this->error("serveCacheFile called in timthumb but we couldn't find the cached file.");
1018
+ return false;
1019
+ }
1020
+ $fp = fopen($this->cachefile, 'rb');
1021
+ if(! $fp){ return $this->error("Could not open cachefile."); }
1022
+ fseek($fp, strlen($this->filePrependSecurityBlock), SEEK_SET);
1023
+ $imgType = fread($fp, 3);
1024
+ fseek($fp, 3, SEEK_CUR);
1025
+ if(ftell($fp) != strlen($this->filePrependSecurityBlock) + 6){
1026
+ @unlink($this->cachefile);
1027
+ return $this->error("The cached image file seems to be corrupt.");
1028
+ }
1029
+ $imageDataSize = filesize($this->cachefile) - (strlen($this->filePrependSecurityBlock) + 6);
1030
+ $this->sendImageHeaders($imgType, $imageDataSize);
1031
+ $bytesSent = @fpassthru($fp);
1032
+ fclose($fp);
1033
+ if($bytesSent > 0){
1034
+ return true;
1035
+ }
1036
+ $content = file_get_contents ($this->cachefile);
1037
+ if ($content != FALSE) {
1038
+ $content = substr($content, strlen($this->filePrependSecurityBlock) + 6);
1039
+ echo $content;
1040
+ $this->debug(3, "Served using file_get_contents and echo");
1041
+ return true;
1042
+ } else {
1043
+ $this->error("Cache file could not be loaded.");
1044
+ return false;
1045
+ }
1046
+ }
1047
+ protected function sendImageHeaders($mimeType, $dataSize){
1048
+ if(! preg_match('/^image\//i', $mimeType)){
1049
+ $mimeType = 'image/' . $mimeType;
1050
+ }
1051
+ if(strtolower($mimeType) == 'image/jpg'){
1052
+ $mimeType = 'image/jpeg';
1053
+ }
1054
+ $gmdate_expires = gmdate ('D, d M Y H:i:s', strtotime ('now +10 days')) . ' GMT';
1055
+ $gmdate_modified = gmdate ('D, d M Y H:i:s') . ' GMT';
1056
+ // send content headers then display image
1057
+ header ('Content-Type: ' . $mimeType);
1058
+ header ('Accept-Ranges: none'); //Changed this because we don't accept range requests
1059
+ header ('Last-Modified: ' . $gmdate_modified);
1060
+ header ('Content-Length: ' . $dataSize);
1061
+ if(BROWSER_CACHE_DISABLE){
1062
+ $this->debug(3, "Browser cache is disabled so setting non-caching headers.");
1063
+ header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
1064
+ header("Pragma: no-cache");
1065
+ header('Expires: ' . gmdate ('D, d M Y H:i:s', time()));
1066
+ } else {
1067
+ $this->debug(3, "Browser caching is enabled");
1068
+ header('Cache-Control: max-age=' . BROWSER_CACHE_MAX_AGE . ', must-revalidate');
1069
+ header('Expires: ' . $gmdate_expires);
1070
+ }
1071
+ return true;
1072
+ }
1073
+ protected function securityChecks(){
1074
+ }
1075
+ protected function param($property, $default = ''){
1076
+ if (isset ($_GET[$property])) {
1077
+ return $_GET[$property];
1078
+ } else {
1079
+ return $default;
1080
+ }
1081
+ }
1082
+ protected function openImage($mimeType, $src){
1083
+ switch ($mimeType) {
1084
+ case 'image/jpeg':
1085
+ $image = imagecreatefromjpeg ($src);
1086
+ break;
1087
+
1088
+ case 'image/png':
1089
+ $image = imagecreatefrompng ($src);
1090
+ imagealphablending( $image, true );
1091
+ imagesavealpha( $image, true );
1092
+ break;
1093
+
1094
+ case 'image/gif':
1095
+ $image = imagecreatefromgif ($src);
1096
+ break;
1097
+
1098
+ default:
1099
+ $this->error("Unrecognised mimeType");
1100
+ }
1101
+
1102
+ return $image;
1103
+ }
1104
+ protected function getIP(){
1105
+ $rem = @$_SERVER["REMOTE_ADDR"];
1106
+ $ff = @$_SERVER["HTTP_X_FORWARDED_FOR"];
1107
+ $ci = @$_SERVER["HTTP_CLIENT_IP"];
1108
+ if(preg_match('/^(?:192\.168|172\.16|10\.|127\.)/', $rem)){
1109
+ if($ff){ return $ff; }
1110
+ if($ci){ return $ci; }
1111
+ return $rem;
1112
+ } else {
1113
+ if($rem){ return $rem; }
1114
+ if($ff){ return $ff; }
1115
+ if($ci){ return $ci; }
1116
+ return "UNKNOWN";
1117
+ }
1118
+ }
1119
+ protected function debug($level, $msg){
1120
+ if(DEBUG_ON && $level <= DEBUG_LEVEL){
1121
+ $execTime = sprintf('%.6f', microtime(true) - $this->startTime);
1122
+ $tick = sprintf('%.6f', 0);
1123
+ if($this->lastBenchTime > 0){
1124
+ $tick = sprintf('%.6f', microtime(true) - $this->lastBenchTime);
1125
+ }
1126
+ $this->lastBenchTime = microtime(true);
1127
+ error_log("TimThumb Debug line " . __LINE__ . " [$execTime : $tick]: $msg");
1128
+ }
1129
+ }
1130
+ protected function sanityFail($msg){
1131
+ return $this->error("There is a problem in the timthumb code. Message: Please report this error at <a href='http://code.google.com/p/timthumb/issues/list'>timthumb's bug tracking page</a>: $msg");
1132
+ }
1133
+ protected function getMimeType($file){
1134
+ $info = getimagesize($file);
1135
+ if(is_array($info) && $info['mime']){
1136
+ return $info['mime'];
1137
+ }
1138
+ return '';
1139
+ }
1140
+ protected function setMemoryLimit(){
1141
+ $inimem = ini_get('memory_limit');
1142
+ $inibytes = timthumb::returnBytes($inimem);
1143
+ $ourbytes = timthumb::returnBytes(MEMORY_LIMIT);
1144
+ if($inibytes < $ourbytes){
1145
+ ini_set ('memory_limit', MEMORY_LIMIT);
1146
+ $this->debug(3, "Increased memory from $inimem to " . MEMORY_LIMIT);
1147
+ } else {
1148
+ $this->debug(3, "Not adjusting memory size because the current setting is " . $inimem . " and our size of " . MEMORY_LIMIT . " is smaller.");
1149
+ }
1150
+ }
1151
+ protected static function returnBytes($size_str){
1152
+ switch (substr ($size_str, -1))
1153
+ {
1154
+ case 'M': case 'm': return (int)$size_str * 1048576;
1155
+ case 'K': case 'k': return (int)$size_str * 1024;
1156
+ case 'G': case 'g': return (int)$size_str * 1073741824;
1157
+ default: return $size_str;
1158
+ }
1159
+ }
1160
+
1161
+ protected function getURL($url, $tempfile){
1162
+ $this->lastURLError = false;
1163
+ $url = preg_replace('/ /', '%20', $url);
1164
+ if(function_exists('curl_init')){
1165
+ $this->debug(3, "Curl is installed so using it to fetch URL.");
1166
+ self::$curlFH = fopen($tempfile, 'w');
1167
+ if(! self::$curlFH){
1168
+ $this->error("Could not open $tempfile for writing.");
1169
+ return false;
1170
+ }
1171
+ self::$curlDataWritten = 0;
1172
+ $this->debug(3, "Fetching url with curl: $url");
1173
+ $curl = curl_init($url);
1174
+ curl_setopt ($curl, CURLOPT_TIMEOUT, CURL_TIMEOUT);
1175
+ curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30");
1176
+ curl_setopt ($curl, CURLOPT_RETURNTRANSFER, TRUE);
1177
+ curl_setopt ($curl, CURLOPT_HEADER, 0);
1178
+ curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
1179
+ curl_setopt ($curl, CURLOPT_WRITEFUNCTION, 'timthumb::curlWrite');
1180
+ @curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, true);
1181
+ @curl_setopt ($curl, CURLOPT_MAXREDIRS, 10);
1182
+
1183
+ $curlResult = curl_exec($curl);
1184
+ fclose(self::$curlFH);
1185
+ $httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
1186
+ if($httpStatus == 404){
1187
+ $this->set404();
1188
+ }
1189
+ if($httpStatus == 302){
1190
+ $this->error("External Image is Redirecting. Try alternate image url");
1191
+ return false;
1192
+ }
1193
+ if($curlResult){
1194
+ curl_close($curl);
1195
+ return true;
1196
+ } else {
1197
+ $this->lastURLError = curl_error($curl);
1198
+ curl_close($curl);
1199
+ return false;
1200
+ }
1201
+ } else {
1202
+ $img = @file_get_contents ($url);
1203
+ if($img === false){
1204
+ $err = error_get_last();
1205
+ if(is_array($err) && $err['message']){
1206
+ $this->lastURLError = $err['message'];
1207
+ } else {
1208
+ $this->lastURLError = $err;
1209
+ }
1210
+ if(preg_match('/404/', $this->lastURLError)){
1211
+ $this->set404();
1212
+ }
1213
+
1214
+ return false;
1215
+ }
1216
+ if(! file_put_contents($tempfile, $img)){
1217
+ $this->error("Could not write to $tempfile.");
1218
+ return false;
1219
+ }
1220
+ return true;
1221
+ }
1222
+
1223
+ }
1224
+ protected function serveImg($file){
1225
+ $s = getimagesize($file);
1226
+ if(! ($s && $s['mime'])){
1227
+ return false;
1228
+ }
1229
+ header ('Content-Type: ' . $s['mime']);
1230
+ header ('Content-Length: ' . filesize($file) );
1231
+ header ('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
1232
+ header ("Pragma: no-cache");
1233
+ $bytes = @readfile($file);
1234
+ if($bytes > 0){
1235
+ return true;
1236
+ }
1237
+ $content = @file_get_contents ($file);
1238
+ if ($content != FALSE){
1239
+ echo $content;
1240
+ return true;
1241
+ }
1242
+ return false;
1243
+
1244
+ }
1245
+ protected function set404(){
1246
+ $this->is404 = true;
1247
+ }
1248
+ protected function is404(){
1249
+ return $this->is404;
1250
+ }
1251
+ }
readme.txt CHANGED
@@ -3,7 +3,7 @@ Contributors: Gallery-Bank
3
  Tags: gallery, image, gallery images, album, foto, fotoalbum, website gallery, multiple pictures, pictures, photo, photoalbum, photogallery, photo gallery, lightbox,media, nextgen, nextgen gallery,photo, photo albums, picture, pictures, thumbnails, slideshow
4
  Requires at least: 3.0
5
  Tested up to: 3.5.2
6
- Stable tag: 1.8.6
7
  License: GPLv3 or later
8
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
9
 
@@ -110,12 +110,17 @@ Visit [here](http://gallery-bank.com) to upgrade to Pro Version now.
110
  6. Opening Image of the Album in Lightbox.
111
 
112
  == Changelog ==
113
- = 1.8.5 =
 
 
 
 
 
114
 
115
  * Readme.txt Updated
116
  * Languages Updated
117
 
118
- = 1.8.4 =
119
 
120
  * Timbthumb Quality Issues Fixed
121
  * Formatting Issue Resolved
3
  Tags: gallery, image, gallery images, album, foto, fotoalbum, website gallery, multiple pictures, pictures, photo, photoalbum, photogallery, photo gallery, lightbox,media, nextgen, nextgen gallery,photo, photo albums, picture, pictures, thumbnails, slideshow
4
  Requires at least: 3.0
5
  Tested up to: 3.5.2
6
+ Stable tag: 1.8.7
7
  License: GPLv3 or later
8
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
9
 
110
  6. Opening Image of the Album in Lightbox.
111
 
112
  == Changelog ==
113
+
114
+ = 1.8.7 =
115
+
116
+ * Timbthumb Thumbnails Issue fixed.
117
+
118
+ = 1.8.6 =
119
 
120
  * Readme.txt Updated
121
  * Languages Updated
122
 
123
+ = 1.8.5 =
124
 
125
  * Timbthumb Quality Issues Fixed
126
  * Formatting Issue Resolved