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// See: phpthumb.readme.txt for usage instructions // 9// /// 10////////////////////////////////////////////////////////////// 11 12if (!class_exists('phpthumb_functions', false)) { 13 ob_start(); 14 if (!include_once __DIR__ . '/phpthumb.functions.php') { 15 ob_end_flush(); 16 die('failed to include_once("' . __DIR__ . '/phpthumb.functions.php")'); 17 } 18 ob_end_clean(); 19} 20 21// make sure all image type constants are defined, even in older PHP versions that don't natively support them 22$predefined_IMG_constants = array( 23 'IMG_GIF' => 1, 24 'IMG_JPG' => 2, // not a typo, both IMG_JPG and IMG_JPEG have a value of "2" 25 'IMG_JPEG' => 2, // not a typo, both IMG_JPG and IMG_JPEG have a value of "2" 26 'IMG_PNG' => 4, 27 'IMG_WBMP' => 8, 28 'IMG_XPM' => 16, 29 'IMG_WEBP' => 32, // PHP 7.0.10 30 'IMG_BMP' => 64, // PHP 7.2.0 31 'IMG_WEBP_LOSSLESS' => 101, // PHP 8.1.0 32 'IMG_AVIF' => 256, // PHP 8.1.0 33); 34$predefined_IMAGETYPE_constants = array( 35 'IMAGETYPE_GIF' => 1, 36 'IMAGETYPE_JPEG' => 2, 37 'IMAGETYPE_PNG' => 3, 38 'IMAGETYPE_SWF' => 4, 39 'IMAGETYPE_PSD' => 5, 40 'IMAGETYPE_BMP' => 6, 41 'IMAGETYPE_TIFF_II' => 7, 42 'IMAGETYPE_TIFF_MM' => 8, 43 'IMAGETYPE_JPC' => 9, 44 'IMAGETYPE_JP2' => 10, 45 'IMAGETYPE_JPX' => 11, 46 'IMAGETYPE_JB2' => 12, 47 'IMAGETYPE_SWC' => 13, 48 'IMAGETYPE_IFF' => 14, 49 'IMAGETYPE_WBMP' => 15, 50 'IMAGETYPE_XBM' => 16, 51 'IMAGETYPE_ICO' => 17, 52 'IMAGETYPE_WEBP' => 18, // PHP 7.0.10 53 'IMAGETYPE_AVIF' => 19, // PHP 8.1.0 54); 55foreach ($predefined_IMG_constants as $PHP_constant_name => $PHP_constant_value) { 56 if (!defined($PHP_constant_name)) { 57 define($PHP_constant_name, $PHP_constant_value); 58 } 59} 60foreach ($predefined_IMAGETYPE_constants as $PHP_constant_name => $PHP_constant_value) { 61 if (!defined($PHP_constant_name)) { 62 define($PHP_constant_name, $PHP_constant_value); 63 } 64} 65unset($predefined_IMG_constants, $predefined_IMAGETYPE_constants, $PHP_constant_name, $PHP_constant_value); 66 67 68class phpthumb { 69 70 // public: 71 // START PARAMETERS (for object mode and phpThumb.php) 72 // See phpthumb.readme.txt for descriptions of what each of these values are 73 public $src = null; // SouRCe filename 74 public $new = null; // NEW image (phpThumb.php only) 75 public $w = null; // Width 76 public $h = null; // Height 77 public $wp = null; // Width (Portrait Images Only) 78 public $hp = null; // Height (Portrait Images Only) 79 public $wl = null; // Width (Landscape Images Only) 80 public $hl = null; // Height (Landscape Images Only) 81 public $ws = null; // Width (Square Images Only) 82 public $hs = null; // Height (Square Images Only) 83 public $f = null; // output image Format 84 public $q = 75; // jpeg output Quality 85 public $sx = null; // Source crop top-left X position 86 public $sy = null; // Source crop top-left Y position 87 public $sw = null; // Source crop Width 88 public $sh = null; // Source crop Height 89 public $zc = null; // Zoom Crop 90 public $ica = null; // Image Crop Auto 91 public $bc = null; // Border Color 92 public $bg = null; // BackGround color 93 public $fltr = array(); // FiLTeRs 94 public $goto = null; // GO TO url after processing 95 public $err = null; // default ERRor image filename 96 public $xto = null; // extract eXif Thumbnail Only 97 public $ra = null; // Rotate by Angle 98 public $ar = null; // Auto Rotate 99 public $aoe = null; // Allow Output Enlargement 100 public $far = null; // Fixed Aspect Ratio 101 public $iar = null; // Ignore Aspect Ratio 102 public $maxb = null; // MAXimum Bytes 103 public $down = null; // DOWNload thumbnail filename 104 public $md5s = null; // MD5 hash of Source image 105 public $sfn = 0; // Source Frame Number 106 public $dpi = 150; // Dots Per Inch for vector source formats 107 public $sia = null; // Save Image As filename 108 109 public $file = null; // >>>deprecated, DO NOT USE, will be removed in future versions<<< 110 111 public $phpThumbDebug = null; 112 // END PARAMETERS 113 114 115 // public: 116 // START CONFIGURATION OPTIONS (for object mode only) 117 // See phpThumb.config.php for descriptions of what each of these settings do 118 119 // * Directory Configuration 120 public $config_cache_directory = null; 121 public $config_cache_directory_depth = 0; 122 public $config_cache_disable_warning = true; 123 public $config_cache_source_enabled = false; 124 public $config_cache_source_directory = null; 125 public $config_temp_directory = null; 126 public $config_document_root = null; 127 128 // * Default output configuration: 129 public $config_output_format = 'jpeg'; 130 public $config_output_maxwidth = 0; 131 public $config_output_maxheight = 0; 132 public $config_output_interlace = true; 133 134 // * Error message configuration 135 public $config_error_image_width = 400; 136 public $config_error_image_height = 100; 137 public $config_error_message_image_default = ''; 138 public $config_error_bgcolor = 'CCCCFF'; 139 public $config_error_textcolor = 'FF0000'; 140 public $config_error_fontsize = 1; 141 public $config_error_die_on_error = false; 142 public $config_error_silent_die_on_error = false; 143 public $config_error_die_on_source_failure = true; 144 145 // * Anti-Hotlink Configuration: 146 public $config_nohotlink_enabled = true; 147 public $config_nohotlink_valid_domains = array(); 148 public $config_nohotlink_erase_image = true; 149 public $config_nohotlink_text_message = 'Off-server thumbnailing is not allowed'; 150 // * Off-server Linking Configuration: 151 public $config_nooffsitelink_enabled = false; 152 public $config_nooffsitelink_valid_domains = array(); 153 public $config_nooffsitelink_require_refer = false; 154 public $config_nooffsitelink_erase_image = true; 155 public $config_nooffsitelink_watermark_src = ''; 156 public $config_nooffsitelink_text_message = 'Off-server linking is not allowed'; 157 158 // * Border & Background default colors 159 public $config_border_hexcolor = '000000'; 160 public $config_background_hexcolor = 'FFFFFF'; 161 162 // * TrueType Fonts 163 public $config_ttf_directory = './fonts'; 164 165 public $config_max_source_pixels = null; 166 public $config_use_exif_thumbnail_for_speed = false; 167 public $config_allow_local_http_src = false; 168 169 public $config_imagemagick_path = null; 170 public $config_prefer_imagemagick = true; 171 public $config_imagemagick_use_thumbnail = true; 172 173 public $config_cache_maxage = null; 174 public $config_cache_maxsize = null; 175 public $config_cache_maxfiles = null; 176 public $config_cache_source_filemtime_ignore_local = false; 177 public $config_cache_source_filemtime_ignore_remote = true; 178 public $config_cache_default_only_suffix = false; 179 public $config_cache_force_passthru = true; 180 public $config_cache_prefix = ''; // default value set in the constructor below 181 182 // * MySQL 183 public $config_mysql_extension = null; 184 public $config_mysql_query = null; 185 public $config_mysql_hostname = null; 186 public $config_mysql_username = null; 187 public $config_mysql_password = null; 188 public $config_mysql_database = null; 189 190 // * Security 191 public $config_high_security_enabled = true; 192 public $config_high_security_password = null; 193 public $config_high_security_url_separator = '&'; 194 public $config_disable_debug = true; 195 public $config_allow_src_above_docroot = false; 196 public $config_allow_src_above_phpthumb = true; 197 public $config_auto_allow_symlinks = true; // allow symlink target directories without explicitly whitelisting them 198 public $config_additional_allowed_dirs = array(); // additional directories to allow source images to be read from 199 public $config_file_create_mask = 0755; 200 public $config_dir_create_mask = 0755; 201 202 // * HTTP fopen 203 public $config_http_fopen_timeout = 10; 204 public $config_http_follow_redirect = true; 205 206 // * Compatability 207 public $config_disable_pathinfo_parsing = false; 208 public $config_disable_imagecopyresampled = false; 209 public $config_disable_onlycreateable_passthru = false; 210 public $config_disable_realpath = false; 211 212 public $config_http_user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7'; 213 214 // END CONFIGURATION OPTIONS 215 216 217 // public: error messages (read-only; persistant) 218 public $debugmessages = array(); 219 public $debugtiming = array(); 220 public $fatalerror = null; 221 222 223 // private: (should not be modified directly) 224 public $thumbnailQuality = 75; 225 public $thumbnailFormat = null; 226 227 public $sourceFilename = null; 228 public $rawImageData = null; 229 public $IMresizedData = null; 230 public $outputImageData = null; 231 232 public $useRawIMoutput = false; 233 234 public $gdimg_output = null; 235 public $gdimg_source = null; 236 237 public $getimagesizeinfo = null; 238 239 public $source_width = null; 240 public $source_height = null; 241 242 public $thumbnailCropX = null; 243 public $thumbnailCropY = null; 244 public $thumbnailCropW = null; 245 public $thumbnailCropH = null; 246 247 public $exif_thumbnail_width = null; 248 public $exif_thumbnail_height = null; 249 public $exif_thumbnail_type = null; 250 public $exif_thumbnail_data = null; 251 public $exif_raw_data = null; 252 253 public $thumbnail_width = null; 254 public $thumbnail_height = null; 255 public $thumbnail_image_width = null; 256 public $thumbnail_image_height = null; 257 258 public $tempFilesToDelete = array(); 259 public $cache_filename = null; 260 261 public $AlphaCapableFormats = array( 'png', 'ico', 'gif', 'webp', 'avif'); 262 public $is_alpha = false; 263 264 public $iswindows = null; 265 public $issafemode = null; 266 public $php_memory_limit = null; 267 268 public $phpthumb_version = '1.7.19-202210110924'; 269 270 ////////////////////////////////////////////////////////////////////// 271 272 // public: constructor 273 public function __construct() { 274 $this->phpThumb(); 275 } 276 277 public function phpThumb() { 278 $this->DebugTimingMessage('phpThumb() constructor', __FILE__, __LINE__); 279 $this->DebugMessage('phpThumb() v'.$this->phpthumb_version, __FILE__, __LINE__); 280 281 foreach (array(ini_get('memory_limit'), get_cfg_var('memory_limit')) as $php_config_memory_limit) { 282 if (!empty($php_config_memory_limit)) { 283 if (strtoupper($php_config_memory_limit[ strlen($php_config_memory_limit) - 1 ]) == 'G') { // PHP memory limit expressed in Gigabytes 284 $php_config_memory_limit = (int) substr($php_config_memory_limit, 0, -1) * 1073741824; 285 } elseif (strtoupper($php_config_memory_limit[ strlen($php_config_memory_limit) - 1 ]) == 'M') { // PHP memory limit expressed in Megabytes 286 $php_config_memory_limit = (int) substr($php_config_memory_limit, 0, -1) * 1048576; 287 } 288 $this->php_memory_limit = max($this->php_memory_limit, $php_config_memory_limit); 289 } 290 } 291 if ($this->php_memory_limit > 0) { // could be "-1" for "no limit" 292 $this->config_max_source_pixels = round($this->php_memory_limit * 0.20); // 20% of memory_limit 293 } 294 295 $this->iswindows = (bool) (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'); 296 $this->issafemode = (bool) preg_match('#(1|ON)#i', ini_get('safe_mode')); 297 $this->config_document_root = (!empty($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : $this->config_document_root); 298 $this->config_cache_prefix = ( isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'].'_' : ''); 299 300 $this->purgeTempFiles(); // purge existing temp files if re-initializing object 301 302 $php_sapi_name = strtolower(function_exists('php_sapi_name') ? PHP_SAPI : ''); 303 if ($php_sapi_name == 'cli') { 304 $this->config_allow_src_above_docroot = true; 305 } 306 307 if (!$this->config_disable_debug) { 308 // if debug mode is enabled, force phpThumbDebug output, do not allow normal thumbnails to be generated 309 $this->phpThumbDebug = (null === $this->phpThumbDebug ? 9 : max(1, (int) $this->phpThumbDebug)); 310 } 311 } 312 313 public function __destruct() { 314 $this->purgeTempFiles(); 315 } 316 317 // public: 318 public function purgeTempFiles() { 319 foreach ($this->tempFilesToDelete as $tempFileToDelete) { 320 if (file_exists($tempFileToDelete)) { 321 $this->DebugMessage('Deleting temp file "'.$tempFileToDelete.'"', __FILE__, __LINE__); 322 @unlink($tempFileToDelete); 323 } 324 } 325 $this->tempFilesToDelete = array(); 326 return true; 327 } 328 329 // public: 330 public function setSourceFilename($sourceFilename) { 331 //$this->resetObject(); 332 //$this->rawImageData = null; 333 $this->sourceFilename = $sourceFilename; 334 $this->src = $sourceFilename; 335 if (null === $this->config_output_format) { 336 $sourceFileExtension = strtolower(substr(strrchr($sourceFilename, '.'), 1)); 337 if (preg_match('#^[a-z]{3,4}$#', $sourceFileExtension)) { 338 $this->config_output_format = $sourceFileExtension; 339 $this->DebugMessage('setSourceFilename('.$sourceFilename.') set $this->config_output_format to "'.$sourceFileExtension.'"', __FILE__, __LINE__); 340 } else { 341 $this->DebugMessage('setSourceFilename('.$sourceFilename.') did NOT set $this->config_output_format to "'.$sourceFileExtension.'" because it did not seem like an appropriate image format', __FILE__, __LINE__); 342 } 343 } 344 $this->DebugMessage('setSourceFilename('.$sourceFilename.') set $this->sourceFilename to "'.$this->sourceFilename.'"', __FILE__, __LINE__); 345 return true; 346 } 347 348 // public: 349 public function setSourceData($rawImageData, $sourceFilename='') { 350 //$this->resetObject(); 351 //$this->sourceFilename = null; 352 $this->rawImageData = $rawImageData; 353 $this->DebugMessage('setSourceData() setting $this->rawImageData ('.strlen($this->rawImageData).' bytes; magic="'.substr($this->rawImageData, 0, 4).'" ('.phpthumb_functions::HexCharDisplay(substr($this->rawImageData, 0, 4)).'))', __FILE__, __LINE__); 354 if ($this->config_cache_source_enabled) { 355 $sourceFilename = ($sourceFilename ? $sourceFilename : md5($rawImageData)); 356 if (!is_dir($this->config_cache_source_directory)) { 357 $this->ErrorImage('$this->config_cache_source_directory ('.$this->config_cache_source_directory.') is not a directory'); 358 } elseif (!@is_writable($this->config_cache_source_directory)) { 359 $this->ErrorImage('$this->config_cache_source_directory ('.$this->config_cache_source_directory.') is not writable'); 360 } 361 $this->DebugMessage('setSourceData() attempting to save source image to "'.$this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename).'"', __FILE__, __LINE__); 362 if ($fp = @fopen($this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename), 'wb')) { 363 fwrite($fp, $rawImageData); 364 fclose($fp); 365 } elseif (!$this->phpThumbDebug) { 366 $this->ErrorImage('setSourceData() failed to write to source cache ('.$this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename).')'); 367 } 368 } 369 return true; 370 } 371 372 // public: 373 public function setSourceImageResource($gdimg) { 374 //$this->resetObject(); 375 $this->gdimg_source = $gdimg; 376 return true; 377 } 378 379 // public: 380 public function setParameter($param, $value) { 381 if ($param == 'src') { 382 $this->setSourceFilename($this->ResolveFilenameToAbsolute($value)); 383 } elseif (@is_array($this->$param)) { 384 if (is_array($value)) { 385 foreach ($value as $arraykey => $arrayvalue) { 386 array_push($this->$param, $arrayvalue); 387 } 388 } else { 389 array_push($this->$param, $value); 390 } 391 } else { 392 $this->$param = $value; 393 } 394 return true; 395 } 396 397 // public: 398 public function getParameter($param) { 399 //if (property_exists('phpThumb', $param)) { 400 return $this->$param; 401 //} 402 //$this->DebugMessage('setParameter() attempting to get non-existant parameter "'.$param.'"', __FILE__, __LINE__); 403 //return false; 404 } 405 406 407 // public: 408 public function GenerateThumbnail() { 409 410 $this->setOutputFormat(); 411 $this->phpThumbDebug('8a'); 412 $this->ResolveSource(); 413 $this->phpThumbDebug('8b'); 414 $this->SetCacheFilename(); 415 $this->phpThumbDebug('8c'); 416 $this->ExtractEXIFgetImageSize(); 417 $this->phpThumbDebug('8d'); 418 if ($this->useRawIMoutput) { 419 $this->DebugMessage('Skipping rest of GenerateThumbnail() because ($this->useRawIMoutput == true)', __FILE__, __LINE__); 420 return true; 421 } 422 $this->phpThumbDebug('8e'); 423 if (!$this->SourceImageToGD()) { 424 $this->DebugMessage('SourceImageToGD() failed', __FILE__, __LINE__); 425 return false; 426 } 427 $this->phpThumbDebug('8f'); 428 $this->ImageCropAuto(); 429 $this->phpThumbDebug('8h'); 430 $this->Rotate(); 431 $this->phpThumbDebug('8h'); 432 $this->CreateGDoutput(); 433 $this->phpThumbDebug('8i'); 434 435 // default values, also applicable for far="C" 436 $destination_offset_x = round(($this->thumbnail_width - $this->thumbnail_image_width) / 2); 437 $destination_offset_y = round(($this->thumbnail_height - $this->thumbnail_image_height) / 2); 438 if (($this->far == 'L') || ($this->far == 'TL') || ($this->far == 'BL')) { 439 $destination_offset_x = 0; 440 } 441 if (($this->far == 'R') || ($this->far == 'TR') || ($this->far == 'BR')) { 442 $destination_offset_x = round($this->thumbnail_width - $this->thumbnail_image_width); 443 } 444 if (($this->far == 'T') || ($this->far == 'TL') || ($this->far == 'TR')) { 445 $destination_offset_y = 0; 446 } 447 if (($this->far == 'B') || ($this->far == 'BL') || ($this->far == 'BR')) { 448 $destination_offset_y = round($this->thumbnail_height - $this->thumbnail_image_height); 449 } 450 451// // copy/resize image to appropriate dimensions 452// $borderThickness = 0; 453// if (!empty($this->fltr)) { 454// foreach ($this->fltr as $key => $value) { 455// if (preg_match('#^bord\|([0-9]+)#', $value, $matches)) { 456// $borderThickness = $matches[1]; 457// break; 458// } 459// } 460// } 461// if ($borderThickness > 0) { 462// //$this->DebugMessage('Skipping ImageResizeFunction() because BorderThickness="'.$borderThickness.'"', __FILE__, __LINE__); 463// $this->thumbnail_image_height /= 2; 464// } 465 $this->ImageResizeFunction( 466 $this->gdimg_output, 467 $this->gdimg_source, 468 $destination_offset_x, 469 $destination_offset_y, 470 $this->thumbnailCropX, 471 $this->thumbnailCropY, 472 $this->thumbnail_image_width, 473 $this->thumbnail_image_height, 474 $this->thumbnailCropW, 475 $this->thumbnailCropH 476 ); 477 478 $this->DebugMessage('memory_get_usage() after copy-resize = '.(function_exists('memory_get_usage') ? @memory_get_usage() : 'n/a'), __FILE__, __LINE__); 479 imagedestroy($this->gdimg_source); 480 $this->DebugMessage('memory_get_usage() after imagedestroy = '.(function_exists('memory_get_usage') ? @memory_get_usage() : 'n/a'), __FILE__, __LINE__); 481 482 $this->phpThumbDebug('8i'); 483 $this->AntiOffsiteLinking(); 484 $this->phpThumbDebug('8j'); 485 $this->ApplyFilters(); 486 $this->phpThumbDebug('8k'); 487 $this->AlphaChannelFlatten(); 488 $this->phpThumbDebug('8l'); 489 $this->MaxFileSize(); 490 $this->phpThumbDebug('8m'); 491 492 $this->DebugMessage('GenerateThumbnail() completed successfully', __FILE__, __LINE__); 493 return true; 494 } 495 496 497 // public: 498 public function RenderOutput() { 499 if (!$this->useRawIMoutput && !(is_resource($this->gdimg_output) || (is_object($this->gdimg_source) && $this->gdimg_source instanceOf \GdImage))) { 500 $this->DebugMessage('RenderOutput() failed because !is_resource($this->gdimg_output)', __FILE__, __LINE__); 501 return false; 502 } 503 if (!$this->thumbnailFormat) { 504 $this->DebugMessage('RenderOutput() failed because $this->thumbnailFormat is empty', __FILE__, __LINE__); 505 return false; 506 } 507 if ($this->useRawIMoutput) { 508 $this->DebugMessage('RenderOutput copying $this->IMresizedData ('.strlen($this->IMresizedData).' bytes) to $this->outputImage', __FILE__, __LINE__); 509 $this->outputImageData = $this->IMresizedData; 510 return true; 511 } 512 513 $builtin_formats = array(); 514 if (function_exists('imagetypes')) { 515 $imagetypes = imagetypes(); 516 $builtin_formats['wbmp'] = (bool) ($imagetypes & IMG_WBMP); 517 $builtin_formats['jpg'] = (bool) ($imagetypes & IMG_JPG); 518 $builtin_formats['gif'] = (bool) ($imagetypes & IMG_GIF); 519 $builtin_formats['png'] = (bool) ($imagetypes & IMG_PNG); 520 $builtin_formats['webp'] = (bool) ($imagetypes & IMG_WEBP); // PHP 7.0.10 521 $builtin_formats['bmp'] = (bool) ($imagetypes & IMG_BMP); // PHP 7.2.0 522 $builtin_formats['avif'] = (bool) ($imagetypes & IMG_AVIF); // PHP 8.1.0 523 } 524 525 $this->DebugMessage('imageinterlace($this->gdimg_output, '. (int) $this->config_output_interlace .')', __FILE__, __LINE__); 526 imageinterlace($this->gdimg_output, (int) $this->config_output_interlace); 527 528 $this->DebugMessage('RenderOutput() attempting image'.strtolower(@$this->thumbnailFormat).'($this->gdimg_output)', __FILE__, __LINE__); 529 ob_start(); 530 switch ($this->thumbnailFormat) { 531 case 'wbmp': 532 if (empty($builtin_formats['wbmp'])) { 533 $this->DebugMessage('GD does not have required built-in support for WBMP output', __FILE__, __LINE__); 534 ob_end_clean(); 535 return false; 536 } 537 imagewbmp($this->gdimg_output, null, $this->thumbnailQuality); 538 $this->outputImageData = ob_get_contents(); 539 break; 540 541 case 'jpeg': 542 case 'jpg': // should be "jpeg" not "jpg" but just in case... 543 if (empty($builtin_formats['jpg'])) { 544 $this->DebugMessage('GD does not have required built-in support for JPEG output', __FILE__, __LINE__); 545 ob_end_clean(); 546 return false; 547 } 548 imagejpeg($this->gdimg_output, null, $this->thumbnailQuality); 549 $this->outputImageData = ob_get_contents(); 550 break; 551 552 case 'png': 553 if (empty($builtin_formats['png'])) { 554 $this->DebugMessage('GD does not have required built-in support for PNG output', __FILE__, __LINE__); 555 ob_end_clean(); 556 return false; 557 } 558 if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.1.2', '>=')) { 559 // https://github.com/JamesHeinrich/phpThumb/issues/24 560 561 /* http://php.net/manual/en/function.imagepng.php: 562 from php source (gd.h): 563 2.0.12: Compression level: 0-9 or -1, where 0 is NO COMPRESSION at all, 564 :: 1 is FASTEST but produces larger files, 9 provides the best 565 :: compression (smallest files) but takes a long time to compress, and 566 :: -1 selects the default compiled into the zlib library. 567 Conclusion: Based on the Zlib manual (http://www.zlib.net/manual.html) the default compression level is set to 6. 568 */ 569 if (($this->thumbnailQuality >= -1) && ($this->thumbnailQuality <= 9)) { 570 $PNGquality = $this->thumbnailQuality; 571 } else { 572 $this->DebugMessage('Specified thumbnailQuality "'.$this->thumbnailQuality.'" is outside the accepted range (0-9, or -1). Using 6 as default value.', __FILE__, __LINE__); 573 $PNGquality = 6; 574 } 575 imagepng($this->gdimg_output, null, $PNGquality); 576 } else { 577 imagepng($this->gdimg_output); 578 } 579 $this->outputImageData = ob_get_contents(); 580 break; 581 582 case 'gif': 583 if (empty($builtin_formats['gif'])) { 584 $this->DebugMessage('GD does not have required built-in support for GIF output', __FILE__, __LINE__); 585 ob_end_clean(); 586 return false; 587 } 588 imagegif($this->gdimg_output); 589 $this->outputImageData = ob_get_contents(); 590 break; 591 592 case 'webp': 593 if (empty($builtin_formats['webp'])) { 594 $this->DebugMessage('GD does not have required built-in support for WebP output', __FILE__, __LINE__); 595 ob_end_clean(); 596 return false; 597 } 598 imagewebp($this->gdimg_output, null, $this->thumbnailQuality); 599 $this->outputImageData = ob_get_contents(); 600 break; 601 602 case 'avif': 603 if (empty($builtin_formats['avif'])) { 604 $this->DebugMessage('GD does not have required built-in support for AVIF output', __FILE__, __LINE__); 605 ob_end_clean(); 606 return false; 607 } 608 imageavif($this->gdimg_output, null, $this->thumbnailQuality); 609 $this->outputImageData = ob_get_contents(); 610 break; 611 612 case 'bmp': 613 if (!empty($builtin_formats['bmp'])) { 614 imagebmp($this->gdimg_output); 615 $this->outputImageData = ob_get_contents(); 616 break; 617 } 618 $this->DebugMessage('GD does not have required built-in support for BMP output', __FILE__, __LINE__); 619 if (!@include_once __DIR__ .'/phpthumb.bmp.php' ) { 620 $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.bmp.php" which is required for BMP format output', __FILE__, __LINE__); 621 ob_end_clean(); 622 return false; 623 } 624 $phpthumb_bmp = new phpthumb_bmp(); 625 $this->outputImageData = $phpthumb_bmp->GD2BMPstring($this->gdimg_output); 626 unset($phpthumb_bmp); 627 break; 628 629 case 'ico': 630 if (!@include_once __DIR__ .'/phpthumb.ico.php' ) { 631 $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.ico.php" which is required for ICO format output', __FILE__, __LINE__); 632 ob_end_clean(); 633 return false; 634 } 635 $phpthumb_ico = new phpthumb_ico(); 636 $arrayOfOutputImages = array($this->gdimg_output); 637 $this->outputImageData = $phpthumb_ico->GD2ICOstring($arrayOfOutputImages); 638 unset($phpthumb_ico); 639 break; 640 641 default: 642 $this->DebugMessage('RenderOutput failed because $this->thumbnailFormat "'.$this->thumbnailFormat.'" is not valid', __FILE__, __LINE__); 643 ob_end_clean(); 644 return false; 645 } 646 ob_end_clean(); 647 if (!$this->outputImageData) { 648 $this->DebugMessage('RenderOutput() for "'.$this->thumbnailFormat.'" failed', __FILE__, __LINE__); 649 ob_end_clean(); 650 return false; 651 } 652 $this->DebugMessage('RenderOutput() completing with $this->outputImageData = '.strlen($this->outputImageData).' bytes', __FILE__, __LINE__); 653 return true; 654 } 655 656 657 // public: 658 public function RenderToFile($filename) { 659 if (preg_match('#^[a-z0-9]+://#i', $filename)) { 660 $this->DebugMessage('RenderToFile() failed because $filename ('.$filename.') is a URL', __FILE__, __LINE__); 661 return false; 662 } 663 // render thumbnail to this file only, do not cache, do not output to browser 664 //$renderfilename = $this->ResolveFilenameToAbsolute(dirname($filename)).DIRECTORY_SEPARATOR.basename($filename); 665 $renderfilename = $filename; 666 if (($filename[0] != '/') && ($filename[0] != '\\') && ($filename[1] != ':')) { 667 $renderfilename = $this->ResolveFilenameToAbsolute($renderfilename); 668 } 669 if (!@is_writable(dirname($renderfilename))) { 670 $this->DebugMessage('RenderToFile() failed because "'.dirname($renderfilename).'/" is not writable', __FILE__, __LINE__); 671 return false; 672 } 673 if (@is_file($renderfilename) && !@is_writable($renderfilename)) { 674 $this->DebugMessage('RenderToFile() failed because "'.$renderfilename.'" is not writable', __FILE__, __LINE__); 675 return false; 676 } 677 678 if ($this->RenderOutput()) { 679 if (file_put_contents($renderfilename, $this->outputImageData)) { 680 @chmod($renderfilename, $this->getParameter('config_file_create_mask')); 681 $this->DebugMessage('RenderToFile('.$renderfilename.') succeeded', __FILE__, __LINE__); 682 return true; 683 } 684 if (!@file_exists($renderfilename)) { 685 $this->DebugMessage('RenderOutput ['.$this->thumbnailFormat.'('.$renderfilename.')] did not appear to fail, but the output image does not exist either...', __FILE__, __LINE__); 686 } 687 } else { 688 $this->DebugMessage('RenderOutput ['.$this->thumbnailFormat.'('.$renderfilename.')] failed', __FILE__, __LINE__); 689 } 690 return false; 691 } 692 693 694 // public: 695 public function OutputThumbnail() { 696 $this->purgeTempFiles(); 697 698 if (!$this->useRawIMoutput && !(is_resource($this->gdimg_output) || (is_object($this->gdimg_source) && $this->gdimg_source instanceOf \GdImage))) { 699 $this->DebugMessage('OutputThumbnail() failed because !is_resource($this->gdimg_output)', __FILE__, __LINE__); 700 return false; 701 } 702 if (headers_sent()) { 703 return $this->ErrorImage('OutputThumbnail() failed - headers already sent'); 704 } 705 706 $downloadfilename = phpthumb_functions::SanitizeFilename(is_string($this->sia) ? $this->sia : ($this->down ? $this->down : 'phpThumb_generated_thumbnail'.'.'.$this->thumbnailFormat)); 707 $this->DebugMessage('Content-Disposition header filename set to "'.$downloadfilename.'"', __FILE__, __LINE__); 708 if ($downloadfilename) { 709 header('Content-Disposition: '.($this->down ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"'); 710 } else { 711 $this->DebugMessage('failed to send Content-Disposition header because $downloadfilename is empty', __FILE__, __LINE__); 712 } 713 714 if ($this->useRawIMoutput) { 715 716 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat)); 717 echo $this->IMresizedData; 718 719 } else { 720 721 $this->DebugMessage('imageinterlace($this->gdimg_output, '. (int) $this->config_output_interlace .')', __FILE__, __LINE__); 722 imageinterlace($this->gdimg_output, (int) $this->config_output_interlace); 723 switch ($this->thumbnailFormat) { 724 case 'gif': 725 case 'jpeg': 726 case 'png': 727 case 'webp': 728 case 'avif': 729 $ImageOutFunction = 'image'.$this->thumbnailFormat; 730 if (!function_exists($ImageOutFunction)) { 731 $this->DebugMessage($ImageOutFunction.' is not available', __FILE__, __LINE__); 732 return false; 733 } 734 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat)); 735 if ($this->thumbnailFormat == 'gif') { 736 @$ImageOutFunction($this->gdimg_output); 737 } else { 738 @$ImageOutFunction($this->gdimg_output, null, $this->thumbnailQuality); 739 } 740 break; 741 742 case 'bmp': 743 if (function_exists('imagebmp')) { 744 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat)); 745 imagebmp($this->gdimg_output); 746 break; 747 } 748 if (!@include_once __DIR__ .'/phpthumb.bmp.php' ) { 749 $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.bmp.php" which is required for BMP format output', __FILE__, __LINE__); 750 return false; 751 } 752 $phpthumb_bmp = new phpthumb_bmp(); 753 if (is_object($phpthumb_bmp)) { 754 $bmp_data = $phpthumb_bmp->GD2BMPstring($this->gdimg_output); 755 unset($phpthumb_bmp); 756 if (!$bmp_data) { 757 $this->DebugMessage('$phpthumb_bmp->GD2BMPstring() failed', __FILE__, __LINE__); 758 return false; 759 } 760 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat)); 761 echo $bmp_data; 762 } else { 763 $this->DebugMessage('new phpthumb_bmp() failed', __FILE__, __LINE__); 764 return false; 765 } 766 break; 767 768 case 'ico': 769 if (!@include_once __DIR__ .'/phpthumb.ico.php' ) { 770 $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.ico.php" which is required for ICO format output', __FILE__, __LINE__); 771 return false; 772 } 773 $phpthumb_ico = new phpthumb_ico(); 774 if (is_object($phpthumb_ico)) { 775 $arrayOfOutputImages = array($this->gdimg_output); 776 $ico_data = $phpthumb_ico->GD2ICOstring($arrayOfOutputImages); 777 unset($phpthumb_ico); 778 if (!$ico_data) { 779 $this->DebugMessage('$phpthumb_ico->GD2ICOstring() failed', __FILE__, __LINE__); 780 return false; 781 } 782 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat)); 783 echo $ico_data; 784 } else { 785 $this->DebugMessage('new phpthumb_ico() failed', __FILE__, __LINE__); 786 return false; 787 } 788 break; 789 790 default: 791 $this->DebugMessage('OutputThumbnail failed because $this->thumbnailFormat "'.$this->thumbnailFormat.'" is not valid', __FILE__, __LINE__); 792 return false; 793 break; 794 } 795 796 } 797 return true; 798 } 799 800 801 // public: 802 public function CleanUpCacheDirectory() { 803 $this->DebugMessage('CleanUpCacheDirectory() set to purge ('.(null === $this->config_cache_maxage ? 'NULL' : number_format($this->config_cache_maxage / 86400, 1)).' days; '.(null === $this->config_cache_maxsize ? 'NULL' : number_format($this->config_cache_maxsize / 1048576, 2)).' MB; '.(null === $this->config_cache_maxfiles ? 'NULL' : number_format($this->config_cache_maxfiles)).' files)', __FILE__, __LINE__); 804 805 if (!is_writable($this->config_cache_directory)) { 806 $this->DebugMessage('CleanUpCacheDirectory() skipped because "'.$this->config_cache_directory.'" is not writable', __FILE__, __LINE__); 807 return true; 808 } 809 810 // cache status of cache directory for 1 hour to avoid hammering the filesystem functions 811 $phpThumbCacheStats_filename = $this->config_cache_directory.DIRECTORY_SEPARATOR.'phpThumbCacheStats.txt'; 812 if (file_exists($phpThumbCacheStats_filename) && is_readable($phpThumbCacheStats_filename) && (filemtime($phpThumbCacheStats_filename) >= (time() - 3600))) { 813 $this->DebugMessage('CleanUpCacheDirectory() skipped because "'.$phpThumbCacheStats_filename.'" is recently modified', __FILE__, __LINE__); 814 return true; 815 } 816 if (!@touch($phpThumbCacheStats_filename)) { 817 $this->DebugMessage('touch('.$phpThumbCacheStats_filename.') failed', __FILE__, __LINE__); 818 } 819 820 $DeletedKeys = array(); 821 $AllFilesInCacheDirectory = array(); 822 if (($this->config_cache_maxage > 0) || ($this->config_cache_maxsize > 0) || ($this->config_cache_maxfiles > 0)) { 823 $CacheDirOldFilesAge = array(); 824 $CacheDirOldFilesSize = array(); 825 $AllFilesInCacheDirectory = phpthumb_functions::GetAllFilesInSubfolders($this->config_cache_directory); 826 foreach ($AllFilesInCacheDirectory as $fullfilename) { 827 if (preg_match('#'.preg_quote($this->config_cache_prefix).'#i', $fullfilename) && file_exists($fullfilename)) { 828 $CacheDirOldFilesAge[$fullfilename] = @fileatime($fullfilename); 829 if ($CacheDirOldFilesAge[$fullfilename] == 0) { 830 $CacheDirOldFilesAge[$fullfilename] = @filemtime($fullfilename); 831 } 832 $CacheDirOldFilesSize[$fullfilename] = @filesize($fullfilename); 833 } 834 } 835 if (empty($CacheDirOldFilesSize)) { 836 $this->DebugMessage('CleanUpCacheDirectory() skipped because $CacheDirOldFilesSize is empty (phpthumb_functions::GetAllFilesInSubfolders('.$this->config_cache_directory.') found no files)', __FILE__, __LINE__); 837 return true; 838 } 839 $DeletedKeys['zerobyte'] = array(); 840 foreach ($CacheDirOldFilesSize as $fullfilename => $filesize) { 841 // purge all zero-size files more than an hour old (to prevent trying to delete just-created and/or in-use files) 842 $cutofftime = time() - 3600; 843 if (($filesize == 0) && ($CacheDirOldFilesAge[$fullfilename] < $cutofftime)) { 844 $this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__); 845 if (@unlink($fullfilename)) { 846 $DeletedKeys['zerobyte'][] = $fullfilename; 847 unset($CacheDirOldFilesSize[$fullfilename]); 848 unset($CacheDirOldFilesAge[$fullfilename]); 849 } 850 } 851 } 852 $this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['zerobyte']).' zero-byte files', __FILE__, __LINE__); 853 asort($CacheDirOldFilesAge); 854 855 if ($this->config_cache_maxfiles > 0) { 856 $TotalCachedFiles = count($CacheDirOldFilesAge); 857 $DeletedKeys['maxfiles'] = array(); 858 foreach ($CacheDirOldFilesAge as $fullfilename => $filedate) { 859 if ($TotalCachedFiles > $this->config_cache_maxfiles) { 860 $this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__); 861 if (@unlink($fullfilename)) { 862 $TotalCachedFiles--; 863 $DeletedKeys['maxfiles'][] = $fullfilename; 864 } 865 } else { 866 // there are few enough files to keep the rest 867 break; 868 } 869 } 870 $this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['maxfiles']).' files based on (config_cache_maxfiles='.$this->config_cache_maxfiles.')', __FILE__, __LINE__); 871 foreach ($DeletedKeys['maxfiles'] as $fullfilename) { 872 unset($CacheDirOldFilesAge[$fullfilename]); 873 unset($CacheDirOldFilesSize[$fullfilename]); 874 } 875 } 876 877 if ($this->config_cache_maxage > 0) { 878 $mindate = time() - $this->config_cache_maxage; 879 $DeletedKeys['maxage'] = array(); 880 foreach ($CacheDirOldFilesAge as $fullfilename => $filedate) { 881 if ($filedate > 0) { 882 if ($filedate < $mindate) { 883 $this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__); 884 if (@unlink($fullfilename)) { 885 $DeletedKeys['maxage'][] = $fullfilename; 886 } 887 } else { 888 // the rest of the files are new enough to keep 889 break; 890 } 891 } 892 } 893 $this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['maxage']).' files based on (config_cache_maxage='.$this->config_cache_maxage.')', __FILE__, __LINE__); 894 foreach ($DeletedKeys['maxage'] as $fullfilename) { 895 unset($CacheDirOldFilesAge[$fullfilename]); 896 unset($CacheDirOldFilesSize[$fullfilename]); 897 } 898 } 899 900 if ($this->config_cache_maxsize > 0) { 901 $TotalCachedFileSize = array_sum($CacheDirOldFilesSize); 902 $DeletedKeys['maxsize'] = array(); 903 foreach ($CacheDirOldFilesAge as $fullfilename => $filedate) { 904 if ($TotalCachedFileSize > $this->config_cache_maxsize) { 905 $this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__); 906 if (@unlink($fullfilename)) { 907 $TotalCachedFileSize -= $CacheDirOldFilesSize[$fullfilename]; 908 $DeletedKeys['maxsize'][] = $fullfilename; 909 } 910 } else { 911 // the total filesizes are small enough to keep the rest of the files 912 break; 913 } 914 } 915 $this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['maxsize']).' files based on (config_cache_maxsize='.$this->config_cache_maxsize.')', __FILE__, __LINE__); 916 foreach ($DeletedKeys['maxsize'] as $fullfilename) { 917 unset($CacheDirOldFilesAge[$fullfilename]); 918 unset($CacheDirOldFilesSize[$fullfilename]); 919 } 920 } 921 922 } else { 923 $this->DebugMessage('skipping CleanUpCacheDirectory() because config set to not use it', __FILE__, __LINE__); 924 } 925 $totalpurged = 0; 926 foreach ($DeletedKeys as $key => $value) { 927 $totalpurged += count($value); 928 } 929 $this->DebugMessage('CleanUpCacheDirectory() purged '.$totalpurged.' files (from '.count($AllFilesInCacheDirectory).') based on config settings', __FILE__, __LINE__); 930 if ($totalpurged > 0) { 931 $empty_dirs = array(); 932 foreach ($AllFilesInCacheDirectory as $fullfilename) { 933 if (is_dir($fullfilename)) { 934 $empty_dirs[$this->realPathSafe($fullfilename)] = 1; 935 } else { 936 unset($empty_dirs[$this->realPathSafe(dirname($fullfilename))]); 937 } 938 } 939 krsort($empty_dirs); 940 $totalpurgeddirs = 0; 941 foreach ($empty_dirs as $empty_dir => $dummy) { 942 if ($empty_dir == $this->config_cache_directory) { 943 // shouldn't happen, but just in case, don't let it delete actual cache directory 944 continue; 945 } elseif (@rmdir($empty_dir)) { 946 $totalpurgeddirs++; 947 } else { 948 $this->DebugMessage('failed to rmdir('.$empty_dir.')', __FILE__, __LINE__); 949 } 950 } 951 $this->DebugMessage('purged '.$totalpurgeddirs.' empty directories', __FILE__, __LINE__); 952 } 953 return true; 954 } 955 956 ////////////////////////////////////////////////////////////////////// 957 958 // private: re-initializator (call between rendering multiple images with one object) 959 public function resetObject() { 960 $class_vars = get_class_vars(get_class($this)); 961 foreach ($class_vars as $key => $value) { 962 // do not clobber debug or config info 963 if (!preg_match('#^(config_|debug|fatalerror)#i', $key)) { 964 $this->$key = $value; 965 } 966 } 967 $this->phpThumb(); // re-initialize some class variables 968 return true; 969 } 970 971 ////////////////////////////////////////////////////////////////////// 972 973 public function ResolveSource() { 974 if (is_resource($this->gdimg_source) || (is_object($this->gdimg_source) && $this->gdimg_source instanceOf \GdImage)) { 975 $this->DebugMessage('ResolveSource() exiting because is_resource($this->gdimg_source)', __FILE__, __LINE__); 976 return true; 977 } 978 if ($this->rawImageData) { 979 $this->sourceFilename = null; 980 $this->DebugMessage('ResolveSource() exiting because $this->rawImageData is set ('.number_format(strlen($this->rawImageData)).' bytes)', __FILE__, __LINE__); 981 return true; 982 } 983 if ($this->sourceFilename) { 984 $this->sourceFilename = $this->ResolveFilenameToAbsolute($this->sourceFilename); 985 $this->DebugMessage('$this->sourceFilename set to "'.$this->sourceFilename.'"', __FILE__, __LINE__); 986 } elseif ($this->src) { 987 $this->sourceFilename = $this->ResolveFilenameToAbsolute($this->src); 988 $this->DebugMessage('$this->sourceFilename set to "'.$this->sourceFilename.'" from $this->src ('.$this->src.')', __FILE__, __LINE__); 989 } else { 990 return $this->ErrorImage('$this->sourceFilename and $this->src are both empty'); 991 } 992 if ($this->iswindows && ((substr($this->sourceFilename, 0, 2) == '//') || (substr($this->sourceFilename, 0, 2) == '\\\\'))) { 993 // Windows \\share\filename.ext 994 } elseif (preg_match('#^[a-z0-9]+://#i', $this->sourceFilename, $protocol_matches)) { 995 if (preg_match('#^(f|ht)tps?\://#i', $this->sourceFilename)) { 996 // URL 997 if ($this->config_http_user_agent) { 998 ini_set('user_agent', $this->config_http_user_agent); 999 } 1000 } else { 1001 return $this->ErrorImage('only FTP and HTTP/HTTPS protocols are allowed, "'.$protocol_matches[1].'" is not'); 1002 } 1003 } elseif (!@file_exists($this->sourceFilename)) { 1004 return $this->ErrorImage('"'.$this->sourceFilename.'" does not exist'); 1005 } elseif (!@is_file($this->sourceFilename)) { 1006 return $this->ErrorImage('"'.$this->sourceFilename.'" is not a file'); 1007 } 1008 return true; 1009 } 1010 1011 1012 public function setOutputFormat() { 1013 static $alreadyCalled = false; 1014 if ($this->thumbnailFormat && $alreadyCalled) { 1015 return true; 1016 } 1017 $alreadyCalled = true; 1018 1019 $AvailableImageOutputFormats = array(); 1020 $AvailableImageOutputFormats[] = 'text'; 1021 if (@is_readable( __DIR__ .'/phpthumb.ico.php')) { 1022 $AvailableImageOutputFormats[] = 'ico'; 1023 } 1024 if (@is_readable( __DIR__ .'/phpthumb.bmp.php')) { 1025 $AvailableImageOutputFormats[] = 'bmp'; 1026 } 1027 1028 $this->thumbnailFormat = 'ico'; 1029 1030 // Set default output format based on what image types are available 1031 if (function_exists('imagetypes')) { 1032 $imagetypes = imagetypes(); 1033 if ($imagetypes & IMG_WBMP) { 1034 $this->thumbnailFormat = 'wbmp'; 1035 $AvailableImageOutputFormats[] = 'wbmp'; 1036 } 1037 if ($imagetypes & IMG_GIF) { 1038 $this->thumbnailFormat = 'gif'; 1039 $AvailableImageOutputFormats[] = 'gif'; 1040 } 1041 if ($imagetypes & IMG_AVIF) { 1042 $this->thumbnailFormat = 'avif'; 1043 $AvailableImageOutputFormats[] = 'avif'; 1044 } 1045 if ($imagetypes & IMG_WEBP) { 1046 $this->thumbnailFormat = 'webp'; 1047 $AvailableImageOutputFormats[] = 'webp'; 1048 } 1049 if ($imagetypes & IMG_PNG) { 1050 $this->thumbnailFormat = 'png'; 1051 $AvailableImageOutputFormats[] = 'png'; 1052 } 1053 if ($imagetypes & IMG_JPG) { 1054 $this->thumbnailFormat = 'jpeg'; 1055 $AvailableImageOutputFormats[] = 'jpeg'; 1056 } 1057 } else { 1058 $this->DebugMessage('imagetypes() does not exist - GD support might not be enabled?', __FILE__, __LINE__); 1059 } 1060 if ($this->ImageMagickVersion()) { 1061 $IMformats = array('jpeg', 'png', 'gif', 'bmp', 'ico', 'wbmp', 'webp', 'avif'); 1062 $this->DebugMessage('Addding ImageMagick formats to $AvailableImageOutputFormats ('.implode(';', $AvailableImageOutputFormats).')', __FILE__, __LINE__); 1063 foreach ($IMformats as $key => $format) { 1064 $AvailableImageOutputFormats[] = $format; 1065 } 1066 } 1067 $AvailableImageOutputFormats = array_unique($AvailableImageOutputFormats); 1068 $this->DebugMessage('$AvailableImageOutputFormats = array('.implode(';', $AvailableImageOutputFormats).')', __FILE__, __LINE__); 1069 1070 $this->f = (!empty($this->f) ? $this->f : ''); 1071 $this->f = preg_replace('#[^a-z]#', '', strtolower($this->f)); 1072 if (strtolower($this->config_output_format) == 'jpg') { 1073 $this->config_output_format = 'jpeg'; 1074 } 1075 if (strtolower($this->f) == 'jpg') { 1076 $this->f = 'jpeg'; 1077 } 1078 if (phpthumb_functions::CaseInsensitiveInArray($this->config_output_format, $AvailableImageOutputFormats)) { 1079 // set output format to config default if that format is available 1080 $this->DebugMessage('$this->thumbnailFormat set to $this->config_output_format "'.strtolower($this->config_output_format).'"', __FILE__, __LINE__); 1081 $this->thumbnailFormat = strtolower($this->config_output_format); 1082 } elseif ($this->config_output_format) { 1083 $this->DebugMessage('$this->thumbnailFormat staying as "'.$this->thumbnailFormat.'" because $this->config_output_format ('.strtolower($this->config_output_format).') is not in $AvailableImageOutputFormats', __FILE__, __LINE__); 1084 } 1085 if ($this->f && phpthumb_functions::CaseInsensitiveInArray($this->f, $AvailableImageOutputFormats) ) { 1086 // override output format if $this->f is set and that format is available 1087 $this->DebugMessage('$this->thumbnailFormat set to $this->f "'.strtolower($this->f).'"', __FILE__, __LINE__); 1088 $this->thumbnailFormat = strtolower($this->f); 1089 } elseif ($this->f) { 1090 $this->DebugMessage('$this->thumbnailFormat staying as "'.$this->thumbnailFormat.'" because $this->f ('.strtolower($this->f).') is not in $AvailableImageOutputFormats', __FILE__, __LINE__); 1091 } 1092 1093 // for JPEG images, quality 1 (worst) to 99 (best) 1094 // quality < 25 is nasty, with not much size savings - not recommended 1095 // problems with 100 - invalid JPEG? 1096 $this->thumbnailQuality = max(1, min(99, ($this->q ? (int) $this->q : 75))); 1097 $this->DebugMessage('$this->thumbnailQuality set to "'.$this->thumbnailQuality.'"', __FILE__, __LINE__); 1098 1099 return true; 1100 } 1101 1102 1103 public function setCacheDirectory() { 1104 // resolve cache directory to absolute pathname 1105 $this->DebugMessage('setCacheDirectory() starting with config_cache_directory = "'.$this->config_cache_directory.'"', __FILE__, __LINE__); 1106 if ($this->config_cache_directory && ($this->config_cache_directory[0] == '.')) { 1107 if (preg_match('#^(f|ht)tps?\://#i', $this->src)) { 1108 if (!$this->config_cache_disable_warning) { 1109 $this->ErrorImage('$this->config_cache_directory ('.$this->config_cache_directory.') cannot be used for remote images. Adjust "cache_directory" or "cache_disable_warning" in phpThumb.config.php'); 1110 } 1111 } elseif ($this->src) { 1112 // resolve relative cache directory to source image 1113 $this->config_cache_directory = dirname($this->ResolveFilenameToAbsolute($this->src)).DIRECTORY_SEPARATOR.$this->config_cache_directory; 1114 } else { 1115 // $this->new is probably set 1116 } 1117 } 1118 if (substr($this->config_cache_directory, -1) == '/') { 1119 $this->config_cache_directory = substr($this->config_cache_directory, 0, -1); 1120 } 1121 if ($this->iswindows) { 1122 $this->config_cache_directory = str_replace('/', DIRECTORY_SEPARATOR, $this->config_cache_directory); 1123 } 1124 if ($this->config_cache_directory) { 1125 $real_cache_path = $this->realPathSafe($this->config_cache_directory); 1126 if (!$real_cache_path) { 1127 $this->DebugMessage('$this->realPathSafe($this->config_cache_directory) failed for "'.$this->config_cache_directory.'"', __FILE__, __LINE__); 1128 if (!is_dir($this->config_cache_directory)) { 1129 $this->DebugMessage('!is_dir('.$this->config_cache_directory.')', __FILE__, __LINE__); 1130 } 1131 } 1132 if ($real_cache_path) { 1133 $this->DebugMessage('setting config_cache_directory to $this->realPathSafe('.$this->config_cache_directory.') = "'.$real_cache_path.'"', __FILE__, __LINE__); 1134 $this->config_cache_directory = $real_cache_path; 1135 } 1136 } 1137 if (!is_dir($this->config_cache_directory)) { 1138 if (!$this->config_cache_disable_warning) { 1139 $this->ErrorImage('$this->config_cache_directory ('.$this->config_cache_directory.') does not exist. Adjust "cache_directory" or "cache_disable_warning" in phpThumb.config.php'); 1140 } 1141 $this->DebugMessage('$this->config_cache_directory ('.$this->config_cache_directory.') is not a directory', __FILE__, __LINE__); 1142 $this->config_cache_directory = null; 1143 } elseif (!@is_writable($this->config_cache_directory)) { 1144 $this->DebugMessage('$this->config_cache_directory is not writable ('.$this->config_cache_directory.')', __FILE__, __LINE__); 1145 } 1146 1147 $this->InitializeTempDirSetting(); 1148 if (!@is_dir($this->config_temp_directory) && !@is_writable($this->config_temp_directory) && @is_dir($this->config_cache_directory) && @is_writable($this->config_cache_directory)) { 1149 $this->DebugMessage('setting $this->config_temp_directory = $this->config_cache_directory ('.$this->config_cache_directory.')', __FILE__, __LINE__); 1150 $this->config_temp_directory = $this->config_cache_directory; 1151 } 1152 return true; 1153 } 1154 1155 /* Takes the array of path segments up to now, and the next segment (maybe a modifier: empty, . or ..) 1156 Applies it, adding or removing from $segments as a result. Returns nothing. */ 1157 // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961 1158 public function applyPathSegment(&$segments, $segment) { 1159 if ($segment == '.') { 1160 return; // always remove 1161 } 1162 if ($segment == '') { 1163 $test = array_pop($segments); 1164 if (null === $test) { 1165 $segments[] = $segment; // keep the first empty block 1166 } elseif ($test == '') { 1167 $test = array_pop($segments); 1168 if (null === $test) { 1169 $segments[] = $test; 1170 $segments[] = $segment; // keep the second one too 1171 } else { // put both back and ignore segment 1172 $segments[] = $test; 1173 $segments[] = $test; 1174 } 1175 } else { 1176 $segments[] = $test; // ignore empty blocks 1177 } 1178 } else { 1179 if ($segment == '..') { 1180 $test = array_pop($segments); 1181 if (null === $test) { 1182 $segments[] = $segment; 1183 } elseif ($test == '..') { 1184 $segments[] = $test; 1185 $segments[] = $segment; 1186 } else { 1187 if ($test == '') { 1188 $segments[] = $test; 1189 } // else nothing, remove both 1190 } 1191 } else { 1192 $segments[] = $segment; 1193 } 1194 } 1195 } 1196 1197 /* Takes array of path components, normalizes it: removes empty slots and '.', collapses '..' and folder names. Returns array. */ 1198 // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961 1199 public function normalizePath($segments) { 1200 $parts = array(); 1201 foreach ($segments as $segment) { 1202 $this->applyPathSegment($parts, $segment); 1203 } 1204 return $parts; 1205 } 1206 1207 /* True if the provided path points (without resolving symbolic links) into one of the allowed directories. */ 1208 // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961 1209 public function matchPath($path, $allowed_dirs) { 1210 if (!empty($allowed_dirs)) { 1211 foreach ($allowed_dirs as $one_dir) { 1212 if (preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', $this->realPathSafe($one_dir))).'#', $path)) { 1213 return true; 1214 } 1215 } 1216 } 1217 return false; 1218 } 1219 1220 /* True if the provided path points inside one of open_basedirs (or if open_basedirs are disabled) */ 1221 // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961 1222 public function isInOpenBasedir($path) { 1223 static $open_basedirs = null; 1224 if (null === $open_basedirs) { 1225 $ini_text = ini_get('open_basedir'); 1226 $this->DebugMessage('open_basedir: "'.$ini_text.'"', __FILE__, __LINE__); 1227 $open_basedirs = array(); 1228 if (strlen($ini_text) > 0) { 1229 foreach (preg_split('#[;:]#', $ini_text) as $key => $value) { 1230 $open_basedirs[$key] = $this->realPathSafe($value); 1231 } 1232 } 1233 } 1234 return (empty($open_basedirs) || $this->matchPath($path, $open_basedirs)); 1235 } 1236 1237 /* Resolves all symlinks in $path, checking that each continuous part ends in an allowed zone. Returns null, if any component leads outside of allowed zone. */ 1238 // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961 1239 public function resolvePath($path, $allowed_dirs) { 1240 $this->DebugMessage('resolvePath: '.$path.' (allowed_dirs: '.print_r($allowed_dirs, true).')', __FILE__, __LINE__); 1241 1242 // add base path to the top of the list 1243 if (!$this->config_allow_src_above_docroot) { 1244 array_unshift($allowed_dirs, $this->realPathSafe($this->config_document_root)); 1245 } else { 1246 if (!$this->config_allow_src_above_phpthumb) { 1247 array_unshift($allowed_dirs, $this->realPathSafe( __DIR__ )); 1248 } else { 1249 // no checks are needed, offload the work to realpath and forget about it 1250 $this->DebugMessage('resolvePath: checks disabled, returning '.$this->realPathSafe($path), __FILE__, __LINE__); 1251 return $this->realPathSafe($path); 1252 } 1253 } 1254 if ($path == '') { 1255 return null; // save us trouble 1256 } 1257 1258 do { 1259 $this->DebugMessage('resolvePath: iteration, path='.$path.', base path = '.$allowed_dirs[0], __FILE__, __LINE__); 1260 1261 $parts = array(); 1262 // do not use "cleaner" foreach version of this loop as later code relies on both $segments and $i 1263 // http://support.silisoftware.com/phpBB3/viewtopic.php?t=964 1264 $segments = explode(DIRECTORY_SEPARATOR, $path); 1265 for ($i = 0, $iMax = count($segments); $i < $iMax; $i++) { 1266 $this->applyPathSegment($parts, $segments[$i]); 1267 $thispart = implode(DIRECTORY_SEPARATOR, $parts); 1268 if ($this->isInOpenBasedir($thispart)) { 1269 if (is_link($thispart)) { 1270 break; 1271 } 1272 } 1273 } 1274 1275 $this->DebugMessage('resolvePath: stop at component '.$i, __FILE__, __LINE__); 1276 // test the part up to here 1277 $path = implode(DIRECTORY_SEPARATOR, $parts); 1278 $this->DebugMessage('resolvePath: stop at path='.$path, __FILE__, __LINE__); 1279 if (!$this->matchPath($path, $allowed_dirs)) { 1280 $this->DebugMessage('resolvePath: no match, returning null', __FILE__, __LINE__); 1281 return null; 1282 } 1283 if ($i >= count($segments)) { // reached end 1284 $this->DebugMessage('resolvePath: path parsed, over', __FILE__, __LINE__); 1285 break; 1286 } 1287 // else it's symlink, rewrite path 1288 $path = readlink($path); 1289 $this->DebugMessage('resolvePath: symlink matched, target='.$path, __FILE__, __LINE__); 1290 1291 /* 1292 Replace base path with symlink target. 1293 Assuming: 1294 /www/img/external -> /external 1295 This is allowed: 1296 GET /www/img/external/../external/test/pic.jpg 1297 This isn't: 1298 GET /www/img/external/../www/img/pic.jpg 1299 So there's only one base path which is the last symlink target, but any number of stable whitelisted paths. 1300 */ 1301 if ($this->config_auto_allow_symlinks) { 1302 $allowed_dirs[0] = $path; 1303 } 1304 $path = $path.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, array_slice($segments,$i + 1)); 1305 } while (true); 1306 return $path; 1307 } 1308 1309 1310 public function realPathSafe($filename) { 1311 // http://php.net/manual/en/function.realpath.php -- "Note: The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE" 1312 // realPathSafe() provides a reasonable facsimile of realpath() but does not resolve symbolic links, nor does it check that the file/path actually exists 1313 if (!$this->config_disable_realpath) { 1314 return realpath($filename); 1315 } 1316 1317 // http://stackoverflow.com/questions/21421569 1318 $newfilename = preg_replace('#[\\/]+#', DIRECTORY_SEPARATOR, $filename); 1319 1320 if (phpthumb_functions::is_windows()) { 1321 $isAlreadyAbsoluteFilename = preg_match('#^[A-Z]\\:#i', $newfilename); // C:\path\filename.ext 1322 } else { 1323 $isAlreadyAbsoluteFilename = ($newfilename[0] == DIRECTORY_SEPARATOR); // /path/filename.ext 1324 } 1325 if (!$isAlreadyAbsoluteFilename) { 1326 // not already an absolute filename, prepend current directory 1327 $newfilename = __DIR__ .DIRECTORY_SEPARATOR.$newfilename; 1328 } 1329 do { 1330 $beforeloop = $newfilename; 1331 1332 // Replace all sequences of more than one / with a single one [[ If you're working on a system that treats // at the start of a path as special, make sure you replace multiple / characters at the start with two of them. This is the only place where POSIX allows (but does not mandate) special handling for multiples, in all other cases, multiple / characters are equivalent to a single one.]] 1333 $newfilename = preg_replace('#'.preg_quote(DIRECTORY_SEPARATOR).'+#', DIRECTORY_SEPARATOR, $newfilename); 1334 1335 // Replace all occurrences of /./ with / 1336 $newfilename = preg_replace('#'.preg_quote(DIRECTORY_SEPARATOR).'\\.'.preg_quote(DIRECTORY_SEPARATOR).'#', DIRECTORY_SEPARATOR, $newfilename); 1337 1338 // Remove ./ if at the start 1339 $newfilename = preg_replace('#^\\.'.preg_quote(DIRECTORY_SEPARATOR).'#', '', $newfilename); 1340 1341 // Remove /. if at the end 1342 $newfilename = preg_replace('#'.preg_quote(DIRECTORY_SEPARATOR).'\\.$#', '', $newfilename); 1343 1344 // Replace /anything/../ with / 1345 $newfilename = preg_replace('#'.preg_quote(DIRECTORY_SEPARATOR).'[^'.preg_quote(DIRECTORY_SEPARATOR).']+'.preg_quote(DIRECTORY_SEPARATOR).'\\.\\.'.preg_quote(DIRECTORY_SEPARATOR).'#', DIRECTORY_SEPARATOR, $newfilename); 1346 1347 // Remove /anything/.. if at the end 1348 $newfilename = preg_replace('#'.preg_quote(DIRECTORY_SEPARATOR).'[^'.preg_quote(DIRECTORY_SEPARATOR).']+'.preg_quote(DIRECTORY_SEPARATOR).'\\.\\.$#', '', $newfilename); 1349 1350 } while ($newfilename != $beforeloop); 1351 return $newfilename; 1352 } 1353 1354 1355 public function ResolveFilenameToAbsolute($filename) { 1356 if (empty($filename)) { 1357 return false; 1358 } 1359 1360 if (preg_match('#^[a-z0-9]+\\:/{1,2}#i', $filename)) { 1361 // eg: http://host/path/file.jpg (HTTP URL) 1362 // eg: ftp://host/path/file.jpg (FTP URL) 1363 // eg: data1:/path/file.jpg (Netware path) 1364 1365 //$AbsoluteFilename = $filename; 1366 return $filename; 1367 1368 } elseif ($this->iswindows && isset($filename[1]) && ($filename[1] == ':')) { 1369 1370 // absolute pathname (Windows) 1371 $AbsoluteFilename = $filename; 1372 1373 } elseif ($this->iswindows && ((substr($filename, 0, 2) == '//') || (substr($filename, 0, 2) == '\\\\'))) { 1374 1375 // absolute pathname (Windows) 1376 $AbsoluteFilename = $filename; 1377 1378 } elseif ($filename[0] == '/') { 1379 1380 if (@is_readable($filename) && !@is_readable($this->config_document_root.$filename)) { 1381 1382 // absolute filename (*nix) 1383 $AbsoluteFilename = $filename; 1384 1385 } elseif (isset($filename[1]) && ($filename[1] == '~')) { 1386 1387 // /~user/path 1388 if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray($filename)) { 1389 $AbsoluteFilename = $ApacheLookupURIarray['filename']; 1390 } else { 1391 $AbsoluteFilename = $this->realPathSafe($filename); 1392 if (@is_readable($AbsoluteFilename)) { 1393 $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for "'.$filename.'", but the correct filename ('.$AbsoluteFilename.') seems to have been resolved with $this->realPathSafe($filename)', __FILE__, __LINE__); 1394 } elseif (is_dir(dirname($AbsoluteFilename))) { 1395 $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for "'.dirname($filename).'", but the correct directory ('.dirname($AbsoluteFilename).') seems to have been resolved with $this->realPathSafe(.)', __FILE__, __LINE__); 1396 } else { 1397 return $this->ErrorImage('phpthumb_functions::ApacheLookupURIarray() failed for "'.$filename.'". This has been known to fail on Apache2 - try using the absolute filename for the source image (ex: "/home/user/httpdocs/image.jpg" instead of "/~user/image.jpg")'); 1398 } 1399 } 1400 1401 } else { 1402 1403 // relative filename (any OS) 1404 if (preg_match('#^'.preg_quote($this->config_document_root).'#', $filename)) { 1405 $AbsoluteFilename = $filename; 1406 $this->DebugMessage('ResolveFilenameToAbsolute() NOT prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = "'.$AbsoluteFilename.'")', __FILE__, __LINE__); 1407 } else { 1408 $AbsoluteFilename = $this->config_document_root.$filename; 1409 $this->DebugMessage('ResolveFilenameToAbsolute() prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = "'.$AbsoluteFilename.'")', __FILE__, __LINE__); 1410 } 1411 1412 } 1413 1414 } else { 1415 1416 // relative to current directory (any OS) 1417 $AbsoluteFilename = __DIR__ .DIRECTORY_SEPARATOR.preg_replace('#[/\\\\]#', DIRECTORY_SEPARATOR, $filename); 1418 1419 if (substr(dirname(@$_SERVER['PHP_SELF']), 0, 2) == '/~') { 1420 if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray(dirname(@$_SERVER['PHP_SELF']))) { 1421 $AbsoluteFilename = $ApacheLookupURIarray['filename'].DIRECTORY_SEPARATOR.$filename; 1422 } else { 1423 $AbsoluteFilename = $this->realPathSafe('.').DIRECTORY_SEPARATOR.$filename; 1424 if (@is_readable($AbsoluteFilename)) { 1425 $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for "'.dirname(@$_SERVER['PHP_SELF']).'", but the correct filename ('.$AbsoluteFilename.') seems to have been resolved with $this->realPathSafe(.)/$filename', __FILE__, __LINE__); 1426 } elseif (is_dir(dirname($AbsoluteFilename))) { 1427 $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for "'.dirname(@$_SERVER['PHP_SELF']).'", but the correct directory ('.dirname($AbsoluteFilename).') seems to have been resolved with $this->realPathSafe(.)', __FILE__, __LINE__); 1428 } else { 1429 return $this->ErrorImage('phpthumb_functions::ApacheLookupURIarray() failed for "'.dirname(@$_SERVER['PHP_SELF']).'". This has been known to fail on Apache2 - try using the absolute filename for the source image'); 1430 } 1431 } 1432 } 1433 1434 } 1435 /* 1436 // removed 2014-May-30: http://support.silisoftware.com/phpBB3/viewtopic.php?t=961 1437 if (is_link($AbsoluteFilename)) { 1438 $this->DebugMessage('is_link()==true, changing "'.$AbsoluteFilename.'" to "'.readlink($AbsoluteFilename).'"', __FILE__, __LINE__); 1439 $AbsoluteFilename = readlink($AbsoluteFilename); 1440 } 1441 if ($this->realPathSafe($AbsoluteFilename)) { 1442 $AbsoluteFilename = $this->realPathSafe($AbsoluteFilename); 1443 } 1444 */ 1445 if ($this->iswindows) { 1446 $AbsoluteFilename = preg_replace('#^'.preg_quote($this->realPathSafe($this->config_document_root)).'#i', str_replace('\\', '\\\\', $this->realPathSafe($this->config_document_root)), $AbsoluteFilename); 1447 $AbsoluteFilename = str_replace(DIRECTORY_SEPARATOR, '/', $AbsoluteFilename); 1448 } 1449 $resolvedAbsoluteFilename = $this->resolvePath($AbsoluteFilename, $this->config_additional_allowed_dirs); 1450 if (!$this->config_allow_src_above_docroot && !preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', $this->realPathSafe($this->config_document_root))).'#', $resolvedAbsoluteFilename)) { 1451 $this->DebugMessage('!$this->config_allow_src_above_docroot therefore setting "'.$AbsoluteFilename.'" (outside "'.$this->realPathSafe($this->config_document_root).'") to null', __FILE__, __LINE__); 1452 return false; 1453 } 1454 if (!$this->config_allow_src_above_phpthumb && !preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', __DIR__ )).'#', $resolvedAbsoluteFilename)) { 1455 $this->DebugMessage('!$this->config_allow_src_above_phpthumb therefore setting "'.$AbsoluteFilename.'" (outside "'. __DIR__ .'") to null', __FILE__, __LINE__); 1456 return false; 1457 } 1458 return $resolvedAbsoluteFilename; 1459 } 1460 1461 1462 public function file_exists_ignoreopenbasedir($filename, $cached=true) { 1463 static $open_basedirs = null; 1464 static $file_exists_cache = array(); 1465 if (!$cached || !isset($file_exists_cache[$filename])) { 1466 if (is_null($open_basedirs)) { 1467 $open_basedirs = preg_split('#[;:]#', ini_get('open_basedir')); 1468 } 1469 if (is_null($filename)) { // shouldn't happen, but https://github.com/JamesHeinrich/phpThumb/issues/188 1470 $file_exists_cache[$filename] = false; 1471 } elseif (empty($open_basedirs) || in_array(dirname($filename), $open_basedirs)) { 1472 $file_exists_cache[$filename] = file_exists($filename); 1473 } elseif ($this->iswindows) { 1474 $ls_filename = trim(phpthumb_functions::SafeExec('dir /b '.phpthumb_functions::escapeshellarg_replacement($filename))); 1475 $file_exists_cache[$filename] = ($ls_filename == basename($filename)); // command dir /b return only filename without path 1476 } else { 1477 $ls_filename = trim(phpthumb_functions::SafeExec('ls '.phpthumb_functions::escapeshellarg_replacement($filename))); 1478 $file_exists_cache[$filename] = ($ls_filename == $filename); 1479 } 1480 } 1481 return $file_exists_cache[$filename]; 1482 } 1483 1484 1485 public function ImageMagickWhichConvert() { 1486 static $WhichConvert = null; 1487 if (null === $WhichConvert) { 1488 if ($this->iswindows) { 1489 $WhichConvert = false; 1490 } else { 1491 $IMwhichConvertCacheFilename = $this->config_cache_directory.DIRECTORY_SEPARATOR.'phpThumbCacheIMwhichConvert.txt'; 1492 if (($cachedwhichconvertstring = @file_get_contents($IMwhichConvertCacheFilename)) !== false) { 1493 $WhichConvert = $cachedwhichconvertstring; 1494 } else { 1495 $WhichConvert = trim(phpthumb_functions::SafeExec('which convert')); 1496 @file_put_contents($IMwhichConvertCacheFilename, $WhichConvert); 1497 @chmod($IMwhichConvertCacheFilename, $this->getParameter('config_file_create_mask')); 1498 } 1499 } 1500 } 1501 return $WhichConvert; 1502 } 1503 1504 1505 public function ImageMagickCommandlineBase() { 1506 static $commandline = null; 1507 if (null === $commandline) { 1508 if ($this->issafemode) { 1509 $commandline = ''; 1510 return $commandline; 1511 } 1512 1513 $IMcommandlineBaseCacheFilename = $this->config_cache_directory.DIRECTORY_SEPARATOR.'phpThumbCacheIMcommandlineBase.txt'; 1514 if (($commandline = @file_get_contents($IMcommandlineBaseCacheFilename)) !== false) { 1515 return $commandline; 1516 } 1517 1518 $commandline = (null !== $this->config_imagemagick_path ? $this->config_imagemagick_path : ''); 1519 1520 if ($this->config_imagemagick_path && ($this->config_imagemagick_path != $this->realPathSafe($this->config_imagemagick_path))) { 1521 if (@is_executable($this->realPathSafe($this->config_imagemagick_path))) { 1522 $this->DebugMessage('Changing $this->config_imagemagick_path ('.$this->config_imagemagick_path.') to $this->realPathSafe($this->config_imagemagick_path) ('.$this->realPathSafe($this->config_imagemagick_path).')', __FILE__, __LINE__); 1523 $this->config_imagemagick_path = $this->realPathSafe($this->config_imagemagick_path); 1524 } else { 1525 $this->DebugMessage('Leaving $this->config_imagemagick_path as ('.$this->config_imagemagick_path.') because !is_execuatable($this->realPathSafe($this->config_imagemagick_path)) ('.$this->realPathSafe($this->config_imagemagick_path).')', __FILE__, __LINE__); 1526 } 1527 } 1528 if (!empty($this->config_imagemagick_path)) { 1529 $this->DebugMessage(' file_exists('.$this->config_imagemagick_path.') = '. (int) (@file_exists($this->config_imagemagick_path)), __FILE__, __LINE__); 1530 $this->DebugMessage('file_exists_ignoreopenbasedir('.$this->config_imagemagick_path.') = '. (int) $this->file_exists_ignoreopenbasedir($this->config_imagemagick_path), __FILE__, __LINE__); 1531 $this->DebugMessage(' is_file('.$this->config_imagemagick_path.') = '. (int) (@is_file($this->config_imagemagick_path)), __FILE__, __LINE__); 1532 $this->DebugMessage(' is_executable('.$this->config_imagemagick_path.') = '. (int) (@is_executable($this->config_imagemagick_path)), __FILE__, __LINE__); 1533 } 1534 1535 if ($this->file_exists_ignoreopenbasedir($this->config_imagemagick_path)) { 1536 1537 $this->DebugMessage('using ImageMagick path from $this->config_imagemagick_path ('.$this->config_imagemagick_path.')', __FILE__, __LINE__); 1538 if ($this->iswindows) { 1539 $commandline = ''; 1540 $commandline .= substr($this->config_imagemagick_path, 0, 2); 1541 $commandline .= ' && cd '.phpthumb_functions::escapeshellarg_replacement(str_replace('/', DIRECTORY_SEPARATOR, substr(dirname($this->config_imagemagick_path), 2))); 1542 $commandline .= ' && '.phpthumb_functions::escapeshellarg_replacement(basename($this->config_imagemagick_path)); 1543 } else { 1544 $commandline = phpthumb_functions::escapeshellarg_replacement($this->config_imagemagick_path); 1545 } 1546 1547 } else { 1548 1549 $which_convert = $this->ImageMagickWhichConvert(); 1550 $IMversion = $this->ImageMagickVersion(); 1551 1552 if ($which_convert && ($which_convert[0] == '/') && $this->file_exists_ignoreopenbasedir($which_convert)) { 1553 1554 // `which convert` *should* return the path if "convert" exist, or nothing if it doesn't 1555 // other things *may* get returned, like "sh: convert: not found" or "no convert in /usr/local/bin /usr/sbin /usr/bin /usr/ccs/bin" 1556 // so only do this if the value returned exists as a file 1557 $this->DebugMessage('using ImageMagick path from `which convert` ('.$which_convert.')', __FILE__, __LINE__); 1558 $commandline = 'convert'; 1559 1560 } elseif ($IMversion) { 1561 1562 $this->DebugMessage('setting ImageMagick path to $this->config_imagemagick_path ('.$this->config_imagemagick_path.') ['.$IMversion.']', __FILE__, __LINE__); 1563 $commandline = $this->config_imagemagick_path; 1564 1565 } else { 1566 1567 $this->DebugMessage('ImageMagickThumbnailToGD() aborting because cannot find convert in $this->config_imagemagick_path ('.$this->config_imagemagick_path.'), and `which convert` returned ('.$which_convert.')', __FILE__, __LINE__); 1568 $commandline = ''; 1569 1570 } 1571 1572 } 1573 1574 @file_put_contents($IMcommandlineBaseCacheFilename, $commandline); 1575 @chmod($IMcommandlineBaseCacheFilename, $this->getParameter('config_file_create_mask')); 1576 } 1577 return $commandline; 1578 } 1579 1580 1581 public function ImageMagickVersion($returnRAW=false) { 1582 static $versionstring = null; 1583 if (null === $versionstring) { 1584 $versionstring = array(0=>false, 1=>false); 1585 1586 $IMversionCacheFilename = $this->config_cache_directory.DIRECTORY_SEPARATOR.'phpThumbCacheIMversion.txt'; 1587 if ($cachedversionstring = @file_get_contents($IMversionCacheFilename)) { 1588 1589 $versionstring = explode("\n", $cachedversionstring, 2); 1590 $versionstring[0] = ($versionstring[0] ? $versionstring[0] : false); // "false" is stored as an empty string in the cache file 1591 $versionstring[1] = ($versionstring[1] ? $versionstring[1] : false); // "false" is stored as an empty string in the cache file 1592 1593 } else { 1594 1595 $commandline = $this->ImageMagickCommandlineBase(); 1596 $commandline = (null !== $commandline ? $commandline : ''); 1597 if ($commandline) { 1598 $commandline .= ' --version'; 1599 $this->DebugMessage('ImageMagick version checked with "'.$commandline.'"', __FILE__, __LINE__); 1600 $versionstring[1] = trim(phpthumb_functions::SafeExec($commandline)); 1601 if (preg_match('#^Version: [^\d]*([ 0-9\\.\\:Q/\\-]+)#i', $versionstring[1], $matches)) { 1602 $versionstring[0] = trim($matches[1]); 1603 } else { 1604 $versionstring[0] = false; 1605 $this->DebugMessage('ImageMagick did not return recognized version string ('.$versionstring[1].')', __FILE__, __LINE__); 1606 } 1607 $this->DebugMessage('ImageMagick convert --version says "'.@$matches[0].'"', __FILE__, __LINE__); 1608 } 1609 1610 @file_put_contents($IMversionCacheFilename, $versionstring[0]."\n".$versionstring[1]); 1611 @chmod($IMversionCacheFilename, $this->getParameter('config_file_create_mask')); 1612 1613 } 1614 } 1615 return $versionstring[ (int) $returnRAW ]; 1616 } 1617 1618 1619 public function ImageMagickSwitchAvailable($switchname) { 1620 static $IMoptions = null; 1621 if (null === $IMoptions) { 1622 $IMoptions = array(); 1623 $commandline = $this->ImageMagickCommandlineBase(); 1624 if (null !== $commandline) { 1625 $commandline .= ' -help'; 1626 $IMhelp_lines = explode("\n", phpthumb_functions::SafeExec($commandline)); 1627 foreach ($IMhelp_lines as $line) { 1628 if (preg_match('#^[\\+\\-]([a-z\\-]+) #', trim($line), $matches)) { 1629 $IMoptions[$matches[1]] = true; 1630 } 1631 } 1632 } 1633 } 1634 if (is_array($switchname)) { 1635 $allOK = true; 1636 foreach ($switchname as $key => $value) { 1637 if (!isset($IMoptions[$value])) { 1638 $allOK = false; 1639 break; 1640 } 1641 } 1642 $this->DebugMessage('ImageMagickSwitchAvailable('.implode(';', $switchname).') = '. (int) $allOK .'', __FILE__, __LINE__); 1643 } else { 1644 $allOK = isset($IMoptions[$switchname]); 1645 $this->DebugMessage('ImageMagickSwitchAvailable('.$switchname.') = '. (int) $allOK .'', __FILE__, __LINE__); 1646 } 1647 return $allOK; 1648 } 1649 1650 1651 public function ImageMagickFormatsList() { 1652 static $IMformatsList = null; 1653 if (null === $IMformatsList) { 1654 $IMformatsList = ''; 1655 $commandline = $this->ImageMagickCommandlineBase(); 1656 if (!is_null($commandline)) { 1657 $commandline = dirname($commandline).DIRECTORY_SEPARATOR.str_replace('convert', 'identify', basename($commandline)); 1658 $commandline .= ' -list format'; 1659 $IMformatsList = phpthumb_functions::SafeExec($commandline); 1660 } 1661 } 1662 return $IMformatsList; 1663 } 1664 1665 1666 public function SourceDataToTempFile() { 1667 if ($IMtempSourceFilename = $this->phpThumb_tempnam()) { 1668 $IMtempSourceFilename = $this->realPathSafe($IMtempSourceFilename); 1669 ob_start(); 1670 $fp_tempfile = fopen($IMtempSourceFilename, 'wb'); 1671 $tempfile_open_error = ob_get_contents(); 1672 ob_end_clean(); 1673 if ($fp_tempfile) { 1674 fwrite($fp_tempfile, $this->rawImageData); 1675 fclose($fp_tempfile); 1676 @chmod($IMtempSourceFilename, $this->getParameter('config_file_create_mask')); 1677 $this->sourceFilename = $IMtempSourceFilename; 1678 $this->DebugMessage('ImageMagickThumbnailToGD() setting $this->sourceFilename to "'.$IMtempSourceFilename.'" from $this->rawImageData ('.strlen($this->rawImageData).' bytes)', __FILE__, __LINE__); 1679 } else { 1680 $this->DebugMessage('ImageMagickThumbnailToGD() FAILED setting $this->sourceFilename to "'.$IMtempSourceFilename.'" (failed to open for writing: "'.$tempfile_open_error.'")', __FILE__, __LINE__); 1681 } 1682 unset($tempfile_open_error, $IMtempSourceFilename); 1683 return true; 1684 } 1685 $this->DebugMessage('SourceDataToTempFile() FAILED because $this->phpThumb_tempnam() failed', __FILE__, __LINE__); 1686 return false; 1687 } 1688 1689 1690 public function ImageMagickThumbnailToGD() { 1691 // http://www.imagemagick.org/script/command-line-options.php 1692 1693 $this->useRawIMoutput = true; 1694 if (phpthumb_functions::gd_version()) { 1695 // if GD is not available, must use whatever ImageMagick can output 1696 1697 // $CannotMagickParameters contains options that cannot be used with ImageMagick 1698 $CannotMagickParameters = array('ica'); 1699 foreach ($CannotMagickParameters as $parameter) { 1700 if (isset($this->$parameter)) { 1701 $this->DebugMessage('cannot process with ImageMagick because "'.$parameter.'" is set', __FILE__, __LINE__); 1702 $this->useRawIMoutput = false; 1703 return false; 1704 } 1705 } 1706 1707 // $UnAllowedParameters contains options that can only be processed in GD, not ImageMagick 1708 // note: 'fltr' *may* need to be processed by GD, but we'll check that in more detail below 1709 $UnAllowedParameters = array('xto', 'ar', 'bg', 'bc'); 1710 // 'ra' may be part of this list, if not a multiple of 90 degrees 1711 foreach ($UnAllowedParameters as $parameter) { 1712 if (isset($this->$parameter)) { 1713 $this->DebugMessage('$this->useRawIMoutput=false because "'.$parameter.'" is set', __FILE__, __LINE__); 1714 $this->useRawIMoutput = false; 1715 break; 1716 } 1717 } 1718 } 1719 $this->DebugMessage('$this->useRawIMoutput='.($this->useRawIMoutput ? 'true' : 'false').' after checking $UnAllowedParameters', __FILE__, __LINE__); 1720 $ImageCreateFunction = ''; 1721 $outputFormat = $this->thumbnailFormat; 1722 if (phpthumb_functions::gd_version()) { 1723 if ($this->useRawIMoutput) { 1724 switch ($this->thumbnailFormat) { 1725 case 'gif': 1726 $ImageCreateFunction = 'imagecreatefromgif'; 1727 $this->is_alpha = true; 1728 break; 1729 case 'png': 1730 $ImageCreateFunction = 'imagecreatefrompng'; 1731 $this->is_alpha = true; 1732 break; 1733 case 'jpg': 1734 case 'jpeg': 1735 $ImageCreateFunction = 'imagecreatefromjpeg'; 1736 break; 1737 case 'webp': 1738 $ImageCreateFunction = 'imagecreatefromwebp'; 1739 $this->is_alpha = true; 1740 break; 1741 case 'avif': 1742 $ImageCreateFunction = 'imagecreatefromavif'; 1743 $this->is_alpha = true; 1744 break; 1745 default: 1746 $this->DebugMessage('Forcing output to PNG because $this->thumbnailFormat ('.$this->thumbnailFormat.' is not a GD-supported format)', __FILE__, __LINE__); 1747 $outputFormat = 'png'; 1748 $ImageCreateFunction = 'imagecreatefrompng'; 1749 $this->is_alpha = true; 1750 $this->useRawIMoutput = false; 1751 break; 1752 } 1753 if (!function_exists($ImageCreateFunction)) { 1754 // ImageMagickThumbnailToGD() depends on imagecreatefrompng/imagecreatefromgif 1755 //$this->DebugMessage('ImageMagickThumbnailToGD() aborting because '.@$ImageCreateFunction.'() is not available', __FILE__, __LINE__); 1756 $this->useRawIMoutput = true; 1757 //return false; 1758 } 1759 } else { 1760 $outputFormat = 'png'; 1761 $ImageCreateFunction = 'imagecreatefrompng'; 1762 $this->is_alpha = true; 1763 $this->useRawIMoutput = false; 1764 } 1765 } 1766 1767 // http://freealter.org/doc_distrib/ImageMagick-5.1.1/www/convert.html 1768 if (!$this->sourceFilename && $this->rawImageData) { 1769 $this->SourceDataToTempFile(); 1770 } 1771 if (!$this->sourceFilename) { 1772 $this->DebugMessage('ImageMagickThumbnailToGD() aborting because $this->sourceFilename is empty', __FILE__, __LINE__); 1773 $this->useRawIMoutput = false; 1774 return false; 1775 } 1776 if ($this->issafemode) { 1777 $this->DebugMessage('ImageMagickThumbnailToGD() aborting because safe_mode is enabled', __FILE__, __LINE__); 1778 $this->useRawIMoutput = false; 1779 return false; 1780 } 1781// TO BE FIXED 1782//if (true) { 1783// $this->DebugMessage('ImageMagickThumbnailToGD() aborting it is broken right now', __FILE__, __LINE__); 1784// $this->useRawIMoutput = false; 1785// return false; 1786//} 1787 1788 $commandline = $this->ImageMagickCommandlineBase(); 1789 if ($commandline) { 1790 $commandline .= ' '.phpthumb_functions::escapeshellarg_replacement(preg_replace('#[/\\\\]#', DIRECTORY_SEPARATOR, $this->sourceFilename).(($outputFormat == 'gif') ? '' : '['. (int) $this->sfn .']')); // [0] means first frame of (GIF) animation, can be ignored 1791 if ($IMtempfilename = $this->phpThumb_tempnam()) { 1792 $IMtempfilename = $this->realPathSafe($IMtempfilename); 1793 1794 $IMuseExplicitImageOutputDimensions = false; 1795 if ($this->ImageMagickSwitchAvailable('thumbnail') && $this->config_imagemagick_use_thumbnail) { 1796 $IMresizeParameter = 'thumbnail'; 1797 } else { 1798 $IMresizeParameter = 'resize'; 1799 1800 // some (older? around 2002) versions of IM won't accept "-resize 100x" but require "-resize 100x100" 1801 $commandline_test = $this->ImageMagickCommandlineBase().' logo: -resize 1x '.phpthumb_functions::escapeshellarg_replacement($IMtempfilename).' 2>&1'; 1802 $IMresult_test = phpthumb_functions::SafeExec($commandline_test); 1803 $IMuseExplicitImageOutputDimensions = preg_match('#image dimensions are zero#i', $IMresult_test); 1804 $this->DebugMessage('IMuseExplicitImageOutputDimensions = '. (int) $IMuseExplicitImageOutputDimensions, __FILE__, __LINE__); 1805 if ($fp_im_temp = @fopen($IMtempfilename, 'wb')) { 1806 // erase temp image so ImageMagick logo doesn't get output if other processing fails 1807 fclose($fp_im_temp); 1808 @chmod($IMtempfilename, $this->getParameter('config_file_create_mask')); 1809 } 1810 } 1811 1812 1813 ob_start(); 1814 $getimagesize = getimagesize($this->sourceFilename); 1815 $GetImageSizeError = ob_get_contents(); 1816 ob_end_clean(); 1817 if (is_array($getimagesize)) { 1818 $this->DebugMessage('getimagesize('.$this->sourceFilename.') SUCCEEDED: '.print_r($getimagesize, true), __FILE__, __LINE__); 1819 } else { 1820 $this->DebugMessage('getimagesize('.$this->sourceFilename.') FAILED with error "'.$GetImageSizeError.'"', __FILE__, __LINE__); 1821 } 1822 if (null !== $this->dpi && $this->ImageMagickSwitchAvailable('density')) { 1823 // for vector source formats only (WMF, PDF, etc) 1824 if (is_array($getimagesize) && isset($getimagesize[2]) && ($getimagesize[2] == IMAGETYPE_PNG)) { 1825 // explicitly exclude PNG from "-flatten" to make sure transparency is preserved 1826 // https://github.com/JamesHeinrich/phpThumb/issues/65 1827 } else { 1828 $commandline .= ' -flatten'; 1829 $commandline .= ' -density '.phpthumb_functions::escapeshellarg_replacement($this->dpi); 1830 } 1831 } 1832 if (is_array($getimagesize)) { 1833 $this->DebugMessage('getimagesize('.$this->sourceFilename.') returned [w='.$getimagesize[0].';h='.$getimagesize[1].';f='.$getimagesize[2].']', __FILE__, __LINE__); 1834 $this->source_width = $getimagesize[0]; 1835 $this->source_height = $getimagesize[1]; 1836 $this->DebugMessage('source dimensions set to '.$this->source_width.'x'.$this->source_height, __FILE__, __LINE__); 1837 $this->SetOrientationDependantWidthHeight(); 1838 1839 if (!preg_match('#('.implode('|', $this->AlphaCapableFormats).')#i', $outputFormat)) { 1840 // not a transparency-capable format 1841 $commandline .= ' -background '.phpthumb_functions::escapeshellarg_replacement('#'.($this->bg ? $this->bg : 'FFFFFF')); 1842 if (!stristr($commandline, ' -flatten')) { 1843 $commandline .= ' -flatten'; 1844 } 1845 } else { 1846 if ($getimagesize[2] == IMAGETYPE_PNG && !$this->bg) { 1847 $commandline .= ' -background none'; 1848 } 1849 } 1850 if ($getimagesize[2] == IMAGETYPE_GIF) { 1851 $commandline .= ' -coalesce'; // may be needed for animated GIFs 1852 } 1853 if ($this->source_width || $this->source_height) { 1854 if ($this->zc) { 1855 1856 $borderThickness = 0; 1857 if (!empty($this->fltr)) { 1858 foreach ($this->fltr as $key => $value) { 1859 if (preg_match('#^bord\|([\d]+)#', $value, $matches)) { 1860 $borderThickness = $matches[1]; 1861 break; 1862 } 1863 } 1864 } 1865 $wAll = (int) max($this->w, $this->wp, $this->wl, $this->ws) - (2 * $borderThickness); 1866 $hAll = (int) max($this->h, $this->hp, $this->hl, $this->hs) - (2 * $borderThickness); 1867 $imAR = $this->source_width / $this->source_height; 1868 $zcAR = (($wAll && $hAll) ? $wAll / $hAll : 1); 1869 $side = phpthumb_functions::nonempty_min($this->source_width, $this->source_height, max($wAll, $hAll)); 1870 $sideX = phpthumb_functions::nonempty_min($this->source_width, $wAll, round($hAll * $zcAR)); 1871 $sideY = phpthumb_functions::nonempty_min( $this->source_height, $hAll, round($wAll / $zcAR)); 1872 1873 $thumbnailH = round(max($sideY, ($sideY * $zcAR) / $imAR)); 1874 if ($this->aoe == 1) { 1875 $commandline .= ' -'.$IMresizeParameter.' "'.$wAll.'x'.$hAll.'^"'; 1876 } else { 1877 $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement(($IMuseExplicitImageOutputDimensions ? $thumbnailH : '').'x'.$thumbnailH); 1878 } 1879 1880 switch (strtoupper($this->zc)) { 1881 case 'T': 1882 $commandline .= ' -gravity north'; 1883 break; 1884 case 'B': 1885 $commandline .= ' -gravity south'; 1886 break; 1887 case 'L': 1888 $commandline .= ' -gravity west'; 1889 break; 1890 case 'R': 1891 $commandline .= ' -gravity east'; 1892 break; 1893 case 'TL': 1894 $commandline .= ' -gravity northwest'; 1895 break; 1896 case 'TR': 1897 $commandline .= ' -gravity northeast'; 1898 break; 1899 case 'BL': 1900 $commandline .= ' -gravity southwest'; 1901 break; 1902 case 'BR': 1903 $commandline .= ' -gravity southeast'; 1904 break; 1905 case '1': 1906 case 'C': 1907 default: 1908 $commandline .= ' -gravity center'; 1909 break; 1910 } 1911 1912 if (($wAll > 0) && ($hAll > 0)) { 1913 $commandline .= ' -crop '.phpthumb_functions::escapeshellarg_replacement($wAll.'x'.$hAll.'+0+0'); 1914 } else { 1915 $commandline .= ' -crop '.phpthumb_functions::escapeshellarg_replacement($side.'x'.$side.'+0+0'); 1916 } 1917 if ($this->ImageMagickSwitchAvailable('repage')) { 1918 $commandline .= ' +repage'; 1919 } else { 1920 $this->DebugMessage('Skipping "+repage" because ImageMagick (v'.$this->ImageMagickVersion().') does not support it', __FILE__, __LINE__); 1921 } 1922 1923 } elseif ($this->sw || $this->sh || $this->sx || $this->sy) { 1924 1925 $crop_param = ''; 1926 $crop_param .= ($this->sw ? (($this->sw < 2) ? round($this->sw * $this->source_width) : $this->sw) : $this->source_width); 1927 $crop_param .= 'x'.($this->sh ? (($this->sh < 2) ? round($this->sh * $this->source_height) : $this->sh) : $this->source_height); 1928 $crop_param .= '+'.(($this->sx < 2) ? round($this->sx * $this->source_width) : $this->sx); 1929 $crop_param .= '+'.(($this->sy < 2) ? round($this->sy * $this->source_height) : $this->sy); 1930// TO BE FIXED 1931// makes 1x1 output 1932// http://trainspotted.com/phpThumb/phpThumb.php?src=/content/CNR/47/CNR-4728-LD-L-20110723-898.jpg&w=100&h=100&far=1&f=png&fltr[]=lvl&sx=0.05&sy=0.25&sw=0.92&sh=0.42 1933// '/usr/bin/convert' -density 150 -thumbnail 100x100 -contrast-stretch '0.1%' '/var/www/vhosts/trainspotted.com/httpdocs/content/CNR/47/CNR-4728-LD-L-20110723-898.jpg[0]' png:'/var/www/vhosts/trainspotted.com/httpdocs/phpThumb/_cache/pThumbIIUlvj' 1934 $commandline .= ' -crop '.phpthumb_functions::escapeshellarg_replacement($crop_param); 1935 1936 // this is broken for aoe=1, but unsure how to fix. Send advice to info@silisoftware.com 1937 if ($this->w || $this->h) { 1938 //if ($this->ImageMagickSwitchAvailable('repage')) { 1939if (false) { 1940// TO BE FIXED 1941// newer versions of ImageMagick require -repage <geometry> 1942 $commandline .= ' -repage'; 1943 } else { 1944 $this->DebugMessage('Skipping "-repage" because ImageMagick (v'.$this->ImageMagickVersion().') does not support it', __FILE__, __LINE__); 1945 } 1946 if ($IMuseExplicitImageOutputDimensions) { 1947 if ($this->w && !$this->h) { 1948 $this->h = ceil($this->w / ($this->source_width / $this->source_height)); 1949 } elseif ($this->h && !$this->w) { 1950 $this->w = ceil($this->h * ($this->source_width / $this->source_height)); 1951 } 1952 } 1953 $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement($this->w.'x'.$this->h); 1954 } 1955 1956 } else { 1957 1958 if ($this->iar && ((int) $this->w > 0) && ((int) $this->h > 0)) { 1959 1960 list($nw, $nh) = phpthumb_functions::TranslateWHbyAngle($this->w, $this->h, $this->ra); 1961 $nw = ((round($nw) != 0) ? round($nw) : ''); 1962 $nh = ((round($nh) != 0) ? round($nh) : ''); 1963 $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement($nw.'x'.$nh.'!'); 1964 1965 } elseif ($this->far && ((int) $this->w > 0) && ((int) $this->h > 0)) { 1966 1967 $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement(phpthumb_functions::nonempty_min($this->w, $getimagesize[0]).'x'.phpthumb_functions::nonempty_min($this->h, $getimagesize[1])); 1968 $commandline .= ' -gravity center'; 1969 if ($this->bg) { 1970 $commandline .= ' -background ' . phpthumb_functions::escapeshellarg_replacement('#' . $this->bg); 1971 } else { 1972 $commandline .= ' -background none'; 1973 } 1974 $commandline .= ' -extent '.phpthumb_functions::escapeshellarg_replacement($this->w.'x'.$this->h); 1975 1976 } else { 1977 1978 $this->w = (($this->aoe && $this->w) ? $this->w : ($this->w ? phpthumb_functions::nonempty_min($this->w, $getimagesize[0]) : null)); 1979 $this->h = (($this->aoe && $this->h) ? $this->h : ($this->h ? phpthumb_functions::nonempty_min($this->h, $getimagesize[1]) : null)); 1980 if ($this->w || $this->h) { 1981 if ($IMuseExplicitImageOutputDimensions) { 1982 if ($this->w && !$this->h) { 1983 $this->h = ceil($this->w / ($this->source_width / $this->source_height)); 1984 } elseif ($this->h && !$this->w) { 1985 $this->w = ceil($this->h * ($this->source_width / $this->source_height)); 1986 } 1987 } 1988 list($nw, $nh) = phpthumb_functions::TranslateWHbyAngle($this->w, $this->h, $this->ra); 1989 $nw = ((round($nw) != 0) ? round($nw) : ''); 1990 $nh = ((round($nh) != 0) ? round($nh) : ''); 1991 $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement($nw.'x'.$nh); 1992 } 1993 1994 } 1995 } 1996 } 1997 1998 } else { 1999 2000 $this->DebugMessage('getimagesize('.$this->sourceFilename.') failed', __FILE__, __LINE__); 2001 if ($this->w || $this->h) { 2002 $exactDimensionsBang = (($this->iar && ((int) $this->w > 0) && ((int) $this->h > 0)) ? '!' : ''); 2003 if ($IMuseExplicitImageOutputDimensions) { 2004 // unknown source aspect ratio, just put large number and hope IM figures it out 2005 $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement(($this->w ? $this->w : '9999').'x'.($this->h ? $this->h : '9999').$exactDimensionsBang); 2006 } else { 2007 $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement($this->w.'x'.$this->h.$exactDimensionsBang); 2008 } 2009 } 2010 2011 } 2012 2013 if ($this->ra) { 2014 $this->ra = (int) $this->ra; 2015 if ($this->ImageMagickSwitchAvailable('rotate')) { 2016 if (!preg_match('#('.implode('|', $this->AlphaCapableFormats).')#i', $outputFormat) || phpthumb_functions::version_compare_replacement($this->ImageMagickVersion(), '6.3.7', '>=')) { 2017 $this->DebugMessage('Using ImageMagick rotate', __FILE__, __LINE__); 2018 $commandline .= ' -rotate '.phpthumb_functions::escapeshellarg_replacement($this->ra); 2019 if (($this->ra % 90) != 0) { 2020 if (preg_match('#('.implode('|', $this->AlphaCapableFormats).')#i', $outputFormat)) { 2021 // alpha-capable format 2022 $commandline .= ' -background rgba(255,255,255,0)'; 2023 } else { 2024 $commandline .= ' -background '.phpthumb_functions::escapeshellarg_replacement('#'.($this->bg ? $this->bg : 'FFFFFF')); 2025 } 2026 } 2027 $this->ra = 0; 2028 } else { 2029 $this->DebugMessage('Not using ImageMagick rotate because alpha background buggy before v6.3.7', __FILE__, __LINE__); 2030 } 2031 } else { 2032 $this->DebugMessage('Not using ImageMagick rotate because not supported', __FILE__, __LINE__); 2033 } 2034 } 2035 2036 $successfullyProcessedFilters = array(); 2037 foreach ($this->fltr as $filterkey => $filtercommand) { 2038 @list($command, $parameter) = explode('|', $filtercommand, 2); 2039 switch ($command) { 2040 case 'brit': 2041 if ($this->ImageMagickSwitchAvailable('modulate')) { 2042 $commandline .= ' -modulate '.phpthumb_functions::escapeshellarg_replacement((100 + (int) $parameter).',100,100'); 2043 $successfullyProcessedFilters[] = $filterkey; 2044 } 2045 break; 2046 2047 case 'cont': 2048 if ($this->ImageMagickSwitchAvailable('contrast')) { 2049 $contDiv10 = round((int) $parameter / 10); 2050 if ($contDiv10 > 0) { 2051 $contDiv10 = min($contDiv10, 100); 2052 for ($i = 0; $i < $contDiv10; $i++) { 2053 $commandline .= ' -contrast'; // increase contrast by 10% 2054 } 2055 } elseif ($contDiv10 < 0) { 2056 $contDiv10 = max($contDiv10, -100); 2057 for ($i = $contDiv10; $i < 0; $i++) { 2058 $commandline .= ' +contrast'; // decrease contrast by 10% 2059 } 2060 } else { 2061 // do nothing 2062 } 2063 $successfullyProcessedFilters[] = $filterkey; 2064 } 2065 break; 2066 2067 case 'ds': 2068 if ($this->ImageMagickSwitchAvailable(array('colorspace', 'modulate'))) { 2069 if ($parameter == 100) { 2070 $commandline .= ' -colorspace GRAY'; 2071 $commandline .= ' -modulate 100,0,100'; 2072 } else { 2073 $commandline .= ' -modulate '.phpthumb_functions::escapeshellarg_replacement('100,'.(100 - (int) $parameter).',100'); 2074 } 2075 $successfullyProcessedFilters[] = $filterkey; 2076 } 2077 break; 2078 2079 case 'sat': 2080 if ($this->ImageMagickSwitchAvailable(array('colorspace', 'modulate'))) { 2081 if ($parameter == -100) { 2082 $commandline .= ' -colorspace GRAY'; 2083 $commandline .= ' -modulate 100,0,100'; 2084 } else { 2085 $commandline .= ' -modulate '.phpthumb_functions::escapeshellarg_replacement('100,'.(100 + (int) $parameter).',100'); 2086 } 2087 $successfullyProcessedFilters[] = $filterkey; 2088 } 2089 break; 2090 2091 case 'gray': 2092 if ($this->ImageMagickSwitchAvailable(array('colorspace', 'modulate'))) { 2093 $commandline .= ' -colorspace GRAY'; 2094 $commandline .= ' -modulate 100,0,100'; 2095 $successfullyProcessedFilters[] = $filterkey; 2096 } 2097 break; 2098 2099 case 'clr': 2100 if ($this->ImageMagickSwitchAvailable(array('fill', 'colorize'))) { 2101 @list($amount, $color) = explode('|', $parameter); 2102 $commandline .= ' -fill '.phpthumb_functions::escapeshellarg_replacement('#'.preg_replace('#[^0-9A-F]#i', '', $color)); 2103 $commandline .= ' -colorize '.phpthumb_functions::escapeshellarg_replacement(min(max((int) $amount, 0), 100)); 2104 $successfullyProcessedFilters[] = $filterkey; 2105 } 2106 break; 2107 2108 case 'sep': 2109 if ($this->ImageMagickSwitchAvailable('sepia-tone')) { 2110 @list($amount, $color) = explode('|', $parameter); 2111 $amount = ($amount ? $amount : 80); 2112 if (!$color) { 2113 $commandline .= ' -sepia-tone '.phpthumb_functions::escapeshellarg_replacement(min(max((int) $amount, 0), 100).'%'); 2114 $successfullyProcessedFilters[] = $filterkey; 2115 } 2116 } 2117 break; 2118 2119 case 'gam': 2120 @list($amount) = explode('|', $parameter); 2121 $amount = min(max((float) $amount, 0.001), 10); 2122 if (number_format($amount, 3) != '1.000') { 2123 if ($this->ImageMagickSwitchAvailable('gamma')) { 2124 $commandline .= ' -gamma '.phpthumb_functions::escapeshellarg_replacement($amount); 2125 $successfullyProcessedFilters[] = $filterkey; 2126 } 2127 } 2128 break; 2129 2130 case 'neg': 2131 if ($this->ImageMagickSwitchAvailable('negate')) { 2132 $commandline .= ' -negate'; 2133 $successfullyProcessedFilters[] = $filterkey; 2134 } 2135 break; 2136 2137 case 'th': 2138 @list($amount) = explode('|', $parameter); 2139 if ($this->ImageMagickSwitchAvailable(array('threshold', 'dither', 'monochrome'))) { 2140 $commandline .= ' -threshold '.phpthumb_functions::escapeshellarg_replacement(round(min(max((int) $amount, 0), 255) / 2.55).'%'); 2141 $commandline .= ' -dither'; 2142 $commandline .= ' -monochrome'; 2143 $successfullyProcessedFilters[] = $filterkey; 2144 } 2145 break; 2146 2147 case 'rcd': 2148 if ($this->ImageMagickSwitchAvailable(array('colors', 'dither'))) { 2149 @list($colors, $dither) = explode('|', $parameter); 2150 $colors = ($colors ? (int) $colors : 256); 2151 $dither = ((strlen($dither) > 0) ? (bool) $dither : true); 2152 $commandline .= ' -colors '.phpthumb_functions::escapeshellarg_replacement(max($colors, 8)); // ImageMagick will otherwise fail with "cannot quantize to fewer than 8 colors" 2153 $commandline .= ($dither ? ' -dither' : ' +dither'); 2154 $successfullyProcessedFilters[] = $filterkey; 2155 } 2156 break; 2157 2158 case 'flip': 2159 if ($this->ImageMagickSwitchAvailable(array('flip', 'flop'))) { 2160 if (strpos(strtolower($parameter), 'x') !== false) { 2161 $commandline .= ' -flop'; 2162 } 2163 if (strpos(strtolower($parameter), 'y') !== false) { 2164 $commandline .= ' -flip'; 2165 } 2166 $successfullyProcessedFilters[] = $filterkey; 2167 } 2168 break; 2169 2170 case 'edge': 2171 if ($this->ImageMagickSwitchAvailable('edge')) { 2172 $parameter = (!empty($parameter) ? $parameter : 2); 2173 $commandline .= ' -edge '.phpthumb_functions::escapeshellarg_replacement(!empty($parameter) ? (int) $parameter : 1); 2174 $successfullyProcessedFilters[] = $filterkey; 2175 } 2176 break; 2177 2178 case 'emb': 2179 if ($this->ImageMagickSwitchAvailable(array('emboss', 'negate'))) { 2180 $parameter = (!empty($parameter) ? $parameter : 2); 2181 $commandline .= ' -emboss '.phpthumb_functions::escapeshellarg_replacement((int) $parameter); 2182 if ($parameter < 2) { 2183 $commandline .= ' -negate'; // ImageMagick negates the image for some reason with '-emboss 1'; 2184 } 2185 $successfullyProcessedFilters[] = $filterkey; 2186 } 2187 break; 2188 2189 case 'lvl': 2190 @list($band, $method, $threshold) = explode('|', $parameter); 2191 $band = ($band ? preg_replace('#[^RGBA\\*]#', '', strtoupper($band)) : '*'); 2192 $method = ((strlen($method) > 0) ? (int) $method : 2); 2193 $threshold = ((strlen($threshold) > 0) ? min(max((float) $threshold, 0), 100) : 0.1); 2194 2195 $band = preg_replace('#[^RGBA\\*]#', '', strtoupper($band)); 2196 2197 if (($method > 1) && !$this->ImageMagickSwitchAvailable(array('channel', 'contrast-stretch'))) { 2198 // Because ImageMagick processing happens before PHP-GD filters, and because some 2199 // clipping is involved in the "lvl" filter, if "lvl" happens before "wb" then the 2200 // "wb" filter will have (almost) no effect. Therefore, if "wb" is enabled then 2201 // force the "lvl" filter to be processed by GD, not ImageMagick. 2202 foreach ($this->fltr as $fltr_key => $fltr_value) { 2203 list($fltr_cmd) = explode('|', $fltr_value); 2204 if ($fltr_cmd == 'wb') { 2205 $this->DebugMessage('Setting "lvl" filter method to "0" (from "'.$method.'") because white-balance filter also enabled', __FILE__, __LINE__); 2206 $method = 0; 2207 } 2208 } 2209 } 2210 2211 switch ($method) { 2212 case 0: // internal RGB 2213 case 1: // internal grayscale 2214 break; 2215 case 2: // ImageMagick "contrast-stretch" 2216 if ($this->ImageMagickSwitchAvailable('contrast-stretch')) { 2217 if ($band != '*') { 2218 $commandline .= ' -channel '.phpthumb_functions::escapeshellarg_replacement(strtoupper($band)); 2219 } 2220 $threshold = preg_replace('#[^0-9\\.]#', '', $threshold); // should be unneccesary, but just to be double-sure 2221 //$commandline .= ' -contrast-stretch '.phpthumb_functions::escapeshellarg_replacement($threshold.'%'); 2222 $commandline .= ' -contrast-stretch \''.$threshold.'%\''; 2223 if ($band != '*') { 2224 $commandline .= ' +channel'; 2225 } 2226 $successfullyProcessedFilters[] = $filterkey; 2227 } 2228 break; 2229 case 3: // ImageMagick "normalize" 2230 if ($this->ImageMagickSwitchAvailable('normalize')) { 2231 if ($band != '*') { 2232 $commandline .= ' -channel '.phpthumb_functions::escapeshellarg_replacement(strtoupper($band)); 2233 } 2234 $commandline .= ' -normalize'; 2235 if ($band != '*') { 2236 $commandline .= ' +channel'; 2237 } 2238 $successfullyProcessedFilters[] = $filterkey; 2239 } 2240 break; 2241 default: 2242 $this->DebugMessage('unsupported method ('.$method.') for "lvl" filter', __FILE__, __LINE__); 2243 break; 2244 } 2245 if (isset($this->fltr[$filterkey]) && ($method > 1)) { 2246 $this->fltr[$filterkey] = $command.'|'.$band.'|0|'.$threshold; 2247 $this->DebugMessage('filter "lvl" remapped from method "'.$method.'" to method "0" because ImageMagick support is missing', __FILE__, __LINE__); 2248 } 2249 break; 2250 2251 case 'wb': 2252 if ($this->ImageMagickSwitchAvailable(array('channel', 'contrast-stretch'))) { 2253 @list($threshold) = explode('|', $parameter); 2254 $threshold = (!empty($threshold) ? min(max((float) $threshold, 0), 100) : 0.1); 2255 $threshold = preg_replace('#[^0-9\\.]#', '', $threshold); // should be unneccesary, but just to be double-sure 2256 //$commandline .= ' -channel R -contrast-stretch '.phpthumb_functions::escapeshellarg_replacement($threshold.'%'); // doesn't work on Windows because most versions of PHP do not properly 2257 //$commandline .= ' -channel G -contrast-stretch '.phpthumb_functions::escapeshellarg_replacement($threshold.'%'); // escape special characters (such as %) and just replace them with spaces 2258 //$commandline .= ' -channel B -contrast-stretch '.phpthumb_functions::escapeshellarg_replacement($threshold.'%'); // https://bugs.php.net/bug.php?id=43261 2259 $commandline .= ' -channel R -contrast-stretch \''.$threshold.'%\''; 2260 $commandline .= ' -channel G -contrast-stretch \''.$threshold.'%\''; 2261 $commandline .= ' -channel B -contrast-stretch \''.$threshold.'%\''; 2262 $commandline .= ' +channel'; 2263 $successfullyProcessedFilters[] = $filterkey; 2264 } 2265 break; 2266 2267 case 'blur': 2268 if ($this->ImageMagickSwitchAvailable('blur')) { 2269 @list($radius) = explode('|', $parameter); 2270 $radius = (!empty($radius) ? min(max((int) $radius, 0), 25) : 1); 2271 $commandline .= ' -blur '.phpthumb_functions::escapeshellarg_replacement($radius); 2272 $successfullyProcessedFilters[] = $filterkey; 2273 } 2274 break; 2275 2276 case 'gblr': 2277 @list($radius) = explode('|', $parameter); 2278 $radius = (!empty($radius) ? min(max((int) $radius, 0), 25) : 1); 2279 // "-gaussian" changed to "-gaussian-blur" sometime around 2009 2280 if ($this->ImageMagickSwitchAvailable('gaussian-blur')) { 2281 $commandline .= ' -gaussian-blur '.phpthumb_functions::escapeshellarg_replacement($radius); 2282 $successfullyProcessedFilters[] = $filterkey; 2283 } elseif ($this->ImageMagickSwitchAvailable('gaussian')) { 2284 $commandline .= ' -gaussian '.phpthumb_functions::escapeshellarg_replacement($radius); 2285 $successfullyProcessedFilters[] = $filterkey; 2286 } 2287 break; 2288 2289 case 'usm': 2290 if ($this->ImageMagickSwitchAvailable('unsharp')) { 2291 @list($amount, $radius, $threshold) = explode('|', $parameter); 2292 $amount = ($amount ? min(max((int) $amount, 0), 255) : 80); 2293 $radius = ($radius ? min(max((int) $radius, 0), 10) : 0.5); 2294 $threshold = ('' !== $threshold ? min(max((int) $threshold, 0), 50) : 3); 2295 $commandline .= ' -unsharp '.phpthumb_functions::escapeshellarg_replacement(number_format(($radius * 2) - 1, 2, '.', '').'x1+'.number_format($amount / 100, 2, '.', '').'+'.number_format($threshold / 100, 2, '.', '')); 2296 $successfullyProcessedFilters[] = $filterkey; 2297 } 2298 break; 2299 2300 case 'bord': 2301 if ($this->ImageMagickSwitchAvailable(array('border', 'bordercolor', 'thumbnail', 'crop'))) { 2302 if (!$this->zc) { 2303 @list($width, $rX, $rY, $color) = explode('|', $parameter); 2304 $width = (int) $width; 2305 $rX = (int) $rX; 2306 $rY = (int) $rY; 2307 if ($width && !$rX && !$rY) { 2308 if (!phpthumb_functions::IsHexColor($color)) { 2309 $color = ((!empty($this->bc) && phpthumb_functions::IsHexColor($this->bc)) ? $this->bc : '000000'); 2310 } 2311 $commandline .= ' -border '.phpthumb_functions::escapeshellarg_replacement((int) $width); 2312 $commandline .= ' -bordercolor '.phpthumb_functions::escapeshellarg_replacement('#'.$color); 2313 2314 if (preg_match('# \\-crop "([\d]+)x([\d]+)\\+0\\+0" #', $commandline, $matches)) { 2315 $commandline = str_replace(' -crop "'.$matches[1].'x'.$matches[2].'+0+0" ', ' -crop '.phpthumb_functions::escapeshellarg_replacement(($matches[1] - (2 * $width)).'x'.($matches[2] - (2 * $width)).'+0+0').' ', $commandline); 2316 } elseif (preg_match('# \\-'.$IMresizeParameter.' "([0-9]+)x([0-9]+)" #', $commandline, $matches)) { 2317 $commandline = str_replace(' -'.$IMresizeParameter.' "'.$matches[1].'x'.$matches[2].'" ', ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement(($matches[1] - (2 * $width)).'x'.($matches[2] - (2 * $width))).' ', $commandline); 2318 } 2319 $successfullyProcessedFilters[] = $filterkey; 2320 } 2321 } 2322 } 2323 break; 2324 2325 case 'crop': 2326 break; 2327 2328 case 'sblr': 2329 break; 2330 2331 case 'mean': 2332 break; 2333 2334 case 'smth': 2335 break; 2336 2337 case 'bvl': 2338 break; 2339 2340 case 'wmi': 2341 break; 2342 2343 case 'wmt': 2344 break; 2345 2346 case 'over': 2347 break; 2348 2349 case 'hist': 2350 break; 2351 2352 case 'fram': 2353 break; 2354 2355 case 'drop': 2356 break; 2357 2358 case 'mask': 2359 break; 2360 2361 case 'elip': 2362 break; 2363 2364 case 'ric': 2365 break; 2366 2367 case 'stc': 2368 break; 2369 2370 case 'size': 2371 break; 2372 2373 default: 2374 $this->DebugMessage('Unknown $this->fltr['.$filterkey.'] ('.$filtercommand.') -- deleting filter command', __FILE__, __LINE__); 2375 $successfullyProcessedFilters[] = $filterkey; 2376 break; 2377 } 2378 if (!isset($this->fltr[$filterkey])) { 2379 $this->DebugMessage('Processed $this->fltr['.$filterkey.'] ('.$filtercommand.') with ImageMagick', __FILE__, __LINE__); 2380 } else { 2381 $this->DebugMessage('Skipping $this->fltr['.$filterkey.'] ('.$filtercommand.') with ImageMagick', __FILE__, __LINE__); 2382 } 2383 } 2384 $this->DebugMessage('Remaining $this->fltr after ImageMagick: ('.$this->phpThumbDebugVarDump($this->fltr).')', __FILE__, __LINE__); 2385 if (count($this->fltr) > 0) { 2386 $this->useRawIMoutput = false; 2387 } 2388 2389 if (preg_match('#jpe?g#i', $outputFormat) && $this->q) { 2390 if ($this->ImageMagickSwitchAvailable(array('quality', 'interlace'))) { 2391 $commandline .= ' -quality '.phpthumb_functions::escapeshellarg_replacement($this->thumbnailQuality); 2392 if ($this->config_output_interlace) { 2393 // causes weird things with animated GIF... leave for JPEG only 2394 $commandline .= ' -interlace line '; // Use Line or Plane to create an interlaced PNG or GIF or progressive JPEG image 2395 } 2396 } 2397 } 2398 $commandline .= ' '.$outputFormat.':'.phpthumb_functions::escapeshellarg_replacement($IMtempfilename); 2399 if (!$this->iswindows) { 2400 $commandline .= ' 2>&1'; 2401 } 2402 $this->DebugMessage('ImageMagick called as ('.$commandline.')', __FILE__, __LINE__); 2403 $IMresult = phpthumb_functions::SafeExec($commandline); 2404 clearstatcache(); 2405 if (!@file_exists($IMtempfilename) || !@filesize($IMtempfilename)) { 2406 $this->FatalError('ImageMagick failed with message ('.trim($IMresult).')'); 2407 $this->DebugMessage('ImageMagick failed with message ('.trim($IMresult).')', __FILE__, __LINE__); 2408 if ($this->iswindows && !$IMresult) { 2409 $this->DebugMessage('Check to make sure that PHP has read+write permissions to "'.dirname($IMtempfilename).'"', __FILE__, __LINE__); 2410 } 2411 2412 } else { 2413 2414 foreach ($successfullyProcessedFilters as $dummy => $filterkey) { 2415 unset($this->fltr[$filterkey]); 2416 } 2417 $this->IMresizedData = file_get_contents($IMtempfilename); 2418 $getimagesize_imresized = @getimagesize($IMtempfilename); 2419 $this->DebugMessage('getimagesize('.$IMtempfilename.') returned [w='.$getimagesize_imresized[0].';h='.$getimagesize_imresized[1].';f='.$getimagesize_imresized[2].']', __FILE__, __LINE__); 2420 if (($this->config_max_source_pixels > 0) && (($getimagesize_imresized[0] * $getimagesize_imresized[1]) > $this->config_max_source_pixels)) { 2421 $this->DebugMessage('skipping ImageMagickThumbnailToGD::'.$ImageCreateFunction.'() because IM output is too large ('.$getimagesize_imresized[0].'x'.$getimagesize_imresized[0].' = '.($getimagesize_imresized[0] * $getimagesize_imresized[1]).' > '.$this->config_max_source_pixels.')', __FILE__, __LINE__); 2422 } elseif (function_exists(@$ImageCreateFunction) && ($this->gdimg_source = @$ImageCreateFunction($IMtempfilename))) { 2423 $this->source_width = imagesx($this->gdimg_source); 2424 $this->source_height = imagesy($this->gdimg_source); 2425 $this->DebugMessage('ImageMagickThumbnailToGD::'.$ImageCreateFunction.'() succeeded, $this->gdimg_source is now ('.$this->source_width.'x'.$this->source_height.')', __FILE__, __LINE__); 2426 $this->DebugMessage('ImageMagickThumbnailToGD() returning $this->IMresizedData ('.strlen($this->IMresizedData).' bytes)', __FILE__, __LINE__); 2427 } else { 2428 $this->useRawIMoutput = true; 2429 $this->DebugMessage('$this->useRawIMoutput set to TRUE because '.@$ImageCreateFunction.'('.$IMtempfilename.') failed', __FILE__, __LINE__); 2430 } 2431 if (file_exists($IMtempfilename)) { 2432 $this->DebugMessage('deleting "'.$IMtempfilename.'"', __FILE__, __LINE__); 2433 @unlink($IMtempfilename); 2434 } 2435 return true; 2436 2437 } 2438 if (file_exists($IMtempfilename)) { 2439 $this->DebugMessage('deleting "'.$IMtempfilename.'"', __FILE__, __LINE__); 2440 @unlink($IMtempfilename); 2441 } 2442 2443 } elseif ($this->issafemode) { 2444 $this->DebugMessage('ImageMagickThumbnailToGD() aborting because PHP safe_mode is enabled and phpThumb_tempnam() failed', __FILE__, __LINE__); 2445 $this->useRawIMoutput = false; 2446 } else { 2447 if (file_exists($IMtempfilename)) { 2448 $this->DebugMessage('deleting "'.$IMtempfilename.'"', __FILE__, __LINE__); 2449 @unlink($IMtempfilename); 2450 } 2451 $this->DebugMessage('ImageMagickThumbnailToGD() aborting, phpThumb_tempnam() failed', __FILE__, __LINE__); 2452 } 2453 } else { 2454 $this->DebugMessage('ImageMagickThumbnailToGD() aborting because ImageMagickCommandlineBase() failed', __FILE__, __LINE__); 2455 } 2456 $this->useRawIMoutput = false; 2457 return false; 2458 } 2459 2460 2461 public function Rotate() { 2462 if ($this->ra || $this->ar) { 2463 if (!function_exists('imagerotate')) { 2464 $this->DebugMessage('!function_exists(imagerotate)', __FILE__, __LINE__); 2465 return false; 2466 } 2467 if (!include_once __DIR__ .'/phpthumb.filters.php' ) { 2468 $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.filters.php" which is required for applying filters ('.implode(';', $this->fltr).')', __FILE__, __LINE__); 2469 return false; 2470 } 2471 2472 $this->config_background_hexcolor = ($this->bg ? $this->bg : $this->config_background_hexcolor); 2473 if (!phpthumb_functions::IsHexColor($this->config_background_hexcolor)) { 2474 return $this->ErrorImage('Invalid hex color string "'.$this->config_background_hexcolor.'" for parameter "bg"'); 2475 } 2476 2477 $rotate_angle = 0; 2478 if ($this->ra) { 2479 2480 $rotate_angle = (float) $this->ra; 2481 2482 } else { 2483 2484 if ($this->ar == 'x') { 2485 if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.2.0', '>=')) { 2486 if ($this->sourceFilename) { 2487 if (function_exists('exif_read_data')) { 2488 if ($exif_data = @exif_read_data($this->sourceFilename, 'IFD0')) { 2489 // http://sylvana.net/jpegcrop/exif_orientation.html 2490 switch (@$exif_data['Orientation']) { 2491 case 1: 2492 $rotate_angle = 0; 2493 break; 2494 case 3: 2495 $rotate_angle = 180; 2496 break; 2497 case 6: 2498 $rotate_angle = 270; 2499 break; 2500 case 8: 2501 $rotate_angle = 90; 2502 break; 2503 2504 default: 2505 $this->DebugMessage('EXIF auto-rotate failed because unknown $exif_data[Orientation] "'.@$exif_data['Orientation'].'"', __FILE__, __LINE__); 2506 return false; 2507 break; 2508 } 2509 $this->DebugMessage('EXIF auto-rotate set to '.$rotate_angle.' degrees ($exif_data[Orientation] = "'.@$exif_data['Orientation'].'")', __FILE__, __LINE__); 2510 } else { 2511 $this->DebugMessage('failed: exif_read_data('.$this->sourceFilename.')', __FILE__, __LINE__); 2512 return false; 2513 } 2514 } else { 2515 $this->DebugMessage('!function_exists(exif_read_data)', __FILE__, __LINE__); 2516 return false; 2517 } 2518 } else { 2519 $this->DebugMessage('Cannot auto-rotate from EXIF data because $this->sourceFilename is empty', __FILE__, __LINE__); 2520 return false; 2521 } 2522 } else { 2523 $this->DebugMessage('Cannot auto-rotate from EXIF data because PHP is less than v4.2.0 ('. PHP_VERSION .')', __FILE__, __LINE__); 2524 return false; 2525 } 2526 } elseif (($this->ar == 'l') && ($this->source_height > $this->source_width)) { 2527 $rotate_angle = 270; 2528 } elseif (($this->ar == 'L') && ($this->source_height > $this->source_width)) { 2529 $rotate_angle = 90; 2530 } elseif (($this->ar == 'p') && ($this->source_width > $this->source_height)) { 2531 $rotate_angle = 90; 2532 } elseif (($this->ar == 'P') && ($this->source_width > $this->source_height)) { 2533 $rotate_angle = 270; 2534 } 2535 2536 } 2537 if ($rotate_angle % 90) { 2538 $this->is_alpha = true; 2539 } 2540 phpthumb_filters::ImprovedImageRotate($this->gdimg_source, $rotate_angle, $this->config_background_hexcolor, $this->bg, $this); 2541 $this->source_width = imagesx($this->gdimg_source); 2542 $this->source_height = imagesy($this->gdimg_source); 2543 } 2544 return true; 2545 } 2546 2547 2548 public function FixedAspectRatio() { 2549 // optional fixed-dimension images (regardless of aspect ratio) 2550 2551 if (!$this->far) { 2552 // do nothing 2553 return true; 2554 } 2555 2556 if (!$this->w || !$this->h) { 2557 return false; 2558 } 2559 $this->thumbnail_width = $this->w; 2560 $this->thumbnail_height = $this->h; 2561 $this->is_alpha = true; 2562 if ($this->thumbnail_image_width >= $this->thumbnail_width) { 2563 2564 $aspectratio = $this->thumbnail_image_height / $this->thumbnail_image_width; 2565 if ($this->w) { 2566 $this->thumbnail_image_height = round($this->thumbnail_image_width * $aspectratio); 2567 $this->thumbnail_height = ($this->h ? $this->h : $this->thumbnail_image_height); 2568 } elseif ($this->thumbnail_image_height < $this->thumbnail_height) { 2569 $this->thumbnail_image_height = $this->thumbnail_height; 2570 $this->thumbnail_image_width = round($this->thumbnail_image_height / $aspectratio); 2571 } 2572 2573 } else { 2574 2575 $aspectratio = $this->thumbnail_image_width / $this->thumbnail_image_height; 2576 if ($this->h) { 2577 $this->thumbnail_image_width = round($this->thumbnail_image_height * $aspectratio); 2578 } elseif ($this->thumbnail_image_width < $this->thumbnail_width) { 2579 $this->thumbnail_image_width = $this->thumbnail_width; 2580 $this->thumbnail_image_height = round($this->thumbnail_image_width / $aspectratio); 2581 } 2582 2583 } 2584 return true; 2585 } 2586 2587 2588 public function OffsiteDomainIsAllowed($hostname, $allowed_domains) { 2589 static $domain_is_allowed = array(); 2590 $hostname = strtolower($hostname); 2591 if (!isset($domain_is_allowed[$hostname])) { 2592 $domain_is_allowed[$hostname] = false; 2593 foreach ($allowed_domains as $valid_domain) { 2594 $starpos = strpos($valid_domain, '*'); 2595 if ($starpos !== false) { 2596 $valid_domain = substr($valid_domain, $starpos + 1); 2597 if (preg_match('#'.preg_quote($valid_domain).'$#', $hostname)) { 2598 $domain_is_allowed[$hostname] = true; 2599 break; 2600 } 2601 } else { 2602 if (strtolower($valid_domain) === $hostname) { 2603 $domain_is_allowed[$hostname] = true; 2604 break; 2605 } 2606 } 2607 } 2608 } 2609 return $domain_is_allowed[$hostname]; 2610 } 2611 2612 2613 public function AntiOffsiteLinking() { 2614 // Optional anti-offsite hijacking of the thumbnail script 2615 $allow = true; 2616 if ($allow && $this->config_nooffsitelink_enabled && (@$_SERVER['HTTP_REFERER'] || $this->config_nooffsitelink_require_refer)) { 2617 $this->DebugMessage('AntiOffsiteLinking() checking $_SERVER[HTTP_REFERER] "'.@$_SERVER['HTTP_REFERER'].'"', __FILE__, __LINE__); 2618 foreach ($this->config_nooffsitelink_valid_domains as $key => $valid_domain) { 2619 // $_SERVER['HTTP_HOST'] contains the port number, so strip it out here to make default configuration work 2620 list($clean_domain) = explode(':', $valid_domain); 2621 $this->config_nooffsitelink_valid_domains[$key] = $clean_domain; 2622 } 2623 $parsed_url = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']); 2624 if (!$this->OffsiteDomainIsAllowed(@$parsed_url['host'], $this->config_nooffsitelink_valid_domains)) { 2625 $allow = false; 2626 //$this->DebugMessage('AntiOffsiteLinking() - "'.@$parsed_url['host'].'" is NOT in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__); 2627 $this->ErrorImage('AntiOffsiteLinking() - "'.@$parsed_url['host'].'" is NOT in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')'); 2628 } else { 2629 $this->DebugMessage('AntiOffsiteLinking() - "'.@$parsed_url['host'].'" is in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__); 2630 } 2631 } 2632 2633 if ($allow && $this->config_nohotlink_enabled && preg_match('#^(f|ht)tps?\://#i', $this->src)) { 2634 $parsed_url = phpthumb_functions::ParseURLbetter($this->src); 2635 //if (!phpthumb_functions::CaseInsensitiveInArray(@$parsed_url['host'], $this->config_nohotlink_valid_domains)) { 2636 if (!$this->OffsiteDomainIsAllowed(@$parsed_url['host'], $this->config_nohotlink_valid_domains)) { 2637 // This domain is not allowed 2638 $allow = false; 2639 $this->DebugMessage('AntiOffsiteLinking() - "'.$parsed_url['host'].'" is NOT in $this->config_nohotlink_valid_domains ('.implode(';', $this->config_nohotlink_valid_domains).')', __FILE__, __LINE__); 2640 } else { 2641 $this->DebugMessage('AntiOffsiteLinking() - "'.$parsed_url['host'].'" is in $this->config_nohotlink_valid_domains ('.implode(';', $this->config_nohotlink_valid_domains).')', __FILE__, __LINE__); 2642 } 2643 } 2644 2645 if ($allow) { 2646 $this->DebugMessage('AntiOffsiteLinking() says this is allowed', __FILE__, __LINE__); 2647 return true; 2648 } 2649 2650 if (!phpthumb_functions::IsHexColor($this->config_error_bgcolor)) { 2651 return $this->ErrorImage('Invalid hex color string "'.$this->config_error_bgcolor.'" for $this->config_error_bgcolor'); 2652 } 2653 if (!phpthumb_functions::IsHexColor($this->config_error_textcolor)) { 2654 return $this->ErrorImage('Invalid hex color string "'.$this->config_error_textcolor.'" for $this->config_error_textcolor'); 2655 } 2656 if ($this->config_nooffsitelink_erase_image) { 2657 2658 return $this->ErrorImage($this->config_nooffsitelink_text_message, $this->thumbnail_width, $this->thumbnail_height); 2659 2660 } else { 2661 2662 $this->config_nooffsitelink_watermark_src = $this->ResolveFilenameToAbsolute($this->config_nooffsitelink_watermark_src); 2663 if (is_file($this->config_nooffsitelink_watermark_src)) { 2664 2665 if (!include_once __DIR__ .'/phpthumb.filters.php' ) { 2666 $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.filters.php" which is required for applying watermark', __FILE__, __LINE__); 2667 return false; 2668 } 2669 $watermark_img = $this->ImageCreateFromStringReplacement(file_get_contents($this->config_nooffsitelink_watermark_src)); 2670 $phpthumbFilters = new phpthumb_filters(); 2671 $phpthumbFilters->phpThumbObject = &$this; 2672 $opacity = 50; 2673 $margin = 5; 2674 $phpthumbFilters->WatermarkOverlay($this->gdimg_output, $watermark_img, '*', $opacity, $margin); 2675 imagedestroy($watermark_img); 2676 unset($phpthumbFilters); 2677 2678 } else { 2679 2680 $nohotlink_text_array = explode("\n", wordwrap($this->config_nooffsitelink_text_message, floor($this->thumbnail_width / imagefontwidth($this->config_error_fontsize)), "\n")); 2681 $nohotlink_text_color = phpthumb_functions::ImageHexColorAllocate($this->gdimg_output, $this->config_error_textcolor); 2682 2683 $topoffset = round(($this->thumbnail_height - (count($nohotlink_text_array) * imagefontheight($this->config_error_fontsize))) / 2); 2684 2685 $rowcounter = 0; 2686 $this->DebugMessage('AntiOffsiteLinking() writing '.count($nohotlink_text_array).' lines of text "'.$this->config_nooffsitelink_text_message.'" (in #'.$this->config_error_textcolor.') on top of image', __FILE__, __LINE__); 2687 foreach ($nohotlink_text_array as $textline) { 2688 $leftoffset = max(0, round(($this->thumbnail_width - (strlen($textline) * imagefontwidth($this->config_error_fontsize))) / 2)); 2689 imagestring($this->gdimg_output, $this->config_error_fontsize, $leftoffset, $topoffset + ($rowcounter++ * imagefontheight($this->config_error_fontsize)), $textline, $nohotlink_text_color); 2690 } 2691 2692 } 2693 2694 } 2695 return true; 2696 } 2697 2698 2699 public function AlphaChannelFlatten() { 2700 if (!$this->is_alpha) { 2701 // image doesn't have alpha transparency, no need to flatten 2702 $this->DebugMessage('skipping AlphaChannelFlatten() because !$this->is_alpha', __FILE__, __LINE__); 2703 return false; 2704 } 2705 switch ($this->thumbnailFormat) { 2706 case 'png': 2707 case 'webp': 2708 case 'avif': 2709 case 'ico': 2710 // image has alpha transparency, but output as PNG, WEBP, AVIF, ICO which can handle it 2711 $this->DebugMessage('skipping AlphaChannelFlatten() because ($this->thumbnailFormat == "'.$this->thumbnailFormat.'")', __FILE__, __LINE__); 2712 return false; 2713 break; 2714 2715 case 'gif': 2716 // image has alpha transparency, but output as GIF which can handle only single-color transparency 2717 $CurrentImageColorTransparent = imagecolortransparent($this->gdimg_output); 2718 if ($CurrentImageColorTransparent == -1) { 2719 // no transparent color defined 2720 2721 if (phpthumb_functions::gd_version() < 2.0) { 2722 $this->DebugMessage('AlphaChannelFlatten() failed because GD version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 2723 return false; 2724 } 2725 2726 if ($img_alpha_mixdown_dither = @imagecreatetruecolor(imagesx($this->gdimg_output), imagesy($this->gdimg_output))) { 2727 2728 $dither_color = array(); 2729 for ($i = 0; $i <= 255; $i++) { 2730 $dither_color[$i] = imagecolorallocate($img_alpha_mixdown_dither, $i, $i, $i); 2731 } 2732 2733 // scan through current truecolor image copy alpha channel to temp image as grayscale 2734 for ($x = 0; $x < $this->thumbnail_width; $x++) { 2735 for ($y = 0; $y < $this->thumbnail_height; $y++) { 2736 $PixelColor = phpthumb_functions::GetPixelColor($this->gdimg_output, $x, $y); 2737 imagesetpixel($img_alpha_mixdown_dither, $x, $y, $dither_color[ $PixelColor[ 'alpha'] * 2 ]); 2738 } 2739 } 2740 2741 // dither alpha channel grayscale version down to 2 colors 2742 imagetruecolortopalette($img_alpha_mixdown_dither, true, 2); 2743 2744 // reduce color palette to 256-1 colors (leave one palette position for transparent color) 2745 imagetruecolortopalette($this->gdimg_output, true, 255); 2746 2747 // allocate a new color for transparent color index 2748 $TransparentColor = imagecolorallocate($this->gdimg_output, 1, 254, 253); 2749 imagecolortransparent($this->gdimg_output, $TransparentColor); 2750 2751 // scan through alpha channel image and note pixels with >50% transparency 2752 for ($x = 0; $x < $this->thumbnail_width; $x++) { 2753 for ($y = 0; $y < $this->thumbnail_height; $y++) { 2754 $AlphaChannelPixel = phpthumb_functions::GetPixelColor($img_alpha_mixdown_dither, $x, $y); 2755 if ($AlphaChannelPixel['red'] > 127) { 2756 imagesetpixel($this->gdimg_output, $x, $y, $TransparentColor); 2757 } 2758 } 2759 } 2760 imagedestroy($img_alpha_mixdown_dither); 2761 2762 $this->DebugMessage('AlphaChannelFlatten() set image to 255+1 colors with transparency for GIF output', __FILE__, __LINE__); 2763 return true; 2764 2765 } else { 2766 $this->DebugMessage('AlphaChannelFlatten() failed imagecreate('.imagesx($this->gdimg_output).', '.imagesy($this->gdimg_output).')', __FILE__, __LINE__); 2767 return false; 2768 } 2769 2770 } else { 2771 // a single transparent color already defined, leave as-is 2772 $this->DebugMessage('skipping AlphaChannelFlatten() because ($this->thumbnailFormat == "'.$this->thumbnailFormat.'") and imagecolortransparent() returned "'.$CurrentImageColorTransparent.'"', __FILE__, __LINE__); 2773 return true; 2774 } 2775 break; 2776 } 2777 $this->DebugMessage('continuing AlphaChannelFlatten() for output format "'.$this->thumbnailFormat.'"', __FILE__, __LINE__); 2778 // image has alpha transparency, and is being output in a format that doesn't support it -- flatten 2779 if ($gdimg_flatten_temp = phpthumb_functions::ImageCreateFunction($this->thumbnail_width, $this->thumbnail_height)) { 2780 2781 $this->config_background_hexcolor = ($this->bg ? $this->bg : $this->config_background_hexcolor); 2782 if (!phpthumb_functions::IsHexColor($this->config_background_hexcolor)) { 2783 return $this->ErrorImage('Invalid hex color string "'.$this->config_background_hexcolor.'" for parameter "bg"'); 2784 } 2785 $background_color = phpthumb_functions::ImageHexColorAllocate($this->gdimg_output, $this->config_background_hexcolor); 2786 imagefilledrectangle($gdimg_flatten_temp, 0, 0, $this->thumbnail_width, $this->thumbnail_height, $background_color); 2787 imagecopy($gdimg_flatten_temp, $this->gdimg_output, 0, 0, 0, 0, $this->thumbnail_width, $this->thumbnail_height); 2788 2789 imagealphablending($this->gdimg_output, true); 2790 imagesavealpha($this->gdimg_output, false); 2791 imagecolortransparent($this->gdimg_output, -1); 2792 imagecopy($this->gdimg_output, $gdimg_flatten_temp, 0, 0, 0, 0, $this->thumbnail_width, $this->thumbnail_height); 2793 2794 imagedestroy($gdimg_flatten_temp); 2795 return true; 2796 2797 } else { 2798 $this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__); 2799 } 2800 return false; 2801 } 2802 2803 2804 public function ApplyFilters() { 2805 if ($this->fltr && is_array($this->fltr)) { 2806 if (!include_once __DIR__ .'/phpthumb.filters.php' ) { 2807 $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.filters.php" which is required for applying filters ('.implode(';', $this->fltr).')', __FILE__, __LINE__); 2808 return false; 2809 } 2810 $phpthumbFilters = new phpthumb_filters(); 2811 $phpthumbFilters->phpThumbObject = &$this; 2812 foreach ($this->fltr as $filtercommand) { 2813 @list($command, $parameter) = explode('|', $filtercommand, 2); 2814 $this->DebugMessage('Attempting to process filter command "'.$command.'('.$parameter.')"', __FILE__, __LINE__); 2815 switch ($command) { 2816 case 'brit': // Brightness 2817 $phpthumbFilters->Brightness($this->gdimg_output, $parameter); 2818 break; 2819 2820 case 'cont': // Contrast 2821 $phpthumbFilters->Contrast($this->gdimg_output, $parameter); 2822 break; 2823 2824 case 'ds': // Desaturation 2825 $phpthumbFilters->Desaturate($this->gdimg_output, $parameter, ''); 2826 break; 2827 2828 case 'sat': // Saturation 2829 $phpthumbFilters->Saturation($this->gdimg_output, $parameter, ''); 2830 break; 2831 2832 case 'gray': // Grayscale 2833 $phpthumbFilters->Grayscale($this->gdimg_output); 2834 break; 2835 2836 case 'clr': // Colorize 2837 if (phpthumb_functions::gd_version() < 2) { 2838 $this->DebugMessage('Skipping Colorize() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 2839 break; 2840 } 2841 @list($amount, $color) = explode('|', $parameter, 2); 2842 $phpthumbFilters->Colorize($this->gdimg_output, $amount, $color); 2843 break; 2844 2845 case 'sep': // Sepia 2846 if (phpthumb_functions::gd_version() < 2) { 2847 $this->DebugMessage('Skipping Sepia() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 2848 break; 2849 } 2850 @list($amount, $color) = explode('|', $parameter, 2); 2851 $phpthumbFilters->Sepia($this->gdimg_output, $amount, $color); 2852 break; 2853 2854 case 'gam': // Gamma correction 2855 $phpthumbFilters->Gamma($this->gdimg_output, $parameter); 2856 break; 2857 2858 case 'neg': // Negative colors 2859 $phpthumbFilters->Negative($this->gdimg_output); 2860 break; 2861 2862 case 'th': // Threshold 2863 $phpthumbFilters->Threshold($this->gdimg_output, $parameter); 2864 break; 2865 2866 case 'rcd': // ReduceColorDepth 2867 if (phpthumb_functions::gd_version() < 2) { 2868 $this->DebugMessage('Skipping ReduceColorDepth() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 2869 break; 2870 } 2871 @list($colors, $dither) = explode('|', $parameter, 2); 2872 $colors = ($colors ? (int) $colors : 256); 2873 $dither = ((strlen($dither) > 0) ? (bool) $dither : true); 2874 $phpthumbFilters->ReduceColorDepth($this->gdimg_output, $colors, $dither); 2875 break; 2876 2877 case 'flip': // Flip 2878 $phpthumbFilters->Flip($this->gdimg_output, strpos(strtolower($parameter), 'x') !== false, strpos(strtolower($parameter), 'y') !== false); 2879 break; 2880 2881 case 'edge': // EdgeDetect 2882 $phpthumbFilters->EdgeDetect($this->gdimg_output); 2883 break; 2884 2885 case 'emb': // Emboss 2886 $phpthumbFilters->Emboss($this->gdimg_output); 2887 break; 2888 2889 case 'bvl': // Bevel 2890 @list($width, $color1, $color2) = explode('|', $parameter, 3); 2891 $phpthumbFilters->Bevel($this->gdimg_output, $width, $color1, $color2); 2892 break; 2893 2894 case 'lvl': // autoLevels 2895 @list($band, $method, $threshold) = explode('|', $parameter, 3); 2896 $band = ($band ? preg_replace('#[^RGBA\\*]#', '', strtoupper($band)) : '*'); 2897 $method = ((strlen($method) > 0) ? (int) $method : 2); 2898 $threshold = ((strlen($threshold) > 0) ? (float) $threshold : 0.1); 2899 2900 $phpthumbFilters->HistogramStretch($this->gdimg_output, $band, $method, $threshold); 2901 break; 2902 2903 case 'wb': // WhiteBalance 2904 $phpthumbFilters->WhiteBalance($this->gdimg_output, $parameter); 2905 break; 2906 2907 case 'hist': // Histogram overlay 2908 if (phpthumb_functions::gd_version() < 2) { 2909 $this->DebugMessage('Skipping HistogramOverlay() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 2910 break; 2911 } 2912 @list($bands, $colors, $width, $height, $alignment, $opacity, $margin_x, $margin_y) = explode('|', $parameter, 8); 2913 $bands = ($bands ? $bands : '*'); 2914 $colors = ($colors ? $colors : ''); 2915 $width = ($width ? $width : 0.25); 2916 $height = ($height ? $height : 0.25); 2917 $alignment = ($alignment ? $alignment : 'BR'); 2918 $opacity = ($opacity ? $opacity : 50); 2919 $margin_x = ($margin_x ? $margin_x : 5); 2920 // $margin_y -- it wasn't forgotten, let the value always pass unchanged 2921 $phpthumbFilters->HistogramOverlay($this->gdimg_output, $bands, $colors, $width, $height, $alignment, $opacity, $margin_x, $margin_y); 2922 break; 2923 2924 case 'fram': // Frame 2925 @list($frame_width, $edge_width, $color_frame, $color1, $color2) = explode('|', $parameter, 5); 2926 $phpthumbFilters->Frame($this->gdimg_output, $frame_width, $edge_width, $color_frame, $color1, $color2); 2927 break; 2928 2929 case 'drop': // DropShadow 2930 if (phpthumb_functions::gd_version() < 2) { 2931 $this->DebugMessage('Skipping DropShadow() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 2932 return false; 2933 } 2934 $this->is_alpha = true; 2935 @list($distance, $width, $color, $angle, $fade) = explode('|', $parameter, 5); 2936 $phpthumbFilters->DropShadow($this->gdimg_output, $distance, $width, $color, $angle, $fade); 2937 break; 2938 2939 case 'mask': // Mask cropping 2940 if (phpthumb_functions::gd_version() < 2) { 2941 $this->DebugMessage('Skipping Mask() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 2942 return false; 2943 } 2944 @list($mask_filename, $invert) = explode('|', $parameter, 2); 2945 $mask_filename = $this->ResolveFilenameToAbsolute($mask_filename); 2946 if (@is_readable($mask_filename) && ($fp_mask = @fopen($mask_filename, 'rb'))) { 2947 $MaskImageData = ''; 2948 do { 2949 $buffer = fread($fp_mask, 8192); 2950 $MaskImageData .= $buffer; 2951 } while (strlen($buffer) > 0); 2952 fclose($fp_mask); 2953 if ($gdimg_mask = $this->ImageCreateFromStringReplacement($MaskImageData)) { 2954 if ($invert && phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) { 2955 imagefilter($gdimg_mask, IMG_FILTER_NEGATE); 2956 } 2957 $this->is_alpha = true; 2958 $phpthumbFilters->ApplyMask($gdimg_mask, $this->gdimg_output); 2959 imagedestroy($gdimg_mask); 2960 } else { 2961 $this->DebugMessage('ImageCreateFromStringReplacement() failed for "'.$mask_filename.'"', __FILE__, __LINE__); 2962 } 2963 } else { 2964 $this->DebugMessage('Cannot open mask file "'.$mask_filename.'"', __FILE__, __LINE__); 2965 } 2966 break; 2967 2968 case 'elip': // Ellipse cropping 2969 if (phpthumb_functions::gd_version() < 2) { 2970 $this->DebugMessage('Skipping Ellipse() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 2971 return false; 2972 } 2973 $this->is_alpha = true; 2974 $phpthumbFilters->Ellipse($this->gdimg_output); 2975 break; 2976 2977 case 'ric': // RoundedImageCorners 2978 if (phpthumb_functions::gd_version() < 2) { 2979 $this->DebugMessage('Skipping RoundedImageCorners() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 2980 return false; 2981 } 2982 @list($radius_x, $radius_y) = explode('|', $parameter, 2); 2983 if (($radius_x < 1) || ($radius_y < 1)) { 2984 $this->DebugMessage('Skipping RoundedImageCorners('.$radius_x.', '.$radius_y.') because x/y radius is less than 1', __FILE__, __LINE__); 2985 break; 2986 } 2987 $this->is_alpha = true; 2988 $phpthumbFilters->RoundedImageCorners($this->gdimg_output, $radius_x, $radius_y); 2989 break; 2990 2991 case 'crop': // Crop 2992 @list($left, $right, $top, $bottom) = explode('|', $parameter, 4); 2993 $phpthumbFilters->Crop($this->gdimg_output, $left, $right, $top, $bottom); 2994 break; 2995 2996 case 'bord': // Border 2997 @list($border_width, $radius_x, $radius_y, $hexcolor_border) = explode('|', $parameter, 4); 2998 $this->is_alpha = true; 2999 $phpthumbFilters->ImageBorder($this->gdimg_output, $border_width, $radius_x, $radius_y, $hexcolor_border); 3000 break; 3001 3002 case 'over': // Overlay 3003 @list($filename, $underlay, $margin, $opacity) = explode('|', $parameter, 4); 3004 $underlay = (bool) ($underlay ? $underlay : false); 3005 $margin = ((strlen($margin) > 0) ? $margin : ($underlay ? 0.1 : 0.0)); 3006 $opacity = ((strlen($opacity) > 0) ? $opacity : 100); 3007 if (($margin > 0) && ($margin < 1)) { 3008 $margin = min(0.499, $margin); 3009 } elseif (($margin > -1) && ($margin < 0)) { 3010 $margin = max(-0.499, $margin); 3011 } 3012 3013 $filename = $this->ResolveFilenameToAbsolute($filename); 3014 if (@is_readable($filename) && ($fp_watermark = @fopen($filename, 'rb'))) { 3015 $WatermarkImageData = ''; 3016 do { 3017 $buffer = fread($fp_watermark, 8192); 3018 $WatermarkImageData .= $buffer; 3019 } while (strlen($buffer) > 0); 3020 fclose($fp_watermark); 3021 if ($img_watermark = $this->ImageCreateFromStringReplacement($WatermarkImageData)) { 3022 if (($margin > 0) && ($margin < 1)) { 3023 $resized_x = max(1, imagesx($this->gdimg_output) - round(2 * (imagesx($this->gdimg_output) * $margin))); 3024 $resized_y = max(1, imagesy($this->gdimg_output) - round(2 * (imagesy($this->gdimg_output) * $margin))); 3025 } else { 3026 $resized_x = max(1, imagesx($this->gdimg_output) - round(2 * $margin)); 3027 $resized_y = max(1, imagesy($this->gdimg_output) - round(2 * $margin)); 3028 } 3029 3030 if ($underlay) { 3031 3032 if ($img_watermark_resized = phpthumb_functions::ImageCreateFunction(imagesx($this->gdimg_output), imagesy($this->gdimg_output))) { 3033 imagealphablending($img_watermark_resized, false); 3034 imagesavealpha($img_watermark_resized, true); 3035 $this->ImageResizeFunction($img_watermark_resized, $img_watermark, 0, 0, 0, 0, imagesx($img_watermark_resized), imagesy($img_watermark_resized), imagesx($img_watermark), imagesy($img_watermark)); 3036 if ($img_source_resized = phpthumb_functions::ImageCreateFunction($resized_x, $resized_y)) { 3037 imagealphablending($img_source_resized, false); 3038 imagesavealpha($img_source_resized, true); 3039 $this->ImageResizeFunction($img_source_resized, $this->gdimg_output, 0, 0, 0, 0, imagesx($img_source_resized), imagesy($img_source_resized), imagesx($this->gdimg_output), imagesy($this->gdimg_output)); 3040 $phpthumbFilters->WatermarkOverlay($img_watermark_resized, $img_source_resized, 'C', $opacity, $margin); 3041 imagecopy($this->gdimg_output, $img_watermark_resized, 0, 0, 0, 0, imagesx($this->gdimg_output), imagesy($this->gdimg_output)); 3042 } else { 3043 $this->DebugMessage('phpthumb_functions::ImageCreateFunction('.$resized_x.', '.$resized_y.')', __FILE__, __LINE__); 3044 } 3045 imagedestroy($img_watermark_resized); 3046 } else { 3047 $this->DebugMessage('phpthumb_functions::ImageCreateFunction('.imagesx($this->gdimg_output).', '.imagesy($this->gdimg_output).')', __FILE__, __LINE__); 3048 } 3049 3050 } else { // overlay 3051 3052 if ($img_watermark_resized = phpthumb_functions::ImageCreateFunction($resized_x, $resized_y)) { 3053 imagealphablending($img_watermark_resized, false); 3054 imagesavealpha($img_watermark_resized, true); 3055 $this->ImageResizeFunction($img_watermark_resized, $img_watermark, 0, 0, 0, 0, imagesx($img_watermark_resized), imagesy($img_watermark_resized), imagesx($img_watermark), imagesy($img_watermark)); 3056 $phpthumbFilters->WatermarkOverlay($this->gdimg_output, $img_watermark_resized, 'C', $opacity, $margin); 3057 imagedestroy($img_watermark_resized); 3058 } else { 3059 $this->DebugMessage('phpthumb_functions::ImageCreateFunction('.$resized_x.', '.$resized_y.')', __FILE__, __LINE__); 3060 } 3061 3062 } 3063 imagedestroy($img_watermark); 3064 3065 } else { 3066 $this->DebugMessage('ImageCreateFromStringReplacement() failed for "'.$filename.'"', __FILE__, __LINE__); 3067 } 3068 } else { 3069 $this->DebugMessage('Cannot open overlay file "'.$filename.'"', __FILE__, __LINE__); 3070 } 3071 break; 3072 3073 case 'wmi': // WaterMarkImage 3074 @list($filename, $alignment, $opacity, $margin['x'], $margin['y'], $rotate_angle) = explode('|', $parameter, 6); 3075 // $margin can be pixel margin or percent margin if $alignment is text, or max width/height if $alignment is position like "50x75" 3076 $alignment = ($alignment ? $alignment : 'BR'); 3077 $opacity = ('' != $opacity ? (int) $opacity : 50); 3078 $rotate_angle = ('' != $rotate_angle ? (int) $rotate_angle : 0); 3079 if (!preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)$#i', $alignment, $matches)) { 3080 $margins = array('x', 'y'); 3081 foreach ($margins as $xy) { 3082 $margin[$xy] = ('' !== $margin[ $xy ] ? $margin[ $xy] : 5); 3083 if (($margin[$xy] > 0) && ($margin[$xy] < 1)) { 3084 $margin[$xy] = min(0.499, $margin[$xy]); 3085 } elseif (($margin[$xy] > -1) && ($margin[$xy] < 0)) { 3086 $margin[$xy] = max(-0.499, $margin[$xy]); 3087 } 3088 } 3089 } 3090 3091 $filename = $this->ResolveFilenameToAbsolute($filename); 3092 if (@is_readable($filename)) { 3093 if ($img_watermark = $this->ImageCreateFromFilename($filename)) { 3094 if ($rotate_angle !== 0) { 3095 $phpthumbFilters->ImprovedImageRotate($img_watermark, $rotate_angle, 'FFFFFF', null, $this); 3096 } 3097 if (preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)$#i', $alignment, $matches)) { 3098 $watermark_max_width = (int) ($margin[ 'x'] ? $margin[ 'x'] : imagesx($img_watermark)); 3099 $watermark_max_height = (int) ($margin[ 'y'] ? $margin[ 'y'] : imagesy($img_watermark)); 3100 $scale = phpthumb_functions::ScaleToFitInBox(imagesx($img_watermark), imagesy($img_watermark), $watermark_max_width, $watermark_max_height, true, true); 3101 $this->DebugMessage('Scaling watermark by a factor of '.number_format($scale, 4), __FILE__, __LINE__); 3102 if (($scale > 1) || ($scale < 1)) { 3103 if ($img_watermark2 = phpthumb_functions::ImageCreateFunction($scale * imagesx($img_watermark), $scale * imagesy($img_watermark))) { 3104 imagealphablending($img_watermark2, false); 3105 imagesavealpha($img_watermark2, true); 3106 $this->ImageResizeFunction($img_watermark2, $img_watermark, 0, 0, 0, 0, imagesx($img_watermark2), imagesy($img_watermark2), imagesx($img_watermark), imagesy($img_watermark)); 3107 $img_watermark = $img_watermark2; 3108 } else { 3109 $this->DebugMessage('ImageCreateFunction('.($scale * imagesx($img_watermark)).', '.($scale * imagesx($img_watermark)).') failed', __FILE__, __LINE__); 3110 } 3111 } 3112 $watermark_dest_x = round($matches[1] - (imagesx($img_watermark) / 2)); 3113 $watermark_dest_y = round($matches[2] - (imagesy($img_watermark) / 2)); 3114 $alignment = $watermark_dest_x.'x'.$watermark_dest_y; 3115 } 3116 $phpthumbFilters->WatermarkOverlay($this->gdimg_output, $img_watermark, $alignment, $opacity, $margin['x'], $margin['y']); 3117 imagedestroy($img_watermark); 3118 if (isset($img_watermark2) && (is_resource($img_watermark2) || (is_object($img_watermark2) && $img_watermark2 instanceOf \GdImage))) { 3119 imagedestroy($img_watermark2); 3120 } 3121 } else { 3122 $this->DebugMessage('ImageCreateFromFilename() failed for "'.$filename.'"', __FILE__, __LINE__); 3123 } 3124 } else { 3125 $this->DebugMessage('!is_readable('.$filename.')', __FILE__, __LINE__); 3126 } 3127 break; 3128 3129 case 'wmt': // WaterMarkText 3130 @list($text, $size, $alignment, $hex_color, $ttffont, $opacity, $margin, $angle, $bg_color, $bg_opacity, $fillextend, $lineheight) = explode('|', $parameter, 12); 3131 $text = ($text ? $text : ''); 3132 $size = ($size ? $size : 3); 3133 $alignment = ($alignment ? $alignment : 'BR'); 3134 $hex_color = ($hex_color ? $hex_color : '000000'); 3135 $ttffont = ($ttffont ? $ttffont : ''); 3136 $opacity = ('' != $opacity ? $opacity : 50); 3137 $margin = ('' != $margin ? $margin : 5); 3138 $angle = ('' != $angle ? $angle : 0); 3139 $bg_color = ($bg_color ? $bg_color : false); 3140 $bg_opacity = ($bg_opacity ? $bg_opacity : 0); 3141 $fillextend = ($fillextend ? $fillextend : ''); 3142 $lineheight = ($lineheight ? $lineheight : 1.0); 3143 3144 if (basename($ttffont) == $ttffont) { 3145 $ttffont = $this->realPathSafe($this->config_ttf_directory.DIRECTORY_SEPARATOR.$ttffont); 3146 } else { 3147 $ttffont = $this->ResolveFilenameToAbsolute($ttffont); 3148 } 3149 $phpthumbFilters->WatermarkText($this->gdimg_output, $text, $size, $alignment, $hex_color, $ttffont, $opacity, $margin, $angle, $bg_color, $bg_opacity, $fillextend, $lineheight); 3150 break; 3151 3152 case 'blur': // Blur 3153 @list($radius) = explode('|', $parameter, 1); 3154 $radius = ($radius ? $radius : 1); 3155 if (phpthumb_functions::gd_version() >= 2) { 3156 $phpthumbFilters->Blur($this->gdimg_output, $radius); 3157 } else { 3158 $this->DebugMessage('Skipping Blur() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__); 3159 } 3160 break; 3161 3162 case 'gblr': // Gaussian Blur 3163 $phpthumbFilters->BlurGaussian($this->gdimg_output); 3164 break; 3165 3166 case 'sblr': // Selective Blur 3167 $phpthumbFilters->BlurSelective($this->gdimg_output); 3168 break; 3169 3170 case 'mean': // MeanRemoval blur 3171 $phpthumbFilters->MeanRemoval($this->gdimg_output); 3172 break; 3173 3174 case 'smth': // Smooth blur 3175 $phpthumbFilters->Smooth($this->gdimg_output, $parameter); 3176 break; 3177 3178 case 'usm': // UnSharpMask sharpening