PageRenderTime 88ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/components/com_flexicontent/librairies/phpthumb/phpthumb.class.php

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