MODX Revolution PHP Cross Reference Content Management Systems

Source: /core/model/phpthumb/phpthumb.functions.php - 1046 lines - 33856 bytes - Summary - Text - Print

Description: general support functions       //

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

title

Description

title

Description

title

Description

title

title

Body