home *** CD-ROM | disk | FTP | other *** search
/ PC World 2005 April / PCWorld_2005-04_cd.bin / akce / web / phptriad / phptriad2-2-1.exe / php / pear / Cache / Graphics.php < prev    next >
PHP Script  |  2001-11-13  |  13KB  |  351 lines

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP version 4.0                                                      |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group             |
  6. // +----------------------------------------------------------------------+
  7. // | This source file is subject to version 2.0 of the PHP license,       |
  8. // | that is bundled with this package in the file LICENSE, and is        |
  9. // | available at through the world-wide-web at                           |
  10. // | http://www.php.net/license/2_02.txt.                                 |
  11. // | If you did not receive a copy of the PHP license and are unable to   |
  12. // | obtain it through the world-wide-web, please send a note to          |
  13. // | license@php.net so we can mail you a copy immediately.               |
  14. // +----------------------------------------------------------------------+
  15. // | Authors: Ulf Wendel <ulf.wendel@phpdoc.de>                           |
  16. // +----------------------------------------------------------------------+
  17. //
  18. // $Id: Graphics.php,v 1.7.2.3 2001/11/13 01:26:40 ssb Exp $
  19.  
  20. require_once 'Cache.php';
  21.  
  22. /**
  23. * Graphics disk cache.
  24. * The usual way to create images is to pass some arguments that describe the image 
  25. * to a script that dynamically creates an image. For every image of a page 
  26. * a new PHP interpreter gets started. This is a good way to kill your webserver.
  27. * When dealing with dynamically generated images you should not call another script 
  28. * to generate the images but generate the images by the script that produces the page
  29. * that contains the images. This is a major improvement but it's only half the way.
  30. * There's no need to rerender an image on every request. A simple disk cache can reduce
  31. * the computation time dramatically. This is what the class graphics_cache is for. 
  32. * Usage:
  33. * // create an instance of the graphics cache
  34. * $cache = new graphics_cache;
  35. *
  36. * $img = ImageCreate(...);
  37. *
  38. * // compute an ID for your image based on typical parameters
  39. * $id = m5d( $size, $colors, $label);
  40. * // check if it's cached
  41. * if (!($link = $cache->getImageLink($id, 'gif'))) {
  42. *  
  43. *   // hmmm, it's not cached, create it
  44. *   ...
  45. *   // cacheImageLink() and cacheImage() make the ImageGIF() call!
  46. *   // cacheImage() returns the value of ImageGIF() [etc.], cacheImageLink() returns a URL
  47. *   $link = $cache->cacheImageLink($id, $img, 'gif');
  48. * }
  49. *
  50. * // Ok, let's build the ImageLink
  51. * $size = getImageSize($link[0]);
  52. * printf('<img src="%s" %s>', $link[1], $size[3]);
  53. *
  54. * // for cacheImage():
  55. * // header('Content-type: image/gif'); print $cache->cacheImage($id, $img, 'gif');
  56. *
  57. * The class requires PHP 4.0.2+ [ImageType()]. Note that cacheImage() works with
  58. * the output buffer. Modify it if required!
  59. *
  60. * @author   Ulf Wendel <ulf.wendel@phpdoc.de>
  61. * @version  $Id: Graphics.php,v 1.7.2.3 2001/11/13 01:26:40 ssb Exp $
  62. * @package  Cache
  63. */
  64. class Cache_Graphics extends Cache {
  65.  
  66.  
  67.     /**
  68.     * Cache URL prefix.
  69.     * 
  70.     * Make sure that the cache URL prefix points to the $cache_dir, otherwise
  71.     * your links will be broken. Use setCacheURL to specify the cache_url and 
  72.     * setCacheDir() for the cache_dir.
  73.     * 
  74.     * @var  string
  75.     * @see  setCacheURL(), setCacheDir()
  76.     */
  77.     var $cache_url = '';
  78.  
  79.     /**
  80.     * Directory where cached files get stored.
  81.     * s
  82.     * Make sure that the cache_dir is writable and offers enough space. Check 
  83.     * also if your cache_url points to the directory. Use setCacheDir() to set
  84.     * the variable.
  85.     * 
  86.     * @var  string
  87.     * @see  setCacheDir(), setCacheURL()
  88.     */
  89.     var $cache_dir = '';
  90.  
  91.     /**
  92.     * Nameprefix of cached files.
  93.     * 
  94.     * Per default the prefix "graphics_" gets used. You might use this 
  95.     * for versioning or to ease (manual) clean ups.
  96.     *
  97.     * @var      string
  98.     */
  99.     var $cache_file_prefix = 'graphics_';
  100.     
  101.     
  102.     /**
  103.     * Cache container group.
  104.     *
  105.     * @var      string
  106.     */
  107.     var $cache_group = 'graphics';
  108.  
  109.     
  110.     /**
  111.     * Mapping from supported image type to a ImageType() constant.
  112.     * 
  113.     * Referr to the PHP manual for more informations on ImageType()
  114.     * 
  115.     * @var  array
  116.     * @link http://www.php.net/ImageType
  117.     */
  118.     var $imagetypes = array(
  119.                                 'gif'   => IMG_GIF, 
  120.                                 'jpg'   => IMG_JPG,
  121.                                 'png'   => IMG_PNG,
  122.                                 'wbmp'  => IMG_WBMP
  123.                             );
  124.  
  125.                             
  126.     /**
  127.     * Instantiates a cache file container.
  128.     *
  129.     */
  130.     function Cache_Graphics() {
  131.     
  132.         $this->Cache('file', array('cache_dir' => $this->cache_dir, 'filename_prefix' => $this->cache_file_prefix));
  133.         
  134.     } // end constructor
  135.  
  136.     
  137.     /**
  138.     * Returns the content of a cached image file.
  139.     * 
  140.     * This function can be used to send the image directly to the browser.
  141.     * Make sure that you send a correspondending header before sending the image itself.
  142.     *
  143.     * Always try to get the image from the cache before you compute it. See 
  144.     * the class docs for an example.
  145.     *
  146.     * @param    string  Image-ID
  147.     * @param    string  Image type: gif, jpg, png, wbmp
  148.     * @return   string  Image file contents if a cached file exists otherwise an empty string
  149.     * @see      cacheImage()
  150.     */                                    
  151.     function getImage($id, $format = 'png') {
  152.         $id = $this->generateID(array('id' => $id, 'format' => strtolower($format)));
  153.         
  154.         return $this->get($id, $this->cache_group);
  155.     } // end func getImage
  156.  
  157.     
  158.     /**
  159.     * Returns an array with a link to the cached image and the image file path.
  160.     * 
  161.     * Always try to get the image from the cache before you compute it. See 
  162.     * the class docs for an example.
  163.     *
  164.     * @param    string  Image-ID
  165.     * @param    string  Image type: gif, jpg, png, wbmp
  166.     * @return   array   [ full path to the image file, image url ]
  167.     * @throw    Cache_Error
  168.     * @see      cacheImageLink()
  169.     */
  170.     function getImageLink($id, $format = 'png') {
  171.         $id = $this->generateID(array('id' => $id, 'format' => strtolower($format)));
  172.         if (!$this->container->idExists($id, $this->cache_group)) 
  173.             return array();
  174.  
  175.         $file = $this->cache_url . $this->cache_file_prefix . $id;
  176.  
  177.         return array($this->container->getFilename($id, $this->cache_group), $file);
  178.     } // end func getImageLink
  179.     
  180.  
  181.     /**
  182.     * Create an image from the given image handler, cache it and return the file content.
  183.     *
  184.     * Always try to retrive the image from the cache before you compute it.
  185.     * 
  186.     * Warning: this function uses the output buffer. If you expect collisions 
  187.     * modify the code.
  188.     *
  189.     * @param    string  Image-ID. Used as a part of the cache filename.
  190.     *                   Use md5() to generate a "unique" ID for your image
  191.     *                   based on characteristic values such as the color, size etc.
  192.     * @param    string  Image handler to create the image from.
  193.     * @param    string  Image type: gif, jpg, png, wbmp. Also used as filename suffix.
  194.     *                   If an unsupported type is requested the functions tries to 
  195.     *                   fallback to a supported type before throwing an exeption.
  196.     * @return   string  Image content returned by ImageGIF/... 
  197.     * @throws   Cache_Error
  198.     * @access   public
  199.     * @see      getImage()
  200.     */
  201.     function cacheImage($id, $img, $format = 'png') {
  202.         if (!$id)
  203.             return new Cache_Error('You must provide an ID for and image to be cached!', __FILE__, __LINE__);
  204.  
  205.         $id = $this->generateID(array('id' => $id, 'format' => strtolower($format)));
  206.  
  207.         $types = ImageTypes();
  208.  
  209.         // Check if the requested image type is supported by the GD lib.
  210.         // If not, try a callback to the first available image type.
  211.         if (!isset($this->imagetypes[$format]) || !($types & $this->imagetypes[$format])) {
  212.             foreach ($this->imagetypes as $supported => $bitmask) {
  213.                 if ($types & $bitmask) {
  214.                     new Cache_Error("The build in GD lib does not support the image type $format. Fallback to $supported.", __FILE__, __LINE__);
  215.                 } else {
  216.                     return new Cache_Error("Hmm, is your PHP build with GD support? Can't find any supported types.", __FILE__, __LINE__);
  217.                 }
  218.             }
  219.         }
  220.  
  221.         if ($image = $this->get($id, $this->cache_group))
  222.             return $image;
  223.  
  224.         // save the image to the output buffer, write it to disk and 
  225.         // return the image.
  226.         ob_end_clean();
  227.         ob_start(); 
  228.  
  229.         if (strtoupper($format) == "JPG") {
  230.             $genFormat = "JPEG";
  231.         } else {
  232.             $genFormat = strtoupper($format);
  233.         }
  234.  
  235.         // generate the image
  236.         $func = 'Image' . $genFormat;
  237.         $func($img);
  238.         ImageDestroy($img);
  239.  
  240.         ob_end();
  241.         $image = ob_get_contents();
  242.         ob_end_clean();
  243.  
  244.         // save the generated image to disk
  245.         $this->save($id, $image, 0, $this->cache_group);
  246.  
  247.         return $image;
  248.     } // end func cacheImage
  249.     
  250.  
  251.     /**
  252.     * Create an image from the given image handler, cache it and return a url and the file path of the image.
  253.     *
  254.     * Always try to retrive the image from the cache before you compute it.
  255.     *
  256.     * @param    string  Image-ID. Used as a part of the cache filename.
  257.     *                   Use md5() to generate a "unique" ID for your image
  258.     *                   based on characteristic values such as the color, size etc.
  259.     * @param    string  Image handler to create the image from.
  260.     * @param    string  Image type: gif, jpg, png, wbmp. Also used as filename suffix.
  261.     *                   If an unsupported type is requested the functions tries to 
  262.     *                   fallback to a supported type before throwing an exeption.
  263.     * @return   array  [ full path to the image file, image url ]
  264.     * @throws   Cache_Error
  265.     * @access   public
  266.     */
  267.     function cacheImageLink($id, &$img, $format = 'png') {
  268.         if (!$id)
  269.             return new Cache_Error ('You must provide an ID for and image to be cached!', __FILE__, __LINE__);
  270.  
  271.         $id = $this->generateID( array('id' => $id, 'format' => strtolower($format)) );
  272.  
  273.         $types = ImageTypes();
  274.  
  275.         // Check if the requested image type is supported by the GD lib.
  276.         // If not, try a callback to the first available image type.
  277.         if (!isset($this->imagetypes[$format]) || !($types & $this->imagetypes[$format])) {
  278.             foreach ($this->imagetypes as $supported => $bitmask) 
  279.                 if ($types & $bitmask)
  280.                     new Cache_Error("The build in GD lib does not support the image type $format. Fallback to $supported.", __FILE__, __LINE__);
  281.                 else
  282.                     return new Cache_Error("Hmm, is your PHP build with GD support? Can't find any supported types.", __FILE__, __LINE__);
  283.         }
  284.  
  285.         $url = $this->cache_url . $this->cache_file_prefix . $id;
  286.         $ffile = $this->container->getFilename($id, $this->cache_group);
  287.  
  288.         if ($this->isCached($id, $this->cache_group) && !isExpired($id, $this->cache_group))
  289.             return array($ffile, $url);
  290.  
  291.         if (strtoupper($format) == "JPG") {
  292.             $genFormat = "JPEG";
  293.         } else {
  294.             $genFormat = strtoupper($format);
  295.         }
  296.  
  297.         $func = 'Image' . $genFormat;
  298.         $func($img, $ffile);
  299.  
  300.         ImageDestroy($img);
  301.  
  302.         return array($ffile, $url);
  303.     } // end func cacheImageLink
  304.  
  305.     
  306.     /**
  307.     * Sets the URL prefix used when rendering HTML Tags. 
  308.     * 
  309.     * Make sure that the URL matches the cache directory, 
  310.     * otherwise you'll get broken links.
  311.     * 
  312.     * @param    string
  313.     * @access   public
  314.     * @see      setCacheDir()
  315.     */
  316.     function setCacheURL($cache_url) {
  317.         if ($cache_url && '/' != substr($cache_url, 1)) 
  318.             $cache_url .= '/';
  319.             
  320.         $this->cache_url = $cache_url;
  321.         
  322.     } // end func setCacheURL
  323.  
  324.     
  325.     /**
  326.     * Sets the directory where to cache generated Images
  327.     * 
  328.     * @param    string
  329.     * @access   public
  330.     * @see      setCacheURL()
  331.     */
  332.     function setCacheDir($cache_dir) {
  333.         if ($cache_dir && '/' != substr($cache_dir, 1))
  334.             $cache_dir .= '/';
  335.  
  336.         $this->cache_dir = $cache_dir;
  337.         $this->container->cache_dir = $cache_dir;
  338.     } // end func setCacheDir
  339.     
  340.     
  341. } // end class Cache_Graphics
  342. ?>
  343.