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

/leganto/document_root/thumb/phpthumb.class.php

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