source: trunk/lib/ImageThumb.inc.php @ 120

Last change on this file since 120 was 120, checked in by scdev, 18 years ago

Completed GD integration to ImageThumb?

File size: 28.6 KB
Line 
1<?php
2/**
3 * ImageThumb.inc.php
4 * Code by Strangecode :: www.strangecode.com :: This document contains copyrighted information
5 *
6 * @author   Quinn Comendant <quinn@strangecode.com>
7 * @requires Netpbm <http://sourceforge.net/projects/netpbm/> and libjpeg or GD.
8 * @version  2.0
9 */
10
11// Image resize options.
12define('IMAGETHUMB_FIT_WIDTH', 1);
13define('IMAGETHUMB_FIT_HEIGHT', 2);
14define('IMAGETHUMB_FIT_LARGER', 3);
15define('IMAGETHUMB_STRETCH', 4);
16define('IMAGETHUMB_NO_SCALE', 5);
17define('IMAGETHUMB_METHOD_NETPBM', 6);
18define('IMAGETHUMB_METHOD_GD', 7);
19
20class ImageThumb {
21   
22    // General object parameters.
23    var $_params = array(
24        // The location for images to create thumbnails from.
25        'source_dir' => null,
26
27        // Existing files will be overwritten when there is a name conflict?
28        'allow_overwriting' => false,
29
30        // The file permissions of the uploaded files. Remember, files will be owned by the web server user.
31        'dest_file_perms' => 0600,
32
33        // Permissions of autocreated directories. Must be at least 0700 with owner=apache.
34        'dest_dir_perms' => 0777,
35
36        // Require file to have one of the following file name extentions.
37        'valid_file_extensions' => array('jpg', 'jpeg', 'gif', 'png'),
38       
39        // Method to use for resizing. (IMAGETHUMB_METHOD_NETPBM or IMAGETHUMB_METHOD_GD)
40        'resize_method' => IMAGETHUMB_METHOD_NETPBM,
41
42        // Netpbm and libjpeg binary locations.
43        'anytopnm_binary' => '/usr/bin/anytopnm',
44        'pnmscale_binary' => '/usr/bin/pnmscale',
45        'cjpeg_binary' => '/usr/bin/cjpeg',
46
47        // Which messages do we pass to raiseMsg? Use one of the MSG_* constants or false to disable.
48        'display_messages' => MSG_ALL,
49    );
50   
51    // Default image size specs.
52    var $default_image_specs = array(
53        // The destination for an image thumbnail size. Path relative to source_dir (eg: ../thumbs).
54        'dest_dir' => null,
55       
56        // Destination file types. (IMG_JPG, IMG_PNG, IMG_GIF, IMG_WBMP)
57        'dest_file_type' => IMG_JPG,
58
59        // Destination file types. ('jpg', 'png', 'gif', 'wbmp')
60        'dest_file_extention' => 'jpg',
61       
62        // Type of scaling to perform, and sizes used to calculate max dimentions.
63        'scaling_type' => IMAGETHUMB_FIT_LARGER,
64        'width' => null,
65        'height' => null,
66
67        // Percentage quality of image compression output 0-100.
68        'quality' => 65,
69
70        // Create progressive jpegs?
71        'progressive' => false,
72
73        // If using GD method, apply sharpen filter. Requires PHP > 5.1.
74        'sharpen' => true,
75       
76        // Integers between 1-100, useful values are 65-85.
77        'sharpen_value' => 75,
78
79        // If source image is smaller than thumbnail, allow upscaling?
80        'allow_upscaling' => false,
81
82        // If thumb exists and filesize is smaller than this, do not overwrite the thumb.
83        'keep_filesize' => null,
84    );
85
86    // Final specifications for image sizes, set with setSpec().
87    var $image_specs = array();
88
89    /**
90     * Set (or overwrite existing) parameters by passing an array of new parameters.
91     *
92     * @access public
93     * @param  array    $params     Array of parameters (key => val pairs).
94     */
95    function setParam($params)
96    {
97        if (isset($params) && is_array($params)) {
98
99            // Enforce valid upload_path parameter.
100            if (isset($params['source_dir'])) {
101                $params['source_dir'] = realpath($params['source_dir']);
102                // Must be directory.
103                if (!is_dir($params['source_dir'])) {
104                    App::logMsg(sprintf('Source directory invalid: %s', $params['source_dir']), LOG_ERR, __FILE__, __LINE__);
105                    trigger_error(sprintf('Source directory invalid: %s', $params['source_dir']), E_USER_ERROR);
106                }
107                // Must be readable.
108                if (!is_readable($params['source_dir'])) {
109                    App::logMsg(sprintf('Source directory not readable: %s', $params['source_dir']), LOG_ERR, __FILE__, __LINE__);
110                    trigger_error(sprintf('Source directory not readable: %s', $params['source_dir']), E_USER_ERROR);
111                }
112            }
113
114            // Merge new parameters with old overriding only those passed.
115            $this->_params = array_merge($this->_params, $params);
116        } else {
117            App::logMsg(sprintf('Parameters are not an array: %s', $params), LOG_ERR, __FILE__, __LINE__);
118        }
119    }
120
121    /**
122     * Return the value of a parameter, if it exists.
123     *
124     * @access public
125     * @param string $param        Which parameter to return.
126     * @return mixed               Configured parameter value.
127     */
128    function getParam($param)
129    {
130        if (isset($this->_params[$param])) {
131            return $this->_params[$param];
132        } else {
133            App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
134            return null;
135        }
136    }
137
138    /**
139     * Set the specification of thumbnails.
140     *
141     * @access  public
142     * @param   array $spec The specifications for a size of output image.
143     */
144    function setSpec($spec, $index=null)
145    {
146        // A little sanity checking.
147        if (!isset($spec['dest_dir']) || '' == $spec['dest_dir']) {
148            App::logMsg('setSpec error: dest_dir not specified.', LOG_ERR, __FILE__, __LINE__);
149        }
150        if (isset($spec['dest_file_type'])) {
151            switch ($spec['dest_file_type']) {
152            case IMG_JPG :
153                if (imagetypes() & IMG_JPG == 0) {
154                    App::logMsg(sprintf('IMG_JPG is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
155                }
156                $spec['dest_file_extention'] = 'jpg';
157                break;
158            case IMG_PNG :
159                if (imagetypes() & IMG_PNG == 0) {
160                    App::logMsg(sprintf('IMG_PNG is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
161                }
162                $spec['dest_file_extention'] = 'png';
163                break;
164            case IMG_GIF :
165                if (imagetypes() & IMG_GIF == 0) {
166                    App::logMsg(sprintf('IMG_GIF is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
167                }
168                $spec['dest_file_extention'] = 'gif';
169                break;
170            case IMG_WBMP :
171                if (imagetypes() & IMG_WBMP == 0) {
172                    App::logMsg(sprintf('IMG_WBMP is not supported by this version of PHP GD.', null), LOG_ERR, __FILE__, __LINE__);
173                }
174                $spec['dest_file_extention'] = 'wbmp';
175                break;
176            default :
177                App::logMsg(sprintf('Invalid dest_file_type: %s', $spec['dest_file_type']), LOG_ERR, __FILE__, __LINE__);
178                break;
179            }
180        }
181        if (!isset($spec['width']) || !is_int($spec['width'])) {
182            App::logMsg('setSpec error: width not specified.', LOG_ERR, __FILE__, __LINE__);
183        }
184        if (!isset($spec['height']) || !is_int($spec['height'])) {
185            App::logMsg('setSpec error: height not specified.', LOG_ERR, __FILE__, __LINE__);
186        }
187        if (isset($spec['quality']) && IMG_JPG != $spec['dest_file_type']) {
188            App::logMsg('The "quality" specification is not used unless IMG_JPG is the dest_file_type.', LOG_INFO, __FILE__, __LINE__);
189        }
190        if (isset($spec['progressive']) && IMG_JPG != $spec['dest_file_type']) {
191            App::logMsg('The "progressive" specification is not used unless IMG_JPG is the dest_file_type.', LOG_INFO, __FILE__, __LINE__);
192        }
193       
194        if (isset($index) && isset($this->image_specs[$index])) {
195            // Merge with previous.
196            $this->image_specs[$index] = array_merge($this->image_specs[$index], $spec);
197        } else {
198            // Merge with defaults.
199            $this->image_specs[] = array_merge($this->default_image_specs, $spec);           
200        }
201    }
202
203    /**
204     * Process an entire directory of images.
205     *
206     * @access  public
207     * @return  bool true on success, false on failure.
208     */
209    function processAll()
210    {
211        // Ensure we have a source.
212        if ('' == $this->getParam('source_dir')) {
213            App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
214            return false;
215        }
216
217        // Get all files in source directory.
218        $dir_handle = opendir($this->getParam('source_dir'));
219        while ($dir_handle && ($file = readdir($dir_handle)) !== false) {
220            // If the file name does not start with a dot (. or .. or .htaccess).
221            if (!preg_match('/^\./', $file) && in_array(strtolower(substr($file, strrpos($file, '.') + 1)), $this->getParam('valid_file_extensions'))) {
222                $files[] = $file;
223            }
224        }
225
226        // Process each found file.
227        if (is_array($files) && !empty($files)) {
228            $return_val = 0;
229            foreach ($files as $file_name) {
230                $return_val += $this->processFile($file_name);
231            }
232            $this->_raiseMsg(sprintf(_("Resized %s images."), sizeof($files)), MSG_SUCCESS, __FILE__, __LINE__);
233            return 0 === $return_val;
234        } else {
235            App::logMsg(sprintf('No images found to thumbnail in directory %s.', $this->getParam('source_dir')), LOG_NOTICE, __FILE__, __LINE__);
236            return false;
237        }
238    }
239
240    /**
241     * Generate thumbnails for the specified file.
242     *
243     * @access  public
244     * @param   string $file_name Name of file with extention.
245     * @return  bool true on success, false on failure.
246     */
247    function processFile($file_name)
248    {
249        // Source file determinted by provided file_name.
250        $source_file = realpath(sprintf('%s/%s', $this->getParam('source_dir'), $file_name));
251       
252        // Ensure we have a source.
253        if (sizeof($this->image_specs) < 1) {
254            App::logMsg(sprintf('Image specifications not set before processing.'), LOG_ERR, __FILE__, __LINE__);
255            return false;
256        }
257
258        // Ensure we have a source.
259        if ('' == $this->getParam('source_dir')) {
260            App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
261            return false;
262        }
263
264        // Confirm source image exists.
265        if (!file_exists($source_file)) {
266            $this->_raiseMsg(sprintf(_("Image resizing failed: source image %s was not found."), $file_name), MSG_ERR, __FILE__, __LINE__);
267            App::logMsg(sprintf('Source image not found: %s', $file_name), LOG_ALERT, __FILE__, __LINE__);
268            return false;
269        }
270
271        // Confirm source image is readable.
272        if (!is_readable($source_file)) {
273            $this->_raiseMsg(sprintf(_("Image resizing failed: source image %s is not readable."), $file_name), MSG_ERR, __FILE__, __LINE__);
274            App::logMsg(sprintf('Source image not readable: %s', $file_name), LOG_ALERT, __FILE__, __LINE__);
275            return false;
276        }
277
278        // Confirm source image contains data.
279        if (filesize($source_file) <= 0) {
280            $this->_raiseMsg(sprintf(_("Image resizing failed: source image %s is zero bytes."), $file_name), MSG_ERR, __FILE__, __LINE__);
281            App::logMsg(sprintf('Source image is zero bytes: %s', $file_name), LOG_ALERT, __FILE__, __LINE__);
282            return false;
283        }
284
285        // Confirm source image has a valid file extension.
286        if (!$this->_validFileExtension($file_name)) {
287            $this->_raiseMsg(sprintf(_("Image resizing failed: source image %s not a valid type. It must have one of the following file name extensions: %s"), $file_name, join(', ', $this->getParam('valid_file_extensions'))), MSG_ERR, __FILE__, __LINE__);
288            App::logMsg(sprintf('Image resizing failed: source image not of valid type: %s', $file_name), LOG_ERR, __FILE__, __LINE__);
289            return false;
290        }
291
292        // Ensure destination directories are created. This will only be called once per page load.
293        $this->_createDestDirs();
294       
295        // To keep this script running even if user tries to stop browser.
296        ignore_user_abort(true);
297        if (!ini_get('safe_mode')) {
298            set_time_limit(300);
299        }
300
301        // This remains zero until something goes wrong.
302        $return_val = 0;
303
304        foreach ($this->image_specs as $spec) {
305           
306            // Destination filename uses the extention defined by dest_file_extention.
307            $dest_file = realpath(sprintf('%s/%s/%s.%s', $this->getParam('source_dir'), $spec['dest_dir'], substr($file_name, 0, strrpos($file_name, '.')), $spec['dest_file_extention']));
308
309            // Skip existing thumbnails with file size below $spec['keep_filesize'].
310            if (isset($spec['keep_filesize']) && file_exists($dest_file)) {
311                $file_size = filesize($dest_file);
312                if (false !== $file_size && $file_size < $spec['keep_filesize']) {
313                    App::logMsg(sprintf('Skipping thumbnail %s. File already exists and file size is less than %s bytes.', $spec['dest_dir'] . '/' . $file_name, $spec['keep_filesize']), LOG_DEBUG, __FILE__, __LINE__);
314                    continue;
315                }
316            }
317
318            // Determine if original file size is smaller than specified thumbnail size. Do not scale-up if $spec['allow_upscaling'] config is set to false.
319            $image_size = getimagesize($source_file);
320            if ($image_size['0'] <= $spec['width'] && $image_size['1'] <= $spec['height'] && !$spec['allow_upscaling']) {
321                $spec['scaling_type'] = IMAGETHUMB_NO_SCALE;
322                App::logMsg(sprintf('Image %s smaller than specified %s thumbnail size. Keeping original size.', $file_name, $spec['dest_dir']), LOG_DEBUG, __FILE__, __LINE__);
323            }
324
325            // DO IT! Based on available method.
326            if (IMAGETHUMB_METHOD_NETPBM === $this->getParam('resize_method') && file_exists($this->getParam('anytopnm_binary')) && file_exists($this->getParam('pnmscale_binary')) && file_exists($this->getParam('cjpeg_binary'))) {
327                // Resize using Netpbm binaries.
328                App::logMsg(sprintf('Resizing with Netpbm...', null), LOG_DEBUG, __FILE__, __LINE__);
329                $return_val += $this->_resizeWithNetpbm($source_file, $dest_file, $spec);
330            } else if (IMAGETHUMB_METHOD_GD === $this->getParam('resize_method') && extension_loaded('gd')) {
331                // Resize with GD.
332                App::logMsg(sprintf('Resizing with GD...', null), LOG_DEBUG, __FILE__, __LINE__);
333                $return_val += $this->_resizeWithGD($source_file, $dest_file, $spec);
334            } else {
335                App::logMsg(sprintf('Image thumbnailing failed. Neither Netpbm or GD is available.', null), LOG_DEBUG, __FILE__, __LINE__);
336                return false;
337            }
338        }
339
340        // If > 0, there was a problem thumb-nailing.
341        return 0 === $return_val;
342    }
343   
344    /*
345    * Use the Netpbm and libjpg cjpeg tools to generate a rescaled compressed image.
346    * This is the preferred method over GD which has (supposedly) less quality.
347    *
348    * @access   private
349    * @param    string  $source_file    Full path to source image file.
350    * @param    string  $dest_file      Full path to destination image file.
351    * @param    array   $spec           Array of image size specifications.
352    * @return   int                     0 if no error, n > 0 if errors.
353    * @author   Quinn Comendant <quinn@strangecode.com>
354    * @version  1.0
355    * @since    19 May 2006 13:55:46
356    */
357    function _resizeWithNetpbm($source_file, $dest_file, $spec)
358    {
359        // Define pnmscale arguments.
360        switch ($spec['scaling_type']) {
361        case IMAGETHUMB_FIT_WIDTH :
362            $pnmscale_args = sprintf(' -width %s ', escapeshellarg($spec['width']));
363            break;
364        case IMAGETHUMB_FIT_HEIGHT :
365            $pnmscale_args = sprintf(' -height %s ', escapeshellarg($spec['height']));
366            break;
367        case IMAGETHUMB_FIT_LARGER :
368            $pnmscale_args = sprintf(' -xysize %s %s ', escapeshellarg($spec['width']), escapeshellarg($spec['height']));
369            break;
370        case IMAGETHUMB_STRETCH :
371            $pnmscale_args = sprintf(' -width %s -height %s ', escapeshellarg($spec['width']), escapeshellarg($spec['height']));
372            break;
373        case IMAGETHUMB_NO_SCALE :
374        default :
375            $pnmscale_args = ' 1 ';
376            break;
377        }
378
379        // Define cjpeg arguments.
380        $cjpeg_args = sprintf(' -optimize -quality %s ', escapeshellarg($spec['quality']));
381        $cjpeg_args .= (true === $spec['progressive']) ? ' -progressive ' : '';
382
383        // Format the command that creates the thumbnail.
384        $command = sprintf('%s %s | %s %s | %s %s > %s/%s',
385            escapeshellcmd($this->getParam('anytopnm_binary')),
386            escapeshellcmd($source_file),
387            escapeshellcmd($this->getParam('pnmscale_binary')),
388            escapeshellcmd($pnmscale_args),
389            escapeshellcmd($this->getParam('cjpeg_binary')),
390            escapeshellcmd($cjpeg_args),
391            escapeshellcmd($dest_file),
392            escapeshellcmd($file_name)
393        );
394        App::logMsg(sprintf('ImageThumb Netpbm command: %s', $command), LOG_DEBUG, __FILE__, __LINE__);
395       
396        // Execute!
397        exec($command, $output, $return_val);
398
399        if (0 === $return_val) {
400            // Success!
401            // Make the thumbnail writable so the user can delete it over ftp without being 'apache'.
402            chmod($dest_file, $this->getParam('dest_file_perms'));
403            App::logMsg(sprintf('Successfully resized image %s', $spec['dest_dir'] . '/' . basename($dest_file), $return_val), LOG_DEBUG, __FILE__, __LINE__);
404        } else {
405            // An error occurred.
406            App::logMsg(sprintf('Image %s failed resizing with return value: %s%s', $spec['dest_dir'] . '/' . basename($dest_file), $return_val, empty($output) ? '' : ' (' . getDump($output) . ')'), LOG_ERR, __FILE__, __LINE__);
407        }
408
409        // Return from the command will be > 0 if there was an error.
410        return $return_val;
411    }
412
413    /*
414    * Use PHP's built-in GD tools to generate a rescaled compressed image.
415    *
416    * @access   private
417    * @param    string  $source_file    Full path to source image file.
418    * @param    string  $dest_file      Full path to destination image file.
419    * @param    array   $spec           Array of image size specifications.
420    * @return   int                     0 if no error, n > 0 if errors.
421    * @author   Quinn Comendant <quinn@strangecode.com>
422    * @version  1.0
423    * @since    19 May 2006 15:46:02
424    */
425    function _resizeWithGD($source_file, $dest_file, $spec)
426    {
427        // Get original file dimensions and type.
428        list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_file);
429
430        // Define destination image dimentions.
431        switch ($spec['scaling_type']) {
432        case IMAGETHUMB_FIT_WIDTH :
433            $dest_image_width = $spec['width'];
434            $dest_image_height = $source_image_height * ($spec['width'] / $source_image_width);
435            break;
436        case IMAGETHUMB_FIT_HEIGHT :
437            $dest_image_height = $spec['height'];
438            $dest_image_width = $source_image_width * ($spec['height'] / $source_image_height);
439            break;
440        case IMAGETHUMB_FIT_LARGER :
441            if (($source_image_width * ($spec['height'] / $source_image_height)) <= $spec['width']) {
442                // Height is larger.
443                $dest_image_height = $spec['height'];
444                $dest_image_width = $source_image_width * ($spec['height'] / $source_image_height);
445            } else {
446                // Width is larger.
447                $dest_image_width = $spec['width'];
448                $dest_image_height = $source_image_height * ($spec['width'] / $source_image_width);
449            }
450            break;
451        case IMAGETHUMB_STRETCH :
452            $dest_image_width = $spec['width'];
453            $dest_image_height = $spec['height'];
454            break;
455        case IMAGETHUMB_NO_SCALE :
456        default :
457            $dest_image_width = $source_image_width;
458            $dest_image_height = $source_image_height;
459            break;
460        }
461
462        // Create source image data in memory.
463        switch ($source_image_type) {
464        case IMAGETYPE_JPEG :
465            $source_image_resource = imagecreatefromjpeg($source_file);
466            break;
467        case IMAGETYPE_PNG :
468            $source_image_resource = imagecreatefrompng($source_file);
469            break;
470        case IMAGETYPE_GIF :
471            $source_image_resource = imagecreatefromgif($source_file);
472            break;
473        case IMAGETYPE_WBMP :
474            $source_image_resource = imagecreatefromwbmp($source_file);
475        default :
476            App::logMsg(sprintf('Source image type %s not supported.', $source_image_type), LOG_WARNING, __FILE__, __LINE__);
477            return 1;
478            break;
479        }
480        if (!$source_image_resource) {
481            App::logMsg(sprintf('Error creating %s image in memory from %s', $source_image_type, $source_file), LOG_WARNING, __FILE__, __LINE__);
482            return 1;
483        }
484       
485        // Create destination image data in memory.
486        $dest_image_resource = imagecreatetruecolor($dest_image_width, $dest_image_height);
487
488        // Resample!
489        if (!imagecopyresampled($dest_image_resource, $source_image_resource, 0, 0, 0, 0, $dest_image_width, $dest_image_height, $source_image_width, $source_image_height)) {
490            App::logMsg(sprintf('Error resampling image %s', $source_file), LOG_WARNING, __FILE__, __LINE__);
491            return 1;
492        }
493       
494        // Sharpen image using a custom filter matrix.
495        if (phpversion() > '5.1' && true === $spec['sharpen'] && $spec['sharpen_value'] > 0) {
496            $sharpen_value = round((((48 - 10) / (100 - 1)) * (100 - $spec['sharpen_value'])) + 10);
497            imageconvolution($dest_image_resource, array(array(-1,-1,-1),array(-1,$sharpen_value,-1),array(-1,-1,-1)), ($sharpen_value - 8), 0);
498        }
499
500        // Save image.
501        $return_val = true;
502        switch ($spec['dest_file_type']) {
503        case IMG_JPG :
504            imageinterlace($dest_image_resource, (true == $spec['progressive'] ? 1 : 0));
505            $return_val = imagejpeg($dest_image_resource, $dest_file, $spec['quality']);
506            break;
507        case IMG_PNG :
508            $return_val = imagepng($dest_image_resource, $dest_file);
509            break;
510        case IMG_GIF :
511            $return_val = imagegif($dest_image_resource, $dest_file);
512            break;
513        case IMG_WBMP :
514            $return_val = imagewbmp($dest_image_resource, $dest_file);
515            break;
516        default :
517            App::logMsg(sprintf('Destination image type %s not supported for image %s.', $spec['dest_file_type'], $dest_file), LOG_WARNING, __FILE__, __LINE__);
518            return 1;
519            break;
520        }
521
522        if ($return_val) {
523            // Success!
524            // Make the thumbnail writable so the user can delete it over ftp without being 'apache'.
525            chmod($dest_file, $this->getParam('dest_file_perms'));
526            App::logMsg(sprintf('Successfully resized image %s', $dest_file), LOG_DEBUG, __FILE__, __LINE__);
527            return 0;
528        } else {
529            // An error occurred.
530            App::logMsg(sprintf('Image %s failed resizing.', $dest_file), LOG_ERR, __FILE__, __LINE__);
531            return 1;
532        }
533    }
534
535    /**
536     * Delete the thumbnails for the specified file name.
537     *
538     * @access  public
539     * @param   string $file_name The file name to delete, with extention.
540     * @return  bool true on success, false on failure.
541     */
542    function deleteThumbs($file_name)
543    {
544        // Ensure we have a source.
545        if ('' == $this->getParam('source_dir')) {
546            App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
547            return false;
548        }
549
550        $return_val = 0;
551        foreach ($this->image_specs as $spec) {
552            $dest_file = realpath(sprintf('%s/%s/%s.%s', $this->getParam('source_dir'), $spec['dest_dir'], substr($file_name, 0, strrpos($file_name, '.')), $spec['dest_file_extention']));
553            if (file_exists($dest_file)) {
554                if (!unlink($dest_file)) {
555                    $return_val++;
556                    App::logMsg(sprintf(_("Delete thumbs failed: %s"), $dest_file), LOG_WARNING, __FILE__, __LINE__);
557                }
558            }
559        }
560        $this->_raiseMsg(sprintf(_("The thumbnails for file <strong>%s</strong> have been deleted."), $file_name), MSG_SUCCESS, __FILE__, __LINE__);
561        return 0 === $return_val;
562    }
563
564    /**
565     * Delete the source image with the specified file name.
566     *
567     * @access  public
568     * @param   string $file_name The file name to delete, with extention.
569     * @return  bool true on success, false on failure.
570     */
571    function deleteOriginal($file_name)
572    {
573        // Ensure we have a source.
574        if ('' == $this->getParam('source_dir')) {
575            App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
576            return false;
577        }
578
579        $source_file = realpath(sprintf('%s/%s', $this->getParam('source_dir'), $file_name));
580        if (!unlink($source_file)) {
581            App::logMsg(sprintf(_("Delete original failed: %s"), $source_file), LOG_WARNING, __FILE__, __LINE__);
582            return false;
583        }
584        $this->_raiseMsg(sprintf(_("The original file <strong>%s</strong> has been deleted."), $file_name), MSG_SUCCESS, __FILE__, __LINE__);
585        return true;
586    }
587
588    /**
589     * Returns true if file exists.
590     *
591     * @access  public
592     * @param   string $file_name The file name to test, with extention.
593     * @return  bool true on success, false on failure.
594     */
595    function exists($file_name)
596    {
597        // Ensure we have a source.
598        if ('' == $this->getParam('source_dir')) {
599            App::logMsg(sprintf('Source directory not set before processing.'), LOG_ERR, __FILE__, __LINE__);
600            return false;
601        }
602
603        $source_file = realpath(sprintf('%s/%s', $this->getParam('source_dir'), $file_name));
604        return file_exists($source_file);
605    }
606
607    /**
608     * Tests if extention of $file_name is in the array valid_file_extensions.
609     *
610     * @access  public
611     * @param   string  $file_name  A file name.
612     * @return  bool    True on success, false on failure.
613     */
614    function _validFileExtension($file_name)
615    {
616        preg_match('/.*?\.(\w+)$/i', $file_name, $ext);
617        return in_array(strtolower($ext[1]), $this->getParam('valid_file_extensions'));
618    }
619
620    /**
621     * Make directory for each specified thumbnail size, if it doesn't exist.
622     *
623     * @access  public
624     * @return  bool true on success, false on failure.
625     */
626    function _createDestDirs()
627    {
628        static $already_checked = false;
629
630        if (!$already_checked) {
631            // Ensure we have a source.
632            if ('' == $this->getParam('source_dir')) {
633                App::logMsg(sprintf('Source directory not set before creating destination directories.'), LOG_ERR, __FILE__, __LINE__);
634                return false;
635            }
636       
637            // Loop through specs and ensure all dirs are created.
638            $return_val = 0;
639            foreach ($this->image_specs as $spec) {
640                if (!file_exists($this->getParam('source_dir') . '/' . $spec['dest_dir'])) {
641                    if (!mkdir($this->getParam('source_dir') . '/' . $spec['dest_dir'], $this->getParam('dest_dir_perms'))) {
642                        $return_val++;
643                        App::logMsg(sprintf('mkdir failure: %s', $this->getParam('source_dir') . '/' . $spec['dest_dir']), LOG_ERR, __FILE__, __LINE__);
644                    }
645                }
646            }
647
648            // If > 0, there was a problem creating dest dirs.
649            return 0 === $return_val;
650        }
651
652        $already_checked = true;
653    }
654
655    /**
656     * An alias for App::raiseMsg that only sends messages configured by display_messages.
657     *
658     * @access public
659     *
660     * @param string $message The text description of the message.
661     * @param int    $type    The type of message: MSG_NOTICE,
662     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
663     * @param string $file    __FILE__.
664     * @param string $line    __LINE__.
665     */
666    function _raiseMsg($message, $type, $file, $line)
667    {
668        if ($this->getParam('display_messages') === true || (is_int($this->getParam('display_messages')) && $this->getParam('display_messages') & $type > 0)) {
669            App::raiseMsg($message, $type, $file, $line);
670        }
671    }
672
673} // End of class.
674?>
Note: See TracBrowser for help on using the repository browser.