sbergmann               Thu Mar  1 11:22:26 2001 EDT

  Added files:                 
    /php4/pear/Cache    Graphics.php Output.php 

  Modified files:              
    /php4/pear  Makefile.in 
  Log:
  Added Graphics and Output Cache.
  
Index: php4/pear/Makefile.in
diff -u php4/pear/Makefile.in:1.70 php4/pear/Makefile.in:1.71
--- php4/pear/Makefile.in:1.70  Thu Mar  1 09:02:05 2001
+++ php4/pear/Makefile.in       Thu Mar  1 11:22:25 2001
@@ -36,6 +36,8 @@
        Benchmark/Timer.php \
        Cache.php \
        Cache/Container.php \
+       Cache/Graphics.php \
+       Cache/Output.php \
        Cache/Container/db.php \
        Cache/Container/file.php \
        Cache/Container/phplib.php \

Index: php4/pear/Cache/Graphics.php
+++ php4/pear/Cache/Graphics.php
<?php
// +----------------------------------------------------------------------+
// | PHP version 4.0                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group             |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | [EMAIL PROTECTED] so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Ulf Wendel <[EMAIL PROTECTED]>                           |
// |          Sebastian Bergmann <[EMAIL PROTECTED]>               |
// +----------------------------------------------------------------------+
//
// $Id: Graphics.php,v 1.1 2001/03/01 19:22:25 sbergmann Exp $

require_once'Cache.php';

/**
* Graphics disk cache.
* 
* The usual way to create images is to pass some arguments that describe the image 
* to a script that dynamically creates an image. For every image of a page 
* a new PHP interpreter gets started. This is a good way to kill your webserver.
* 
* When dealing with dynamically generated images you should not call another script 
* to generate the images but generate the images by the script that produces the page
* that contains the images. This is a major improvement but it's only half the way.
* 
* There's no need to rerender an image on every request. A simple disk cache can reduce
* the computation time dramatically. This is what the class graphics_cache is for. 
* 
* Usage:
* 
* // create an instance of the graphics cache
* $cache = new graphics_cache;
*
* $img = ImageCreate(...);
*
* // compute an ID for your image based on typical parameters
* $id = m5d( $size, $colors, $label);
* 
* // check if it's cached
* if (!($link = $cache->getImageLink($id, "gif"))) {
*  
*   // hmmm, it's not cached, create it
*   ...
*   // cacheImageLink() and cacheImage() make the ImageGIF() call!
*   // cacheImage() returns the value of ImageGIF() [etc.], cacheImageLink() returns a 
URL
*   $link = $cache->cacheImageLink($id, $img, "gif");
* 
* }
*
* // Ok, let's build the ImageLink
* $size = getImageSize($link[0]);
* printf('<img src="%s" %s>', $link[1], $size[3]);
*
* // for cacheImage():
* // header("Content-type: image/gif"); print $cache->cacheImage($id, $img, "gif");
* 
*
* The class requires PHP 4.0.2+ [ImageType()]. Note that cacheImage() works with
* the output buffer. Modify it if required!
*
* @author   Ulf Wendel <[EMAIL PROTECTED]>
* @version  $Id: Graphics.php,v 1.1 2001/03/01 19:22:25 sbergmann Exp $
*/
class graphics_cache extends cache {

    /**
    * Cache URL prefix.
    * 
    * Make sure that the cache URL prefix points to the $cache_dir, otherwise
    * your links will be broken. Use setCacheURL to specify the cache_url and 
    * setCacheDir() for the cache_dir.
    * 
    * @var  string
    * @see  setCacheURL(), setCacheDir()
    */
    var $cache_url = "";
    
    /**
    * Directory where cached files get stored.
    * s
    * Make sure that the cache_dir is writable and offers enough space. Check 
    * also if your cache_url points to the directory. Use setCacheDir() to set
    * the variable.
    * 
    * @var  string
    * @see  setCacheDir(), setCacheURL()
    */
    var $cache_dir = "";
    
    /**
    * Nameprefix of cached files.
    * 
    * Per default the prefix "graphics_" gets used. You might use this 
    * for versioning or to ease (manual) clean ups.
    *
    * @var      string
    */
    var $cache_file_prefix = "graphics_";
    
    
    /**
    * Mapping from supported image type to a ImageType() constant.
    * 
    * Referr to the PHP manual for more informations on ImageType()
    * 
    * @var  array
    * @link http://www.php.net/ImageType
    */
    var $imagetypes = array(
                                "gif"   => IMG_GIF, 
                                "jpg"   => IMG_JPG,
                                "png"   => IMG_PNG,
                                "wbmp"  => IMG_WBMP
                            );

    /**
    * TODO: add docs
    */
    function graphics_cache() {
        $this->cache("cache_container_file", array("cache_dir" => $this->cache_dir, 
"filename_prefix" => $this->cache_file_prefix));
    } // end constructor

    
    /**
    * Returns the content of a cached image file.
    * 
    * This function can be used to send the image directly to the browser.
    * Make sure that you send a correspondending header before sending the image 
itself.
    *
    * Always try to get the image from the cache before you compute it. See 
    * the class docs for an example.
    *
    * @param    string  Image-ID
    * @param    string  Image type: gif, jpg, png, wbmp
    * @return   string  Image file contents if a cached file exists otherwise an empty 
string
    * @see      cacheImage()
    */                                    
    function getImage($id, $format = "png") {
        
        $id = $this->generateID(array("id" => $id, "format" => strtolower($format)));
        
        return $this->get($id);
    } // end func getImage
    
    
    /**
    * Returns an array with a link to the cached image and the image file path.
    * 
    * Always try to get the image from the cache before you compute it. See 
    * the class docs for an example.
    *
    * @param    string  Image-ID
    * @param    string  Image type: gif, jpg, png, wbmp
    * @return   array   [ full path to the image file, image url ]
    * @throw    gerror
    * @see      cacheImageLink()
    */
    function getImageLink($id, $format = "png") {

        $id = $this->generateID(array("id" => $id, "format" => strtolower($format)));
        if (!$this->container->idExists($id)) 
            return array();
            
        $file = $this->cache_url . $this->cache_file_prefix . $id;
        
        return array($this->container->getFilename($id), $file);
    } // end func getImageLink
    
    
    /**
    * Create an image from the given image handler, cache it and return the file 
content.
    *
    * Always try to retrive the image from the cache before you compute it.
    * 
    * Warning: this function uses the output buffer. If you expect collisions 
    * modify the code.
    *
    * @param    string  Image-ID. Used as a part of the cache filename.
    *                   Use md5() to generate a "unique" ID for your image
    *                   based on characteristic values such as the color, size etc.
    * @param    string  Image handler to create the image from.
    * @param    string  Image type: gif, jpg, png, wbmp. Also used as filename suffix.
    *                   If an unsupported type is requested the functions tries to 
    *                   fallback to a supported type before throwing an exeption.
    * @return   string  Image content returned by ImageGIF/... 
    * @throws   gerror
    * @access   public
    * @see      getImage()
    */
    function cacheImage($id, &$img, $format = "png") {
        if (!$id)
            return new gerror("You must provide an ID for and image to be cached!");
    
        $id = $this->generateID(array("id" => $id, "format" => strtolower($format)));
        
        // Check if the requested image type is supported by the GD lib.
        // If not, try a callback to the first available image type.
        if (!isset($this->imagetypes[$format]) || !(ImageTypes() & 
$this->imagetypes[$format])) {
            foreach ($this->imagetypes as $supported => $bitmask) 
                if (ImageTypes() & $bitmask)
                    new gerror("The build in GD lib does not support the image type 
$format. Fallback to $supported.");
                else
                    return new gerror("Hmm, is you PHP build with GD support? Can't 
find any supported types.");
        }
        
        if ($image = $this->get($id))
            return $image;
        
        // save the image to the output buffer, write it to disk and 
        // return the image.
        ob_end_clean();
        ob_start(); 
        
        // generate the image
        $func = "Image" . strtoupper($format);    
        $func($img);
        ImageDestroy($img);
                
        ob_end();
        $image = ob_get_contents();
        ob_end_clean();
    
        // save the generated image to disk
        $this->save($id, $image, 0);
        
        return $image;
    } // end func cacheImage

    
    /**
    * Create an image from the given image handler, cache it and return a url and the 
file path of the image.
    *
    * Always try to retrive the image from the cache before you compute it.
    *
    * @param    string  Image-ID. Used as a part of the cache filename.
    *                   Use md5() to generate a "unique" ID for your image
    *                   based on characteristic values such as the color, size etc.
    * @param    string  Image handler to create the image from.
    * @param    string  Image type: gif, jpg, png, wbmp. Also used as filename suffix.
    *                   If an unsupported type is requested the functions tries to 
    *                   fallback to a supported type before throwing an exeption.
    * @return   array  [ full path to the image file, image url ]
    * @throws   gerror
    * @access   public
    */

    function cacheImageLink($id, &$img, $format = "png") {
        if (!$id)
            return new gerror("You must provide an ID for and image to be cached!");
            
        $id = $this->generateID(array("id" => $id, "format" => strtolower($format));
        
        // Check if the requested image type is supported by the GD lib.
        // If not, try a callback to the first available image type.
        if (!isset($this->imagetypes[$format]) || !(ImageTypes() & 
$this->imagetypes[$format])) {
            foreach ($this->imagetypes as $supported => $bitmask) 
                if (ImageTypes() & $bitmask)
                    new gerror("The build in GD lib does not support the image type 
$format. Fallback to $supported.");
                else
                    return new gerror("Hmm, is you PHP build with GD support? Can't 
find any supported types.");
        }

        $url = $this->cache_url . $this->cache_file_prefix . $id;
        $ffile = $this->container->getFilename($id);
        
        if ($this->isCached($id) && !isExpired($id))
            return array($ffile, $url)

        $func = "Image" . strtoupper($format);    
        $func($img, $ffile);

        ImageDestroy($img);

        return array($ffile, $url);
    } // end func cacheImageLink


    /**
    * Sets the URL prefix used when rendering HTML Tags. 
    * 
    * Make sure that the URL matches the cache directory, 
    * otherwise you'll get broken links.
    * 
    * @param    string
    * @access   public
    * @see      setCacheDir()
    */
    function setCacheURL($cache_url) {
    
        if ($cache_url && "/" != substr($cache_url, 1)) 
            $cache_url .= "/";
            
        $this->cache_url = $cache_url;
        
    } // end func setCacheURL
    
    /**
    * Sets the directory where to cache generated Images
    * 
    * @param    string
    * @access   public
    * @see      setCacheURL()
    */
    function setCacheDir($cache_dir) {
        
        if ($cache_dir && "/" != substr($cache_dir, 1))
            $cache_dir .= "/";
            
        $this->cache_dir = $cache_dir;
        $this->container->cache_dir = $cache_dir;
                        
    } // end func setCacheDir

    
} // end class graphics_cache
?>
Index: php4/pear/Cache/Output.php
+++ php4/pear/Cache/Output.php
<?php
// +----------------------------------------------------------------------+
// | PHP version 4.0                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997, 1998, 1999, 2000, 2001 The PHP Group             |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | [EMAIL PROTECTED] so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Ulf Wendel <[EMAIL PROTECTED]>                           |
// |          Sebastian Bergmann <[EMAIL PROTECTED]>               |
// |          Christian Stocker <[EMAIL PROTECTED]>                         |
// |          Vinai Kopp <[EMAIL PROTECTED]>                           |
// +----------------------------------------------------------------------+
//
// $Id: Output.php,v 1.1 2001/03/01 19:22:25 sbergmann Exp $

require_once'Cache.php';

/**
* Class to cache the output of a script using the output buffering functions
*
* Simple output cache. Some pages require lots of time to compute. Caching the 
* output can increase the overall speed dramatically, especially if you use
* a Shared Memory storage container.
* 
* As you can see in the example the usage is extemely simple. To cache a script 
* simple put some few lines of code in front of your script and some at the end. 
* A preferrable place for this are the auto_prepend and auto_append files (=> 
php.ini). 
* 
* Usage example:
*
*  // place this somewhere in a central config file
*  define(CACHE_STORAGE_CLASS, "cache_container_file");
*
* // get a cache object
*  $cache = new Cache_Output(CACHE_STORAGE_CLASS)
*
*  // compute the unique handle.
*  // if your script depends on Cookie and HTTP Post data as well 
*  // you should use:
*  // $cache_handle = array( 
*  //                       "file" => $REQUEST_URI,
*  //                       "post" => $HTTP_POST_VAS"
*  //                       "cookie"  => $HTTP_COOKIE_VARS
*  //                    );
*  $cache_handle = $REQUEST_URI;
* 
*  // now the magic happens: if cached call die() 
*  // to end the time consumptiong script script execution and use the cached value!
*  if ($content = $cache->start($cache_handle)) {
*     print $content;
*     die();
*  }
*  
*  // time consumption script goes here. 
* 
*  // store the output of the cache into the cache and print the output.
*  print $cache->end();
* 
* If you do not want to cache a whole page - no problem:
* 
* if (!($content = $cache->start($cache_handle))) {
*    // do the computation here
*    print $cache->end()
* } else {
    print $content;
* }
*
* Have fun!
* 
* @authors  Ulf Wendel <[EMAIL PROTECTED]>
* @version  $ID: $
* @package  Cache
* @access   public
*/
class Cache_Output extends Cache {

    /**
    * ID passed to start()
    * 
    * @var  string
    * @see  start(), end()
    */
    var $cache_id = "";
    
    /**
    * starts the output buffering and returns an empty string or returns the cached 
output from the cache.
    * 
    * @param    string  dataset ID
    * @return   string  
    * @access   public
    */
    function start($id) {
        if ($this->no_cache)
            return "";

        // this is already cached return it from the cache so that the user 
        // can use the cache content and stop script execution
        if ($content = $this->get($id))
            return $content;

        // remember some data to be able to fill the cache on calling end()
        $this->cache_id = $id;
        
        // WARNING: we need the output buffer - possible clashes
        ob_start();
        ob_implicit_flush(false);
        
        return "";
    } // end func start

    /*
    * Stores the content of the output buffer into the cache and returns the content.
    *
    * @param    integer lifetime of the cached data in seconds - 0 for endless
    * @return   string  cached output
    * @access   public
    * @see      endPrint()
    */
    function end($expire = 0) {
    
        $content = ob_get_content();
        ob_end_clean();
        
        // store in the cache
        if (!$this->no_cache)
            $this->container->save($content, $this->id, $expire);

        return $content;
    } // end func end()
    
    /**
    * Stores the content of the output buffer into the cache and prints the content.
    *
    * @brother  end()
    */
    function endPrint($expire = 0) {
    
        print $this->end($expire);      
        
    } // end func endPrint

    
} // end class output
?>
-- 
PHP CVS Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to