hdmasters

thumb.php

Nov 2nd, 2011
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 20.14 KB | None | 0 0
  1. <?php
  2. /**
  3.  * TimThumb script created by Ben Gillbanks, originally created by Tim McDaniels and Darren Hoyt
  4.  * http://code.google.com/p/timthumb/
  5.  *
  6.  * GNU General Public License, version 2
  7.  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  8.  *
  9.  * Examples and documentation available on the project homepage
  10.  * http://www.binarymoon.co.uk/projects/timthumb/
  11.  */
  12.  
  13. define ('CACHE_SIZE', 1000);                // number of files to store before clearing cache
  14. define ('CACHE_CLEAR', 20);                 // maximum number of files to delete on each cache clear
  15. define ('CACHE_USE', TRUE);                 // use the cache files? (mostly for testing)
  16. define ('CACHE_MAX_AGE', 864000);           // time to cache in the browser
  17. define ('VERSION', '1.26');                 // version number (to force a cache refresh)
  18. define ('DIRECTORY_CACHE', './cache');      // cache directory
  19. define ('MAX_WIDTH', 1500);                 // maximum image width
  20. define ('MAX_HEIGHT', 1500);                // maximum image height
  21. define ('ALLOW_EXTERNAL', FALSE);           // allow external website (override security precaution - not advised!)
  22. define ('MEMORY_LIMIT', '30M');             // set PHP memory limit
  23. define ('MAX_FILE_SIZE', 1500000);          // file size limit to prevent possible DOS attacks (roughly 1.5 megabytes)
  24. define ('CURL_TIMEOUT', 10);                // timeout duration. Tweak as you require (lower = better)
  25.  
  26. // external domains that are allowed to be displayed on your website
  27. $allowedSites = array (
  28.     'flickr.com',
  29.     'picasa.com',
  30.     'blogger.com',
  31.     'wordpress.com',
  32.     'img.youtube.com',
  33.     'upload.wikimedia.org',
  34. );
  35.  
  36. // STOP MODIFYING HERE!
  37. // --------------------
  38.  
  39. // sort out image source
  40. $src = get_request ('src', '');
  41. if ($src == '' || strlen ($src) <= 3) {
  42.     display_error (('IMAGEM NAO ESPECIFICADA!'));
  43. }
  44.  
  45. // clean params before use
  46. $src = clean_source ($src);
  47.  
  48. // get mime type of src
  49. $mime_type = mime_type ($src);
  50.  
  51. // used for external websites only
  52. $external_data_string = '';
  53.  
  54. // generic file handle for reading and writing to files
  55. $fh = '';
  56.  
  57. // check to see if this image is in the cache already
  58. // if already cached then display the image and die
  59. check_cache ($mime_type);
  60.  
  61. // cache doesn't exist and then process everything
  62. // check to see if GD function exist
  63. if (!function_exists ('imagecreatetruecolor')) {
  64.     display_error ('GD Library Error: imagecreatetruecolor does not exist - please contact your webhost and ask them to install the GD library');
  65. }
  66.  
  67. if (function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
  68.     $imageFilters = array (
  69.         1 => array (IMG_FILTER_NEGATE, 0),
  70.         2 => array (IMG_FILTER_GRAYSCALE, 0),
  71.         3 => array (IMG_FILTER_BRIGHTNESS, 1),
  72.         4 => array (IMG_FILTER_CONTRAST, 1),
  73.         5 => array (IMG_FILTER_COLORIZE, 4),
  74.         6 => array (IMG_FILTER_EDGEDETECT, 0),
  75.         7 => array (IMG_FILTER_EMBOSS, 0),
  76.         8 => array (IMG_FILTER_GAUSSIAN_BLUR, 0),
  77.         9 => array (IMG_FILTER_SELECTIVE_BLUR, 0),
  78.         10 => array (IMG_FILTER_MEAN_REMOVAL, 0),
  79.         11 => array (IMG_FILTER_SMOOTH, 0),
  80.     );
  81. }
  82.  
  83. // get standard input properties
  84. $new_width =  (int) abs (get_request ('w', 0));
  85. $new_height = (int) abs (get_request ('h', 0));
  86. $zoom_crop = (int) get_request ('zc', 1);
  87. $quality = (int) abs (get_request ('q', 90));
  88. $align = get_request ('a', 'c');
  89. $filters = get_request ('f', '');
  90. $sharpen = (bool) get_request ('s', 0);
  91.  
  92. // set default width and height if neither are set already
  93. if ($new_width == 0 && $new_height == 0) {
  94.     $new_width = 100;
  95.     $new_height = 100;
  96. }
  97.  
  98. // ensure size limits can not be abused
  99. $new_width = min ($new_width, MAX_WIDTH);
  100. $new_height = min ($new_height, MAX_HEIGHT);
  101.  
  102. // set memory limit to be able to have enough space to resize larger images
  103. ini_set ('memory_limit', MEMORY_LIMIT);
  104.  
  105. if (file_exists ($src)) {
  106.  
  107.     // open the existing image
  108.     $image = open_image ($mime_type, $src);
  109.     if ($image === false) {
  110.         display_error ('Unable to open image : ' . $src);
  111.     }
  112.  
  113.     // Get original width and height
  114.     $width = imagesx ($image);
  115.     $height = imagesy ($image);
  116.     $origin_x = 0;
  117.     $origin_y = 0;
  118.  
  119.     // generate new w/h if not provided
  120.     if ($new_width && !$new_height) {
  121.         $new_height = floor ($height * ($new_width / $width));
  122.     } else if ($new_height && !$new_width) {
  123.         $new_width = floor ($width * ($new_height / $height));
  124.     }
  125.  
  126.     // scale down and add borders
  127.     if ($zoom_crop == 3) {
  128.  
  129.         $final_height = $height * ($new_width / $width);
  130.  
  131.         if ($final_height > $new_height) {
  132.             $new_width = $width * ($new_height / $height);
  133.         } else {
  134.             $new_height = $final_height;
  135.         }
  136.  
  137.     }
  138.  
  139.     // create a new true color image
  140.     $canvas = imagecreatetruecolor ($new_width, $new_height);
  141.     imagealphablending ($canvas, false);
  142.  
  143.     // Create a new transparent color for image
  144.     $color = imagecolorallocatealpha ($canvas, 0, 0, 0, 127);
  145.  
  146.     // Completely fill the background of the new image with allocated color.
  147.     imagefill ($canvas, 0, 0, $color);
  148.  
  149.     // scale down and add borders
  150.     if ($zoom_crop == 2) {
  151.  
  152.         $final_height = $height * ($new_width / $width);
  153.        
  154.         if ($final_height > $new_height) {
  155.            
  156.             $origin_x = $new_width / 2;
  157.             $new_width = $width * ($new_height / $height);
  158.             $origin_x = round ($origin_x - ($new_width / 2));
  159.  
  160.         } else {
  161.  
  162.             $origin_y = $new_height / 2;
  163.             $new_height = $final_height;
  164.             $origin_y = round ($origin_y - ($new_height / 2));
  165.  
  166.         }
  167.  
  168.     }
  169.  
  170.     // Restore transparency blending
  171.     imagesavealpha ($canvas, true);
  172.  
  173.     if ($zoom_crop > 0) {
  174.  
  175.         $src_x = $src_y = 0;
  176.         $src_w = $width;
  177.         $src_h = $height;
  178.  
  179.         $cmp_x = $width / $new_width;
  180.         $cmp_y = $height / $new_height;
  181.  
  182.         // calculate x or y coordinate and width or height of source
  183.         if ($cmp_x > $cmp_y) {
  184.  
  185.             $src_w = round ($width / $cmp_x * $cmp_y);
  186.             $src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
  187.  
  188.         } else if ($cmp_y > $cmp_x) {
  189.  
  190.             $src_h = round ($height / $cmp_y * $cmp_x);
  191.             $src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
  192.  
  193.         }
  194.  
  195.         // positional cropping!
  196.         switch ($align) {
  197.             case 't':
  198.             case 'tl':
  199.             case 'lt':
  200.             case 'tr':
  201.             case 'rt':
  202.                 $src_y = 0;
  203.                 break;
  204.  
  205.             case 'b':
  206.             case 'bl':
  207.             case 'lb':
  208.             case 'br':
  209.             case 'rb':
  210.                 $src_y = $height - $src_h;
  211.                 break;
  212.  
  213.             case 'l':
  214.             case 'tl':
  215.             case 'lt':
  216.             case 'bl':
  217.             case 'lb':
  218.                 $src_x = 0;
  219.                 break;
  220.  
  221.             case 'r':
  222.             case 'tr':
  223.             case 'rt':
  224.             case 'br':
  225.             case 'rb':
  226.                 $src_x = $width - $new_width;
  227.                 $src_x = $width - $src_w;
  228.                 break;
  229.  
  230.             default:
  231.                 break;
  232.         }
  233.  
  234.         imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
  235.  
  236.     } else {
  237.  
  238.         // copy and resize part of an image with resampling
  239.         imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  240.  
  241.     }
  242.  
  243.     if ($filters != '' && function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
  244.         // apply filters to image
  245.         $filterList = explode ('|', $filters);
  246.         foreach ($filterList as $fl) {
  247.  
  248.             $filterSettings = explode (',', $fl);
  249.             if (isset ($imageFilters[$filterSettings[0]])) {
  250.  
  251.                 for ($i = 0; $i < 4; $i ++) {
  252.                     if (!isset ($filterSettings[$i])) {
  253.                         $filterSettings[$i] = null;
  254.                     } else {
  255.                         $filterSettings[$i] = (int) $filterSettings[$i];
  256.                     }
  257.                 }
  258.  
  259.                 switch ($imageFilters[$filterSettings[0]][1]) {
  260.  
  261.                     case 1:
  262.  
  263.                         imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
  264.                         break;
  265.  
  266.                     case 2:
  267.  
  268.                         imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
  269.                         break;
  270.  
  271.                     case 3:
  272.  
  273.                         imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
  274.                         break;
  275.  
  276.                     case 4:
  277.  
  278.                         imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3], $filterSettings[4]);
  279.                         break;
  280.  
  281.                     default:
  282.  
  283.                         imagefilter ($canvas, $imageFilters[$filterSettings[0]][0]);
  284.                         break;
  285.  
  286.                 }
  287.             }
  288.         }
  289.     }
  290.  
  291.     // sharpen image
  292.     if ($sharpen && function_exists ('imageconvolution')) {
  293.  
  294.         $sharpenMatrix = array (
  295.             array (-1,-1,-1),
  296.             array (-1,16,-1),
  297.             array (-1,-1,-1),
  298.         );
  299.  
  300.         $divisor = 8;
  301.         $offset = 0;
  302.  
  303.         imageconvolution ($canvas, $sharpenMatrix, $divisor, $offset);
  304.  
  305.     }
  306.  
  307.     // output image to browser based on mime type
  308.     show_image ($mime_type, $canvas);
  309.  
  310.     // remove image from memory
  311.     imagedestroy ($canvas);
  312.  
  313.     // if not in cache then clear some space and generate a new file
  314.     clean_cache ();
  315.  
  316.     die ();
  317.  
  318. } else {
  319.  
  320.     if (strlen ($src)) {
  321.         display_error ('image ' . $src . ' not found');
  322.     } else {
  323.         display_error ('no source specified');
  324.     }
  325.  
  326. }
  327.  
  328.  
  329. /**
  330.  *
  331.  * @global <type> $quality
  332.  * @param <type> $mime_type
  333.  * @param <type> $image_resized
  334.  */
  335. function show_image ($mime_type, $image_resized) {
  336.  
  337.     global $quality;
  338.  
  339.     $cache_file = get_cache_file ($mime_type);
  340.  
  341.     if (strpos ($mime_type, 'jpeg') > 1) {
  342.         imagejpeg ($image_resized, $cache_file, $quality);
  343.     } else {
  344.         imagepng ($image_resized, $cache_file, floor ($quality * 0.09));
  345.     }
  346.  
  347.     show_cache_file ($mime_type);
  348.  
  349. }
  350.  
  351.  
  352. /**
  353.  *
  354.  * @param <type> $property
  355.  * @param <type> $default
  356.  * @return <type>
  357.  */
  358. function get_request ($property, $default = 0) {
  359.  
  360.     if (isset ($_GET[$property])) {
  361.         return $_GET[$property];
  362.     } else {
  363.         return $default;
  364.     }
  365.  
  366. }
  367.  
  368.  
  369. /**
  370.  *
  371.  * @param <type> $mime_type
  372.  * @param <type> $src
  373.  * @return <type>
  374.  */
  375. function open_image ($mime_type, $src) {
  376.  
  377.     if (strpos ($mime_type, 'jpeg') !== false) {
  378.         $image = imagecreatefromjpeg ($src);
  379.     } elseif (strpos ($mime_type, 'png') !== false) {
  380.         $image = imagecreatefrompng ($src);
  381.     } elseif (strpos ($mime_type, 'gif') !== false) {
  382.         $image = imagecreatefromgif ($src);
  383.     }
  384.  
  385.     return $image;
  386.  
  387. }
  388.  
  389. /**
  390.  * clean out old files from the cache
  391.  * you can change the number of files to store and to delete per loop in the defines at the top of the code
  392.  *
  393.  * @return <type>
  394.  */
  395. function clean_cache () {
  396.  
  397.     // add an escape
  398.     // Reduces the amount of cache clearing to save some processor speed
  399.     if (rand (1, 50) > 10) {
  400.         return true;
  401.     }
  402.  
  403.     flush ();
  404.  
  405.     $files = glob (DIRECTORY_CACHE . '/*', GLOB_BRACE);
  406.  
  407.     if (count ($files) > CACHE_SIZE) {
  408.        
  409.         $yesterday = time () - (24 * 60 * 60);
  410.  
  411.         usort ($files, 'filemtime_compare');
  412.         $i = 0;
  413.  
  414.         foreach ($files as $file) {
  415.  
  416.             $i ++;
  417.  
  418.             if ($i >= CACHE_CLEAR) {
  419.                 return;
  420.             }
  421.  
  422.             if (@filemtime ($file) > $yesterday) {
  423.                 return;
  424.             }
  425.  
  426.             if (file_exists ($file)) {
  427.                 unlink ($file);
  428.             }
  429.  
  430.         }
  431.  
  432.     }
  433.  
  434. }
  435.  
  436.  
  437. /**
  438.  * compare the file time of two files
  439.  *
  440.  * @param <type> $a
  441.  * @param <type> $b
  442.  * @return <type>
  443.  */
  444. function filemtime_compare ($a, $b) {
  445.  
  446.     $break = explode ('/', $_SERVER['SCRIPT_FILENAME']);
  447.     $filename = $break[count ($break) - 1];
  448.     $filepath = str_replace ($filename, '', $_SERVER['SCRIPT_FILENAME']);
  449.  
  450.     $file_a = realpath ($filepath . $a);
  451.     $file_b = realpath ($filepath . $b);
  452.  
  453.     return filemtime ($file_a) - filemtime ($file_b);
  454.  
  455. }
  456.  
  457.  
  458. /**
  459.  * determine the file mime type
  460.  *
  461.  * @param <type> $file
  462.  * @return <type>
  463.  */
  464. function mime_type ($file) {
  465.  
  466.     $file_infos = getimagesize ($file);
  467.     $mime_type = $file_infos['mime'];
  468.  
  469.     // no mime type
  470.     if (empty ($mime_type)) {
  471.         display_error ('no mime type specified');
  472.     }
  473.  
  474.     // use mime_type to determine mime type
  475.     if (!preg_match ("/jpg|jpeg|gif|png/i", $mime_type)) {
  476.         display_error ('Invalid src mime type: ' . $mime_type);
  477.     }
  478.  
  479.     return strtolower ($mime_type);
  480.  
  481. }
  482.  
  483.  
  484. /**
  485.  *
  486.  * @param <type> $mime_type
  487.  */
  488. function check_cache ($mime_type) {
  489.  
  490.     if (CACHE_USE) {
  491.  
  492.         if (!show_cache_file ($mime_type)) {
  493.             // make sure cache dir exists
  494.             if (!file_exists (DIRECTORY_CACHE)) {
  495.                 // give 777 permissions so that developer can overwrite
  496.                 // files created by web server user
  497.                 mkdir (DIRECTORY_CACHE);
  498.                 chmod (DIRECTORY_CACHE, 0777);
  499.             }
  500.         }
  501.  
  502.     }
  503.  
  504. }
  505.  
  506.  
  507. /**
  508.  *
  509.  * @param <type> $mime_type
  510.  * @return <type>
  511.  */
  512. function show_cache_file ($mime_type) {
  513.  
  514.     // use browser cache if available to speed up page load
  515.     if (isset ($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
  516.         if (strtotime ($_SERVER['HTTP_IF_MODIFIED_SINCE']) < strtotime('now')) {
  517.             header ('HTTP/1.1 304 Not Modified');
  518.             die ();
  519.         }
  520.     }
  521.  
  522.     $cache_file = get_cache_file ($mime_type);
  523.  
  524.     if (file_exists ($cache_file)) {
  525.  
  526.         // change the modified headers
  527.         $gmdate_expires = gmdate ('D, d M Y H:i:s', strtotime ('now +10 days')) . ' GMT';
  528.         $gmdate_modified = gmdate ('D, d M Y H:i:s') . ' GMT';
  529.  
  530.         // send content headers then display image
  531.         header ('Content-Type: ' . $mime_type);
  532.         header ('Accept-Ranges: bytes');
  533.         header ('Last-Modified: ' . $gmdate_modified);
  534.         header ('Content-Length: ' . filesize ($cache_file));
  535.         header ('Cache-Control: max-age=' . CACHE_MAX_AGE . ', must-revalidate');
  536.         header ('Expires: ' . $gmdate_expires);
  537.  
  538.         if (!@readfile ($cache_file)) {
  539.             $content = file_get_contents ($cache_file);
  540.             if ($content != FALSE) {
  541.                 echo $content;
  542.             } else {
  543.                 display_error ('cache file could not be loaded');
  544.             }
  545.         }
  546.  
  547.         die ();
  548.  
  549.     }
  550.  
  551.     return FALSE;
  552.  
  553. }
  554.  
  555.  
  556. /**
  557.  *
  558.  * @staticvar string $cache_file
  559.  * @param <type> $mime_type
  560.  * @return string
  561.  */
  562. function get_cache_file ($mime_type) {
  563.  
  564.     static $cache_file;
  565.     global $src;
  566.  
  567.     $file_type = '.png';
  568.  
  569.     if (strpos ($mime_type, 'jpeg') > 1) {
  570.         $file_type = '.jpg';
  571.     }
  572.  
  573.     if (!$cache_file) {
  574.         // filemtime is used to make sure updated files get recached
  575.         $cache_file = DIRECTORY_CACHE . '/' . md5 ($_SERVER ['QUERY_STRING'] . VERSION . filemtime ($src)) . $file_type;
  576.     }
  577.  
  578.     return $cache_file;
  579.  
  580. }
  581.  
  582.  
  583. /**
  584.  *
  585.  * @param <type> $url
  586.  * @return <type>
  587.  */
  588. function validate_url ($url) {
  589.     $pattern = "/\b(?:(?:https?):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
  590.     return preg_match ($pattern, $url);
  591. }
  592.  
  593.  
  594. /**
  595.  *
  596.  * @global array $allowedSites
  597.  * @param string $src
  598.  * @return string
  599.  */
  600. function check_external ($src) {
  601.  
  602.     global $allowedSites;
  603.  
  604.     // work out file details
  605.     $fileDetails = pathinfo ($src);
  606.     $filename = 'external_' . md5 ($src);
  607.     $local_filepath = DIRECTORY_CACHE . '/' . $filename . '.' . strtolower ($fileDetails['extension']);
  608.  
  609.     // only do this stuff the file doesn't already exist
  610.     if (!file_exists ($local_filepath)) {
  611.  
  612.         if (strpos (strtolower ($src), 'http://') !== false || strpos (strtolower ($src), 'https://') !== false) {
  613.  
  614.             if (!validate_url ($src)) {
  615.                 display_error ('invalid url');
  616.             }
  617.  
  618.             $url_info = parse_url ($src);
  619.  
  620.             // convert youtube video urls
  621.             // need to tidy up the code
  622.  
  623.             if ($url_info['host'] == 'www.youtube.com' || $url_info['host'] == 'youtube.com') {
  624.                 parse_str ($url_info['query']);
  625.  
  626.                 if (isset ($v)) {
  627.                     $src = 'http://img.youtube.com/vi/' . $v . '/0.jpg';
  628.                     $url_info['host'] = 'img.youtube.com';
  629.                 }
  630.             }
  631.  
  632.             // check allowed sites (if required)
  633.             if (ALLOW_EXTERNAL) {
  634.  
  635.                 $isAllowedSite = true;
  636.  
  637.             } else {
  638.  
  639.                 $isAllowedSite = false;
  640.                 foreach ($allowedSites as $site) {
  641.                     if (strpos (strtolower ($url_info['host']), $site) !== false) {
  642.                         $isAllowedSite = true;
  643.                     }
  644.                 }
  645.  
  646.             }
  647.  
  648.             // if allowed
  649.             if ($isAllowedSite) {
  650.  
  651.                 if (function_exists ('curl_init')) {
  652.  
  653.                     global $fh;
  654.  
  655.                     $fh = fopen ($local_filepath, 'w');
  656.                     $ch = curl_init ($src);
  657.  
  658.                     curl_setopt ($ch, CURLOPT_TIMEOUT, CURL_TIMEOUT);
  659.                     curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
  660.                     curl_setopt ($ch, CURLOPT_URL, $src);
  661.                     curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
  662.                     curl_setopt ($ch, CURLOPT_HEADER, 0);
  663.                     curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  664.                     curl_setopt ($ch, CURLOPT_FILE, $fh);
  665.                     curl_setopt ($ch, CURLOPT_WRITEFUNCTION, 'curl_write');
  666.  
  667.                     // error so die
  668.                     if (curl_exec ($ch) === FALSE) {
  669.                         unlink ($local_filepath);
  670.                         touch ($local_filepath);
  671.                         display_error ('error reading file ' . $src . ' from remote host: ' . curl_error ($ch));
  672.                     }
  673.  
  674.                     curl_close ($ch);
  675.                     fclose ($fh);
  676.  
  677.                 } else {
  678.  
  679.                     if (!$img = file_get_contents ($src)) {
  680.                         display_error ('remote file for ' . $src . ' can not be accessed. It is likely that the file permissions are restricted');
  681.                     }
  682.  
  683.                     if (file_put_contents ($local_filepath, $img) == FALSE) {
  684.                         display_error ('error writing temporary file');
  685.                     }
  686.  
  687.                 }
  688.  
  689.                 if (!file_exists ($local_filepath)) {
  690.                     display_error ('local file for ' . $src . ' can not be created');
  691.                 }
  692.  
  693.                 $src = $local_filepath;
  694.  
  695.             } else {
  696.  
  697.                 display_error ('remote host "' . $url_info['host'] . '" not allowed');
  698.  
  699.             }
  700.  
  701.         }
  702.  
  703.     } else {
  704.  
  705.         $src = $local_filepath;
  706.  
  707.     }
  708.  
  709.     return $src;
  710.  
  711. }
  712.  
  713.  
  714. /**
  715.  * callback for curl command to receive external images
  716.  * limit the amount of data downloaded from external servers
  717.  *
  718.  * @global <type> $data_string
  719.  * @param <type> $handle
  720.  * @param <type> $data
  721.  * @return <type>
  722.  */
  723. function curl_write ($handle, $data) {
  724.  
  725.     global $external_data_string, $fh;
  726.  
  727.     fwrite ($fh, $data);
  728.     $external_data_string .= $data;
  729.  
  730.     if (strlen ($external_data_string) > MAX_FILE_SIZE) {
  731.         return 0;
  732.     } else {
  733.         return strlen ($data);
  734.     }
  735.  
  736. }
  737.  
  738.  
  739. /**
  740.  * tidy up the image source url
  741.  *
  742.  * @param <type> $src
  743.  * @return string
  744.  */
  745. function clean_source ($src) {
  746.  
  747.     $host = str_replace ('www.', '', $_SERVER['HTTP_HOST']);
  748.     $regex = "/^(http(s|):\/\/)(www\.|)" . $host . "\//i";
  749.  
  750.     $src = preg_replace ($regex, '', $src);
  751.     $src = strip_tags ($src);
  752.     $src = check_external ($src);
  753.  
  754.     // remove slash from start of string
  755.     if (strpos ($src, '/') === 0) {
  756.         $src = substr ($src, -(strlen ($src) - 1));
  757.     }
  758.  
  759.     // don't allow users the ability to use '../'
  760.     // in order to gain access to files below document root
  761.     $src = preg_replace ("/\.\.+\//", "", $src);
  762.  
  763.     // get path to image on file system
  764.     $src = get_document_root ($src) . '/' . $src;
  765.  
  766.     if (!is_file ($src)) {
  767.         display_error ('source is not a valid file');
  768.     }
  769.  
  770.     if (filesize ($src) > MAX_FILE_SIZE) {
  771.         display_error ('source file is too big (filesize > MAX_FILE_SIZE)');
  772.     }
  773.  
  774.     if (filesize ($src) <= 0) {
  775.         display_error ('source file <= 0 bytes. Possible external file download error (file is too large)');
  776.     }
  777.    
  778.     return realpath ($src);
  779.  
  780. }
  781.  
  782.  
  783. /**
  784.  *
  785.  * @param <type> $src
  786.  * @return string
  787.  */
  788. function get_document_root ($src) {
  789.  
  790.     // check for unix servers
  791.     if (file_exists ($_SERVER['DOCUMENT_ROOT'] . '/' . $src)) {
  792.         return $_SERVER['DOCUMENT_ROOT'];
  793.     }
  794.  
  795.     // check from script filename (to get all directories to timthumb location)
  796.     $parts = array_diff (explode ('/', $_SERVER['SCRIPT_FILENAME']), explode ('/', $_SERVER['DOCUMENT_ROOT']));
  797.  
  798.     $path = $_SERVER['DOCUMENT_ROOT'];
  799.    
  800.     foreach ($parts as $part) {
  801.         $path .= '/' . $part;
  802.         if (file_exists ($path . '/' . $src)) {
  803.             return $path;
  804.         }
  805.     }
  806.  
  807.     // special check for microsoft servers
  808.     if (!isset ($_SERVER['DOCUMENT_ROOT'])) {
  809.         $path = str_replace ("/", "\\", $_SERVER['ORIG_PATH_INFO']);
  810.         $path = str_replace ($path, '', $_SERVER['SCRIPT_FILENAME']);
  811.  
  812.         if (file_exists ($path . '/' . $src)) {
  813.             return $path;
  814.         }
  815.     }
  816.  
  817.     display_error ('file not found');
  818.  
  819. }
  820.  
  821.  
  822. /**
  823.  * generic error message
  824.  *
  825.  * @param <type> $errorString
  826.  */
  827. function display_error ($errorString = '') {
  828.  
  829.     header ('HTTP/1.1 400 Bad Request');
  830.     echo '<pre>' . htmlentities ($errorString);
  831.     echo '<br />Query String : ' . htmlentities ($_SERVER['QUERY_STRING']);
  832.     echo '<br />TimThumb version : ' . VERSION . '</pre>';
  833.     die ();
  834.  
  835. }
  836. ?>
  837.  
Advertisement
Add Comment
Please, Sign In to add comment