07.18 php saved
drayen
Tags add more
 
Note
phpThumbComponent

based on : http://bakery.cakephp.org/articles/view/phpthumb-component

  1. <?php
  2. /* $Id$ */
  3. /**
  4. * PhpThumbComponent - A CakePHP Component to use with PhpThumb
  5. * Copyright (C) 2007-2008 Alex McFadyen aka Drayen
  6. *
  7. * @license MIT
  8. */
  9.  
  10. /**
  11. * PhpThumbComponent - A CakePHP Component to use with PhpThumb
  12. * (http://phpthumb.sourceforge.net/)
  13. *
  14. * Based on CakePHP tutorial on : http://bakery.cakephp.org/articles/view/274
  15. *
  16. * This component will allow you to create/display thumbnails as well as have them
  17. * auto generated and cached.
  18. *
  19. * Its set up to allow off site linking.
  20. *
  21. * @package PhpThumbComponent
  22. * @subpackage controllers.components
  23. *
  24. * @author Alex McFadyen aka Drayen
  25. *
  26. * @version 0.1
  27. **/
  28.  
  29. class PhpThumbComponent extends Component{
  30.  
  31.     /**
  32.      * Array of errors
  33.      */
  34.     var $errors = array();
  35.    
  36.     /**
  37.      * preset $_GET string varables, also defines what can be passed in the get string
  38.      */
  39.  
  40.     var $presets = array(
  41.                                 'w'=>null,      // Width
  42.                                 'h'=>null,      // Height
  43.                                 'wp'=>null,   // Width  (Portrait Images Only)
  44.                                 'hp'=>null,   // Height (Portrait Images Only)
  45.                                 'wl'=>null,   // Width  (Landscape Images Only)
  46.                                 'hl'=>null,   // Height (Landscape Images Only)
  47.                                 'ws'=>null,   // Width  (Square Images Only)
  48.                                 'hs'=>null,   // Height (Square Images Only)
  49.                                 'q'=>75,                // jpeg output Quality
  50.                                 'zc'=>0,                // Zoom Crop
  51.                                 'sx'=>null,   // Source crop top-left X position
  52.                                 'sy'=>null,   // Source crop top-left Y position
  53.                                 'sw'=>null,   // Source crop Width
  54.                                 'sh'=>null,   // Source crop Height
  55.                                 'far'=>1,         // Fixed Aspect Ratio
  56.                                 'iar'=>null,        // Ignore Aspect Ratio
  57.                                 'ra'=>null,   // Rotate by Angle
  58.                                 'ar'=>null,   // Auto Rotate X=based on exif data, L=always landscape, P=portrait
  59.                                 'aoe'=>1,         // Allow Uutput Enlargment
  60.                                 'bc'=>null,   // Border Color
  61.                                 'bg'=>'FFFFFF'// Background Colour
  62.                                 'fltr[]'=>null, // FiLTeRs (crazy stuff)
  63.                                 'err'=>null   // default ERRor image filename
  64.                                 );
  65.    
  66.     /**
  67.      * The mime types that are allowed for images
  68.      */
  69.     var $allowed_mime_types = array(IMAGETYPE_JPEG,IMAGETYPE_GIF,IMAGETYPE_PNG);
  70.  
  71.     /**
  72.      * File system location to save thumbnails to. 
  73.      */
  74.     var $cache_location = null;
  75.  
  76.     /**
  77.      * How old the cached image can be before its updated.
  78.      */
  79.     var $max_cache_age = 1; #7776000; #90 days in seconds
  80.    
  81.     /**
  82.      * Size in bytes that the cashe folder can reach before it over writes old images,
  83.      * comment out to disable
  84.      */
  85.     var $max_cache_size = 10485760; //10 * 1024 * 1024;
  86.    
  87.  
  88.     var $controller;
  89.     var $model;
  90.  
  91.     function startup( &$controller ) {
  92.         $this->controller = &$controller;
  93.         if(isset($controller->max_cache_age)){
  94.             $this->max_cache_age = $controller->max_cache_age;
  95.         }      
  96.         $this->cache_location = CACHE.'thumbs'.DS;
  97.     }
  98.  
  99.  
  100.    
  101.     /**
  102.      * Will generate a thumbnail as defined by the presets (or by $_GET vars)
  103.      * and place it in the target. If display = true it will also output the
  104.      * thumbnail.
  105.      *
  106.      * @param string $source the location of the source image (may be relative or absolute)
  107.      * @param string $target the target directory and filename for the generated thumbnail
  108.      * @param bool $overwrite if the target should be overwritten
  109.      * @param bool $display if the image should be displayed
  110.      * @return bool Success?
  111.      * @author Alex McFadyen
  112.      */
  113.     function generateThumbnail($source = null, $target = null, $overwrite = true, $display = false){
  114.  
  115.         $target_dir = substr($target, 0, -(strpos(strrev($target),'/')));
  116.  
  117.         if($source == null OR $target == null){//check correct params are set
  118.             $this->addError("Both source[$source] and target[$target] must be set");
  119.             return false;/*
  120.         }elseif(!is_file($source)){//check source is a file
  121.             $this->addError("Source[$source] is not a valid file");
  122.             return false;*/
  123.         }elseif(in_array($this->ImageTypeToMIMEtype($source), $this->allowed_mime_types)){//and is of allowed type
  124.             $this->addError("Source[$source] is not a valid file type");
  125.             return false;
  126.         }elseif(!is_writable($target_dir)){//check if target directory is writeable
  127.             $this->addError("Can not write to target directory [$target_dir]");
  128.             return false;
  129.         }elseif(is_file($target) AND !$overwrite){//check if target is a file already and not ok to be over written
  130.             $this->addError("Target[$target] exsists and overwrite is not true");
  131.             return false;
  132.         }elseif(is_file($target) AND !is_writable($target)){
  133.             $this->addError("Can not overwrite Target[$target]");
  134.             return false;
  135.         }
  136.  
  137.         //load PhpThumb
  138.         vendor('phpThumb'.DS.'phpthumb.class');
  139.         $phpThumb = new phpThumb();
  140.        
  141.         //set presets
  142.         $phpThumb->config_nohotlink_enabled = false;
  143.         $phpThumb->config_nooffsitelink_enabled = false;
  144.         $phpThumb->config_prefer_imagemagick = true;
  145.         $phpThumb->config_output_format = 'jpeg';
  146.         $phpThumb->config_error_die_on_error = true;
  147.         $phpThumb->config_allow_src_above_docroot = true;
  148.        
  149.        
  150.         //optionals
  151.         if(isset($this->max_cache_size)) $phpThumb->config_cache_maxsize = $this->max_cache_size;
  152.        
  153.         //load in source image
  154.         $phpThumb->setSourceFilename($source);
  155.        
  156.         //load vars from $_GET if they are set
  157.         foreach($this->presets as $key=>$value) {
  158.             if(isset($_GET[$key])) {
  159.                 $phpThumb->setParameter($key, $_GET[$key]);
  160.             } else {
  161.                 if($value !== null) {
  162.                     $phpThumb->setParameter($key, $value);
  163.                 }
  164.             }
  165.         }
  166.        
  167.            
  168.         //create the thumbnail
  169.         if($phpThumb->generateThumbnail()){
  170.             if(!$phpThumb->RenderToFile($target)){
  171.                 $this->addError('Could not render file to: '.$target);
  172.             }elseif($display==true){
  173.                 $phpThumb->OutputThumbnail();   
  174.                 die();//not perfect, i know but it insures cake doenst add extra code after the image.
  175.             }
  176.         } else {
  177.             $this->addError('could not generate thumbnail');
  178.         }
  179.  
  180.         // if we have any errors, remove any thumbnail that was generated and return false
  181.         if(count($this->errors)>0){
  182.             if(file_exists($target)){
  183.                 unlink($target);
  184.             }
  185.             return false;
  186.         } else return true;
  187.     }
  188.    
  189.    
  190.    
  191.     /**
  192.      * Display and/or generate a auto-named thumbnail, based on presets in $_GET.
  193.      *
  194.      * @param string $source the location of the source image (may be relative or absolute)
  195.      * @param bool $forceUpdate if the thumbnal should be refreashed
  196.      * @param bool $display if the image should be displayed
  197.      * @return bool Success?
  198.      * @author Alex McFadyen
  199.      */
  200.     function displayThumbnail($source, $forceUpdate = false, $display = true){
  201.         if($source == null) $source = $_GET['src'];
  202.  
  203.         $cache_filename = $this->cache_location . md5(env('REQUEST_URI')) . '_' . md5($source).'.jpg';
  204.    
  205.         #check the cache'ed image exsists and its new enough and that it needs to be displayed
  206.         if(is_file($cache_filename) //file exsists
  207.                 AND (time() < filectime($cache_filename) + $this->max_cache_age) //not too old
  208.                 AND (is_file($source) ? ( filectime($cache_filename) > filectime($source) ) : true) //cached image is newer than source
  209.                 AND ($display == true)
  210.                 AND !($forceUpdate == true))
  211.             {
  212.  
  213.             header('Content-Type: '.IMAGETYPE_JPEG);
  214.             @readfile($cache_filename);
  215.  
  216.             exit();//not perfect, i know but it insures cake doenst add extra code after the image.
  217.         }else{
  218.             return $this->generateThumbnail($source, $cache_filename, true, $display);
  219.         }
  220.     }
  221.    
  222.     /**
  223.      * Function borrowed form phpThumb libs
  224.      */
  225.     function ImageTypeToMIMEtype($imagetype) {
  226.         if (function_exists('image_type_to_mime_type') && ($imagetype >= 1) && ($imagetype <= 16)) {
  227.             // PHP v4.3.0+
  228.             return image_type_to_mime_type($imagetype);
  229.         }
  230.         static $image_type_to_mime_type = array(
  231.             1  => 'image/gif',                     // IMAGETYPE_GIF
  232.             2  => 'image/jpeg',                    // IMAGETYPE_JPEG
  233.             3  => 'image/png',                     // IMAGETYPE_PNG
  234.             4  => 'application/x-shockwave-flash', // IMAGETYPE_SWF
  235.             5  => 'image/psd',                     // IMAGETYPE_PSD
  236.             6  => 'image/bmp',                     // IMAGETYPE_BMP
  237.             7  => 'image/tiff',                    // IMAGETYPE_TIFF_II (intel byte order)
  238.             8  => 'image/tiff',                    // IMAGETYPE_TIFF_MM (motorola byte order)
  239.             9  => 'application/octet-stream',      // IMAGETYPE_JPC
  240.             10 => 'image/jp2',                     // IMAGETYPE_JP2
  241.             11 => 'application/octet-stream',      // IMAGETYPE_JPX
  242.             12 => 'application/octet-stream',      // IMAGETYPE_JB2
  243.             13 => 'application/x-shockwave-flash', // IMAGETYPE_SWC
  244.             14 => 'image/iff',                     // IMAGETYPE_IFF
  245.             15 => 'image/vnd.wap.wbmp',            // IMAGETYPE_WBMP
  246.             16 => 'image/xbm',                     // IMAGETYPE_XBM
  247.    
  248.             'gif'  => 'image/gif',                 // IMAGETYPE_GIF
  249.             'jpg'  => 'image/jpeg',                // IMAGETYPE_JPEG
  250.             'jpeg' => 'image/jpeg',                // IMAGETYPE_JPEG
  251.             'png'  => 'image/png',                 // IMAGETYPE_PNG
  252.             'bmp'  => 'image/bmp',                 // IMAGETYPE_BMP
  253.             'ico'  => 'image/x-icon',
  254.         );
  255.  
  256.         return (isset($image_type_to_mime_type[$imagetype]) ? $image_type_to_mime_type[$imagetype] : false);
  257.     }
  258.    
  259.     /**
  260.      * Clears the current set cache directory of expired files (or all) images
  261.      *
  262.      * @param bool $clearAll if set, it will clear all the files in the cache directory
  263.      * @return bool true
  264.      * @author Alex McFadyen
  265.      */
  266.     function clearCache($clearAll = false){
  267.         $files = glob($this->cache_location.'*.jpg');
  268.         foreach($files as $file)
  269.             if($clearAll OR time() < filectime($file))
  270.                 unlink($file);
  271.            
  272.         return true;
  273.     }
  274.  
  275.     function addError($msg){
  276.         $this->errors[] = $msg;
  277.     }
  278. }
  279. ?>
Parsed in 0.388 seconds, using GeSHi 1.0.7.14

Modify this Paste