source: extensions/stripped_black_bloc/library/phpthumb/phpThumb.php @ 12048

Last change on this file since 12048 was 12048, checked in by flop25, 13 years ago

adding an option to create big thumbnails periodically : new class css, admin option
changing timthumb to phpThumb.php : it's safer and works according document_root
=> new keys to translate

File size: 28.3 KB
RevLine 
[12048]1<?php
2//////////////////////////////////////////////////////////////
3///  phpThumb() by James Heinrich <info@silisoftware.com>   //
4//        available at http://phpthumb.sourceforge.net     ///
5//////////////////////////////////////////////////////////////
6///                                                         //
7// See: phpthumb.changelog.txt for recent changes           //
8// See: phpthumb.readme.txt for usage instructions          //
9//                                                         ///
10//////////////////////////////////////////////////////////////
11
12error_reporting(E_ALL);
13ini_set('display_errors', '1');
14ini_set('magic_quotes_runtime', '0');
15if (ini_get('magic_quotes_runtime')) {
16        die('"magic_quotes_runtime" is set in php.ini, cannot run phpThumb with this enabled');
17}
18$starttime = array_sum(explode(' ', microtime()));
19
20// this script relies on the superglobal arrays, fake it here for old PHP versions
21if (phpversion() < '4.1.0') {
22        $_SERVER = $HTTP_SERVER_VARS;
23        $_GET    = $HTTP_GET_VARS;
24}
25
26function SendSaveAsFileHeaderIfNeeded() {
27        if (headers_sent()) {
28                return false;
29        }
30        global $phpThumb;
31        $downloadfilename = phpthumb_functions::SanitizeFilename(@$_GET['sia'] ? $_GET['sia'] : (@$_GET['down'] ? $_GET['down'] : 'phpThumb_generated_thumbnail'.(@$_GET['f'] ? $_GET['f'] : 'jpg')));
32        if (@$downloadfilename) {
33                $phpThumb->DebugMessage('SendSaveAsFileHeaderIfNeeded() sending header: Content-Disposition: '.(@$_GET['down'] ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"', __FILE__, __LINE__);
34                header('Content-Disposition: '.(@$_GET['down'] ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"');
35        }
36        return true;
37}
38
39function PasswordStrength($password) {
40        $strength = 0;
41        $strength += strlen(preg_replace('#[^a-z]#',       '', $password)) * 0.5; // lowercase characters are weak
42        $strength += strlen(preg_replace('#[^A-Z]#',       '', $password)) * 0.8; // uppercase characters are somewhat better
43        $strength += strlen(preg_replace('#[^0-9]#',       '', $password)) * 1.0; // numbers are somewhat better
44        $strength += strlen(preg_replace('#[a-zA-Z0-9]#',  '', $password)) * 2.0; // other non-alphanumeric characters are best
45        return $strength;
46}
47
48function RedirectToCachedFile() {
49        global $phpThumb, $PHPTHUMB_CONFIG;
50
51        $nice_cachefile = str_replace(DIRECTORY_SEPARATOR, '/', $phpThumb->cache_filename);
52        $nice_docroot   = str_replace(DIRECTORY_SEPARATOR, '/', rtrim($PHPTHUMB_CONFIG['document_root'], '/\\'));
53
54        $parsed_url = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);
55
56        $nModified  = filemtime($phpThumb->cache_filename);
57
58        if ($phpThumb->config_nooffsitelink_enabled && @$_SERVER['HTTP_REFERER'] && !in_array(@$parsed_url['host'], $phpThumb->config_nooffsitelink_valid_domains)) {
59
60                $phpThumb->DebugMessage('Would have used cached (image/'.$phpThumb->thumbnailFormat.') file "'.$phpThumb->cache_filename.'" (Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT), but skipping because $_SERVER[HTTP_REFERER] ('.@$_SERVER['HTTP_REFERER'].') is not in $phpThumb->config_nooffsitelink_valid_domains ('.implode(';', $phpThumb->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);
61
62        } elseif ($phpThumb->phpThumbDebug) {
63
64                $phpThumb->DebugTimingMessage('skipped using cached image', __FILE__, __LINE__);
65                $phpThumb->DebugMessage('Would have used cached file, but skipping due to phpThumbDebug', __FILE__, __LINE__);
66                $phpThumb->DebugMessage('* Would have sent headers (1): Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT', __FILE__, __LINE__);
67                if ($getimagesize = @GetImageSize($phpThumb->cache_filename)) {
68                        $phpThumb->DebugMessage('* Would have sent headers (2): Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]), __FILE__, __LINE__);
69                }
70                if (preg_match('#^'.preg_quote($nice_docroot).'(.*)$#', $nice_cachefile, $matches)) {
71                        $phpThumb->DebugMessage('* Would have sent headers (3): Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])), __FILE__, __LINE__);
72                } else {
73                        $phpThumb->DebugMessage('* Would have sent data: readfile('.$phpThumb->cache_filename.')', __FILE__, __LINE__);
74                }
75
76        } else {
77
78                if (headers_sent()) {
79                        $phpThumb->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');
80                        exit;
81                }
82                SendSaveAsFileHeaderIfNeeded();
83
84                header('Last-Modified: '.gmdate('D, d M Y H:i:s', $nModified).' GMT');
85                if (@$_SERVER['HTTP_IF_MODIFIED_SINCE'] && ($nModified == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) && @$_SERVER['SERVER_PROTOCOL']) {
86                        header($_SERVER['SERVER_PROTOCOL'].' 304 Not Modified');
87                        exit;
88                }
89
90                if ($getimagesize = @GetImageSize($phpThumb->cache_filename)) {
91                        header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));
92                } elseif (preg_match('#\\.ico$#i', $phpThumb->cache_filename)) {
93                        header('Content-Type: image/x-icon');
94                }
95                if (!@$PHPTHUMB_CONFIG['cache_force_passthru'] && preg_match('#^'.preg_quote($nice_docroot).'(.*)$#', $nice_cachefile, $matches)) {
96                        header('Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])));
97                } else {
98                        @readfile($phpThumb->cache_filename);
99                }
100                exit;
101
102        }
103        return true;
104}
105
106
107
108// instantiate a new phpThumb() object
109ob_start();
110if (!include_once(dirname(__FILE__).'/phpthumb.class.php')) {
111        ob_end_flush();
112        die('failed to include_once("'.realpath(dirname(__FILE__).'/phpthumb.class.php').'")');
113}
114ob_end_clean();
115
116$phpThumb = new phpThumb();
117$phpThumb->DebugTimingMessage('phpThumb.php start', __FILE__, __LINE__, $starttime);
118$phpThumb->SetParameter('config_error_die_on_error', true);
119
120if (!phpthumb_functions::FunctionIsDisabled('set_time_limit')) {
121        set_time_limit(60);  // shouldn't take nearly this long in most cases, but with many filters and/or a slow server...
122}
123
124// phpThumbDebug[0] used to be here, but may reveal too much
125// info when high_security_mode should be enabled (not set yet)
126
127if (file_exists(dirname(__FILE__).'/phpThumb.config.php')) {
128        ob_start();
129        if (include_once(dirname(__FILE__).'/phpThumb.config.php')) {
130                // great
131        } else {
132                ob_end_flush();
133                $phpThumb->config_disable_debug = false; // otherwise error message won't print
134                $phpThumb->ErrorImage('failed to include_once('.dirname(__FILE__).'/phpThumb.config.php) - realpath="'.realpath(dirname(__FILE__).'/phpThumb.config.php').'"');
135        }
136        ob_end_clean();
137} elseif (file_exists(dirname(__FILE__).'/phpThumb.config.php.default')) {
138        $phpThumb->config_disable_debug = false; // otherwise error message won't print
139        $phpThumb->ErrorImage('Please rename "phpThumb.config.php.default" to "phpThumb.config.php"');
140} else {
141        $phpThumb->config_disable_debug = false; // otherwise error message won't print
142        $phpThumb->ErrorImage('failed to include_once('.dirname(__FILE__).'/phpThumb.config.php) - realpath="'.realpath(dirname(__FILE__).'/phpThumb.config.php').'"');
143}
144
145if (empty($PHPTHUMB_CONFIG['disable_pathinfo_parsing']) && (empty($_GET) || isset($_GET['phpThumbDebug'])) && !empty($_SERVER['PATH_INFO'])) {
146        $_SERVER['PHP_SELF'] = str_replace($_SERVER['PATH_INFO'], '', @$_SERVER['PHP_SELF']);
147
148        $args = explode(';', substr($_SERVER['PATH_INFO'], 1));
149        $phpThumb->DebugMessage('PATH_INFO.$args set to ('.implode(')(', $args).')', __FILE__, __LINE__);
150        if (!empty($args)) {
151                $_GET['src'] = @$args[count($args) - 1];
152                $phpThumb->DebugMessage('PATH_INFO."src" = "'.$_GET['src'].'"', __FILE__, __LINE__);
153                if (preg_match('#^new\=([a-z0-9]+)#i', $_GET['src'], $matches)) {
154                        unset($_GET['src']);
155                        $_GET['new'] = $matches[1];
156                }
157        }
158        if (preg_match('#^([0-9]*)x?([0-9]*)$#i', @$args[count($args) - 2], $matches)) {
159                $_GET['w'] = $matches[1];
160                $_GET['h'] = $matches[2];
161                $phpThumb->DebugMessage('PATH_INFO."w"x"h" set to "'.$_GET['w'].'"x"'.$_GET['h'].'"', __FILE__, __LINE__);
162        }
163        for ($i = 0; $i < count($args) - 2; $i++) {
164                @list($key, $value) = explode('=', @$args[$i]);
165                if (substr($key, -2) == '[]') {
166                        $array_key_name = substr($key, 0, -2);
167                        $_GET[$array_key_name][] = $value;
168                        $phpThumb->DebugMessage('PATH_INFO."'.$array_key_name.'[]" = "'.$value.'"', __FILE__, __LINE__);
169                } else {
170                        $_GET[$key] = $value;
171                        $phpThumb->DebugMessage('PATH_INFO."'.$key.'" = "'.$value.'"', __FILE__, __LINE__);
172                }
173        }
174}
175
176if (!empty($PHPTHUMB_CONFIG['high_security_enabled'])) {
177        if (empty($_GET['hash'])) {
178                $phpThumb->config_disable_debug = false; // otherwise error message won't print
179                $phpThumb->ErrorImage('ERROR: missing hash');
180        } elseif (PasswordStrength($PHPTHUMB_CONFIG['high_security_password']) < 20) {
181                $phpThumb->config_disable_debug = false; // otherwise error message won't print
182                $phpThumb->ErrorImage('ERROR: $PHPTHUMB_CONFIG[high_security_password] is not complex enough');
183        } elseif ($_GET['hash'] != md5(str_replace('&hash='.$_GET['hash'], '', $_SERVER['QUERY_STRING']).$PHPTHUMB_CONFIG['high_security_password'])) {
184                sleep(10); // deliberate delay to discourage password-guessing
185                $phpThumb->config_disable_debug = false; // otherwise error message won't print
186                $phpThumb->ErrorImage('ERROR: invalid hash');
187        }
188}
189
190////////////////////////////////////////////////////////////////
191// Debug output, to try and help me diagnose problems
192$phpThumb->DebugTimingMessage('phpThumbDebug[0]', __FILE__, __LINE__);
193if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '0')) {
194        $phpThumb->phpThumbDebug();
195}
196////////////////////////////////////////////////////////////////
197
198// returned the fixed string if the evil "magic_quotes_gpc" setting is on
199if (get_magic_quotes_gpc()) {
200        // deprecated: 'err', 'file', 'goto',
201        $RequestVarsToStripSlashes = array('src', 'wmf', 'down');
202        foreach ($RequestVarsToStripSlashes as $key) {
203                if (isset($_GET[$key])) {
204                        if (is_string($_GET[$key])) {
205                                $_GET[$key] = stripslashes($_GET[$key]);
206                        } else {
207                                unset($_GET[$key]);
208                        }
209                }
210        }
211}
212
213if (empty($_SERVER['PATH_INFO']) && empty($_SERVER['QUERY_STRING'])) {
214        $phpThumb->config_disable_debug = false; // otherwise error message won't print
215        $phpThumb->ErrorImage('ERROR: no parameters specified');
216}
217
218if (@$_GET['src'] && isset($_GET['md5s']) && empty($_GET['md5s'])) {
219        if (preg_match('#^(f|ht)tps?://#i', $_GET['src'])) {
220                if ($rawImageData = phpthumb_functions::SafeURLread($_GET['src'], $error, $phpThumb->config_http_fopen_timeout, $phpThumb->config_http_follow_redirect)) {
221                        $md5s = md5($rawImageData);
222                }
223        } else {
224                $SourceFilename = $phpThumb->ResolveFilenameToAbsolute($_GET['src']);
225                if (is_readable($SourceFilename)) {
226                        $md5s = phpthumb_functions::md5_file_safe($SourceFilename);
227                } else {
228                        $phpThumb->ErrorImage('ERROR: "'.$SourceFilename.'" cannot be read');
229                }
230        }
231        if (@$_SERVER['HTTP_REFERER']) {
232                $phpThumb->ErrorImage('&md5s='.$md5s);
233        } else {
234                die('&md5s='.$md5s);
235        }
236}
237
238if (!empty($PHPTHUMB_CONFIG)) {
239        foreach ($PHPTHUMB_CONFIG as $key => $value) {
240                $keyname = 'config_'.$key;
241                $phpThumb->setParameter($keyname, $value);
242                if (!preg_match('#(password|mysql)#i', $key)) {
243                        $phpThumb->DebugMessage('setParameter('.$keyname.', '.$phpThumb->phpThumbDebugVarDump($value).')', __FILE__, __LINE__);
244                }
245        }
246} else {
247        $phpThumb->DebugMessage('$PHPTHUMB_CONFIG is empty', __FILE__, __LINE__);
248}
249
250if (@$_GET['src'] && !@$PHPTHUMB_CONFIG['allow_local_http_src'] && preg_match('#^http://'.@$_SERVER['HTTP_HOST'].'(.+)#i', @$_GET['src'], $matches)) {
251        $phpThumb->ErrorImage('It is MUCH better to specify the "src" parameter as "'.$matches[1].'" instead of "'.$matches[0].'".'."\n\n".'If you really must do it this way, enable "allow_local_http_src" in phpThumb.config.php');
252}
253
254////////////////////////////////////////////////////////////////
255// Debug output, to try and help me diagnose problems
256$phpThumb->DebugTimingMessage('phpThumbDebug[1]', __FILE__, __LINE__);
257if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '1')) {
258        $phpThumb->phpThumbDebug();
259}
260////////////////////////////////////////////////////////////////
261
262$parsed_url_referer = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);
263if ($phpThumb->config_nooffsitelink_require_refer && !in_array(@$parsed_url_referer['host'], $phpThumb->config_nohotlink_valid_domains)) {
264        $phpThumb->ErrorImage('config_nooffsitelink_require_refer enabled and '.(@$parsed_url_referer['host'] ? '"'.$parsed_url_referer['host'].'" is not an allowed referer' : 'no HTTP_REFERER exists'));
265}
266$parsed_url_src = phpthumb_functions::ParseURLbetter(@$_GET['src']);
267if ($phpThumb->config_nohotlink_enabled && $phpThumb->config_nohotlink_erase_image && preg_match('#^(f|ht)tps?://#i', @$_GET['src']) && !in_array(@$parsed_url_src['host'], $phpThumb->config_nohotlink_valid_domains)) {
268        $phpThumb->ErrorImage($phpThumb->config_nohotlink_text_message);
269}
270
271if ($phpThumb->config_mysql_query) {
272        if ($cid = @mysql_connect($phpThumb->config_mysql_hostname, $phpThumb->config_mysql_username, $phpThumb->config_mysql_password)) {
273                if (@mysql_select_db($phpThumb->config_mysql_database, $cid)) {
274                        if ($result = @mysql_query($phpThumb->config_mysql_query, $cid)) {
275                                if ($row = @mysql_fetch_array($result)) {
276
277                                        mysql_free_result($result);
278                                        mysql_close($cid);
279                                        $phpThumb->setSourceData($row[0]);
280                                        unset($row);
281
282                                } else {
283                                        mysql_free_result($result);
284                                        mysql_close($cid);
285                                        $phpThumb->ErrorImage('no matching data in database.');
286                                }
287                        } else {
288                                mysql_close($cid);
289                                $phpThumb->ErrorImage('Error in MySQL query: "'.mysql_error($cid).'"');
290                        }
291                } else {
292                        mysql_close($cid);
293                        $phpThumb->ErrorImage('cannot select MySQL database: "'.mysql_error($cid).'"');
294                }
295        } else {
296                $phpThumb->ErrorImage('cannot connect to MySQL server');
297        }
298        unset($_GET['id']);
299}
300
301////////////////////////////////////////////////////////////////
302// Debug output, to try and help me diagnose problems
303$phpThumb->DebugTimingMessage('phpThumbDebug[2]', __FILE__, __LINE__);
304if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '2')) {
305        $phpThumb->phpThumbDebug();
306}
307////////////////////////////////////////////////////////////////
308
309$PHPTHUMB_DEFAULTS_DISABLEGETPARAMS = (bool) (@$PHPTHUMB_CONFIG['cache_default_only_suffix'] && (strpos($PHPTHUMB_CONFIG['cache_default_only_suffix'], '*') !== false));
310
311if (!empty($PHPTHUMB_DEFAULTS) && is_array($PHPTHUMB_DEFAULTS)) {
312        $phpThumb->DebugMessage('setting $PHPTHUMB_DEFAULTS['.implode(';', array_keys($PHPTHUMB_DEFAULTS)).']', __FILE__, __LINE__);
313        foreach ($PHPTHUMB_DEFAULTS as $key => $value) {
314                if ($PHPTHUMB_DEFAULTS_GETSTRINGOVERRIDE || !isset($_GET[$key])) {
315                        $_GET[$key] = $value;
316                        $phpThumb->DebugMessage('PHPTHUMB_DEFAULTS assigning ('.$value.') to $_GET['.$key.']', __FILE__, __LINE__);
317                }
318        }
319}
320
321// deprecated: 'err', 'file', 'goto',
322$allowedGETparameters = array('src', 'new', 'w', 'h', 'wp', 'hp', 'wl', 'hl', 'ws', 'hs', 'f', 'q', 'sx', 'sy', 'sw', 'sh', 'zc', 'bc', 'bg', 'bgt', 'fltr', 'xto', 'ra', 'ar', 'aoe', 'far', 'iar', 'maxb', 'down', 'phpThumbDebug', 'hash', 'md5s', 'sfn', 'dpi', 'sia', 'nocache');
323foreach ($_GET as $key => $value) {
324        if (!empty($PHPTHUMB_DEFAULTS_DISABLEGETPARAMS) && ($key != 'src')) {
325                // disabled, do not set parameter
326                $phpThumb->DebugMessage('ignoring $_GET['.$key.'] because of $PHPTHUMB_DEFAULTS_DISABLEGETPARAMS', __FILE__, __LINE__);
327        } elseif (in_array($key, $allowedGETparameters)) {
328                $phpThumb->DebugMessage('setParameter('.$key.', '.$phpThumb->phpThumbDebugVarDump($value).')', __FILE__, __LINE__);
329                $phpThumb->setParameter($key, $value);
330        } else {
331                $phpThumb->ErrorImage('Forbidden parameter: '.$key);
332        }
333}
334
335////////////////////////////////////////////////////////////////
336// Debug output, to try and help me diagnose problems
337$phpThumb->DebugTimingMessage('phpThumbDebug[3]', __FILE__, __LINE__);
338if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '3')) {
339        $phpThumb->phpThumbDebug();
340}
341////////////////////////////////////////////////////////////////
342
343//if (!@$_GET['phpThumbDebug'] && !is_file($phpThumb->sourceFilename) && !phpthumb_functions::gd_version()) {
344//      if (!headers_sent()) {
345//              // base64-encoded error image in GIF format
346//              $ERROR_NOGD = 'R0lGODlhIAAgALMAAAAAABQUFCQkJDY2NkZGRldXV2ZmZnJycoaGhpSUlKWlpbe3t8XFxdXV1eTk5P7+/iwAAAAAIAAgAAAE/vDJSau9WILtTAACUinDNijZtAHfCojS4W5H+qxD8xibIDE9h0OwWaRWDIljJSkUJYsN4bihMB8th3IToAKs1VtYM75cyV8sZ8vygtOE5yMKmGbO4jRdICQCjHdlZzwzNW4qZSQmKDaNjhUMBX4BBAlmMywFSRWEmAI6b5gAlhNxokGhooAIK5o/pi9vEw4Lfj4OLTAUpj6IabMtCwlSFw0DCKBoFqwAB04AjI54PyZ+yY3TD0ss2YcVmN/gvpcu4TOyFivWqYJlbAHPpOntvxNAACcmGHjZzAZqzSzcq5fNjxFmAFw9iFRunD1epU6tsIPmFCAJnWYE0FURk7wJDA0MTKpEzoWAAskiAAA7';
347//              header('Content-Type: image/gif');
348//              echo base64_decode($ERROR_NOGD);
349//      } else {
350//              echo '*** ERROR: No PHP-GD support available ***';
351//      }
352//      exit;
353//}
354
355// check to see if file can be output from source with no processing or caching
356$CanPassThroughDirectly = true;
357if ($phpThumb->rawImageData) {
358        // data from SQL, should be fine
359} elseif (preg_match('#^http\://[^\\?&]+\\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
360        // assume is ok to passthru if no other parameters specified
361} elseif (preg_match('#^(f|ht)tp\://#i', $phpThumb->src)) {
362        $phpThumb->DebugMessage('$CanPassThroughDirectly=false because preg_match("#^(f|ht)tp\://#i", '.$phpThumb->src.')', __FILE__, __LINE__);
363        $CanPassThroughDirectly = false;
364} elseif (!@is_readable($phpThumb->sourceFilename)) {
365        $phpThumb->DebugMessage('$CanPassThroughDirectly=false because !@is_readable('.$phpThumb->sourceFilename.')', __FILE__, __LINE__);
366        $CanPassThroughDirectly = false;
367} elseif (!@is_file($phpThumb->sourceFilename)) {
368        $phpThumb->DebugMessage('$CanPassThroughDirectly=false because !@is_file('.$phpThumb->sourceFilename.')', __FILE__, __LINE__);
369        $CanPassThroughDirectly = false;
370}
371foreach ($_GET as $key => $value) {
372        switch ($key) {
373                case 'src':
374                        // allowed
375                        break;
376
377                case 'w':
378                case 'h':
379                        // might be OK if exactly matches original
380                        if (preg_match('#^http\://[^\\?&]+\\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
381                                // assume it is not ok for direct-passthru of remote image
382                                $CanPassThroughDirectly = false;
383                        }
384                        break;
385
386                case 'phpThumbDebug':
387                        // handled in direct-passthru code
388                        break;
389
390                default:
391                        // all other parameters will cause some processing,
392                        // therefore cannot pass through original image unmodified
393                        $CanPassThroughDirectly = false;
394                        $UnAllowedGET[] = $key;
395                        break;
396        }
397}
398if (!empty($UnAllowedGET)) {
399        $phpThumb->DebugMessage('$CanPassThroughDirectly=false because $_GET['.implode(';', array_unique($UnAllowedGET)).'] are set', __FILE__, __LINE__);
400}
401
402////////////////////////////////////////////////////////////////
403// Debug output, to try and help me diagnose problems
404$phpThumb->DebugTimingMessage('phpThumbDebug[4]', __FILE__, __LINE__);
405if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '4')) {
406        $phpThumb->phpThumbDebug();
407}
408////////////////////////////////////////////////////////////////
409
410$phpThumb->DebugMessage('$CanPassThroughDirectly="'.intval($CanPassThroughDirectly).'" && $phpThumb->src="'.$phpThumb->src.'"', __FILE__, __LINE__);
411while ($CanPassThroughDirectly && $phpThumb->src) {
412        // no parameters set, passthru
413
414        if (preg_match('#^http\://[^\\?&]+\.(jpe?g|gif|png)$#i', $phpThumb->src)) {
415                $phpThumb->DebugMessage('Passing HTTP source through directly as Location: redirect ('.$phpThumb->src.')', __FILE__, __LINE__);
416                header('Location: '.$phpThumb->src);
417                exit;
418        }
419
420        $SourceFilename = $phpThumb->ResolveFilenameToAbsolute($phpThumb->src);
421
422        // security and size checks
423        if ($phpThumb->getimagesizeinfo = @GetImageSize($SourceFilename)) {
424                $phpThumb->DebugMessage('Direct passthru GetImageSize() returned [w='.$phpThumb->getimagesizeinfo[0].';h='.$phpThumb->getimagesizeinfo[1].';t='.$phpThumb->getimagesizeinfo[2].']', __FILE__, __LINE__);
425
426                if (!@$_GET['w'] && !@$_GET['wp'] && !@$_GET['wl'] && !@$_GET['ws'] && !@$_GET['h'] && !@$_GET['hp'] && !@$_GET['hl'] && !@$_GET['hs']) {
427                        // no resizing needed
428                        $phpThumb->DebugMessage('Passing "'.$SourceFilename.'" through directly, no resizing required ("'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'")', __FILE__, __LINE__);
429                } elseif (($phpThumb->getimagesizeinfo[0] <= @$_GET['w']) && ($phpThumb->getimagesizeinfo[1] <= @$_GET['h']) && ((@$_GET['w'] == $phpThumb->getimagesizeinfo[0]) || (@$_GET['h'] == $phpThumb->getimagesizeinfo[1]))) {
430                        // image fits into 'w'x'h' box, and at least one dimension matches exactly, therefore no resizing needed
431                        $phpThumb->DebugMessage('Passing "'.$SourceFilename.'" through directly, no resizing required ("'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'" fits inside "'.@$_GET['w'].'"x"'.@$_GET['h'].'")', __FILE__, __LINE__);
432                } else {
433                        $phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because resizing required (from "'.$phpThumb->getimagesizeinfo[0].'"x"'.$phpThumb->getimagesizeinfo[1].'" to "'.@$_GET['w'].'"x"'.@$_GET['h'].'")', __FILE__, __LINE__);
434                        break;
435                }
436                switch ($phpThumb->getimagesizeinfo[2]) {
437                        case 1: // GIF
438                        case 2: // JPG
439                        case 3: // PNG
440                                // great, let it through
441                                break;
442                        default:
443                                // browser probably can't handle format, remangle it to JPEG/PNG/GIF
444                                $phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because $phpThumb->getimagesizeinfo[2] = "'.$phpThumb->getimagesizeinfo[2].'"', __FILE__, __LINE__);
445                                break 2;
446                }
447
448                $ImageCreateFunctions = array(1=>'ImageCreateFromGIF', 2=>'ImageCreateFromJPEG', 3=>'ImageCreateFromPNG');
449                $theImageCreateFunction = @$ImageCreateFunctions[$phpThumb->getimagesizeinfo[2]];
450                if ($phpThumb->config_disable_onlycreateable_passthru || (function_exists($theImageCreateFunction) && ($dummyImage = @$theImageCreateFunction($SourceFilename)))) {
451
452                        // great
453                        if (@is_resource($dummyImage)) {
454                                unset($dummyImage);
455                        }
456
457                        if (headers_sent()) {
458                                $phpThumb->ErrorImage('Headers already sent ('.basename(__FILE__).' line '.__LINE__.')');
459                                exit;
460                        }
461                        if (@$_GET['phpThumbDebug']) {
462                                $phpThumb->DebugTimingMessage('skipped direct $SourceFilename passthru', __FILE__, __LINE__);
463                                $phpThumb->DebugMessage('Would have passed "'.$SourceFilename.'" through directly, but skipping due to phpThumbDebug', __FILE__, __LINE__);
464                                break;
465                        }
466
467                        SendSaveAsFileHeaderIfNeeded();
468                        header('Last-Modified: '.gmdate('D, d M Y H:i:s', @filemtime($SourceFilename)).' GMT');
469                        if ($contentType = phpthumb_functions::ImageTypeToMIMEtype(@$phpThumb->getimagesizeinfo[2])) {
470                                header('Content-Type: '.$contentType);
471                        }
472                        @readfile($SourceFilename);
473                        exit;
474
475                } else {
476                        $phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because ($phpThumb->config_disable_onlycreateable_passthru = "'.$phpThumb->config_disable_onlycreateable_passthru.'") and '.$theImageCreateFunction.'() failed', __FILE__, __LINE__);
477                        break;
478                }
479
480        } else {
481                $phpThumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because GetImageSize() failed', __FILE__, __LINE__);
482                break;
483        }
484        break;
485}
486
487////////////////////////////////////////////////////////////////
488// Debug output, to try and help me diagnose problems
489$phpThumb->DebugTimingMessage('phpThumbDebug[5]', __FILE__, __LINE__);
490if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '5')) {
491        $phpThumb->phpThumbDebug();
492}
493////////////////////////////////////////////////////////////////
494
495// check to see if file already exists in cache, and output it with no processing if it does
496$phpThumb->SetCacheFilename();
497if (@is_readable($phpThumb->cache_filename)) {
498        RedirectToCachedFile();
499} else {
500        $phpThumb->DebugMessage('Cached file "'.$phpThumb->cache_filename.'" does not exist, processing as normal', __FILE__, __LINE__);
501}
502
503////////////////////////////////////////////////////////////////
504// Debug output, to try and help me diagnose problems
505$phpThumb->DebugTimingMessage('phpThumbDebug[6]', __FILE__, __LINE__);
506if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '6')) {
507        $phpThumb->phpThumbDebug();
508}
509////////////////////////////////////////////////////////////////
510
511if ($phpThumb->rawImageData) {
512
513        // great
514
515} elseif (!empty($_GET['new'])) {
516
517        // generate a blank image resource of the specified size/background color/opacity
518        if (($phpThumb->w <= 0) || ($phpThumb->h <= 0)) {
519                $phpThumb->ErrorImage('"w" and "h" parameters required for "new"');
520        }
521        @list($bghexcolor, $opacity) = explode('|', $_GET['new']);
522        if (!phpthumb_functions::IsHexColor($bghexcolor)) {
523                $phpThumb->ErrorImage('BGcolor parameter for "new" is not valid');
524        }
525        $opacity = (strlen($opacity) ? $opacity : 100);
526        if ($phpThumb->gdimg_source = phpthumb_functions::ImageCreateFunction($phpThumb->w, $phpThumb->h)) {
527                $alpha = (100 - min(100, max(0, $opacity))) * 1.27;
528                if ($alpha) {
529                        $phpThumb->setParameter('is_alpha', true);
530                        ImageAlphaBlending($phpThumb->gdimg_source, false);
531                        ImageSaveAlpha($phpThumb->gdimg_source, true);
532                }
533                $new_background_color = phpthumb_functions::ImageHexColorAllocate($phpThumb->gdimg_source, $bghexcolor, false, $alpha);
534                ImageFilledRectangle($phpThumb->gdimg_source, 0, 0, $phpThumb->w, $phpThumb->h, $new_background_color);
535        } else {
536                $phpThumb->ErrorImage('failed to create "new" image ('.$phpThumb->w.'x'.$phpThumb->h.')');
537        }
538
539} elseif (!$phpThumb->src) {
540
541        $phpThumb->ErrorImage('Usage: '.$_SERVER['PHP_SELF'].'?src=/path/and/filename.jpg'."\n".'read Usage comments for details');
542
543} elseif (preg_match('#^(f|ht)tp\://#i', $phpThumb->src)) {
544
545        $phpThumb->DebugMessage('$phpThumb->src ('.$phpThumb->src.') is remote image, attempting to download', __FILE__, __LINE__);
546        if ($phpThumb->config_http_user_agent) {
547                $phpThumb->DebugMessage('Setting "user_agent" to "'.$phpThumb->config_http_user_agent.'"', __FILE__, __LINE__);
548                ini_set('user_agent', $phpThumb->config_http_user_agent);
549        }
550        $cleanedupurl = phpthumb_functions::CleanUpURLencoding($phpThumb->src);
551        $phpThumb->DebugMessage('CleanUpURLencoding('.$phpThumb->src.') returned "'.$cleanedupurl.'"', __FILE__, __LINE__);
552        $phpThumb->src = $cleanedupurl;
553        unset($cleanedupurl);
554        if ($rawImageData = phpthumb_functions::SafeURLread($phpThumb->src, $error, $phpThumb->config_http_fopen_timeout, $phpThumb->config_http_follow_redirect)) {
555                $phpThumb->DebugMessage('SafeURLread('.$phpThumb->src.') succeeded'.($error ? ' with messsages: "'.$error.'"' : ''), __FILE__, __LINE__);
556                $phpThumb->DebugMessage('Setting source data from URL "'.$phpThumb->src.'"', __FILE__, __LINE__);
557                $phpThumb->setSourceData($rawImageData, urlencode($phpThumb->src));
558        } else {
559                $phpThumb->ErrorImage($error);
560        }
561}
562
563////////////////////////////////////////////////////////////////
564// Debug output, to try and help me diagnose problems
565$phpThumb->DebugTimingMessage('phpThumbDebug[7]', __FILE__, __LINE__);
566if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '7')) {
567        $phpThumb->phpThumbDebug();
568}
569////////////////////////////////////////////////////////////////
570
571$phpThumb->GenerateThumbnail();
572
573////////////////////////////////////////////////////////////////
574// Debug output, to try and help me diagnose problems
575$phpThumb->DebugTimingMessage('phpThumbDebug[8]', __FILE__, __LINE__);
576if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '8')) {
577        $phpThumb->phpThumbDebug();
578}
579////////////////////////////////////////////////////////////////
580
581if (!empty($PHPTHUMB_CONFIG['high_security_enabled']) && !empty($_GET['nocache'])) {
582
583        // cache disabled, don't write cachefile
584
585} else {
586
587        phpthumb_functions::EnsureDirectoryExists(dirname($phpThumb->cache_filename));
588        if (is_writable(dirname($phpThumb->cache_filename)) || (file_exists($phpThumb->cache_filename) && is_writable($phpThumb->cache_filename))) {
589
590                $phpThumb->CleanUpCacheDirectory();
591                if ($phpThumb->RenderToFile($phpThumb->cache_filename) && is_readable($phpThumb->cache_filename)) {
592                        chmod($phpThumb->cache_filename, 0644);
593                        RedirectToCachedFile();
594                } else {
595                        $phpThumb->DebugMessage('Failed: RenderToFile('.$phpThumb->cache_filename.')', __FILE__, __LINE__);
596                }
597
598        } else {
599
600                $phpThumb->DebugMessage('Cannot write to $phpThumb->cache_filename ('.$phpThumb->cache_filename.') because that directory ('.dirname($phpThumb->cache_filename).') is not writable', __FILE__, __LINE__);
601
602        }
603
604}
605
606////////////////////////////////////////////////////////////////
607// Debug output, to try and help me diagnose problems
608$phpThumb->DebugTimingMessage('phpThumbDebug[9]', __FILE__, __LINE__);
609if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '9')) {
610        $phpThumb->phpThumbDebug();
611}
612////////////////////////////////////////////////////////////////
613
614if (!$phpThumb->OutputThumbnail()) {
615        $phpThumb->ErrorImage('Error in OutputThumbnail():'."\n".$phpThumb->debugmessages[(count($phpThumb->debugmessages) - 1)]);
616}
617
618////////////////////////////////////////////////////////////////
619// Debug output, to try and help me diagnose problems
620$phpThumb->DebugTimingMessage('phpThumbDebug[10]', __FILE__, __LINE__);
621if (isset($_GET['phpThumbDebug']) && ($_GET['phpThumbDebug'] == '10')) {
622        $phpThumb->phpThumbDebug();
623}
624////////////////////////////////////////////////////////////////
625
626?>
Note: See TracBrowser for help on using the repository browser.