PageRenderTime 49ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/src/phpthumb/phpthumb.functions.php

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