root/afridex/plugins/Flutter/phpthumb.class.php

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