2 //////////////////////////////////////////////////////////////
3 /// phpThumb() by James Heinrich <info@silisoftware.com> //
4 // available at http://phpthumb.sourceforge.net ///
5 //////////////////////////////////////////////////////////////
7 // See: phpthumb.readme.txt for usage instructions //
9 //////////////////////////////////////////////////////////////
12 if (!include_once(dirname(__FILE__).'/phpthumb.functions.php')) {
14 die('failed to include_once("'.realpath(dirname(__FILE__).'/phpthumb.functions.php').'")');
21 // START PARAMETERS (for object mode and phpThumb.php)
22 // See phpthumb.readme.txt for descriptions of what each of these values are
23 var $src = null; // SouRCe filename
24 var $new = null; // NEW image (phpThumb.php only)
25 var $w = null; // Width
26 var $h = null; // Height
27 var $wp = null; // Width (Portrait Images Only)
28 var $hp = null; // Height (Portrait Images Only)
29 var $wl = null; // Width (Landscape Images Only)
30 var $hl = null; // Height (Landscape Images Only)
31 var $ws = null; // Width (Square Images Only)
32 var $hs = null; // Height (Square Images Only)
33 var $f = null; // Format
34 var $q = 75; // jpeg output Quality
35 var $sx = null; // Source crop top-left X position
36 var $sy = null; // Source crop top-left Y position
37 var $sw = null; // Source crop Width
38 var $sh = null; // Source crop Height
39 var $zc = null; // Zoom Crop
40 var $bc = null; // Border Color
41 var $bg = null; // BackGround color
42 var $fltr = array(); // FiLTeRs
43 var $goto = null; // GO TO url after processing
44 var $err = null; // default ERRor image filename
45 var $xto = null; // extract eXif Thumbnail Only
46 var $ra = null; // Rotate by Angle
47 var $ar = null; // Auto Rotate
48 var $aoe = null; // Allow Output Enlargement
49 var $far = null; // Fixed Aspect Ratio
50 var $iar = null; // Ignore Aspect Ratio
51 var $maxb = null; // MAXimum Bytes
52 var $down = null; // DOWNload thumbnail filename
53 var $md5s = null; // MD5 hash of Source image
54 var $file = null; // >>deprecated, do not use<<
56 var $phpThumbDebug = null;
61 // START CONFIGURATION OPTIONS (for object mode only)
62 // See phpThumb.config.php for descriptions of what each of these settings do
64 // * Directory Configuration
65 var $config_cache_directory = null;
66 var $config_cache_disable_warning = true;
67 var $config_cache_source_enabled = false;
68 var $config_cache_source_directory = null;
69 var $config_temp_directory = null;
70 var $config_document_root = null;
72 // * Default output configuration:
73 var $config_output_format = 'jpeg';
74 var $config_output_maxwidth = 0;
75 var $config_output_maxheight = 0;
76 var $config_output_interlace = true;
78 // * Error message configuration
79 var $config_error_image_width = 400;
80 var $config_error_image_height = 100;
81 var $config_error_message_image_default = '';
82 var $config_error_bgcolor = 'CCCCFF';
83 var $config_error_textcolor = 'FF0000';
84 var $config_error_fontsize = 1;
85 var $config_error_die_on_error = false;
86 var $config_error_silent_die_on_error = false;
87 var $config_error_die_on_source_failure = true;
89 // * Anti-Hotlink Configuration:
90 var $config_nohotlink_enabled = true;
91 var $config_nohotlink_valid_domains = array();
92 var $config_nohotlink_erase_image = true;
93 var $config_nohotlink_text_message = 'Off-server thumbnailing is not allowed';
94 // * Off-server Linking Configuration:
95 var $config_nooffsitelink_enabled = false;
96 var $config_nooffsitelink_valid_domains = array();
97 var $config_nooffsitelink_require_refer = false;
98 var $config_nooffsitelink_erase_image = true;
99 var $config_nooffsitelink_text_message = 'Off-server linking is not allowed';
101 // * Border & Background default colors
102 var $config_border_hexcolor = '000000';
103 var $config_background_hexcolor = 'FFFFFF';
106 var $config_ttf_directory = '.';
108 var $config_max_source_pixels = null;
109 var $config_use_exif_thumbnail_for_speed = false;
110 var $allow_local_http_src = false;
112 var $config_imagemagick_path = null;
113 var $config_prefer_imagemagick = true;
115 var $config_cache_maxage = null;
116 var $config_cache_maxsize = null;
117 var $config_cache_maxfiles = null;
118 var $config_cache_source_filemtime_ignore_local = false;
119 var $config_cache_source_filemtime_ignore_remote = true;
120 var $config_cache_default_only_suffix = false;
121 var $config_cache_force_passthru = true;
122 var $config_cache_prefix = ''; // default value set in the constructor below
125 var $config_mysql_query = null;
126 var $config_mysql_hostname = null;
127 var $config_mysql_username = null;
128 var $config_mysql_password = null;
129 var $config_mysql_database = null;
132 var $config_high_security_enabled = false;
133 var $config_high_security_password = null;
134 var $config_disable_debug = false;
135 var $config_allow_src_above_docroot = true;
136 var $config_allow_src_above_phpthumb = true;
137 var $config_allow_parameter_file = false;
138 var $config_allow_parameter_goto = false;
141 var $config_disable_pathinfo_parsing = false;
142 var $config_disable_imagecopyresampled = false;
143 var $config_disable_onlycreateable_passthru = false;
145 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';
147 // END CONFIGURATION OPTIONS
150 // public: error messages (read-only)
151 var $debugmessages = array();
152 var $debugtiming = array();
153 var $fatalerror = null;
156 // private: (should not be modified directly)
157 var $thumbnailQuality = 75;
158 var $thumbnailFormat = null;
160 var $sourceFilename = null;
161 var $rawImageData = null;
162 var $IMresizedData = null;
163 var $outputImageData = null;
165 var $useRawIMoutput = false;
167 var $gdimg_output = null;
168 var $gdimg_source = null;
170 var $getimagesizeinfo = null;
172 var $source_width = null;
173 var $source_height = null;
175 var $thumbnailCropX = null;
176 var $thumbnailCropY = null;
177 var $thumbnailCropW = null;
178 var $thumbnailCropH = null;
180 var $exif_thumbnail_width = null;
181 var $exif_thumbnail_height = null;
182 var $exif_thumbnail_type = null;
183 var $exif_thumbnail_data = null;
184 var $exif_raw_data = null;
186 var $thumbnail_width = null;
187 var $thumbnail_height = null;
188 var $thumbnail_image_width = null;
189 var $thumbnail_image_height = null;
191 var $cache_filename = null;
193 var $AlphaCapableFormats = array('png', 'ico', 'gif');
194 var $is_alpha = false;
196 var $iswindows = null;
198 var $phpthumb_version = '1.7.2-200606220757';
200 //////////////////////////////////////////////////////////////////////
202 // public: constructor
203 function phpThumb() {
204 $this->DebugTimingMessage('phpThumb() constructor', __FILE__, __LINE__);
205 $this->DebugMessage('phpThumb() v'.$this->phpthumb_version, __FILE__, __LINE__);
206 $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
207 $this->iswindows = (bool) (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN');
208 $this->config_temp_directory = realpath($this->config_temp_directory ? $this->config_temp_directory : (getenv('TMPDIR') ? getenv('TMPDIR') : getenv('TMP')));
209 $this->config_document_root = (@$_SERVER['DOCUMENT_ROOT'] ? $_SERVER['DOCUMENT_ROOT'] : $this->config_document_root);
210 $this->config_cache_prefix = 'phpThumb_cache_'.@$_SERVER['SERVER_NAME'];
212 $php_sapi_name = strtolower(function_exists('php_sapi_name') ? php_sapi_name() : '');
213 if ($php_sapi_name == 'cli') {
214 $this->config_allow_src_above_docroot = true;
219 function setSourceFilename($sourceFilename) {
220 $this->rawImageData = null;
221 $this->sourceFilename = $sourceFilename;
222 $this->src = $sourceFilename;
223 $this->DebugMessage('setSourceFilename('.$sourceFilename.') set $this->sourceFilename to "'.$this->sourceFilename.'"', __FILE__, __LINE__);
228 function setSourceData($rawImageData, $sourceFilename='') {
229 $this->sourceFilename = null;
230 $this->rawImageData = $rawImageData;
231 $this->DebugMessage('setSourceData() setting $this->rawImageData ('.strlen($this->rawImageData).' bytes)', __FILE__, __LINE__);
232 if ($this->config_cache_source_enabled) {
233 $sourceFilename = ($sourceFilename ? $sourceFilename : md5($rawImageData));
234 if (!is_dir($this->config_cache_source_directory)) {
235 $this->ErrorImage('$this->config_cache_source_directory ('.$this->config_cache_source_directory.') is not a directory');
236 } elseif (!@is_writable($this->config_cache_source_directory)) {
237 $this->ErrorImage('$this->config_cache_source_directory ('.$this->config_cache_source_directory.') is not writable');
239 $this->DebugMessage('setSourceData() attempting to save source image to "'.$this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename).'"', __FILE__, __LINE__);
240 if ($fp = @fopen($this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename), 'wb')) {
241 fwrite($fp, $rawImageData);
243 } elseif (!$this->phpThumbDebug) {
244 $this->ErrorImage('setSourceData() failed to write to source cache ('.$this->config_cache_source_directory.DIRECTORY_SEPARATOR.urlencode($sourceFilename).')');
251 function setSourceImageResource($gdimg) {
252 $this->gdimg_source = $gdimg;
257 function setParameter($param, $value) {
258 if ($param == 'src') {
259 $this->setSourceFilename($this->ResolveFilenameToAbsolute($value));
260 } elseif (@is_array($this->$param)) {
261 if (is_array($value)) {
262 foreach ($value as $arraykey => $arrayvalue) {
263 array_push($this->$param, $arrayvalue);
266 array_push($this->$param, $value);
269 $this->$param = $value;
275 function getParameter($param) {
276 //if (property_exists('phpThumb', $param)) {
277 return $this->$param;
279 //$this->DebugMessage('setParameter() attempting to get non-existant parameter "'.$param.'"', __FILE__, __LINE__);
285 function GenerateThumbnail() {
287 $this->setOutputFormat();
288 $this->ResolveSource();
289 $this->SetCacheFilename();
290 $this->ExtractEXIFgetImageSize();
291 if ($this->useRawIMoutput) {
292 $this->DebugMessage('Skipping rest of GenerateThumbnail() because $this->useRawIMoutput', __FILE__, __LINE__);
295 if (!$this->SourceImageToGD()) {
296 $this->DebugMessage('SourceImageToGD() failed', __FILE__, __LINE__);
300 $this->CreateGDoutput();
302 switch ($this->far) {
306 $destination_offset_x = 0;
307 $destination_offset_y = round(($this->thumbnail_height - $this->thumbnail_image_height) / 2);
312 $destination_offset_x = round($this->thumbnail_width - $this->thumbnail_image_width);
313 $destination_offset_y = round(($this->thumbnail_height - $this->thumbnail_image_height) / 2);
318 $destination_offset_x = round(($this->thumbnail_width - $this->thumbnail_image_width) / 2);
319 $destination_offset_y = 0;
324 $destination_offset_x = round(($this->thumbnail_width - $this->thumbnail_image_width) / 2);
325 $destination_offset_y = round($this->thumbnail_height - $this->thumbnail_image_height);
329 $destination_offset_x = round(($this->thumbnail_width - $this->thumbnail_image_width) / 2);
330 $destination_offset_y = round(($this->thumbnail_height - $this->thumbnail_image_height) / 2);
333 // // copy/resize image to appropriate dimensions
334 // $borderThickness = 0;
335 // if (!empty($this->fltr)) {
336 // foreach ($this->fltr as $key => $value) {
337 // if (ereg('^bord\|([0-9]+)', $value, $matches)) {
338 // $borderThickness = $matches[1];
343 // if ($borderThickness > 0) {
344 // //$this->DebugMessage('Skipping ImageResizeFunction() because BorderThickness="'.$borderThickness.'"', __FILE__, __LINE__);
345 // $this->thumbnail_image_height /= 2;
347 $this->ImageResizeFunction(
350 $destination_offset_x,
351 $destination_offset_y,
352 $this->thumbnailCropX,
353 $this->thumbnailCropY,
354 $this->thumbnail_image_width,
355 $this->thumbnail_image_height,
356 $this->thumbnailCropW,
357 $this->thumbnailCropH
360 $this->DebugMessage('memory_get_usage() after copy-resize = '.(function_exists('memory_get_usage') ? @memory_get_usage() : 'n/a'), __FILE__, __LINE__);
361 ImageDestroy($this->gdimg_source);
362 $this->DebugMessage('memory_get_usage() after ImageDestroy = '.(function_exists('memory_get_usage') ? @memory_get_usage() : 'n/a'), __FILE__, __LINE__);
364 $this->AntiOffsiteLinking();
365 $this->ApplyFilters();
366 $this->AlphaChannelFlatten();
367 $this->MaxFileSize();
369 $this->DebugMessage('GenerateThumbnail() completed successfully', __FILE__, __LINE__);
375 function RenderOutput() {
376 if (!$this->useRawIMoutput && !is_resource($this->gdimg_output)) {
377 $this->DebugMessage('RenderOutput() failed because !is_resource($this->gdimg_output)', __FILE__, __LINE__);
380 if (!$this->thumbnailFormat) {
381 $this->DebugMessage('RenderOutput() failed because $this->thumbnailFormat is empty', __FILE__, __LINE__);
384 if ($this->useRawIMoutput) {
385 $this->DebugMessage('RenderOutput copying $this->IMresizedData ('.strlen($this->IMresizedData).' bytes) to $this->outputImage', __FILE__, __LINE__);
386 $this->outputImageData = $this->IMresizedData;
390 $this->DebugMessage('RenderOutput() attempting Image'.strtoupper(@$this->thumbnailFormat).'($this->gdimg_output)', __FILE__, __LINE__);
392 switch ($this->thumbnailFormat) {
394 ImageJPEG($this->gdimg_output, null, $this->thumbnailQuality);
395 $this->outputImageData = ob_get_contents();
399 ImagePNG($this->gdimg_output);
400 $this->outputImageData = ob_get_contents();
404 ImageGIF($this->gdimg_output);
405 $this->outputImageData = ob_get_contents();
409 $ImageOutFunction = '"builtin BMP output"';
410 if (!@include_once(dirname(__FILE__).'/phpthumb.bmp.php')) {
411 $this->DebugMessage('Error including "'.dirname(__FILE__).'/phpthumb.bmp.php" which is required for BMP format output', __FILE__, __LINE__);
415 $phpthumb_bmp = new phpthumb_bmp();
416 $this->outputImageData = $phpthumb_bmp->GD2BMPstring($this->gdimg_output);
417 unset($phpthumb_bmp);
421 $ImageOutFunction = '"builtin ICO output"';
422 if (!@include_once(dirname(__FILE__).'/phpthumb.ico.php')) {
423 $this->DebugMessage('Error including "'.dirname(__FILE__).'/phpthumb.ico.php" which is required for ICO format output', __FILE__, __LINE__);
427 $phpthumb_ico = new phpthumb_ico();
428 $arrayOfOutputImages = array($this->gdimg_output);
429 $this->outputImageData = $phpthumb_ico->GD2ICOstring($arrayOfOutputImages);
430 unset($phpthumb_ico);
434 $this->DebugMessage('RenderToFile failed because $this->thumbnailFormat "'.$this->thumbnailFormat.'" is not valid', __FILE__, __LINE__);
439 if (!$this->outputImageData) {
440 $this->DebugMessage('RenderOutput() for "'.$this->thumbnailFormat.'" failed', __FILE__, __LINE__);
444 $this->DebugMessage('RenderOutput() completing with $this->outputImageData = '.strlen($this->outputImageData).' bytes', __FILE__, __LINE__);
448 function RenderToFile($filename) {
449 if (eregi('^(f|ht)tps?\://', $filename)) {
450 $this->DebugMessage('RenderToFile() failed because $filename ('.$filename.') is a URL', __FILE__, __LINE__);
453 // render thumbnail to this file only, do not cache, do not output to browser
454 //$renderfilename = $this->ResolveFilenameToAbsolute(dirname($filename)).DIRECTORY_SEPARATOR.basename($filename);
455 $renderfilename = $filename;
456 if (($filename{0} != '/') && ($filename{0} != '\\') && ($filename{1} != ':')) {
457 $renderfilename = $this->ResolveFilenameToAbsolute($renderfilename);
459 if (!@is_writable(dirname($renderfilename))) {
460 $this->DebugMessage('RenderToFile() failed because "'.dirname($renderfilename).'/" is not writable', __FILE__, __LINE__);
463 if (@is_file($renderfilename) && !@is_writable($renderfilename)) {
464 $this->DebugMessage('RenderToFile() failed because "'.$renderfilename.'" is not writable', __FILE__, __LINE__);
468 if ($this->RenderOutput()) {
469 if (file_put_contents($renderfilename, $this->outputImageData)) {
470 $this->DebugMessage('RenderToFile('.$renderfilename.') succeeded', __FILE__, __LINE__);
473 if (!@file_exists($renderfilename)) {
474 $this->DebugMessage('RenderOutput ['.$this->thumbnailFormat.'('.$renderfilename.')] did not appear to fail, but the output image does not exist either...', __FILE__, __LINE__);
477 $this->DebugMessage('RenderOutput ['.$this->thumbnailFormat.'('.$renderfilename.')] failed', __FILE__, __LINE__);
484 function OutputThumbnail() {
485 if (!$this->useRawIMoutput && !is_resource($this->gdimg_output)) {
486 $this->DebugMessage('OutputThumbnail() failed because !is_resource($this->gdimg_output)', __FILE__, __LINE__);
489 if (headers_sent()) {
490 return $this->ErrorImage('OutputThumbnail() failed - headers already sent');
495 $downloadfilename = ereg_replace('[/\\:\*\?"<>|]', '_', $this->down);
496 if (phpthumb_functions::version_compare_replacement(phpversion(), '4.1.0', '>=')) {
497 $downloadfilename = trim($downloadfilename, '.');
499 if ($downloadfilename != $this->down) {
500 $this->DebugMessage('renaming output file for "down" from "'.$this->down.'" to "'.$downloadfilename.'"', __FILE__, __LINE__);
502 if ($downloadfilename) {
503 header('Content-Disposition: attachment; filename="'.$downloadfilename.'"');
505 $this->DebugMessage('failed to send Content-Disposition header because $downloadfilename is empty', __FILE__, __LINE__);
509 if ($this->useRawIMoutput) {
511 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
512 echo $this->IMresizedData;
516 $this->DebugMessage('ImageInterlace($this->gdimg_output, '.intval($this->config_output_interlace).')', __FILE__, __LINE__);
517 ImageInterlace($this->gdimg_output, intval($this->config_output_interlace));
518 switch ($this->thumbnailFormat) {
520 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
521 $ImageOutFunction = 'image'.$this->thumbnailFormat;
522 @$ImageOutFunction($this->gdimg_output, '', $this->thumbnailQuality);
527 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
528 $ImageOutFunction = 'image'.$this->thumbnailFormat;
529 @$ImageOutFunction($this->gdimg_output);
533 if (!@include_once(dirname(__FILE__).'/phpthumb.bmp.php')) {
534 $this->DebugMessage('Error including "'.dirname(__FILE__).'/phpthumb.bmp.php" which is required for BMP format output', __FILE__, __LINE__);
537 $phpthumb_bmp = new phpthumb_bmp();
538 if (is_object($phpthumb_bmp)) {
539 $bmp_data = $phpthumb_bmp->GD2BMPstring($this->gdimg_output);
540 unset($phpthumb_bmp);
542 $this->DebugMessage('$phpthumb_bmp->GD2BMPstring() failed', __FILE__, __LINE__);
545 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
548 $this->DebugMessage('new phpthumb_bmp() failed', __FILE__, __LINE__);
554 if (!@include_once(dirname(__FILE__).'/phpthumb.ico.php')) {
555 $this->DebugMessage('Error including "'.dirname(__FILE__).'/phpthumb.ico.php" which is required for ICO format output', __FILE__, __LINE__);
558 $phpthumb_ico = new phpthumb_ico();
559 if (is_object($phpthumb_ico)) {
560 $arrayOfOutputImages = array($this->gdimg_output);
561 $ico_data = $phpthumb_ico->GD2ICOstring($arrayOfOutputImages);
562 unset($phpthumb_ico);
564 $this->DebugMessage('$phpthumb_ico->GD2ICOstring() failed', __FILE__, __LINE__);
567 header('Content-Type: '.phpthumb_functions::ImageTypeToMIMEtype($this->thumbnailFormat));
570 $this->DebugMessage('new phpthumb_ico() failed', __FILE__, __LINE__);
576 $this->DebugMessage('OutputThumbnail failed because $this->thumbnailFormat "'.$this->thumbnailFormat.'" is not valid', __FILE__, __LINE__);
587 function CleanUpCacheDirectory() {
588 if (($this->config_cache_maxage > 0) || ($this->config_cache_maxsize > 0) || ($this->config_cache_maxfiles > 0)) {
589 $CacheDirOldFilesAge = array();
590 $CacheDirOldFilesSize = array();
591 if ($dirhandle = opendir($this->config_cache_directory)) {
592 while ($oldcachefile = readdir($dirhandle)) {
593 $fullfilename = $this->config_cache_directory.DIRECTORY_SEPARATOR.$oldcachefile;
594 if (eregi('^phpThumb_cache_', $oldcachefile) && file_exists($fullfilename)) {
595 $CacheDirOldFilesAge[$oldcachefile] = @fileatime($fullfilename);
596 if ($CacheDirOldFilesAge[$oldcachefile] == 0) {
597 $CacheDirOldFilesAge[$oldcachefile] = @filemtime($fullfilename);
600 $CacheDirOldFilesSize[$oldcachefile] = @filesize($fullfilename);
604 asort($CacheDirOldFilesAge);
606 if ($this->config_cache_maxfiles > 0) {
607 $TotalCachedFiles = count($CacheDirOldFilesAge);
608 $DeletedKeys = array();
609 foreach ($CacheDirOldFilesAge as $oldcachefile => $filedate) {
610 if ($TotalCachedFiles > $this->config_cache_maxfiles) {
612 if (@unlink($fullfilename)) {
613 $DeletedKeys[] = $oldcachefile;
616 // there are few enough files to keep the rest
620 foreach ($DeletedKeys as $dummy => $oldcachefile) {
621 unset($CacheDirOldFilesAge[$oldcachefile]);
622 unset($CacheDirOldFilesSize[$oldcachefile]);
626 if ($this->config_cache_maxage > 0) {
627 $mindate = time() - $this->config_cache_maxage;
628 $DeletedKeys = array();
629 foreach ($CacheDirOldFilesAge as $oldcachefile => $filedate) {
631 if ($filedate < $mindate) {
632 if (@unlink($fullfilename)) {
633 $DeletedKeys[] = $oldcachefile;
636 // the rest of the files are new enough to keep
641 foreach ($DeletedKeys as $dummy => $oldcachefile) {
642 unset($CacheDirOldFilesAge[$oldcachefile]);
643 unset($CacheDirOldFilesSize[$oldcachefile]);
647 if ($this->config_cache_maxsize > 0) {
648 $TotalCachedFileSize = array_sum($CacheDirOldFilesSize);
649 $DeletedKeys = array();
650 foreach ($CacheDirOldFilesAge as $oldcachefile => $filedate) {
651 if ($TotalCachedFileSize > $this->config_cache_maxsize) {
652 $TotalCachedFileSize -= $CacheDirOldFilesSize[$oldcachefile];
653 if (@unlink($fullfilename)) {
654 $DeletedKeys[] = $oldcachefile;
657 // the total filesizes are small enough to keep the rest of the files
661 foreach ($DeletedKeys as $dummy => $oldcachefile) {
662 unset($CacheDirOldFilesAge[$oldcachefile]);
663 unset($CacheDirOldFilesSize[$oldcachefile]);
671 //////////////////////////////////////////////////////////////////////
673 function ResolveSource() {
674 if (is_resource($this->gdimg_source)) {
675 $this->DebugMessage('ResolveSource() exiting because is_resource($this->gdimg_source)', __FILE__, __LINE__);
678 if ($this->rawImageData) {
679 $this->sourceFilename = null;
680 $this->DebugMessage('ResolveSource() exiting because $this->rawImageData is set', __FILE__, __LINE__);
683 if ($this->sourceFilename) {
684 $this->sourceFilename = $this->ResolveFilenameToAbsolute($this->sourceFilename);
685 $this->DebugMessage('$this->sourceFilename set to "'.$this->sourceFilename.'"', __FILE__, __LINE__);
687 $this->sourceFilename = $this->ResolveFilenameToAbsolute($this->src);
688 $this->DebugMessage('$this->sourceFilename set to "'.$this->sourceFilename.'" from $this->src ('.$this->src.')', __FILE__, __LINE__);
690 if ($this->iswindows && ((substr($this->sourceFilename, 0, 2) == '//') || (substr($this->sourceFilename, 0, 2) == '\\\\'))) {
691 // Windows \\share\filename.ext
692 } elseif (eregi('^(f|ht)tps?\://', $this->sourceFilename)) {
694 if ($this->config_http_user_agent) {
695 ini_set('user_agent', $this->config_http_user_agent);
697 } elseif (!@file_exists($this->sourceFilename)) {
698 return $this->ErrorImage('"'.$this->sourceFilename.'" does not exist');
699 } elseif (!@is_file($this->sourceFilename)) {
700 return $this->ErrorImage('"'.$this->sourceFilename.'" is not a file');
705 function setOutputFormat() {
706 static $alreadyCalled = false;
707 if ($this->thumbnailFormat && $alreadyCalled) {
710 $alreadyCalled = true;
712 $AvailableImageOutputFormats = array();
713 $AvailableImageOutputFormats[] = 'text';
714 if (@is_readable(dirname(__FILE__).'/phpthumb.ico.php')) {
715 $AvailableImageOutputFormats[] = 'ico';
717 if (@is_readable(dirname(__FILE__).'/phpthumb.bmp.php')) {
718 $AvailableImageOutputFormats[] = 'bmp';
721 $this->thumbnailFormat = 'ico';
723 // Set default output format based on what image types are available
724 if (function_exists('ImageTypes')) {
725 $imagetypes = ImageTypes();
726 if ($imagetypes & IMG_WBMP) {
727 $this->thumbnailFormat = 'wbmp';
728 $AvailableImageOutputFormats[] = 'wbmp';
730 if ($imagetypes & IMG_GIF) {
731 $this->thumbnailFormat = 'gif';
732 $AvailableImageOutputFormats[] = 'gif';
734 if ($imagetypes & IMG_PNG) {
735 $this->thumbnailFormat = 'png';
736 $AvailableImageOutputFormats[] = 'png';
738 if ($imagetypes & IMG_JPG) {
739 $this->thumbnailFormat = 'jpeg';
740 $AvailableImageOutputFormats[] = 'jpeg';
743 //return $this->ErrorImage('ImageTypes() does not exist - GD support might not be enabled?');
744 $this->DebugMessage('ImageTypes() does not exist - GD support might not be enabled?', __FILE__, __LINE__);
746 if ($this->ImageMagickVersion()) {
747 $IMformats = array('jpeg', 'png', 'gif', 'bmp', 'ico');
748 $this->DebugMessage('Addding ImageMagick formats to $AvailableImageOutputFormats ('.implode(';', $AvailableImageOutputFormats).')', __FILE__, __LINE__);
749 foreach ($IMformats as $key => $format) {
750 $AvailableImageOutputFormats[] = $format;
753 $AvailableImageOutputFormats = array_unique($AvailableImageOutputFormats);
754 $this->DebugMessage('$AvailableImageOutputFormats = array('.implode(';', $AvailableImageOutputFormats).')', __FILE__, __LINE__);
756 if (strtolower($this->config_output_format) == 'jpg') {
757 $this->config_output_format = 'jpeg';
759 if (strtolower($this->f) == 'jpg') {
762 if (phpthumb_functions::CaseInsensitiveInArray($this->config_output_format, $AvailableImageOutputFormats)) {
763 // set output format to config default if that format is available
764 $this->DebugMessage('$this->thumbnailFormat set to $this->config_output_format "'.strtolower($this->config_output_format).'"', __FILE__, __LINE__);
765 $this->thumbnailFormat = strtolower($this->config_output_format);
766 } elseif ($this->config_output_format) {
767 $this->DebugMessage('$this->thumbnailFormat staying as "'.$this->thumbnailFormat.'" because $this->config_output_format ('.strtolower($this->config_output_format).') is not in $AvailableImageOutputFormats', __FILE__, __LINE__);
769 if ($this->f && (phpthumb_functions::CaseInsensitiveInArray($this->f, $AvailableImageOutputFormats))) {
770 // override output format if $this->f is set and that format is available
771 $this->DebugMessage('$this->thumbnailFormat set to $this->f "'.strtolower($this->f).'"', __FILE__, __LINE__);
772 $this->thumbnailFormat = strtolower($this->f);
773 } elseif ($this->f) {
774 $this->DebugMessage('$this->thumbnailFormat staying as "'.$this->thumbnailFormat.'" because $this->f ('.strtolower($this->f).') is not in $AvailableImageOutputFormats', __FILE__, __LINE__);
777 // for JPEG images, quality 1 (worst) to 99 (best)
778 // quality < 25 is nasty, with not much size savings - not recommended
779 // problems with 100 - invalid JPEG?
780 $this->thumbnailQuality = max(1, min(99, ($this->q ? $this->q : 75)));
781 $this->DebugMessage('$this->thumbnailQuality set to "'.$this->thumbnailQuality.'"', __FILE__, __LINE__);
786 function setCacheDirectory() {
787 // resolve cache directory to absolute pathname
788 $this->DebugMessage('setCacheDirectory() starting with config_cache_directory = "'.$this->config_cache_directory.'"', __FILE__, __LINE__);
789 if (substr($this->config_cache_directory, 0, 1) == '.') {
790 if (eregi('^(f|ht)tps?\://', $this->src)) {
791 if (!$this->config_cache_disable_warning) {
792 $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');
794 } elseif ($this->src) {
795 // resolve relative cache directory to source image
796 $this->config_cache_directory = dirname($this->ResolveFilenameToAbsolute($this->src)).DIRECTORY_SEPARATOR.$this->config_cache_directory;
798 // $this->new is probably set
801 if (substr($this->config_cache_directory, -1) == '/') {
802 $this->config_cache_directory = substr($this->config_cache_directory, 0, -1);
804 if ($this->iswindows) {
805 $this->config_cache_directory = str_replace('/', DIRECTORY_SEPARATOR, $this->config_cache_directory);
807 if ($this->config_cache_directory) {
808 $real_cache_path = realpath($this->config_cache_directory);
809 if (!$real_cache_path) {
810 $this->DebugMessage('realpath($this->config_cache_directory) failed for "'.$this->config_cache_directory.'"', __FILE__, __LINE__);
811 if (!is_dir($this->config_cache_directory)) {
812 $this->DebugMessage('!is_dir('.$this->config_cache_directory.')', __FILE__, __LINE__);
815 if ($real_cache_path) {
816 $this->DebugMessage('setting config_cache_directory to realpath('.$this->config_cache_directory.') = "'.$real_cache_path.'"', __FILE__, __LINE__);
817 $this->config_cache_directory = $real_cache_path;
820 if (!is_dir($this->config_cache_directory)) {
821 if (!$this->config_cache_disable_warning) {
822 $this->ErrorImage('$this->config_cache_directory ('.$this->config_cache_directory.') does not exist. Adjust "cache_directory" or "cache_disable_warning" in phpThumb.config.php');
824 $this->DebugMessage('$this->config_cache_directory ('.$this->config_cache_directory.') is not a directory', __FILE__, __LINE__);
825 $this->config_cache_directory = null;
826 } elseif (!@is_writable($this->config_cache_directory)) {
827 $this->DebugMessage('$this->config_cache_directory is not writable ('.$this->config_cache_directory.')', __FILE__, __LINE__);
833 function ResolveFilenameToAbsolute($filename) {
834 //if (eregi('^(f|ht)tps?\://', $filename)) {
835 if (eregi('^[a-z0-9]+\:/{1,2}', $filename)) {
836 // eg: http://host/path/file.jpg (HTTP URL)
837 // eg: ftp://host/path/file.jpg (FTP URL)
838 // eg: data1:/path/file.jpg (Netware path)
840 //$AbsoluteFilename = $filename;
843 } elseif ($this->iswindows && ($filename{1} == ':')) {
845 // absolute pathname (Windows)
846 $AbsoluteFilename = $filename;
848 } elseif ($this->iswindows && ((substr($filename, 0, 2) == '//') || (substr($filename, 0, 2) == '\\\\'))) {
850 // absolute pathname (Windows)
851 $AbsoluteFilename = $filename;
853 } elseif ($filename{0} == '/') {
855 if (@is_readable($filename) && !@is_readable($this->config_document_root.$filename)) {
857 // absolute filename (*nix)
858 $AbsoluteFilename = $filename;
860 } elseif ($filename{1} == '~') {
863 if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray($filename)) {
864 $AbsoluteFilename = $ApacheLookupURIarray['filename'];
866 $AbsoluteFilename = realpath($filename);
867 if (@is_readable($AbsoluteFilename)) {
868 $this->DebugMessage('phpthumb_functions::ApacheLookupURIarray() failed for "'.$filename.'", but the correct filename ('.$AbsoluteFilename.') seems to have been resolved with realpath($filename)', __FILE__, __LINE__);
870 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")');
876 // relative filename (any OS)
877 if (ereg('^'.preg_quote($this->config_document_root), $filename)) {
878 $AbsoluteFilename = $filename;
879 $this->DebugMessage('ResolveFilenameToAbsolute() NOT prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = "'.$AbsoluteFilename.'")', __FILE__, __LINE__);
881 $AbsoluteFilename = $this->config_document_root.$filename;
882 $this->DebugMessage('ResolveFilenameToAbsolute() prepending $this->config_document_root ('.$this->config_document_root.') to $filename ('.$filename.') resulting in ($AbsoluteFilename = "'.$AbsoluteFilename.'")', __FILE__, __LINE__);
889 // relative to current directory (any OS)
890 $AbsoluteFilename = $this->config_document_root.dirname(@$_SERVER['PHP_SELF']).DIRECTORY_SEPARATOR.$filename;
891 //if (!@file_exists($AbsoluteFilename) && @file_exists(realpath($this->DotPadRelativeDirectoryPath($filename)))) {
892 // $AbsoluteFilename = realpath($this->DotPadRelativeDirectoryPath($filename));
895 if (substr(dirname(@$_SERVER['PHP_SELF']), 0, 2) == '/~') {
896 if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray(dirname(@$_SERVER['PHP_SELF']))) {
897 $AbsoluteFilename = $ApacheLookupURIarray['filename'].DIRECTORY_SEPARATOR.$filename;
899 $AbsoluteFilename = realpath('.').DIRECTORY_SEPARATOR.$filename;
900 if (@is_readable($AbsoluteFilename)) {
901 $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__);
903 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');
909 if (is_link($AbsoluteFilename)) {
910 $this->DebugMessage('is_link()==true, changing "'.$AbsoluteFilename.'" to "'.readlink($AbsoluteFilename).'"', __FILE__, __LINE__);
911 $AbsoluteFilename = readlink($AbsoluteFilename);
913 if (realpath($AbsoluteFilename)) {
914 $AbsoluteFilename = realpath($AbsoluteFilename);
916 if ($this->iswindows) {
917 $AbsoluteFilename = eregi_replace('^'.preg_quote(realpath($this->config_document_root)), realpath($this->config_document_root), $AbsoluteFilename);
918 $AbsoluteFilename = str_replace(DIRECTORY_SEPARATOR, '/', $AbsoluteFilename);
920 if (!$this->config_allow_src_above_docroot && !ereg('^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', realpath($this->config_document_root))), $AbsoluteFilename)) {
921 $this->DebugMessage('!$this->config_allow_src_above_docroot therefore setting "'.$AbsoluteFilename.'" (outside "'.realpath($this->config_document_root).'") to null', __FILE__, __LINE__);
924 if (!$this->config_allow_src_above_phpthumb && !ereg('^'.preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__))), $AbsoluteFilename)) {
925 $this->DebugMessage('!$this->config_allow_src_above_phpthumb therefore setting "'.$AbsoluteFilename.'" (outside "'.dirname(__FILE__).'") to null', __FILE__, __LINE__);
928 return $AbsoluteFilename;
931 function ImageMagickWhichConvert() {
932 static $WhichConvert = null;
933 if (is_null($WhichConvert)) {
934 if ($this->iswindows) {
935 $WhichConvert = false;
937 $WhichConvert = trim(phpthumb_functions::SafeExec('which convert'));
940 return $WhichConvert;
943 function ImageMagickCommandlineBase() {
944 static $commandline = null;
945 if (is_null($commandline)) {
946 $commandline = (!is_null($this->config_imagemagick_path) ? $this->config_imagemagick_path : '');
948 if ($this->config_imagemagick_path && ($this->config_imagemagick_path != realpath($this->config_imagemagick_path))) {
949 if (@is_executable(realpath($this->config_imagemagick_path))) {
950 $this->DebugMessage('Changing $this->config_imagemagick_path ('.$this->config_imagemagick_path.') to realpath($this->config_imagemagick_path) ('.realpath($this->config_imagemagick_path).')', __FILE__, __LINE__);
951 $this->config_imagemagick_path = realpath($this->config_imagemagick_path);
953 $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__);
956 $this->DebugMessage(' file_exists('.$this->config_imagemagick_path.') = '.intval( @file_exists($this->config_imagemagick_path)), __FILE__, __LINE__);
957 $this->DebugMessage('is_executable('.$this->config_imagemagick_path.') = '.intval(@is_executable($this->config_imagemagick_path)), __FILE__, __LINE__);
958 if (@file_exists($this->config_imagemagick_path)) {
959 $this->DebugMessage('using ImageMagick path from $this->config_imagemagick_path ('.$this->config_imagemagick_path.')', __FILE__, __LINE__);
960 if ($this->iswindows) {
961 $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);
963 $commandline = '"'.$this->config_imagemagick_path.'"';
968 $which_convert = $this->ImageMagickWhichConvert();
969 $IMversion = $this->ImageMagickVersion();
971 if ($which_convert && ($which_convert{0} == '/') && @file_exists($which_convert)) {
973 // `which convert` *should* return the path if "convert" exist, or nothing if it doesn't
974 // other things *may* get returned, like "sh: convert: not found" or "no convert in /usr/local/bin /usr/sbin /usr/bin /usr/ccs/bin"
975 // so only do this if the value returned exists as a file
976 $this->DebugMessage('using ImageMagick path from `which convert` ('.$which_convert.')', __FILE__, __LINE__);
977 $commandline = 'convert';
979 } elseif ($IMversion) {
981 $this->DebugMessage('setting ImageMagick path to $this->config_imagemagick_path ('.$this->config_imagemagick_path.') ['.$IMversion.']', __FILE__, __LINE__);
982 $commandline = $this->config_imagemagick_path;
986 $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__);
994 function ImageMagickVersion($returnRAW=false) {
995 static $versionstring = null;
996 if (is_null($versionstring)) {
997 $commandline = $this->ImageMagickCommandlineBase();
998 $commandline = (!is_null($commandline) ? $commandline : '');
1000 $versionstring = array(0=>'', 1=>'');
1002 $commandline .= ' -version';
1003 $this->DebugMessage('ImageMagick version checked with "'.$commandline.'"', __FILE__, __LINE__);
1004 $versionstring[1] = trim(phpthumb_functions::SafeExec($commandline));
1005 if (eregi('^Version: (.*) (http|file)\:', $versionstring[1], $matches)) {
1006 $versionstring[0] = $matches[1];
1008 $versionstring[0] = false;
1009 $this->DebugMessage('ImageMagick did not return recognized version string ('.$versionstring[1].')', __FILE__, __LINE__);
1013 return @$versionstring[intval($returnRAW)];
1016 function ImageMagickSwitchAvailable($switchname) {
1017 static $IMoptions = null;
1018 if (is_null($IMoptions)) {
1019 $IMoptions = array();
1020 $commandline = $this->ImageMagickCommandlineBase();
1021 if (!is_null($commandline)) {
1022 $commandline .= ' -help';
1023 $IMhelp_lines = explode("\n", phpthumb_functions::SafeExec($commandline));
1024 foreach ($IMhelp_lines as $line) {
1025 if (ereg('^[\+\-]([a-z\-]+) ', trim($line), $matches)) {
1026 $IMoptions[$matches[1]] = true;
1031 if (is_array($switchname)) {
1033 foreach ($switchname as $key => $value) {
1034 if (!isset($IMoptions[$value])) {
1039 $this->DebugMessage('ImageMagickSwitchAvailable('.implode(';', $switchname).') = '.intval($allOK).'', __FILE__, __LINE__);
1041 $allOK = isset($IMoptions[$switchname]);
1042 $this->DebugMessage('ImageMagickSwitchAvailable('.$switchname.') = '.intval($allOK).'', __FILE__, __LINE__);
1047 function ImageMagickThumbnailToGD() {
1048 // http://www.imagemagick.org/script/command-line-options.php
1050 $this->useRawIMoutput = true;
1051 if (phpthumb_functions::gd_version()) {
1052 //$UnAllowedParameters = array('sx', 'sy', 'sw', 'sh', 'xto', 'ra', 'ar', 'bg', 'bc', 'fltr');
1053 $UnAllowedParameters = array('xto', 'ra', 'ar', 'bg', 'bc', 'fltr');
1054 foreach ($UnAllowedParameters as $dummy => $parameter) {
1055 if ($this->$parameter) {
1056 $this->DebugMessage('$this->useRawIMoutput=false because "'.$parameter.'" is set', __FILE__, __LINE__);
1057 $this->useRawIMoutput = false;
1062 $outputFormat = $this->thumbnailFormat;
1063 if (phpthumb_functions::gd_version()) {
1064 if ($this->useRawIMoutput) {
1065 switch ($this->thumbnailFormat) {
1067 $ImageCreateFunction = 'ImageCreateFromGIF';
1068 $this->is_alpha = true;
1071 $ImageCreateFunction = 'ImageCreateFromPNG';
1072 $this->is_alpha = true;
1076 $ImageCreateFunction = 'ImageCreateFromJPEG';
1079 $outputFormat = 'png';
1080 $ImageCreateFunction = 'ImageCreateFromPNG';
1081 $this->is_alpha = true;
1082 $this->useRawIMoutput = false;
1085 if (!function_exists(@$ImageCreateFunction)) {
1086 // ImageMagickThumbnailToGD() depends on ImageCreateFromPNG/ImageCreateFromGIF
1087 //$this->DebugMessage('ImageMagickThumbnailToGD() aborting because '.@$ImageCreateFunction.'() is not available', __FILE__, __LINE__);
1088 $this->useRawIMoutput = true;
1092 $outputFormat = 'png';
1093 $ImageCreateFunction = 'ImageCreateFromPNG';
1094 $this->is_alpha = true;
1095 $this->useRawIMoutput = false;
1099 // http://freealter.org/doc_distrib/ImageMagick-5.1.1/www/convert.html
1100 if (!$this->sourceFilename) {
1101 $this->DebugMessage('ImageMagickThumbnailToGD() aborting because $this->sourceFilename is empty', __FILE__, __LINE__);
1102 $this->useRawIMoutput = false;
1105 if (ini_get('safe_mode')) {
1106 $this->DebugMessage('ImageMagickThumbnailToGD() aborting because safe_mode is enabled', __FILE__, __LINE__);
1107 $this->useRawIMoutput = false;
1111 $commandline = $this->ImageMagickCommandlineBase();
1113 if ($IMtempfilename = $this->phpThumb_tempnam()) {
1115 if (!eregi('('.implode('|', $this->AlphaCapableFormats).')', $outputFormat)) {
1116 // not a transparency-capable format
1117 $commandline .= ' -background "#'.($this->bg ? $this->bg : 'FFFFFF').'"';
1118 $commandline .= ' -flatten';
1120 $IMtempfilename = realpath($IMtempfilename);
1121 if ($getimagesize = @GetImageSize($this->sourceFilename)) {
1122 $this->DebugMessage('GetImageSize('.$this->sourceFilename.') returned [w='.$getimagesize[0].';h='.$getimagesize[1].';f='.$getimagesize[2].']', __FILE__, __LINE__);
1123 $this->source_width = $getimagesize[0];
1124 $this->source_height = $getimagesize[1];
1125 $this->DebugMessage('source dimensions set to '.$this->source_width.'x'.$this->source_height, __FILE__, __LINE__);
1126 $this->SetOrientationDependantWidthHeight();
1128 $commandline .= ' -coalesce'; // may be needed for animated GIFs
1129 if ($this->source_width || $this->source_height) {
1132 $borderThickness = 0;
1133 if (!empty($this->fltr)) {
1134 foreach ($this->fltr as $key => $value) {
1135 if (ereg('^bord\|([0-9]+)', $value, $matches)) {
1136 $borderThickness = $matches[1];
1141 $wAll = intval(max($this->w, $this->wp, $this->wl, $this->ws)) - (2 * $borderThickness);
1142 $hAll = intval(max($this->h, $this->hp, $this->hl, $this->hs)) - (2 * $borderThickness);
1143 $imAR = $this->source_width / $this->source_height;
1144 //$zcAR = (($wAll && $hAll) ? $wAll / $hAll : $imAR);
1145 $zcAR = (($wAll && $hAll) ? $wAll / $hAll : 1);
1150 //if (($wAll > $borderThickness) && ($wAll > $borderThickness)) {
1151 // $zcAR = ($wAll - (2 * $borderThickness)) / ($hAll - (2 * $borderThickness));
1153 //echo ($wAll - (2 * $borderThickness))."\n";
1154 //echo ($hAll - (2 * $borderThickness))."\n";
1156 $side = phpthumb_functions::nonempty_min($this->source_width, $this->source_height, max($wAll, $hAll));
1157 $sideX = phpthumb_functions::nonempty_min($this->source_width, $wAll, round($hAll * $zcAR));
1158 $sideY = phpthumb_functions::nonempty_min( $this->source_height, $hAll, round($wAll / $zcAR));
1160 //if ($zcAR > 1) { // landscape
1161 $thumbnailH = round(max($sideY, ($sideY * $zcAR) / $imAR));
1166 //var_dump($thumbnailH);
1168 $commandline .= ' -thumbnail x'.$thumbnailH;
1169 //} else { // portrait or square
1170 // $thumbnailH = max($sideY, ($sideY * $zcAR) / $imAR);
1171 // $commandline .= ' -thumbnail '.$sideX.'x'.round($sideX / $zcAR);
1174 //var_dump($this->w);
1175 //var_dump($this->wp);
1176 //var_dump($this->wl);
1177 //var_dump($this->ws);
1183 //var_dump($thumbnailH);
1184 //print_r($getimagesize);
1187 $commandline .= ' -gravity center';
1189 if (($wAll > 0) && ($hAll > 0)) {
1190 $commandline .= ' -crop '.$wAll.'x'.$hAll.'+0+0';
1192 $commandline .= ' -crop '.$side.'x'.$side.'+0+0';
1194 $commandline .= ' +repage';
1196 } elseif ($this->sw || $this->sh || $this->sx || $this->sy) {
1198 $commandline .= ' -crop '.($this->sw ? $this->sw : $this->source_width).'x'.($this->sh ? $this->sh : $this->source_height).'+'.$this->sx.'+'.$this->sy;
1199 // this is broken for aoe=1, but unsure how to fix. Send advice to info@silisoftware.com
1200 if ($this->w || $this->h) {
1201 $commandline .= ' -repage';
1202 $commandline .= ' -thumbnail '.$this->w.'x'.$this->h;
1207 if ($this->iar && (intval($this->w) > 0) && (intval($this->h) > 0)) {
1208 $commandline .= ' -thumbnail '.$this->w.'x'.$this->h.'!';
1211 //print_r($getimagesize);
1213 //echo $this->w.'x'.$this->h.'<br>';
1214 $this->w = ((($this->aoe || $this->far) && $this->w) ? $this->w : ($this->w ? phpthumb_functions::nonempty_min($this->w, $getimagesize[0]) : ''));
1215 $this->h = ((($this->aoe || $this->far) && $this->h) ? $this->h : ($this->h ? phpthumb_functions::nonempty_min($this->h, $getimagesize[1]) : ''));
1216 //echo $this->w.'x'.$this->h.'<br>';
1217 if ($this->w || $this->h) {
1218 $commandline .= ' -thumbnail '.$this->w.'x'.$this->h;
1226 $this->DebugMessage('GetImageSize('.$this->sourceFilename.') failed', __FILE__, __LINE__);
1227 if ($this->w || $this->h) {
1228 $commandline .= ' -thumbnail '.$this->w.'x'.$this->h;
1229 if ($this->iar && (intval($this->w) > 0) && (intval($this->h) > 0)) {
1230 $commandline .= '!';
1235 foreach ($this->fltr as $filterkey => $filtercommand) {
1236 @list($command, $parameter) = explode('|', $filtercommand, 2);
1239 if ($this->ImageMagickSwitchAvailable('modulate')) {
1240 $commandline .= ' -modulate '.(100 + $parameter).',100,100';
1241 unset($this->fltr[$filterkey]);
1246 if ($this->ImageMagickSwitchAvailable('contrast')) {
1247 $contDiv10 = round($parameter / 10);
1248 if ($contDiv10 > 0) {
1249 for ($i = 0; $i < $contDiv10; $i++) {
1250 $commandline .= ' -contrast'; // increase contrast by 10%
1252 } elseif ($contDiv10 < 0) {
1253 for ($i = $contDiv10; $i < 0; $i++) {
1254 $commandline .= ' +contrast'; // decrease contrast by 10%
1259 unset($this->fltr[$filterkey]);
1264 if ($this->ImageMagickSwitchAvailable(array('colorspace', 'modulate'))) {
1265 if ($parameter == 100) {
1266 $commandline .= ' -colorspace GRAY -modulate 100,0,100';
1268 $commandline .= ' -modulate 100,'.(100 - $parameter).',100';
1270 unset($this->fltr[$filterkey]);
1275 if ($this->ImageMagickSwitchAvailable(array('colorspace', 'modulate'))) {
1276 if ($parameter == -100) {
1277 $commandline .= ' -colorspace GRAY -modulate 100,0,100';
1279 $commandline .= ' -modulate 100,'.(100 + $parameter).',100';
1281 unset($this->fltr[$filterkey]);
1286 if ($this->ImageMagickSwitchAvailable(array('colorspace', 'modulate'))) {
1287 $commandline .= ' -colorspace GRAY -modulate 100,0,100';
1288 //$commandline .= ' -colorspace GRAY';
1289 unset($this->fltr[$filterkey]);
1294 if ($this->ImageMagickSwitchAvailable(array('fill', 'colorize'))) {
1295 @list($amount, $color) = explode('|', $parameter);
1296 $commandline .= ' -fill #'.$color.' -colorize '.$amount;
1301 if ($this->ImageMagickSwitchAvailable('sepia-tone')) {
1302 @list($amount, $color) = explode('|', $parameter);
1303 $amount = ($amount ? $amount : 80);
1305 $commandline .= ' -sepia-tone '.$amount.'%';
1306 unset($this->fltr[$filterkey]);
1312 if ($this->ImageMagickSwitchAvailable('gamma')) {
1313 $commandline .= ' -gamma '.$parameter;
1314 unset($this->fltr[$filterkey]);
1319 if ($this->ImageMagickSwitchAvailable('negate')) {
1320 $commandline .= ' -negate';
1321 unset($this->fltr[$filterkey]);
1326 if ($this->ImageMagickSwitchAvailable(array('threshold', 'dither', 'monochrome'))) {
1327 $commandline .= ' -threshold '.round($parameter / 2.55).'% -dither -monochrome';
1328 unset($this->fltr[$filterkey]);
1333 if ($this->ImageMagickSwitchAvailable(array('colors', 'dither'))) {
1334 @list($colors, $dither) = explode('|', $parameter);
1335 $colors = ($colors ? (int) $colors : 256);
1336 $dither = ((strlen($dither) > 0) ? (bool) $dither : true);
1337 $commandline .= ' -colors '.max($colors, 8); // ImageMagick will otherwise fail with "cannot quantize to fewer than 8 colors"
1338 $commandline .= ($dither ? ' -dither' : ' +dither');
1339 unset($this->fltr[$filterkey]);
1344 if ($this->ImageMagickSwitchAvailable(array('flip', 'flop'))) {
1345 if (strpos(strtolower($parameter), 'x') !== false) {
1346 $commandline .= ' -flop';
1348 if (strpos(strtolower($parameter), 'y') !== false) {
1349 $commandline .= ' -flip';
1351 unset($this->fltr[$filterkey]);
1356 if ($this->ImageMagickSwitchAvailable('edge')) {
1357 $parameter = ($parameter ? $parameter : 2);
1358 $commandline .= ' -edge '.($parameter ? $parameter : 1);
1359 unset($this->fltr[$filterkey]);
1364 if ($this->ImageMagickSwitchAvailable(array('emboss', 'negate'))) {
1365 $parameter = ($parameter ? $parameter : 2);
1366 $commandline .= ' -emboss '.$parameter;
1367 if ($parameter < 2) {
1368 $commandline .= ' -negate'; // ImageMagick negates the image for some reason with '-emboss 1';
1370 unset($this->fltr[$filterkey]);
1375 if ($this->ImageMagickSwitchAvailable(array('normalize', 'level'))) {
1376 @list($band, $min, $max) = explode('|', $parameter);
1377 $band = ($band ? $band : '*');
1378 $min = ((strlen($min) > 0) ? $min : '-1');
1379 $max = ((strlen($max) > 0) ? $max : '-1');
1381 if (($min == -1) && ($max == -1)) {
1382 $commandline .= ' -normalize';
1383 unset($this->fltr[$filterkey]);
1384 } elseif (($min == -1) || ($max == -1)) {
1387 $commandline .= ' -level '.$min.'%,'.$max.'%';
1388 unset($this->fltr[$filterkey]);
1395 if ($this->ImageMagickSwitchAvailable('blur')) {
1396 @list($radius) = explode('|', $parameter);
1397 $radius = ($radius ? $radius : 1);
1398 $commandline .= ' -blur '.$radius;
1399 unset($this->fltr[$filterkey]);
1404 if ($this->ImageMagickSwitchAvailable('gaussian')) {
1405 @list($radius) = explode('|', $parameter);
1406 $radius = ($radius ? $radius : 1);
1407 $commandline .= ' -gaussian '.$radius;
1408 unset($this->fltr[$filterkey]);
1413 if ($this->ImageMagickSwitchAvailable('unsharp')) {
1414 @list($amount, $radius, $threshold) = explode('|', $parameter);
1415 $amount = ($amount ? $amount : 80);
1416 $radius = ($radius ? $radius : 0.5);
1417 $threshold = (strlen($threshold) ? $threshold : 3);
1418 $commandline .= ' -unsharp '.number_format(($radius * 2) - 1, 2).'x1+'.number_format($amount / 100, 2).'+'.number_format($threshold / 100, 2);
1419 unset($this->fltr[$filterkey]);
1424 if ($this->ImageMagickSwitchAvailable(array('border', 'bordercolor', 'thumbnail', 'crop'))) {
1426 @list($width, $rX, $rY, $color) = explode('|', $parameter);
1427 if ($width && !$rX && !$rY) {
1428 if (!phpthumb_functions::IsHexColor($color)) {
1429 $color = ($this->bc ? $this->bc : '000000');
1431 $commandline .= ' -border '.$width.' -bordercolor "#'.$color.'"';
1432 if (ereg(' \-crop ([0-9]+)x([0-9]+)\+0\+0 ', $commandline, $matches)) {
1433 $commandline = str_replace(' -crop '.$matches[1].'x'.$matches[2].'+0+0 ', ' -crop '.($matches[1] - (2 * $width)).'x'.($matches[2] - (2 * $width)).'+0+0 ', $commandline);
1434 } elseif (ereg(' \-thumbnail ([0-9]+)x([0-9]+) ', $commandline, $matches)) {
1435 $commandline = str_replace(' -thumbnail '.$matches[1].'x'.$matches[2].' ', ' -thumbnail '.($matches[1] - (2 * $width)).'x'.($matches[2] - (2 * $width)).' ', $commandline);
1437 unset($this->fltr[$filterkey]);
1489 if (!isset($this->fltr[$filterkey])) {
1490 $this->DebugMessage('Processed $this->fltr['.$filterkey.'] ('.$filtercommand.') with ImageMagick', __FILE__, __LINE__);
1492 $this->DebugMessage('Skipping $this->fltr['.$filterkey.'] ('.$filtercommand.') with ImageMagick', __FILE__, __LINE__);
1495 $this->DebugMessage('Remaining $this->fltr after ImageMagick: ('.$this->phpThumbDebugVarDump($this->fltr).')', __FILE__, __LINE__);
1497 if (eregi('jpe?g', $outputFormat) && $this->q) {
1498 if ($this->ImageMagickSwitchAvailable(array('quality', 'interlace'))) {
1499 $commandline .= ' -quality '.$this->thumbnailQuality;
1500 if ($this->config_output_interlace) {
1501 // causes weird things with animated GIF... leave for JPEG only
1502 $commandline .= ' -interlace line '; // Use Line or Plane to create an interlaced PNG or GIF or progressive JPEG image
1506 $commandline .= ' "'.str_replace('/', DIRECTORY_SEPARATOR, $this->sourceFilename).(($outputFormat == 'gif') ? '' : '[0]').'"'; // [0] means first frame of (GIF) animation, can be ignored
1507 $commandline .= ' '.$outputFormat.':"'.$IMtempfilename.'"';
1508 $commandline .= ' 2>&1';
1509 $this->DebugMessage('ImageMagick called as ('.$commandline.')', __FILE__, __LINE__);
1510 $IMresult = phpthumb_functions::SafeExec($commandline);
1512 //var_dump($commandline);
1513 ////var_dump($ImageCreateFunction);
1514 ////var_dump($IMresult);
1518 if (!@file_exists($IMtempfilename) || !@filesize($IMtempfilename)) {
1520 $this->DebugMessage('ImageMagick failed with message ('.$IMresult.')', __FILE__, __LINE__);
1521 if ($this->iswindows && !$IMresult) {
1522 $this->DebugMessage('Check to make sure that PHP has read+write permissions to "'.dirname($IMtempfilename).'"', __FILE__, __LINE__);
1527 $this->IMresizedData = file_get_contents($IMtempfilename);
1528 if (function_exists(@$ImageCreateFunction) && ($this->gdimg_source = @$ImageCreateFunction($IMtempfilename))) {
1529 //header('Content-Type: image/png');
1530 //ImageSaveAlpha($this->gdimg_source, true);
1531 //ImagePNG($this->gdimg_source);
1533 $this->source_width = ImageSX($this->gdimg_source);
1534 $this->source_height = ImageSY($this->gdimg_source);
1535 $this->DebugMessage('ImageMagickThumbnailToGD::'.$ImageCreateFunction.'() succeeded, $this->gdimg_source is now ('.$this->source_width.'x'.$this->source_height.')', __FILE__, __LINE__);
1536 $this->DebugMessage('ImageMagickThumbnailToGD() returning $IMresizedData ('.strlen($this->IMresizedData).' bytes)', __FILE__, __LINE__);
1538 $this->useRawIMoutput = true;
1539 $this->DebugMessage('$this->useRawIMoutput set to TRUE because '.@$ImageCreateFunction.'('.$IMtempfilename.') failed', __FILE__, __LINE__);
1541 @unlink($IMtempfilename);
1545 unlink($IMtempfilename);
1548 $this->DebugMessage('ImageMagickThumbnailToGD() aborting, phpThumb_tempnam() failed', __FILE__, __LINE__);
1551 $this->DebugMessage('ImageMagickThumbnailToGD() aborting because ImageMagickCommandlineBase() failed', __FILE__, __LINE__);
1553 $this->useRawIMoutput = false;
1559 if ($this->ra || $this->ar) {
1560 if (!function_exists('ImageRotate')) {
1561 $this->DebugMessage('!function_exists(ImageRotate)', __FILE__, __LINE__);
1564 if (!include_once(dirname(__FILE__).'/phpthumb.filters.php')) {
1565 $this->DebugMessage('Error including "'.dirname(__FILE__).'/phpthumb.filters.php" which is required for applying filters ('.implode(';', $this->fltr).')', __FILE__, __LINE__);
1569 $this->config_background_hexcolor = ($this->bg ? $this->bg : $this->config_background_hexcolor);
1570 if (!phpthumb_functions::IsHexColor($this->config_background_hexcolor)) {
1571 return $this->ErrorImage('Invalid hex color string "'.$this->config_background_hexcolor.'" for parameter "bg"');
1577 $rotate_angle = floatval($this->ra);
1581 if ($this->ar == 'x') {
1582 if (phpthumb_functions::version_compare_replacement(phpversion(), '4.2.0', '>=')) {
1583 if ($this->sourceFilename) {
1584 if (function_exists('exif_read_data')) {
1585 if ($exif_data = @exif_read_data($this->sourceFilename, 'IFD0')) {
1586 // http://sylvana.net/jpegcrop/exif_orientation.html
1587 switch (@$exif_data['Orientation']) {
1592 $rotate_angle = 180;
1595 $rotate_angle = 270;
1602 $this->DebugMessage('EXIF auto-rotate failed because unknown $exif_data[Orientation] "'.@$exif_data['Orientation'].'"', __FILE__, __LINE__);
1606 $this->DebugMessage('EXIF auto-rotate set to '.$rotate_angle.' degrees ($exif_data[Orientation] = "'.@$exif_data['Orientation'].'")', __FILE__, __LINE__);
1608 $this->DebugMessage('failed: exif_read_data('.$this->sourceFilename.')', __FILE__, __LINE__);
1612 $this->DebugMessage('!function_exists(exif_read_data)', __FILE__, __LINE__);
1616 $this->DebugMessage('Cannot auto-rotate from EXIF data because $this->sourceFilename is empty', __FILE__, __LINE__);
1620 $this->DebugMessage('Cannot auto-rotate from EXIF data because PHP is less than v4.2.0 ('.phpversion().')', __FILE__, __LINE__);
1623 } elseif (($this->ar == 'l') && ($this->source_height > $this->source_width)) {
1624 $rotate_angle = 270;
1625 } elseif (($this->ar == 'L') && ($this->source_height > $this->source_width)) {
1627 } elseif (($this->ar == 'p') && ($this->source_width > $this->source_height)) {
1629 } elseif (($this->ar == 'P') && ($this->source_width > $this->source_height)) {
1630 $rotate_angle = 270;
1634 while ($rotate_angle < 0) {
1635 $rotate_angle += 360;
1637 $rotate_angle = $rotate_angle % 360;
1638 if ($rotate_angle != 0) {
1640 if ($rotate_angle % 90) {
1641 $this->is_alpha = true;
1644 $background_color = phpthumb_functions::ImageHexColorAllocate($this->gdimg_source, $this->config_background_hexcolor);
1646 //if ((phpthumb_functions::gd_version() >= 2) && phpthumb_functions::CaseInsensitiveInArray($this->thumbnailFormat, $this->AlphaCapableFormats) && !$this->bg && ($rotate_angle % 90)) {
1647 if ((phpthumb_functions::gd_version() >= 2) && !$this->bg && ($rotate_angle % 90)) {
1649 $this->DebugMessage('Using alpha rotate', __FILE__, __LINE__);
1650 if ($gdimg_rotate_mask = phpthumb_functions::ImageCreateFunction(ImageSX($this->gdimg_source), ImageSY($this->gdimg_source))) {
1652 for ($i = 0; $i <= 255; $i++) {
1653 $color_mask[$i] = ImageColorAllocate($gdimg_rotate_mask, $i, $i, $i);
1655 ImageFilledRectangle($gdimg_rotate_mask, 0, 0, ImageSX($gdimg_rotate_mask), ImageSY($gdimg_rotate_mask), $color_mask[255]);
1656 $imageX = ImageSX($this->gdimg_source);
1657 $imageY = ImageSY($this->gdimg_source);
1658 for ($x = 0; $x < $imageX; $x++) {
1659 for ($y = 0; $y < $imageY; $y++) {
1660 $pixelcolor = phpthumb_functions::GetPixelColor($this->gdimg_source, $x, $y);
1661 ImageSetPixel($gdimg_rotate_mask, $x, $y, $color_mask[255 - round($pixelcolor['alpha'] * 255 / 127)]);
1664 $gdimg_rotate_mask = ImageRotate($gdimg_rotate_mask, $rotate_angle, $color_mask[0]);
1665 $this->gdimg_source = ImageRotate($this->gdimg_source, $rotate_angle, $background_color);
1667 ImageAlphaBlending($this->gdimg_source, false);
1668 ImageSaveAlpha($this->gdimg_source, true);
1669 $this->is_alpha = true;
1670 $phpThumbFilters = new phpthumb_filters();
1671 $phpThumbFilters->phpThumbObject = $this;
1672 $phpThumbFilters->ApplyMask($gdimg_rotate_mask, $this->gdimg_source);
1674 ImageDestroy($gdimg_rotate_mask);
1675 $this->source_width = ImageSX($this->gdimg_source);
1676 $this->source_height = ImageSY($this->gdimg_source);
1679 $this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__);
1684 if (phpthumb_functions::gd_version() < 2) {
1685 $this->DebugMessage('Using non-alpha rotate because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
1686 } elseif ($this->bg) {
1687 $this->DebugMessage('Using non-alpha rotate because $this->bg is "'.$this->bg.'"', __FILE__, __LINE__);
1688 } elseif ($this->bg) {
1689 $this->DebugMessage('Using non-alpha rotate because ($rotate_angle % 90) = "'.($rotate_angle % 90).'"', __FILE__, __LINE__);
1691 $this->DebugMessage('Using non-alpha rotate because $this->thumbnailFormat is "'.$this->thumbnailFormat.'"', __FILE__, __LINE__);
1694 if (ImageColorTransparent($this->gdimg_source) >= 0) {
1695 // ImageRotate() forgets all about an image's transparency and sets the transparent color to black
1696 // To compensate, flood-fill the transparent color of the source image with the specified background color first
1697 // then rotate and the colors should match
1699 if (!function_exists('ImageIsTrueColor') || !ImageIsTrueColor($this->gdimg_source)) {
1700 // convert paletted image to true-color before rotating to prevent nasty aliasing artifacts
1702 $this->source_width = ImageSX($this->gdimg_source);
1703 $this->source_height = ImageSY($this->gdimg_source);
1704 $gdimg_newsrc = phpthumb_functions::ImageCreateFunction($this->source_width, $this->source_height);
1705 $background_color = phpthumb_functions::ImageHexColorAllocate($gdimg_newsrc, $this->config_background_hexcolor);
1706 ImageFilledRectangle($gdimg_newsrc, 0, 0, $this->source_width, $this->source_height, phpthumb_functions::ImageHexColorAllocate($gdimg_newsrc, $this->config_background_hexcolor));
1707 ImageCopy($gdimg_newsrc, $this->gdimg_source, 0, 0, 0, 0, $this->source_width, $this->source_height);
1708 ImageDestroy($this->gdimg_source);
1709 unset($this->gdimg_source);
1710 $this->gdimg_source = $gdimg_newsrc;
1711 unset($gdimg_newsrc);
1716 $this->gdimg_source,
1717 ImageColorTransparent($this->gdimg_source),
1718 hexdec(substr($this->config_background_hexcolor, 0, 2)),
1719 hexdec(substr($this->config_background_hexcolor, 2, 2)),
1720 hexdec(substr($this->config_background_hexcolor, 4, 2)));
1722 ImageColorTransparent($this->gdimg_source, -1);
1727 $this->gdimg_source = ImageRotate($this->gdimg_source, $rotate_angle, $background_color);
1728 $this->source_width = ImageSX($this->gdimg_source);
1729 $this->source_height = ImageSY($this->gdimg_source);
1738 function FixedAspectRatio() {
1739 // optional fixed-dimension images (regardless of aspect ratio)
1741 //echo $this->thumbnail_width.'x'.$this->thumbnail_height.'['.__LINE__.']<br>';
1747 if (!$this->w || !$this->h) {
1750 $this->thumbnail_width = $this->w;
1751 $this->thumbnail_height = $this->h;
1752 $this->is_alpha = true;
1753 if ($this->thumbnail_image_width >= $this->thumbnail_width) {
1754 //echo __LINE__.'<br>';
1757 $aspectratio = $this->thumbnail_image_height / $this->thumbnail_image_width;
1758 $this->thumbnail_image_height = round($this->thumbnail_image_width * $aspectratio);
1759 $this->thumbnail_height = ($this->h ? $this->h : $this->thumbnail_image_height);
1760 } elseif ($this->thumbnail_image_height < $this->thumbnail_height) {
1761 $this->thumbnail_image_height = $this->thumbnail_height;
1762 $this->thumbnail_image_width = round($this->thumbnail_image_height / $aspectratio);
1766 //echo __LINE__.'<br>';
1769 $aspectratio = $this->thumbnail_image_width / $this->thumbnail_image_height;
1770 $this->thumbnail_image_width = round($this->thumbnail_image_height * $aspectratio);
1771 } elseif ($this->thumbnail_image_width < $this->thumbnail_width) {
1772 $this->thumbnail_image_width = $this->thumbnail_width;
1773 $this->thumbnail_image_height = round($this->thumbnail_image_width / $aspectratio);
1777 //echo $this->thumbnail_width.'x'.$this->thumbnail_height.'['.__LINE__.']<br>';
1783 function AntiOffsiteLinking() {
1784 // Optional anti-offsite hijacking of the thumbnail script
1786 if ($allow && $this->config_nooffsitelink_enabled && (@$_SERVER['HTTP_REFERER'] || $this->config_nooffsitelink_require_refer)) {
1787 $this->DebugMessage('AntiOffsiteLinking() checking $_SERVER[HTTP_REFERER] "'.@$_SERVER['HTTP_REFERER'].'"', __FILE__, __LINE__);
1788 $parsed_url = parse_url(@$_SERVER['HTTP_REFERER']);
1789 if (!phpthumb_functions::CaseInsensitiveInArray(@$parsed_url['host'], $this->config_nooffsitelink_valid_domains)) {
1791 $erase = $this->config_nooffsitelink_erase_image;
1792 $message = $this->config_nooffsitelink_text_message;
1793 $this->DebugMessage('AntiOffsiteLinking() - "'.@$parsed_url['host'].'" is NOT in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);
1795 $this->DebugMessage('AntiOffsiteLinking() - "'.@$parsed_url['host'].'" is in $this->config_nooffsitelink_valid_domains ('.implode(';', $this->config_nooffsitelink_valid_domains).')', __FILE__, __LINE__);
1799 if ($allow && $this->config_nohotlink_enabled && eregi('^(f|ht)tps?\://', $this->src)) {
1800 $parsed_url = parse_url($this->src);
1801 if (!phpthumb_functions::CaseInsensitiveInArray(@$parsed_url['host'], $this->config_nohotlink_valid_domains)) {
1802 // This domain is not allowed
1804 $erase = $this->config_nohotlink_erase_image;
1805 $message = $this->config_nohotlink_text_message;
1806 $this->DebugMessage('AntiOffsiteLinking() - "'.$parsed_url['host'].'" is NOT in $this->config_nohotlink_valid_domains ('.implode(';', $this->config_nohotlink_valid_domains).')', __FILE__, __LINE__);
1808 $this->DebugMessage('AntiOffsiteLinking() - "'.$parsed_url['host'].'" is in $this->config_nohotlink_valid_domains ('.implode(';', $this->config_nohotlink_valid_domains).')', __FILE__, __LINE__);
1813 $this->DebugMessage('AntiOffsiteLinking() says this is allowed', __FILE__, __LINE__);
1817 if (!phpthumb_functions::IsHexColor($this->config_error_bgcolor)) {
1818 return $this->ErrorImage('Invalid hex color string "'.$this->config_error_bgcolor.'" for $this->config_error_bgcolor');
1820 if (!phpthumb_functions::IsHexColor($this->config_error_textcolor)) {
1821 return $this->ErrorImage('Invalid hex color string "'.$this->config_error_textcolor.'" for $this->config_error_textcolor');
1825 return $this->ErrorImage($message, $this->thumbnail_width, $this->thumbnail_height, $this->config_error_bgcolor, $this->config_error_textcolor, $this->config_error_fontsize);
1829 $nohotlink_text_array = explode("\n", wordwrap($message, floor($this->thumbnail_width / ImageFontWidth($this->config_error_fontsize)), "\n"));
1830 $nohotlink_text_color = phpthumb_functions::ImageHexColorAllocate($this->gdimg_output, $this->config_error_textcolor);
1832 $topoffset = round(($this->thumbnail_height - (count($nohotlink_text_array) * ImageFontHeight($this->config_error_fontsize))) / 2);
1835 $this->DebugMessage('AntiOffsiteLinking() writing '.count($nohotlink_text_array).' lines of text "'.$message.'" (in #'.$this->config_error_textcolor.') on top of image', __FILE__, __LINE__);
1836 foreach ($nohotlink_text_array as $dummy => $textline) {
1837 $leftoffset = max(0, round(($this->thumbnail_width - (strlen($textline) * ImageFontWidth($this->config_error_fontsize))) / 2));
1838 ImageString($this->gdimg_output, $this->config_error_fontsize, $leftoffset, $topoffset + ($rowcounter++ * ImageFontHeight($this->config_error_fontsize)), $textline, $nohotlink_text_color);
1846 function AlphaChannelFlatten() {
1847 if (!$this->is_alpha) {
1848 // image doesn't have alpha transparency, no need to flatten
1849 $this->DebugMessage('skipping AlphaChannelFlatten() because !$this->is_alpha', __FILE__, __LINE__);
1852 switch ($this->thumbnailFormat) {
1855 // image has alpha transparency, but output as PNG or ICO which can handle it
1856 $this->DebugMessage('skipping AlphaChannelFlatten() because ($this->thumbnailFormat == "'.$this->thumbnailFormat.'")', __FILE__, __LINE__);
1861 // image has alpha transparency, but output as GIF which can handle only single-color transparency
1862 $CurrentImageColorTransparent = ImageColorTransparent($this->gdimg_output);
1863 if ($CurrentImageColorTransparent == -1) {
1864 // no transparent color defined
1866 if (phpthumb_functions::gd_version() < 2.0) {
1867 $this->DebugMessage('AlphaChannelFlatten() failed because GD version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
1871 if ($img_alpha_mixdown_dither = @ImageCreateTrueColor(ImageSX($this->gdimg_output), ImageSY($this->gdimg_output))) {
1873 for ($i = 0; $i <= 255; $i++) {
1874 $dither_color[$i] = ImageColorAllocate($img_alpha_mixdown_dither, $i, $i, $i);
1877 // scan through current truecolor image copy alpha channel to temp image as grayscale
1878 for ($x = 0; $x < $this->thumbnail_width; $x++) {
1879 for ($y = 0; $y < $this->thumbnail_height; $y++) {
1880 $PixelColor = phpthumb_functions::GetPixelColor($this->gdimg_output, $x, $y);
1881 ImageSetPixel($img_alpha_mixdown_dither, $x, $y, $dither_color[($PixelColor['alpha'] * 2)]);
1885 // dither alpha channel grayscale version down to 2 colors
1886 ImageTrueColorToPalette($img_alpha_mixdown_dither, true, 2);
1888 // reduce color palette to 256-1 colors (leave one palette position for transparent color)
1889 ImageTrueColorToPalette($this->gdimg_output, true, 255);
1891 // allocate a new color for transparent color index
1892 $TransparentColor = ImageColorAllocate($this->gdimg_output, 1, 254, 253);
1893 ImageColorTransparent($this->gdimg_output, $TransparentColor);
1895 // scan through alpha channel image and note pixels with >50% transparency
1896 $TransparentPixels = array();
1897 for ($x = 0; $x < $this->thumbnail_width; $x++) {
1898 for ($y = 0; $y < $this->thumbnail_height; $y++) {
1899 $AlphaChannelPixel = phpthumb_functions::GetPixelColor($img_alpha_mixdown_dither, $x, $y);
1900 if ($AlphaChannelPixel['red'] > 127) {
1901 ImageSetPixel($this->gdimg_output, $x, $y, $TransparentColor);
1905 ImageDestroy($img_alpha_mixdown_dither);
1907 $this->DebugMessage('AlphaChannelFlatten() set image to 255+1 colors with transparency for GIF output', __FILE__, __LINE__);
1911 $this->DebugMessage('AlphaChannelFlatten() failed ImageCreate('.ImageSX($this->gdimg_output).', '.ImageSY($this->gdimg_output).')', __FILE__, __LINE__);
1916 // a single transparent color already defined, leave as-is
1917 $this->DebugMessage('skipping AlphaChannelFlatten() because ($this->thumbnailFormat == "'.$this->thumbnailFormat.'") and ImageColorTransparent returned "'.$CurrentImageColorTransparent.'"', __FILE__, __LINE__);
1922 $this->DebugMessage('continuing AlphaChannelFlatten() for output format "'.$this->thumbnailFormat.'"', __FILE__, __LINE__);
1924 // image has alpha transparency, and is being output in a format that doesn't support it -- flatten
1925 if ($gdimg_flatten_temp = phpthumb_functions::ImageCreateFunction($this->thumbnail_width, $this->thumbnail_height)) {
1927 $this->config_background_hexcolor = ($this->bg ? $this->bg : $this->config_background_hexcolor);
1928 if (!phpthumb_functions::IsHexColor($this->config_background_hexcolor)) {
1929 return $this->ErrorImage('Invalid hex color string "'.$this->config_background_hexcolor.'" for parameter "bg"');
1931 $background_color = phpthumb_functions::ImageHexColorAllocate($this->gdimg_output, $this->config_background_hexcolor);
1932 ImageFilledRectangle($gdimg_flatten_temp, 0, 0, $this->thumbnail_width, $this->thumbnail_height, $background_color);
1933 ImageCopy($gdimg_flatten_temp, $this->gdimg_output, 0, 0, 0, 0, $this->thumbnail_width, $this->thumbnail_height);
1935 ImageAlphaBlending($this->gdimg_output, true);
1936 ImageSaveAlpha($this->gdimg_output, false);
1937 ImageColorTransparent($this->gdimg_output, -1);
1938 ImageCopy($this->gdimg_output, $gdimg_flatten_temp, 0, 0, 0, 0, $this->thumbnail_width, $this->thumbnail_height);
1940 ImageDestroy($gdimg_flatten_temp);
1944 $this->DebugMessage('ImageCreateFunction() failed', __FILE__, __LINE__);
1950 function ApplyFilters() {
1951 if ($this->fltr && is_array($this->fltr)) {
1952 if (!include_once(dirname(__FILE__).'/phpthumb.filters.php')) {
1953 $this->DebugMessage('Error including "'.dirname(__FILE__).'/phpthumb.filters.php" which is required for applying filters ('.implode(';', $this->fltr).')', __FILE__, __LINE__);
1956 $phpthumbFilters = new phpthumb_filters();
1957 $phpthumbFilters->phpThumbObject = $this;
1958 foreach ($this->fltr as $dummy => $filtercommand) {
1959 @list($command, $parameter) = explode('|', $filtercommand, 2);
1960 $this->DebugMessage('Attempting to process filter command "'.$command.'('.$parameter.')"', __FILE__, __LINE__);
1963 $phpthumbFilters->Brightness($this->gdimg_output, $parameter);
1967 $phpthumbFilters->Contrast($this->gdimg_output, $parameter);
1971 $phpthumbFilters->Desaturate($this->gdimg_output, $parameter, '');
1975 $phpthumbFilters->Saturation($this->gdimg_output, $parameter, '');
1979 $phpthumbFilters->Grayscale($this->gdimg_output);
1983 if (phpthumb_functions::gd_version() < 2) {
1984 $this->DebugMessage('Skipping Colorize() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
1987 @list($amount, $color) = explode('|', $parameter);
1988 $phpthumbFilters->Colorize($this->gdimg_output, $amount, $color);
1992 if (phpthumb_functions::gd_version() < 2) {
1993 $this->DebugMessage('Skipping Sepia() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
1996 @list($amount, $color) = explode('|', $parameter);
1997 $phpthumbFilters->Sepia($this->gdimg_output, $amount, $color);
2001 $phpthumbFilters->Gamma($this->gdimg_output, $parameter);
2005 $phpthumbFilters->Negative($this->gdimg_output);
2009 $phpthumbFilters->Threshold($this->gdimg_output, $parameter);
2013 if (phpthumb_functions::gd_version() < 2) {
2014 $this->DebugMessage('Skipping ReduceColorDepth() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
2017 @list($colors, $dither) = explode('|', $parameter);
2018 $colors = ($colors ? (int) $colors : 256);
2019 $dither = ((strlen($dither) > 0) ? (bool) $dither : true);
2020 $phpthumbFilters->ReduceColorDepth($this->gdimg_output, $colors, $dither);
2024 $phpthumbFilters->Flip($this->gdimg_output, (strpos(strtolower($parameter), 'x') !== false), (strpos(strtolower($parameter), 'y') !== false));
2028 $phpthumbFilters->EdgeDetect($this->gdimg_output);
2032 $phpthumbFilters->Emboss($this->gdimg_output);
2036 @list($width, $color1, $color2) = explode('|', $parameter);
2037 $phpthumbFilters->Bevel($this->gdimg_output, $width, $color1, $color2);
2041 @list($band, $min, $max) = explode('|', $parameter);
2042 $band = ($band ? $band : '*');
2043 $min = ((strlen($min) > 0) ? $min : '-1');
2044 $max = ((strlen($max) > 0) ? $max : '-1');
2045 $phpthumbFilters->HistogramStretch($this->gdimg_output, $band, $min, $max);
2049 $phpthumbFilters->WhiteBalance($this->gdimg_output, $parameter);
2053 if (phpthumb_functions::gd_version() < 2) {
2054 $this->DebugMessage('Skipping HistogramOverlay() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
2057 @list($bands, $colors, $width, $height, $alignment, $opacity, $margin) = explode('|', $parameter);
2058 $bands = ($bands ? $bands : '*');
2059 $colors = ($colors ? $colors : '');
2060 $width = ($width ? $width : 0.25);
2061 $height = ($height ? $height : 0.25);
2062 $alignment = ($alignment ? $alignment : 'BR');
2063 $opacity = ($opacity ? $opacity : 50);
2064 $margin = ($margin ? $margin : 5);
2065 $phpthumbFilters->HistogramOverlay($this->gdimg_output, $bands, $colors, $width, $height, $alignment, $opacity, $margin);
2069 @list($frame_width, $edge_width, $color_frame, $color1, $color2) = explode('|', $parameter);
2070 $phpthumbFilters->Frame($this->gdimg_output, $frame_width, $edge_width, $color_frame, $color1, $color2);
2074 if (phpthumb_functions::gd_version() < 2) {
2075 $this->DebugMessage('Skipping DropShadow() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
2078 $this->is_alpha = true;
2079 @list($distance, $width, $color, $angle, $fade) = explode('|', $parameter);
2080 $phpthumbFilters->DropShadow($this->gdimg_output, $distance, $width, $color, $angle, $fade);
2084 if (phpthumb_functions::gd_version() < 2) {
2085 $this->DebugMessage('Skipping Mask() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
2088 $mask_filename = $this->ResolveFilenameToAbsolute($parameter);
2089 if (@is_readable($mask_filename) && ($fp_mask = @fopen($mask_filename, 'rb'))) {
2090 $MaskImageData = '';
2092 $buffer = fread($fp_mask, 8192);
2093 $MaskImageData .= $buffer;
2094 } while (strlen($buffer) > 0);
2096 if ($gdimg_mask = $this->ImageCreateFromStringReplacement($MaskImageData)) {
2097 $this->is_alpha = true;
2098 $phpthumbFilters->ApplyMask($gdimg_mask, $this->gdimg_output);
2099 ImageDestroy($gdimg_mask);
2101 $this->DebugMessage('ImageCreateFromStringReplacement() failed for "'.$mask_filename.'"', __FILE__, __LINE__);
2104 $this->DebugMessage('Cannot open mask file "'.$mask_filename.'"', __FILE__, __LINE__);
2109 if (phpthumb_functions::gd_version() < 2) {
2110 $this->DebugMessage('Skipping Elipse() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
2113 $this->is_alpha = true;
2114 $phpthumbFilters->Elipse($this->gdimg_output);
2118 if (phpthumb_functions::gd_version() < 2) {
2119 $this->DebugMessage('Skipping RoundedImageCorners() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
2122 @list($radius_x, $radius_y) = explode('|', $parameter);
2123 if (($radius_x < 1) || ($radius_y < 1)) {
2124 $this->DebugMessage('Skipping RoundedImageCorners('.$radius_x.', '.$radius_y.') because x/y radius is less than 1', __FILE__, __LINE__);
2127 $this->is_alpha = true;
2128 $phpthumbFilters->RoundedImageCorners($this->gdimg_output, $radius_x, $radius_y);
2132 @list($left, $right, $top, $bottom) = explode('|', $parameter);
2133 $phpthumbFilters->Crop($this->gdimg_output, $left, $right, $top, $bottom);
2137 @list($border_width, $radius_x, $radius_y, $hexcolor_border) = explode('|', $parameter);
2138 $this->is_alpha = true;
2139 $phpthumbFilters->ImageBorder($this->gdimg_output, $border_width, $radius_x, $radius_y, $hexcolor_border);
2143 @list($filename, $underlay, $margin, $opacity) = explode('|', $parameter);
2144 $underlay = (bool) ($underlay ? $underlay : false);
2145 $margin = ((strlen($margin) > 0) ? $margin : ($underlay ? 0.1 : 0.0));
2146 $opacity = ((strlen($opacity) > 0) ? $opacity : 100);
2147 if (($margin > 0) && ($margin < 1)) {
2148 $margin = min(0.499, $margin);
2149 } elseif (($margin > -1) && ($margin < 0)) {
2150 $margin = max(-0.499, $margin);
2153 $filename = $this->ResolveFilenameToAbsolute($filename);
2154 if (@is_readable($filename) && ($fp_watermark = @fopen($filename, 'rb'))) {
2155 $WatermarkImageData = '';
2157 $buffer = fread($fp_watermark, 8192);
2158 $WatermarkImageData .= $buffer;
2159 } while (strlen($buffer) > 0);
2160 fclose($fp_watermark);
2161 if ($img_watermark = $this->ImageCreateFromStringReplacement($WatermarkImageData)) {
2163 $resized_x = max(1, ImageSX($this->gdimg_output) - round(2 * (ImageSX($this->gdimg_output) * $margin)));
2164 $resized_y = max(1, ImageSY($this->gdimg_output) - round(2 * (ImageSY($this->gdimg_output) * $margin)));
2166 $resized_x = max(1, ImageSX($this->gdimg_output) - round(2 * $margin));
2167 $resized_y = max(1, ImageSY($this->gdimg_output) - round(2 * $margin));
2172 if ($img_watermark_resized = phpthumb_functions::ImageCreateFunction(ImageSX($this->gdimg_output), ImageSY($this->gdimg_output))) {
2173 ImageAlphaBlending($img_watermark_resized, false);
2174 ImageSaveAlpha($img_watermark_resized, true);
2175 $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));
2176 if ($img_source_resized = phpthumb_functions::ImageCreateFunction($resized_x, $resized_y)) {
2177 ImageAlphaBlending($img_source_resized, false);
2178 ImageSaveAlpha($img_source_resized, true);
2179 $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));
2180 $phpthumbFilters->WatermarkOverlay($img_watermark_resized, $img_source_resized, 'C', $opacity, $margin);
2181 ImageCopy($this->gdimg_output, $img_watermark_resized, 0, 0, 0, 0, ImageSX($this->gdimg_output), ImageSY($this->gdimg_output));
2183 $this->DebugMessage('phpthumb_functions::ImageCreateFunction('.$resized_x.', '.$resized_y.')', __FILE__, __LINE__);
2185 ImageDestroy($img_watermark_resized);
2187 $this->DebugMessage('phpthumb_functions::ImageCreateFunction('.ImageSX($this->gdimg_output).', '.ImageSY($this->gdimg_output).')', __FILE__, __LINE__);
2192 if ($img_watermark_resized = phpthumb_functions::ImageCreateFunction($resized_x, $resized_y)) {
2193 ImageAlphaBlending($img_watermark_resized, false);
2194 ImageSaveAlpha($img_watermark_resized, true);
2195 $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));
2196 $phpthumbFilters->WatermarkOverlay($this->gdimg_output, $img_watermark_resized, 'C', $opacity, $margin);
2197 ImageDestroy($img_watermark_resized);
2199 $this->DebugMessage('phpthumb_functions::ImageCreateFunction('.$resized_x.', '.$resized_y.')', __FILE__, __LINE__);
2203 ImageDestroy($img_watermark);
2206 $this->DebugMessage('ImageCreateFromStringReplacement() failed for "'.$filename.'"', __FILE__, __LINE__);
2209 $this->DebugMessage('Cannot open overlay file "'.$filename.'"', __FILE__, __LINE__);
2214 @list($filename, $alignment, $opacity, $margin) = explode('|', $parameter);
2215 $alignment = ($alignment ? $alignment : 'BR');
2216 $opacity = (strlen($opacity) ? $opacity : 50);
2217 $margin = (strlen($margin) ? $margin : 5);
2219 $filename = $this->ResolveFilenameToAbsolute($filename);
2220 if (@is_readable($filename)) {
2221 //if ($img_watermark = $this->ImageCreateFromFilename($filename, $rawImageData)) {
2222 if ($img_watermark = $this->ImageCreateFromFilename($filename)) {
2224 $phpthumbFilters->WatermarkOverlay($this->gdimg_output, $img_watermark, $alignment, $opacity, $margin);
2225 ImageDestroy($img_watermark);
2227 $this->DebugMessage('ImageCreateFromFilename() failed for "'.$filename.'"', __FILE__, __LINE__);
2230 $this->DebugMessage('!is_readable('.$filename.')', __FILE__, __LINE__);
2235 @list($text, $size, $alignment, $hex_color, $ttffont, $opacity, $margin, $angle, $bg_color, $bg_opacity, $fillextend) = explode('|', $parameter);
2236 $text = ($text ? $text : '');
2237 $size = ($size ? $size : 3);
2238 $alignment = ($alignment ? $alignment : 'BR');
2239 $hex_color = ($hex_color ? $hex_color : '000000');
2240 $ttffont = ($ttffont ? $ttffont : '');
2241 $opacity = (strlen($opacity) ? $opacity : 50);
2242 $margin = (strlen($margin) ? $margin : 5);
2243 $angle = (strlen($angle) ? $angle : 0);
2244 $bg_color = ($bg_color ? $bg_color : false);
2245 $bg_opacity = ($bg_opacity ? $bg_opacity : 0);
2246 $fillextend = ($fillextend ? $fillextend : '');
2248 if (basename($ttffont) == $ttffont) {
2249 $ttffont = realpath($this->config_ttf_directory.DIRECTORY_SEPARATOR.$ttffont);
2251 $ttffont = $this->ResolveFilenameToAbsolute($ttffont);
2253 $phpthumbFilters->WatermarkText($this->gdimg_output, $text, $size, $alignment, $hex_color, $ttffont, $opacity, $margin, $angle, $bg_color, $bg_opacity, $fillextend);
2257 @list($radius) = explode('|', $parameter);
2258 $radius = ($radius ? $radius : 1);
2259 if (phpthumb_functions::gd_version() < 2) {
2260 $this->DebugMessage('Skipping Blur() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
2263 $phpthumbFilters->Blur($this->gdimg_output, $radius);
2267 $phpthumbFilters->BlurGaussian($this->gdimg_output);
2271 $phpthumbFilters->BlurSelective($this->gdimg_output);
2275 $phpthumbFilters->MeanRemoval($this->gdimg_output);
2279 $phpthumbFilters->Smooth($this->gdimg_output, $parameter);
2283 @list($amount, $radius, $threshold) = explode('|', $parameter);
2284 $amount = ($amount ? $amount : 80);
2285 $radius = ($radius ? $radius : 0.5);
2286 $threshold = (strlen($threshold) ? $threshold : 3);
2287 if (phpthumb_functions::gd_version() >= 2.0) {
2289 if (!@include_once(dirname(__FILE__).'/phpthumb.unsharp.php')) {
2290 $include_error = ob_get_contents();
2291 if ($include_error) {
2292 $this->DebugMessage('include_once("'.dirname(__FILE__).'/phpthumb.unsharp.php") generated message: "'.$include_error.'"', __FILE__, __LINE__);
2294 $this->DebugMessage('Error including "'.dirname(__FILE__).'/phpthumb.unsharp.php" which is required for unsharp masking', __FILE__, __LINE__);
2299 phpUnsharpMask::applyUnsharpMask($this->gdimg_output, $amount, $radius, $threshold);
2301 $this->DebugMessage('Skipping unsharp mask because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
2312 function MaxFileSize() {
2313 if (phpthumb_functions::gd_version() < 2) {
2314 $this->DebugMessage('Skipping MaxFileSize() because gd_version is "'.phpthumb_functions::gd_version().'"', __FILE__, __LINE__);
2317 if ($this->maxb > 0) {
2318 switch ($this->thumbnailFormat) {
2321 $imgRenderFunction = 'image'.$this->thumbnailFormat;
2324 $imgRenderFunction($this->gdimg_output);
2325 $imgdata = ob_get_contents();
2328 if (strlen($imgdata) > $this->maxb) {
2329 for ($i = 8; $i >= 1; $i--) {
2330 $tempIMG = ImageCreateTrueColor(ImageSX($this->gdimg_output), ImageSY($this->gdimg_output));
2331 ImageCopy($tempIMG, $this->gdimg_output, 0, 0, 0, 0, ImageSX($this->gdimg_output), ImageSY($this->gdimg_output));
2332 ImageTrueColorToPalette($tempIMG, true, pow(2, $i));
2334 $imgRenderFunction($tempIMG);
2335 $imgdata = ob_get_contents();
2338 if (strlen($imgdata) <= $this->maxb) {
2339 ImageTrueColorToPalette($this->gdimg_output, true, pow(2, $i));
2344 if (strlen($imgdata) > $this->maxb) {
2345 ImageTrueColorToPalette($this->gdimg_output, true, pow(2, $i));
2352 ImageJPEG($this->gdimg_output);
2353 $imgdata = ob_get_contents();
2356 $OriginalJPEGquality = $this->thumbnailQuality;
2357 if (strlen($imgdata) > $this->maxb) {
2358 for ($i = 3; $i < 20; $i++) {
2359 $q = round(100 * (1 - log10($i / 2)));
2361 ImageJPEG($this->gdimg_output, '', $q);
2362 $imgdata = ob_get_contents();
2365 $this->thumbnailQuality = $q;
2366 if (strlen($imgdata) <= $this->maxb) {
2371 if (strlen($imgdata) > $this->maxb) {
2385 function CalculateThumbnailDimensions() {
2386 //echo $this->source_width.'x'.$this->source_height.'<hr>';
2387 $this->thumbnailCropX = ($this->sx ? (($this->sx >= 1) ? $this->sx : round($this->sx * $this->source_width)) : 0);
2388 //echo $this->thumbnailCropX.'<br>';
2389 $this->thumbnailCropY = ($this->sy ? (($this->sy >= 1) ? $this->sy : round($this->sy * $this->source_height)) : 0);
2390 //echo $this->thumbnailCropY.'<br>';
2391 $this->thumbnailCropW = ($this->sw ? (($this->sw >= 1) ? $this->sw : round($this->sw * $this->source_width)) : $this->source_width);
2392 //echo $this->thumbnailCropW.'<br>';
2393 $this->thumbnailCropH = ($this->sh ? (($this->sh >= 1) ? $this->sh : round($this->sh * $this->source_height)) : $this->source_height);
2394 //echo $this->thumbnailCropH.'<hr>';
2396 // limit source area to original image area
2397 $this->thumbnailCropW = max(1, min($this->thumbnailCropW, $this->source_width - $this->thumbnailCropX));
2398 $this->thumbnailCropH = max(1, min($this->thumbnailCropH, $this->source_height - $this->thumbnailCropY));
2400 $this->DebugMessage('CalculateThumbnailDimensions() [x,y,w,h] initially set to ['.$this->thumbnailCropX.','.$this->thumbnailCropY.','.$this->thumbnailCropW.','.$this->thumbnailCropH.']', __FILE__, __LINE__);
2403 if ($this->zc && $this->w && $this->h) {
2405 // retain proportional resizing we did above, but crop off larger dimension so smaller
2406 // dimension fully fits available space
2408 $scaling_X = $this->source_width / $this->w;
2409 $scaling_Y = $this->source_height / $this->h;
2410 if ($scaling_X > $scaling_Y) {
2411 // some of the width will need to be cropped
2412 $allowable_width = $this->source_width / $scaling_X * $scaling_Y;
2413 $this->thumbnailCropW = round($allowable_width);
2414 $this->thumbnailCropX = round(($this->source_width - $allowable_width) / 2);
2416 } elseif ($scaling_Y > $scaling_X) {
2417 // some of the height will need to be cropped
2418 $allowable_height = $this->source_height / $scaling_Y * $scaling_X;
2419 $this->thumbnailCropH = round($allowable_height);
2420 $this->thumbnailCropY = round(($this->source_height - $allowable_height) / 2);
2423 // image fits perfectly, no cropping needed
2425 $this->thumbnail_width = $this->w;
2426 $this->thumbnail_height = $this->h;
2427 $this->thumbnail_image_width = $this->thumbnail_width;
2428 $this->thumbnail_image_height = $this->thumbnail_height;
2430 } elseif ($this->iar && $this->w && $this->h) {
2432 // Ignore Aspect Ratio
2433 // stretch image to fit exactly 'w' x 'h'
2434 $this->thumbnail_width = $this->w;
2435 $this->thumbnail_height = $this->h;
2436 $this->thumbnail_image_width = $this->thumbnail_width;
2437 $this->thumbnail_image_height = $this->thumbnail_height;
2441 $original_aspect_ratio = $this->thumbnailCropW / $this->thumbnailCropH;
2442 //var_dump($original_aspect_ratio);
2445 if ($this->w && $this->h) {
2446 $maxwidth = min($this->w, $this->h * $original_aspect_ratio);
2447 $maxheight = min($this->h, $this->w / $original_aspect_ratio);
2448 } elseif ($this->w) {
2449 $maxwidth = $this->w;
2450 $maxheight = $this->w / $original_aspect_ratio;
2451 } elseif ($this->h) {
2452 $maxwidth = $this->h * $original_aspect_ratio;
2453 $maxheight = $this->h;
2455 $maxwidth = $this->thumbnailCropW;
2456 $maxheight = $this->thumbnailCropH;
2459 $maxwidth = phpthumb_functions::nonempty_min($this->w, $this->thumbnailCropW, $this->config_output_maxwidth);
2460 $maxheight = phpthumb_functions::nonempty_min($this->h, $this->thumbnailCropH, $this->config_output_maxheight);
2461 //echo $maxwidth.'x'.$maxheight.'<br>';
2462 $maxwidth = min($maxwidth, $maxheight * $original_aspect_ratio);
2463 $maxheight = min($maxheight, $maxwidth / $original_aspect_ratio);
2464 //echo $maxwidth.'x'.$maxheight.'<hr>';
2467 $this->thumbnail_image_width = $maxwidth;
2468 $this->thumbnail_image_height = $maxheight;
2469 $this->thumbnail_width = $maxwidth;
2470 $this->thumbnail_height = $maxheight;
2472 $this->FixedAspectRatio();
2475 $this->thumbnail_width = max(1, floor($this->thumbnail_width));
2476 $this->thumbnail_height = max(1, floor($this->thumbnail_height));
2481 function CreateGDoutput() {
2482 $this->CalculateThumbnailDimensions();
2484 // Create the GD image (either true-color or 256-color, depending on GD version)
2485 $this->gdimg_output = phpthumb_functions::ImageCreateFunction($this->thumbnail_width, $this->thumbnail_height);
2487 // Images that have transparency must have the background filled with the configured 'bg' color
2488 // otherwise the transparent color will appear as black
2489 ImageSaveAlpha($this->gdimg_output, true);
2490 if ($this->is_alpha && phpthumb_functions::gd_version() >= 2) {
2492 ImageAlphaBlending($this->gdimg_output, false);
2493 $output_full_alpha = phpthumb_functions::ImageColorAllocateAlphaSafe($this->gdimg_output, 255, 255, 255, 127);
2494 ImageFilledRectangle($this->gdimg_output, 0, 0, $this->thumbnail_width, $this->thumbnail_height, $output_full_alpha);
2498 $current_transparent_color = ImageColorTransparent($this->gdimg_source);
2499 if ($this->bg || (@$current_transparent_color >= 0)) {
2501 $this->config_background_hexcolor = ($this->bg ? $this->bg : $this->config_background_hexcolor);
2502 if (!phpthumb_functions::IsHexColor($this->config_background_hexcolor)) {
2503 return $this->ErrorImage('Invalid hex color string "'.$this->config_background_hexcolor.'" for parameter "bg"');
2505 $background_color = phpthumb_functions::ImageHexColorAllocate($this->gdimg_output, $this->config_background_hexcolor);
2506 ImageFilledRectangle($this->gdimg_output, 0, 0, $this->thumbnail_width, $this->thumbnail_height, $background_color);
2511 $this->DebugMessage('CreateGDoutput() returning canvas "'.$this->thumbnail_width.'x'.$this->thumbnail_height.'"', __FILE__, __LINE__);
2515 function SetOrientationDependantWidthHeight() {
2516 $this->DebugMessage('SetOrientationDependantWidthHeight() starting with "'.$this->source_width.'"x"'.$this->source_height.'"', __FILE__, __LINE__);
2517 if ($this->source_height > $this->source_width) {
2519 $this->w = phpthumb_functions::OneOfThese($this->wp, $this->w, $this->ws, $this->wl);
2520 $this->h = phpthumb_functions::OneOfThese($this->hp, $this->h, $this->hs, $this->hl);
2521 } elseif ($this->source_height < $this->source_width) {
2523 $this->w = phpthumb_functions::OneOfThese($this->wl, $this->w, $this->ws, $this->wp);
2524 $this->h = phpthumb_functions::OneOfThese($this->hl, $this->h, $this->hs, $this->hp);
2527 $this->w = phpthumb_functions::OneOfThese($this->ws, $this->w, $this->wl, $this->wp);
2528 $this->h = phpthumb_functions::OneOfThese($this->hs, $this->h, $this->hl, $this->hp);
2530 //$this->w = round($this->w ? $this->w : (($this->h && $this->source_height) ? $this->h * $this->source_width / $this->source_height : $this->w));
2531 //$this->h = round($this->h ? $this->h : (($this->w && $this->source_width) ? $this->w * $this->source_height / $this->source_width : $this->h));
2532 $this->DebugMessage('SetOrientationDependantWidthHeight() setting w="'.intval($this->w).'", h="'.intval($this->h).'"', __FILE__, __LINE__);
2536 function ExtractEXIFgetImageSize() {
2537 $this->DebugMessage('starting ExtractEXIFgetImageSize()', __FILE__, __LINE__);
2539 if (is_resource($this->gdimg_source)) {
2541 $this->source_width = ImageSX($this->gdimg_source);
2542 $this->source_height = ImageSY($this->gdimg_source);
2544 $this->SetOrientationDependantWidthHeight();
2546 } elseif ($this->rawImageData && !$this->sourceFilename) {
2548 $this->DebugMessage('bypassing EXIF and GetImageSize sections because $this->rawImageData is set and $this->sourceFilename is not set', __FILE__, __LINE__);
2552 if (is_null($this->getimagesizeinfo)) {
2553 $this->getimagesizeinfo = @GetImageSize($this->sourceFilename);
2556 if (!empty($this->getimagesizeinfo)) {
2558 $this->getimagesizeinfo['filesize'] = @filesize($this->sourceFilename);
2559 } elseif (!$this->rawImageData) {
2560 $this->DebugMessage('GetImageSize("'.$this->sourceFilename.'") failed', __FILE__, __LINE__);
2563 if ($this->config_prefer_imagemagick) {
2564 if ($this->ImageMagickThumbnailToGD()) {
2567 $this->DebugMessage('ImageMagickThumbnailToGD() failed', __FILE__, __LINE__);
2570 $this->source_width = $this->getimagesizeinfo[0];
2571 $this->source_height = $this->getimagesizeinfo[1];
2573 $this->SetOrientationDependantWidthHeight();
2575 if (phpthumb_functions::version_compare_replacement(phpversion(), '4.2.0', '>=') && function_exists('exif_read_data')) {
2576 $this->exif_raw_data = @exif_read_data($this->sourceFilename, 0, true);
2578 if (function_exists('exif_thumbnail') && ($this->getimagesizeinfo[2] == 2)) {
2579 // Extract EXIF info from JPEGs
2581 $this->exif_thumbnail_width = '';
2582 $this->exif_thumbnail_height = '';
2583 $this->exif_thumbnail_type = '';
2585 // The parameters width, height and imagetype are available since PHP v4.3.0
2586 if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=')) {
2588 $this->exif_thumbnail_data = @exif_thumbnail($this->sourceFilename, $this->exif_thumbnail_width, $this->exif_thumbnail_height, $this->exif_thumbnail_type);
2592 // older versions of exif_thumbnail output an error message but NOT return false on failure
2594 $this->exif_thumbnail_data = exif_thumbnail($this->sourceFilename);
2595 $exit_thumbnail_error = ob_get_contents();
2597 if (!$exit_thumbnail_error && $this->exif_thumbnail_data) {
2599 if ($gdimg_exif_temp = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data, false)) {
2600 $this->exif_thumbnail_width = ImageSX($gdimg_exif_temp);
2601 $this->exif_thumbnail_height = ImageSY($gdimg_exif_temp);
2602 $this->exif_thumbnail_type = 2; // (2 == JPEG) before PHP v4.3.0 only JPEG format EXIF thumbnails are returned
2603 unset($gdimg_exif_temp);
2605 return $this->ErrorImage('Failed - $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data) in '.__FILE__.' on line '.__LINE__);
2612 } elseif (!function_exists('exif_thumbnail')) {
2614 $this->DebugMessage('exif_thumbnail() does not exist, cannot extract EXIF thumbnail', __FILE__, __LINE__);
2619 $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__);
2621 // see if EXIF thumbnail can be used directly with no processing
2622 if ($this->config_use_exif_thumbnail_for_speed && $this->exif_thumbnail_data) {
2625 $source_ar = $this->source_width / $this->source_height;
2626 $exif_ar = $this->exif_thumbnail_width / $this->exif_thumbnail_height;
2627 if (number_format($source_ar, 2) != number_format($exif_ar, 2)) {
2628 $this->DebugMessage('not using EXIF thumbnail because $source_ar != $exif_ar ('.$source_ar.' != '.$exif_ar.')', __FILE__, __LINE__);
2631 if ($this->w && ($this->w != $this->exif_thumbnail_width)) {
2632 $this->DebugMessage('not using EXIF thumbnail because $this->w != $this->exif_thumbnail_width ('.$this->w.' != '.$this->exif_thumbnail_width.')', __FILE__, __LINE__);
2635 if ($this->h && ($this->h != $this->exif_thumbnail_height)) {
2636 $this->DebugMessage('not using EXIF thumbnail because $this->h != $this->exif_thumbnail_height ('.$this->h.' != '.$this->exif_thumbnail_height.')', __FILE__, __LINE__);
2639 $CannotBeSetParameters = array('sx', 'sy', 'sh', 'sw', 'far', 'bg', 'bc', 'fltr', 'phpThumbDebug');
2640 foreach ($CannotBeSetParameters as $dummy => $parameter) {
2641 if ($this->$parameter) {
2647 $this->DebugMessage('setting $this->gdimg_source = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data)', __FILE__, __LINE__);
2648 $this->gdimg_source = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data);
2649 $this->source_width = ImageSX($this->gdimg_source);
2650 $this->source_height = ImageSY($this->gdimg_source);
2655 if (($this->config_max_source_pixels > 0) && (($this->source_width * $this->source_height) > $this->config_max_source_pixels)) {
2657 // Source image is larger than would fit in available PHP memory.
2658 // If ImageMagick is installed, use it to generate the thumbnail.
2659 // Else, if an EXIF thumbnail is available, use that as the source image.
2660 // Otherwise, no choice but to fail with an error message
2661 $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__);
2662 if (!$this->config_prefer_imagemagick && $this->ImageMagickThumbnailToGD()) {
2663 // excellent, we have a thumbnailed source image
2672 function SetCacheFilename() {
2673 if (!is_null($this->cache_filename)) {
2674 $this->DebugMessage('$this->cache_filename already set, skipping SetCacheFilename()', __FILE__, __LINE__);
2677 $this->setOutputFormat();
2678 $this->setCacheDirectory();
2679 if (!$this->config_cache_directory) {
2680 $this->DebugMessage('SetCacheFilename() failed because $this->config_cache_directory is empty', __FILE__, __LINE__);
2684 if (!$this->sourceFilename && !$this->rawImageData && $this->src) {
2685 $this->sourceFilename = $this->ResolveFilenameToAbsolute($this->src);
2688 if ($this->config_cache_default_only_suffix && $this->sourceFilename) {
2689 // simplified cache filenames:
2690 // only use default parameters in phpThumb.config.php
2691 // substitute source filename into * in $this->config_cache_default_only_suffix
2692 // (eg: '*_thumb' becomes 'picture_thumb.jpg')
2693 if (strpos($this->config_cache_default_only_suffix, '*') === false) {
2694 $this->DebugMessage('aborting simplified caching filename because no * in "'.$this->config_cache_default_only_suffix.'"', __FILE__, __LINE__);
2696 eregi('(.+)(\.[a-z0-9]+)?$', basename($this->sourceFilename), $matches);
2697 $this->cache_filename = $this->config_cache_directory.DIRECTORY_SEPARATOR.rawurlencode(str_replace('*', @$matches[1], $this->config_cache_default_only_suffix)).'.'.strtolower($this->thumbnailFormat);
2702 $this->cache_filename = '';
2704 $this->cache_filename .= '_new'.strtolower(md5($this->new));
2705 } elseif ($this->md5s) {
2706 // source image MD5 hash provided
2707 $this->DebugMessage('SetCacheFilename() _raw set from $this->md5s = "'.$this->md5s.'"', __FILE__, __LINE__);
2708 $this->cache_filename .= '_raw'.$this->md5s;
2709 } elseif (!$this->src && $this->rawImageData) {
2710 $this->DebugMessage('SetCacheFilename() _raw set from md5($this->rawImageData) = "'.md5($this->rawImageData).'"', __FILE__, __LINE__);
2711 $this->cache_filename .= '_raw'.strtolower(md5($this->rawImageData));
2713 $this->DebugMessage('SetCacheFilename() _src set from md5($this->sourceFilename) "'.$this->sourceFilename.'" = "'.md5($this->sourceFilename).'"', __FILE__, __LINE__);
2714 $this->cache_filename .= '_src'.strtolower(md5($this->sourceFilename));
2716 if (@$_SERVER['HTTP_REFERER'] && $this->config_nooffsitelink_enabled) {
2717 $parsed_url1 = @parse_url(@$_SERVER['HTTP_REFERER']);
2718 $parsed_url2 = @parse_url('http://'.@$_SERVER['HTTP_HOST']);
2719 if (@$parsed_url1['host'] && @$parsed_url2['host'] && ($parsed_url1['host'] != $parsed_url2['host'])) {
2720 // include "_offsite" only if nooffsitelink_enabled and if referrer doesn't match the domain of the current server
2721 $this->cache_filename .= '_offsite';
2725 $ParametersString = '';
2726 if ($this->fltr && is_array($this->fltr)) {
2727 $ParametersString .= '_fltr'.implode('_fltr', $this->fltr);
2729 $FilenameParameters1 = array('ar', 'bg', 'bc', 'far', 'sx', 'sy', 'sw', 'sh', 'zc');
2730 foreach ($FilenameParameters1 as $dummy => $key) {
2732 $ParametersString .= '_'.$key.$this->$key;
2735 $FilenameParameters2 = array('h', 'w', 'wl', 'wp', 'ws', 'hp', 'hs', 'xto', 'ra', 'iar', 'aoe', 'maxb');
2736 foreach ($FilenameParameters2 as $dummy => $key) {
2738 $ParametersString .= '_'.$key.intval($this->$key);
2741 if ($this->thumbnailFormat == 'jpeg') {
2742 // only JPEG output has variable quality option
2743 $ParametersString .= '_q'.intval($this->thumbnailQuality);
2745 $this->DebugMessage('SetCacheFilename() _par set from md5('.$ParametersString.')', __FILE__, __LINE__);
2746 $this->cache_filename .= '_par'.strtolower(md5($ParametersString));
2749 // source image MD5 hash provided
2750 // do not source image modification date --
2751 // cached image will be used even if file was modified or removed
2752 } elseif (!$this->config_cache_source_filemtime_ignore_remote && eregi('^(f|ht)tps?\://', $this->src)) {
2753 $this->cache_filename .= '_dat'.intval(phpthumb_functions::filedate_remote($this->src));
2754 } elseif (!$this->config_cache_source_filemtime_ignore_local && $this->src && !$this->rawImageData) {
2755 $this->cache_filename .= '_dat'.intval(@filemtime($this->sourceFilename));
2758 $this->cache_filename .= '.'.strtolower($this->thumbnailFormat);
2760 $this->cache_filename = $this->config_cache_directory.DIRECTORY_SEPARATOR.$this->config_cache_prefix.rawurlencode($this->cache_filename);
2765 function ImageCreateFromFilename($filename) {
2766 // try to create GD image source directly via GD, if possible,
2767 // rather than buffering to memory and creating with ImageCreateFromString
2768 $ImageCreateWasAttempted = false;
2771 $this->DebugMessage('starting ImageCreateFromFilename('.$filename.')', __FILE__, __LINE__);
2773 if ($filename && ($getimagesizeinfo = @GetImageSize($filename))) {
2774 if ($this->config_max_source_pixels > 0) {
2775 if (($getimagesizeinfo[0] * $getimagesizeinfo[1]) < $this->config_max_source_pixels) {
2776 $ImageCreateFromFunction = array(
2777 1 => 'ImageCreateFromGIF',
2778 2 => 'ImageCreateFromJPEG',
2779 3 => 'ImageCreateFromPNG',
2780 15 => 'ImageCreateFromWBMP',
2782 $this->DebugMessage('ImageCreateFromFilename found ($getimagesizeinfo[2]=='.@$getimagesizeinfo[2].')', __FILE__, __LINE__);
2783 switch (@$getimagesizeinfo[2]) {
2788 $ImageCreateFromFunctionName = $ImageCreateFromFunction[$getimagesizeinfo[2]];
2789 if (function_exists($ImageCreateFromFunctionName)) {
2790 $this->DebugMessage('Calling '.$ImageCreateFromFunctionName.'('.$filename.')', __FILE__, __LINE__);
2791 $ImageCreateWasAttempted = true;
2792 $gd_image = @$ImageCreateFromFunctionName($filename);
2794 $this->DebugMessage('NOT calling '.$ImageCreateFromFunctionName.'('.$filename.') because !function_exists('.$ImageCreateFromFunctionName.')', __FILE__, __LINE__);
2801 case 7: // TIFF (LE)
2802 case 8: // TIFF (BE)
2810 $this->DebugMessage('No built-in image creation function for image type "'.@$getimagesizeinfo[2].'" ($getimagesizeinfo[2])', __FILE__, __LINE__);
2814 $this->DebugMessage('Unknown value for $getimagesizeinfo[2]: "'.@$getimagesizeinfo[2].'"', __FILE__, __LINE__);
2818 $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__);
2822 $this->DebugMessage('empty $filename or GetImageSize('.$filename.') failed', __FILE__, __LINE__);
2826 // cannot create from filename, attempt to create source image with ImageCreateFromString, if possible
2827 if ($ImageCreateWasAttempted) {
2828 $this->DebugMessage(@$ImageCreateFromFunctionName.'() was attempted but FAILED', __FILE__, __LINE__);
2830 $this->DebugMessage('Populating $rawimagedata', __FILE__, __LINE__);
2832 if ($fp = @fopen($filename, 'rb')) {
2833 $filesize = filesize($filename);
2835 $blockreads = ceil($filesize / $blocksize);
2836 for ($i = 0; $i < $blockreads; $i++) {
2837 $rawimagedata .= fread($fp, $blocksize);
2841 $this->DebugMessage('cannot fopen('.$filename.')', __FILE__, __LINE__);
2843 if ($rawimagedata) {
2844 $this->DebugMessage('attempting ImageCreateFromStringReplacement($rawimagedata ('.strlen($rawimagedata).' bytes), true)', __FILE__, __LINE__);
2845 $gd_image = $this->ImageCreateFromStringReplacement($rawimagedata, true);
2851 function SourceImageToGD() {
2852 if (is_resource($this->gdimg_source)) {
2853 $this->source_width = ImageSX($this->gdimg_source);
2854 $this->source_height = ImageSY($this->gdimg_source);
2855 $this->DebugMessage('skipping SourceImageToGD() because $this->gdimg_source is already a resource ('.$this->source_width.'x'.$this->source_height.')', __FILE__, __LINE__);
2858 $this->DebugMessage('starting SourceImageToGD()', __FILE__, __LINE__);
2860 if (!$this->exif_thumbnail_data) {
2861 $this->DebugMessage('Not using EXIF thumbnail data because $this->exif_thumbnail_data is empty', __FILE__, __LINE__);
2864 if (ini_get('safe_mode')) {
2865 if (($this->config_max_source_pixels > 0) && (($this->source_width * $this->source_height) > $this->config_max_source_pixels)) {
2866 $this->DebugMessage('Using EXIF thumbnail data because source image too large and safe_mode enabled', __FILE__, __LINE__);
2872 if (!$this->config_use_exif_thumbnail_for_speed) {
2873 $this->DebugMessage('Not using EXIF thumbnail data because $this->config_use_exif_thumbnail_for_speed is FALSE', __FILE__, __LINE__);
2876 if (($this->thumbnailCropX != 0) || ($this->thumbnailCropY != 0)) {
2877 $this->DebugMessage('Not using EXIF thumbnail data because source cropping is enabled ('.$this->thumbnailCropX.','.$this->thumbnailCropY.')', __FILE__, __LINE__);
2880 if (($this->w > $this->exif_thumbnail_width) || ($this->h > $this->exif_thumbnail_height)) {
2881 $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__);
2884 $source_ar = $this->source_width / $this->source_height;
2885 $exif_ar = $this->exif_thumbnail_width / $this->exif_thumbnail_height;
2886 if (number_format($source_ar, 2) != number_format($exif_ar, 2)) {
2887 $this->DebugMessage('not using EXIF thumbnail because $source_ar != $exif_ar ('.$source_ar.' != '.$exif_ar.')', __FILE__, __LINE__);
2892 // EXIF thumbnail exists, and is equal to or larger than destination thumbnail, and will be use as source image
2893 $this->DebugMessage('Trying to use EXIF thumbnail as source image', __FILE__, __LINE__);
2895 if ($gdimg_exif_temp = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data, false)) {
2897 $this->DebugMessage('Successfully using EXIF thumbnail as source image', __FILE__, __LINE__);
2898 $this->gdimg_source = $gdimg_exif_temp;
2899 $this->source_width = $this->exif_thumbnail_width;
2900 $this->source_height = $this->exif_thumbnail_height;
2901 $this->thumbnailCropW = $this->source_width;
2902 $this->thumbnailCropH = $this->source_height;
2906 $this->DebugMessage('$this->ImageCreateFromStringReplacement($this->exif_thumbnail_data, false) failed', __FILE__, __LINE__);
2911 if (!$this->gdimg_source) {
2913 if ($this->md5s && ($this->md5s != phpthumb_functions::md5_file_safe($this->sourceFilename))) {
2914 return $this->ErrorImage('$this->md5s != md5($rawimagedata)'."\n".'"'.$this->md5s.'" != '."\n".'"'.phpthumb_functions::md5_file_safe($this->sourceFilename).'"');
2916 switch (@$this->getimagesizeinfo[2]) {
2919 // GIF or PNG input file may have transparency
2920 $this->is_alpha = true;
2924 //$this->gdimg_source = $this->ImageCreateFromFilename($this->sourceFilename, $this->rawImageData);
2925 $this->gdimg_source = $this->ImageCreateFromFilename($this->sourceFilename);
2927 //if ($this->md5s && ($this->md5s != md5($this->rawImageData))) {
2928 // return $this->ErrorImage('$this->md5s != md5($this->rawImageData)'."\n".'"'.$this->md5s.'" != '."\n".'"'.md5($this->rawImageData).'"');
2931 if (!$this->gdimg_source) {
2932 $this->DebugMessage('$this->gdimg_source is still empty', __FILE__, __LINE__);
2934 if ($this->ImageMagickThumbnailToGD()) {
2936 // excellent, we have a thumbnailed source image
2937 $this->DebugMessage('ImageMagickThumbnailToGD() succeeded', __FILE__, __LINE__);
2941 $this->DebugMessage('ImageMagickThumbnailToGD() failed', __FILE__, __LINE__);
2944 $gd_info = gd_info();
2945 $GDreadSupport = false;
2946 //switch (substr($this->rawImageData, 0, 3)) {
2948 // $imageHeader = 'Content-Type: image/gif';
2949 // $GDreadSupport = (bool) @$gd_info['GIF Read Support'];
2951 // case "\xFF\xD8\xFF":
2952 // $imageHeader = 'Content-Type: image/jpeg';
2953 // $GDreadSupport = (bool) @$gd_info['JPG Support'];
2955 // case "\x89".'PN':
2956 // $imageHeader = 'Content-Type: image/png';
2957 // $GDreadSupport = (bool) @$gd_info['PNG Support'];
2960 switch (@$this->getimagesizeinfo[2]) {
2962 $imageHeader = 'Content-Type: image/gif';
2963 $GDreadSupport = (bool) @$gd_info['GIF Read Support'];
2966 $imageHeader = 'Content-Type: image/jpeg';
2967 $GDreadSupport = (bool) @$gd_info['JPG Support'];
2970 $imageHeader = 'Content-Type: image/png';
2971 $GDreadSupport = (bool) @$gd_info['PNG Support'];
2975 // cannot create image for whatever reason (maybe ImageCreateFromJPEG et al are not available?)
2976 // and ImageMagick is not available either, no choice but to output original (not resized/modified) data and exit
2977 if ($this->config_error_die_on_source_failure) {
2978 $this->ErrorImage('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');
2980 //$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__);
2981 //if (!$this->phpThumbDebug) {
2982 // header($imageHeader);
2983 // echo $this->rawImageData;
2990 //switch (substr($this->rawImageData, 0, 2)) {
2992 switch (@$this->getimagesizeinfo[2]) {
2995 if (!@include_once(dirname(__FILE__).'/phpthumb.bmp.php')) {
2997 return $this->ErrorImage('include_once('.dirname(__FILE__).'/phpthumb.bmp.php) failed');
3000 if ($fp = @fopen($this->sourceFilename, 'rb')) {
3001 $this->rawImageData = '';
3002 while (!feof($fp)) {
3003 $this->rawImageData .= fread($fp, 32768);
3007 $phpthumb_bmp = new phpthumb_bmp();
3008 if ($this->gdimg_source = $phpthumb_bmp->phpthumb_bmp2gd($this->rawImageData, (phpthumb_functions::gd_version() >= 2.0))) {
3009 $this->DebugMessage('$phpthumb_bmp->phpthumb_bmp2gd() succeeded', __FILE__, __LINE__);
3012 return $this->ErrorImage($this->ImageMagickVersion() ? 'ImageMagick failed on BMP source conversion' : 'phpthumb_bmp2gd() failed');
3015 //switch (substr($this->rawImageData, 0, 4)) {
3016 // case 'II'."\x2A\x00":
3017 // case 'MM'."\x00\x2A":
3020 return $this->ErrorImage($this->ImageMagickVersion() ? 'ImageMagick failed on TIFF source conversion' : 'ImageMagick is unavailable and phpThumb() does not support TIFF source images without it');
3023 //case "\xD7\xCD\xC6\x9A":
3024 // return $this->ErrorImage($this->ImageMagickVersion() ? 'ImageMagick failed on WMF source conversion' : 'ImageMagick is unavailable and phpThumb() does not support WMF source images without it');
3028 if (!$this->gdimg_source) {
3029 $HeaderFourBytes = '';
3030 if ($fp = @fopen($this->sourceFilename, 'rb')) {
3031 $HeaderFourBytes = fread($fp, 4);
3034 if ($HeaderFourBytes == "\xD7\xCD\xC6\x9A") {
3035 return $this->ErrorImage($this->ImageMagickVersion() ? 'ImageMagick failed on WMF source conversion' : 'ImageMagick is unavailable and phpThumb() does not support WMF source images without it');
3037 return $this->ErrorImage('Unknown image type identified by "'.substr($HeaderFourBytes, 0, 4).'" ('.phpthumb_functions::HexCharDisplay(substr($this->rawImageData, 0, 4)).') in SourceImageToGD()');
3043 if (!$this->gdimg_source) {
3044 if ($gdimg_exif_temp = $this->ImageCreateFromStringReplacement($this->exif_thumbnail_data, false)) {
3045 $this->DebugMessage('All other attempts failed, but successfully using EXIF thumbnail as source image', __FILE__, __LINE__);
3046 $this->gdimg_source = $gdimg_exif_temp;
3047 // override allow-enlarging setting if EXIF thumbnail is the only source available
3048 // otherwise thumbnails larger than the EXIF thumbnail will be created at EXIF size
3054 $this->source_width = ImageSX($this->gdimg_source);
3055 $this->source_height = ImageSY($this->gdimg_source);
3060 function phpThumbDebugVarDump($var) {
3061 if (is_null($var)) {
3063 } elseif (is_bool($var)) {
3064 return ($var ? 'TRUE' : 'FALSE');
3065 } elseif (is_string($var)) {
3066 return 'string('.strlen($var).')'.str_repeat(' ', max(0, 3 - strlen(strlen($var)))).' "'.$var.'"';
3067 } elseif (is_int($var)) {
3068 return 'integer '.$var;
3069 } elseif (is_float($var)) {
3070 return 'float '.$var;
3071 } elseif (is_array($var)) {
3074 $vardumpoutput = ob_get_contents();
3076 return strtr($vardumpoutput, "\n\r\t", ' ');
3078 return gettype($var);
3081 function phpThumbDebug() {
3082 if ($this->config_disable_debug) {
3083 return $this->ErrorImage('phpThumbDebug disabled');
3086 $FunctionsExistance = array('exif_thumbnail', 'gd_info', 'image_type_to_mime_type', 'ImageCopyResampled', 'ImageCopyResized', 'ImageCreate', 'ImageCreateFromString', 'ImageCreateTrueColor', 'ImageIsTrueColor', 'ImageRotate', 'ImageTypes', 'version_compare', 'ImageCreateFromGIF', 'ImageCreateFromJPEG', 'ImageCreateFromPNG', 'ImageCreateFromWBMP', 'ImageCreateFromXBM', 'ImageCreateFromXPM', 'ImageCreateFromString', 'ImageCreateFromGD', 'ImageCreateFromGD2', 'ImageCreateFromGD2Part', 'ImageJPEG', 'ImageGIF', 'ImagePNG', 'ImageWBMP');
3087 $ParameterNames = array('src', 'new', 'w', 'h', 'f', 'q', 'sx', 'sy', 'sw', 'sh', 'far', 'bg', 'bc', 'file', 'goto', 'err', 'xto', 'ra', 'ar', 'aoe', 'iar', 'maxb');
3088 $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');
3089 $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');
3091 $DebugOutput = array();
3092 $DebugOutput[] = 'phpThumb() version = '.$this->phpthumb_version;
3093 $DebugOutput[] = 'phpversion() = '.@phpversion();
3094 $DebugOutput[] = 'PHP_OS = '.PHP_OS;
3095 $DebugOutput[] = '__FILE__ = '.__FILE__;
3096 $DebugOutput[] = 'realpath(.) = '.@realpath('.');
3097 $DebugOutput[] = '$_SERVER[PHP_SELF] = '.@$_SERVER['PHP_SELF'];
3098 $DebugOutput[] = '$_SERVER[HOST_NAME] = '.@$_SERVER['HOST_NAME'];
3099 $DebugOutput[] = '$_SERVER[HTTP_REFERER] = '.@$_SERVER['HTTP_REFERER'];
3100 $DebugOutput[] = '$_SERVER[QUERY_STRING] = '.@$_SERVER['QUERY_STRING'];
3101 $DebugOutput[] = '$_SERVER[PATH_INFO] = '.@$_SERVER['PATH_INFO'];
3102 $DebugOutput[] = '$_SERVER[DOCUMENT_ROOT] = '.@$_SERVER['DOCUMENT_ROOT'];
3103 $DebugOutput[] = 'getenv(DOCUMENT_ROOT) = '.@getenv('DOCUMENT_ROOT');
3104 $DebugOutput[] = '';
3106 $DebugOutput[] = 'get_magic_quotes_gpc() = '.$this->phpThumbDebugVarDump(@get_magic_quotes_gpc());
3107 $DebugOutput[] = 'get_magic_quotes_runtime() = '.$this->phpThumbDebugVarDump(@get_magic_quotes_runtime());
3108 $DebugOutput[] = 'error_reporting() = '.$this->phpThumbDebugVarDump(error_reporting());
3109 $DebugOutput[] = 'ini_get(error_reporting) = '.$this->phpThumbDebugVarDump(@ini_get('error_reporting'));
3110 $DebugOutput[] = 'ini_get(display_errors) = '.$this->phpThumbDebugVarDump(@ini_get('display_errors'));
3111 $DebugOutput[] = 'ini_get(allow_url_fopen) = '.$this->phpThumbDebugVarDump(@ini_get('allow_url_fopen'));
3112 $DebugOutput[] = 'ini_get(disable_functions) = '.$this->phpThumbDebugVarDump(@ini_get('disable_functions'));
3113 $DebugOutput[] = 'ini_get(safe_mode) = '.$this->phpThumbDebugVarDump(@ini_get('safe_mode'));
3114 $DebugOutput[] = 'ini_get(open_basedir) = '.$this->phpThumbDebugVarDump(@ini_get('open_basedir'));
3115 $DebugOutput[] = 'ini_get(memory_limit) = '.$this->phpThumbDebugVarDump(@ini_get('memory_limit'));
3116 $DebugOutput[] = 'ini_get(max_execution_time) = '.$this->phpThumbDebugVarDump(@ini_get('max_execution_time'));
3117 $DebugOutput[] = 'get_cfg_var(memory_limit) = '.$this->phpThumbDebugVarDump(@get_cfg_var('memory_limit'));
3118 $DebugOutput[] = 'memory_get_usage() = '.(function_exists('memory_get_usage') ? $this->phpThumbDebugVarDump(@memory_get_usage()) : 'n/a');
3119 $DebugOutput[] = '';
3121 $DebugOutput[] = '$this->config_prefer_imagemagick = '.$this->phpThumbDebugVarDump($this->config_prefer_imagemagick);
3122 $DebugOutput[] = '$this->config_imagemagick_path = '.$this->phpThumbDebugVarDump($this->config_imagemagick_path);
3123 $DebugOutput[] = '$this->ImageMagickWhichConvert() = '.$this->ImageMagickWhichConvert();
3124 $IMpathUsed = ($this->config_imagemagick_path ? $this->config_imagemagick_path : $this->ImageMagickWhichConvert());
3125 $DebugOutput[] = '[actual ImageMagick path used] = '.$this->phpThumbDebugVarDump($IMpathUsed);
3126 $DebugOutput[] = 'file_exists([actual ImageMagick path used]) = '.$this->phpThumbDebugVarDump(@file_exists($IMpathUsed));
3127 $DebugOutput[] = 'ImageMagickVersion(false) = '.$this->ImageMagickVersion(false);
3128 $DebugOutput[] = 'ImageMagickVersion(true) = '.$this->ImageMagickVersion(true);
3129 $DebugOutput[] = '';
3131 $DebugOutput[] = '$this->config_cache_directory = '.$this->phpThumbDebugVarDump($this->config_cache_directory);
3132 $DebugOutput[] = '$this->config_cache_disable_warning = '.$this->phpThumbDebugVarDump($this->config_cache_disable_warning);
3133 $DebugOutput[] = '$this->config_cache_maxage = '.$this->phpThumbDebugVarDump($this->config_cache_maxage);
3134 $DebugOutput[] = '$this->config_cache_maxsize = '.$this->phpThumbDebugVarDump($this->config_cache_maxsize);
3135 $DebugOutput[] = '$this->config_cache_maxfiles = '.$this->phpThumbDebugVarDump($this->config_cache_maxfiles);
3136 $DebugOutput[] = '$this->config_cache_force_passthru = '.$this->phpThumbDebugVarDump($this->config_cache_force_passthru);
3137 $DebugOutput[] = '$this->cache_filename = '.$this->phpThumbDebugVarDump($this->cache_filename);
3138 $DebugOutput[] = 'is_readable($this->config_cache_directory) = '.$this->phpThumbDebugVarDump(@is_readable($this->config_cache_directory));
3139 $DebugOutput[] = 'is_writable($this->config_cache_directory) = '.$this->phpThumbDebugVarDump(@is_writable($this->config_cache_directory));
3140 $DebugOutput[] = 'is_readable($this->cache_filename) = '.$this->phpThumbDebugVarDump(@is_readable($this->cache_filename));
3141 $DebugOutput[] = 'is_writable($this->cache_filename) = '.(@file_exists($this->cache_filename) ? $this->phpThumbDebugVarDump(@is_writable($this->cache_filename)) : 'n/a');
3142 $DebugOutput[] = '';
3144 foreach ($ConfigVariableNames as $dummy => $varname) {
3145 $varname = 'config_'.$varname;
3146 $value = $this->$varname;
3147 $DebugOutput[] = '$this->'.str_pad($varname, 37, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
3149 $DebugOutput[] = '';
3150 foreach ($OtherVariableNames as $dummy => $varname) {
3151 $value = $this->$varname;
3152 $DebugOutput[] = '$this->'.str_pad($varname, 27, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
3154 $DebugOutput[] = 'strlen($this->rawImageData) = '.strlen(@$this->rawImageData);
3155 $DebugOutput[] = 'strlen($this->exif_thumbnail_data) = '.strlen(@$this->exif_thumbnail_data);
3156 $DebugOutput[] = '';
3158 foreach ($ParameterNames as $dummy => $varname) {
3159 $value = $this->$varname;
3160 $DebugOutput[] = '$this->'.str_pad($varname, 4, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
3162 $DebugOutput[] = '';
3164 foreach ($FunctionsExistance as $dummy => $functionname) {
3165 $DebugOutput[] = 'builtin_function_exists('.$functionname.')'.str_repeat(' ', 23 - strlen($functionname)).' = '.$this->phpThumbDebugVarDump(phpthumb_functions::builtin_function_exists($functionname));
3167 $DebugOutput[] = '';
3169 $gd_info = gd_info();
3170 foreach ($gd_info as $key => $value) {
3171 $DebugOutput[] = 'gd_info.'.str_pad($key, 34, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
3173 $DebugOutput[] = '';
3175 $exif_info = phpthumb_functions::exif_info();
3176 foreach ($exif_info as $key => $value) {
3177 $DebugOutput[] = 'exif_info.'.str_pad($key, 26, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
3179 $DebugOutput[] = '';
3181 if ($ApacheLookupURIarray = phpthumb_functions::ApacheLookupURIarray(dirname(@$_SERVER['PHP_SELF']))) {
3182 foreach ($ApacheLookupURIarray as $key => $value) {
3183 $DebugOutput[] = 'ApacheLookupURIarray.'.str_pad($key, 15, ' ', STR_PAD_RIGHT).' = '.$this->phpThumbDebugVarDump($value);
3186 $DebugOutput[] = 'ApacheLookupURIarray() -- FAILED';
3188 $DebugOutput[] = '';
3190 if (isset($_GET) && is_array($_GET)) {
3191 foreach ($_GET as $key => $value) {
3192 $DebugOutput[] = '$_GET['.$key.']'.str_repeat(' ', 30 - strlen($key)).'= '.$this->phpThumbDebugVarDump($value);
3195 if (isset($_POST) && is_array($_POST)) {
3196 foreach ($_POST as $key => $value) {
3197 $DebugOutput[] = '$_POST['.$key.']'.str_repeat(' ', 29 - strlen($key)).'= '.$this->phpThumbDebugVarDump($value);
3200 $DebugOutput[] = '';
3202 $DebugOutput[] = '$this->debugmessages:';
3203 foreach ($this->debugmessages as $dummy => $errorstring) {
3204 $DebugOutput[] = ' * '.$errorstring;
3206 $DebugOutput[] = '';
3208 $DebugOutput[] = '$this->debugtiming:';
3209 foreach ($this->debugtiming as $timestamp => $timingstring) {
3210 $DebugOutput[] = ' * '.$timestamp.' '.$timingstring;
3212 $DebugOutput[] = ' * Total processing time: '.number_format(max(array_keys($this->debugtiming)) - min(array_keys($this->debugtiming)), 6);
3214 return $this->ErrorImage(implode("\n", $DebugOutput), 700, 500, true);
3217 function ErrorImage($text, $width=0, $height=0, $forcedisplay=false) {
3218 $width = ($width ? $width : $this->config_error_image_width);
3219 $height = ($height ? $height : $this->config_error_image_height);
3221 $text = 'phpThumb() v'.$this->phpthumb_version."\n\n".$text;
3222 if ($this->config_disable_debug) {
3223 $text = 'Error messages disabled';
3226 $this->DebugMessage($text, __FILE__, __LINE__);
3227 if ($this->phpThumbDebug && !$forcedisplay) {
3230 if (!$this->config_error_die_on_error && !$forcedisplay) {
3231 $this->fatalerror = $text;
3234 if ($this->config_error_silent_die_on_error) {
3237 if ($this->err || $this->config_error_message_image_default) {
3238 // Show generic custom error image instead of error message
3239 // for use on production sites where you don't want debug messages
3240 if ($this->err == 'showerror') {
3241 // fall through and actually show error message even if default error image is set
3243 header('Location: '.($this->err ? $this->err : $this->config_error_message_image_default));
3247 $this->setOutputFormat();
3248 if (!$this->thumbnailFormat || (phpthumb_functions::gd_version() < 1)) {
3249 $this->thumbnailFormat = 'text';
3251 if (@$this->thumbnailFormat == 'text') {
3252 // bypass all GD functions and output text error message
3253 die('<pre>'.$text.'</pre>');
3256 $FontWidth = ImageFontWidth($this->config_error_fontsize);
3257 $FontHeight = ImageFontHeight($this->config_error_fontsize);
3259 $LinesOfText = explode("\n", @wordwrap($text, floor($width / $FontWidth), "\n", true));
3260 $height = max($height, count($LinesOfText) * $FontHeight);
3264 if (phpthumb_functions::version_compare_replacement(phpversion(), '4.3.0', '>=') && headers_sent($headers_file, $headers_line)) {
3266 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>';
3268 } elseif (headers_sent()) {
3270 echo "\n".'**Headers already sent, dumping error message as text:**<br><pre>'."\n\n".$text."\n".'</pre>';
3272 } elseif ($gdimg_error = ImageCreate($width, $height)) {
3274 $background_color = phpthumb_functions::ImageHexColorAllocate($gdimg_error, $this->config_error_bgcolor, true);
3275 $text_color = phpthumb_functions::ImageHexColorAllocate($gdimg_error, $this->config_error_textcolor, true);
3276 ImageFilledRectangle($gdimg_error, 0, 0, $width, $height, $background_color);
3278 foreach ($LinesOfText as $dummy => $line) {
3279 ImageString($gdimg_error, $this->config_error_fontsize, 2, $lineYoffset, $line, $text_color);
3280 $lineYoffset += $FontHeight;
3282 if (function_exists('ImageTypes')) {
3283 $imagetypes = ImageTypes();
3284 if ($imagetypes & IMG_PNG) {
3285 header('Content-Type: image/png');
3286 ImagePNG($gdimg_error);
3287 } elseif ($imagetypes & IMG_GIF) {
3288 header('Content-Type: image/gif');
3289 ImageGIF($gdimg_error);
3290 } elseif ($imagetypes & IMG_JPG) {
3291 header('Content-Type: image/jpeg');
3292 ImageJPEG($gdimg_error);
3293 } elseif ($imagetypes & IMG_WBMP) {
3294 header('Content-Type: image/wbmp');
3295 ImageWBMP($gdimg_error);
3298 ImageDestroy($gdimg_error);
3301 if (!headers_sent()) {
3302 echo "\n".'**Failed to send graphical error image, dumping error message as text:**<br>'."\n\n".$text;
3308 function ImageCreateFromStringReplacement(&$RawImageData, $DieOnErrors=false) {
3309 // there are serious bugs in the non-bundled versions of GD which may cause
3310 // PHP to segfault when calling ImageCreateFromString() - avoid if at all possible
3311 // when not using a bundled version of GD2
3312 if (phpthumb_functions::gd_is_bundled()) {
3313 return @ImageCreateFromString($RawImageData);
3315 if (ini_get('safe_mode')) {
3316 $this->DebugMessage('ImageCreateFromStringReplacement() failed: cannot create temp file in SAFE_MODE', __FILE__, __LINE__);
3320 switch (substr($RawImageData, 0, 3)) {
3322 $ICFSreplacementFunctionName = 'ImageCreateFromGIF';
3324 case "\xFF\xD8\xFF":
3325 $ICFSreplacementFunctionName = 'ImageCreateFromJPEG';
3328 $ICFSreplacementFunctionName = 'ImageCreateFromPNG';
3331 $this->DebugMessage('ImageCreateFromStringReplacement() failed: unknown fileformat signature "'.phpthumb_functions::HexCharDisplay(substr($RawImageData, 0, 3)).'"', __FILE__, __LINE__);
3335 if ($tempnam = $this->phpThumb_tempnam()) {
3336 if ($fp_tempnam = @fopen($tempnam, 'wb')) {
3337 fwrite($fp_tempnam, $RawImageData);
3338 fclose($fp_tempnam);
3339 if (($ICFSreplacementFunctionName == 'ImageCreateFromGIF') && !function_exists($ICFSreplacementFunctionName)) {
3341 // Need to create from GIF file, but ImageCreateFromGIF does not exist
3343 if (!@include_once(dirname(__FILE__).'/phpthumb.gif.php')) {
3344 $ErrorMessage = 'Failed to include required file "'.dirname(__FILE__).'/phpthumb.gif.php" in '.__FILE__.' on line '.__LINE__;
3345 $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
3348 // gif_loadFileToGDimageResource() cannot read from raw data, write to file first
3349 if ($tempfilename = $this->phpThumb_tempnam()) {
3350 if ($fp_tempfile = @fopen($tempfilename, 'wb')) {
3351 fwrite($fp_tempfile, $RawImageData);
3352 fclose($fp_tempfile);
3353 $gdimg_source = gif_loadFileToGDimageResource($tempfilename);
3354 unlink($tempfilename);
3355 return $gdimg_source;
3358 $ErrorMessage = 'Failed to open tempfile in '.__FILE__.' on line '.__LINE__;
3359 $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
3362 $ErrorMessage = 'Failed to open generate tempfile name in '.__FILE__.' on line '.__LINE__;
3363 $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
3366 } elseif (function_exists($ICFSreplacementFunctionName) && ($gdimg_source = @$ICFSreplacementFunctionName($tempnam))) {
3370 return $gdimg_source;
3372 } else { // GD functions not available
3374 if (isset($_GET['phpThumbDebug'])) {
3375 $this->phpThumbDebug();
3376 } elseif (!headers_sent()) {
3377 // base64-encoded error image in GIF format
3378 $ERROR_NOGD = 'R0lGODlhIAAgALMAAAAAABQUFCQkJDY2NkZGRldXV2ZmZnJycoaGhpSUlKWlpbe3t8XFxdXV1eTk5P7+/iwAAAAAIAAgAAAE/vDJSau9WILtTAACUinDNijZtAHfCojS4W5H+qxD8xibIDE9h0OwWaRWDIljJSkUJYsN4bihMB8th3IToAKs1VtYM75cyV8sZ8vygtOE5yMKmGbO4jRdICQCjHdlZzwzNW4qZSQmKDaNjhUMBX4BBAlmMywFSRWEmAI6b5gAlhNxokGhooAIK5o/pi9vEw4Lfj4OLTAUpj6IabMtCwlSFw0DCKBoFqwAB04AjI54PyZ+yY3TD0ss2YcVmN/gvpcu4TOyFivWqYJlbAHPpOntvxNAACcmGHjZzAZqzSzcq5fNjxFmAFw9iFRunD1epU6tsIPmFCAJnWYE0FURk7wJDA0MTKpEzoWAAskiAAA7';
3379 header('Content-Type: image/gif');
3380 echo base64_decode($ERROR_NOGD);
3382 echo '*** ERROR: No PHP-GD support available ***';
3388 $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';
3389 $this->DebugMessage($ErrorMessage, __FILE__, __LINE__);
3393 $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';
3395 if ($DieOnErrors && $ErrorMessage) {
3396 return $this->ErrorImage($ErrorMessage);
3401 function ImageResizeFunction(&$dst_im, &$src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH) {
3402 $this->DebugMessage('ImageResizeFunction($o, $s, '.$dstX.', '.$dstY.', '.$srcX.', '.$srcY.', '.$dstW.', '.$dstH.', '.$srcW.', '.$srcH.')', __FILE__, __LINE__);
3403 if (phpthumb_functions::gd_version() >= 2.0) {
3404 if ($this->config_disable_imagecopyresampled) {
3405 return phpthumb_functions::ImageCopyResampleBicubic($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
3407 return ImageCopyResampled($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
3409 return ImageCopyResized($dst_im, $src_im, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
3412 function phpThumb_tempnam() {
3413 $tempnam = realpath(tempnam($this->config_temp_directory, 'pThumb'));
3414 $this->DebugMessage('phpThumb_tempnam() returning "'.$tempnam.'"', __FILE__, __LINE__);
3418 function DebugMessage($message, $file='', $line='') {
3419 $this->debugmessages[] = $message.($file ? ' in file "'.(basename($file) ? basename($file) : $file).'"' : '').($line ? ' on line '.$line : '');
3423 function DebugTimingMessage($message, $file='', $line='', $timestamp=0) {
3425 $timestamp = array_sum(explode(' ', microtime()));
3427 $this->debugtiming[number_format($timestamp, 6, '.', '')] = ': '.$message.($file ? ' in file "'.(basename($file) ? basename($file) : $file).'"' : '').($line ? ' on line '.$line : '');