PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/core/model/phpthumb/phpthumb.functions.php

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