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