Advertisement
Guest User

Untitled

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