PageRenderTime 44ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/Vendor/phpThumb/phpThumb.php

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