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

/assets/snippets/phpthumb/phpthumb.class.php

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