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

/phpthumb.class.php

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