PageRenderTime 61ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/leganto/document_root/thumb/phpthumb.functions.php

http://preader.googlecode.com/
PHP | 1044 lines | 873 code | 120 blank | 51 comment | 145 complexity | 0f9806f2f95fb6ca63bf96f7fc091e6d MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. //////////////////////////////////////////////////////////////
  3. /// phpThumb() by James Heinrich <info@silisoftware.com> //
  4. // available at http://phpthumb.sourceforge.net ///
  5. //////////////////////////////////////////////////////////////
  6. /// //
  7. // phpthumb.functions.php - general support functions //
  8. // ///
  9. //////////////////////////////////////////////////////////////
  10. class phpthumb_functions {
  11. function user_function_exists($functionname) {
  12. if (function_exists('get_defined_functions')) {
  13. static $get_defined_functions = array();
  14. if (empty($get_defined_functions)) {
  15. $get_defined_functions = get_defined_functions();
  16. }
  17. return in_array(strtolower($functionname), $get_defined_functions['user']);
  18. }
  19. return function_exists($functionname);
  20. }
  21. function builtin_function_exists($functionname) {
  22. if (function_exists('get_defined_functions')) {
  23. static $get_defined_functions = array();
  24. if (empty($get_defined_functions)) {
  25. $get_defined_functions = get_defined_functions();
  26. }
  27. return in_array(strtolower($functionname), $get_defined_functions['internal']);
  28. }
  29. return function_exists($functionname);
  30. }
  31. function version_compare_replacement_sub($version1, $version2, $operator='') {
  32. // If you specify the third optional operator argument, you can test for a particular relationship.
  33. // The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.
  34. // Using this argument, the function will return 1 if the relationship is the one specified by the operator, 0 otherwise.
  35. // If a part contains special version strings these are handled in the following order: dev < (alpha = a) < (beta = b) < RC < pl
  36. static $versiontype_lookup = array();
  37. if (empty($versiontype_lookup)) {
  38. $versiontype_lookup['dev'] = 10001;
  39. $versiontype_lookup['a'] = 10002;
  40. $versiontype_lookup['alpha'] = 10002;
  41. $versiontype_lookup['b'] = 10003;
  42. $versiontype_lookup['beta'] = 10003;
  43. $versiontype_lookup['RC'] = 10004;
  44. $versiontype_lookup['pl'] = 10005;
  45. }
  46. if (isset($versiontype_lookup[$version1])) {
  47. $version1 = $versiontype_lookup[$version1];
  48. }
  49. if (isset($versiontype_lookup[$version2])) {
  50. $version2 = $versiontype_lookup[$version2];
  51. }
  52. switch ($operator) {
  53. case '<':
  54. case 'lt':
  55. return intval($version1 < $version2);
  56. break;
  57. case '<=':
  58. case 'le':
  59. return intval($version1 <= $version2);
  60. break;
  61. case '>':
  62. case 'gt':
  63. return intval($version1 > $version2);
  64. break;
  65. case '>=':
  66. case 'ge':
  67. return intval($version1 >= $version2);
  68. break;
  69. case '==':
  70. case '=':
  71. case 'eq':
  72. return intval($version1 == $version2);
  73. break;
  74. case '!=':
  75. case '<>':
  76. case 'ne':
  77. return intval($version1 != $version2);
  78. break;
  79. }
  80. if ($version1 == $version2) {
  81. return 0;
  82. } elseif ($version1 < $version2) {
  83. return -1;
  84. }
  85. return 1;
  86. }
  87. function version_compare_replacement($version1, $version2, $operator='') {
  88. if (function_exists('version_compare')) {
  89. // built into PHP v4.1.0+
  90. return version_compare($version1, $version2, $operator);
  91. }
  92. // The function first replaces _, - and + with a dot . in the version strings
  93. $version1 = strtr($version1, '_-+', '...');
  94. $version2 = strtr($version2, '_-+', '...');
  95. // and also inserts dots . before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'.
  96. // Then it splits the results like if you were using explode('.',$ver). Then it compares the parts starting from left to right.
  97. $version1 = eregi_replace('([0-9]+)([A-Z]+)([0-9]+)', '\\1.\\2.\\3', $version1);
  98. $version2 = eregi_replace('([0-9]+)([A-Z]+)([0-9]+)', '\\1.\\2.\\3', $version2);
  99. $parts1 = explode('.', $version1);
  100. $parts2 = explode('.', $version1);
  101. $parts_count = max(count($parts1), count($parts2));
  102. for ($i = 0; $i < $parts_count; $i++) {
  103. $comparison = phpthumb_functions::version_compare_replacement_sub($version1, $version2, $operator);
  104. if ($comparison != 0) {
  105. return $comparison;
  106. }
  107. }
  108. return 0;
  109. }
  110. function phpinfo_array() {
  111. static $phpinfo_array = array();
  112. if (empty($phpinfo_array)) {
  113. ob_start();
  114. phpinfo();
  115. $phpinfo = ob_get_contents();
  116. ob_end_clean();
  117. $phpinfo_array = explode("\n", $phpinfo);
  118. }
  119. return $phpinfo_array;
  120. }
  121. function exif_info() {
  122. static $exif_info = array();
  123. if (empty($exif_info)) {
  124. // based on code by johnschaefer at gmx dot de
  125. // from PHP help on gd_info()
  126. $exif_info = array(
  127. 'EXIF Support' => '',
  128. 'EXIF Version' => '',
  129. 'Supported EXIF Version' => '',
  130. 'Supported filetypes' => ''
  131. );
  132. $phpinfo_array = phpthumb_functions::phpinfo_array();
  133. foreach ($phpinfo_array as $line) {
  134. $line = trim(strip_tags($line));
  135. foreach ($exif_info as $key => $value) {
  136. if (strpos($line, $key) === 0) {
  137. $newvalue = trim(str_replace($key, '', $line));
  138. $exif_info[$key] = $newvalue;
  139. }
  140. }
  141. }
  142. }
  143. return $exif_info;
  144. }
  145. function ImageTypeToMIMEtype($imagetype) {
  146. if (function_exists('image_type_to_mime_type') && ($imagetype >= 1) && ($imagetype <= 16)) {
  147. // PHP v4.3.0+
  148. return image_type_to_mime_type($imagetype);
  149. }
  150. static $image_type_to_mime_type = array(
  151. 1 => 'image/gif', // IMAGETYPE_GIF
  152. 2 => 'image/jpeg', // IMAGETYPE_JPEG
  153. 3 => 'image/png', // IMAGETYPE_PNG
  154. 4 => 'application/x-shockwave-flash', // IMAGETYPE_SWF
  155. 5 => 'image/psd', // IMAGETYPE_PSD
  156. 6 => 'image/bmp', // IMAGETYPE_BMP
  157. 7 => 'image/tiff', // IMAGETYPE_TIFF_II (intel byte order)
  158. 8 => 'image/tiff', // IMAGETYPE_TIFF_MM (motorola byte order)
  159. 9 => 'application/octet-stream', // IMAGETYPE_JPC
  160. 10 => 'image/jp2', // IMAGETYPE_JP2
  161. 11 => 'application/octet-stream', // IMAGETYPE_JPX
  162. 12 => 'application/octet-stream', // IMAGETYPE_JB2
  163. 13 => 'application/x-shockwave-flash', // IMAGETYPE_SWC
  164. 14 => 'image/iff', // IMAGETYPE_IFF
  165. 15 => 'image/vnd.wap.wbmp', // IMAGETYPE_WBMP
  166. 16 => 'image/xbm', // IMAGETYPE_XBM
  167. 'gif' => 'image/gif', // IMAGETYPE_GIF
  168. 'jpg' => 'image/jpeg', // IMAGETYPE_JPEG
  169. 'jpeg' => 'image/jpeg', // IMAGETYPE_JPEG
  170. 'png' => 'image/png', // IMAGETYPE_PNG
  171. 'bmp' => 'image/bmp', // IMAGETYPE_BMP
  172. 'ico' => 'image/x-icon',
  173. );
  174. return (isset($image_type_to_mime_type[$imagetype]) ? $image_type_to_mime_type[$imagetype] : false);
  175. }
  176. function TranslateWHbyAngle($width, $height, $angle) {
  177. if (($angle % 180) == 0) {
  178. return array($width, $height);
  179. }
  180. $newwidth = (abs(sin(deg2rad($angle))) * $height) + (abs(cos(deg2rad($angle))) * $width);
  181. $newheight = (abs(sin(deg2rad($angle))) * $width) + (abs(cos(deg2rad($angle))) * $height);
  182. return array($newwidth, $newheight);
  183. }
  184. function HexCharDisplay($string) {
  185. $len = strlen($string);
  186. $output = '';
  187. for ($i = 0; $i < $len; $i++) {
  188. $output .= ' 0x'.str_pad(dechex(ord($string{$i})), 2, '0', STR_PAD_LEFT);
  189. }
  190. return $output;
  191. }
  192. function IsHexColor($HexColorString) {
  193. return eregi('^[0-9A-F]{6}$', $HexColorString);
  194. }
  195. function ImageColorAllocateAlphaSafe(&$gdimg_hexcolorallocate, $R, $G, $B, $alpha=false) {
  196. if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.2', '>=') && ($alpha !== false)) {
  197. return ImageColorAllocateAlpha($gdimg_hexcolorallocate, $R, $G, $B, intval($alpha));
  198. } else {
  199. return ImageColorAllocate($gdimg_hexcolorallocate, $R, $G, $B);
  200. }
  201. }
  202. function ImageHexColorAllocate(&$gdimg_hexcolorallocate, $HexColorString, $dieOnInvalid=false, $alpha=false) {
  203. if (!is_resource($gdimg_hexcolorallocate)) {
  204. die('$gdimg_hexcolorallocate is not a GD resource in ImageHexColorAllocate()');
  205. }
  206. if (phpthumb_functions::IsHexColor($HexColorString)) {
  207. $R = hexdec(substr($HexColorString, 0, 2));
  208. $G = hexdec(substr($HexColorString, 2, 2));
  209. $B = hexdec(substr($HexColorString, 4, 2));
  210. return phpthumb_functions::ImageColorAllocateAlphaSafe($gdimg_hexcolorallocate, $R, $G, $B, $alpha);
  211. }
  212. if ($dieOnInvalid) {
  213. die('Invalid hex color string: "'.$HexColorString.'"');
  214. }
  215. return ImageColorAllocate($gdimg_hexcolorallocate, 0x00, 0x00, 0x00);
  216. }
  217. function HexColorXOR($hexcolor) {
  218. return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
  219. }
  220. function GetPixelColor(&$img, $x, $y) {
  221. if (!is_resource($img)) {
  222. return false;
  223. }
  224. return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
  225. }
  226. function PixelColorDifferencePercent($currentPixel, $targetPixel) {
  227. $diff = 0;
  228. foreach ($targetPixel as $channel => $currentvalue) {
  229. $diff = max($diff, (max($currentPixel[$channel], $targetPixel[$channel]) - min($currentPixel[$channel], $targetPixel[$channel])) / 255);
  230. }
  231. return $diff * 100;
  232. }
  233. function GrayscaleValue($r, $g, $b) {
  234. return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
  235. }
  236. function GrayscalePixel($OriginalPixel) {
  237. $gray = phpthumb_functions::GrayscaleValue($OriginalPixel['red'], $OriginalPixel['green'], $OriginalPixel['blue']);
  238. return array('red'=>$gray, 'green'=>$gray, 'blue'=>$gray);
  239. }
  240. function GrayscalePixelRGB($rgb) {
  241. $r = ($rgb >> 16) & 0xFF;
  242. $g = ($rgb >> 8) & 0xFF;
  243. $b = $rgb & 0xFF;
  244. return ($r * 0.299) + ($g * 0.587) + ($b * 0.114);
  245. }
  246. function ScaleToFitInBox($width, $height, $maxwidth=null, $maxheight=null, $allow_enlarge=true, $allow_reduce=true) {
  247. $maxwidth = (is_null($maxwidth) ? $width : $maxwidth);
  248. $maxheight = (is_null($maxheight) ? $height : $maxheight);
  249. $scale_x = 1;
  250. $scale_y = 1;
  251. if (($width > $maxwidth) || ($width < $maxwidth)) {
  252. $scale_x = ($maxwidth / $width);
  253. }
  254. if (($height > $maxheight) || ($height < $maxheight)) {
  255. $scale_y = ($maxheight / $height);
  256. }
  257. $scale = min($scale_x, $scale_y);
  258. if (!$allow_enlarge) {
  259. $scale = min($scale, 1);
  260. }
  261. if (!$allow_reduce) {
  262. $scale = max($scale, 1);
  263. }
  264. return $scale;
  265. }
  266. function ImageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) {
  267. // ron at korving dot demon dot nl
  268. // http://www.php.net/imagecopyresampled
  269. $scaleX = ($src_w - 1) / $dst_w;
  270. $scaleY = ($src_h - 1) / $dst_h;
  271. $scaleX2 = $scaleX / 2.0;
  272. $scaleY2 = $scaleY / 2.0;
  273. $isTrueColor = ImageIsTrueColor($src_img);
  274. for ($y = $src_y; $y < $src_y + $dst_h; $y++) {
  275. $sY = $y * $scaleY;
  276. $siY = (int) $sY;
  277. $siY2 = (int) $sY + $scaleY2;
  278. for ($x = $src_x; $x < $src_x + $dst_w; $x++) {
  279. $sX = $x * $scaleX;
  280. $siX = (int) $sX;
  281. $siX2 = (int) $sX + $scaleX2;
  282. if ($isTrueColor) {
  283. $c1 = ImageColorAt($src_img, $siX, $siY2);
  284. $c2 = ImageColorAt($src_img, $siX, $siY);
  285. $c3 = ImageColorAt($src_img, $siX2, $siY2);
  286. $c4 = ImageColorAt($src_img, $siX2, $siY);
  287. $r = (( $c1 + $c2 + $c3 + $c4 ) >> 2) & 0xFF0000;
  288. $g = ((($c1 & 0x00FF00) + ($c2 & 0x00FF00) + ($c3 & 0x00FF00) + ($c4 & 0x00FF00)) >> 2) & 0x00FF00;
  289. $b = ((($c1 & 0x0000FF) + ($c2 & 0x0000FF) + ($c3 & 0x0000FF) + ($c4 & 0x0000FF)) >> 2);
  290. } else {
  291. $c1 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX, $siY2));
  292. $c2 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX, $siY));
  293. $c3 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX2, $siY2));
  294. $c4 = ImageColorsForIndex($src_img, ImageColorAt($src_img, $siX2, $siY));
  295. $r = ($c1['red'] + $c2['red'] + $c3['red'] + $c4['red'] ) << 14;
  296. $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
  297. $b = ($c1['blue'] + $c2['blue'] + $c3['blue'] + $c4['blue'] ) >> 2;
  298. }
  299. ImageSetPixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
  300. }
  301. }
  302. return true;
  303. }
  304. function ImageCreateFunction($x_size, $y_size) {
  305. $ImageCreateFunction = 'ImageCreate';
  306. if (phpthumb_functions::gd_version() >= 2.0) {
  307. $ImageCreateFunction = 'ImageCreateTrueColor';
  308. }
  309. if (!function_exists($ImageCreateFunction)) {
  310. return phpthumb::ErrorImage($ImageCreateFunction.'() does not exist - no GD support?');
  311. }
  312. if (($x_size <= 0) || ($y_size <= 0)) {
  313. return phpthumb::ErrorImage('Invalid image dimensions: '.$ImageCreateFunction.'('.$x_size.', '.$y_size.')');
  314. }
  315. return $ImageCreateFunction(round($x_size), round($y_size));
  316. }
  317. function ImageCopyRespectAlpha(&$dst_im, &$src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $opacity_pct=100) {
  318. $opacipct = $opacity_pct / 100;
  319. for ($x = $src_x; $x < $src_w; $x++) {
  320. for ($y = $src_y; $y < $src_h; $y++) {
  321. $RealPixel = phpthumb_functions::GetPixelColor($dst_im, $dst_x + $x, $dst_y + $y);
  322. $OverlayPixel = phpthumb_functions::GetPixelColor($src_im, $x, $y);
  323. $alphapct = $OverlayPixel['alpha'] / 127;
  324. $overlaypct = (1 - $alphapct) * $opacipct;
  325. $newcolor = phpthumb_functions::ImageColorAllocateAlphaSafe(
  326. $dst_im,
  327. round($RealPixel['red'] * (1 - $overlaypct)) + ($OverlayPixel['red'] * $overlaypct),
  328. round($RealPixel['green'] * (1 - $overlaypct)) + ($OverlayPixel['green'] * $overlaypct),
  329. round($RealPixel['blue'] * (1 - $overlaypct)) + ($OverlayPixel['blue'] * $overlaypct),
  330. //$RealPixel['alpha']);
  331. 0);
  332. ImageSetPixel($dst_im, $dst_x + $x, $dst_y + $y, $newcolor);
  333. }
  334. }
  335. return true;
  336. }
  337. function ProportionalResize($old_width, $old_height, $new_width=false, $new_height=false) {
  338. $old_aspect_ratio = $old_width / $old_height;
  339. if (($new_width === false) && ($new_height === false)) {
  340. return false;
  341. } elseif ($new_width === false) {
  342. $new_width = $new_height * $old_aspect_ratio;
  343. } elseif ($new_height === false) {
  344. $new_height = $new_width / $old_aspect_ratio;
  345. }
  346. $new_aspect_ratio = $new_width / $new_height;
  347. if ($new_aspect_ratio == $old_aspect_ratio) {
  348. // great, done
  349. } elseif ($new_aspect_ratio < $old_aspect_ratio) {
  350. // limited by width
  351. $new_height = $new_width / $old_aspect_ratio;
  352. } elseif ($new_aspect_ratio > $old_aspect_ratio) {
  353. // limited by height
  354. $new_width = $new_height * $old_aspect_ratio;
  355. }
  356. return array(intval(round($new_width)), intval(round($new_height)));
  357. }
  358. function FunctionIsDisabled($function) {
  359. static $DisabledFunctions = null;
  360. if (is_null($DisabledFunctions)) {
  361. $disable_functions_local = explode(',', strtolower(@ini_get('disable_functions')));
  362. $disable_functions_global = explode(',', strtolower(@get_cfg_var('disable_functions')));
  363. foreach ($disable_functions_local as $key => $value) {
  364. $DisabledFunctions[trim($value)] = 'local';
  365. }
  366. foreach ($disable_functions_global as $key => $value) {
  367. $DisabledFunctions[trim($value)] = 'global';
  368. }
  369. if (@ini_get('safe_mode')) {
  370. $DisabledFunctions['shell_exec'] = 'local';
  371. $DisabledFunctions['set_time_limit'] = 'local';
  372. }
  373. }
  374. return isset($DisabledFunctions[strtolower($function)]);
  375. }
  376. function SafeExec($command) {
  377. static $AllowedExecFunctions = array();
  378. if (empty($AllowedExecFunctions)) {
  379. $AllowedExecFunctions = array('shell_exec'=>true, 'passthru'=>true, 'system'=>true, 'exec'=>true);
  380. foreach ($AllowedExecFunctions as $key => $value) {
  381. $AllowedExecFunctions[$key] = !phpthumb_functions::FunctionIsDisabled($key);
  382. }
  383. }
  384. $command .= ' 2>&1'; // force redirect stderr to stdout
  385. foreach ($AllowedExecFunctions as $execfunction => $is_allowed) {
  386. if (!$is_allowed) {
  387. continue;
  388. }
  389. $returnvalue = false;
  390. switch ($execfunction) {
  391. case 'passthru':
  392. case 'system':
  393. ob_start();
  394. $execfunction($command);
  395. $returnvalue = ob_get_contents();
  396. ob_end_clean();
  397. break;
  398. case 'exec':
  399. $output = array();
  400. $lastline = $execfunction($command, $output);
  401. $returnvalue = implode("\n", $output);
  402. break;
  403. case 'shell_exec':
  404. ob_start();
  405. $returnvalue = $execfunction($command);
  406. ob_end_clean();
  407. break;
  408. }
  409. return $returnvalue;
  410. }
  411. return false;
  412. }
  413. function ApacheLookupURIarray($filename) {
  414. // apache_lookup_uri() only works when PHP is installed as an Apache module.
  415. if (php_sapi_name() == 'apache') {
  416. $keys = array('status', 'the_request', 'status_line', 'method', 'content_type', 'handler', 'uri', 'filename', 'path_info', 'args', 'boundary', 'no_cache', 'no_local_copy', 'allowed', 'send_bodyct', 'bytes_sent', 'byterange', 'clength', 'unparsed_uri', 'mtime', 'request_time');
  417. if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
  418. $apacheLookupURIarray = array();
  419. foreach ($keys as $key) {
  420. $apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
  421. }
  422. return $apacheLookupURIarray;
  423. }
  424. }
  425. return false;
  426. }
  427. function gd_is_bundled() {
  428. static $isbundled = null;
  429. if (is_null($isbundled)) {
  430. $gd_info = gd_info();
  431. $isbundled = (strpos($gd_info['GD Version'], 'bundled') !== false);
  432. }
  433. return $isbundled;
  434. }
  435. function gd_version($fullstring=false) {
  436. static $cache_gd_version = array();
  437. if (empty($cache_gd_version)) {
  438. $gd_info = gd_info();
  439. if (eregi('bundled \((.+)\)$', $gd_info['GD Version'], $matches)) {
  440. $cache_gd_version[1] = $gd_info['GD Version']; // e.g. "bundled (2.0.15 compatible)"
  441. $cache_gd_version[0] = (float) $matches[1]; // e.g. "2.0" (not "bundled (2.0.15 compatible)")
  442. } else {
  443. $cache_gd_version[1] = $gd_info['GD Version']; // e.g. "1.6.2 or higher"
  444. $cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
  445. }
  446. }
  447. return $cache_gd_version[intval($fullstring)];
  448. }
  449. function filesize_remote($remotefile, $timeout=10) {
  450. $size = false;
  451. $url = phpthumb_functions::ParseURLbetter($remotefile);
  452. if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
  453. fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
  454. if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
  455. stream_set_timeout($fp, $timeout);
  456. }
  457. while (!feof($fp)) {
  458. $headerline = fgets($fp, 4096);
  459. if (eregi('^Content-Length: (.*)', $headerline, $matches)) {
  460. $size = intval($matches[1]);
  461. break;
  462. }
  463. }
  464. fclose ($fp);
  465. }
  466. return $size;
  467. }
  468. function filedate_remote($remotefile, $timeout=10) {
  469. $date = false;
  470. $url = phpthumb_functions::ParseURLbetter($remotefile);
  471. if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
  472. fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
  473. if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
  474. stream_set_timeout($fp, $timeout);
  475. }
  476. while (!feof($fp)) {
  477. $headerline = fgets($fp, 4096);
  478. if (eregi('^Last-Modified: (.*)', $headerline, $matches)) {
  479. $date = strtotime($matches[1]) - date('Z');
  480. break;
  481. }
  482. }
  483. fclose ($fp);
  484. }
  485. return $date;
  486. }
  487. function md5_file_safe($filename) {
  488. // md5_file() doesn't exist in PHP < 4.2.0
  489. if (function_exists('md5_file')) {
  490. return md5_file($filename);
  491. }
  492. if ($fp = @fopen($filename, 'rb')) {
  493. $rawData = '';
  494. do {
  495. $buffer = fread($fp, 8192);
  496. $rawData .= $buffer;
  497. } while (strlen($buffer) > 0);
  498. fclose($fp);
  499. return md5($rawData);
  500. }
  501. return false;
  502. }
  503. function nonempty_min() {
  504. $arg_list = func_get_args();
  505. $acceptable = array();
  506. foreach ($arg_list as $arg) {
  507. if ($arg) {
  508. $acceptable[] = $arg;
  509. }
  510. }
  511. return min($acceptable);
  512. }
  513. function LittleEndian2String($number, $minbytes=1) {
  514. $intstring = '';
  515. while ($number > 0) {
  516. $intstring = $intstring.chr($number & 255);
  517. $number >>= 8;
  518. }
  519. return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
  520. }
  521. function OneOfThese() {
  522. // return the first useful (non-empty/non-zero/non-false) value from those passed
  523. $arg_list = func_get_args();
  524. foreach ($arg_list as $key => $value) {
  525. if ($value) {
  526. return $value;
  527. }
  528. }
  529. return false;
  530. }
  531. function CaseInsensitiveInArray($needle, $haystack) {
  532. $needle = strtolower($needle);
  533. foreach ($haystack as $key => $value) {
  534. if (is_array($value)) {
  535. // skip?
  536. } elseif ($needle == strtolower($value)) {
  537. return true;
  538. }
  539. }
  540. return false;
  541. }
  542. function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
  543. if (!function_exists('fsockopen') || phpthumb_functions::FunctionIsDisabled('fsockopen')) {
  544. $errstr = 'fsockopen() unavailable';
  545. return false;
  546. }
  547. if ($fp = @fsockopen($host, 80, $errno, $errstr, $timeout)) {
  548. $out = 'GET '.$file.' HTTP/1.0'."\r\n";
  549. $out .= 'Host: '.$host."\r\n";
  550. $out .= 'Connection: Close'."\r\n\r\n";
  551. fwrite($fp, $out);
  552. $isHeader = true;
  553. $Data_header = '';
  554. $Data_body = '';
  555. $header_newlocation = '';
  556. while (!feof($fp)) {
  557. $line = fgets($fp, 1024);
  558. if ($isHeader) {
  559. $Data_header .= $line;
  560. } else {
  561. $Data_body .= $line;
  562. }
  563. if (eregi('^HTTP/[\\.0-9]+ ([0-9]+) (.+)$', rtrim($line), $matches)) {
  564. list($dummy, $errno, $errstr) = $matches;
  565. $errno = intval($errno);
  566. } elseif (eregi('^Location: (.*)$', rtrim($line), $matches)) {
  567. $header_newlocation = $matches[1];
  568. }
  569. if ($isHeader && ($line == "\r\n")) {
  570. $isHeader = false;
  571. if ($successonly) {
  572. switch ($errno) {
  573. case 200:
  574. // great, continue
  575. break;
  576. default:
  577. $errstr = $errno.' '.$errstr.($header_newlocation ? '; Location: '.$header_newlocation : '');
  578. fclose($fp);
  579. return false;
  580. break;
  581. }
  582. }
  583. }
  584. }
  585. fclose($fp);
  586. return $Data_body;
  587. }
  588. return null;
  589. }
  590. function CleanUpURLencoding($url, $queryseperator='&') {
  591. if (!eregi('^http', $url)) {
  592. return $url;
  593. }
  594. $parse_url = phpthumb_functions::ParseURLbetter($url);
  595. $pathelements = explode('/', $parse_url['path']);
  596. $CleanPathElements = array();
  597. $TranslationMatrix = array(' '=>'%20');
  598. foreach ($pathelements as $key => $pathelement) {
  599. $CleanPathElements[] = strtr($pathelement, $TranslationMatrix);
  600. }
  601. foreach ($CleanPathElements as $key => $value) {
  602. if ($value === '') {
  603. unset($CleanPathElements[$key]);
  604. }
  605. }
  606. $queries = explode($queryseperator, @$parse_url['query']);
  607. $CleanQueries = array();
  608. foreach ($queries as $key => $query) {
  609. @list($param, $value) = explode('=', $query);
  610. $CleanQueries[] = strtr($param, $TranslationMatrix).($value ? '='.strtr($value, $TranslationMatrix) : '');
  611. }
  612. foreach ($CleanQueries as $key => $value) {
  613. if ($value === '') {
  614. unset($CleanQueries[$key]);
  615. }
  616. }
  617. $cleaned_url = $parse_url['scheme'].'://';
  618. $cleaned_url .= (@$parse_url['username'] ? $parse_url['host'].(@$parse_url['password'] ? ':'.$parse_url['password'] : '').'@' : '');
  619. $cleaned_url .= $parse_url['host'];
  620. $cleaned_url .= '/'.implode('/', $CleanPathElements);
  621. $cleaned_url .= (@$CleanQueries ? '?'.implode($queryseperator, $CleanQueries) : '');
  622. return $cleaned_url;
  623. }
  624. function ParseURLbetter($url) {
  625. $parsedURL = @parse_url($url);
  626. if (!@$parsedURL['port']) {
  627. switch (strtolower(@$parsedURL['scheme'])) {
  628. case 'ftp':
  629. $parsedURL['port'] = 21;
  630. break;
  631. case 'https':
  632. $parsedURL['port'] = 443;
  633. break;
  634. case 'http':
  635. $parsedURL['port'] = 80;
  636. break;
  637. }
  638. }
  639. return $parsedURL;
  640. }
  641. function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
  642. $error = '';
  643. $parsed_url = phpthumb_functions::ParseURLbetter($url);
  644. $alreadyLookedAtURLs[trim($url)] = true;
  645. while (true) {
  646. $tryagain = false;
  647. $rawData = phpthumb_functions::URLreadFsock(@$parsed_url['host'], @$parsed_url['path'].'?'.@$parsed_url['query'], $errstr, true, (@$parsed_url['port'] ? @$parsed_url['port'] : 80), $timeout);
  648. if (eregi('302 [a-z ]+; Location\\: (http.*)', $errstr, $matches)) {
  649. $matches[1] = trim(@$matches[1]);
  650. if (!@$alreadyLookedAtURLs[$matches[1]]) {
  651. // loop through and examine new URL
  652. $error .= 'URL "'.$url.'" redirected to "'.$matches[1].'"';
  653. $tryagain = true;
  654. $alreadyLookedAtURLs[$matches[1]] = true;
  655. $parsed_url = phpthumb_functions::ParseURLbetter($matches[1]);
  656. }
  657. }
  658. if (!$tryagain) {
  659. break;
  660. }
  661. }
  662. if ($rawData === false) {
  663. $error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
  664. return false;
  665. } elseif ($rawData === null) {
  666. // fall through
  667. $error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
  668. } else {
  669. return $rawData;
  670. }
  671. if (function_exists('curl_version') && !phpthumb_functions::FunctionIsDisabled('curl_exec')) {
  672. $ch = curl_init();
  673. curl_setopt($ch, CURLOPT_URL, $url);
  674. curl_setopt($ch, CURLOPT_HEADER, false);
  675. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  676. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  677. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  678. $rawData = curl_exec($ch);
  679. curl_close($ch);
  680. if (strlen($rawData) > 0) {
  681. $error .= 'CURL succeeded ('.strlen($rawData).' bytes); ';
  682. return $rawData;
  683. }
  684. $error .= 'CURL available but returned no data; ';
  685. } else {
  686. $error .= 'CURL unavailable; ';
  687. }
  688. $BrokenURLfopenPHPversions = array('4.4.2');
  689. if (in_array(phpversion(), $BrokenURLfopenPHPversions)) {
  690. $error .= 'fopen(URL) broken in PHP v'.phpversion().'; ';
  691. } elseif (@ini_get('allow_url_fopen')) {
  692. $rawData = '';
  693. $error_fopen = '';
  694. ob_start();
  695. if ($fp = fopen($url, 'rb')) {
  696. do {
  697. $buffer = fread($fp, 8192);
  698. $rawData .= $buffer;
  699. } while (strlen($buffer) > 0);
  700. fclose($fp);
  701. } else {
  702. $error_fopen .= trim(strip_tags(ob_get_contents()));
  703. }
  704. ob_end_clean();
  705. $error .= $error_fopen;
  706. if (!$error_fopen) {
  707. $error .= '; "allow_url_fopen" succeeded ('.strlen($rawData).' bytes); ';
  708. return $rawData;
  709. }
  710. $error .= '; "allow_url_fopen" enabled but returned no data ('.$error_fopen.'); ';
  711. } else {
  712. $error .= '"allow_url_fopen" disabled; ';
  713. }
  714. return false;
  715. }
  716. function EnsureDirectoryExists($dirname) {
  717. $directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
  718. $startoffset = (!$directory_elements[0] ? 2 : 1); // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
  719. $open_basedirs = split('[;:]', ini_get('open_basedir'));
  720. foreach ($open_basedirs as $key => $open_basedir) {
  721. if (ereg('^'.preg_quote($open_basedir), $dirname) && (strlen($dirname) > strlen($open_basedir))) {
  722. $startoffset = count(explode(DIRECTORY_SEPARATOR, $open_basedir));
  723. break;
  724. }
  725. }
  726. $i = $startoffset;
  727. $endoffset = count($directory_elements);
  728. for ($i = $startoffset; $i <= $endoffset; $i++) {
  729. $test_directory = implode(DIRECTORY_SEPARATOR, array_slice($directory_elements, 0, $i));
  730. if (!$test_directory) {
  731. continue;
  732. }
  733. if (!@is_dir($test_directory)) {
  734. if (@file_exists($test_directory)) {
  735. // directory name already exists as a file
  736. return false;
  737. }
  738. @mkdir($test_directory, 0755);
  739. @chmod($test_directory, 0755);
  740. if (!@is_dir($test_directory) || !@is_writeable($test_directory)) {
  741. return false;
  742. }
  743. }
  744. }
  745. return true;
  746. }
  747. function GetAllFilesInSubfolders($dirname) {
  748. $AllFiles = array();
  749. $dirname = rtrim(realpath($dirname), '/\\');
  750. if ($dirhandle = @opendir($dirname)) {
  751. while (($file = readdir($dirhandle)) !== false) {
  752. $fullfilename = $dirname.DIRECTORY_SEPARATOR.$file;
  753. if (is_file($fullfilename)) {
  754. $AllFiles[] = $fullfilename;
  755. } elseif (is_dir($fullfilename)) {
  756. switch ($file) {
  757. case '.':
  758. case '..':
  759. break;
  760. default:
  761. $AllFiles[] = $fullfilename;
  762. $subfiles = phpthumb_functions::GetAllFilesInSubfolders($fullfilename);
  763. foreach ($subfiles as $filename) {
  764. $AllFiles[] = $filename;
  765. }
  766. break;
  767. }
  768. } else {
  769. // ignore?
  770. }
  771. }
  772. closedir($dirhandle);
  773. }
  774. sort($AllFiles);
  775. return array_unique($AllFiles);
  776. }
  777. function SanitizeFilename($filename) {
  778. $filename = ereg_replace('[^'.preg_quote(' !#$%^()+,-.;<>=@[]_{}').'a-zA-Z0-9]', '_', $filename);
  779. if (phpthumb_functions::version_compare_replacement(phpversion(), '4.1.0', '>=')) {
  780. $filename = trim($filename, '.');
  781. }
  782. return $filename;
  783. }
  784. }
  785. ////////////// END: class phpthumb_functions //////////////
  786. if (!function_exists('gd_info')) {
  787. // built into PHP v4.3.0+ (with bundled GD2 library)
  788. function gd_info() {
  789. static $gd_info = array();
  790. if (empty($gd_info)) {
  791. // based on code by johnschaefer at gmx dot de
  792. // from PHP help on gd_info()
  793. $gd_info = array(
  794. 'GD Version' => '',
  795. 'FreeType Support' => false,
  796. 'FreeType Linkage' => '',
  797. 'T1Lib Support' => false,
  798. 'GIF Read Support' => false,
  799. 'GIF Create Support' => false,
  800. 'JPG Support' => false,
  801. 'PNG Support' => false,
  802. 'WBMP Support' => false,
  803. 'XBM Support' => false
  804. );
  805. $phpinfo_array = phpthumb_functions::phpinfo_array();
  806. foreach ($phpinfo_array as $line) {
  807. $line = trim(strip_tags($line));
  808. foreach ($gd_info as $key => $value) {
  809. //if (strpos($line, $key) !== false) {
  810. if (strpos($line, $key) === 0) {
  811. $newvalue = trim(str_replace($key, '', $line));
  812. $gd_info[$key] = $newvalue;
  813. }
  814. }
  815. }
  816. if (empty($gd_info['GD Version'])) {
  817. // probable cause: "phpinfo() disabled for security reasons"
  818. if (function_exists('ImageTypes')) {
  819. $imagetypes = ImageTypes();
  820. if ($imagetypes & IMG_PNG) {
  821. $gd_info['PNG Support'] = true;
  822. }
  823. if ($imagetypes & IMG_GIF) {
  824. $gd_info['GIF Create Support'] = true;
  825. }
  826. if ($imagetypes & IMG_JPG) {
  827. $gd_info['JPG Support'] = true;
  828. }
  829. if ($imagetypes & IMG_WBMP) {
  830. $gd_info['WBMP Support'] = true;
  831. }
  832. }
  833. // to determine capability of GIF creation, try to use ImageCreateFromGIF on a 1px GIF
  834. if (function_exists('ImageCreateFromGIF')) {
  835. if ($tempfilename = phpthumb::phpThumb_tempnam()) {
  836. if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
  837. fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
  838. fclose($fp_tempfile);
  839. // if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
  840. $gd_info['GIF Read Support'] = (bool) @ImageCreateFromGIF($tempfilename);
  841. }
  842. unlink($tempfilename);
  843. }
  844. }
  845. if (function_exists('ImageCreateTrueColor') && @ImageCreateTrueColor(1, 1)) {
  846. $gd_info['GD Version'] = '2.0.1 or higher (assumed)';
  847. } elseif (function_exists('ImageCreate') && @ImageCreate(1, 1)) {
  848. $gd_info['GD Version'] = '1.6.0 or higher (assumed)';
  849. }
  850. }
  851. }
  852. return $gd_info;
  853. }
  854. }
  855. if (!function_exists('is_executable')) {
  856. // in PHP v3+, but v5.0+ for Windows
  857. function is_executable($filename) {
  858. // poor substitute, but better than nothing
  859. return file_exists($filename);
  860. }
  861. }
  862. if (!function_exists('preg_quote')) {
  863. // included in PHP v3.0.9+, but may be unavailable if not compiled in
  864. function preg_quote($string, $delimiter='\\') {
  865. static $preg_quote_array = array();
  866. if (empty($preg_quote_array)) {
  867. $escapeables = '.\\+*?[^]$(){}=!<>|:';
  868. for ($i = 0; $i < strlen($escapeables); $i++) {
  869. $strtr_preg_quote[$escapeables{$i}] = $delimiter.$escapeables{$i};
  870. }
  871. }
  872. return strtr($string, $strtr_preg_quote);
  873. }
  874. }
  875. if (!function_exists('file_get_contents')) {
  876. // included in PHP v4.3.0+
  877. function file_get_contents($filename) {
  878. if (eregi('^(f|ht)tp\://', $filename)) {
  879. return SafeURLread($filename, $error);
  880. }
  881. if ($fp = @fopen($filename, 'rb')) {
  882. $rawData = '';
  883. do {
  884. $buffer = fread($fp, 8192);
  885. $rawData .= $buffer;
  886. } while (strlen($buffer) > 0);
  887. fclose($fp);
  888. return $rawData;
  889. }
  890. return false;
  891. }
  892. }
  893. if (!function_exists('file_put_contents')) {
  894. // included in PHP v5.0.0+
  895. function file_put_contents($filename, $filedata) {
  896. if ($fp = @fopen($filename, 'wb')) {
  897. fwrite($fp, $filedata);
  898. fclose($fp);
  899. return true;
  900. }
  901. return false;
  902. }
  903. }
  904. if (!function_exists('imagealphablending')) {
  905. // built-in function requires PHP v4.0.6+ *and* GD v2.0.1+
  906. function imagealphablending(&$img, $blendmode=true) {
  907. // do nothing, this function is declared here just to
  908. // prevent runtime errors if GD2 is not available
  909. return true;
  910. }
  911. }
  912. if (!function_exists('imagesavealpha')) {
  913. // built-in function requires PHP v4.3.2+ *and* GD v2.0.1+
  914. function imagesavealpha(&$img, $blendmode=true) {
  915. // do nothing, this function is declared here just to
  916. // prevent runtime errors if GD2 is not available
  917. return true;
  918. }
  919. }
  920. ?>