source: trunk/www.guidonia.net/wp/wp-content/plugins/ferdinand-wordbook/phpthumb/phpthumb.class.php@ 44

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