PageRenderTime 62ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/cms113/phpthumb.php

http://cmsfromscratch.googlecode.com/
PHP | 471 lines | 340 code | 66 blank | 65 comment | 126 complexity | 24bbf28184822781c10915d250f01cb5 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1
  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. if (!@ini_get('safe_mode')) {
  14. set_time_limit(60); // shouldn't take nearly this long in most cases, but with many filter and/or a slow server...
  15. }
  16. // this script relies on the superglobal arrays, fake it here for old PHP versions
  17. if (phpversion() < '4.1.0') {
  18. $_SERVER = $HTTP_SERVER_VARS;
  19. $_GET = $HTTP_GET_VARS;
  20. }
  21. if (file_exists('phpthumb.config.php')) {
  22. ob_start();
  23. if (include_once(dirname(__FILE__).'/phpthumb.config.php')) {
  24. // great
  25. } else {
  26. ob_end_flush();
  27. die('failed to include_once('.dirname(__FILE__).'/phpthumb.config.php) - realpath="'.realpath(dirname(__FILE__).'/phpthumb.config.php').'"');
  28. }
  29. ob_end_clean();
  30. } elseif (file_exists('phpthumb.config.php.default')) {
  31. die('Please rename "phpthumb.config.php.default" to "phpthumb.config.php"');
  32. } else {
  33. die('failed to include_once('.dirname(__FILE__).'/phpthumb.config.php) - realpath="'.realpath(dirname(__FILE__).'/phpthumb.config.php').'"');
  34. }
  35. if (!@$_SERVER['QUERY_STRING']) {
  36. die('$_SERVER[QUERY_STRING] is empty');
  37. }
  38. if (@$PHPTHUMB_CONFIG['high_security_enabled']) {
  39. if (!@$_GET['hash']) {
  40. die('ERROR: missing hash');
  41. }
  42. if (strlen($PHPTHUMB_CONFIG['high_security_password']) < 5) {
  43. die('ERROR: strlen($PHPTHUMB_CONFIG[high_security_password]) < 5');
  44. }
  45. if ($_GET['hash'] != md5(str_replace('&hash='.$_GET['hash'], '', $_SERVER['QUERY_STRING']).$PHPTHUMB_CONFIG['high_security_password'])) {
  46. die('ERROR: invalid hash');
  47. }
  48. }
  49. if (!function_exists('ImageJPEG') && !function_exists('ImagePNG') && !function_exists('ImageGIF')) {
  50. // base64-encoded error image in GIF format
  51. $ERROR_NOGD = 'R0lGODlhIAAgALMAAAAAABQUFCQkJDY2NkZGRldXV2ZmZnJycoaGhpSUlKWlpbe3t8XFxdXV1eTk5P7+/iwAAAAAIAAgAAAE/vDJSau9WILtTAACUinDNijZtAHfCojS4W5H+qxD8xibIDE9h0OwWaRWDIljJSkUJYsN4bihMB8th3IToAKs1VtYM75cyV8sZ8vygtOE5yMKmGbO4jRdICQCjHdlZzwzNW4qZSQmKDaNjhUMBX4BBAlmMywFSRWEmAI6b5gAlhNxokGhooAIK5o/pi9vEw4Lfj4OLTAUpj6IabMtCwlSFw0DCKBoFqwAB04AjI54PyZ+yY3TD0ss2YcVmN/gvpcu4TOyFivWqYJlbAHPpOntvxNAACcmGHjZzAZqzSzcq5fNjxFmAFw9iFRunD1epU6tsIPmFCAJnWYE0FURk7wJDA0MTKpEzoWAAskiAAA7';
  52. header('Content-Type: image/gif');
  53. echo base64_decode($ERROR_NOGD);
  54. exit;
  55. }
  56. // returned the fixed string if the evil "magic_quotes_gpc" setting is on
  57. if (get_magic_quotes_gpc()) {
  58. $RequestVarsToStripSlashes = array('src', 'wmf', 'file', 'err', 'goto', 'down');
  59. foreach ($RequestVarsToStripSlashes as $key) {
  60. if (isset($_GET[$key])) {
  61. $_GET[$key] = stripslashes($_GET[$key]);
  62. }
  63. }
  64. }
  65. // instantiate a new phpthumb() object
  66. ob_start();
  67. if (!include_once(dirname(__FILE__).'/phpthumb.class.php')) {
  68. ob_end_flush();
  69. die('failed to include_once("'.realpath(dirname(__FILE__).'/phpthumb.class.php').'")');
  70. }
  71. ob_end_clean();
  72. $phpthumb = new phpthumb();
  73. if (@$_GET['src'] && isset($_GET['md5s']) && empty($_GET['md5s'])) {
  74. if (eregi('^(f|ht)tp[s]?://', $_GET['src'])) {
  75. if ($fp_source = @fopen($_GET['src'], 'rb')) {
  76. $filedata = '';
  77. while (true) {
  78. $buffer = fread($fp_source, 16384);
  79. if (strlen($buffer) == 0) {
  80. break;
  81. }
  82. $filedata .= $buffer;
  83. }
  84. fclose($fp_source);
  85. $md5s = md5($filedata);
  86. }
  87. } else {
  88. $SourceFilename = $phpthumb->ResolveFilenameToAbsolute($_GET['src']);
  89. if (is_readable($SourceFilename)) {
  90. $md5s = phpthumb_functions::md5_file_safe($SourceFilename);
  91. } else {
  92. $phpthumb->ErrorImage('ERROR: "'.$SourceFilename.'" cannot be read');
  93. }
  94. }
  95. if (@$_SERVER['HTTP_REFERER']) {
  96. $phpthumb->ErrorImage('&md5s='.$md5s);
  97. } else {
  98. die('&md5s='.$md5s);
  99. }
  100. }
  101. foreach ($PHPTHUMB_CONFIG as $key => $value) {
  102. $keyname = 'config_'.$key;
  103. $phpthumb->$keyname = $value;
  104. }
  105. ////////////////////////////////////////////////////////////////
  106. // Debug output, to try and help me diagnose problems
  107. if (@$_GET['phpthumbDebug'] == '1') {
  108. $phpthumb->phpthumbDebug();
  109. }
  110. ////////////////////////////////////////////////////////////////
  111. $parsed_url_referer = parse_url(@$_SERVER['HTTP_REFERER']);
  112. if ($phpthumb->config_nooffsitelink_require_refer && !in_array(@$parsed_url_referer['host'], $phpthumb->config_nohotlink_valid_domains)) {
  113. $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'));
  114. }
  115. $parsed_url_src = parse_url(@$_GET['src']);
  116. if ($phpthumb->config_nohotlink_enabled && $phpthumb->config_nohotlink_erase_image && eregi('^(f|ht)tp[s]?://', @$_GET['src']) && !in_array(@$parsed_url_src['host'], $phpthumb->config_nohotlink_valid_domains)) {
  117. $phpthumb->ErrorImage($phpthumb->config_nohotlink_text_message);
  118. }
  119. ////////////////////////////////////////////////////////////////
  120. // You may want to pull data from a database rather than a physical file
  121. // If so, uncomment the following $SQLquery line (modified to suit your database)
  122. // Note: this must be the actual binary data of the image, not a URL or filename
  123. // see http://www.billy-corgan.com/blog/archive/000143.php for a brief tutorial on this section
  124. //$SQLquery = 'SELECT `picture` FROM `products` WHERE (`id` = \''.mysql_escape_string(@$_GET['id']).'\')';
  125. if (@$SQLquery) {
  126. // change this information to match your server
  127. $hostname = 'localhost';
  128. $username = 'username';
  129. $password = 'password';
  130. $database = 'database';
  131. if ($cid = @mysql_connect($hostname, $username, $password)) {
  132. if (@mysql_select_db($database, $cid)) {
  133. if ($result = @mysql_query($SQLquery, $cid)) {
  134. if ($row = @mysql_fetch_array($result)) {
  135. mysql_free_result($result);
  136. mysql_close($cid);
  137. $phpthumb->setSourceData($row[0]);
  138. unset($row);
  139. } else {
  140. mysql_free_result($result);
  141. mysql_close($cid);
  142. $phpthumb->ErrorImage('no matching data in database.');
  143. //$phpthumb->ErrorImage('no matching data in database. MySQL said: "'.mysql_error($cid).'"');
  144. }
  145. } else {
  146. mysql_close($cid);
  147. $phpthumb->ErrorImage('Error in MySQL query: "'.mysql_error($cid).'"');
  148. }
  149. } else {
  150. mysql_close($cid);
  151. $phpthumb->ErrorImage('cannot select MySQL database: "'.mysql_error($cid).'"');
  152. }
  153. } else {
  154. $phpthumb->ErrorImage('cannot connect to MySQL server');
  155. }
  156. unset($_GET['id']);
  157. }
  158. ////////////////////////////////////////////////////////////////
  159. // Debug output, to try and help me diagnose problems
  160. if (@$_GET['phpthumbDebug'] == '2') {
  161. $phpthumb->phpthumbDebug();
  162. }
  163. ////////////////////////////////////////////////////////////////
  164. $allowedGETparameters = array('src', 'new', 'w', 'h', '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');
  165. foreach ($_GET as $key => $value) {
  166. if (in_array($key, $allowedGETparameters)) {
  167. $phpthumb->$key = $value;
  168. } else {
  169. $phpthumb->ErrorImage('Forbidden parameter: '.$key);
  170. }
  171. }
  172. if (!empty($PHPTHUMB_DEFAULTS)) {
  173. foreach ($PHPTHUMB_DEFAULTS as $key => $value) {
  174. if ($PHPTHUMB_DEFAULTS_GETSTRINGOVERRIDE || !isset($_GET[$key])) {
  175. $phpthumb->$key = $value;
  176. }
  177. }
  178. }
  179. ////////////////////////////////////////////////////////////////
  180. // Debug output, to try and help me diagnose problems
  181. if (@$_GET['phpthumbDebug'] == '3') {
  182. $phpthumb->phpthumbDebug();
  183. }
  184. ////////////////////////////////////////////////////////////////
  185. // check to see if file can be output from source with no processing or caching
  186. $CanPassThroughDirectly = true;
  187. if (!empty($phpthumb->rawImageData)) {
  188. // data from SQL, should be fine
  189. } elseif (!@is_file(@$_GET['src']) || !@is_readable(@$_GET['src'])) {
  190. $CanPassThroughDirectly = false;
  191. }
  192. foreach ($_GET as $key => $value) {
  193. switch ($key) {
  194. case 'src':
  195. // allowed
  196. break;
  197. default:
  198. // all other parameters will cause some processing,
  199. // therefore cannot pass through original image unmodified
  200. $CanPassThroughDirectly = false;
  201. $UnAllowedGET[] = $key;
  202. break;
  203. }
  204. }
  205. if (!empty($UnAllowedGET)) {
  206. $phpthumb->DebugMessage('Cannot pass through directly because $_GET['.implode(';', array_unique($UnAllowedGET)).'] are set', __FILE__, __LINE__);
  207. }
  208. ////////////////////////////////////////////////////////////////
  209. // Debug output, to try and help me diagnose problems
  210. if (@$_GET['phpthumbDebug'] == '4') {
  211. $phpthumb->phpthumbDebug();
  212. }
  213. ////////////////////////////////////////////////////////////////
  214. function SendSaveAsFileHeaderIfNeeded() {
  215. global $phpthumb;
  216. if (@$_GET['down']) {
  217. $downloadfilename = ereg_replace('[/\\:\*\?"<>|]', '_', $_GET['down']);
  218. if (phpthumb_functions::version_compare_replacement(phpversion(), '4.1.0', '>=')) {
  219. $downloadfilename = trim($downloadfilename, '.');
  220. }
  221. if (@$downloadfilename) {
  222. $phpthumb->DebugMessage('SendSaveAsFileHeaderIfNeeded() sending header: Content-Disposition: attachment; filename="'.$downloadfilename.'"', __FILE__, __LINE__);
  223. header('Content-Disposition: attachment; filename="'.$downloadfilename.'"');
  224. return true;
  225. }
  226. }
  227. $phpthumb->DebugMessage('SendSaveAsFileHeaderIfNeeded() sending header: Content-Disposition: inline', __FILE__, __LINE__);
  228. header('Content-Disposition: inline');
  229. return true;
  230. }
  231. while ($CanPassThroughDirectly && $phpthumb->src) {
  232. // no parameters set, passthru
  233. $SourceFilename = $phpthumb->ResolveFilenameToAbsolute($phpthumb->src);
  234. if (!GetImageSize($SourceFilename)) {
  235. // security -- prevent passing through of non-image files
  236. $phpthumb->DebugMessage('GetImageSize('.$SourceFilename.') failed (invalid image?)', __FILE__, __LINE__);
  237. } else if (@$_GET['phpthumbDebug']) {
  238. $phpthumb->DebugMessage('Would have passed "'.$SourceFilename.'" through directly, but skipping due to phpthumbDebug', __FILE__, __LINE__);
  239. } else {
  240. // security checks
  241. if ($GetImageSize = @GetImageSize($SourceFilename)) {
  242. $ImageCreateFunctions = array(1=>'ImageCreateFromGIF', 2=>'ImageCreateFromJPEG', 3=>'ImageCreateFromPNG');
  243. if (@$ImageCreateFunctions[$GetImageSize[2]]) {
  244. $theFunction = $ImageCreateFunctions[$GetImageSize[2]];
  245. if (function_exists($theFunction) && ($dummyImage = @$theFunction($SourceFilename))) {
  246. // great
  247. unset($dummyImage);
  248. } else {
  249. $phpthumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because '.$theFunction.'() failed', __FILE__, __LINE__);
  250. break;
  251. }
  252. } else {
  253. $phpthumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because GetImageSize() returned unhandled image type "'.$GetImageSize[2].'"', __FILE__, __LINE__);
  254. break;
  255. }
  256. } else {
  257. $phpthumb->DebugMessage('Not passing "'.$SourceFilename.'" through directly because GetImageSize() failed', __FILE__, __LINE__);
  258. break;
  259. }
  260. SendSaveAsFileHeaderIfNeeded();
  261. header('Last-Modified: '.gmdate('D, d M Y H:i:s', @filemtime($SourceFilename)).' GMT');
  262. if ($getimagesize = @GetImageSize($SourceFilename)) {
  263. header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));
  264. }
  265. @readfile($SourceFilename);
  266. exit;
  267. }
  268. break;
  269. }
  270. ////////////////////////////////////////////////////////////////
  271. // Debug output, to try and help me diagnose problems
  272. if (@$_GET['phpthumbDebug'] == '5') {
  273. $phpthumb->phpthumbDebug();
  274. }
  275. ////////////////////////////////////////////////////////////////
  276. // check to see if file already exists in cache, and output it with no processing if it does
  277. $phpthumb->SetCacheFilename();
  278. if (is_file($phpthumb->cache_filename)) {
  279. $parsed_url = @parse_url(@$_SERVER['HTTP_REFERER']);
  280. if ($phpthumb->config_nooffsitelink_enabled && @$_SERVER['HTTP_REFERER'] && !in_array(@$parsed_url['host'], $phpthumb->config_nooffsitelink_valid_domains)) {
  281. $phpthumb->DebugMessage('Would have used cached (image/'.$phpthumb->thumbnailFormat.') file "'.$phpthumb->cache_filename.'" (Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($phpthumb->cache_filename)).' 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__);
  282. } elseif ($phpthumb->phpthumbDebug) {
  283. $phpthumb->DebugMessage('Would have used cached file, but skipping due to phpthumbDebug', __FILE__, __LINE__);
  284. $phpthumb->DebugMessage('* Would have sent headers (1): Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($phpthumb->cache_filename)).' GMT', __FILE__, __LINE__);
  285. if ($getimagesize = @GetImageSize($phpthumb->cache_filename)) {
  286. $phpthumb->DebugMessage('* Would have sent headers (2): Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]), __FILE__, __LINE__);
  287. }
  288. if (ereg('^'.preg_quote(str_replace($phpthumb->osslash, '/', $PHPTHUMB_CONFIG['document_root'])).'(.*)$', str_replace($phpthumb->osslash, '/', $phpthumb->cache_filename), $matches)) {
  289. $phpthumb->DebugMessage('* Would have sent headers (3): Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])), __FILE__, __LINE__);
  290. } else {
  291. $phpthumb->DebugMessage('* Would have sent headers (3): readfile('.$phpthumb->cache_filename.')', __FILE__, __LINE__);
  292. }
  293. } else {
  294. SendSaveAsFileHeaderIfNeeded();
  295. header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($phpthumb->cache_filename)).' GMT');
  296. if ($getimagesize = @GetImageSize($phpthumb->cache_filename)) {
  297. header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($getimagesize[2]));
  298. }
  299. if (ereg('^'.preg_quote(str_replace($phpthumb->osslash, '/', $PHPTHUMB_CONFIG['document_root'])).'(.*)$', str_replace($phpthumb->osslash, '/', $phpthumb->cache_filename), $matches)) {
  300. // BEN HACKED THIS
  301. header('Location:cache/'.urlencode(basename($matches[1])));
  302. // WAS
  303. // header('Location: '.dirname($matches[1]).'/'.urlencode(basename($matches[1])));
  304. } else {
  305. @readfile($phpthumb->cache_filename);
  306. }
  307. exit;
  308. }
  309. }
  310. else {
  311. $phpthumb->DebugMessage('Cached file "'.$phpthumb->cache_filename.'" does not exist, processing as normal', __FILE__, __LINE__);
  312. }
  313. ////////////////////////////////////////////////////////////////
  314. // Debug output, to try and help me diagnose problems
  315. if (@$_GET['phpthumbDebug'] == '6') {
  316. $phpthumb->phpthumbDebug();
  317. }
  318. ////////////////////////////////////////////////////////////////
  319. if ($phpthumb->rawImageData) {
  320. // great
  321. } elseif (!empty($_GET['new'])) {
  322. // generate a blank image resource of the specified size/background color/opacity
  323. if (($phpthumb->w <= 0) || ($phpthumb->h <= 0)) {
  324. $phpthumb->ErrorImage('"w" and "h" parameters required for "new"');
  325. }
  326. @list($bghexcolor, $opacity) = explode('|', $_GET['new']);
  327. if (!phpthumb_functions::IsHexColor($bghexcolor)) {
  328. $phpthumb->ErrorImage('BGcolor parameter for "new" is not valid');
  329. }
  330. $opacity = (strlen($opacity) ? $opacity : 100);
  331. if ($phpthumb->gdimg_source = phpthumb_functions::ImageCreateFunction($phpthumb->w, $phpthumb->h)) {
  332. $alpha = (100 - min(100, max(0, $opacity))) * 1.27;
  333. if ($alpha) {
  334. $phpthumb->is_alpha = true;
  335. ImageAlphaBlending($phpthumb->gdimg_source, false);
  336. ImageSaveAlpha($phpthumb->gdimg_source, true);
  337. }
  338. $new_background_color = phpthumb_functions::ImageHexColorAllocate($phpthumb->gdimg_source, $bghexcolor, false, $alpha);
  339. ImageFilledRectangle($phpthumb->gdimg_source, 0, 0, $phpthumb->w, $phpthumb->h, $new_background_color);
  340. } else {
  341. $phpthumb->ErrorImage('failed to create "new" image ('.$phpthumb->w.'x'.$phpthumb->h.')');
  342. }
  343. } elseif (!$phpthumb->src) {
  344. $phpthumb->ErrorImage('Usage: '.$_SERVER['PHP_SELF'].'?src=/path/and/filename.jpg'."\n".'read Usage comments for details');
  345. } elseif (substr(strtolower($phpthumb->src), 0, 7) == 'http://') {
  346. ob_start();
  347. $HTTPurl = strtr($phpthumb->src, array(' '=>'%20'));
  348. if ($fp = fopen($HTTPurl, 'rb')) {
  349. $rawImageData = '';
  350. do {
  351. $buffer = fread($fp, 8192);
  352. if (strlen($buffer) == 0) {
  353. break;
  354. }
  355. $rawImageData .= $buffer;
  356. } while (true);
  357. fclose($fp);
  358. $phpthumb->setSourceData($rawImageData, urlencode($phpthumb->src));
  359. } else {
  360. $fopen_error = strip_tags(ob_get_contents());
  361. ob_end_clean();
  362. if (ini_get('allow_url_fopen')) {
  363. $phpthumb->ErrorImage('cannot open "'.$HTTPurl.'" - fopen() said: "'.$fopen_error.'"');
  364. } else {
  365. $phpthumb->ErrorImage('"allow_url_fopen" disabled');
  366. }
  367. }
  368. ob_end_clean();
  369. }
  370. ////////////////////////////////////////////////////////////////
  371. // Debug output, to try and help me diagnose problems
  372. if (@$_GET['phpthumbDebug'] == '7') {
  373. $phpthumb->phpthumbDebug();
  374. }
  375. ////////////////////////////////////////////////////////////////
  376. $phpthumb->GenerateThumbnail();
  377. ////////////////////////////////////////////////////////////////
  378. // Debug output, to try and help me diagnose problems
  379. if (@$_GET['phpthumbDebug'] == '8') {
  380. $phpthumb->phpthumbDebug();
  381. }
  382. ////////////////////////////////////////////////////////////////
  383. if ($phpthumb->file) {
  384. $phpthumb->RenderToFile($phpthumb->ResolveFilenameToAbsolute($phpthumb->file));
  385. if ($phpthumb->goto && (substr(strtolower($phpthumb->goto), 0, strlen('http://')) == 'http://')) {
  386. // redirect to another URL after image has been rendered to file
  387. header('Location: '.$phpthumb->goto);
  388. exit;
  389. }
  390. } else {
  391. if ((file_exists($phpthumb->cache_filename) && is_writable($phpthumb->cache_filename)) || is_writable(dirname($phpthumb->cache_filename))) {
  392. $phpthumb->CleanUpCacheDirectory();
  393. $phpthumb->RenderToFile($phpthumb->cache_filename);
  394. } else {
  395. $phpthumb->DebugMessage('Cannot write to $phpthumb->cache_filename ('.$phpthumb->cache_filename.') because that directory ('.dirname($phpthumb->cache_filename).') is not writable', __FILE__, __LINE__);
  396. }
  397. }
  398. ////////////////////////////////////////////////////////////////
  399. // Debug output, to try and help me diagnose problems
  400. if (@$_GET['phpthumbDebug'] == '9') {
  401. $phpthumb->phpthumbDebug();
  402. }
  403. ////////////////////////////////////////////////////////////////
  404. $phpthumb->OutputThumbnail();
  405. ?>