PageRenderTime 87ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/core/model/phpthumb/phpthumb.class.php

http://github.com/modxcms/revolution
PHP | 4443 lines | 3658 code | 487 blank | 298 comment | 873 complexity | 7c87218066514b922c8b6d56f41cd943 MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, BSD-3-Clause, LGPL-2.1
  1. <?php
  2. //////////////////////////////////////////////////////////////
  3. // phpThumb() by James Heinrich <info@silisoftware.com> //
  4. // available at http://phpthumb.sourceforge.net //
  5. // and/or https://github.com/JamesHeinrich/phpThumb //
  6. //////////////////////////////////////////////////////////////
  7. /// //
  8. // See: phpthumb.readme.txt for usage instructions //
  9. // ///
  10. //////////////////////////////////////////////////////////////
  11. if (!class_exists('phpthumb_functions'))
  12. {
  13. ob_start();
  14. if(!include_once __DIR__ . '/phpthumb.functions.php')
  15. {
  16. ob_end_flush();
  17. die('failed to include_once("' . __DIR__ . '/phpthumb.functions.php")');
  18. }
  19. ob_end_clean();
  20. }
  21. class phpthumb {
  22. // public:
  23. // START PARAMETERS (for object mode and phpThumb.php)
  24. // See phpthumb.readme.txt for descriptions of what each of these values are
  25. public $src = null; // SouRCe filename
  26. public $new = null; // NEW image (phpThumb.php only)
  27. public $w = null; // Width
  28. public $h = null; // Height
  29. public $wp = null; // Width (Portrait Images Only)
  30. public $hp = null; // Height (Portrait Images Only)
  31. public $wl = null; // Width (Landscape Images Only)
  32. public $hl = null; // Height (Landscape Images Only)
  33. public $ws = null; // Width (Square Images Only)
  34. public $hs = null; // Height (Square Images Only)
  35. public $f = null; // output image Format
  36. public $q = 75; // jpeg output Quality
  37. public $sx = null; // Source crop top-left X position
  38. public $sy = null; // Source crop top-left Y position
  39. public $sw = null; // Source crop Width
  40. public $sh = null; // Source crop Height
  41. public $zc = null; // Zoom Crop
  42. public $bc = null; // Border Color
  43. public $bg = null; // BackGround color
  44. public $fltr = array(); // FiLTeRs
  45. public $goto = null; // GO TO url after processing
  46. public $err = null; // default ERRor image filename
  47. public $xto = null; // extract eXif Thumbnail Only
  48. public $ra = null; // Rotate by Angle
  49. public $ar = null; // Auto Rotate
  50. public $aoe = null; // Allow Output Enlargement
  51. public $far = null; // Fixed Aspect Ratio
  52. public $iar = null; // Ignore Aspect Ratio
  53. public $maxb = null; // MAXimum Bytes
  54. public $down = null; // DOWNload thumbnail filename
  55. public $md5s = null; // MD5 hash of Source image
  56. public $sfn = 0; // Source Frame Number
  57. public $dpi = 150; // Dots Per Inch for vector source formats
  58. public $sia = null; // Save Image As filename
  59. public $file = null; // >>>deprecated, DO NOT USE, will be removed in future versions<<<
  60. public $phpThumbDebug = null;
  61. // END PARAMETERS
  62. // public:
  63. // START CONFIGURATION OPTIONS (for object mode only)
  64. // See phpThumb.config.php for descriptions of what each of these settings do
  65. // * Directory Configuration
  66. public $config_cache_directory = null;
  67. public $config_cache_directory_depth = 0;
  68. public $config_cache_disable_warning = true;
  69. public $config_cache_source_enabled = false;
  70. public $config_cache_source_directory = null;
  71. public $config_temp_directory = null;
  72. public $config_document_root = null;
  73. // * Default output configuration:
  74. public $config_output_format = 'jpeg';
  75. public $config_output_maxwidth = 0;
  76. public $config_output_maxheight = 0;
  77. public $config_output_interlace = true;
  78. // * Error message configuration
  79. public $config_error_image_width = 400;
  80. public $config_error_image_height = 100;
  81. public $config_error_message_image_default = '';
  82. public $config_error_bgcolor = 'CCCCFF';
  83. public $config_error_textcolor = 'FF0000';
  84. public $config_error_fontsize = 1;
  85. public $config_error_die_on_error = false;
  86. public $config_error_silent_die_on_error = false;
  87. public $config_error_die_on_source_failure = true;
  88. // * Anti-Hotlink Configuration:
  89. public $config_nohotlink_enabled = true;
  90. public $config_nohotlink_valid_domains = array();
  91. public $config_nohotlink_erase_image = true;
  92. public $config_nohotlink_text_message = 'Off-server thumbnailing is not allowed';
  93. // * Off-server Linking Configuration:
  94. public $config_nooffsitelink_enabled = false;
  95. public $config_nooffsitelink_valid_domains = array();
  96. public $config_nooffsitelink_require_refer = false;
  97. public $config_nooffsitelink_erase_image = true;
  98. public $config_nooffsitelink_watermark_src = '';
  99. public $config_nooffsitelink_text_message = 'Off-server linking is not allowed';
  100. // * Border & Background default colors
  101. public $config_border_hexcolor = '000000';
  102. public $config_background_hexcolor = 'FFFFFF';
  103. // * TrueType Fonts
  104. public $config_ttf_directory = './fonts';
  105. public $config_max_source_pixels = null;
  106. public $config_use_exif_thumbnail_for_speed = false;
  107. public $config_allow_local_http_src = false;
  108. public $config_imagemagick_path = null;
  109. public $config_prefer_imagemagick = true;
  110. public $config_imagemagick_use_thumbnail = true;
  111. public $config_cache_maxage = null;
  112. public $config_cache_maxsize = null;
  113. public $config_cache_maxfiles = null;
  114. public $config_cache_source_filemtime_ignore_local = false;
  115. public $config_cache_source_filemtime_ignore_remote = true;
  116. public $config_cache_default_only_suffix = false;
  117. public $config_cache_force_passthru = true;
  118. public $config_cache_prefix = ''; // default value set in the constructor below
  119. // * MySQL
  120. public $config_mysql_extension = null;
  121. public $config_mysql_query = null;
  122. public $config_mysql_hostname = null;
  123. public $config_mysql_username = null;
  124. public $config_mysql_password = null;
  125. public $config_mysql_database = null;
  126. // * Security
  127. public $config_high_security_enabled = true;
  128. public $config_high_security_password = null;
  129. public $config_high_security_url_separator = '&';
  130. public $config_disable_debug = true;
  131. public $config_allow_src_above_docroot = false;
  132. public $config_allow_src_above_phpthumb = true;
  133. public $config_auto_allow_symlinks = true; // allow symlink target directories without explicitly whitelisting them
  134. public $config_additional_allowed_dirs = array(); // additional directories to allow source images to be read from
  135. public $config_file_create_mask = 0755;
  136. public $config_dir_create_mask = 0755;
  137. // * HTTP fopen
  138. public $config_http_fopen_timeout = 10;
  139. public $config_http_follow_redirect = true;
  140. // * Compatability
  141. public $config_disable_pathinfo_parsing = false;
  142. public $config_disable_imagecopyresampled = false;
  143. public $config_disable_onlycreateable_passthru = false;
  144. public $config_disable_realpath = false;
  145. 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';
  146. // END CONFIGURATION OPTIONS
  147. // public: error messages (read-only; persistant)
  148. public $debugmessages = array();
  149. public $debugtiming = array();
  150. public $fatalerror = null;
  151. // private: (should not be modified directly)
  152. public $thumbnailQuality = 75;
  153. public $thumbnailFormat = null;
  154. public $sourceFilename = null;
  155. public $rawImageData = null;
  156. public $IMresizedData = null;
  157. public $outputImageData = null;
  158. public $useRawIMoutput = false;
  159. public $gdimg_output = null;
  160. public $gdimg_source = null;
  161. public $getimagesizeinfo = null;
  162. public $source_width = null;
  163. public $source_height = null;
  164. public $thumbnailCropX = null;
  165. public $thumbnailCropY = null;
  166. public $thumbnailCropW = null;
  167. public $thumbnailCropH = null;
  168. public $exif_thumbnail_width = null;
  169. public $exif_thumbnail_height = null;
  170. public $exif_thumbnail_type = null;
  171. public $exif_thumbnail_data = null;
  172. public $exif_raw_data = null;
  173. public $thumbnail_width = null;
  174. public $thumbnail_height = null;
  175. public $thumbnail_image_width = null;
  176. public $thumbnail_image_height = null;
  177. public $tempFilesToDelete = array();
  178. public $cache_filename = null;
  179. public $AlphaCapableFormats = array( 'png', 'ico', 'gif', 'webp');
  180. public $is_alpha = false;
  181. public $iswindows = null;
  182. public $issafemode = null;
  183. public $php_memory_limit = null;
  184. public $phpthumb_version = '1.7.15-202004301145';
  185. //////////////////////////////////////////////////////////////////////
  186. // public: constructor
  187. public function __construct() {
  188. $this->phpThumb();
  189. }
  190. public function phpThumb() {
  191. $this->DebugTimingMessage('phpThumb() constructor', __FILE__, __LINE__);
  192. $this->DebugMessage('phpThumb() v'.$this->phpthumb_version, __FILE__, __LINE__);
  193. foreach (array(ini_get('memory_limit'), get_cfg_var('memory_limit')) as $php_config_memory_limit) {
  194. if ('' !== $php_config_memory_limit) {
  195. if (strtoupper($php_config_memory_limit[ strlen($php_config_memory_limit) - 1 ]) == 'G') { // PHP memory limit expressed in Gigabytes
  196. $php_config_memory_limit = (int) substr($php_config_memory_limit, 0, -1) * 1073741824;
  197. } elseif (strtoupper($php_config_memory_limit[ strlen($php_config_memory_limit) - 1 ]) == 'M') { // PHP memory limit expressed in Megabytes
  198. $php_config_memory_limit = (int) substr($php_config_memory_limit, 0, -1) * 1048576;
  199. }
  200. $this->php_memory_limit = max($this->php_memory_limit, $php_config_memory_limit);
  201. }
  202. }
  203. if ($this->php_memory_limit > 0) { // could be "-1" for "no limit"
  204. $this->config_max_source_pixels = round($this->php_memory_limit * 0.20); // 20% of memory_limit
  205. }
  206. $this->iswindows = (bool) (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN');
  207. $this->issafemode = (bool) preg_match('#(1|ON)#i', ini_get('safe_mode'));
  208. $this->config_document_root = (!empty($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : $this->config_document_root);
  209. $this->config_cache_prefix = ( isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'].'_' : '');
  210. $this->purgeTempFiles(); // purge existing temp files if re-initializing object
  211. $php_sapi_name = strtolower(function_exists('php_sapi_name') ? PHP_SAPI : '');
  212. if ($php_sapi_name == 'cli') {
  213. $this->config_allow_src_above_docroot = true;
  214. }
  215. if (!$this->config_disable_debug) {
  216. // if debug mode is enabled, force phpThumbDebug output, do not allow normal thumbnails to be generated
  217. $this->phpThumbDebug = (null === $this->phpThumbDebug ? 9 : max(1, (int) $this->phpThumbDebug));
  218. }
  219. }
  220. public function __destruct() {
  221. $this->purgeTempFiles();
  222. }
  223. // public:
  224. public function purgeTempFiles() {
  225. foreach ($this->tempFilesToDelete as $tempFileToDelete) {
  226. if (file_exists($tempFileToDelete)) {
  227. $this->DebugMessage('Deleting temp file "'.$tempFileToDelete.'"', __FILE__, __LINE__);
  228. @unlink($tempFileToDelete);
  229. }
  230. }
  231. $this->tempFilesToDelete = array();
  232. return true;
  233. }
  234. // public:
  235. public function setSourceFilename($sourceFilename) {
  236. //$this->resetObject();
  237. //$this->rawImageData = null;
  238. $this->sourceFilename = $sourceFilename;
  239. $this->src = $sourceFilename;
  240. if (null === $this->config_output_format) {
  241. $sourceFileExtension = strtolower(substr(strrchr($sourceFilename, '.'), 1));
  242. if (preg_match('#^[a-z]{3,4}$#', $sourceFileExtension)) {
  243. $this->config_output_format = $sourceFileExtension;
  244. $this->DebugMessage('setSourceFilename('.$sourceFilename.') set $this->config_output_format to "'.$sourceFileExtension.'"', __FILE__, __LINE__);
  245. } else {
  246. $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__);
  247. }
  248. }
  249. $this->DebugMessage('setSourceFilename('.$sourceFilename.') set $this->sourceFilename to "'.$this->sourceFilename.'"', __FILE__, __LINE__);
  250. return true;
  251. }
  252. // public:
  253. public function setSourceData($rawImageData, $sourceFilename='') {
  254. //$this->resetObject();
  255. //$this->sourceFilename = null;
  256. $this->rawImageData = $rawImageData;
  257. $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__);
  258. if ($this->config_cache_source_enabled) {
  259. $sourceFilename = ($sourceFilename ? $sourceFilename : md5($rawImageData));
  260. if (!is_dir($this->config_cache_source_directory)) {
  261. $this->ErrorImage('$this->config_cache_source_directory ('.$this->config_cache_source_directory.') is not a directory');
  262. } elseif (!@is_writable($this->config_cache_source_directory)) {
  263. $this->ErrorImage('$this->config_cache_source_directory ('.$this->config_cache_source_directory.') is not writable');
  264. }
  265. $this->DebugMessage('setSourceData() attempting to save source image to "'.$this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename).'"', __FILE__, __LINE__);
  266. if ($fp = @fopen($this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename), 'wb')) {
  267. fwrite($fp, $rawImageData);
  268. fclose($fp);
  269. } elseif (!$this->phpThumbDebug) {
  270. $this->ErrorImage('setSourceData() failed to write to source cache ('.$this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename).')');
  271. }
  272. }
  273. return true;
  274. }
  275. // public:
  276. public function setSourceImageResource($gdimg) {
  277. //$this->resetObject();
  278. $this->gdimg_source = $gdimg;
  279. return true;
  280. }
  281. // public:
  282. public function setParameter($param, $value) {
  283. if ($param == 'src') {
  284. $this->setSourceFilename($this->ResolveFilenameToAbsolute($value));
  285. } elseif (@is_array($this->$param)) {
  286. if (is_array($value)) {
  287. foreach ($value as $arraykey => $arrayvalue) {
  288. array_push($this->$param, $arrayvalue);
  289. }
  290. } else {
  291. array_push($this->$param, $value);
  292. }
  293. } else {
  294. $this->$param = $value;
  295. }
  296. return true;
  297. }
  298. // public:
  299. public function getParameter($param) {
  300. //if (property_exists('phpThumb', $param)) {
  301. return $this->$param;
  302. //}
  303. //$this->DebugMessage('setParameter() attempting to get non-existant parameter "'.$param.'"', __FILE__, __LINE__);
  304. //return false;
  305. }
  306. // public:
  307. public function GenerateThumbnail() {
  308. $this->setOutputFormat();
  309. $this->phpThumbDebug('8a');
  310. $this->ResolveSource();
  311. $this->phpThumbDebug('8b');
  312. $this->SetCacheFilename();
  313. $this->phpThumbDebug('8c');
  314. $this->ExtractEXIFgetImageSize();
  315. $this->phpThumbDebug('8d');
  316. if ($this->useRawIMoutput) {
  317. $this->DebugMessage('Skipping rest of GenerateThumbnail() because ($this->useRawIMoutput == true)', __FILE__, __LINE__);
  318. return true;
  319. }
  320. $this->phpThumbDebug('8e');
  321. if (!$this->SourceImageToGD()) {
  322. $this->DebugMessage('SourceImageToGD() failed', __FILE__, __LINE__);
  323. return false;
  324. }
  325. $this->phpThumbDebug('8f');
  326. $this->Rotate();
  327. $this->phpThumbDebug('8g');
  328. $this->CreateGDoutput();
  329. $this->phpThumbDebug('8h');
  330. // default values, also applicable for far="C"
  331. $destination_offset_x = round(($this->thumbnail_width - $this->thumbnail_image_width) / 2);
  332. $destination_offset_y = round(($this->thumbnail_height - $this->thumbnail_image_height) / 2);
  333. if (($this->far == 'L') || ($this->far == 'TL') || ($this->far == 'BL')) {
  334. $destination_offset_x = 0;
  335. }
  336. if (($this->far == 'R') || ($this->far == 'TR') || ($this->far == 'BR')) {
  337. $destination_offset_x = round($this->thumbnail_width - $this->thumbnail_image_width);
  338. }
  339. if (($this->far == 'T') || ($this->far == 'TL') || ($this->far == 'TR')) {
  340. $destination_offset_y = 0;
  341. }
  342. if (($this->far == 'B') || ($this->far == 'BL') || ($this->far == 'BR')) {
  343. $destination_offset_y = round($this->thumbnail_height - $this->thumbnail_image_height);
  344. }
  345. // // copy/resize image to appropriate dimensions
  346. // $borderThickness = 0;
  347. // if (!empty($this->fltr)) {
  348. // foreach ($this->fltr as $key => $value) {
  349. // if (preg_match('#^bord\|([0-9]+)#', $value, $matches)) {
  350. // $borderThickness = $matches[1];
  351. // break;
  352. // }
  353. // }
  354. // }
  355. // if ($borderThickness > 0) {
  356. // //$this->DebugMessage('Skipping ImageResizeFunction() because BorderThickness="'.$borderThickness.'"', __FILE__, __LINE__);
  357. // $this->thumbnail_image_height /= 2;
  358. // }
  359. $this->ImageResizeFunction(
  360. $this->gdimg_output,
  361. $this->gdimg_source,
  362. $destination_offset_x,
  363. $destination_offset_y,
  364. $this->thumbnailCropX,
  365. $this->thumbnailCropY,
  366. $this->thumbnail_image_width,
  367. $this->thumbnail_image_height,
  368. $this->thumbnailCropW,
  369. $this->thumbnailCropH
  370. );
  371. $this->DebugMessage('memory_get_usage() after copy-resize = '.(function_exists('memory_get_usage') ? @memory_get_usage() : 'n/a'), __FILE__, __LINE__);
  372. imagedestroy($this->gdimg_source);
  373. $this->DebugMessage('memory_get_usage() after imagedestroy = '.(function_exists('memory_get_usage') ? @memory_get_usage() : 'n/a'), __FILE__, __LINE__);
  374. $this->phpThumbDebug('8i');
  375. $this->AntiOffsiteLinking();
  376. $this->phpThumbDebug('8j');
  377. $this->ApplyFilters();
  378. $this->phpThumbDebug('8k');
  379. $this->AlphaChannelFlatten();
  380. $this->phpThumbDebug('8l');
  381. $this->MaxFileSize();
  382. $this->phpThumbDebug('8m');
  383. $this->DebugMessage('GenerateThumbnail() completed successfully', __FILE__, __LINE__);
  384. return true;
  385. }
  386. // public:
  387. public function RenderOutput() {
  388. if (!$this->useRawIMoutput && !is_resource($this->gdimg_output)) {
  389. $this->DebugMessage('RenderOutput() failed because !is_resource($this->gdimg_output)', __FILE__, __LINE__);
  390. return false;
  391. }
  392. if (!$this->thumbnailFormat) {
  393. $this->DebugMessage('RenderOutput() failed because $this->thumbnailFormat is empty', __FILE__, __LINE__);
  394. return false;
  395. }
  396. if ($this->useRawIMoutput) {
  397. $this->DebugMessage('RenderOutput copying $this->IMresizedData ('.strlen($this->IMresizedData).' bytes) to $this->outputImage', __FILE__, __LINE__);
  398. $this->outputImageData = $this->IMresizedData;
  399. return true;
  400. }
  401. $builtin_formats = array();
  402. if (function_exists('imagetypes')) {
  403. $imagetypes = imagetypes();
  404. $builtin_formats['wbmp'] = (bool) ($imagetypes & IMG_WBMP);
  405. $builtin_formats['jpg'] = (bool) ($imagetypes & IMG_JPG);
  406. $builtin_formats['gif'] = (bool) ($imagetypes & IMG_GIF);
  407. $builtin_formats['png'] = (bool) ($imagetypes & IMG_PNG);
  408. if (defined('IMG_WEBP')) {
  409. $builtin_formats['webp'] = (bool) ($imagetypes & IMG_WEBP); // PHP 5.6.25, 7.0.10
  410. }
  411. if (defined('IMG_BMP')) {
  412. $builtin_formats['bmp'] = (bool) ($imagetypes & IMG_BMP); // PHP 7.2.0
  413. }
  414. }
  415. $this->DebugMessage('imageinterlace($this->gdimg_output, '. (int) $this->config_output_interlace .')', __FILE__, __LINE__);
  416. imageinterlace($this->gdimg_output, (int) $this->config_output_interlace);
  417. $this->DebugMessage('RenderOutput() attempting image'.strtolower(@$this->thumbnailFormat).'($this->gdimg_output)', __FILE__, __LINE__);
  418. ob_start();
  419. switch ($this->thumbnailFormat) {
  420. case 'wbmp':
  421. if (empty($builtin_formats['wbmp'])) {
  422. $this->DebugMessage('GD does not have required built-in support for WBMP output', __FILE__, __LINE__);
  423. ob_end_clean();
  424. return false;
  425. }
  426. imagewbmp($this->gdimg_output, null, $this->thumbnailQuality);
  427. $this->outputImageData = ob_get_contents();
  428. break;
  429. case 'jpeg':
  430. case 'jpg': // should be "jpeg" not "jpg" but just in case...
  431. if (empty($builtin_formats['jpg'])) {
  432. $this->DebugMessage('GD does not have required built-in support for JPEG output', __FILE__, __LINE__);
  433. ob_end_clean();
  434. return false;
  435. }
  436. imagejpeg($this->gdimg_output, null, $this->thumbnailQuality);
  437. $this->outputImageData = ob_get_contents();
  438. break;
  439. case 'png':
  440. if (empty($builtin_formats['png'])) {
  441. $this->DebugMessage('GD does not have required built-in support for PNG output', __FILE__, __LINE__);
  442. ob_end_clean();
  443. return false;
  444. }
  445. if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.1.2', '>=')) {
  446. // https://github.com/JamesHeinrich/phpThumb/issues/24
  447. /* http://php.net/manual/en/function.imagepng.php:
  448. from php source (gd.h):
  449. 2.0.12: Compression level: 0-9 or -1, where 0 is NO COMPRESSION at all,
  450. :: 1 is FASTEST but produces larger files, 9 provides the best
  451. :: compression (smallest files) but takes a long time to compress, and
  452. :: -1 selects the default compiled into the zlib library.
  453. Conclusion: Based on the Zlib manual (http://www.zlib.net/manual.html) the default compression level is set to 6.
  454. */
  455. if (($this->thumbnailQuality >= -1) && ($this->thumbnailQuality <= 9)) {
  456. $PNGquality = $this->thumbnailQuality;
  457. } else {
  458. $this->DebugMessage('Specified thumbnailQuality "'.$this->thumbnailQuality.'" is outside the accepted range (0-9, or -1). Using 6 as default value.', __FILE__, __LINE__);
  459. $PNGquality = 6;
  460. }
  461. imagepng($this->gdimg_output, null, $PNGquality);
  462. } else {
  463. imagepng($this->gdimg_output);
  464. }
  465. $this->outputImageData = ob_get_contents();
  466. break;
  467. case 'gif':
  468. if (empty($builtin_formats['gif'])) {
  469. $this->DebugMessage('GD does not have required built-in support for GIF output', __FILE__, __LINE__);
  470. ob_end_clean();
  471. return false;
  472. }
  473. imagegif($this->gdimg_output);
  474. $this->outputImageData = ob_get_contents();
  475. break;
  476. case 'webp':
  477. if (empty($builtin_formats['webp'])) {
  478. $this->DebugMessage('GD does not have required built-in support for WebP output', __FILE__, __LINE__);
  479. ob_end_clean();
  480. return false;
  481. }
  482. imagewebp($this->gdimg_output);
  483. $this->outputImageData = ob_get_contents();
  484. break;
  485. case 'bmp':
  486. if (!empty($builtin_formats['bmp'])) {
  487. imagebmp($this->gdimg_output);
  488. $this->outputImageData = ob_get_contents();
  489. break;
  490. }
  491. $this->DebugMessage('GD does not have required built-in support for BMP output', __FILE__, __LINE__);
  492. if (!@include_once __DIR__ .'/phpthumb.bmp.php' ) {
  493. $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.bmp.php" which is required for BMP format output', __FILE__, __LINE__);
  494. ob_end_clean();
  495. return false;
  496. }
  497. $phpthumb_bmp = new phpthumb_bmp();
  498. $this->outputImageData = $phpthumb_bmp->GD2BMPstring($this->gdimg_output);
  499. unset($phpthumb_bmp);
  500. break;
  501. case 'ico':
  502. if (!@include_once __DIR__ .'/phpthumb.ico.php' ) {
  503. $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.ico.php" which is required for ICO format output', __FILE__, __LINE__);
  504. ob_end_clean();
  505. return false;
  506. }
  507. $phpthumb_ico = new phpthumb_ico();
  508. $arrayOfOutputImages = array($this->gdimg_output);
  509. $this->outputImageData = $phpthumb_ico->GD2ICOstring($arrayOfOutputImages);
  510. unset($phpthumb_ico);
  511. break;
  512. default:
  513. $this->DebugMessage('RenderOutput failed because $this->thumbnailFormat "'.$this->thumbnailFormat.'" is not valid', __FILE__, __LINE__);
  514. ob_end_clean();
  515. return false;
  516. }
  517. ob_end_clean();
  518. if (!$this->outputImageData) {
  519. $this->DebugMessage('RenderOutput() for "'.$this->thumbnailFormat.'" failed', __FILE__, __LINE__);
  520. ob_end_clean();
  521. return false;
  522. }
  523. $this->DebugMessage('RenderOutput() completing with $this->outputImageData = '.strlen($this->outputImageData).' bytes', __FILE__, __LINE__);
  524. return true;
  525. }
  526. // public:
  527. public function RenderToFile($filename) {
  528. if (preg_match('#^[a-z0-9]+://#i', $filename)) {
  529. $this->DebugMessage('RenderToFile() failed because $filename ('.$filename.') is a URL', __FILE__, __LINE__);
  530. return false;
  531. }
  532. // render thumbnail to this file only, do not cache, do not output to browser
  533. //$renderfilename = $this->ResolveFilenameToAbsolute(dirname($filename)).DIRECTORY_SEPARATOR.basename($filename);
  534. $renderfilename = $filename;
  535. if (($filename[0] != '/') && ($filename[0] != '\\') && ($filename[1] != ':')) {
  536. $renderfilename = $this->ResolveFilenameToAbsolute($renderfilename);
  537. }
  538. if (!@is_writable(dirname($renderfilename))) {
  539. $this->DebugMessage('RenderToFile() failed because "'.dirname($renderfilename).'/" is not writable', __FILE__, __LINE__);
  540. return false;
  541. }
  542. if (@is_file($renderfilename) && !@is_writable($renderfilename)) {
  543. $this->DebugMessage('RenderToFile() failed because "'.$renderfilename.'" is not writable', __FILE__, __LINE__);
  544. return false;
  545. }
  546. if ($this->RenderOutput()) {
  547. if (file_put_contents($renderfilename, $this->outputImageData)) {
  548. @chmod($renderfilename, $this->getParameter('config_file_create_mask'));
  549. $this->DebugMessage('RenderToFile('.$renderfilename.') succeeded', __FILE__, __LINE__);
  550. return true;
  551. }
  552. if (!@file_exists($renderfilename)) {
  553. $this->DebugMessage('RenderOutput ['.$this->thumbnailFormat.'('.$renderfilename.')] did not appear to fail, but the output image does not exist either...', __FILE__, __LINE__);
  554. }
  555. } else {
  556. $this->DebugMessage('RenderOutput ['.$this->thumbnailFormat.'('.$renderfilename.')] failed', __FILE__, __LINE__);
  557. }
  558. return false;
  559. }
  560. // public:
  561. public function OutputThumbnail() {
  562. $this->purgeTempFiles();
  563. if (!$this->useRawIMoutput && !is_resource($this->gdimg_output)) {
  564. $this->DebugMessage('OutputThumbnail() failed because !is_resource($this->gdimg_output)', __FILE__, __LINE__);
  565. return false;
  566. }
  567. if (headers_sent()) {
  568. return $this->ErrorImage('OutputThumbnail() failed - headers already sent');
  569. }
  570. $downloadfilename = phpthumb_functions::SanitizeFilename(is_string($this->sia) ? $this->sia : ($this->down ? $this->down : 'phpThumb_generated_thumbnail'.'.'.$this->thumbnailFormat));
  571. $this->DebugMessage('Content-Disposition header filename set to "'.$downloadfilename.'"', __FILE__, __LINE__);
  572. if ($downloadfilename) {
  573. header('Content-Disposition: '.($this->down ? 'attachment' : 'inline').'; filename="'.$downloadfilename.'"');
  574. } else {
  575. $this->DebugMessage('failed to send Content-Disposition header because $downloadfilename is empty', __FILE__, __LINE__);
  576. }
  577. if ($this->useRawIMoutput) {
  578. header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
  579. echo $this->IMresizedData;
  580. } else {
  581. $this->DebugMessage('imageinterlace($this->gdimg_output, '. (int) $this->config_output_interlace .')', __FILE__, __LINE__);
  582. imageinterlace($this->gdimg_output, (int) $this->config_output_interlace);
  583. switch ($this->thumbnailFormat) {
  584. case 'jpeg':
  585. header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
  586. $ImageOutFunction = 'image'.$this->thumbnailFormat;
  587. @$ImageOutFunction($this->gdimg_output, null, $this->thumbnailQuality);
  588. break;
  589. case 'png':
  590. case 'gif':
  591. case 'webp':
  592. $ImageOutFunction = 'image'.$this->thumbnailFormat;
  593. if (!function_exists($ImageOutFunction)) {
  594. $this->DebugMessage($ImageOutFunction.' is not available', __FILE__, __LINE__);
  595. return false;
  596. }
  597. header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
  598. @$ImageOutFunction($this->gdimg_output);
  599. break;
  600. case 'bmp':
  601. if (function_exists('imagebmp')) {
  602. header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
  603. imagebmp($this->gdimg_output);
  604. break;
  605. }
  606. if (!@include_once __DIR__ .'/phpthumb.bmp.php' ) {
  607. $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.bmp.php" which is required for BMP format output', __FILE__, __LINE__);
  608. return false;
  609. }
  610. $phpthumb_bmp = new phpthumb_bmp();
  611. if (is_object($phpthumb_bmp)) {
  612. $bmp_data = $phpthumb_bmp->GD2BMPstring($this->gdimg_output);
  613. unset($phpthumb_bmp);
  614. if (!$bmp_data) {
  615. $this->DebugMessage('$phpthumb_bmp->GD2BMPstring() failed', __FILE__, __LINE__);
  616. return false;
  617. }
  618. header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
  619. echo $bmp_data;
  620. } else {
  621. $this->DebugMessage('new phpthumb_bmp() failed', __FILE__, __LINE__);
  622. return false;
  623. }
  624. break;
  625. case 'ico':
  626. if (!@include_once __DIR__ .'/phpthumb.ico.php' ) {
  627. $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.ico.php" which is required for ICO format output', __FILE__, __LINE__);
  628. return false;
  629. }
  630. $phpthumb_ico = new phpthumb_ico();
  631. if (is_object($phpthumb_ico)) {
  632. $arrayOfOutputImages = array($this->gdimg_output);
  633. $ico_data = $phpthumb_ico->GD2ICOstring($arrayOfOutputImages);
  634. unset($phpthumb_ico);
  635. if (!$ico_data) {
  636. $this->DebugMessage('$phpthumb_ico->GD2ICOstring() failed', __FILE__, __LINE__);
  637. return false;
  638. }
  639. header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
  640. echo $ico_data;
  641. } else {
  642. $this->DebugMessage('new phpthumb_ico() failed', __FILE__, __LINE__);
  643. return false;
  644. }
  645. break;
  646. default:
  647. $this->DebugMessage('OutputThumbnail failed because $this->thumbnailFormat "'.$this->thumbnailFormat.'" is not valid', __FILE__, __LINE__);
  648. return false;
  649. break;
  650. }
  651. }
  652. return true;
  653. }
  654. // public:
  655. public function CleanUpCacheDirectory() {
  656. $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__);
  657. if (!is_writable($this->config_cache_directory)) {
  658. $this->DebugMessage('CleanUpCacheDirectory() skipped because "'.$this->config_cache_directory.'" is not writable', __FILE__, __LINE__);
  659. return true;
  660. }
  661. // cache status of cache directory for 1 hour to avoid hammering the filesystem functions
  662. $phpThumbCacheStats_filename = $this->config_cache_directory.DIRECTORY_SEPARATOR.'phpThumbCacheStats.txt';
  663. if (file_exists($phpThumbCacheStats_filename) && is_readable($phpThumbCacheStats_filename) && (filemtime($phpThumbCacheStats_filename) >= (time() - 3600))) {
  664. $this->DebugMessage('CleanUpCacheDirectory() skipped because "'.$phpThumbCacheStats_filename.'" is recently modified', __FILE__, __LINE__);
  665. return true;
  666. }
  667. if (!@touch($phpThumbCacheStats_filename)) {
  668. $this->DebugMessage('touch('.$phpThumbCacheStats_filename.') failed', __FILE__, __LINE__);
  669. }
  670. $DeletedKeys = array();
  671. $AllFilesInCacheDirectory = array();
  672. if (($this->config_cache_maxage > 0) || ($this->config_cache_maxsize > 0) || ($this->config_cache_maxfiles > 0)) {
  673. $CacheDirOldFilesAge = array();
  674. $CacheDirOldFilesSize = array();
  675. $AllFilesInCacheDirectory = phpthumb_functions::GetAllFilesInSubfolders($this->config_cache_directory);
  676. foreach ($AllFilesInCacheDirectory as $fullfilename) {
  677. if (preg_match('#'.preg_quote($this->config_cache_prefix).'#i', $fullfilename) && file_exists($fullfilename)) {
  678. $CacheDirOldFilesAge[$fullfilename] = @fileatime($fullfilename);
  679. if ($CacheDirOldFilesAge[$fullfilename] == 0) {
  680. $CacheDirOldFilesAge[$fullfilename] = @filemtime($fullfilename);
  681. }
  682. $CacheDirOldFilesSize[$fullfilename] = @filesize($fullfilename);
  683. }
  684. }
  685. if (empty($CacheDirOldFilesSize)) {
  686. $this->DebugMessage('CleanUpCacheDirectory() skipped because $CacheDirOldFilesSize is empty (phpthumb_functions::GetAllFilesInSubfolders('.$this->config_cache_directory.') found no files)', __FILE__, __LINE__);
  687. return true;
  688. }
  689. $DeletedKeys['zerobyte'] = array();
  690. foreach ($CacheDirOldFilesSize as $fullfilename => $filesize) {
  691. // purge all zero-size files more than an hour old (to prevent trying to delete just-created and/or in-use files)
  692. $cutofftime = time() - 3600;
  693. if (($filesize == 0) && ($CacheDirOldFilesAge[$fullfilename] < $cutofftime)) {
  694. $this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__);
  695. if (@unlink($fullfilename)) {
  696. $DeletedKeys['zerobyte'][] = $fullfilename;
  697. unset($CacheDirOldFilesSize[$fullfilename]);
  698. unset($CacheDirOldFilesAge[$fullfilename]);
  699. }
  700. }
  701. }
  702. $this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['zerobyte']).' zero-byte files', __FILE__, __LINE__);
  703. asort($CacheDirOldFilesAge);
  704. if ($this->config_cache_maxfiles > 0) {
  705. $TotalCachedFiles = count($CacheDirOldFilesAge);
  706. $DeletedKeys['maxfiles'] = array();
  707. foreach ($CacheDirOldFilesAge as $fullfilename => $filedate) {
  708. if ($TotalCachedFiles > $this->config_cache_maxfiles) {
  709. $this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__);
  710. if (@unlink($fullfilename)) {
  711. $TotalCachedFiles--;
  712. $DeletedKeys['maxfiles'][] = $fullfilename;
  713. }
  714. } else {
  715. // there are few enough files to keep the rest
  716. break;
  717. }
  718. }
  719. $this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['maxfiles']).' files based on (config_cache_maxfiles='.$this->config_cache_maxfiles.')', __FILE__, __LINE__);
  720. foreach ($DeletedKeys['maxfiles'] as $fullfilename) {
  721. unset($CacheDirOldFilesAge[$fullfilename]);
  722. unset($CacheDirOldFilesSize[$fullfilename]);
  723. }
  724. }
  725. if ($this->config_cache_maxage > 0) {
  726. $mindate = time() - $this->config_cache_maxage;
  727. $DeletedKeys['maxage'] = array();
  728. foreach ($CacheDirOldFilesAge as $fullfilename => $filedate) {
  729. if ($filedate > 0) {
  730. if ($filedate < $mindate) {
  731. $this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__);
  732. if (@unlink($fullfilename)) {
  733. $DeletedKeys['maxage'][] = $fullfilename;
  734. }
  735. } else {
  736. // the rest of the files are new enough to keep
  737. break;
  738. }
  739. }
  740. }
  741. $this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['maxage']).' files based on (config_cache_maxage='.$this->config_cache_maxage.')', __FILE__, __LINE__);
  742. foreach ($DeletedKeys['maxage'] as $fullfilename) {
  743. unset($CacheDirOldFilesAge[$fullfilename]);
  744. unset($CacheDirOldFilesSize[$fullfilename]);
  745. }
  746. }
  747. if ($this->config_cache_maxsize > 0) {
  748. $TotalCachedFileSize = array_sum($CacheDirOldFilesSize);
  749. $DeletedKeys['maxsize'] = array();
  750. foreach ($CacheDirOldFilesAge as $fullfilename => $filedate) {
  751. if ($TotalCachedFileSize > $this->config_cache_maxsize) {
  752. $this->DebugMessage('deleting "'.$fullfilename.'"', __FILE__, __LINE__);
  753. if (@unlink($fullfilename)) {
  754. $TotalCachedFileSize -= $CacheDirOldFilesSize[$fullfilename];
  755. $DeletedKeys['maxsize'][] = $fullfilename;
  756. }
  757. } else {
  758. // the total filesizes are small enough to keep the rest of the files
  759. break;
  760. }
  761. }
  762. $this->DebugMessage('CleanUpCacheDirectory() purged '.count($DeletedKeys['maxsize']).' files based on (config_cache_maxsize='.$this->config_cache_maxsize.')', __FILE__, __LINE__);
  763. foreach ($DeletedKeys['maxsize'] as $fullfilename) {
  764. unset($CacheDirOldFilesAge[$fullfilename]);
  765. unset($CacheDirOldFilesSize[$fullfilename]);
  766. }
  767. }
  768. } else {
  769. $this->DebugMessage('skipping CleanUpCacheDirectory() because config set to not use it', __FILE__, __LINE__);
  770. }
  771. $totalpurged = 0;
  772. foreach ($DeletedKeys as $key => $value) {
  773. $totalpurged += count($value);
  774. }
  775. $this->DebugMessage('CleanUpCacheDirectory() purged '.$totalpurged.' files (from '.count($AllFilesInCacheDirectory).') based on config settings', __FILE__, __LINE__);
  776. if ($totalpurged > 0) {
  777. $empty_dirs = array();
  778. foreach ($AllFilesInCacheDirectory as $fullfilename) {
  779. if (is_dir($fullfilename)) {
  780. $empty_dirs[$this->realPathSafe($fullfilename)] = 1;
  781. } else {
  782. unset($empty_dirs[$this->realPathSafe(dirname($fullfilename))]);
  783. }
  784. }
  785. krsort($empty_dirs);
  786. $totalpurgeddirs = 0;
  787. foreach ($empty_dirs as $empty_dir => $dummy) {
  788. if ($empty_dir == $this->config_cache_directory) {
  789. // shouldn't happen, but just in case, don't let it delete actual cache directory
  790. continue;
  791. } elseif (@rmdir($empty_dir)) {
  792. $totalpurgeddirs++;
  793. } else {
  794. $this->DebugMessage('failed to rmdir('.$empty_dir.')', __FILE__, __LINE__);
  795. }
  796. }
  797. $this->DebugMessage('purged '.$totalpurgeddirs.' empty directories', __FILE__, __LINE__);
  798. }
  799. return true;
  800. }
  801. //////////////////////////////////////////////////////////////////////
  802. // private: re-initializator (call between rendering multiple images with one object)
  803. public function resetObject() {
  804. $class_vars = get_class_vars(get_class($this));
  805. foreach ($class_vars as $key => $value) {
  806. // do not clobber debug or config info
  807. if (!preg_match('#^(config_|debug|fatalerror)#i', $key)) {
  808. $this->$key = $value;
  809. }
  810. }
  811. $this->phpThumb(); // re-initialize some class variables
  812. return true;
  813. }
  814. //////////////////////////////////////////////////////////////////////
  815. public function ResolveSource() {
  816. if (is_resource($this->gdimg_source)) {
  817. $this->DebugMessage('ResolveSource() exiting because is_resource($this->gdimg_source)', __FILE__, __LINE__);
  818. return true;
  819. }
  820. if ($this->rawImageData) {
  821. $this->sourceFilename = null;
  822. $this->DebugMessage('ResolveSource() exiting because $this->rawImageData is set ('.number_format(strlen($this->rawImageData)).' bytes)', __FILE__, __LINE__);
  823. return true;
  824. }
  825. if ($this->sourceFilename) {
  826. $this->sourceFilename = $this->ResolveFilenameToAbsolute($this->sourceFilename);
  827. $this->DebugMessage('$this->sourceFilename set to "'.$this->sourceFilename.'"', __FILE__, __LINE__);
  828. } elseif ($this->src) {
  829. $this->sourceFilename = $this->ResolveFilenameToAbsolute($this->src);
  830. $this->DebugMessage('$this->sourceFilename set to "'.$this->sourceFilename.'" from $this->src ('.$this->src.')', __FILE__, __LINE__);
  831. } else {
  832. return $this->ErrorImage('$this->sourceFilename and $this->src are both empty');
  833. }
  834. if ($this->iswindows && ((substr($this->sourceFilename, 0, 2) == '//') || (substr($this->sourceFilename, 0, 2) == '\\\\'))) {
  835. // Windows \\share\filename.ext
  836. } elseif (preg_match('#^[a-z0-9]+://#i', $this->sourceFilename, $protocol_matches)) {
  837. if (preg_match('#^(f|ht)tps?\://#i', $this->sourceFilename)) {
  838. // URL
  839. if ($this->config_http_user_agent) {
  840. ini_set('user_agent', $this->config_http_user_agent);
  841. }
  842. } else {
  843. return $this->ErrorImage('only FTP and HTTP/HTTPS protocols are allowed, "'.$protocol_matches[1].'" is not');
  844. }
  845. } elseif (!@file_exists($this->sourceFilename)) {
  846. return $this->ErrorImage('"'.$this->sourceFilename.'" does not exist');
  847. } elseif (!@is_file($this->sourceFilename)) {
  848. return $this->ErrorImage('"'.$this->sourceFilename.'" is not a file');
  849. }
  850. return true;
  851. }
  852. public function setOutputFormat() {
  853. static $alreadyCalled = false;
  854. if ($this->thumbnailFormat && $alreadyCalled) {
  855. return true;
  856. }
  857. $alreadyCalled = true;
  858. $AvailableImageOutputFormats = array();
  859. $AvailableImageOutputFormats[] = 'text';
  860. if (@is_readable( __DIR__ .'/phpthumb.ico.php')) {
  861. $AvailableImageOutputFormats[] = 'ico';
  862. }
  863. if (@is_readable( __DIR__ .'/phpthumb.bmp.php')) {
  864. $AvailableImageOutputFormats[] = 'bmp';
  865. }
  866. $this->thumbnailFormat = 'ico';
  867. // Set default output format based on what image types are available
  868. if (function_exists('imagetypes')) {
  869. $imagetypes = imagetypes();
  870. if ($imagetypes & IMG_WBMP) {
  871. $this->thumbnailFormat = 'wbmp';
  872. $AvailableImageOutputFormats[] = 'wbmp';
  873. }
  874. if ($imagetypes & IMG_GIF) {
  875. $this->thumbnailFormat = 'gif';
  876. $AvailableImageOutputFormats[] = 'gif';
  877. }
  878. if ($imagetypes & IMG_WEBP) {
  879. $this->thumbnailFormat = 'webp';
  880. $AvailableImageOutputFormats[] = 'webp';
  881. }
  882. if ($imagetypes & IMG_PNG) {
  883. $this->thumbnailFormat = 'png';
  884. $AvailableImageOutputFormats[] = 'png';
  885. }
  886. if ($imagetypes & IMG_JPG) {
  887. $this->thumbnailFormat = 'jpeg';
  888. $AvailableImageOutputFormats[] = 'jpeg';
  889. }
  890. } else {
  891. $this->DebugMessage('imagetypes() does not exist - GD support might not be enabled?', __FILE__, __LINE__);
  892. }
  893. if ($this->ImageMagickVersion()) {
  894. $IMformats = array('jpeg', 'png', 'gif', 'bmp', 'ico', 'wbmp', 'webp');
  895. $this->DebugMessage('Addding ImageMagick formats to $AvailableImageOutputFormats ('.implode(';', $AvailableImageOutputFormats).')', __FILE__, __LINE__);
  896. foreach ($IMformats as $key => $format) {
  897. $AvailableImageOutputFormats[] = $format;
  898. }
  899. }
  900. $AvailableImageOutputFormats = array_unique($AvailableImageOutputFormats);
  901. $this->DebugMessage('$AvailableImageOutputFormats = array('.implode(';', $AvailableImageOutputFormats).')', __FILE__, __LINE__);
  902. $this->f = preg_replace('#[^a-z]#', '', strtolower($this->f));
  903. if (strtolower($this->config_output_format) == 'jpg') {
  904. $this->config_output_format = 'jpeg';
  905. }
  906. if (strtolower($this->f) == 'jpg') {
  907. $this->f = 'jpeg';
  908. }
  909. if (phpthumb_functions::CaseInsensitiveInArray($this->config_output_format, $AvailableImageOutputFormats)) {
  910. // set output format to config default if that format is available
  911. $this->DebugMessage('$this->thumbnailFormat set to $this->config_output_format "'.strtolower($this->config_output_format).'"', __FILE__, __LINE__);
  912. $this->thumbnailFormat = strtolower($this->config_output_format);
  913. } elseif ($this->config_output_format) {
  914. $this->DebugMessage('$this->thumbnailFormat staying as "'.$this->thumbnailFormat.'" because $this->config_output_format ('.strtolower($this->config_output_format).') is not in $AvailableImageOutputFormats', __FILE__, __LINE__);
  915. }
  916. if ($this->f && phpthumb_functions::CaseInsensitiveInArray($this->f, $AvailableImageOutputFormats) ) {
  917. // override output format if $this->f is set and that format is available
  918. $this->DebugMessage('$this->thumbnailFormat set to $this->f "'.strtolower($this->f).'"', __FILE__, __LINE__);
  919. $this->thumbnailFormat = strtolower($this->f);
  920. } elseif ($this->f) {
  921. $this->DebugMessage('$this->thumbnailFormat staying as "'.$this->thumbnailFormat.'" because $this->f ('.strtolower($this->f).') is not in $AvailableImageOutputFormats', __FILE__, __LINE__);
  922. }
  923. // for JPEG images, quality 1 (worst) to 99 (best)
  924. // quality < 25 is nasty, with not much size savings - not recommended
  925. // problems with 100 - invalid JPEG?
  926. $this->thumbnailQuality = max(1, min(99, ($this->q ? (int) $this->q : 75)));
  927. $this->DebugMessage('$this->thumbnailQuality set to "'.$this->thumbnailQuality.'"', __FILE__, __LINE__);
  928. return true;
  929. }
  930. public function setCacheDirectory() {
  931. // resolve cache directory to absolute pathname
  932. $this->DebugMessage('setCacheDirectory() starting with config_cache_directory = "'.$this->config_cache_directory.'"', __FILE__, __LINE__);
  933. if ($this->config_cache_directory[ 0 ] == '.') {
  934. if (preg_match('#^(f|ht)tps?\://#i', $this->src)) {
  935. if (!$this->config_cache_disable_warning) {
  936. $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');
  937. }
  938. } elseif ($this->src) {
  939. // resolve relative cache directory to source image
  940. $this->config_cache_directory = dirname($this->ResolveFilenameToAbsolute($this->src)).DIRECTORY_SEPARATOR.$this->config_cache_directory;
  941. } else {
  942. // $this->new is probably set
  943. }
  944. }
  945. if (substr($this->config_cache_directory, -1) == '/') {
  946. $this->config_cache_directory = substr($this->config_cache_directory, 0, -1);
  947. }
  948. if ($this->iswindows) {
  949. $this->config_cache_directory = str_replace('/', DIRECTORY_SEPARATOR, $this->config_cache_directory);
  950. }
  951. if ($this->config_cache_directory) {
  952. $real_cache_path = $this->realPathSafe($this->config_cache_directory);
  953. if (!$real_cache_path) {
  954. $this->DebugMessage('$this->realPathSafe($this->config_cache_directory) failed for "'.$this->config_cache_directory.'"', __FILE__, __LINE__);
  955. if (!is_dir($this->config_cache_directory)) {
  956. $this->DebugMessage('!is_dir('.$this->config_cache_directory.')', __FILE__, __LINE__);
  957. }
  958. }
  959. if ($real_cache_path) {
  960. $this->DebugMessage('setting config_cache_directory to $this->realPathSafe('.$this->config_cache_directory.') = "'.$real_cache_path.'"', __FILE__, __LINE__);
  961. $this->config_cache_directory = $real_cache_path;
  962. }
  963. }
  964. if (!is_dir($this->config_cache_directory)) {
  965. if (!$this->config_cache_disable_warning) {
  966. $this->ErrorImage('$this->config_cache_directory ('.$this->config_cache_directory.') does not exist. Adjust "cache_directory" or "cache_disable_warning" in phpThumb.config.php');
  967. }
  968. $this->DebugMessage('$this->config_cache_directory ('.$this->config_cache_directory.') is not a directory', __FILE__, __LINE__);
  969. $this->config_cache_directory = null;
  970. } elseif (!@is_writable($this->config_cache_directory)) {
  971. $this->DebugMessage('$this->config_cache_directory is not writable ('.$this->config_cache_directory.')', __FILE__, __LINE__);
  972. }
  973. $this->InitializeTempDirSetting();
  974. 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)) {
  975. $this->DebugMessage('setting $this->config_temp_directory = $this->config_cache_directory ('.$this->config_cache_directory.')', __FILE__, __LINE__);
  976. $this->config_temp_directory = $this->config_cache_directory;
  977. }
  978. return true;
  979. }
  980. /* Takes the array of path segments up to now, and the next segment (maybe a modifier: empty, . or ..)
  981. Applies it, adding or removing from $segments as a result. Returns nothing. */
  982. // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961
  983. public function applyPathSegment(&$segments, $segment) {
  984. if ($segment == '.') {
  985. return; // always remove
  986. }
  987. if ($segment == '') {
  988. $test = array_pop($segments);
  989. if (null === $test) {
  990. $segments[] = $segment; // keep the first empty block
  991. } elseif ($test == '') {
  992. $test = array_pop($segments);
  993. if (null === $test) {
  994. $segments[] = $test;
  995. $segments[] = $segment; // keep the second one too
  996. } else { // put both back and ignore segment
  997. $segments[] = $test;
  998. $segments[] = $test;
  999. }
  1000. } else {
  1001. $segments[] = $test; // ignore empty blocks
  1002. }
  1003. } else {
  1004. if ($segment == '..') {
  1005. $test = array_pop($segments);
  1006. if (null === $test) {
  1007. $segments[] = $segment;
  1008. } elseif ($test == '..') {
  1009. $segments[] = $test;
  1010. $segments[] = $segment;
  1011. } else {
  1012. if ($test == '') {
  1013. $segments[] = $test;
  1014. } // else nothing, remove both
  1015. }
  1016. } else {
  1017. $segments[] = $segment;
  1018. }
  1019. }
  1020. }
  1021. /* Takes array of path components, normalizes it: removes empty slots and '.', collapses '..' and folder names. Returns array. */
  1022. // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961
  1023. public function normalizePath($segments) {
  1024. $parts = array();
  1025. foreach ($segments as $segment) {
  1026. $this->applyPathSegment($parts, $segment);
  1027. }
  1028. return $parts;
  1029. }
  1030. /* True if the provided path points (without resolving symbolic links) into one of the allowed directories. */
  1031. // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961
  1032. public function matchPath($path, $allowed_dirs) {
  1033. if (!empty($allowed_dirs)) {
  1034. foreach ($allowed_dirs as $one_dir) {
  1035. if (preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', $this->realPathSafe($one_dir))).'#', $path)) {
  1036. return true;
  1037. }
  1038. }
  1039. }
  1040. return false;
  1041. }
  1042. /* True if the provided path points inside one of open_basedirs (or if open_basedirs are disabled) */
  1043. // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961
  1044. public function isInOpenBasedir($path) {
  1045. static $open_basedirs = null;
  1046. if (null === $open_basedirs) {
  1047. $ini_text = ini_get('open_basedir');
  1048. $this->DebugMessage('open_basedir: "'.$ini_text.'"', __FILE__, __LINE__);
  1049. $open_basedirs = array();
  1050. if (strlen($ini_text) > 0) {
  1051. foreach (preg_split('#[;:]#', $ini_text) as $key => $value) {
  1052. $open_basedirs[$key] = $this->realPathSafe($value);
  1053. }
  1054. }
  1055. }
  1056. return (empty($open_basedirs) || $this->matchPath($path, $open_basedirs));
  1057. }
  1058. /* 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. */
  1059. // http://support.silisoftware.com/phpBB3/viewtopic.php?t=961
  1060. public function resolvePath($path, $allowed_dirs) {
  1061. $this->DebugMessage('resolvePath: '.$path.' (allowed_dirs: '.print_r($allowed_dirs, true).')', __FILE__, __LINE__);
  1062. // add base path to the top of the list
  1063. if (!$this->config_allow_src_above_docroot) {
  1064. array_unshift($allowed_dirs, $this->realPathSafe($this->config_document_root));
  1065. } else {
  1066. if (!$this->config_allow_src_above_phpthumb) {
  1067. array_unshift($allowed_dirs, $this->realPathSafe( __DIR__ ));
  1068. } else {
  1069. // no checks are needed, offload the work to realpath and forget about it
  1070. $this->DebugMessage('resolvePath: checks disabled, returning '.$this->realPathSafe($path), __FILE__, __LINE__);
  1071. return $this->realPathSafe($path);
  1072. }
  1073. }
  1074. if ($path == '') {
  1075. return null; // save us trouble
  1076. }
  1077. do {
  1078. $this->DebugMessage('resolvePath: iteration, path='.$path.', base path = '.$allowed_dirs[0], __FILE__, __LINE__);
  1079. $parts = array();
  1080. // do not use "cleaner" foreach version of this loop as later code relies on both $segments and $i
  1081. // http://support.silisoftware.com/phpBB3/viewtopic.php?t=964
  1082. $segments = explode(DIRECTORY_SEPARATOR, $path);
  1083. for ($i = 0, $iMax = count($segments); $i < $iMax; $i++) {
  1084. $this->applyPathSegment($parts, $segments[$i]);
  1085. $thispart = implode(DIRECTORY_SEPARATOR, $parts);
  1086. if ($this->isInOpenBasedir($thispart)) {
  1087. if (is_link($thispart)) {
  1088. break;
  1089. }
  1090. }
  1091. }
  1092. $this->DebugMessage('resolvePath: stop at component '.$i, __FILE__, __LINE__);
  1093. // test the part up to here
  1094. $path = implode(DIRECTORY_SEPARATOR, $parts);
  1095. $this->DebugMessage('resolvePath: stop at path='.$path, __FILE__, __LINE__);
  1096. if (!$this->matchPath($path, $allowed_dirs)) {
  1097. $this->DebugMessage('resolvePath: no match, returning null', __FILE__, __LINE__);
  1098. return null;
  1099. }
  1100. if ($i >= count($segments)) { // reached end
  1101. $this->DebugMessage('resolvePath: path parsed, over', __FILE__, __LINE__);
  1102. break;
  1103. }
  1104. // else it's symlink, rewrite path
  1105. $path = readlink($path);
  1106. $this->DebugMessage('resolvePath: symlink matched, target='.$path, __FILE__, __LINE__);
  1107. /*
  1108. Replace base path with symlink target.
  1109. Assuming:
  1110. /www/img/external -> /external
  1111. This is allowed:
  1112. GET /www/img/external/../external/test/pic.jpg
  1113. This isn't:
  1114. GET /www/img/external/../www/img/pic.jpg
  1115. So there's only one base path which is the last symlink target, but any number of stable whitelisted paths.
  1116. */
  1117. if ($this->config_auto_allow_symlinks) {
  1118. $allowed_dirs[0] = $path;
  1119. }
  1120. $path = $path.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, array_slice($segments,$i + 1));
  1121. } while (true);
  1122. return $path;
  1123. }
  1124. public function realPathSafe($filename) {
  1125. // 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"
  1126. // realPathSafe() provides a reasonable facsimile of realpath() but does not resolve symbolic links, nor does it check that the file/path actually exists
  1127. if (!$this->config_disable_realpath) {
  1128. return realpath($filename);
  1129. }
  1130. // http://stackoverflow.com/questions/21421569
  1131. $newfilename = preg_replace('#[\\/]+#', DIRECTORY_SEPARATOR, $filename);
  1132. if (!preg_match('#^'.DIRECTORY_SEPARATOR.'#', $newfilename)) {
  1133. $newfilename = __DIR__ .DIRECTORY_SEPARATOR.$newfilename;
  1134. }
  1135. do {
  1136. $beforeloop = $newfilename;
  1137. // 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.]]
  1138. $newfilename = preg_replace('#'.DIRECTORY_SEPARATOR.'+#', DIRECTORY_SEPARATOR, $newfilename);
  1139. // Replace all occurrences of /./ with /
  1140. $newfilename = preg_replace('#'.DIRECTORY_SEPARATOR.'\\.'.DIRECTORY_SEPARATOR.'#', DIRECTORY_SEPARATOR, $newfilename);
  1141. // Remove ./ if at the start
  1142. $newfilename = preg_replace('#^\\.'.DIRECTORY_SEPARATOR.'#', '', $newfilename);
  1143. // Remove /. if at the end
  1144. $newfilename = preg_replace('#'.DIRECTORY_SEPARATOR.'\\.$#', '', $newfilename);
  1145. // Replace /anything/../ with /
  1146. $newfilename = preg_replace('#'.DIRECTORY_SEPARATOR.'[^'.DIRECTORY_SEPARATOR.']+'.DIRECTORY_SEPARATOR.'\\.\\.'.DIRECTORY_SEPARATOR.'#', DIRECTORY_SEPARATOR, $newfilename);
  1147. // Remove /anything/.. if at the end
  1148. $newfilename = preg_replace('#'.DIRECTORY_SEPARATOR.'[^'.DIRECTORY_SEPARATOR.']+'.DIRECTORY_SEPARATOR.'\\.\\.$#', '', $newfilename);
  1149. } while ($newfilename != $beforeloop);
  1150. return $newfilename;
  1151. }
  1152. public function ResolveFilenameToAbsolute($filename) {
  1153. if (empty($filename)) {
  1154. return false;
  1155. }
  1156. if (preg_match('#^[a-z0-9]+\\:/{1,2}#i', $filename)) {
  1157. // eg: http://host/path/file.jpg (HTTP URL)
  1158. // eg: ftp://host/path/file.jpg (FTP URL)
  1159. // eg: data1:/path/file.jpg (Netware path)
  1160. //$AbsoluteFilename = $filename;
  1161. return $filename;
  1162. } elseif ($this->iswindows && isset($filename[1]) && ($filename[1] == ':')) {
  1163. // absolute pathname (Windows)
  1164. $AbsoluteFilename = $filename;
  1165. } elseif ($this->iswindows && ((substr($filename, 0, 2) == '//') || (substr($filename, 0, 2) == '\\\\'))) {
  1166. // absolute pathname (Windows)
  1167. $AbsoluteFilename = $filename;
  1168. } elseif ($filename[0] == '/') {
  1169. if (@is_readable($filename) && !@is_readable($this->config_document_root.$filename)) {
  1170. // absolute filename (*nix)
  1171. $AbsoluteFilename = $filename;
  1172. } elseif (isset($filename[1]) && ($filename[1] == '~')) {
  1173. // /~user/path
  1174. if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray($filename)) {
  1175. $AbsoluteFilename = $ApacheLookupURIarray['filename'];
  1176. } else {
  1177. $AbsoluteFilename = $this->realPathSafe($filename);
  1178. if (@is_readable($AbsoluteFilename)) {
  1179. $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for "'.$filename.'", but the correct filename ('.$AbsoluteFilename.') seems to have been resolved with $this->realPathSafe($filename)', __FILE__, __LINE__);
  1180. } elseif (is_dir(dirname($AbsoluteFilename))) {
  1181. $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__);
  1182. } else {
  1183. 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")');
  1184. }
  1185. }
  1186. } else {
  1187. // relative filename (any OS)
  1188. if (preg_match('#^'.preg_quote($this->config_document_root).'#', $filename)) {
  1189. $AbsoluteFilename = $filename;
  1190. $this->DebugMessage('ResolveFilenameToAbsolute() NOT prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = "'.$AbsoluteFilename.'")', __FILE__, __LINE__);
  1191. } else {
  1192. $AbsoluteFilename = $this->config_document_root.$filename;
  1193. $this->DebugMessage('ResolveFilenameToAbsolute() prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = "'.$AbsoluteFilename.'")', __FILE__, __LINE__);
  1194. }
  1195. }
  1196. } else {
  1197. // relative to current directory (any OS)
  1198. $AbsoluteFilename = __DIR__ .DIRECTORY_SEPARATOR.preg_replace('#[/\\\\]#', DIRECTORY_SEPARATOR, $filename);
  1199. if (substr(dirname(@$_SERVER['PHP_SELF']), 0, 2) == '/~') {
  1200. if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray(dirname(@$_SERVER['PHP_SELF']))) {
  1201. $AbsoluteFilename = $ApacheLookupURIarray['filename'].DIRECTORY_SEPARATOR.$filename;
  1202. } else {
  1203. $AbsoluteFilename = $this->realPathSafe('.').DIRECTORY_SEPARATOR.$filename;
  1204. if (@is_readable($AbsoluteFilename)) {
  1205. $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__);
  1206. } elseif (is_dir(dirname($AbsoluteFilename))) {
  1207. $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__);
  1208. } else {
  1209. 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');
  1210. }
  1211. }
  1212. }
  1213. }
  1214. /*
  1215. // removed 2014-May-30: http://support.silisoftware.com/phpBB3/viewtopic.php?t=961
  1216. if (is_link($AbsoluteFilename)) {
  1217. $this->DebugMessage('is_link()==true, changing "'.$AbsoluteFilename.'" to "'.readlink($AbsoluteFilename).'"', __FILE__, __LINE__);
  1218. $AbsoluteFilename = readlink($AbsoluteFilename);
  1219. }
  1220. if ($this->realPathSafe($AbsoluteFilename)) {
  1221. $AbsoluteFilename = $this->realPathSafe($AbsoluteFilename);
  1222. }
  1223. */
  1224. if ($this->iswindows) {
  1225. $AbsoluteFilename = preg_replace('#^'.preg_quote($this->realPathSafe($this->config_document_root)).'#i', str_replace('\\', '\\\\', $this->realPathSafe($this->config_document_root)), $AbsoluteFilename);
  1226. $AbsoluteFilename = str_replace(DIRECTORY_SEPARATOR, '/', $AbsoluteFilename);
  1227. }
  1228. $resolvedAbsoluteFilename = $this->resolvePath($AbsoluteFilename, $this->config_additional_allowed_dirs);
  1229. if (!$this->config_allow_src_above_docroot && !preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', $this->realPathSafe($this->config_document_root))).'#', $resolvedAbsoluteFilename)) {
  1230. $this->DebugMessage('!$this->config_allow_src_above_docroot therefore setting "'.$AbsoluteFilename.'" (outside "'.$this->realPathSafe($this->config_document_root).'") to null', __FILE__, __LINE__);
  1231. return false;
  1232. }
  1233. if (!$this->config_allow_src_above_phpthumb && !preg_match('#^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', __DIR__ )).'#', $resolvedAbsoluteFilename)) {
  1234. $this->DebugMessage('!$this->config_allow_src_above_phpthumb therefore setting "'.$AbsoluteFilename.'" (outside "'. __DIR__ .'") to null', __FILE__, __LINE__);
  1235. return false;
  1236. }
  1237. return $resolvedAbsoluteFilename;
  1238. }
  1239. public function file_exists_ignoreopenbasedir($filename, $cached=true) {
  1240. static $open_basedirs = null;
  1241. static $file_exists_cache = array();
  1242. if (!$cached || !isset($file_exists_cache[$filename])) {
  1243. if (null === $open_basedirs) {
  1244. $open_basedirs = preg_split('#[;:]#', ini_get('open_basedir'));
  1245. }
  1246. if (empty($open_basedirs) || in_array(dirname($filename), $open_basedirs)) {
  1247. $file_exists_cache[$filename] = file_exists($filename);
  1248. } elseif ($this->iswindows) {
  1249. $ls_filename = trim(phpthumb_functions::SafeExec('dir /b '.phpthumb_functions::escapeshellarg_replacement($filename)));
  1250. $file_exists_cache[$filename] = ($ls_filename == basename($filename)); // command dir /b return only filename without path
  1251. } else {
  1252. $ls_filename = trim(phpthumb_functions::SafeExec('ls '.phpthumb_functions::escapeshellarg_replacement($filename)));
  1253. $file_exists_cache[$filename] = ($ls_filename == $filename);
  1254. }
  1255. }
  1256. return $file_exists_cache[$filename];
  1257. }
  1258. public function ImageMagickWhichConvert() {
  1259. static $WhichConvert = null;
  1260. if (null === $WhichConvert) {
  1261. if ($this->iswindows) {
  1262. $WhichConvert = false;
  1263. } else {
  1264. $IMwhichConvertCacheFilename = $this->config_cache_directory.DIRECTORY_SEPARATOR.'phpThumbCacheIMwhichConvert.txt';
  1265. if (($cachedwhichconvertstring = @file_get_contents($IMwhichConvertCacheFilename)) !== false) {
  1266. $WhichConvert = $cachedwhichconvertstring;
  1267. } else {
  1268. $WhichConvert = trim(phpthumb_functions::SafeExec('which convert'));
  1269. @file_put_contents($IMwhichConvertCacheFilename, $WhichConvert);
  1270. @chmod($IMwhichConvertCacheFilename, $this->getParameter('config_file_create_mask'));
  1271. }
  1272. }
  1273. }
  1274. return $WhichConvert;
  1275. }
  1276. public function ImageMagickCommandlineBase() {
  1277. static $commandline = null;
  1278. if (null === $commandline) {
  1279. if ($this->issafemode) {
  1280. $commandline = '';
  1281. return $commandline;
  1282. }
  1283. $IMcommandlineBaseCacheFilename = $this->config_cache_directory.DIRECTORY_SEPARATOR.'phpThumbCacheIMcommandlineBase.txt';
  1284. if (($commandline = @file_get_contents($IMcommandlineBaseCacheFilename)) !== false) {
  1285. return $commandline;
  1286. }
  1287. $commandline = (null !== $this->config_imagemagick_path ? $this->config_imagemagick_path : '');
  1288. if ($this->config_imagemagick_path && ($this->config_imagemagick_path != $this->realPathSafe($this->config_imagemagick_path))) {
  1289. if (@is_executable($this->realPathSafe($this->config_imagemagick_path))) {
  1290. $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__);
  1291. $this->config_imagemagick_path = $this->realPathSafe($this->config_imagemagick_path);
  1292. } else {
  1293. $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__);
  1294. }
  1295. }
  1296. $this->DebugMessage(' file_exists('.$this->config_imagemagick_path.') = '. (int) (@file_exists($this->config_imagemagick_path)), __FILE__, __LINE__);
  1297. $this->DebugMessage('file_exists_ignoreopenbasedir('.$this->config_imagemagick_path.') = '. (int) $this->file_exists_ignoreopenbasedir($this->config_imagemagick_path), __FILE__, __LINE__);
  1298. $this->DebugMessage(' is_file('.$this->config_imagemagick_path.') = '. (int) (@is_file($this->config_imagemagick_path)), __FILE__, __LINE__);
  1299. $this->DebugMessage(' is_executable('.$this->config_imagemagick_path.') = '. (int) (@is_executable($this->config_imagemagick_path)), __FILE__, __LINE__);
  1300. if ($this->file_exists_ignoreopenbasedir($this->config_imagemagick_path)) {
  1301. $this->DebugMessage('using ImageMagick path from $this->config_imagemagick_path ('.$this->config_imagemagick_path.')', __FILE__, __LINE__);
  1302. if ($this->iswindows) {
  1303. $commandline = substr($this->config_imagemagick_path, 0, 2).' && cd '.phpthumb_functions::escapeshellarg_replacement(str_replace('/', DIRECTORY_SEPARATOR, substr(dirname($this->config_imagemagick_path), 2))).' && '.phpthumb_functions::escapeshellarg_replacement(basename($this->config_imagemagick_path));
  1304. } else {
  1305. $commandline = phpthumb_functions::escapeshellarg_replacement($this->config_imagemagick_path);
  1306. }
  1307. } else {
  1308. $which_convert = $this->ImageMagickWhichConvert();
  1309. $IMversion = $this->ImageMagickVersion();
  1310. if ($which_convert && ($which_convert[0] == '/') && $this->file_exists_ignoreopenbasedir($which_convert)) {
  1311. // `which convert` *should* return the path if "convert" exist, or nothing if it doesn't
  1312. // other things *may* get returned, like "sh: convert: not found" or "no convert in /usr/local/bin /usr/sbin /usr/bin /usr/ccs/bin"
  1313. // so only do this if the value returned exists as a file
  1314. $this->DebugMessage('using ImageMagick path from `which convert` ('.$which_convert.')', __FILE__, __LINE__);
  1315. $commandline = 'convert';
  1316. } elseif ($IMversion) {
  1317. $this->DebugMessage('setting ImageMagick path to $this->config_imagemagick_path ('.$this->config_imagemagick_path.') ['.$IMversion.']', __FILE__, __LINE__);
  1318. $commandline = $this->config_imagemagick_path;
  1319. } else {
  1320. $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__);
  1321. $commandline = '';
  1322. }
  1323. }
  1324. @file_put_contents($IMcommandlineBaseCacheFilename, $commandline);
  1325. @chmod($IMcommandlineBaseCacheFilename, $this->getParameter('config_file_create_mask'));
  1326. }
  1327. return $commandline;
  1328. }
  1329. public function ImageMagickVersion($returnRAW=false) {
  1330. static $versionstring = null;
  1331. if (null === $versionstring) {
  1332. $versionstring = array(0=>false, 1=>false);
  1333. $IMversionCacheFilename = $this->config_cache_directory.DIRECTORY_SEPARATOR.'phpThumbCacheIMversion.txt';
  1334. if ($cachedversionstring = @file_get_contents($IMversionCacheFilename)) {
  1335. $versionstring = explode("\n", $cachedversionstring, 2);
  1336. $versionstring[0] = ($versionstring[0] ? $versionstring[0] : false); // "false" is stored as an empty string in the cache file
  1337. $versionstring[1] = ($versionstring[1] ? $versionstring[1] : false); // "false" is stored as an empty string in the cache file
  1338. } else {
  1339. $commandline = $this->ImageMagickCommandlineBase();
  1340. $commandline = (null !== $commandline ? $commandline : '');
  1341. if ($commandline) {
  1342. $commandline .= ' --version';
  1343. $this->DebugMessage('ImageMagick version checked with "'.$commandline.'"', __FILE__, __LINE__);
  1344. $versionstring[1] = trim(phpthumb_functions::SafeExec($commandline));
  1345. if (preg_match('#^Version: [^\d]*([ 0-9\\.\\:Q/\\-]+)#i', $versionstring[1], $matches)) {
  1346. $versionstring[0] = trim($matches[1]);
  1347. } else {
  1348. $versionstring[0] = false;
  1349. $this->DebugMessage('ImageMagick did not return recognized version string ('.$versionstring[1].')', __FILE__, __LINE__);
  1350. }
  1351. $this->DebugMessage('ImageMagick convert --version says "'.@$matches[0].'"', __FILE__, __LINE__);
  1352. }
  1353. @file_put_contents($IMversionCacheFilename, $versionstring[0]."\n".$versionstring[1]);
  1354. @chmod($IMversionCacheFilename, $this->getParameter('config_file_create_mask'));
  1355. }
  1356. }
  1357. return $versionstring[ (int) $returnRAW ];
  1358. }
  1359. public function ImageMagickSwitchAvailable($switchname) {
  1360. static $IMoptions = null;
  1361. if (null === $IMoptions) {
  1362. $IMoptions = array();
  1363. $commandline = $this->ImageMagickCommandlineBase();
  1364. if (null !== $commandline) {
  1365. $commandline .= ' -help';
  1366. $IMhelp_lines = explode("\n", phpthumb_functions::SafeExec($commandline));
  1367. foreach ($IMhelp_lines as $line) {
  1368. if (preg_match('#^[\\+\\-]([a-z\\-]+) #', trim($line), $matches)) {
  1369. $IMoptions[$matches[1]] = true;
  1370. }
  1371. }
  1372. }
  1373. }
  1374. if (is_array($switchname)) {
  1375. $allOK = true;
  1376. foreach ($switchname as $key => $value) {
  1377. if (!isset($IMoptions[$value])) {
  1378. $allOK = false;
  1379. break;
  1380. }
  1381. }
  1382. $this->DebugMessage('ImageMagickSwitchAvailable('.implode(';', $switchname).') = '. (int) $allOK .'', __FILE__, __LINE__);
  1383. } else {
  1384. $allOK = isset($IMoptions[$switchname]);
  1385. $this->DebugMessage('ImageMagickSwitchAvailable('.$switchname.') = '. (int) $allOK .'', __FILE__, __LINE__);
  1386. }
  1387. return $allOK;
  1388. }
  1389. public function ImageMagickFormatsList() {
  1390. static $IMformatsList = null;
  1391. if (null === $IMformatsList) {
  1392. $IMformatsList = '';
  1393. $commandline = $this->ImageMagickCommandlineBase();
  1394. if (null !== $commandline) {
  1395. $commandline = dirname($commandline).DIRECTORY_SEPARATOR.str_replace('convert', 'identify', basename($commandline));
  1396. $commandline .= ' -list format';
  1397. $IMformatsList = phpthumb_functions::SafeExec($commandline);
  1398. }
  1399. }
  1400. return $IMformatsList;
  1401. }
  1402. public function SourceDataToTempFile() {
  1403. if ($IMtempSourceFilename = $this->phpThumb_tempnam()) {
  1404. $IMtempSourceFilename = $this->realPathSafe($IMtempSourceFilename);
  1405. ob_start();
  1406. $fp_tempfile = fopen($IMtempSourceFilename, 'wb');
  1407. $tempfile_open_error = ob_get_contents();
  1408. ob_end_clean();
  1409. if ($fp_tempfile) {
  1410. fwrite($fp_tempfile, $this->rawImageData);
  1411. fclose($fp_tempfile);
  1412. @chmod($IMtempSourceFilename, $this->getParameter('config_file_create_mask'));
  1413. $this->sourceFilename = $IMtempSourceFilename;
  1414. $this->DebugMessage('ImageMagickThumbnailToGD() setting $this->sourceFilename to "'.$IMtempSourceFilename.'" from $this->rawImageData ('.strlen($this->rawImageData).' bytes)', __FILE__, __LINE__);
  1415. } else {
  1416. $this->DebugMessage('ImageMagickThumbnailToGD() FAILED setting $this->sourceFilename to "'.$IMtempSourceFilename.'" (failed to open for writing: "'.$tempfile_open_error.'")', __FILE__, __LINE__);
  1417. }
  1418. unset($tempfile_open_error, $IMtempSourceFilename);
  1419. return true;
  1420. }
  1421. $this->DebugMessage('SourceDataToTempFile() FAILED because $this->phpThumb_tempnam() failed', __FILE__, __LINE__);
  1422. return false;
  1423. }
  1424. public function ImageMagickThumbnailToGD() {
  1425. // http://www.imagemagick.org/script/command-line-options.php
  1426. $this->useRawIMoutput = true;
  1427. if (phpthumb_functions::gd_version()) {
  1428. // if GD is not available, must use whatever ImageMagick can output
  1429. // $UnAllowedParameters contains options that can only be processed in GD, not ImageMagick
  1430. // note: 'fltr' *may* need to be processed by GD, but we'll check that in more detail below
  1431. $UnAllowedParameters = array('xto', 'ar', 'bg', 'bc');
  1432. // 'ra' may be part of this list, if not a multiple of 90 degrees
  1433. foreach ($UnAllowedParameters as $parameter) {
  1434. if (isset($this->$parameter)) {
  1435. $this->DebugMessage('$this->useRawIMoutput=false because "'.$parameter.'" is set', __FILE__, __LINE__);
  1436. $this->useRawIMoutput = false;
  1437. break;
  1438. }
  1439. }
  1440. }
  1441. $this->DebugMessage('$this->useRawIMoutput='.($this->useRawIMoutput ? 'true' : 'false').' after checking $UnAllowedParameters', __FILE__, __LINE__);
  1442. $ImageCreateFunction = '';
  1443. $outputFormat = $this->thumbnailFormat;
  1444. if (phpthumb_functions::gd_version()) {
  1445. if ($this->useRawIMoutput) {
  1446. switch ($this->thumbnailFormat) {
  1447. case 'gif':
  1448. $ImageCreateFunction = 'imagecreatefromgif';
  1449. $this->is_alpha = true;
  1450. break;
  1451. case 'png':
  1452. $ImageCreateFunction = 'imagecreatefrompng';
  1453. $this->is_alpha = true;
  1454. break;
  1455. case 'jpg':
  1456. case 'jpeg':
  1457. $ImageCreateFunction = 'imagecreatefromjpeg';
  1458. break;
  1459. case 'webp':
  1460. $ImageCreateFunction = 'imagecreatefromwebp';
  1461. $this->is_alpha = true;
  1462. break;
  1463. default:
  1464. $this->DebugMessage('Forcing output to PNG because $this->thumbnailFormat ('.$this->thumbnailFormat.' is not a GD-supported format)', __FILE__, __LINE__);
  1465. $outputFormat = 'png';
  1466. $ImageCreateFunction = 'imagecreatefrompng';
  1467. $this->is_alpha = true;
  1468. $this->useRawIMoutput = false;
  1469. break;
  1470. }
  1471. if (!function_exists($ImageCreateFunction)) {
  1472. // ImageMagickThumbnailToGD() depends on imagecreatefrompng/imagecreatefromgif
  1473. //$this->DebugMessage('ImageMagickThumbnailToGD() aborting because '.@$ImageCreateFunction.'() is not available', __FILE__, __LINE__);
  1474. $this->useRawIMoutput = true;
  1475. //return false;
  1476. }
  1477. } else {
  1478. $outputFormat = 'png';
  1479. $ImageCreateFunction = 'imagecreatefrompng';
  1480. $this->is_alpha = true;
  1481. $this->useRawIMoutput = false;
  1482. }
  1483. }
  1484. // http://freealter.org/doc_distrib/ImageMagick-5.1.1/www/convert.html
  1485. if (!$this->sourceFilename && $this->rawImageData) {
  1486. $this->SourceDataToTempFile();
  1487. }
  1488. if (!$this->sourceFilename) {
  1489. $this->DebugMessage('ImageMagickThumbnailToGD() aborting because $this->sourceFilename is empty', __FILE__, __LINE__);
  1490. $this->useRawIMoutput = false;
  1491. return false;
  1492. }
  1493. if ($this->issafemode) {
  1494. $this->DebugMessage('ImageMagickThumbnailToGD() aborting because safe_mode is enabled', __FILE__, __LINE__);
  1495. $this->useRawIMoutput = false;
  1496. return false;
  1497. }
  1498. // TO BE FIXED
  1499. //if (true) {
  1500. // $this->DebugMessage('ImageMagickThumbnailToGD() aborting it is broken right now', __FILE__, __LINE__);
  1501. // $this->useRawIMoutput = false;
  1502. // return false;
  1503. //}
  1504. $commandline = $this->ImageMagickCommandlineBase();
  1505. if ($commandline) {
  1506. $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
  1507. if ($IMtempfilename = $this->phpThumb_tempnam()) {
  1508. $IMtempfilename = $this->realPathSafe($IMtempfilename);
  1509. $IMuseExplicitImageOutputDimensions = false;
  1510. if ($this->ImageMagickSwitchAvailable('thumbnail') && $this->config_imagemagick_use_thumbnail) {
  1511. $IMresizeParameter = 'thumbnail';
  1512. } else {
  1513. $IMresizeParameter = 'resize';
  1514. // some (older? around 2002) versions of IM won't accept "-resize 100x" but require "-resize 100x100"
  1515. $commandline_test = $this->ImageMagickCommandlineBase().' logo: -resize 1x '.phpthumb_functions::escapeshellarg_replacement($IMtempfilename).' 2>&1';
  1516. $IMresult_test = phpthumb_functions::SafeExec($commandline_test);
  1517. $IMuseExplicitImageOutputDimensions = preg_match('#image dimensions are zero#i', $IMresult_test);
  1518. $this->DebugMessage('IMuseExplicitImageOutputDimensions = '. (int) $IMuseExplicitImageOutputDimensions, __FILE__, __LINE__);
  1519. if ($fp_im_temp = @fopen($IMtempfilename, 'wb')) {
  1520. // erase temp image so ImageMagick logo doesn't get output if other processing fails
  1521. fclose($fp_im_temp);
  1522. @chmod($IMtempfilename, $this->getParameter('config_file_create_mask'));
  1523. }
  1524. }
  1525. ob_start();
  1526. $getimagesize = getimagesize($this->sourceFilename);
  1527. $GetImageSizeError = ob_get_contents();
  1528. ob_end_clean();
  1529. if (is_array($getimagesize)) {
  1530. $this->DebugMessage('getimagesize('.$this->sourceFilename.') SUCCEEDED: '.print_r($getimagesize, true), __FILE__, __LINE__);
  1531. } else {
  1532. $this->DebugMessage('getimagesize('.$this->sourceFilename.') FAILED with error "'.$GetImageSizeError.'"', __FILE__, __LINE__);
  1533. }
  1534. if (null !== $this->dpi && $this->ImageMagickSwitchAvailable('density')) {
  1535. // for vector source formats only (WMF, PDF, etc)
  1536. if (is_array($getimagesize) && isset($getimagesize[2]) && ($getimagesize[2] == IMAGETYPE_PNG)) {
  1537. // explicitly exclude PNG from "-flatten" to make sure transparency is preserved
  1538. // https://github.com/JamesHeinrich/phpThumb/issues/65
  1539. } else {
  1540. $commandline .= ' -flatten';
  1541. $commandline .= ' -density '.phpthumb_functions::escapeshellarg_replacement($this->dpi);
  1542. }
  1543. }
  1544. if (is_array($getimagesize)) {
  1545. $this->DebugMessage('getimagesize('.$this->sourceFilename.') returned [w='.$getimagesize[0].';h='.$getimagesize[1].';f='.$getimagesize[2].']', __FILE__, __LINE__);
  1546. $this->source_width = $getimagesize[0];
  1547. $this->source_height = $getimagesize[1];
  1548. $this->DebugMessage('source dimensions set to '.$this->source_width.'x'.$this->source_height, __FILE__, __LINE__);
  1549. $this->SetOrientationDependantWidthHeight();
  1550. if (!preg_match('#('.implode('|', $this->AlphaCapableFormats).')#i', $outputFormat)) {
  1551. // not a transparency-capable format
  1552. $commandline .= ' -background '.phpthumb_functions::escapeshellarg_replacement('#'.($this->bg ? $this->bg : 'FFFFFF'));
  1553. if (!stristr($commandline, ' -flatten')) {
  1554. $commandline .= ' -flatten';
  1555. }
  1556. } else {
  1557. if ($getimagesize[2] == IMAGETYPE_PNG && !$this->bg) {
  1558. $commandline .= ' -background none';
  1559. }
  1560. }
  1561. if ($getimagesize[2] == IMAGETYPE_GIF) {
  1562. $commandline .= ' -coalesce'; // may be needed for animated GIFs
  1563. }
  1564. if ($this->source_width || $this->source_height) {
  1565. if ($this->zc) {
  1566. $borderThickness = 0;
  1567. if (!empty($this->fltr)) {
  1568. foreach ($this->fltr as $key => $value) {
  1569. if (preg_match('#^bord\|([\d]+)#', $value, $matches)) {
  1570. $borderThickness = $matches[1];
  1571. break;
  1572. }
  1573. }
  1574. }
  1575. $wAll = (int) max($this->w, $this->wp, $this->wl, $this->ws) - (2 * $borderThickness);
  1576. $hAll = (int) max($this->h, $this->hp, $this->hl, $this->hs) - (2 * $borderThickness);
  1577. $imAR = $this->source_width / $this->source_height;
  1578. $zcAR = (($wAll && $hAll) ? $wAll / $hAll : 1);
  1579. $side = phpthumb_functions::nonempty_min($this->source_width, $this->source_height, max($wAll, $hAll));
  1580. $sideX = phpthumb_functions::nonempty_min($this->source_width, $wAll, round($hAll * $zcAR));
  1581. $sideY = phpthumb_functions::nonempty_min( $this->source_height, $hAll, round($wAll / $zcAR));
  1582. $thumbnailH = round(max($sideY, ($sideY * $zcAR) / $imAR));
  1583. if ($this->aoe == 1) {
  1584. $commandline .= ' -'.$IMresizeParameter.' "'.$wAll.'x'.$hAll.'^"';
  1585. } else {
  1586. $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement(($IMuseExplicitImageOutputDimensions ? $thumbnailH : '').'x'.$thumbnailH);
  1587. }
  1588. switch (strtoupper($this->zc)) {
  1589. case 'T':
  1590. $commandline .= ' -gravity north';
  1591. break;
  1592. case 'B':
  1593. $commandline .= ' -gravity south';
  1594. break;
  1595. case 'L':
  1596. $commandline .= ' -gravity west';
  1597. break;
  1598. case 'R':
  1599. $commandline .= ' -gravity east';
  1600. break;
  1601. case 'TL':
  1602. $commandline .= ' -gravity northwest';
  1603. break;
  1604. case 'TR':
  1605. $commandline .= ' -gravity northeast';
  1606. break;
  1607. case 'BL':
  1608. $commandline .= ' -gravity southwest';
  1609. break;
  1610. case 'BR':
  1611. $commandline .= ' -gravity southeast';
  1612. break;
  1613. case '1':
  1614. case 'C':
  1615. default:
  1616. $commandline .= ' -gravity center';
  1617. break;
  1618. }
  1619. if (($wAll > 0) && ($hAll > 0)) {
  1620. $commandline .= ' -crop '.phpthumb_functions::escapeshellarg_replacement($wAll.'x'.$hAll.'+0+0');
  1621. } else {
  1622. $commandline .= ' -crop '.phpthumb_functions::escapeshellarg_replacement($side.'x'.$side.'+0+0');
  1623. }
  1624. if ($this->ImageMagickSwitchAvailable('repage')) {
  1625. $commandline .= ' +repage';
  1626. } else {
  1627. $this->DebugMessage('Skipping "+repage" because ImageMagick (v'.$this->ImageMagickVersion().') does not support it', __FILE__, __LINE__);
  1628. }
  1629. } elseif ($this->sw || $this->sh || $this->sx || $this->sy) {
  1630. $crop_param = '';
  1631. $crop_param .= ($this->sw ? (($this->sw < 2) ? round($this->sw * $this->source_width) : $this->sw) : $this->source_width);
  1632. $crop_param .= 'x'.($this->sh ? (($this->sh < 2) ? round($this->sh * $this->source_height) : $this->sh) : $this->source_height);
  1633. $crop_param .= '+'.(($this->sx < 2) ? round($this->sx * $this->source_width) : $this->sx);
  1634. $crop_param .= '+'.(($this->sy < 2) ? round($this->sy * $this->source_height) : $this->sy);
  1635. // TO BE FIXED
  1636. // makes 1x1 output
  1637. // 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
  1638. // '/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'
  1639. $commandline .= ' -crop '.phpthumb_functions::escapeshellarg_replacement($crop_param);
  1640. // this is broken for aoe=1, but unsure how to fix. Send advice to info@silisoftware.com
  1641. if ($this->w || $this->h) {
  1642. //if ($this->ImageMagickSwitchAvailable('repage')) {
  1643. if (false) {
  1644. // TO BE FIXED
  1645. // newer versions of ImageMagick require -repage <geometry>
  1646. $commandline .= ' -repage';
  1647. } else {
  1648. $this->DebugMessage('Skipping "-repage" because ImageMagick (v'.$this->ImageMagickVersion().') does not support it', __FILE__, __LINE__);
  1649. }
  1650. if ($IMuseExplicitImageOutputDimensions) {
  1651. if ($this->w && !$this->h) {
  1652. $this->h = ceil($this->w / ($this->source_width / $this->source_height));
  1653. } elseif ($this->h && !$this->w) {
  1654. $this->w = ceil($this->h * ($this->source_width / $this->source_height));
  1655. }
  1656. }
  1657. $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement($this->w.'x'.$this->h);
  1658. }
  1659. } else {
  1660. if ($this->iar && ((int) $this->w > 0) && ((int) $this->h > 0)) {
  1661. list($nw, $nh) = phpthumb_functions::TranslateWHbyAngle($this->w, $this->h, $this->ra);
  1662. $nw = ((round($nw) != 0) ? round($nw) : '');
  1663. $nh = ((round($nh) != 0) ? round($nh) : '');
  1664. $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement($nw.'x'.$nh.'!');
  1665. } elseif ($this->far && ((int) $this->w > 0) && ((int) $this->h > 0)) {
  1666. $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement(phpthumb_functions::nonempty_min($this->w, $getimagesize[0]).'x'.phpthumb_functions::nonempty_min($this->h, $getimagesize[1]));
  1667. $commandline .= ' -gravity center';
  1668. if ($this->bg) {
  1669. $commandline .= ' -background ' . phpthumb_functions::escapeshellarg_replacement('#' . $this->bg);
  1670. } else {
  1671. $commandline .= ' -background none';
  1672. }
  1673. $commandline .= ' -extent '.phpthumb_functions::escapeshellarg_replacement($this->w.'x'.$this->h);
  1674. } else {
  1675. $this->w = (($this->aoe && $this->w) ? $this->w : ($this->w ? phpthumb_functions::nonempty_min($this->w, $getimagesize[0]) : ''));
  1676. $this->h = (($this->aoe && $this->h) ? $this->h : ($this->h ? phpthumb_functions::nonempty_min($this->h, $getimagesize[1]) : ''));
  1677. if ($this->w || $this->h) {
  1678. if ($IMuseExplicitImageOutputDimensions) {
  1679. if ($this->w && !$this->h) {
  1680. $this->h = ceil($this->w / ($this->source_width / $this->source_height));
  1681. } elseif ($this->h && !$this->w) {
  1682. $this->w = ceil($this->h * ($this->source_width / $this->source_height));
  1683. }
  1684. }
  1685. list($nw, $nh) = phpthumb_functions::TranslateWHbyAngle($this->w, $this->h, $this->ra);
  1686. $nw = ((round($nw) != 0) ? round($nw) : '');
  1687. $nh = ((round($nh) != 0) ? round($nh) : '');
  1688. $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement($nw.'x'.$nh);
  1689. }
  1690. }
  1691. }
  1692. }
  1693. } else {
  1694. $this->DebugMessage('getimagesize('.$this->sourceFilename.') failed', __FILE__, __LINE__);
  1695. if ($this->w || $this->h) {
  1696. $exactDimensionsBang = (($this->iar && ((int) $this->w > 0) && ((int) $this->h > 0)) ? '!' : '');
  1697. if ($IMuseExplicitImageOutputDimensions) {
  1698. // unknown source aspect ratio, just put large number and hope IM figures it out
  1699. $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement(($this->w ? $this->w : '9999').'x'.($this->h ? $this->h : '9999').$exactDimensionsBang);
  1700. } else {
  1701. $commandline .= ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement($this->w.'x'.$this->h.$exactDimensionsBang);
  1702. }
  1703. }
  1704. }
  1705. if ($this->ra) {
  1706. $this->ra = (int) $this->ra;
  1707. if ($this->ImageMagickSwitchAvailable('rotate')) {
  1708. if (!preg_match('#('.implode('|', $this->AlphaCapableFormats).')#i', $outputFormat) || phpthumb_functions::version_compare_replacement($this->ImageMagickVersion(), '6.3.7', '>=')) {
  1709. $this->DebugMessage('Using ImageMagick rotate', __FILE__, __LINE__);
  1710. $commandline .= ' -rotate '.phpthumb_functions::escapeshellarg_replacement($this->ra);
  1711. if (($this->ra % 90) != 0) {
  1712. if (preg_match('#('.implode('|', $this->AlphaCapableFormats).')#i', $outputFormat)) {
  1713. // alpha-capable format
  1714. $commandline .= ' -background rgba(255,255,255,0)';
  1715. } else {
  1716. $commandline .= ' -background '.phpthumb_functions::escapeshellarg_replacement('#'.($this->bg ? $this->bg : 'FFFFFF'));
  1717. }
  1718. }
  1719. $this->ra = 0;
  1720. } else {
  1721. $this->DebugMessage('Not using ImageMagick rotate because alpha background buggy before v6.3.7', __FILE__, __LINE__);
  1722. }
  1723. } else {
  1724. $this->DebugMessage('Not using ImageMagick rotate because not supported', __FILE__, __LINE__);
  1725. }
  1726. }
  1727. $successfullyProcessedFilters = array();
  1728. foreach ($this->fltr as $filterkey => $filtercommand) {
  1729. @list($command, $parameter) = explode('|', $filtercommand, 2);
  1730. switch ($command) {
  1731. case 'brit':
  1732. if ($this->ImageMagickSwitchAvailable('modulate')) {
  1733. $commandline .= ' -modulate '.phpthumb_functions::escapeshellarg_replacement((100 + (int) $parameter).',100,100');
  1734. $successfullyProcessedFilters[] = $filterkey;
  1735. }
  1736. break;
  1737. case 'cont':
  1738. if ($this->ImageMagickSwitchAvailable('contrast')) {
  1739. $contDiv10 = round((int) $parameter / 10);
  1740. if ($contDiv10 > 0) {
  1741. $contDiv10 = min($contDiv10, 100);
  1742. for ($i = 0; $i < $contDiv10; $i++) {
  1743. $commandline .= ' -contrast'; // increase contrast by 10%
  1744. }
  1745. } elseif ($contDiv10 < 0) {
  1746. $contDiv10 = max($contDiv10, -100);
  1747. for ($i = $contDiv10; $i < 0; $i++) {
  1748. $commandline .= ' +contrast'; // decrease contrast by 10%
  1749. }
  1750. } else {
  1751. // do nothing
  1752. }
  1753. $successfullyProcessedFilters[] = $filterkey;
  1754. }
  1755. break;
  1756. case 'ds':
  1757. if ($this->ImageMagickSwitchAvailable(array('colorspace', 'modulate'))) {
  1758. if ($parameter == 100) {
  1759. $commandline .= ' -colorspace GRAY';
  1760. $commandline .= ' -modulate 100,0,100';
  1761. } else {
  1762. $commandline .= ' -modulate '.phpthumb_functions::escapeshellarg_replacement('100,'.(100 - (int) $parameter).',100');
  1763. }
  1764. $successfullyProcessedFilters[] = $filterkey;
  1765. }
  1766. break;
  1767. case 'sat':
  1768. if ($this->ImageMagickSwitchAvailable(array('colorspace', 'modulate'))) {
  1769. if ($parameter == -100) {
  1770. $commandline .= ' -colorspace GRAY';
  1771. $commandline .= ' -modulate 100,0,100';
  1772. } else {
  1773. $commandline .= ' -modulate '.phpthumb_functions::escapeshellarg_replacement('100,'.(100 + (int) $parameter).',100');
  1774. }
  1775. $successfullyProcessedFilters[] = $filterkey;
  1776. }
  1777. break;
  1778. case 'gray':
  1779. if ($this->ImageMagickSwitchAvailable(array('colorspace', 'modulate'))) {
  1780. $commandline .= ' -colorspace GRAY';
  1781. $commandline .= ' -modulate 100,0,100';
  1782. $successfullyProcessedFilters[] = $filterkey;
  1783. }
  1784. break;
  1785. case 'clr':
  1786. if ($this->ImageMagickSwitchAvailable(array('fill', 'colorize'))) {
  1787. @list($amount, $color) = explode('|', $parameter);
  1788. $commandline .= ' -fill '.phpthumb_functions::escapeshellarg_replacement('#'.preg_replace('#[^0-9A-F]#i', '', $color));
  1789. $commandline .= ' -colorize '.phpthumb_functions::escapeshellarg_replacement(min(max((int) $amount, 0), 100));
  1790. $successfullyProcessedFilters[] = $filterkey;
  1791. }
  1792. break;
  1793. case 'sep':
  1794. if ($this->ImageMagickSwitchAvailable('sepia-tone')) {
  1795. @list($amount, $color) = explode('|', $parameter);
  1796. $amount = ($amount ? $amount : 80);
  1797. if (!$color) {
  1798. $commandline .= ' -sepia-tone '.phpthumb_functions::escapeshellarg_replacement(min(max((int) $amount, 0), 100).'%');
  1799. $successfullyProcessedFilters[] = $filterkey;
  1800. }
  1801. }
  1802. break;
  1803. case 'gam':
  1804. @list($amount) = explode('|', $parameter);
  1805. $amount = min(max((float) $amount, 0.001), 10);
  1806. if (number_format($amount, 3) != '1.000') {
  1807. if ($this->ImageMagickSwitchAvailable('gamma')) {
  1808. $commandline .= ' -gamma '.phpthumb_functions::escapeshellarg_replacement($amount);
  1809. $successfullyProcessedFilters[] = $filterkey;
  1810. }
  1811. }
  1812. break;
  1813. case 'neg':
  1814. if ($this->ImageMagickSwitchAvailable('negate')) {
  1815. $commandline .= ' -negate';
  1816. $successfullyProcessedFilters[] = $filterkey;
  1817. }
  1818. break;
  1819. case 'th':
  1820. @list($amount) = explode('|', $parameter);
  1821. if ($this->ImageMagickSwitchAvailable(array('threshold', 'dither', 'monochrome'))) {
  1822. $commandline .= ' -threshold '.phpthumb_functions::escapeshellarg_replacement(round(min(max((int) $amount, 0), 255) / 2.55).'%');
  1823. $commandline .= ' -dither';
  1824. $commandline .= ' -monochrome';
  1825. $successfullyProcessedFilters[] = $filterkey;
  1826. }
  1827. break;
  1828. case 'rcd':
  1829. if ($this->ImageMagickSwitchAvailable(array('colors', 'dither'))) {
  1830. @list($colors, $dither) = explode('|', $parameter);
  1831. $colors = ($colors ? (int) $colors : 256);
  1832. $dither = ((strlen($dither) > 0) ? (bool) $dither : true);
  1833. $commandline .= ' -colors '.phpthumb_functions::escapeshellarg_replacement(max($colors, 8)); // ImageMagick will otherwise fail with "cannot quantize to fewer than 8 colors"
  1834. $commandline .= ($dither ? ' -dither' : ' +dither');
  1835. $successfullyProcessedFilters[] = $filterkey;
  1836. }
  1837. break;
  1838. case 'flip':
  1839. if ($this->ImageMagickSwitchAvailable(array('flip', 'flop'))) {
  1840. if (strpos(strtolower($parameter), 'x') !== false) {
  1841. $commandline .= ' -flop';
  1842. }
  1843. if (strpos(strtolower($parameter), 'y') !== false) {
  1844. $commandline .= ' -flip';
  1845. }
  1846. $successfullyProcessedFilters[] = $filterkey;
  1847. }
  1848. break;
  1849. case 'edge':
  1850. if ($this->ImageMagickSwitchAvailable('edge')) {
  1851. $parameter = (!empty($parameter) ? $parameter : 2);
  1852. $commandline .= ' -edge '.phpthumb_functions::escapeshellarg_replacement(!empty($parameter) ? (int) $parameter : 1);
  1853. $successfullyProcessedFilters[] = $filterkey;
  1854. }
  1855. break;
  1856. case 'emb':
  1857. if ($this->ImageMagickSwitchAvailable(array('emboss', 'negate'))) {
  1858. $parameter = (!empty($parameter) ? $parameter : 2);
  1859. $commandline .= ' -emboss '.phpthumb_functions::escapeshellarg_replacement((int) $parameter);
  1860. if ($parameter < 2) {
  1861. $commandline .= ' -negate'; // ImageMagick negates the image for some reason with '-emboss 1';
  1862. }
  1863. $successfullyProcessedFilters[] = $filterkey;
  1864. }
  1865. break;
  1866. case 'lvl':
  1867. @list($band, $method, $threshold) = explode('|', $parameter);
  1868. $band = ($band ? preg_replace('#[^RGBA\\*]#', '', strtoupper($band)) : '*');
  1869. $method = ((strlen($method) > 0) ? (int) $method : 2);
  1870. $threshold = ((strlen($threshold) > 0) ? min(max((float) $threshold, 0), 100) : 0.1);
  1871. $band = preg_replace('#[^RGBA\\*]#', '', strtoupper($band));
  1872. if (($method > 1) && !$this->ImageMagickSwitchAvailable(array('channel', 'contrast-stretch'))) {
  1873. // Because ImageMagick processing happens before PHP-GD filters, and because some
  1874. // clipping is involved in the "lvl" filter, if "lvl" happens before "wb" then the
  1875. // "wb" filter will have (almost) no effect. Therefore, if "wb" is enabled then
  1876. // force the "lvl" filter to be processed by GD, not ImageMagick.
  1877. foreach ($this->fltr as $fltr_key => $fltr_value) {
  1878. list($fltr_cmd) = explode('|', $fltr_value);
  1879. if ($fltr_cmd == 'wb') {
  1880. $this->DebugMessage('Setting "lvl" filter method to "0" (from "'.$method.'") because white-balance filter also enabled', __FILE__, __LINE__);
  1881. $method = 0;
  1882. }
  1883. }
  1884. }
  1885. switch ($method) {
  1886. case 0: // internal RGB
  1887. case 1: // internal grayscale
  1888. break;
  1889. case 2: // ImageMagick "contrast-stretch"
  1890. if ($this->ImageMagickSwitchAvailable('contrast-stretch')) {
  1891. if ($band != '*') {
  1892. $commandline .= ' -channel '.phpthumb_functions::escapeshellarg_replacement(strtoupper($band));
  1893. }
  1894. $threshold = preg_replace('#[^0-9\\.]#', '', $threshold); // should be unneccesary, but just to be double-sure
  1895. //$commandline .= ' -contrast-stretch '.phpthumb_functions::escapeshellarg_replacement($threshold.'%');
  1896. $commandline .= ' -contrast-stretch \''.$threshold.'%\'';
  1897. if ($band != '*') {
  1898. $commandline .= ' +channel';
  1899. }
  1900. $successfullyProcessedFilters[] = $filterkey;
  1901. }
  1902. break;
  1903. case 3: // ImageMagick "normalize"
  1904. if ($this->ImageMagickSwitchAvailable('normalize')) {
  1905. if ($band != '*') {
  1906. $commandline .= ' -channel '.phpthumb_functions::escapeshellarg_replacement(strtoupper($band));
  1907. }
  1908. $commandline .= ' -normalize';
  1909. if ($band != '*') {
  1910. $commandline .= ' +channel';
  1911. }
  1912. $successfullyProcessedFilters[] = $filterkey;
  1913. }
  1914. break;
  1915. default:
  1916. $this->DebugMessage('unsupported method ('.$method.') for "lvl" filter', __FILE__, __LINE__);
  1917. break;
  1918. }
  1919. if (isset($this->fltr[$filterkey]) && ($method > 1)) {
  1920. $this->fltr[$filterkey] = $command.'|'.$band.'|0|'.$threshold;
  1921. $this->DebugMessage('filter "lvl" remapped from method "'.$method.'" to method "0" because ImageMagick support is missing', __FILE__, __LINE__);
  1922. }
  1923. break;
  1924. case 'wb':
  1925. if ($this->ImageMagickSwitchAvailable(array('channel', 'contrast-stretch'))) {
  1926. @list($threshold) = explode('|', $parameter);
  1927. $threshold = (!empty($threshold) ? min(max((float) $threshold, 0), 100) : 0.1);
  1928. $threshold = preg_replace('#[^0-9\\.]#', '', $threshold); // should be unneccesary, but just to be double-sure
  1929. //$commandline .= ' -channel R -contrast-stretch '.phpthumb_functions::escapeshellarg_replacement($threshold.'%'); // doesn't work on Windows because most versions of PHP do not properly
  1930. //$commandline .= ' -channel G -contrast-stretch '.phpthumb_functions::escapeshellarg_replacement($threshold.'%'); // escape special characters (such as %) and just replace them with spaces
  1931. //$commandline .= ' -channel B -contrast-stretch '.phpthumb_functions::escapeshellarg_replacement($threshold.'%'); // https://bugs.php.net/bug.php?id=43261
  1932. $commandline .= ' -channel R -contrast-stretch \''.$threshold.'%\'';
  1933. $commandline .= ' -channel G -contrast-stretch \''.$threshold.'%\'';
  1934. $commandline .= ' -channel B -contrast-stretch \''.$threshold.'%\'';
  1935. $commandline .= ' +channel';
  1936. $successfullyProcessedFilters[] = $filterkey;
  1937. }
  1938. break;
  1939. case 'blur':
  1940. if ($this->ImageMagickSwitchAvailable('blur')) {
  1941. @list($radius) = explode('|', $parameter);
  1942. $radius = (!empty($radius) ? min(max((int) $radius, 0), 25) : 1);
  1943. $commandline .= ' -blur '.phpthumb_functions::escapeshellarg_replacement($radius);
  1944. $successfullyProcessedFilters[] = $filterkey;
  1945. }
  1946. break;
  1947. case 'gblr':
  1948. @list($radius) = explode('|', $parameter);
  1949. $radius = (!empty($radius) ? min(max((int) $radius, 0), 25) : 1);
  1950. // "-gaussian" changed to "-gaussian-blur" sometime around 2009
  1951. if ($this->ImageMagickSwitchAvailable('gaussian-blur')) {
  1952. $commandline .= ' -gaussian-blur '.phpthumb_functions::escapeshellarg_replacement($radius);
  1953. $successfullyProcessedFilters[] = $filterkey;
  1954. } elseif ($this->ImageMagickSwitchAvailable('gaussian')) {
  1955. $commandline .= ' -gaussian '.phpthumb_functions::escapeshellarg_replacement($radius);
  1956. $successfullyProcessedFilters[] = $filterkey;
  1957. }
  1958. break;
  1959. case 'usm':
  1960. if ($this->ImageMagickSwitchAvailable('unsharp')) {
  1961. @list($amount, $radius, $threshold) = explode('|', $parameter);
  1962. $amount = ($amount ? min(max((int) $amount, 0), 255) : 80);
  1963. $radius = ($radius ? min(max((int) $radius, 0), 10) : 0.5);
  1964. $threshold = ('' !== $threshold ? min(max((int) $threshold, 0), 50) : 3);
  1965. $commandline .= ' -unsharp '.phpthumb_functions::escapeshellarg_replacement(number_format(($radius * 2) - 1, 2, '.', '').'x1+'.number_format($amount / 100, 2, '.', '').'+'.number_format($threshold / 100, 2, '.', ''));
  1966. $successfullyProcessedFilters[] = $filterkey;
  1967. }
  1968. break;
  1969. case 'bord':
  1970. if ($this->ImageMagickSwitchAvailable(array('border', 'bordercolor', 'thumbnail', 'crop'))) {
  1971. if (!$this->zc) {
  1972. @list($width, $rX, $rY, $color) = explode('|', $parameter);
  1973. $width = (int) $width;
  1974. $rX = (int) $rX;
  1975. $rY = (int) $rY;
  1976. if ($width && !$rX && !$rY) {
  1977. if (!phpthumb_functions::IsHexColor($color)) {
  1978. $color = ((!empty($this->bc) && phpthumb_functions::IsHexColor($this->bc)) ? $this->bc : '000000');
  1979. }
  1980. $commandline .= ' -border '.phpthumb_functions::escapeshellarg_replacement((int) $width);
  1981. $commandline .= ' -bordercolor '.phpthumb_functions::escapeshellarg_replacement('#'.$color);
  1982. if (preg_match('# \\-crop "([\d]+)x([\d]+)\\+0\\+0" #', $commandline, $matches)) {
  1983. $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);
  1984. } elseif (preg_match('# \\-'.$IMresizeParameter.' "([0-9]+)x([0-9]+)" #', $commandline, $matches)) {
  1985. $commandline = str_replace(' -'.$IMresizeParameter.' "'.$matches[1].'x'.$matches[2].'" ', ' -'.$IMresizeParameter.' '.phpthumb_functions::escapeshellarg_replacement(($matches[1] - (2 * $width)).'x'.($matches[2] - (2 * $width))).' ', $commandline);
  1986. }
  1987. $successfullyProcessedFilters[] = $filterkey;
  1988. }
  1989. }
  1990. }
  1991. break;
  1992. case 'crop':
  1993. break;
  1994. case 'sblr':
  1995. break;
  1996. case 'mean':
  1997. break;
  1998. case 'smth':
  1999. break;
  2000. case 'bvl':
  2001. break;
  2002. case 'wmi':
  2003. break;
  2004. case 'wmt':
  2005. break;
  2006. case 'over':
  2007. break;
  2008. case 'hist':
  2009. break;
  2010. case 'fram':
  2011. break;
  2012. case 'drop':
  2013. break;
  2014. case 'mask':
  2015. break;
  2016. case 'elip':
  2017. break;
  2018. case 'ric':
  2019. break;
  2020. case 'stc':
  2021. break;
  2022. case 'size':
  2023. break;
  2024. default:
  2025. $this->DebugMessage('Unknown $this->fltr['.$filterkey.'] ('.$filtercommand.') -- deleting filter command', __FILE__, __LINE__);
  2026. $successfullyProcessedFilters[] = $filterkey;
  2027. break;
  2028. }
  2029. if (!isset($this->fltr[$filterkey])) {
  2030. $this->DebugMessage('Processed $this->fltr['.$filterkey.'] ('.$filtercommand.') with ImageMagick', __FILE__, __LINE__);
  2031. } else {
  2032. $this->DebugMessage('Skipping $this->fltr['.$filterkey.'] ('.$filtercommand.') with ImageMagick', __FILE__, __LINE__);
  2033. }
  2034. }
  2035. $this->DebugMessage('Remaining $this->fltr after ImageMagick: ('.$this->phpThumbDebugVarDump($this->fltr).')', __FILE__, __LINE__);
  2036. if (count($this->fltr) > 0) {
  2037. $this->useRawIMoutput = false;
  2038. }
  2039. if (preg_match('#jpe?g#i', $outputFormat) && $this->q) {
  2040. if ($this->ImageMagickSwitchAvailable(array('quality', 'interlace'))) {
  2041. $commandline .= ' -quality '.phpthumb_functions::escapeshellarg_replacement($this->thumbnailQuality);
  2042. if ($this->config_output_interlace) {
  2043. // causes weird things with animated GIF... leave for JPEG only
  2044. $commandline .= ' -interlace line '; // Use Line or Plane to create an interlaced PNG or GIF or progressive JPEG image
  2045. }
  2046. }
  2047. }
  2048. $commandline .= ' '.$outputFormat.':'.phpthumb_functions::escapeshellarg_replacement($IMtempfilename);
  2049. if (!$this->iswindows) {
  2050. $commandline .= ' 2>&1';
  2051. }
  2052. $this->DebugMessage('ImageMagick called as ('.$commandline.')', __FILE__, __LINE__);
  2053. $IMresult = phpthumb_functions::SafeExec($commandline);
  2054. clearstatcache();
  2055. if (!@file_exists($IMtempfilename) || !@filesize($IMtempfilename)) {
  2056. $this->FatalError('ImageMagick failed with message ('.trim($IMresult).')');
  2057. $this->DebugMessage('ImageMagick failed with message ('.trim($IMresult).')', __FILE__, __LINE__);
  2058. if ($this->iswindows && !$IMresult) {
  2059. $this->DebugMessage('Check to make sure that PHP has read+write permissions to "'.dirname($IMtempfilename).'"', __FILE__, __LINE__);
  2060. }
  2061. } else {
  2062. foreach ($successfullyProcessedFilters as $dummy => $filterkey) {
  2063. unset($this->fltr[$filterkey]);
  2064. }
  2065. $this->IMresizedData = file_get_contents($IMtempfilename);
  2066. $getimagesize_imresized = @getimagesize($IMtempfilename);
  2067. $this->DebugMessage('getimagesize('.$IMtempfilename.') returned [w='.$getimagesize_imresized[0].';h='.$getimagesize_imresized[1].';f='.$getimagesize_imresized[2].']', __FILE__, __LINE__);
  2068. if (($this->config_max_source_pixels > 0) && (($getimagesize_imresized[0] * $getimagesize_imresized[1]) > $this->config_max_source_pixels)) {
  2069. $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__);
  2070. } elseif (function_exists(@$ImageCreateFunction) && ($this->gdimg_source = @$ImageCreateFunction($IMtempfilename))) {
  2071. $this->source_width = imagesx($this->gdimg_source);
  2072. $this->source_height = imagesy($this->gdimg_source);
  2073. $this->DebugMessage('ImageMagickThumbnailToGD::'.$ImageCreateFunction.'() succeeded, $this->gdimg_source is now ('.$this->source_width.'x'.$this->source_height.')', __FILE__, __LINE__);
  2074. $this->DebugMessage('ImageMagickThumbnailToGD() returning $this->IMresizedData ('.strlen($this->IMresizedData).' bytes)', __FILE__, __LINE__);
  2075. } else {
  2076. $this->useRawIMoutput = true;
  2077. $this->DebugMessage('$this->useRawIMoutput set to TRUE because '.@$ImageCreateFunction.'('.$IMtempfilename.') failed', __FILE__, __LINE__);
  2078. }
  2079. if (file_exists($IMtempfilename)) {
  2080. $this->DebugMessage('deleting "'.$IMtempfilename.'"', __FILE__, __LINE__);
  2081. @unlink($IMtempfilename);
  2082. }
  2083. return true;
  2084. }
  2085. if (file_exists($IMtempfilename)) {
  2086. $this->DebugMessage('deleting "'.$IMtempfilename.'"', __FILE__, __LINE__);
  2087. @unlink($IMtempfilename);
  2088. }
  2089. } elseif ($this->issafemode) {
  2090. $this->DebugMessage('ImageMagickThumbnailToGD() aborting because PHP safe_mode is enabled and phpThumb_tempnam() failed', __FILE__, __LINE__);
  2091. $this->useRawIMoutput = false;
  2092. } else {
  2093. if (file_exists($IMtempfilename)) {
  2094. $this->DebugMessage('deleting "'.$IMtempfilename.'"', __FILE__, __LINE__);
  2095. @unlink($IMtempfilename);
  2096. }
  2097. $this->DebugMessage('ImageMagickThumbnailToGD() aborting, phpThumb_tempnam() failed', __FILE__, __LINE__);
  2098. }
  2099. } else {
  2100. $this->DebugMessage('ImageMagickThumbnailToGD() aborting because ImageMagickCommandlineBase() failed', __FILE__, __LINE__);
  2101. }
  2102. $this->useRawIMoutput = false;
  2103. return false;
  2104. }
  2105. public function Rotate() {
  2106. if ($this->ra || $this->ar) {
  2107. if (!function_exists('imagerotate')) {
  2108. $this->DebugMessage('!function_exists(imagerotate)', __FILE__, __LINE__);
  2109. return false;
  2110. }
  2111. if (!include_once __DIR__ .'/phpthumb.filters.php' ) {
  2112. $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.filters.php" which is required for applying filters ('.implode(';', $this->fltr).')', __FILE__, __LINE__);
  2113. return false;
  2114. }
  2115. $this->config_background_hexcolor = ($this->bg ? $this->bg : $this->config_background_hexcolor);
  2116. if (!phpthumb_functions::IsHexColor($this->config_background_hexcolor)) {
  2117. return $this->ErrorImage('Invalid hex color string "'.$this->config_background_hexcolor.'" for parameter "bg"');
  2118. }
  2119. $rotate_angle = 0;
  2120. if ($this->ra) {
  2121. $rotate_angle = (float) $this->ra;
  2122. } else {
  2123. if ($this->ar == 'x') {
  2124. if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.2.0', '>=')) {
  2125. if ($this->sourceFilename) {
  2126. if (function_exists('exif_read_data')) {
  2127. if ($exif_data = @exif_read_data($this->sourceFilename, 'IFD0')) {
  2128. // http://sylvana.net/jpegcrop/exif_orientation.html
  2129. switch (@$exif_data['Orientation']) {
  2130. case 1:
  2131. $rotate_angle = 0;
  2132. break;
  2133. case 3:
  2134. $rotate_angle = 180;
  2135. break;
  2136. case 6:
  2137. $rotate_angle = 270;
  2138. break;
  2139. case 8:
  2140. $rotate_angle = 90;
  2141. break;
  2142. default:
  2143. $this->DebugMessage('EXIF auto-rotate failed because unknown $exif_data[Orientation] "'.@$exif_data['Orientation'].'"', __FILE__, __LINE__);
  2144. return false;
  2145. break;
  2146. }
  2147. $this->DebugMessage('EXIF auto-rotate set to '.$rotate_angle.' degrees ($exif_data[Orientation] = "'.@$exif_data['Orientation'].'")', __FILE__, __LINE__);
  2148. } else {
  2149. $this->DebugMessage('failed: exif_read_data('.$this->sourceFilename.')', __FILE__, __LINE__);
  2150. return false;
  2151. }
  2152. } else {
  2153. $this->DebugMessage('!function_exists(exif_read_data)', __FILE__, __LINE__);
  2154. return false;
  2155. }
  2156. } else {
  2157. $this->DebugMessage('Cannot auto-rotate from EXIF data because $this->sourceFilename is empty', __FILE__, __LINE__);
  2158. return false;
  2159. }
  2160. } else {
  2161. $this->DebugMessage('Cannot auto-rotate from EXIF data because PHP is less than v4.2.0 ('. PHP_VERSION .')', __FILE__, __LINE__);
  2162. return false;
  2163. }
  2164. } elseif (($this->ar == 'l') && ($this->source_height > $this->source_width)) {
  2165. $rotate_angle = 270;
  2166. } elseif (($this->ar == 'L') && ($this->source_height > $this->source_width)) {
  2167. $rotate_angle = 90;
  2168. } elseif (($this->ar == 'p') && ($this->source_width > $this->source_height)) {
  2169. $rotate_angle = 90;
  2170. } elseif (($this->ar == 'P') && ($this->source_width > $this->source_height)) {
  2171. $rotate_angle = 270;
  2172. }
  2173. }
  2174. if ($rotate_angle % 90) {
  2175. $this->is_alpha = true;
  2176. }
  2177. phpthumb_filters::ImprovedImageRotate($this->gdimg_source, $rotate_angle, $this->config_background_hexcolor, $this->bg, $this);
  2178. $this->source_width = imagesx($this->gdimg_source);
  2179. $this->source_height = imagesy($this->gdimg_source);
  2180. }
  2181. return true;
  2182. }
  2183. public function FixedAspectRatio() {
  2184. // optional fixed-dimension images (regardless of aspect ratio)
  2185. if (!$this->far) {
  2186. // do nothing
  2187. return true;
  2188. }
  2189. if (!$this->w || !$this->h) {
  2190. return false;
  2191. }
  2192. $this->thumbnail_width = $this->w;
  2193. $this->thumbnail_height = $this->h;
  2194. $this->is_alpha = true;
  2195. if ($this->thumbnail_image_width >= $this->thumbnail_width) {
  2196. $aspectratio = $this->thumbnail_image_height / $this->thumbnail_image_width;
  2197. if ($this->w) {
  2198. $this->thumbnail_image_height = round($this->thumbnail_image_width * $aspectratio);
  2199. $this->thumbnail_height = ($this->h ? $this->h : $this->thumbnail_image_height);
  2200. } elseif ($this->thumbnail_image_height < $this->thumbnail_height) {
  2201. $this->thumbnail_image_height = $this->thumbnail_height;
  2202. $this->thumbnail_image_width = round($this->thumbnail_image_height / $aspectratio);
  2203. }
  2204. } else {
  2205. $aspectratio = $this->thumbnail_image_width / $this->thumbnail_image_height;
  2206. if ($this->h) {
  2207. $this->thumbnail_image_width = round($this->thumbnail_image_height * $aspectratio);
  2208. } elseif ($this->thumbnail_image_width < $this->thumbnail_width) {
  2209. $this->thumbnail_image_width = $this->thumbnail_width;
  2210. $this->thumbnail_image_height = round($this->thumbnail_image_width / $aspectratio);
  2211. }
  2212. }
  2213. return true;
  2214. }
  2215. public function OffsiteDomainIsAllowed($hostname, $allowed_domains) {
  2216. static $domain_is_allowed = array();
  2217. $hostname = strtolower($hostname);
  2218. if (!isset($domain_is_allowed[$hostname])) {
  2219. $domain_is_allowed[$hostname] = false;
  2220. foreach ($allowed_domains as $valid_domain) {
  2221. $starpos = strpos($valid_domain, '*');
  2222. if ($starpos !== false) {
  2223. $valid_domain = substr($valid_domain, $starpos + 1);
  2224. if (preg_match('#'.preg_quote($valid_domain).'$#', $hostname)) {
  2225. $domain_is_allowed[$hostname] = true;
  2226. break;
  2227. }
  2228. } else {
  2229. if (strtolower($valid_domain) === $hostname) {
  2230. $domain_is_allowed[$hostname] = true;
  2231. break;
  2232. }
  2233. }
  2234. }
  2235. }
  2236. return $domain_is_allowed[$hostname];
  2237. }
  2238. public function AntiOffsiteLinking() {
  2239. // Optional anti-offsite hijacking of the thumbnail script
  2240. $allow = true;
  2241. if ($allow && $this->config_nooffsitelink_enabled && (@$_SERVER['HTTP_REFERER'] || $this->config_nooffsitelink_require_refer)) {
  2242. $this->DebugMessage('AntiOffsiteLinking() checking $_SERVER[HTTP_REFERER] "'.@$_SERVER['HTTP_REFERER'].'"', __FILE__, __LINE__);
  2243. foreach ($this->config_nooffsitelink_valid_domains as $key => $valid_domain) {
  2244. // $_SERVER['HTTP_HOST'] contains the port number, so strip it out here to make default configuration work
  2245. list($clean_domain) = explode(':', $valid_domain);
  2246. $this->config_nooffsitelink_valid_domains[$key] = $clean_domain;
  2247. }
  2248. $parsed_url = phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);
  2249. if (!$this->OffsiteDomainIsAllowed(@$parsed_url['host'], $this->config_nooffsitelink_valid_domains)) {
  2250. $allow = false;
  2251. //$this->DebugMessage('AntiOffsiteLinking() - "'.@$parsed_url['host'].'" is NOT in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);
  2252. $this->ErrorImage('AntiOffsiteLinking() - "'.@$parsed_url['host'].'" is NOT in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')');
  2253. } else {
  2254. $this->DebugMessage('AntiOffsiteLinking() - "'.@$parsed_url['host'].'" is in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);
  2255. }
  2256. }
  2257. if ($allow && $this->config_nohotlink_enabled && preg_match('#^(f|ht)tps?\://#i', $this->src)) {
  2258. $parsed_url = phpthumb_functions::ParseURLbetter($this->src);
  2259. //if (!phpthumb_functions::CaseInsensitiveInArray(@$parsed_url['host'], $this->config_nohotlink_valid_domains)) {
  2260. if (!$this->OffsiteDomainIsAllowed(@$parsed_url['host'], $this->config_nohotlink_valid_domains)) {
  2261. // This domain is not allowed
  2262. $allow = false;
  2263. $this->DebugMessage('AntiOffsiteLinking() - "'.$parsed_url['host'].'" is NOT in $this->config_nohotlink_valid_domains ('.implode(';', $this->config_nohotlink_valid_domains).')', __FILE__, __LINE__);
  2264. } else {
  2265. $this->DebugMessage('AntiOffsiteLinking() - "'.$parsed_url['host'].'" is in $this->config_nohotlink_valid_domains ('.implode(';', $this->config_nohotlink_valid_domains).')', __FILE__, __LINE__);
  2266. }
  2267. }
  2268. if ($allow) {
  2269. $this->DebugMessage('AntiOffsiteLinking() says this is allowed', __FILE__, __LINE__);
  2270. return true;
  2271. }
  2272. if (!phpthumb_functions::IsHexColor($this->config_error_bgcolor)) {
  2273. return $this->ErrorImage('Invalid hex color string "'.$this->config_error_bgcolor.'" for $this->config_error_bgcolor');
  2274. }
  2275. if (!phpthumb_functions::IsHexColor($this->config_error_textcolor)) {
  2276. return $this->ErrorImage('Invalid hex color string "'.$this->config_error_textcolor.'" for $this->config_error_textcolor');
  2277. }
  2278. if ($this->config_nooffsitelink_erase_image) {
  2279. return $this->ErrorImage($this->config_nooffsitelink_text_message, $this->thumbnail_width, $this->thumbnail_height);
  2280. } else {
  2281. $this->config_nooffsitelink_watermark_src = $this->ResolveFilenameToAbsolute($this->config_nooffsitelink_watermark_src);
  2282. if (is_file($this->config_nooffsitelink_watermark_src)) {
  2283. if (!include_once __DIR__ .'/phpthumb.filters.php' ) {
  2284. $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.filters.php" which is required for applying watermark', __FILE__, __LINE__);
  2285. return false;
  2286. }
  2287. $watermark_img = $this->ImageCreateFromStringReplacement(file_get_contents($this->config_nooffsitelink_watermark_src));
  2288. $phpthumbFilters = new phpthumb_filters();
  2289. $phpthumbFilters->phpThumbObject = &$this;
  2290. $opacity = 50;
  2291. $margin = 5;
  2292. $phpthumbFilters->WatermarkOverlay($this->gdimg_output, $watermark_img, '*', $opacity, $margin);
  2293. imagedestroy($watermark_img);
  2294. unset($phpthumbFilters);
  2295. } else {
  2296. $nohotlink_text_array = explode("\n", wordwrap($this->config_nooffsitelink_text_message, floor($this->thumbnail_width / imagefontwidth($this->config_error_fontsize)), "\n"));
  2297. $nohotlink_text_color = phpthumb_functions::ImageHexColorAllocate($this->gdimg_output, $this->config_error_textcolor);
  2298. $topoffset = round(($this->thumbnail_height - (count($nohotlink_text_array) * imagefontheight($this->config_error_fontsize))) / 2);
  2299. $rowcounter = 0;
  2300. $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__);
  2301. foreach ($nohotlink_text_array as $textline) {
  2302. $leftoffset = max(0, round(($this->thumbnail_width - (strlen($textline) * imagefontwidth($this->config_error_fontsize))) / 2));
  2303. imagestring($this->gdimg_output, $this->config_error_fontsize, $leftoffset, $topoffset + ($rowcounter++ * imagefontheight($this->config_error_fontsize)), $textline, $nohotlink_text_color);
  2304. }
  2305. }
  2306. }
  2307. return true;
  2308. }
  2309. public function AlphaChannelFlatten() {
  2310. if (!$this->is_alpha) {
  2311. // image doesn't have alpha transparency, no need to flatten
  2312. $this->DebugMessage('skipping AlphaChannelFlatten() because !$this->is_alpha', __FILE__, __LINE__);
  2313. return false;
  2314. }
  2315. switch ($this->thumbnailFormat) {
  2316. case 'png':
  2317. case 'webp':
  2318. case 'ico':
  2319. // image has alpha transparency, but output as PNG, WEBP or ICO which can handle it
  2320. $this->DebugMessage('skipping AlphaChannelFlatten() because ($this->thumbnailFormat == "'.$this->thumbnailFormat.'")', __FILE__, __LINE__);
  2321. return false;
  2322. break;
  2323. case 'gif':
  2324. // image has alpha transparency, but output as GIF which can handle only single-color transparency
  2325. $CurrentImageColorTransparent = imagecolortransparent($this->gdimg_output);
  2326. if ($CurrentImageColorTransparent == -1) {
  2327. // no transparent color defined
  2328. if (phpthumb_functions::gd_version() < 2.0) {
  2329. $this->DebugMessage('AlphaChannelFlatten() failed because GD version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2330. return false;
  2331. }
  2332. if ($img_alpha_mixdown_dither = @imagecreatetruecolor(imagesx($this->gdimg_output), imagesy($this->gdimg_output))) {
  2333. $dither_color = array();
  2334. for ($i = 0; $i <= 255; $i++) {
  2335. $dither_color[$i] = imagecolorallocate($img_alpha_mixdown_dither, $i, $i, $i);
  2336. }
  2337. // scan through current truecolor image copy alpha channel to temp image as grayscale
  2338. for ($x = 0; $x < $this->thumbnail_width; $x++) {
  2339. for ($y = 0; $y < $this->thumbnail_height; $y++) {
  2340. $PixelColor = phpthumb_functions::GetPixelColor($this->gdimg_output, $x, $y);
  2341. imagesetpixel($img_alpha_mixdown_dither, $x, $y, $dither_color[ $PixelColor[ 'alpha'] * 2 ]);
  2342. }
  2343. }
  2344. // dither alpha channel grayscale version down to 2 colors
  2345. imagetruecolortopalette($img_alpha_mixdown_dither, true, 2);
  2346. // reduce color palette to 256-1 colors (leave one palette position for transparent color)
  2347. imagetruecolortopalette($this->gdimg_output, true, 255);
  2348. // allocate a new color for transparent color index
  2349. $TransparentColor = imagecolorallocate($this->gdimg_output, 1, 254, 253);
  2350. imagecolortransparent($this->gdimg_output, $TransparentColor);
  2351. // scan through alpha channel image and note pixels with >50% transparency
  2352. for ($x = 0; $x < $this->thumbnail_width; $x++) {
  2353. for ($y = 0; $y < $this->thumbnail_height; $y++) {
  2354. $AlphaChannelPixel = phpthumb_functions::GetPixelColor($img_alpha_mixdown_dither, $x, $y);
  2355. if ($AlphaChannelPixel['red'] > 127) {
  2356. imagesetpixel($this->gdimg_output, $x, $y, $TransparentColor);
  2357. }
  2358. }
  2359. }
  2360. imagedestroy($img_alpha_mixdown_dither);
  2361. $this->DebugMessage('AlphaChannelFlatten() set image to 255+1 colors with transparency for GIF output', __FILE__, __LINE__);
  2362. return true;
  2363. } else {
  2364. $this->DebugMessage('AlphaChannelFlatten() failed imagecreate('.imagesx($this->gdimg_output).', '.imagesy($this->gdimg_output).')', __FILE__, __LINE__);
  2365. return false;
  2366. }
  2367. } else {
  2368. // a single transparent color already defined, leave as-is
  2369. $this->DebugMessage('skipping AlphaChannelFlatten() because ($this->thumbnailFormat == "'.$this->thumbnailFormat.'") and imagecolortransparent() returned "'.$CurrentImageColorTransparent.'"', __FILE__, __LINE__);
  2370. return true;
  2371. }
  2372. break;
  2373. }
  2374. $this->DebugMessage('continuing AlphaChannelFlatten() for output format "'.$this->thumbnailFormat.'"', __FILE__, __LINE__);
  2375. // image has alpha transparency, and is being output in a format that doesn't support it -- flatten
  2376. if ($gdimg_flatten_temp = phpthumb_functions::ImageCreateFunction($this->thumbnail_width, $this->thumbnail_height)) {
  2377. $this->config_background_hexcolor = ($this->bg ? $this->bg : $this->config_background_hexcolor);
  2378. if (!phpthumb_functions::IsHexColor($this->config_background_hexcolor)) {
  2379. return $this->ErrorImage('Invalid hex color string "'.$this->config_background_hexcolor.'" for parameter "bg"');
  2380. }
  2381. $background_color = phpthumb_functions::ImageHexColorAllocate($this->gdimg_output, $this->config_background_hexcolor);
  2382. imagefilledrectangle($gdimg_flatten_temp, 0, 0, $this->thumbnail_width, $this->thumbnail_height, $background_color);
  2383. imagecopy($gdimg_flatten_temp, $this->gdimg_output, 0, 0, 0, 0, $this->thumbnail_width, $this->thumbnail_height);
  2384. imagealphablending($this->gdimg_output, true);
  2385. imagesavealpha($this->gdimg_output, false);
  2386. imagecolortransparent($this->gdimg_output, -1);
  2387. imagecopy($this->gdimg_output, $gdimg_flatten_temp, 0, 0, 0, 0, $this->thumbnail_width, $this->thumbnail_height);
  2388. imagedestroy($gdimg_flatten_temp);
  2389. return true;
  2390. } else {
  2391. $this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__);
  2392. }
  2393. return false;
  2394. }
  2395. public function ApplyFilters() {
  2396. if ($this->fltr && is_array($this->fltr)) {
  2397. if (!include_once __DIR__ .'/phpthumb.filters.php' ) {
  2398. $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.filters.php" which is required for applying filters ('.implode(';', $this->fltr).')', __FILE__, __LINE__);
  2399. return false;
  2400. }
  2401. $phpthumbFilters = new phpthumb_filters();
  2402. $phpthumbFilters->phpThumbObject = &$this;
  2403. foreach ($this->fltr as $filtercommand) {
  2404. @list($command, $parameter) = explode('|', $filtercommand, 2);
  2405. $this->DebugMessage('Attempting to process filter command "'.$command.'('.$parameter.')"', __FILE__, __LINE__);
  2406. switch ($command) {
  2407. case 'brit': // Brightness
  2408. $phpthumbFilters->Brightness($this->gdimg_output, $parameter);
  2409. break;
  2410. case 'cont': // Contrast
  2411. $phpthumbFilters->Contrast($this->gdimg_output, $parameter);
  2412. break;
  2413. case 'ds': // Desaturation
  2414. $phpthumbFilters->Desaturate($this->gdimg_output, $parameter, '');
  2415. break;
  2416. case 'sat': // Saturation
  2417. $phpthumbFilters->Saturation($this->gdimg_output, $parameter, '');
  2418. break;
  2419. case 'gray': // Grayscale
  2420. $phpthumbFilters->Grayscale($this->gdimg_output);
  2421. break;
  2422. case 'clr': // Colorize
  2423. if (phpthumb_functions::gd_version() < 2) {
  2424. $this->DebugMessage('Skipping Colorize() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2425. break;
  2426. }
  2427. @list($amount, $color) = explode('|', $parameter, 2);
  2428. $phpthumbFilters->Colorize($this->gdimg_output, $amount, $color);
  2429. break;
  2430. case 'sep': // Sepia
  2431. if (phpthumb_functions::gd_version() < 2) {
  2432. $this->DebugMessage('Skipping Sepia() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2433. break;
  2434. }
  2435. @list($amount, $color) = explode('|', $parameter, 2);
  2436. $phpthumbFilters->Sepia($this->gdimg_output, $amount, $color);
  2437. break;
  2438. case 'gam': // Gamma correction
  2439. $phpthumbFilters->Gamma($this->gdimg_output, $parameter);
  2440. break;
  2441. case 'neg': // Negative colors
  2442. $phpthumbFilters->Negative($this->gdimg_output);
  2443. break;
  2444. case 'th': // Threshold
  2445. $phpthumbFilters->Threshold($this->gdimg_output, $parameter);
  2446. break;
  2447. case 'rcd': // ReduceColorDepth
  2448. if (phpthumb_functions::gd_version() < 2) {
  2449. $this->DebugMessage('Skipping ReduceColorDepth() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2450. break;
  2451. }
  2452. @list($colors, $dither) = explode('|', $parameter, 2);
  2453. $colors = ($colors ? (int) $colors : 256);
  2454. $dither = ((strlen($dither) > 0) ? (bool) $dither : true);
  2455. $phpthumbFilters->ReduceColorDepth($this->gdimg_output, $colors, $dither);
  2456. break;
  2457. case 'flip': // Flip
  2458. $phpthumbFilters->Flip($this->gdimg_output, strpos(strtolower($parameter), 'x') !== false, strpos(strtolower($parameter), 'y') !== false);
  2459. break;
  2460. case 'edge': // EdgeDetect
  2461. $phpthumbFilters->EdgeDetect($this->gdimg_output);
  2462. break;
  2463. case 'emb': // Emboss
  2464. $phpthumbFilters->Emboss($this->gdimg_output);
  2465. break;
  2466. case 'bvl': // Bevel
  2467. @list($width, $color1, $color2) = explode('|', $parameter, 3);
  2468. $phpthumbFilters->Bevel($this->gdimg_output, $width, $color1, $color2);
  2469. break;
  2470. case 'lvl': // autoLevels
  2471. @list($band, $method, $threshold) = explode('|', $parameter, 3);
  2472. $band = ($band ? preg_replace('#[^RGBA\\*]#', '', strtoupper($band)) : '*');
  2473. $method = ((strlen($method) > 0) ? (int) $method : 2);
  2474. $threshold = ((strlen($threshold) > 0) ? (float) $threshold : 0.1);
  2475. $phpthumbFilters->HistogramStretch($this->gdimg_output, $band, $method, $threshold);
  2476. break;
  2477. case 'wb': // WhiteBalance
  2478. $phpthumbFilters->WhiteBalance($this->gdimg_output, $parameter);
  2479. break;
  2480. case 'hist': // Histogram overlay
  2481. if (phpthumb_functions::gd_version() < 2) {
  2482. $this->DebugMessage('Skipping HistogramOverlay() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2483. break;
  2484. }
  2485. @list($bands, $colors, $width, $height, $alignment, $opacity, $margin_x, $margin_y) = explode('|', $parameter, 8);
  2486. $bands = ($bands ? $bands : '*');
  2487. $colors = ($colors ? $colors : '');
  2488. $width = ($width ? $width : 0.25);
  2489. $height = ($height ? $height : 0.25);
  2490. $alignment = ($alignment ? $alignment : 'BR');
  2491. $opacity = ($opacity ? $opacity : 50);
  2492. $margin_x = ($margin_x ? $margin_x : 5);
  2493. // $margin_y -- it wasn't forgotten, let the value always pass unchanged
  2494. $phpthumbFilters->HistogramOverlay($this->gdimg_output, $bands, $colors, $width, $height, $alignment, $opacity, $margin_x, $margin_y);
  2495. break;
  2496. case 'fram': // Frame
  2497. @list($frame_width, $edge_width, $color_frame, $color1, $color2) = explode('|', $parameter, 5);
  2498. $phpthumbFilters->Frame($this->gdimg_output, $frame_width, $edge_width, $color_frame, $color1, $color2);
  2499. break;
  2500. case 'drop': // DropShadow
  2501. if (phpthumb_functions::gd_version() < 2) {
  2502. $this->DebugMessage('Skipping DropShadow() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2503. return false;
  2504. }
  2505. $this->is_alpha = true;
  2506. @list($distance, $width, $color, $angle, $fade) = explode('|', $parameter, 5);
  2507. $phpthumbFilters->DropShadow($this->gdimg_output, $distance, $width, $color, $angle, $fade);
  2508. break;
  2509. case 'mask': // Mask cropping
  2510. if (phpthumb_functions::gd_version() < 2) {
  2511. $this->DebugMessage('Skipping Mask() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2512. return false;
  2513. }
  2514. @list($mask_filename, $invert) = explode('|', $parameter, 2);
  2515. $mask_filename = $this->ResolveFilenameToAbsolute($mask_filename);
  2516. if (@is_readable($mask_filename) && ($fp_mask = @fopen($mask_filename, 'rb'))) {
  2517. $MaskImageData = '';
  2518. do {
  2519. $buffer = fread($fp_mask, 8192);
  2520. $MaskImageData .= $buffer;
  2521. } while (strlen($buffer) > 0);
  2522. fclose($fp_mask);
  2523. if ($gdimg_mask = $this->ImageCreateFromStringReplacement($MaskImageData)) {
  2524. if ($invert && phpthumb_functions::version_compare_replacement(PHP_VERSION, '5.0.0', '>=') && phpthumb_functions::gd_is_bundled()) {
  2525. imagefilter($gdimg_mask, IMG_FILTER_NEGATE);
  2526. }
  2527. $this->is_alpha = true;
  2528. $phpthumbFilters->ApplyMask($gdimg_mask, $this->gdimg_output);
  2529. imagedestroy($gdimg_mask);
  2530. } else {
  2531. $this->DebugMessage('ImageCreateFromStringReplacement() failed for "'.$mask_filename.'"', __FILE__, __LINE__);
  2532. }
  2533. } else {
  2534. $this->DebugMessage('Cannot open mask file "'.$mask_filename.'"', __FILE__, __LINE__);
  2535. }
  2536. break;
  2537. case 'elip': // Ellipse cropping
  2538. if (phpthumb_functions::gd_version() < 2) {
  2539. $this->DebugMessage('Skipping Ellipse() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2540. return false;
  2541. }
  2542. $this->is_alpha = true;
  2543. $phpthumbFilters->Ellipse($this->gdimg_output);
  2544. break;
  2545. case 'ric': // RoundedImageCorners
  2546. if (phpthumb_functions::gd_version() < 2) {
  2547. $this->DebugMessage('Skipping RoundedImageCorners() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2548. return false;
  2549. }
  2550. @list($radius_x, $radius_y) = explode('|', $parameter, 2);
  2551. if (($radius_x < 1) || ($radius_y < 1)) {
  2552. $this->DebugMessage('Skipping RoundedImageCorners('.$radius_x.', '.$radius_y.') because x/y radius is less than 1', __FILE__, __LINE__);
  2553. break;
  2554. }
  2555. $this->is_alpha = true;
  2556. $phpthumbFilters->RoundedImageCorners($this->gdimg_output, $radius_x, $radius_y);
  2557. break;
  2558. case 'crop': // Crop
  2559. @list($left, $right, $top, $bottom) = explode('|', $parameter, 4);
  2560. $phpthumbFilters->Crop($this->gdimg_output, $left, $right, $top, $bottom);
  2561. break;
  2562. case 'bord': // Border
  2563. @list($border_width, $radius_x, $radius_y, $hexcolor_border) = explode('|', $parameter, 4);
  2564. $this->is_alpha = true;
  2565. $phpthumbFilters->ImageBorder($this->gdimg_output, $border_width, $radius_x, $radius_y, $hexcolor_border);
  2566. break;
  2567. case 'over': // Overlay
  2568. @list($filename, $underlay, $margin, $opacity) = explode('|', $parameter, 4);
  2569. $underlay = (bool) ($underlay ? $underlay : false);
  2570. $margin = ((strlen($margin) > 0) ? $margin : ($underlay ? 0.1 : 0.0));
  2571. $opacity = ((strlen($opacity) > 0) ? $opacity : 100);
  2572. if (($margin > 0) && ($margin < 1)) {
  2573. $margin = min(0.499, $margin);
  2574. } elseif (($margin > -1) && ($margin < 0)) {
  2575. $margin = max(-0.499, $margin);
  2576. }
  2577. $filename = $this->ResolveFilenameToAbsolute($filename);
  2578. if (@is_readable($filename) && ($fp_watermark = @fopen($filename, 'rb'))) {
  2579. $WatermarkImageData = '';
  2580. do {
  2581. $buffer = fread($fp_watermark, 8192);
  2582. $WatermarkImageData .= $buffer;
  2583. } while (strlen($buffer) > 0);
  2584. fclose($fp_watermark);
  2585. if ($img_watermark = $this->ImageCreateFromStringReplacement($WatermarkImageData)) {
  2586. if (($margin > 0) && ($margin < 1)) {
  2587. $resized_x = max(1, imagesx($this->gdimg_output) - round(2 * (imagesx($this->gdimg_output) * $margin)));
  2588. $resized_y = max(1, imagesy($this->gdimg_output) - round(2 * (imagesy($this->gdimg_output) * $margin)));
  2589. } else {
  2590. $resized_x = max(1, imagesx($this->gdimg_output) - round(2 * $margin));
  2591. $resized_y = max(1, imagesy($this->gdimg_output) - round(2 * $margin));
  2592. }
  2593. if ($underlay) {
  2594. if ($img_watermark_resized = phpthumb_functions::ImageCreateFunction(imagesx($this->gdimg_output), imagesy($this->gdimg_output))) {
  2595. imagealphablending($img_watermark_resized, false);
  2596. imagesavealpha($img_watermark_resized, true);
  2597. $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));
  2598. if ($img_source_resized = phpthumb_functions::ImageCreateFunction($resized_x, $resized_y)) {
  2599. imagealphablending($img_source_resized, false);
  2600. imagesavealpha($img_source_resized, true);
  2601. $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));
  2602. $phpthumbFilters->WatermarkOverlay($img_watermark_resized, $img_source_resized, 'C', $opacity, $margin);
  2603. imagecopy($this->gdimg_output, $img_watermark_resized, 0, 0, 0, 0, imagesx($this->gdimg_output), imagesy($this->gdimg_output));
  2604. } else {
  2605. $this->DebugMessage('phpthumb_functions::ImageCreateFunction('.$resized_x.', '.$resized_y.')', __FILE__, __LINE__);
  2606. }
  2607. imagedestroy($img_watermark_resized);
  2608. } else {
  2609. $this->DebugMessage('phpthumb_functions::ImageCreateFunction('.imagesx($this->gdimg_output).', '.imagesy($this->gdimg_output).')', __FILE__, __LINE__);
  2610. }
  2611. } else { // overlay
  2612. if ($img_watermark_resized = phpthumb_functions::ImageCreateFunction($resized_x, $resized_y)) {
  2613. imagealphablending($img_watermark_resized, false);
  2614. imagesavealpha($img_watermark_resized, true);
  2615. $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));
  2616. $phpthumbFilters->WatermarkOverlay($this->gdimg_output, $img_watermark_resized, 'C', $opacity, $margin);
  2617. imagedestroy($img_watermark_resized);
  2618. } else {
  2619. $this->DebugMessage('phpthumb_functions::ImageCreateFunction('.$resized_x.', '.$resized_y.')', __FILE__, __LINE__);
  2620. }
  2621. }
  2622. imagedestroy($img_watermark);
  2623. } else {
  2624. $this->DebugMessage('ImageCreateFromStringReplacement() failed for "'.$filename.'"', __FILE__, __LINE__);
  2625. }
  2626. } else {
  2627. $this->DebugMessage('Cannot open overlay file "'.$filename.'"', __FILE__, __LINE__);
  2628. }
  2629. break;
  2630. case 'wmi': // WaterMarkImage
  2631. @list($filename, $alignment, $opacity, $margin['x'], $margin['y'], $rotate_angle) = explode('|', $parameter, 6);
  2632. // $margin can be pixel margin or percent margin if $alignment is text, or max width/height if $alignment is position like "50x75"
  2633. $alignment = ($alignment ? $alignment : 'BR');
  2634. $opacity = ('' != $opacity ? (int) $opacity : 50);
  2635. $rotate_angle = ('' != $rotate_angle ? (int) $rotate_angle : 0);
  2636. if (!preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)$#i', $alignment, $matches)) {
  2637. $margins = array('x', 'y');
  2638. foreach ($margins as $xy) {
  2639. $margin[$xy] = ('' !== $margin[ $xy ] ? $margin[ $xy] : 5);
  2640. if (($margin[$xy] > 0) && ($margin[$xy] < 1)) {
  2641. $margin[$xy] = min(0.499, $margin[$xy]);
  2642. } elseif (($margin[$xy] > -1) && ($margin[$xy] < 0)) {
  2643. $margin[$xy] = max(-0.499, $margin[$xy]);
  2644. }
  2645. }
  2646. }
  2647. $filename = $this->ResolveFilenameToAbsolute($filename);
  2648. if (@is_readable($filename)) {
  2649. if ($img_watermark = $this->ImageCreateFromFilename($filename)) {
  2650. if ($rotate_angle !== 0) {
  2651. $phpthumbFilters->ImprovedImageRotate($img_watermark, $rotate_angle, 'FFFFFF', null, $this);
  2652. }
  2653. if (preg_match('#^([0-9\\.\\-]*)x([0-9\\.\\-]*)$#i', $alignment, $matches)) {
  2654. $watermark_max_width = (int) ($margin[ 'x'] ? $margin[ 'x'] : imagesx($img_watermark));
  2655. $watermark_max_height = (int) ($margin[ 'y'] ? $margin[ 'y'] : imagesy($img_watermark));
  2656. $scale = phpthumb_functions::ScaleToFitInBox(imagesx($img_watermark), imagesy($img_watermark), $watermark_max_width, $watermark_max_height, true, true);
  2657. $this->DebugMessage('Scaling watermark by a factor of '.number_format($scale, 4), __FILE__, __LINE__);
  2658. if (($scale > 1) || ($scale < 1)) {
  2659. if ($img_watermark2 = phpthumb_functions::ImageCreateFunction($scale * imagesx($img_watermark), $scale * imagesy($img_watermark))) {
  2660. imagealphablending($img_watermark2, false);
  2661. imagesavealpha($img_watermark2, true);
  2662. $this->ImageResizeFunction($img_watermark2, $img_watermark, 0, 0, 0, 0, imagesx($img_watermark2), imagesy($img_watermark2), imagesx($img_watermark), imagesy($img_watermark));
  2663. $img_watermark = $img_watermark2;
  2664. } else {
  2665. $this->DebugMessage('ImageCreateFunction('.($scale * imagesx($img_watermark)).', '.($scale * imagesx($img_watermark)).') failed', __FILE__, __LINE__);
  2666. }
  2667. }
  2668. $watermark_dest_x = round($matches[1] - (imagesx($img_watermark) / 2));
  2669. $watermark_dest_y = round($matches[2] - (imagesy($img_watermark) / 2));
  2670. $alignment = $watermark_dest_x.'x'.$watermark_dest_y;
  2671. }
  2672. $phpthumbFilters->WatermarkOverlay($this->gdimg_output, $img_watermark, $alignment, $opacity, $margin['x'], $margin['y']);
  2673. imagedestroy($img_watermark);
  2674. if (isset($img_watermark2) && is_resource($img_watermark2)) {
  2675. imagedestroy($img_watermark2);
  2676. }
  2677. } else {
  2678. $this->DebugMessage('ImageCreateFromFilename() failed for "'.$filename.'"', __FILE__, __LINE__);
  2679. }
  2680. } else {
  2681. $this->DebugMessage('!is_readable('.$filename.')', __FILE__, __LINE__);
  2682. }
  2683. break;
  2684. case 'wmt': // WaterMarkText
  2685. @list($text, $size, $alignment, $hex_color, $ttffont, $opacity, $margin, $angle, $bg_color, $bg_opacity, $fillextend, $lineheight) = explode('|', $parameter, 12);
  2686. $text = ($text ? $text : '');
  2687. $size = ($size ? $size : 3);
  2688. $alignment = ($alignment ? $alignment : 'BR');
  2689. $hex_color = ($hex_color ? $hex_color : '000000');
  2690. $ttffont = ($ttffont ? $ttffont : '');
  2691. $opacity = ('' != $opacity ? $opacity : 50);
  2692. $margin = ('' != $margin ? $margin : 5);
  2693. $angle = ('' != $angle ? $angle : 0);
  2694. $bg_color = ($bg_color ? $bg_color : false);
  2695. $bg_opacity = ($bg_opacity ? $bg_opacity : 0);
  2696. $fillextend = ($fillextend ? $fillextend : '');
  2697. $lineheight = ($lineheight ? $lineheight : 1.0);
  2698. if (basename($ttffont) == $ttffont) {
  2699. $ttffont = $this->realPathSafe($this->config_ttf_directory.DIRECTORY_SEPARATOR.$ttffont);
  2700. } else {
  2701. $ttffont = $this->ResolveFilenameToAbsolute($ttffont);
  2702. }
  2703. $phpthumbFilters->WatermarkText($this->gdimg_output, $text, $size, $alignment, $hex_color, $ttffont, $opacity, $margin, $angle, $bg_color, $bg_opacity, $fillextend, $lineheight);
  2704. break;
  2705. case 'blur': // Blur
  2706. @list($radius) = explode('|', $parameter, 1);
  2707. $radius = ($radius ? $radius : 1);
  2708. if (phpthumb_functions::gd_version() >= 2) {
  2709. $phpthumbFilters->Blur($this->gdimg_output, $radius);
  2710. } else {
  2711. $this->DebugMessage('Skipping Blur() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2712. }
  2713. break;
  2714. case 'gblr': // Gaussian Blur
  2715. $phpthumbFilters->BlurGaussian($this->gdimg_output);
  2716. break;
  2717. case 'sblr': // Selective Blur
  2718. $phpthumbFilters->BlurSelective($this->gdimg_output);
  2719. break;
  2720. case 'mean': // MeanRemoval blur
  2721. $phpthumbFilters->MeanRemoval($this->gdimg_output);
  2722. break;
  2723. case 'smth': // Smooth blur
  2724. $phpthumbFilters->Smooth($this->gdimg_output, $parameter);
  2725. break;
  2726. case 'usm': // UnSharpMask sharpening
  2727. @list($amount, $radius, $threshold) = explode('|', $parameter, 3);
  2728. $amount = ($amount ? $amount : 80);
  2729. $radius = ($radius ? $radius : 0.5);
  2730. $threshold = ('' !== $threshold ? $threshold : 3);
  2731. if (phpthumb_functions::gd_version() >= 2.0) {
  2732. ob_start();
  2733. if (!@include_once __DIR__ .'/phpthumb.unsharp.php' ) {
  2734. $include_error = ob_get_contents();
  2735. if ($include_error) {
  2736. $this->DebugMessage('include_once("'. __DIR__ .'/phpthumb.unsharp.php") generated message: "'.$include_error.'"', __FILE__, __LINE__);
  2737. }
  2738. $this->DebugMessage('Error including "'. __DIR__ .'/phpthumb.unsharp.php" which is required for unsharp masking', __FILE__, __LINE__);
  2739. ob_end_clean();
  2740. return false;
  2741. }
  2742. ob_end_clean();
  2743. phpUnsharpMask::applyUnsharpMask($this->gdimg_output, $amount, $radius, $threshold);
  2744. } else {
  2745. $this->DebugMessage('Skipping unsharp mask because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2746. return false;
  2747. }
  2748. break;
  2749. case 'size': // Resize
  2750. @list($newwidth, $newheight, $stretch) = explode('|', $parameter);
  2751. $newwidth = (!$newwidth ? imagesx($this->gdimg_output) : ((($newwidth > 0) && ($newwidth < 1)) ? round($newwidth * imagesx($this->gdimg_output)) : round($newwidth)));
  2752. $newheight = (!$newheight ? imagesy($this->gdimg_output) : ((($newheight > 0) && ($newheight < 1)) ? round($newheight * imagesy($this->gdimg_output)) : round($newheight)));
  2753. $stretch = ($stretch ? true : false);
  2754. if ($stretch) {
  2755. $scale_x = phpthumb_functions::ScaleToFitInBox(imagesx($this->gdimg_output), imagesx($this->gdimg_output), $newwidth, $newwidth, true, true);
  2756. $scale_y = phpthumb_functions::ScaleToFitInBox(imagesy($this->gdimg_output), imagesy($this->gdimg_output), $newheight, $newheight, true, true);
  2757. } else {
  2758. $scale_x = phpthumb_functions::ScaleToFitInBox(imagesx($this->gdimg_output), imagesy($this->gdimg_output), $newwidth, $newheight, true, true);
  2759. $scale_y = $scale_x;
  2760. }
  2761. $this->DebugMessage('Scaling watermark ('.($stretch ? 'with' : 'without').' stretch) by a factor of "'.number_format($scale_x, 4).' x '.number_format($scale_y, 4).'"', __FILE__, __LINE__);
  2762. if (($scale_x > 1) || ($scale_x < 1) || ($scale_y > 1) || ($scale_y < 1)) {
  2763. if ($img_temp = phpthumb_functions::ImageCreateFunction(imagesx($this->gdimg_output), imagesy($this->gdimg_output))) {
  2764. imagecopy($img_temp, $this->gdimg_output, 0, 0, 0, 0, imagesx($this->gdimg_output), imagesy($this->gdimg_output));
  2765. if ($this->gdimg_output = phpthumb_functions::ImageCreateFunction($scale_x * imagesx($img_temp), $scale_y * imagesy($img_temp))) {
  2766. imagealphablending($this->gdimg_output, false);
  2767. imagesavealpha($this->gdimg_output, true);
  2768. $this->ImageResizeFunction($this->gdimg_output, $img_temp, 0, 0, 0, 0, imagesx($this->gdimg_output), imagesy($this->gdimg_output), imagesx($img_temp), imagesy($img_temp));
  2769. } else {
  2770. $this->DebugMessage('ImageCreateFunction('.($scale_x * imagesx($img_temp)).', '.($scale_y * imagesy($img_temp)).') failed', __FILE__, __LINE__);
  2771. }
  2772. imagedestroy($img_temp);
  2773. } else {
  2774. $this->DebugMessage('ImageCreateFunction('.imagesx($this->gdimg_output).', '.imagesy($this->gdimg_output).') failed', __FILE__, __LINE__);
  2775. }
  2776. }
  2777. break;
  2778. case 'rot': // ROTate
  2779. @list($angle, $bgcolor) = explode('|', $parameter, 2);
  2780. $phpthumbFilters->ImprovedImageRotate($this->gdimg_output, $angle, $bgcolor, null, $this);
  2781. break;
  2782. case 'stc': // Source Transparent Color
  2783. @list($hexcolor, $min_limit, $max_limit) = explode('|', $parameter, 3);
  2784. if (!phpthumb_functions::IsHexColor($hexcolor)) {
  2785. $this->DebugMessage('Skipping SourceTransparentColor hex color is invalid ('.$hexcolor.')', __FILE__, __LINE__);
  2786. return false;
  2787. }
  2788. $min_limit = ('' !== $min_limit ? $min_limit : 5);
  2789. $max_limit = ('' !== $max_limit ? $max_limit : 10);
  2790. if ($gdimg_mask = $phpthumbFilters->SourceTransparentColorMask($this->gdimg_output, $hexcolor, $min_limit, $max_limit)) {
  2791. $this->is_alpha = true;
  2792. $phpthumbFilters->ApplyMask($gdimg_mask, $this->gdimg_output);
  2793. imagedestroy($gdimg_mask);
  2794. } else {
  2795. $this->DebugMessage('SourceTransparentColorMask() failed for "'.$hexcolor.','.$min_limit.','.$max_limit.'"', __FILE__, __LINE__);
  2796. }
  2797. break;
  2798. }
  2799. $this->DebugMessage('Finished processing filter command "'.$command.'('.$parameter.')"', __FILE__, __LINE__);
  2800. }
  2801. }
  2802. return true;
  2803. }
  2804. public function MaxFileSize() {
  2805. if (phpthumb_functions::gd_version() < 2) {
  2806. $this->DebugMessage('Skipping MaxFileSize() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  2807. return false;
  2808. }
  2809. if ($this->maxb > 0) {
  2810. switch ($this->thumbnailFormat) {
  2811. case 'png':
  2812. case 'gif':
  2813. $imgRenderFunction = 'image'.$this->thumbnailFormat;
  2814. ob_start();
  2815. $imgRenderFunction($this->gdimg_output);
  2816. $imgdata = ob_get_contents();
  2817. ob_end_clean();
  2818. if (strlen($imgdata) > $this->maxb) {
  2819. for ($i = 8; $i >= 1; $i--) {
  2820. $tempIMG = imagecreatetruecolor(imagesx($this->gdimg_output), imagesy($this->gdimg_output));
  2821. imagecopy($tempIMG, $this->gdimg_output, 0, 0, 0, 0, imagesx($this->gdimg_output), imagesy($this->gdimg_output));
  2822. imagetruecolortopalette($tempIMG, true, pow(2, $i));
  2823. ob_start();
  2824. $imgRenderFunction($tempIMG);
  2825. $imgdata = ob_get_contents();
  2826. ob_end_clean();
  2827. if (strlen($imgdata) <= $this->maxb) {
  2828. imagetruecolortopalette($this->gdimg_output, true, pow(2, $i));
  2829. break;
  2830. }
  2831. }
  2832. }
  2833. break;
  2834. case 'jpeg':
  2835. ob_start();
  2836. imagejpeg($this->gdimg_output);
  2837. $imgdata = ob_get_contents();
  2838. ob_end_clean();
  2839. if (strlen($imgdata) > $this->maxb) {
  2840. for ($i = 3; $i < 20; $i++) {
  2841. $q = round(100 * (1 - log10($i / 2)));
  2842. ob_start();
  2843. imagejpeg($this->gdimg_output, null, $q);
  2844. $imgdata = ob_get_contents();
  2845. ob_end_clean();
  2846. $this->thumbnailQuality = $q;
  2847. if (strlen($imgdata) <= $this->maxb) {
  2848. break;
  2849. }
  2850. }
  2851. }
  2852. if (strlen($imgdata) > $this->maxb) {
  2853. return false;
  2854. }
  2855. break;
  2856. default:
  2857. return false;
  2858. }
  2859. }
  2860. return true;
  2861. }
  2862. public function CalculateThumbnailDimensions() {
  2863. $this->DebugMessage('CalculateThumbnailDimensions() starting with [W,H,sx,sy,sw,sh] initially set to ['.$this->source_width.','.$this->source_height.','.$this->sx.','.$this->sy.','.$this->sw.','.$this->sh.']', __FILE__, __LINE__);
  2864. //echo $this->source_width.'x'.$this->source_height.'<hr>';
  2865. $this->thumbnailCropX = ($this->sx ? (($this->sx >= 2) ? $this->sx : round($this->sx * $this->source_width)) : 0);
  2866. //echo $this->thumbnailCropX.'<br>';
  2867. $this->thumbnailCropY = ($this->sy ? (($this->sy >= 2) ? $this->sy : round($this->sy * $this->source_height)) : 0);
  2868. //echo $this->thumbnailCropY.'<br>';
  2869. $this->thumbnailCropW = ($this->sw ? (($this->sw >= 2) ? $this->sw : round($this->sw * $this->source_width)) : $this->source_width);
  2870. //echo $this->thumbnailCropW.'<br>';
  2871. $this->thumbnailCropH = ($this->sh ? (($this->sh >= 2) ? $this->sh : round($this->sh * $this->source_height)) : $this->source_height);
  2872. //echo $this->thumbnailCropH.'<hr>';
  2873. // limit source area to original image area
  2874. $this->thumbnailCropW = max(1, min($this->thumbnailCropW, $this->source_width - $this->thumbnailCropX));
  2875. $this->thumbnailCropH = max(1, min($this->thumbnailCropH, $this->source_height - $this->thumbnailCropY));
  2876. $this->DebugMessage('CalculateThumbnailDimensions() starting with [x,y,w,h] initially set to ['.$this->thumbnailCropX.','.$this->thumbnailCropY.','.$this->thumbnailCropW.','.$this->thumbnailCropH.']', __FILE__, __LINE__);
  2877. if ($this->zc && $this->w && $this->h) {
  2878. // Zoom Crop
  2879. // retain proportional resizing we did above, but crop off larger dimension so smaller
  2880. // dimension fully fits available space
  2881. $scaling_X = $this->source_width / $this->w;
  2882. $scaling_Y = $this->source_height / $this->h;
  2883. if ($scaling_X > $scaling_Y) {
  2884. // some of the width will need to be cropped
  2885. $allowable_width = $this->source_width / $scaling_X * $scaling_Y;
  2886. $this->thumbnailCropW = round($allowable_width);
  2887. $this->thumbnailCropX = round(($this->source_width - $allowable_width) / 2);
  2888. } elseif ($scaling_Y > $scaling_X) {
  2889. // some of the height will need to be cropped
  2890. $allowable_height = $this->source_height / $scaling_Y * $scaling_X;
  2891. $this->thumbnailCropH = round($allowable_height);
  2892. $this->thumbnailCropY = round(($this->source_height - $allowable_height) / 2);
  2893. } else {
  2894. // image fits perfectly, no cropping needed
  2895. }
  2896. $this->thumbnail_width = $this->w;
  2897. $this->thumbnail_height = $this->h;
  2898. $this->thumbnail_image_width = $this->thumbnail_width;
  2899. $this->thumbnail_image_height = $this->thumbnail_height;
  2900. } elseif ($this->iar && $this->w && $this->h) {
  2901. // Ignore Aspect Ratio
  2902. // stretch image to fit exactly 'w' x 'h'
  2903. $this->thumbnail_width = $this->w;
  2904. $this->thumbnail_height = $this->h;
  2905. $this->thumbnail_image_width = $this->thumbnail_width;
  2906. $this->thumbnail_image_height = $this->thumbnail_height;
  2907. } else {
  2908. $original_aspect_ratio = $this->thumbnailCropW / $this->thumbnailCropH;
  2909. if ($this->aoe) {
  2910. if ($this->w && $this->h) {
  2911. $maxwidth = min($this->w, $this->h * $original_aspect_ratio);
  2912. $maxheight = min($this->h, $this->w / $original_aspect_ratio);
  2913. } elseif ($this->w) {
  2914. $maxwidth = $this->w;
  2915. $maxheight = $this->w / $original_aspect_ratio;
  2916. } elseif ($this->h) {
  2917. $maxwidth = $this->h * $original_aspect_ratio;
  2918. $maxheight = $this->h;
  2919. } else {
  2920. $maxwidth = $this->thumbnailCropW;
  2921. $maxheight = $this->thumbnailCropH;
  2922. }
  2923. } else {
  2924. $maxwidth = phpthumb_functions::nonempty_min($this->w, $this->thumbnailCropW, $this->config_output_maxwidth);
  2925. $maxheight = phpthumb_functions::nonempty_min($this->h, $this->thumbnailCropH, $this->config_output_maxheight);
  2926. //echo $maxwidth.'x'.$maxheight.'<br>';
  2927. $maxwidth = min($maxwidth, $maxheight * $original_aspect_ratio);
  2928. $maxheight = min($maxheight, $maxwidth / $original_aspect_ratio);
  2929. //echo $maxwidth.'x'.$maxheight.'<hr>';
  2930. }
  2931. $this->thumbnail_image_width = $maxwidth;
  2932. $this->thumbnail_image_height = $maxheight;
  2933. $this->thumbnail_width = $maxwidth;
  2934. $this->thumbnail_height = $maxheight;
  2935. $this->FixedAspectRatio();
  2936. }
  2937. $this->thumbnail_width = max(1, floor($this->thumbnail_width));
  2938. $this->thumbnail_height = max(1, floor($this->thumbnail_height));
  2939. return true;
  2940. }
  2941. public function CreateGDoutput() {
  2942. $this->CalculateThumbnailDimensions();
  2943. // create the GD image (either true-color or 256-color, depending on GD version)
  2944. $this->gdimg_output = phpthumb_functions::ImageCreateFunction($this->thumbnail_width, $this->thumbnail_height);
  2945. // images that have transparency must have the background filled with the configured 'bg' color otherwise the transparent color will appear as black
  2946. imagesavealpha($this->gdimg_output, true);
  2947. if ($this->is_alpha && phpthumb_functions::gd_version() >= 2) {
  2948. imagealphablending($this->gdimg_output, false);
  2949. $output_full_alpha = phpthumb_functions::ImageColorAllocateAlphaSafe($this->gdimg_output, 255, 255, 255, 127);
  2950. imagefilledrectangle($this->gdimg_output, 0, 0, $this->thumbnail_width, $this->thumbnail_height, $output_full_alpha);
  2951. } else {
  2952. $current_transparent_color = imagecolortransparent($this->gdimg_source);
  2953. if ($this->bg || (@$current_transparent_color >= 0)) {
  2954. $this->config_background_hexcolor = ($this->bg ? $this->bg : $this->config_background_hexcolor);
  2955. if (!phpthumb_functions::IsHexColor($this->config_background_hexcolor)) {
  2956. return $this->ErrorImage('Invalid hex color string "'.$this->config_background_hexcolor.'" for parameter "bg"');
  2957. }
  2958. $background_color = phpthumb_functions::ImageHexColorAllocate($this->gdimg_output, $this->config_background_hexcolor);
  2959. imagefilledrectangle($this->gdimg_output, 0, 0, $this->thumbnail_width, $this->thumbnail_height, $background_color);
  2960. }
  2961. }
  2962. $this->DebugMessage('CreateGDoutput() returning canvas "'.$this->thumbnail_width.'x'.$this->thumbnail_height.'"', __FILE__, __LINE__);
  2963. return true;
  2964. }
  2965. public function SetOrientationDependantWidthHeight() {
  2966. $this->DebugMessage('SetOrientationDependantWidthHeight() starting with "'.$this->source_width.'"x"'.$this->source_height.'"', __FILE__, __LINE__);
  2967. if ($this->source_height > $this->source_width) {
  2968. // portrait
  2969. $this->w = phpthumb_functions::OneOfThese($this->wp, $this->w, $this->ws, $this->wl);
  2970. $this->h = phpthumb_functions::OneOfThese($this->hp, $this->h, $this->hs, $this->hl);
  2971. } elseif ($this->source_height < $this->source_width) {
  2972. // landscape
  2973. $this->w = phpthumb_functions::OneOfThese($this->wl, $this->w, $this->ws, $this->wp);
  2974. $this->h = phpthumb_functions::OneOfThese($this->hl, $this->h, $this->hs, $this->hp);
  2975. } else {
  2976. // square
  2977. $this->w = phpthumb_functions::OneOfThese($this->ws, $this->w, $this->wl, $this->wp);
  2978. $this->h = phpthumb_functions::OneOfThese($this->hs, $this->h, $this->hl, $this->hp);
  2979. }
  2980. //$this->w = round($this->w ? $this->w : (($this->h && $this->source_height) ? $this->h * $this->source_width / $this->source_height : $this->w));
  2981. //$this->h = round($this->h ? $this->h : (($this->w && $this->source_width) ? $this->w * $this->source_height / $this->source_width : $this->h));
  2982. $this->DebugMessage('SetOrientationDependantWidthHeight() setting w="'. (int) $this->w .'", h="'. (int) $this->h .'"', __FILE__, __LINE__);
  2983. return true;
  2984. }
  2985. public function ExtractEXIFgetImageSize() {
  2986. $this->DebugMessage('starting ExtractEXIFgetImageSize()', __FILE__, __LINE__);
  2987. if (preg_match('#^http:#i', $this->src) && !$this->sourceFilename && $this->rawImageData) {
  2988. $this->SourceDataToTempFile();
  2989. }
  2990. if (null === $this->getimagesizeinfo) {
  2991. if ($this->sourceFilename) {
  2992. $this->getimagesizeinfo = @getimagesize($this->sourceFilename);
  2993. $this->source_width = $this->getimagesizeinfo[0];
  2994. $this->source_height = $this->getimagesizeinfo[1];
  2995. $this->DebugMessage('getimagesize('.$this->sourceFilename.') says image is '.$this->source_width.'x'.$this->source_height, __FILE__, __LINE__);
  2996. } else {
  2997. $this->DebugMessage('skipping getimagesize() because $this->sourceFilename is empty', __FILE__, __LINE__);
  2998. }
  2999. } else {
  3000. $this->DebugMessage('skipping getimagesize() because !is_null($this->getimagesizeinfo)', __FILE__, __LINE__);
  3001. }
  3002. if (is_resource($this->gdimg_source)) {
  3003. $this->source_width = imagesx($this->gdimg_source);
  3004. $this->source_height = imagesy($this->gdimg_source);
  3005. $this->SetOrientationDependantWidthHeight();
  3006. } elseif ($this->rawImageData && !$this->sourceFilename) {
  3007. if ($this->SourceImageIsTooLarge($this->source_width, $this->source_height)) {
  3008. $this->DebugMessage('NOT bypassing EXIF and getimagesize sections because source image is too large for GD ('.$this->source_width.'x'.$this->source_width.'='.($this->source_width * $this->source_height * 5).'MB)', __FILE__, __LINE__);
  3009. } else {
  3010. $this->DebugMessage('bypassing EXIF and getimagesize sections because $this->rawImageData is set, and $this->sourceFilename is not set, and source image is not too large for GD ('.$this->source_width.'x'.$this->source_width.'='.($this->source_width * $this->source_height * 5).'MB)', __FILE__, __LINE__);
  3011. }
  3012. }
  3013. if (!empty($this->getimagesizeinfo)) {
  3014. // great
  3015. $this->getimagesizeinfo['filesize'] = @filesize($this->sourceFilename);
  3016. } elseif (!$this->rawImageData) {
  3017. $this->DebugMessage('getimagesize("'.$this->sourceFilename.'") failed', __FILE__, __LINE__);
  3018. }
  3019. if ($this->config_prefer_imagemagick) {
  3020. if ($this->ImageMagickThumbnailToGD()) {
  3021. return true;
  3022. }
  3023. $this->DebugMessage('ImageMagickThumbnailToGD() failed', __FILE__, __LINE__);
  3024. }
  3025. $this->source_width = $this->getimagesizeinfo[0];
  3026. $this->source_height = $this->getimagesizeinfo[1];
  3027. $this->SetOrientationDependantWidthHeight();
  3028. if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.2.0', '>=') && function_exists('exif_read_data')) {
  3029. switch ($this->getimagesizeinfo[2]) {
  3030. case IMAGETYPE_JPEG:
  3031. case IMAGETYPE_TIFF_II:
  3032. case IMAGETYPE_TIFF_MM:
  3033. $this->exif_raw_data = @exif_read_data($this->sourceFilename, 0, true);
  3034. break;
  3035. }
  3036. }
  3037. if (function_exists('exif_thumbnail') && ($this->getimagesizeinfo[2] == IMAGETYPE_JPEG)) {
  3038. // Extract EXIF info from JPEGs
  3039. $this->exif_thumbnail_width = '';
  3040. $this->exif_thumbnail_height = '';
  3041. $this->exif_thumbnail_type = '';
  3042. // The parameters width, height and imagetype are available since PHP v4.3.0
  3043. if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.3.0', '>=')) {
  3044. $this->exif_thumbnail_data = @exif_thumbnail($this->sourceFilename, $this->exif_thumbnail_width, $this->exif_thumbnail_height, $this->exif_thumbnail_type);
  3045. } else {
  3046. // older versions of exif_thumbnail output an error message but NOT return false on failure
  3047. ob_start();
  3048. $this->exif_thumbnail_data = exif_thumbnail($this->sourceFilename);
  3049. $exit_thumbnail_error = ob_get_contents();
  3050. ob_end_clean();
  3051. if (!$exit_thumbnail_error && $this->exif_thumbnail_data) {
  3052. if ($gdimg_exif_temp = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data, false)) {
  3053. $this->exif_thumbnail_width = imagesx($gdimg_exif_temp);
  3054. $this->exif_thumbnail_height = imagesy($gdimg_exif_temp);
  3055. $this->exif_thumbnail_type = 2; // (2 == JPEG) before PHP v4.3.0 only JPEG format EXIF thumbnails are returned
  3056. unset($gdimg_exif_temp);
  3057. } else {
  3058. return $this->ErrorImage('Failed - $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data) in '.__FILE__.' on line '.__LINE__);
  3059. }
  3060. }
  3061. }
  3062. } elseif (!function_exists('exif_thumbnail')) {
  3063. $this->DebugMessage('exif_thumbnail() does not exist, cannot extract EXIF thumbnail', __FILE__, __LINE__);
  3064. }
  3065. $this->DebugMessage('EXIF thumbnail extraction: (size='.strlen($this->exif_thumbnail_data).'; type="'.$this->exif_thumbnail_type.'"; '. (int) $this->exif_thumbnail_width .'x'. (int) $this->exif_thumbnail_height .')', __FILE__, __LINE__);
  3066. // see if EXIF thumbnail can be used directly with no processing
  3067. if ($this->config_use_exif_thumbnail_for_speed && $this->exif_thumbnail_data) {
  3068. while (true) {
  3069. if (!$this->xto) {
  3070. $source_ar = $this->source_width / $this->source_height;
  3071. $exif_ar = $this->exif_thumbnail_width / $this->exif_thumbnail_height;
  3072. if (number_format($source_ar, 2) != number_format($exif_ar, 2)) {
  3073. $this->DebugMessage('not using EXIF thumbnail because $source_ar != $exif_ar ('.$source_ar.' != '.$exif_ar.')', __FILE__, __LINE__);
  3074. break;
  3075. }
  3076. if ($this->w && ($this->w != $this->exif_thumbnail_width)) {
  3077. $this->DebugMessage('not using EXIF thumbnail because $this->w != $this->exif_thumbnail_width ('.$this->w.' != '.$this->exif_thumbnail_width.')', __FILE__, __LINE__);
  3078. break;
  3079. }
  3080. if ($this->h && ($this->h != $this->exif_thumbnail_height)) {
  3081. $this->DebugMessage('not using EXIF thumbnail because $this->h != $this->exif_thumbnail_height ('.$this->h.' != '.$this->exif_thumbnail_height.')', __FILE__, __LINE__);
  3082. break;
  3083. }
  3084. $CannotBeSetParameters = array('sx', 'sy', 'sh', 'sw', 'far', 'bg', 'bc', 'fltr', 'phpThumbDebug');
  3085. foreach ($CannotBeSetParameters as $parameter) {
  3086. if ($this->$parameter) {
  3087. break 2;
  3088. }
  3089. }
  3090. }
  3091. $this->DebugMessage('setting $this->gdimg_source = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data)', __FILE__, __LINE__);
  3092. $this->gdimg_source = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data);
  3093. $this->source_width = imagesx($this->gdimg_source);
  3094. $this->source_height = imagesy($this->gdimg_source);
  3095. return true;
  3096. }
  3097. }
  3098. if (($this->config_max_source_pixels > 0) && (($this->source_width * $this->source_height) > $this->config_max_source_pixels)) {
  3099. // Source image is larger than would fit in available PHP memory.
  3100. // If ImageMagick is installed, use it to generate the thumbnail.
  3101. // Else, if an EXIF thumbnail is available, use that as the source image.
  3102. // Otherwise, no choice but to fail with an error message
  3103. $this->DebugMessage('image is '.$this->source_width.'x'.$this->source_height.' and therefore contains more pixels ('.($this->source_width * $this->source_height).') than $this->config_max_source_pixels setting ('.$this->config_max_source_pixels.')', __FILE__, __LINE__);
  3104. if (!$this->config_prefer_imagemagick && $this->ImageMagickThumbnailToGD()) {
  3105. // excellent, we have a thumbnailed source image
  3106. return true;
  3107. }
  3108. }
  3109. return true;
  3110. }
  3111. public function SetCacheFilename() {
  3112. if (null !== $this->cache_filename) {
  3113. $this->DebugMessage('$this->cache_filename already set, skipping SetCacheFilename()', __FILE__, __LINE__);
  3114. return true;
  3115. }
  3116. if (null === $this->config_cache_directory) {
  3117. $this->setCacheDirectory();
  3118. if (!$this->config_cache_directory) {
  3119. $this->DebugMessage('SetCacheFilename() failed because $this->config_cache_directory is empty', __FILE__, __LINE__);
  3120. return false;
  3121. }
  3122. }
  3123. $this->setOutputFormat();
  3124. if (!$this->sourceFilename && !$this->rawImageData && $this->src) {
  3125. $this->sourceFilename = $this->ResolveFilenameToAbsolute($this->src);
  3126. }
  3127. if ($this->config_cache_default_only_suffix && $this->sourceFilename) {
  3128. // simplified cache filenames:
  3129. // only use default parameters in phpThumb.config.php
  3130. // substitute source filename into * in $this->config_cache_default_only_suffix
  3131. // (eg: '*_thumb' becomes 'picture_thumb.jpg')
  3132. if (strpos($this->config_cache_default_only_suffix, '*') === false) {
  3133. $this->DebugMessage('aborting simplified caching filename because no * in "'.$this->config_cache_default_only_suffix.'"', __FILE__, __LINE__);
  3134. } else {
  3135. preg_match('#(.+)(\\.[a-z0-9]+)?$#i', basename($this->sourceFilename), $matches);
  3136. $this->cache_filename = $this->config_cache_directory.DIRECTORY_SEPARATOR.rawurlencode(str_replace('*', @$matches[1], $this->config_cache_default_only_suffix)).'.'.strtolower($this->thumbnailFormat);
  3137. return true;
  3138. }
  3139. }
  3140. $this->cache_filename = '';
  3141. if ($this->new) {
  3142. $broad_directory_name = strtolower(md5($this->new));
  3143. $this->cache_filename .= '_new'.$broad_directory_name;
  3144. } elseif ($this->md5s) {
  3145. // source image MD5 hash provided
  3146. $this->DebugMessage('SetCacheFilename() _raw set from $this->md5s = "'.$this->md5s.'"', __FILE__, __LINE__);
  3147. $broad_directory_name = $this->md5s;
  3148. $this->cache_filename .= '_raw'.$this->md5s;
  3149. } elseif (!$this->src && $this->rawImageData) {
  3150. $this->DebugMessage('SetCacheFilename() _raw set from md5($this->rawImageData) = "'.md5($this->rawImageData).'"', __FILE__, __LINE__);
  3151. $broad_directory_name = strtolower(md5($this->rawImageData));
  3152. $this->cache_filename .= '_raw'.$broad_directory_name;
  3153. } else {
  3154. $this->DebugMessage('SetCacheFilename() _src set from md5($this->sourceFilename) "'.$this->sourceFilename.'" = "'.md5($this->sourceFilename).'"', __FILE__, __LINE__);
  3155. $broad_directory_name = strtolower(md5($this->sourceFilename));
  3156. $this->cache_filename .= '_src'.$broad_directory_name;
  3157. }
  3158. if (!empty($_SERVER['HTTP_REFERER']) && $this->config_nooffsitelink_enabled) {
  3159. $parsed_url1 = @phpthumb_functions::ParseURLbetter(@$_SERVER['HTTP_REFERER']);
  3160. $parsed_url2 = @phpthumb_functions::ParseURLbetter('http://'.@$_SERVER['HTTP_HOST']);
  3161. if (@$parsed_url1['host'] && @$parsed_url2['host'] && ($parsed_url1['host'] != $parsed_url2['host'])) {
  3162. // include "_offsite" only if nooffsitelink_enabled and if referrer doesn't match the domain of the current server
  3163. $this->cache_filename .= '_offsite';
  3164. }
  3165. }
  3166. $ParametersString = '';
  3167. if ($this->fltr && is_array($this->fltr)) {
  3168. $ParametersString .= '_fltr'.implode('_fltr', $this->fltr);
  3169. }
  3170. $FilenameParameters1 = array('ar', 'bg', 'bc', 'far', 'sx', 'sy', 'sw', 'sh', 'zc');
  3171. foreach ($FilenameParameters1 as $key) {
  3172. if ($this->$key) {
  3173. $ParametersString .= '_'.$key.$this->$key;
  3174. }
  3175. }
  3176. $FilenameParameters2 = array('h', 'w', 'wl', 'wp', 'ws', 'hp', 'hs', 'xto', 'ra', 'iar', 'aoe', 'maxb', 'sfn', 'dpi');
  3177. foreach ($FilenameParameters2 as $key) {
  3178. if ($this->$key) {
  3179. $ParametersString .= '_'.$key. (int) $this->$key;
  3180. }
  3181. }
  3182. if ($this->thumbnailFormat == 'jpeg') {
  3183. // only JPEG output has variable quality option
  3184. $ParametersString .= '_q'. (int) $this->thumbnailQuality;
  3185. }
  3186. $this->DebugMessage('SetCacheFilename() _par set from md5('.$ParametersString.')', __FILE__, __LINE__);
  3187. $this->cache_filename .= '_par'.strtolower(md5($ParametersString));
  3188. if ($this->md5s) {
  3189. // source image MD5 hash provided
  3190. // do not source image modification date --
  3191. // cached image will be used even if file was modified or removed
  3192. } elseif (!$this->config_cache_source_filemtime_ignore_remote && preg_match('#^(f|ht)tps?\://#i', $this->src)) {
  3193. $this->cache_filename .= '_dat'. (int) phpthumb_functions::filedate_remote($this->src);
  3194. } elseif (!$this->config_cache_source_filemtime_ignore_local && $this->src && !$this->rawImageData) {
  3195. $this->cache_filename .= '_dat'. (int) (@filemtime($this->sourceFilename));
  3196. }
  3197. $this->cache_filename .= '.'.strtolower($this->thumbnailFormat);
  3198. $broad_directories = '';
  3199. for ($i = 0; $i < $this->config_cache_directory_depth; $i++) {
  3200. $broad_directories .= DIRECTORY_SEPARATOR.substr($broad_directory_name, 0, $i + 1);
  3201. }
  3202. $this->cache_filename = $this->config_cache_directory.$broad_directories.DIRECTORY_SEPARATOR.$this->config_cache_prefix.rawurlencode($this->cache_filename);
  3203. return true;
  3204. }
  3205. public function SourceImageIsTooLarge($width, $height) {
  3206. if (!$this->config_max_source_pixels) {
  3207. return false;
  3208. }
  3209. if ($this->php_memory_limit && function_exists('memory_get_usage')) {
  3210. $available_memory = $this->php_memory_limit - memory_get_usage();
  3211. return (bool) (($width * $height * 5) > $available_memory);
  3212. }
  3213. return (bool) (($width * $height) > $this->config_max_source_pixels);
  3214. }
  3215. public function ImageCreateFromFilename($filename) {
  3216. // try to create GD image source directly via GD, if possible,
  3217. // rather than buffering to memory and creating with imagecreatefromstring
  3218. $ImageCreateWasAttempted = false;
  3219. $gd_image = false;
  3220. $this->DebugMessage('starting ImageCreateFromFilename('.$filename.')', __FILE__, __LINE__);
  3221. if ($filename && ($getimagesizeinfo = @getimagesize($filename))) {
  3222. if (!$this->SourceImageIsTooLarge($getimagesizeinfo[0], $getimagesizeinfo[1])) {
  3223. $ImageCreateFromFunction = array(
  3224. 1 => 'imagecreatefromgif',
  3225. 2 => 'imagecreatefromjpeg',
  3226. 3 => 'imagecreatefrompng',
  3227. 15 => 'imagecreatefromwbmp',
  3228. );
  3229. $this->DebugMessage('ImageCreateFromFilename found ($getimagesizeinfo[2]=='.@$getimagesizeinfo[2].')', __FILE__, __LINE__);
  3230. switch (@$getimagesizeinfo[2]) {
  3231. case 1: // GIF
  3232. case 2: // JPEG
  3233. case 3: // PNG
  3234. case 15: // WBMP
  3235. $ImageCreateFromFunctionName = $ImageCreateFromFunction[$getimagesizeinfo[2]];
  3236. if (function_exists($ImageCreateFromFunctionName)) {
  3237. $this->DebugMessage('Calling '.$ImageCreateFromFunctionName.'('.$filename.')', __FILE__, __LINE__);
  3238. $ImageCreateWasAttempted = true;
  3239. $gd_image = $ImageCreateFromFunctionName($filename);
  3240. } else {
  3241. $this->DebugMessage('NOT calling '.$ImageCreateFromFunctionName.'('.$filename.') because !function_exists('.$ImageCreateFromFunctionName.')', __FILE__, __LINE__);
  3242. }
  3243. break;
  3244. case 4: // SWF
  3245. case 5: // PSD
  3246. case 6: // BMP
  3247. case 7: // TIFF (LE)
  3248. case 8: // TIFF (BE)
  3249. case 9: // JPC
  3250. case 10: // JP2
  3251. case 11: // JPX
  3252. case 12: // JB2
  3253. case 13: // SWC
  3254. case 14: // IFF
  3255. case 16: // XBM
  3256. $this->DebugMessage('No built-in image creation function for image type "'.@$getimagesizeinfo[2].'" ($getimagesizeinfo[2])', __FILE__, __LINE__);
  3257. break;
  3258. default:
  3259. $this->DebugMessage('Unknown value for $getimagesizeinfo[2]: "'.@$getimagesizeinfo[2].'"', __FILE__, __LINE__);
  3260. break;
  3261. }
  3262. } else {
  3263. $this->DebugMessage('image is '.$getimagesizeinfo[0].'x'.$getimagesizeinfo[1].' and therefore contains more pixels ('.($getimagesizeinfo[0] * $getimagesizeinfo[1]).') than $this->config_max_source_pixels setting ('.$this->config_max_source_pixels.')', __FILE__, __LINE__);
  3264. return false;
  3265. }
  3266. } else {
  3267. $this->DebugMessage('empty $filename or getimagesize('.$filename.') failed', __FILE__, __LINE__);
  3268. }
  3269. if (!$gd_image) {
  3270. // cannot create from filename, attempt to create source image with imagecreatefromstring, if possible
  3271. if ($ImageCreateWasAttempted) {
  3272. $this->DebugMessage($ImageCreateFromFunctionName.'() was attempted but FAILED', __FILE__, __LINE__);
  3273. }
  3274. $this->DebugMessage('Populating $rawimagedata', __FILE__, __LINE__);
  3275. $rawimagedata = '';
  3276. if ($fp = @fopen($filename, 'rb')) {
  3277. $filesize = filesize($filename);
  3278. $blocksize = 8192;
  3279. $blockreads = ceil($filesize / $blocksize);
  3280. for ($i = 0; $i < $blockreads; $i++) {
  3281. $rawimagedata .= fread($fp, $blocksize);
  3282. }
  3283. fclose($fp);
  3284. } else {
  3285. $this->DebugMessage('cannot fopen('.$filename.')', __FILE__, __LINE__);
  3286. }
  3287. if ($rawimagedata) {
  3288. $this->DebugMessage('attempting ImageCreateFromStringReplacement($rawimagedata ('.strlen($rawimagedata).' bytes), true)', __FILE__, __LINE__);
  3289. $gd_image = $this->ImageCreateFromStringReplacement($rawimagedata, true);
  3290. }
  3291. }
  3292. return $gd_image;
  3293. }
  3294. public function SourceImageToGD() {
  3295. if (is_resource($this->gdimg_source)) {
  3296. $this->source_width = imagesx($this->gdimg_source);
  3297. $this->source_height = imagesy($this->gdimg_source);
  3298. $this->DebugMessage('skipping SourceImageToGD() because $this->gdimg_source is already a resource ('.$this->source_width.'x'.$this->source_height.')', __FILE__, __LINE__);
  3299. return true;
  3300. }
  3301. $this->DebugMessage('starting SourceImageToGD()', __FILE__, __LINE__);
  3302. if ($this->config_prefer_imagemagick) {
  3303. if (empty($this->sourceFilename) && !empty($this->rawImageData)) {
  3304. $this->DebugMessage('Copying raw image data to temp file and trying again with ImageMagick', __FILE__, __LINE__);
  3305. if ($tempnam = $this->phpThumb_tempnam()) {
  3306. if (file_put_contents($tempnam, $this->rawImageData)) {
  3307. $this->sourceFilename = $tempnam;
  3308. if ($this->ImageMagickThumbnailToGD()) {
  3309. // excellent, we have a thumbnailed source image
  3310. $this->DebugMessage('ImageMagickThumbnailToGD() succeeded', __FILE__, __LINE__);
  3311. } else {
  3312. $this->DebugMessage('ImageMagickThumbnailToGD() failed', __FILE__, __LINE__);
  3313. }
  3314. @chmod($tempnam, $this->getParameter('config_file_create_mask'));
  3315. } else {
  3316. $this->DebugMessage('failed to put $this->rawImageData into temp file "'.$tempnam.'"', __FILE__, __LINE__);
  3317. }
  3318. } else {
  3319. $this->DebugMessage('failed to generate temp file name', __FILE__, __LINE__);
  3320. }
  3321. }
  3322. }
  3323. if (!$this->gdimg_source && $this->rawImageData) {
  3324. if ($this->SourceImageIsTooLarge($this->source_width, $this->source_height)) {
  3325. $memory_get_usage = (function_exists('memory_get_usage') ? memory_get_usage() : 0);
  3326. return $this->ErrorImage('Source image is too large ('.$this->source_width.'x'.$this->source_height.' = '.number_format($this->source_width * $this->source_height / 1000000, 1).'Mpx, max='.number_format($this->config_max_source_pixels / 1000000, 1).'Mpx) for GD creation (either install ImageMagick or increase PHP memory_limit to at least '.ceil(($memory_get_usage + (5 * $this->source_width * $this->source_height)) / 1048576).'M).');
  3327. }
  3328. if ($this->md5s && ($this->md5s != md5($this->rawImageData))) {
  3329. return $this->ErrorImage('$this->md5s != md5($this->rawImageData)'."\n".'"'.$this->md5s.'" != '."\n".'"'.md5($this->rawImageData).'"');
  3330. }
  3331. //if ($this->issafemode) {
  3332. // return $this->ErrorImage('Cannot generate thumbnails from raw image data when PHP SAFE_MODE enabled');
  3333. //}
  3334. $this->gdimg_source = $this->ImageCreateFromStringReplacement($this->rawImageData);
  3335. if (!$this->gdimg_source) {
  3336. if (substr($this->rawImageData, 0, 2) === 'BM') {
  3337. $this->getimagesizeinfo[2] = 6; // BMP
  3338. } elseif (substr($this->rawImageData, 0, 4) === 'II'."\x2A\x00") {
  3339. $this->getimagesizeinfo[2] = 7; // TIFF (littlendian)
  3340. } elseif (substr($this->rawImageData, 0, 4) === 'MM'."\x00\x2A") {
  3341. $this->getimagesizeinfo[2] = 8; // TIFF (bigendian)
  3342. }
  3343. $this->DebugMessage('SourceImageToGD.ImageCreateFromStringReplacement() failed with unknown image type "'.substr($this->rawImageData, 0, 4).'" ('.phpthumb_functions::HexCharDisplay(substr($this->rawImageData, 0, 4)).')', __FILE__, __LINE__);
  3344. // return $this->ErrorImage('Unknown image type identified by "'.substr($this->rawImageData, 0, 4).'" ('.phpthumb_functions::HexCharDisplay(substr($this->rawImageData, 0, 4)).') in SourceImageToGD()['.__LINE__.']');
  3345. }
  3346. } elseif (!$this->gdimg_source && $this->sourceFilename) {
  3347. if ($this->md5s && ($this->md5s != phpthumb_functions::md5_file_safe($this->sourceFilename))) {
  3348. return $this->ErrorImage('$this->md5s != md5(sourceFilename)'."\n".'"'.$this->md5s.'" != '."\n".'"'.phpthumb_functions::md5_file_safe($this->sourceFilename).'"');
  3349. }
  3350. switch (@$this->getimagesizeinfo[2]) {
  3351. case 1:
  3352. case 3:
  3353. // GIF or PNG input file may have transparency
  3354. $this->is_alpha = true;
  3355. break;
  3356. }
  3357. if (!$this->SourceImageIsTooLarge($this->source_width, $this->source_height)) {
  3358. $this->gdimg_source = $this->ImageCreateFromFilename($this->sourceFilename);
  3359. }
  3360. }
  3361. while (true) {
  3362. if ($this->gdimg_source) {
  3363. $this->DebugMessage('Not using EXIF thumbnail data because $this->gdimg_source is already set', __FILE__, __LINE__);
  3364. break;
  3365. }
  3366. if (!$this->exif_thumbnail_data) {
  3367. $this->DebugMessage('Not using EXIF thumbnail data because $this->exif_thumbnail_data is empty', __FILE__, __LINE__);
  3368. break;
  3369. }
  3370. if (ini_get('safe_mode')) {
  3371. if (!$this->SourceImageIsTooLarge($this->source_width, $this->source_height)) {
  3372. $this->DebugMessage('Using EXIF thumbnail data because source image too large and safe_mode enabled', __FILE__, __LINE__);
  3373. $this->aoe = true;
  3374. } else {
  3375. break;
  3376. }
  3377. } else {
  3378. if (!$this->config_use_exif_thumbnail_for_speed) {
  3379. $this->DebugMessage('Not using EXIF thumbnail data because $this->config_use_exif_thumbnail_for_speed is FALSE', __FILE__, __LINE__);
  3380. break;
  3381. }
  3382. if (($this->thumbnailCropX != 0) || ($this->thumbnailCropY != 0)) {
  3383. $this->DebugMessage('Not using EXIF thumbnail data because source cropping is enabled ('.$this->thumbnailCropX.','.$this->thumbnailCropY.')', __FILE__, __LINE__);
  3384. break;
  3385. }
  3386. if (($this->w > $this->exif_thumbnail_width) || ($this->h > $this->exif_thumbnail_height)) {
  3387. $this->DebugMessage('Not using EXIF thumbnail data because EXIF thumbnail is too small ('.$this->exif_thumbnail_width.'x'.$this->exif_thumbnail_height.' vs '.$this->w.'x'.$this->h.')', __FILE__, __LINE__);
  3388. break;
  3389. }
  3390. $source_ar = $this->source_width / $this->source_height;
  3391. $exif_ar = $this->exif_thumbnail_width / $this->exif_thumbnail_height;
  3392. if (number_format($source_ar, 2) != number_format($exif_ar, 2)) {
  3393. $this->DebugMessage('not using EXIF thumbnail because $source_ar != $exif_ar ('.$source_ar.' != '.$exif_ar.')', __FILE__, __LINE__);
  3394. break;
  3395. }
  3396. }
  3397. // EXIF thumbnail exists, and is equal to or larger than destination thumbnail, and will be use as source image
  3398. $this->DebugMessage('Trying to use EXIF thumbnail as source image', __FILE__, __LINE__);
  3399. if ($gdimg_exif_temp = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data, false)) {
  3400. $this->DebugMessage('Successfully using EXIF thumbnail as source image', __FILE__, __LINE__);
  3401. $this->gdimg_source = $gdimg_exif_temp;
  3402. $this->source_width = $this->exif_thumbnail_width;
  3403. $this->source_height = $this->exif_thumbnail_height;
  3404. $this->thumbnailCropW = $this->source_width;
  3405. $this->thumbnailCropH = $this->source_height;
  3406. return true;
  3407. } else {
  3408. $this->DebugMessage('$this->ImageCreateFromStringReplacement($this->exif_thumbnail_data, false) failed', __FILE__, __LINE__);
  3409. }
  3410. break;
  3411. }
  3412. if (!$this->gdimg_source) {
  3413. $this->DebugMessage('$this->gdimg_source is still empty', __FILE__, __LINE__);
  3414. $this->DebugMessage('ImageMagickThumbnailToGD() failed', __FILE__, __LINE__);
  3415. $imageHeader = '';
  3416. $gd_info = gd_info();
  3417. $GDreadSupport = false;
  3418. switch (@$this->getimagesizeinfo[2]) {
  3419. case 1:
  3420. $imageHeader = 'Content-Type: image/gif';
  3421. $GDreadSupport = (bool) @$gd_info['GIF Read Support'];
  3422. break;
  3423. case 2:
  3424. $imageHeader = 'Content-Type: image/jpeg';
  3425. $GDreadSupport = (bool) @$gd_info['JPG Support'];
  3426. break;
  3427. case 3:
  3428. $imageHeader = 'Content-Type: image/png';
  3429. $GDreadSupport = (bool) @$gd_info['PNG Support'];
  3430. break;
  3431. }
  3432. if ($imageHeader) {
  3433. // cannot create image for whatever reason (maybe imagecreatefromjpeg et al are not available?)
  3434. // and ImageMagick is not available either, no choice but to output original (not resized/modified) data and exit
  3435. if ($this->config_error_die_on_source_failure) {
  3436. $errormessages = array();
  3437. $errormessages[] = 'All attempts to create GD image source failed.';
  3438. if ($this->fatalerror) {
  3439. $errormessages[] = $this->fatalerror;
  3440. }
  3441. if ($this->issafemode) {
  3442. $errormessages[] = 'Safe Mode enabled, therefore ImageMagick is unavailable. (disable Safe Mode if possible)';
  3443. } elseif (!$this->ImageMagickVersion()) {
  3444. $errormessages[] = 'ImageMagick is not installed (it is highly recommended that you install it).';
  3445. }
  3446. if ($this->SourceImageIsTooLarge($this->getimagesizeinfo[0], $this->getimagesizeinfo[1])) {
  3447. $memory_get_usage = (function_exists('memory_get_usage') ? memory_get_usage() : 0);
  3448. $errormessages[] = 'Source image is too large ('.$this->getimagesizeinfo[0].'x'.$this->getimagesizeinfo[1].' = '.number_format($this->getimagesizeinfo[0] * $this->getimagesizeinfo[1] / 1000000, 1).'Mpx, max='.number_format($this->config_max_source_pixels / 1000000, 1).'Mpx) for GD creation (either install ImageMagick or increase PHP memory_limit to at least '.ceil(($memory_get_usage + (5 * $this->getimagesizeinfo[0] * $this->getimagesizeinfo[1])) / 1048576).'M).';
  3449. } elseif (!$GDreadSupport) {
  3450. $errormessages[] = 'GD does not have read support for "'.$imageHeader.'".';
  3451. } else {
  3452. $errormessages[] = 'Source image probably corrupt.';
  3453. }
  3454. $this->ErrorImage(implode("\n", $errormessages));
  3455. } else {
  3456. $this->DebugMessage('All attempts to create GD image source failed ('.(ini_get('safe_mode') ? 'Safe Mode enabled, ImageMagick unavailable and source image probably too large for GD': ($GDreadSupport ? 'source image probably corrupt' : 'GD does not have read support for "'.$imageHeader.'"')).'), cannot generate thumbnail');
  3457. //$this->DebugMessage('All attempts to create GD image source failed ('.($GDreadSupport ? 'source image probably corrupt' : 'GD does not have read support for "'.$imageHeader.'"').'), outputing raw image', __FILE__, __LINE__);
  3458. //if (!$this->phpThumbDebug) {
  3459. // header($imageHeader);
  3460. // echo $this->rawImageData;
  3461. // exit;
  3462. //}
  3463. return false;
  3464. }
  3465. }
  3466. //switch (substr($this->rawImageData, 0, 2)) {
  3467. // case 'BM':
  3468. switch (@$this->getimagesizeinfo[2]) {
  3469. case 6:
  3470. ob_start();
  3471. if (!@include_once __DIR__ .'/phpthumb.bmp.php' ) {
  3472. ob_end_clean();
  3473. return $this->ErrorImage('include_once('. __DIR__ .'/phpthumb.bmp.php) failed');
  3474. }
  3475. ob_end_clean();
  3476. if ($fp = @fopen($this->sourceFilename, 'rb')) {
  3477. $this->rawImageData = '';
  3478. while (!feof($fp)) {
  3479. $this->rawImageData .= fread($fp, 32768);
  3480. }
  3481. fclose($fp);
  3482. }
  3483. $phpthumb_bmp = new phpthumb_bmp();
  3484. $this->gdimg_source = $phpthumb_bmp->phpthumb_bmp2gd($this->rawImageData, phpthumb_functions::gd_version() >= 2.0);
  3485. unset($phpthumb_bmp);
  3486. if ($this->gdimg_source) {
  3487. $this->DebugMessage('$phpthumb_bmp->phpthumb_bmp2gd() succeeded', __FILE__, __LINE__);
  3488. } else {
  3489. return $this->ErrorImage($this->ImageMagickVersion() ? 'ImageMagick failed on BMP source conversion' : 'phpthumb_bmp2gd() failed');
  3490. }
  3491. break;
  3492. //}
  3493. //switch (substr($this->rawImageData, 0, 4)) {
  3494. // case 'II'."\x2A\x00":
  3495. // case 'MM'."\x00\x2A":
  3496. case 7:
  3497. case 8:
  3498. return $this->ErrorImage($this->ImageMagickVersion() ? 'ImageMagick failed on TIFF source conversion' : 'ImageMagick is unavailable and phpThumb() does not support TIFF source images without it');
  3499. break;
  3500. //case "\xD7\xCD\xC6\x9A":
  3501. // return $this->ErrorImage($this->ImageMagickVersion() ? 'ImageMagick failed on WMF source conversion' : 'ImageMagick is unavailable and phpThumb() does not support WMF source images without it');
  3502. // break;
  3503. }
  3504. if (!$this->gdimg_source) {
  3505. if ($this->rawImageData) {
  3506. $HeaderFourBytes = substr($this->rawImageData, 0, 4);
  3507. } elseif ($this->sourceFilename) {
  3508. if ($fp = @fopen($this->sourceFilename, 'rb')) {
  3509. $HeaderFourBytes = fread($fp, 4);
  3510. fclose($fp);
  3511. } else {
  3512. return $this->ErrorImage('failed to open "'.$this->sourceFilename.'" SourceImageToGD() ['.__LINE__.']');
  3513. }
  3514. } else {
  3515. return $this->ErrorImage('Unable to create image, neither filename nor image data suppplied in SourceImageToGD() ['.__LINE__.']');
  3516. }
  3517. if (!$this->ImageMagickVersion() && !phpthumb_functions::gd_version()) {
  3518. return $this->ErrorImage('Neither GD nor ImageMagick seem to be installed on this server. At least one (preferably GD), or better both, MUST be installed for phpThumb to work.');
  3519. } elseif ($HeaderFourBytes == "\xD7\xCD\xC6\x9A") { // WMF
  3520. return $this->ErrorImage($this->ImageMagickVersion() ? 'ImageMagick failed on WMF source conversion' : 'ImageMagick is unavailable and phpThumb() does not support WMF source images without it');
  3521. } elseif ($HeaderFourBytes == '%PDF') { // "%PDF"
  3522. return $this->ErrorImage($this->ImageMagickVersion() ? 'ImageMagick and GhostScript are both required for PDF source images; GhostScript may not be properly configured' : 'ImageMagick and/or GhostScript are unavailable and phpThumb() does not support PDF source images without them');
  3523. } elseif (substr($HeaderFourBytes, 0, 3) == "\xFF\xD8\xFF") { // JPEG
  3524. return $this->ErrorImage('Image (JPEG) is too large for PHP-GD memory_limit, please install ImageMagick or increase php.ini memory_limit setting');
  3525. } elseif ($HeaderFourBytes == '%PNG') { // "%PNG"
  3526. return $this->ErrorImage('Image (PNG) is too large for PHP-GD memory_limit, please install ImageMagick or increase php.ini memory_limit setting');
  3527. } elseif (substr($HeaderFourBytes, 0, 3) == 'GIF') { // GIF
  3528. return $this->ErrorImage('Image (GIF) is too large for PHP-GD memory_limit, please install ImageMagick or increase php.ini memory_limit setting');
  3529. }
  3530. return $this->ErrorImage('Unknown image type identified by "'.$HeaderFourBytes.'" ('.phpthumb_functions::HexCharDisplay($HeaderFourBytes).') in SourceImageToGD() ['.__LINE__.']');
  3531. }
  3532. }
  3533. if (!$this->gdimg_source) {
  3534. if ($gdimg_exif_temp = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data, false)) {
  3535. $this->DebugMessage('All other attempts failed, but successfully using EXIF thumbnail as source image', __FILE__, __LINE__);
  3536. $this->gdimg_source = $gdimg_exif_temp;
  3537. // override allow-enlarging setting if EXIF thumbnail is the only source available
  3538. // otherwise thumbnails larger than the EXIF thumbnail will be created at EXIF size
  3539. $this->aoe = true;
  3540. return true;
  3541. }
  3542. return false;
  3543. }
  3544. $this->source_width = imagesx($this->gdimg_source);
  3545. $this->source_height = imagesy($this->gdimg_source);
  3546. return true;
  3547. }
  3548. public function phpThumbDebugVarDump($var) {
  3549. if (null === $var) {
  3550. return 'NULL';
  3551. } elseif (is_bool($var)) {
  3552. return ($var ? 'TRUE' : 'FALSE');
  3553. } elseif (is_string($var)) {
  3554. return 'string('.strlen($var).')'.str_repeat(' ', max(0, 3 - strlen(strlen($var)))).' "'.$var.'"';
  3555. } elseif (is_int($var)) {
  3556. return 'integer '.$var;
  3557. } elseif (is_float($var)) {
  3558. return 'float '.$var;
  3559. } elseif (is_array($var)) {
  3560. ob_start();
  3561. var_dump($var);
  3562. $vardumpoutput = ob_get_contents();
  3563. ob_end_clean();
  3564. return strtr($vardumpoutput, "\n\r\t", ' ');
  3565. }
  3566. return gettype($var);
  3567. }
  3568. public function phpThumbDebug($level='') {
  3569. if ($level && ($this->phpThumbDebug !== $level)) {
  3570. return true;
  3571. }
  3572. if ($this->config_disable_debug) {
  3573. return $this->ErrorImage('phpThumbDebug disabled');
  3574. }
  3575. $FunctionsExistance = array('exif_thumbnail', 'gd_info', 'image_type_to_mime_type', 'getimagesize', 'imagecopyresampled', 'imagecopyresized', 'imagecreate', 'imagecreatefromstring', 'imagecreatetruecolor', 'imageistruecolor', 'imagerotate', 'imagetypes', 'version_compare', 'imagecreatefromgif', 'imagecreatefromjpeg', 'imagecreatefrompng', 'imagecreatefromwbmp', 'imagecreatefromxbm', 'imagecreatefromxpm', 'imagecreatefromstring', 'imagecreatefromgd', 'imagecreatefromgd2', 'imagecreatefromgd2part', 'imagejpeg', 'imagegif', 'imagepng', 'imagewbmp');
  3576. $ParameterNames = array('src', 'new', 'w', 'h', 'f', 'q', 'sx', 'sy', 'sw', 'sh', 'far', 'bg', 'bc', 'file', 'goto', 'err', 'xto', 'ra', 'ar', 'aoe', 'iar', 'maxb');
  3577. $ConfigVariableNames = array('document_root', 'temp_directory', 'output_format', 'output_maxwidth', 'output_maxheight', 'error_message_image_default', 'error_bgcolor', 'error_textcolor', 'error_fontsize', 'error_die_on_error', 'error_silent_die_on_error', 'error_die_on_source_failure', 'nohotlink_enabled', 'nohotlink_valid_domains', 'nohotlink_erase_image', 'nohotlink_text_message', 'nooffsitelink_enabled', 'nooffsitelink_valid_domains', 'nooffsitelink_require_refer', 'nooffsitelink_erase_image', 'nooffsitelink_text_message', 'high_security_enabled', 'allow_src_above_docroot', 'allow_src_above_phpthumb', 'max_source_pixels', 'use_exif_thumbnail_for_speed', 'border_hexcolor', 'background_hexcolor', 'ttf_directory', 'disable_pathinfo_parsing', 'disable_imagecopyresampled');
  3578. $OtherVariableNames = array('phpThumbDebug', 'thumbnailQuality', 'thumbnailFormat', 'gdimg_output', 'gdimg_source', 'sourceFilename', 'source_width', 'source_height', 'thumbnailCropX', 'thumbnailCropY', 'thumbnailCropW', 'thumbnailCropH', 'exif_thumbnail_width', 'exif_thumbnail_height', 'exif_thumbnail_type', 'thumbnail_width', 'thumbnail_height', 'thumbnail_image_width', 'thumbnail_image_height');
  3579. $DebugOutput = array();
  3580. $DebugOutput[] = 'phpThumb() version = '.$this->phpthumb_version;
  3581. $DebugOutput[] = 'phpversion() = '.@PHP_VERSION;
  3582. $DebugOutput[] = 'PHP_OS = '.PHP_OS;
  3583. $DebugOutput[] = '$_SERVER[SERVER_SOFTWARE] = '.@$_SERVER['SERVER_SOFTWARE'];
  3584. $DebugOutput[] = '__FILE__ = '.__FILE__;
  3585. $DebugOutput[] = 'realpath(.) = '.@realpath('.');
  3586. $DebugOutput[] = '$_SERVER[PHP_SELF] = '.@$_SERVER['PHP_SELF'];
  3587. $DebugOutput[] = '$_SERVER[HOST_NAME] = '.@$_SERVER['HOST_NAME'];
  3588. $DebugOutput[] = '$_SERVER[HTTP_REFERER] = '.@$_SERVER['HTTP_REFERER'];
  3589. $DebugOutput[] = '$_SERVER[QUERY_STRING] = '.@$_SERVER['QUERY_STRING'];
  3590. $DebugOutput[] = '$_SERVER[PATH_INFO] = '.@$_SERVER['PATH_INFO'];
  3591. $DebugOutput[] = '$_SERVER[DOCUMENT_ROOT] = '.@$_SERVER['DOCUMENT_ROOT'];
  3592. $DebugOutput[] = 'getenv(DOCUMENT_ROOT) = '.@getenv('DOCUMENT_ROOT');
  3593. $DebugOutput[] = '';
  3594. $DebugOutput[] = 'get_magic_quotes_gpc() = '.$this->phpThumbDebugVarDump(@get_magic_quotes_gpc());
  3595. $DebugOutput[] = 'get_magic_quotes_runtime() = '.$this->phpThumbDebugVarDump(@get_magic_quotes_runtime());
  3596. $DebugOutput[] = 'error_reporting() = '.$this->phpThumbDebugVarDump(error_reporting());
  3597. $DebugOutput[] = 'ini_get(error_reporting) = '.$this->phpThumbDebugVarDump(@ini_get('error_reporting'));
  3598. $DebugOutput[] = 'ini_get(display_errors) = '.$this->phpThumbDebugVarDump(@ini_get('display_errors'));
  3599. $DebugOutput[] = 'ini_get(allow_url_fopen) = '.$this->phpThumbDebugVarDump(@ini_get('allow_url_fopen'));
  3600. $DebugOutput[] = 'ini_get(disable_functions) = '.$this->phpThumbDebugVarDump(@ini_get('disable_functions'));
  3601. $DebugOutput[] = 'get_cfg_var(disable_functions) = '.$this->phpThumbDebugVarDump(@get_cfg_var('disable_functions'));
  3602. $DebugOutput[] = 'ini_get(safe_mode) = '.$this->phpThumbDebugVarDump(@ini_get('safe_mode'));
  3603. $DebugOutput[] = 'ini_get(open_basedir) = '.$this->phpThumbDebugVarDump(@ini_get('open_basedir'));
  3604. $DebugOutput[] = 'ini_get(max_execution_time) = '.$this->phpThumbDebugVarDump(@ini_get('max_execution_time'));
  3605. $DebugOutput[] = 'ini_get(memory_limit) = '.$this->phpThumbDebugVarDump(@ini_get('memory_limit'));
  3606. $DebugOutput[] = 'get_cfg_var(memory_limit) = '.$this->phpThumbDebugVarDump(@get_cfg_var('memory_limit'));
  3607. $DebugOutput[] = 'memory_get_usage() = '.(function_exists('memory_get_usage') ? $this->phpThumbDebugVarDump(@memory_get_usage()) : 'n/a');
  3608. $DebugOutput[] = '';
  3609. $DebugOutput[] = '$this->config_prefer_imagemagick = '.$this->phpThumbDebugVarDump($this->config_prefer_imagemagick);
  3610. $DebugOutput[] = '$this->config_imagemagick_path = '.$this->phpThumbDebugVarDump($this->config_imagemagick_path);
  3611. $DebugOutput[] = '$this->ImageMagickWhichConvert() = '.$this->ImageMagickWhichConvert();
  3612. $IMpathUsed = ($this->config_imagemagick_path ? $this->config_imagemagick_path : $this->ImageMagickWhichConvert());
  3613. $DebugOutput[] = '[actual ImageMagick path used] = '.$this->phpThumbDebugVarDump($IMpathUsed);
  3614. $DebugOutput[] = 'file_exists([actual ImageMagick path used]) = '.$this->phpThumbDebugVarDump(@file_exists($IMpathUsed));
  3615. $DebugOutput[] = 'ImageMagickVersion(false) = '.$this->ImageMagickVersion(false);
  3616. $DebugOutput[] = 'ImageMagickVersion(true) = '.$this->ImageMagickVersion(true);
  3617. $DebugOutput[] = '';
  3618. $DebugOutput[] = '$this->config_cache_directory = '.$this->phpThumbDebugVarDump($this->config_cache_directory);
  3619. $DebugOutput[] = '$this->config_cache_directory_depth = '.$this->phpThumbDebugVarDump($this->config_cache_directory_depth);
  3620. $DebugOutput[] = '$this->config_cache_disable_warning = '.$this->phpThumbDebugVarDump($this->config_cache_disable_warning);
  3621. $DebugOutput[] = '$this->config_cache_maxage = '.$this->phpThumbDebugVarDump($this->config_cache_maxage);
  3622. $DebugOutput[] = '$this->config_cache_maxsize = '.$this->phpThumbDebugVarDump($this->config_cache_maxsize);
  3623. $DebugOutput[] = '$this->config_cache_maxfiles = '.$this->phpThumbDebugVarDump($this->config_cache_maxfiles);
  3624. $DebugOutput[] = '$this->config_cache_force_passthru = '.$this->phpThumbDebugVarDump($this->config_cache_force_passthru);
  3625. $DebugOutput[] = '$this->cache_filename = '.$this->phpThumbDebugVarDump($this->cache_filename);
  3626. $DebugOutput[] = 'is_readable($this->config_cache_directory) = '.$this->phpThumbDebugVarDump(@is_readable($this->config_cache_directory));
  3627. $DebugOutput[] = 'is_writable($this->config_cache_directory) = '.$this->phpThumbDebugVarDump(@is_writable($this->config_cache_directory));
  3628. $DebugOutput[] = 'is_readable($this->cache_filename) = '.$this->phpThumbDebugVarDump(@is_readable($this->cache_filename));
  3629. $DebugOutput[] = 'is_writable($this->cache_filename) = '.(@file_exists($this->cache_filename) ? $this->phpThumbDebugVarDump(@is_writable($this->cache_filename)) : 'n/a');
  3630. $DebugOutput[] = '';
  3631. foreach ($ConfigVariableNames as $varname) {
  3632. $varname = 'config_'.$varname;
  3633. $value = $this->$varname;
  3634. $DebugOutput[] = '$this->'.str_pad($varname, 37, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
  3635. }
  3636. $DebugOutput[] = '';
  3637. foreach ($OtherVariableNames as $varname) {
  3638. $value = $this->$varname;
  3639. $DebugOutput[] = '$this->'.str_pad($varname, 27, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
  3640. }
  3641. $DebugOutput[] = 'strlen($this->rawImageData) = '.strlen(@$this->rawImageData);
  3642. $DebugOutput[] = 'strlen($this->exif_thumbnail_data) = '.strlen(@$this->exif_thumbnail_data);
  3643. $DebugOutput[] = '';
  3644. foreach ($ParameterNames as $varname) {
  3645. $value = $this->$varname;
  3646. $DebugOutput[] = '$this->'.str_pad($varname, 4, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
  3647. }
  3648. $DebugOutput[] = '';
  3649. foreach ($FunctionsExistance as $functionname) {
  3650. $DebugOutput[] = 'builtin_function_exists('.$functionname.')'.str_repeat(' ', 23 - strlen($functionname)).' = '.$this->phpThumbDebugVarDump(phpthumb_functions::builtin_function_exists($functionname));
  3651. }
  3652. $DebugOutput[] = '';
  3653. $gd_info = gd_info();
  3654. foreach ($gd_info as $key => $value) {
  3655. $DebugOutput[] = 'gd_info.'.str_pad($key, 34, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
  3656. }
  3657. $DebugOutput[] = '';
  3658. $exif_info = phpthumb_functions::exif_info();
  3659. foreach ($exif_info as $key => $value) {
  3660. $DebugOutput[] = 'exif_info.'.str_pad($key, 26, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
  3661. }
  3662. $DebugOutput[] = '';
  3663. if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray(dirname(@$_SERVER['PHP_SELF']))) {
  3664. foreach ($ApacheLookupURIarray as $key => $value) {
  3665. $DebugOutput[] = 'ApacheLookupURIarray.'.str_pad($key, 15, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
  3666. }
  3667. } else {
  3668. $DebugOutput[] = 'ApacheLookupURIarray() -- FAILED';
  3669. }
  3670. $DebugOutput[] = '';
  3671. if (isset($_GET) && is_array($_GET)) {
  3672. foreach ($_GET as $key => $value) {
  3673. $DebugOutput[] = '$_GET['.$key.']'.str_repeat(' ', 30 - strlen($key)).'= '.$this->phpThumbDebugVarDump($value);
  3674. }
  3675. }
  3676. if (isset($_POST) && is_array($_POST)) {
  3677. foreach ($_POST as $key => $value) {
  3678. $DebugOutput[] = '$_POST['.$key.']'.str_repeat(' ', 29 - strlen($key)).'= '.$this->phpThumbDebugVarDump($value);
  3679. }
  3680. }
  3681. $DebugOutput[] = '';
  3682. $DebugOutput[] = '$this->debugmessages:';
  3683. foreach ($this->debugmessages as $errorstring) {
  3684. $DebugOutput[] = ' * '.$errorstring;
  3685. }
  3686. $DebugOutput[] = '';
  3687. $DebugOutput[] = '$this->debugtiming:';
  3688. foreach ($this->debugtiming as $timestamp => $timingstring) {
  3689. $DebugOutput[] = ' * '.$timestamp.' '.$timingstring;
  3690. }
  3691. $DebugOutput[] = ' * Total processing time: '.number_format(max(array_keys($this->debugtiming)) - min(array_keys($this->debugtiming)), 6);
  3692. $this->f = (isset($_GET['f']) ? $_GET['f'] : $this->f); // debug modes 0-2 don't recognize text mode otherwise
  3693. return $this->ErrorImage(implode("\n", $DebugOutput), 700, 500, true);
  3694. }
  3695. public function FatalError($text) {
  3696. if (null === $this->fatalerror) {
  3697. $this->fatalerror = $text;
  3698. }
  3699. return true;
  3700. }
  3701. public function ErrorImage($text, $width=0, $height=0, $forcedisplay=false) {
  3702. $width = ($width ? $width : $this->config_error_image_width);
  3703. $height = ($height ? $height : $this->config_error_image_height);
  3704. $text = 'phpThumb() v'.$this->phpthumb_version."\n".'http://phpthumb.sourceforge.net'."\n\n".($this->config_disable_debug ? 'Error messages disabled.'."\n\n".'edit phpThumb.config.php and (temporarily) set'."\n".'$PHPTHUMB_CONFIG[\'disable_debug\'] = false;'."\n".'to view the details of this error' : $text);
  3705. $this->FatalError($text);
  3706. $this->DebugMessage($text, __FILE__, __LINE__);
  3707. $this->purgeTempFiles();
  3708. if ($this->config_error_silent_die_on_error) {
  3709. exit;
  3710. }
  3711. if ($this->phpThumbDebug && !$forcedisplay) {
  3712. return false;
  3713. }
  3714. if (!$this->config_error_die_on_error && !$forcedisplay) {
  3715. return false;
  3716. }
  3717. if ($this->err || $this->config_error_message_image_default) {
  3718. // Show generic custom error image instead of error message
  3719. // for use on production sites where you don't want debug messages
  3720. if (($this->err == 'showerror') || $this->phpThumbDebug) {
  3721. // fall through and actually show error message even if default error image is set
  3722. } else {
  3723. header('Location: '.($this->err ? $this->err : $this->config_error_message_image_default));
  3724. exit;
  3725. }
  3726. }
  3727. $this->setOutputFormat();
  3728. if (!$this->thumbnailFormat || !$this->config_disable_debug || (phpthumb_functions::gd_version() < 1)) {
  3729. $this->thumbnailFormat = 'text';
  3730. }
  3731. if (@$this->thumbnailFormat == 'text') {
  3732. // bypass all GD functions and output text error message
  3733. if (!headers_sent()) {
  3734. header('Content-type: text/plain');
  3735. echo $text;
  3736. } else {
  3737. echo '<pre>'.htmlspecialchars($text).'</pre>';
  3738. }
  3739. exit;
  3740. }
  3741. $FontWidth = imagefontwidth($this->config_error_fontsize);
  3742. $FontHeight = imagefontheight($this->config_error_fontsize);
  3743. $LinesOfText = explode("\n", @wordwrap($text, floor($width / $FontWidth), "\n", true));
  3744. $height = max($height, count($LinesOfText) * $FontHeight);
  3745. $headers_file = '';
  3746. $headers_line = '';
  3747. if (phpthumb_functions::version_compare_replacement(PHP_VERSION, '4.3.0', '>=') && headers_sent($headers_file, $headers_line)) {
  3748. echo "\n".'**Headers already sent in file "'.$headers_file.'" on line "'.$headers_line.'", dumping error message as text:**<br><pre>'."\n\n".$text."\n".'</pre>';
  3749. } elseif (headers_sent()) {
  3750. echo "\n".'**Headers already sent, dumping error message as text:**<br><pre>'."\n\n".$text."\n".'</pre>';
  3751. } elseif ($gdimg_error = imagecreate($width, $height)) {
  3752. $background_color = phpthumb_functions::ImageHexColorAllocate($gdimg_error, $this->config_error_bgcolor, true);
  3753. $text_color = phpthumb_functions::ImageHexColorAllocate($gdimg_error, $this->config_error_textcolor, true);
  3754. imagefilledrectangle($gdimg_error, 0, 0, $width, $height, $background_color);
  3755. $lineYoffset = 0;
  3756. foreach ($LinesOfText as $line) {
  3757. imagestring($gdimg_error, $this->config_error_fontsize, 2, $lineYoffset, $line, $text_color);
  3758. $lineYoffset += $FontHeight;
  3759. }
  3760. if (function_exists('imagetypes')) {
  3761. $imagetypes = imagetypes();
  3762. if ($imagetypes & IMG_PNG) {
  3763. header('Content-Type: image/png');
  3764. imagepng($gdimg_error);
  3765. } elseif ($imagetypes & IMG_GIF) {
  3766. header('Content-Type: image/gif');
  3767. imagegif($gdimg_error);
  3768. } elseif ($imagetypes & IMG_JPG) {
  3769. header('Content-Type: image/jpeg');
  3770. imagejpeg($gdimg_error);
  3771. } elseif ($imagetypes & IMG_WBMP) {
  3772. header('Content-Type: image/vnd.wap.wbmp');
  3773. imagewbmp($gdimg_error);
  3774. }
  3775. }
  3776. imagedestroy($gdimg_error);
  3777. }
  3778. if (!headers_sent()) {
  3779. echo "\n".'**Failed to send graphical error image, dumping error message as text:**<br>'."\n\n".$text;
  3780. }
  3781. exit;
  3782. }
  3783. public function ImageCreateFromStringReplacement(&$RawImageData, $DieOnErrors=false) {
  3784. // there are serious bugs in the non-bundled versions of GD which may cause
  3785. // PHP to segfault when calling imagecreatefromstring() - avoid if at all possible
  3786. // when not using a bundled version of GD2
  3787. if (!phpthumb_functions::gd_version()) {
  3788. if ($DieOnErrors) {
  3789. if (!headers_sent()) {
  3790. // base64-encoded error image in GIF format
  3791. $ERROR_NOGD = 'R0lGODlhIAAgALMAAAAAABQUFCQkJDY2NkZGRldXV2ZmZnJycoaGhpSUlKWlpbe3t8XFxdXV1eTk5P7+/iwAAAAAIAAgAAAE/vDJSau9WILtTAACUinDNijZtAHfCojS4W5H+qxD8xibIDE9h0OwWaRWDIljJSkUJYsN4bihMB8th3IToAKs1VtYM75cyV8sZ8vygtOE5yMKmGbO4jRdICQCjHdlZzwzNW4qZSQmKDaNjhUMBX4BBAlmMywFSRWEmAI6b5gAlhNxokGhooAIK5o/pi9vEw4Lfj4OLTAUpj6IabMtCwlSFw0DCKBoFqwAB04AjI54PyZ+yY3TD0ss2YcVmN/gvpcu4TOyFivWqYJlbAHPpOntvxNAACcmGHjZzAZqzSzcq5fNjxFmAFw9iFRunD1epU6tsIPmFCAJnWYE0FURk7wJDA0MTKpEzoWAAskiAAA7';
  3792. header('Content-Type: image/gif');
  3793. echo base64_decode($ERROR_NOGD);
  3794. } else {
  3795. echo '*** ERROR: No PHP-GD support available ***';
  3796. }
  3797. exit;
  3798. } else {
  3799. $this->DebugMessage('ImageCreateFromStringReplacement() failed: gd_version says "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
  3800. return false;
  3801. }
  3802. }
  3803. if (phpthumb_functions::gd_is_bundled()) {
  3804. $this->DebugMessage('ImageCreateFromStringReplacement() calling built-in imagecreatefromstring()', __FILE__, __LINE__);
  3805. return @imagecreatefromstring($RawImageData);
  3806. }
  3807. if ($this->issafemode) {
  3808. $this->DebugMessage('ImageCreateFromStringReplacement() failed: cannot create temp file in SAFE_MODE', __FILE__, __LINE__);
  3809. return false;
  3810. }
  3811. switch (substr($RawImageData, 0, 3)) {
  3812. case 'GIF':
  3813. $ICFSreplacementFunctionName = 'imagecreatefromgif';
  3814. break;
  3815. case "\xFF\xD8\xFF":
  3816. $ICFSreplacementFunctionName = 'imagecreatefromjpeg';
  3817. break;
  3818. case "\x89".'PN':
  3819. $ICFSreplacementFunctionName = 'imagecreatefrompng';
  3820. break;
  3821. default:
  3822. $this->DebugMessage('ImageCreateFromStringReplacement() failed: unknown fileformat signature "'.phpthumb_functions::HexCharDisplay(substr($RawImageData, 0, 3)).'"', __FILE__, __LINE__);
  3823. return false;
  3824. break;
  3825. }
  3826. $ErrorMessage = '';
  3827. if ($tempnam = $this->phpThumb_tempnam()) {
  3828. if ($fp_tempnam = @fopen($tempnam, 'wb')) {
  3829. fwrite($fp_tempnam, $RawImageData);
  3830. fclose($fp_tempnam);
  3831. @chmod($tempnam, $this->getParameter('config_file_create_mask'));
  3832. if (($ICFSreplacementFunctionName == 'imagecreatefromgif') && !function_exists($ICFSreplacementFunctionName)) {
  3833. // Need to create from GIF file, but imagecreatefromgif does not exist
  3834. ob_start();
  3835. if (!@include_once __DIR__ .'/phpthumb.gif.php' ) {
  3836. $ErrorMessage = 'Failed to include required file "'. __DIR__ .'/phpthumb.gif.php" in '.__FILE__.' on line '.__LINE__;
  3837. $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
  3838. }
  3839. ob_end_clean();
  3840. // gif_loadFileToGDimageResource() cannot read from raw data, write to file first
  3841. if ($tempfilename = $this->phpThumb_tempnam()) {
  3842. if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
  3843. fwrite($fp_tempfile, $RawImageData);
  3844. fclose($fp_tempfile);
  3845. $gdimg_source = gif_loadFileToGDimageResource($tempfilename);
  3846. $this->DebugMessage('gif_loadFileToGDimageResource('.$tempfilename.') completed', __FILE__, __LINE__);
  3847. $this->DebugMessage('deleting "'.$tempfilename.'"', __FILE__, __LINE__);
  3848. unlink($tempfilename);
  3849. return $gdimg_source;
  3850. } else {
  3851. $ErrorMessage = 'Failed to open tempfile in '.__FILE__.' on line '.__LINE__;
  3852. $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
  3853. }
  3854. } else {
  3855. $ErrorMessage = 'Failed to open generate tempfile name in '.__FILE__.' on line '.__LINE__;
  3856. $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
  3857. }
  3858. } elseif (function_exists($ICFSreplacementFunctionName) && ($gdimg_source = @$ICFSreplacementFunctionName($tempnam))) {
  3859. // great
  3860. $this->DebugMessage($ICFSreplacementFunctionName.'('.$tempnam.') succeeded', __FILE__, __LINE__);
  3861. $this->DebugMessage('deleting "'.$tempnam.'"', __FILE__, __LINE__);
  3862. unlink($tempnam);
  3863. return $gdimg_source;
  3864. } else {
  3865. // GD functions not available, or failed to create image
  3866. $this->DebugMessage($ICFSreplacementFunctionName.'('.$tempnam.') '.(function_exists($ICFSreplacementFunctionName) ? 'failed' : 'does not exist'), __FILE__, __LINE__);
  3867. if (isset($_GET['phpThumbDebug'])) {
  3868. $this->phpThumbDebug();
  3869. }
  3870. }
  3871. } else {
  3872. $ErrorMessage = 'Failed to fopen('.$tempnam.', "wb") in '.__FILE__.' on line '.__LINE__."\n".'You may need to set $PHPTHUMB_CONFIG[temp_directory] in phpThumb.config.php';
  3873. if ($this->issafemode) {
  3874. $ErrorMessage = 'ImageCreateFromStringReplacement() failed in '.__FILE__.' on line '.__LINE__.': cannot create temp file in SAFE_MODE';
  3875. }
  3876. $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
  3877. }
  3878. $this->DebugMessage('deleting "'.$tempnam.'"', __FILE__, __LINE__);
  3879. @unlink($tempnam);
  3880. } else {
  3881. $ErrorMessage = 'Failed to generate phpThumb_tempnam() in '.__FILE__.' on line '.__LINE__."\n".'You may need to set $PHPTHUMB_CONFIG[temp_directory] in phpThumb.config.php';
  3882. if ($this->issafemode) {
  3883. $ErrorMessage = 'ImageCreateFromStringReplacement() failed in '.__FILE__.' on line '.__LINE__.': cannot create temp file in SAFE_MODE';
  3884. }
  3885. }
  3886. if ($DieOnErrors && $ErrorMessage) {
  3887. return $this->ErrorImage($ErrorMessage);
  3888. }
  3889. return false;
  3890. }
  3891. public function ImageResizeFunction(&$dst_im, &$src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH) {
  3892. $this->DebugMessage('ImageResizeFunction($o, $s, '.$dstX.', '.$dstY.', '.$srcX.', '.$srcY.', '.$dstW.', '.$dstH.', '.$srcW.', '.$srcH.')', __FILE__, __LINE__);
  3893. if (($dstW == $srcW) && ($dstH == $srcH)) {
  3894. return imagecopy($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH);
  3895. }
  3896. if (phpthumb_functions::gd_version() >= 2.0) {
  3897. if ($this->config_disable_imagecopyresampled) {
  3898. return phpthumb_functions::ImageCopyResampleBicubic($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
  3899. }
  3900. return imagecopyresampled($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
  3901. }
  3902. return imagecopyresized($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
  3903. }
  3904. public function InitializeTempDirSetting() {
  3905. $this->config_temp_directory = ($this->config_temp_directory ? $this->config_temp_directory : $this->realPathSafe((function_exists('sys_get_temp_dir') ? sys_get_temp_dir() : ''))); // sys_get_temp_dir added in PHP v5.2.1
  3906. $this->config_temp_directory = ($this->config_temp_directory ? $this->config_temp_directory : $this->realPathSafe(ini_get('upload_tmp_dir')));
  3907. $this->config_temp_directory = ($this->config_temp_directory ? $this->config_temp_directory : $this->realPathSafe(getenv('TMPDIR')));
  3908. $this->config_temp_directory = ($this->config_temp_directory ? $this->config_temp_directory : $this->realPathSafe(getenv('TMP')));
  3909. return true;
  3910. }
  3911. public function phpThumb_tempnam() {
  3912. $this->InitializeTempDirSetting();
  3913. $tempnam = $this->realPathSafe(tempnam($this->config_temp_directory, 'pThumb'));
  3914. $this->tempFilesToDelete[$tempnam] = $tempnam;
  3915. $this->DebugMessage('phpThumb_tempnam() returning "'.$tempnam.'"', __FILE__, __LINE__);
  3916. return $tempnam;
  3917. }
  3918. public function DebugMessage($message, $file='', $line='') {
  3919. $this->debugmessages[] = $message.($file ? ' in file "'.(basename($file) ? basename($file) : $file).'"' : '').($line ? ' on line '.$line : '');
  3920. return true;
  3921. }
  3922. public function DebugTimingMessage($message, $file='', $line='', $timestamp=0) {
  3923. if (!$timestamp) {
  3924. $timestamp = array_sum(explode(' ', microtime()));
  3925. }
  3926. $this->debugtiming[number_format($timestamp, 6, '.', '')] = ': '.$message.($file ? ' in file "'.(basename($file) ? basename($file) : $file).'"' : '').($line ? ' on line '.$line : '');
  3927. return true;
  3928. }
  3929. }