PageRenderTime 42ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/tinymce/jscripts/tiny_mce/plugins/iBrowser/scripts/phpThumb/phpthumb.functions.php

https://bitbucket.org/c_maksud/tinymce-with-ibrowser-in-codeignitor
PHP | 1046 lines | 873 code | 120 blank | 53 comment | 145 complexity | 2319f7081cc447cf6818a4cf2130c910 MD5 | raw file
  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. static 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. static 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. static 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:
  36. // (any string not found in this list) < (dev) < (alpha = a) < (beta = b) < (RC = rc) < (#) < (pl = p)
  37. static $versiontype_lookup = array();
  38. if (empty($versiontype_lookup)) {
  39. $versiontype_lookup['dev'] = 10001;
  40. $versiontype_lookup['a'] = 10002;
  41. $versiontype_lookup['alpha'] = 10002;
  42. $versiontype_lookup['b'] = 10003;
  43. $versiontype_lookup['beta'] = 10003;
  44. $versiontype_lookup['RC'] = 10004;
  45. $versiontype_lookup['rc'] = 10004;
  46. $versiontype_lookup['#'] = 10005;
  47. $versiontype_lookup['pl'] = 10006;
  48. $versiontype_lookup['p'] = 10006;
  49. }
  50. $version1 = (isset($versiontype_lookup[$version1]) ? $versiontype_lookup[$version1] : $version1);
  51. $version2 = (isset($versiontype_lookup[$version2]) ? $versiontype_lookup[$version2] : $version2);
  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. static 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 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$1.$2.$3", $version1);
  98. $version2 = preg_replace('#([0-9]+)([A-Z]+)([0-9]+)#i', "$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. static 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. static 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. static 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. static 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. static 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. static function IsHexColor($HexColorString) {
  193. return preg_match('#^[0-9A-F]{6}$#i', $HexColorString);
  194. }
  195. static 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. static 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. static function HexColorXOR($hexcolor) {
  218. return strtoupper(str_pad(dechex(~hexdec($hexcolor) & 0xFFFFFF), 6, '0', STR_PAD_LEFT));
  219. }
  220. static function GetPixelColor(&$img, $x, $y) {
  221. if (!is_resource($img)) {
  222. return false;
  223. }
  224. return @ImageColorsForIndex($img, @ImageColorAt($img, $x, $y));
  225. }
  226. static 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. static function GrayscaleValue($r, $g, $b) {
  234. return round(($r * 0.30) + ($g * 0.59) + ($b * 0.11));
  235. }
  236. static 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. static 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. static 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. static 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. static 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. static 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. static 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. static 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. static 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. static function ApacheLookupURIarray($filename) {
  414. // apache_lookup_uri() only works when PHP is installed as an Apache module.
  415. if (php_sapi_name() == 'apache') {
  416. //$property_exists_exists = function_exists('property_exists');
  417. $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');
  418. if ($apacheLookupURIobject = @apache_lookup_uri($filename)) {
  419. $apacheLookupURIarray = array();
  420. foreach ($keys as $key) {
  421. $apacheLookupURIarray[$key] = @$apacheLookupURIobject->$key;
  422. }
  423. return $apacheLookupURIarray;
  424. }
  425. }
  426. return false;
  427. }
  428. static function gd_is_bundled() {
  429. static $isbundled = null;
  430. if (is_null($isbundled)) {
  431. $gd_info = gd_info();
  432. $isbundled = (strpos($gd_info['GD Version'], 'bundled') !== false);
  433. }
  434. return $isbundled;
  435. }
  436. static function gd_version($fullstring=false) {
  437. static $cache_gd_version = array();
  438. if (empty($cache_gd_version)) {
  439. $gd_info = gd_info();
  440. if (preg_match('#bundled \((.+)\)$#i', $gd_info['GD Version'], $matches)) {
  441. $cache_gd_version[1] = $gd_info['GD Version']; // e.g. "bundled (2.0.15 compatible)"
  442. $cache_gd_version[0] = (float) $matches[1]; // e.g. "2.0" (not "bundled (2.0.15 compatible)")
  443. } else {
  444. $cache_gd_version[1] = $gd_info['GD Version']; // e.g. "1.6.2 or higher"
  445. $cache_gd_version[0] = (float) substr($gd_info['GD Version'], 0, 3); // e.g. "1.6" (not "1.6.2 or higher")
  446. }
  447. }
  448. return $cache_gd_version[intval($fullstring)];
  449. }
  450. static function filesize_remote($remotefile, $timeout=10) {
  451. $size = false;
  452. $url = phpthumb_functions::ParseURLbetter($remotefile);
  453. if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
  454. fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
  455. if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
  456. stream_set_timeout($fp, $timeout);
  457. }
  458. while (!feof($fp)) {
  459. $headerline = fgets($fp, 4096);
  460. if (preg_match('#^Content-Length: (.*)#i', $headerline, $matches)) {
  461. $size = intval($matches[1]);
  462. break;
  463. }
  464. }
  465. fclose ($fp);
  466. }
  467. return $size;
  468. }
  469. static function filedate_remote($remotefile, $timeout=10) {
  470. $date = false;
  471. $url = phpthumb_functions::ParseURLbetter($remotefile);
  472. if ($fp = @fsockopen($url['host'], ($url['port'] ? $url['port'] : 80), $errno, $errstr, $timeout)) {
  473. fwrite($fp, 'HEAD '.@$url['path'].@$url['query'].' HTTP/1.0'."\r\n".'Host: '.@$url['host']."\r\n\r\n");
  474. if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
  475. stream_set_timeout($fp, $timeout);
  476. }
  477. while (!feof($fp)) {
  478. $headerline = fgets($fp, 4096);
  479. if (preg_match('#^Last-Modified: (.*)#i', $headerline, $matches)) {
  480. $date = strtotime($matches[1]) - date('Z');
  481. break;
  482. }
  483. }
  484. fclose ($fp);
  485. }
  486. return $date;
  487. }
  488. static function md5_file_safe($filename) {
  489. // md5_file() doesn't exist in PHP < 4.2.0
  490. if (function_exists('md5_file')) {
  491. return md5_file($filename);
  492. }
  493. if ($fp = @fopen($filename, 'rb')) {
  494. $rawData = '';
  495. do {
  496. $buffer = fread($fp, 8192);
  497. $rawData .= $buffer;
  498. } while (strlen($buffer) > 0);
  499. fclose($fp);
  500. return md5($rawData);
  501. }
  502. return false;
  503. }
  504. static function nonempty_min() {
  505. $arg_list = func_get_args();
  506. $acceptable = array();
  507. foreach ($arg_list as $arg) {
  508. if ($arg) {
  509. $acceptable[] = $arg;
  510. }
  511. }
  512. return min($acceptable);
  513. }
  514. static function LittleEndian2String($number, $minbytes=1) {
  515. $intstring = '';
  516. while ($number > 0) {
  517. $intstring = $intstring.chr($number & 255);
  518. $number >>= 8;
  519. }
  520. return str_pad($intstring, $minbytes, "\x00", STR_PAD_RIGHT);
  521. }
  522. static function OneOfThese() {
  523. // return the first useful (non-empty/non-zero/non-false) value from those passed
  524. $arg_list = func_get_args();
  525. foreach ($arg_list as $key => $value) {
  526. if ($value) {
  527. return $value;
  528. }
  529. }
  530. return false;
  531. }
  532. static function CaseInsensitiveInArray($needle, $haystack) {
  533. $needle = strtolower($needle);
  534. foreach ($haystack as $key => $value) {
  535. if (is_array($value)) {
  536. // skip?
  537. } elseif ($needle == strtolower($value)) {
  538. return true;
  539. }
  540. }
  541. return false;
  542. }
  543. static function URLreadFsock($host, $file, &$errstr, $successonly=true, $port=80, $timeout=10) {
  544. if (!function_exists('fsockopen') || phpthumb_functions::FunctionIsDisabled('fsockopen')) {
  545. $errstr = 'fsockopen() unavailable';
  546. return false;
  547. }
  548. if ($fp = @fsockopen($host, $port, $errno, $errstr, $timeout)) {
  549. $out = 'GET '.$file.' HTTP/1.0'."\r\n";
  550. $out .= 'Host: '.$host."\r\n";
  551. $out .= 'Connection: Close'."\r\n\r\n";
  552. fwrite($fp, $out);
  553. $isHeader = true;
  554. $Data_header = '';
  555. $Data_body = '';
  556. $header_newlocation = '';
  557. while (!feof($fp)) {
  558. $line = fgets($fp, 1024);
  559. if ($isHeader) {
  560. $Data_header .= $line;
  561. } else {
  562. $Data_body .= $line;
  563. }
  564. if (preg_match('#^HTTP/[\\.0-9]+ ([0-9]+) (.+)$#i', rtrim($line), $matches)) {
  565. list($dummy, $errno, $errstr) = $matches;
  566. $errno = intval($errno);
  567. } elseif (preg_match('#^Location: (.*)$#i', rtrim($line), $matches)) {
  568. $header_newlocation = $matches[1];
  569. }
  570. if ($isHeader && ($line == "\r\n")) {
  571. $isHeader = false;
  572. if ($successonly) {
  573. switch ($errno) {
  574. case 200:
  575. // great, continue
  576. break;
  577. default:
  578. $errstr = $errno.' '.$errstr.($header_newlocation ? '; Location: '.$header_newlocation : '');
  579. fclose($fp);
  580. return false;
  581. break;
  582. }
  583. }
  584. }
  585. }
  586. fclose($fp);
  587. return $Data_body;
  588. }
  589. return null;
  590. }
  591. static function CleanUpURLencoding($url, $queryseperator='&') {
  592. if (!preg_match('#^http#i', $url)) {
  593. return $url;
  594. }
  595. $parse_url = phpthumb_functions::ParseURLbetter($url);
  596. $pathelements = explode('/', $parse_url['path']);
  597. $CleanPathElements = array();
  598. $TranslationMatrix = array(' '=>'%20');
  599. foreach ($pathelements as $key => $pathelement) {
  600. $CleanPathElements[] = strtr($pathelement, $TranslationMatrix);
  601. }
  602. foreach ($CleanPathElements as $key => $value) {
  603. if ($value === '') {
  604. unset($CleanPathElements[$key]);
  605. }
  606. }
  607. $queries = explode($queryseperator, (isset($parse_url['query']) ? $parse_url['query'] : ''));
  608. $CleanQueries = array();
  609. foreach ($queries as $key => $query) {
  610. @list($param, $value) = explode('=', $query);
  611. $CleanQueries[] = strtr($param, $TranslationMatrix).($value ? '='.strtr($value, $TranslationMatrix) : '');
  612. }
  613. foreach ($CleanQueries as $key => $value) {
  614. if ($value === '') {
  615. unset($CleanQueries[$key]);
  616. }
  617. }
  618. $cleaned_url = $parse_url['scheme'].'://';
  619. $cleaned_url .= (@$parse_url['username'] ? $parse_url['host'].(@$parse_url['password'] ? ':'.$parse_url['password'] : '').'@' : '');
  620. $cleaned_url .= $parse_url['host'];
  621. $cleaned_url .= ((!empty($parse_url['port']) && ($parse_url['port'] != 80)) ? ':'.$parse_url['port'] : '');
  622. $cleaned_url .= '/'.implode('/', $CleanPathElements);
  623. $cleaned_url .= (@$CleanQueries ? '?'.implode($queryseperator, $CleanQueries) : '');
  624. return $cleaned_url;
  625. }
  626. static function ParseURLbetter($url) {
  627. $parsedURL = @parse_url($url);
  628. if (!@$parsedURL['port']) {
  629. switch (strtolower(@$parsedURL['scheme'])) {
  630. case 'ftp':
  631. $parsedURL['port'] = 21;
  632. break;
  633. case 'https':
  634. $parsedURL['port'] = 443;
  635. break;
  636. case 'http':
  637. $parsedURL['port'] = 80;
  638. break;
  639. }
  640. }
  641. return $parsedURL;
  642. }
  643. static function SafeURLread($url, &$error, $timeout=10, $followredirects=true) {
  644. $error = '';
  645. $parsed_url = phpthumb_functions::ParseURLbetter($url);
  646. $alreadyLookedAtURLs[trim($url)] = true;
  647. while (true) {
  648. $tryagain = false;
  649. $rawData = phpthumb_functions::URLreadFsock(@$parsed_url['host'], @$parsed_url['path'].'?'.@$parsed_url['query'], $errstr, true, (@$parsed_url['port'] ? @$parsed_url['port'] : 80), $timeout);
  650. if (preg_match('#302 [a-z ]+; Location\\: (http.*)#i', $errstr, $matches)) {
  651. $matches[1] = trim(@$matches[1]);
  652. if (!@$alreadyLookedAtURLs[$matches[1]]) {
  653. // loop through and examine new URL
  654. $error .= 'URL "'.$url.'" redirected to "'.$matches[1].'"';
  655. $tryagain = true;
  656. $alreadyLookedAtURLs[$matches[1]] = true;
  657. $parsed_url = phpthumb_functions::ParseURLbetter($matches[1]);
  658. }
  659. }
  660. if (!$tryagain) {
  661. break;
  662. }
  663. }
  664. if ($rawData === false) {
  665. $error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
  666. return false;
  667. } elseif ($rawData === null) {
  668. // fall through
  669. $error .= 'Error opening "'.$url.'":'."\n\n".$errstr;
  670. } else {
  671. return $rawData;
  672. }
  673. if (function_exists('curl_version') && !phpthumb_functions::FunctionIsDisabled('curl_exec')) {
  674. $ch = curl_init();
  675. curl_setopt($ch, CURLOPT_URL, $url);
  676. curl_setopt($ch, CURLOPT_HEADER, false);
  677. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  678. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  679. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  680. $rawData = curl_exec($ch);
  681. curl_close($ch);
  682. if (strlen($rawData) > 0) {
  683. $error .= 'CURL succeeded ('.strlen($rawData).' bytes); ';
  684. return $rawData;
  685. }
  686. $error .= 'CURL available but returned no data; ';
  687. } else {
  688. $error .= 'CURL unavailable; ';
  689. }
  690. $BrokenURLfopenPHPversions = array('4.4.2');
  691. if (in_array(phpversion(), $BrokenURLfopenPHPversions)) {
  692. $error .= 'fopen(URL) broken in PHP v'.phpversion().'; ';
  693. } elseif (@ini_get('allow_url_fopen')) {
  694. $rawData = '';
  695. $error_fopen = '';
  696. ob_start();
  697. if ($fp = fopen($url, 'rb')) {
  698. do {
  699. $buffer = fread($fp, 8192);
  700. $rawData .= $buffer;
  701. } while (strlen($buffer) > 0);
  702. fclose($fp);
  703. } else {
  704. $error_fopen .= trim(strip_tags(ob_get_contents()));
  705. }
  706. ob_end_clean();
  707. $error .= $error_fopen;
  708. if (!$error_fopen) {
  709. $error .= '; "allow_url_fopen" succeeded ('.strlen($rawData).' bytes); ';
  710. return $rawData;
  711. }
  712. $error .= '; "allow_url_fopen" enabled but returned no data ('.$error_fopen.'); ';
  713. } else {
  714. $error .= '"allow_url_fopen" disabled; ';
  715. }
  716. return false;
  717. }
  718. static function EnsureDirectoryExists($dirname) {
  719. $directory_elements = explode(DIRECTORY_SEPARATOR, $dirname);
  720. $startoffset = (!$directory_elements[0] ? 2 : 1); // unix with leading "/" then start with 2nd element; Windows with leading "c:\" then start with 1st element
  721. $open_basedirs = preg_split('#[;:]#', ini_get('open_basedir'));
  722. foreach ($open_basedirs as $key => $open_basedir) {
  723. if (preg_match('#^'.preg_quote($open_basedir).'#', $dirname) && (strlen($dirname) > strlen($open_basedir))) {
  724. $startoffset = count(explode(DIRECTORY_SEPARATOR, $open_basedir));
  725. break;
  726. }
  727. }
  728. $i = $startoffset;
  729. $endoffset = count($directory_elements);
  730. for ($i = $startoffset; $i <= $endoffset; $i++) {
  731. $test_directory = implode(DIRECTORY_SEPARATOR, array_slice($directory_elements, 0, $i));
  732. if (!$test_directory) {
  733. continue;
  734. }
  735. if (!@is_dir($test_directory)) {
  736. if (@file_exists($test_directory)) {
  737. // directory name already exists as a file
  738. return false;
  739. }
  740. @mkdir($test_directory, 0755);
  741. @chmod($test_directory, 0755);
  742. if (!@is_dir($test_directory) || !@is_writeable($test_directory)) {
  743. return false;
  744. }
  745. }
  746. }
  747. return true;
  748. }
  749. static function GetAllFilesInSubfolders($dirname) {
  750. $AllFiles = array();
  751. $dirname = rtrim(realpath($dirname), '/\\');
  752. if ($dirhandle = @opendir($dirname)) {
  753. while (($file = readdir($dirhandle)) !== false) {
  754. $fullfilename = $dirname.DIRECTORY_SEPARATOR.$file;
  755. if (is_file($fullfilename)) {
  756. $AllFiles[] = $fullfilename;
  757. } elseif (is_dir($fullfilename)) {
  758. switch ($file) {
  759. case '.':
  760. case '..':
  761. break;
  762. default:
  763. $AllFiles[] = $fullfilename;
  764. $subfiles = phpthumb_functions::GetAllFilesInSubfolders($fullfilename);
  765. foreach ($subfiles as $filename) {
  766. $AllFiles[] = $filename;
  767. }
  768. break;
  769. }
  770. } else {
  771. // ignore?
  772. }
  773. }
  774. closedir($dirhandle);
  775. }
  776. sort($AllFiles);
  777. return array_unique($AllFiles);
  778. }
  779. static function SanitizeFilename($filename) {
  780. $filename = preg_replace('/[^'.preg_quote(' !#$%^()+,-.;<>=@[]_{}').'a-zA-Z0-9]/', '_', $filename);
  781. if (phpthumb_functions::version_compare_replacement(phpversion(), '4.1.0', '>=')) {
  782. $filename = trim($filename, '.');
  783. }
  784. return $filename;
  785. }
  786. }
  787. ////////////// END: class phpthumb_functions //////////////
  788. if (!function_exists('gd_info')) {
  789. // built into PHP v4.3.0+ (with bundled GD2 library)
  790. function gd_info() {
  791. static $gd_info = array();
  792. if (empty($gd_info)) {
  793. // based on code by johnschaefer at gmx dot de
  794. // from PHP help on gd_info()
  795. $gd_info = array(
  796. 'GD Version' => '',
  797. 'FreeType Support' => false,
  798. 'FreeType Linkage' => '',
  799. 'T1Lib Support' => false,
  800. 'GIF Read Support' => false,
  801. 'GIF Create Support' => false,
  802. 'JPG Support' => false,
  803. 'PNG Support' => false,
  804. 'WBMP Support' => false,
  805. 'XBM Support' => false
  806. );
  807. $phpinfo_array = phpthumb_functions::phpinfo_array();
  808. foreach ($phpinfo_array as $line) {
  809. $line = trim(strip_tags($line));
  810. foreach ($gd_info as $key => $value) {
  811. //if (strpos($line, $key) !== false) {
  812. if (strpos($line, $key) === 0) {
  813. $newvalue = trim(str_replace($key, '', $line));
  814. $gd_info[$key] = $newvalue;
  815. }
  816. }
  817. }
  818. if (empty($gd_info['GD Version'])) {
  819. // probable cause: "phpinfo() disabled for security reasons"
  820. if (function_exists('ImageTypes')) {
  821. $imagetypes = ImageTypes();
  822. if ($imagetypes & IMG_PNG) {
  823. $gd_info['PNG Support'] = true;
  824. }
  825. if ($imagetypes & IMG_GIF) {
  826. $gd_info['GIF Create Support'] = true;
  827. }
  828. if ($imagetypes & IMG_JPG) {
  829. $gd_info['JPG Support'] = true;
  830. }
  831. if ($imagetypes & IMG_WBMP) {
  832. $gd_info['WBMP Support'] = true;
  833. }
  834. }
  835. // to determine capability of GIF creation, try to use ImageCreateFromGIF on a 1px GIF
  836. if (function_exists('ImageCreateFromGIF')) {
  837. if ($tempfilename = phpthumb::phpThumb_tempnam()) {
  838. if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
  839. fwrite($fp_tempfile, base64_decode('R0lGODlhAQABAIAAAH//AP///ywAAAAAAQABAAACAUQAOw==')); // very simple 1px GIF file base64-encoded as string
  840. fclose($fp_tempfile);
  841. // if we can convert the GIF file to a GD image then GIF create support must be enabled, otherwise it's not
  842. $gd_info['GIF Read Support'] = (bool) @ImageCreateFromGIF($tempfilename);
  843. }
  844. unlink($tempfilename);
  845. }
  846. }
  847. if (function_exists('ImageCreateTrueColor') && @ImageCreateTrueColor(1, 1)) {
  848. $gd_info['GD Version'] = '2.0.1 or higher (assumed)';
  849. } elseif (function_exists('ImageCreate') && @ImageCreate(1, 1)) {
  850. $gd_info['GD Version'] = '1.6.0 or higher (assumed)';
  851. }
  852. }
  853. }
  854. return $gd_info;
  855. }
  856. }
  857. if (!function_exists('is_executable')) {
  858. // in PHP v3+, but v5.0+ for Windows
  859. function is_executable($filename) {
  860. // poor substitute, but better than nothing
  861. return file_exists($filename);
  862. }
  863. }
  864. if (!function_exists('preg_quote')) {
  865. // included in PHP v3.0.9+, but may be unavailable if not compiled in
  866. function preg_quote($string, $delimiter='\\') {
  867. static $preg_quote_array = array();
  868. if (empty($preg_quote_array)) {
  869. $escapeables = '.\\+*?[^]$(){}=!<>|:';
  870. for ($i = 0; $i < strlen($escapeables); $i++) {
  871. $strtr_preg_quote[$escapeables{$i}] = $delimiter.$escapeables{$i};
  872. }
  873. }
  874. return strtr($string, $strtr_preg_quote);
  875. }
  876. }
  877. if (!function_exists('file_get_contents')) {
  878. // included in PHP v4.3.0+
  879. function file_get_contents($filename) {
  880. if (preg_match('#^(f|ht)tp\://#i', $filename)) {
  881. return SafeURLread($filename, $error);
  882. }
  883. if ($fp = @fopen($filename, 'rb')) {
  884. $rawData = '';
  885. do {
  886. $buffer = fread($fp, 8192);
  887. $rawData .= $buffer;
  888. } while (strlen($buffer) > 0);
  889. fclose($fp);
  890. return $rawData;
  891. }
  892. return false;
  893. }
  894. }
  895. if (!function_exists('file_put_contents')) {
  896. // included in PHP v5.0.0+
  897. function file_put_contents($filename, $filedata) {
  898. if ($fp = @fopen($filename, 'wb')) {
  899. fwrite($fp, $filedata);
  900. fclose($fp);
  901. return true;
  902. }
  903. return false;
  904. }
  905. }
  906. if (!function_exists('imagealphablending')) {
  907. // built-in function requires PHP v4.0.6+ *and* GD v2.0.1+
  908. function imagealphablending(&$img, $blendmode=true) {
  909. // do nothing, this function is declared here just to
  910. // prevent runtime errors if GD2 is not available
  911. return true;
  912. }
  913. }
  914. if (!function_exists('imagesavealpha')) {
  915. // built-in function requires PHP v4.3.2+ *and* GD v2.0.1+
  916. function imagesavealpha(&$img, $blendmode=true) {
  917. // do nothing, this function is declared here just to
  918. // prevent runtime errors if GD2 is not available
  919. return true;
  920. }
  921. }
  922. ?>