Cache
[ class tree: Cache ] [ index: Cache ] [ all elements ]

Source for file file.php

Documentation is available at file.php

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PEAR :: Cache                                                        |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1997-2003 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. // |          Sebastian Bergmann <sb@sebastian-bergmann.de>               |
  17. // +----------------------------------------------------------------------+
  18. //
  19. // $Id: file.php,v 1.13 2003/03/27 10:48:42 chregu Exp $
  20.  
  21. require_once 'Cache/Container.php';
  22.  
  23. /**
  24. * Stores cache contents in a file.
  25. *
  26. @author   Ulf Wendel  <ulf.wendel@phpdoc.de>
  27. @version  $Id: file.php,v 1.13 2003/03/27 10:48:42 chregu Exp $
  28. */
  29.  
  30.     /**
  31.     * File locking
  32.     *
  33.     * With file container, it's possible, that you get corrupted
  34.     * data-entries under bad circumstances. The file locking must
  35.     * improve this problem but it's experimental stuff. So the
  36.     * default value is false. But it seems to give good results
  37.     *
  38.     * @var boolean 
  39.     */
  40.     var $fileLocking = false;
  41.  
  42.     /**
  43.     * Directory where to put the cache files.
  44.     *
  45.     * @var  string  Make sure to add a trailing slash
  46.     */
  47.     var $cache_dir = '';
  48.  
  49.     /**
  50.     * Filename prefix for cache files.
  51.     *
  52.     * You can use the filename prefix to implement a "domain" based cache or just
  53.     * to give the files a more descriptive name. The word "domain" is borroed from
  54.     * a user authentification system. One user id (cached dataset with the ID x)
  55.     * may exists in different domains (different filename prefix). You might want
  56.     * to use this to have different cache values for a production, development and
  57.     * quality assurance system. If you want the production cache not to be influenced
  58.     * by the quality assurance activities, use different filename prefixes for them.
  59.     *
  60.     * I personally don't think that you'll never need this, but 640kb happend to be
  61.     * not enough, so... you know what I mean. If you find a useful application of the
  62.     * feature please update this inline doc.
  63.     *
  64.     * @var  string 
  65.     */
  66.     var $filename_prefix = '';
  67.     
  68.     
  69.     /**
  70.     * List of cache entries, used within a gc run
  71.     * 
  72.     * @var array 
  73.     */
  74.     var $entries;
  75.     
  76.     /**
  77.     * Total number of bytes required by all cache entries, used within a gc run.
  78.     * 
  79.     * @var  int 
  80.     */
  81.     var $total_size = 0;
  82.  
  83.  
  84.     /**
  85.     * Max Line Length of userdata
  86.     *
  87.     * If set to 0, it will take the default
  88.     * ( 1024 in php 4.2, unlimited in php 4.3)
  89.     * see http://ch.php.net/manual/en/function.fgets.php
  90.     * for details
  91.     *
  92.     * @var int 
  93.     */
  94.     var $max_userdata_linelength = 257;
  95.  
  96.     /**
  97.     * Creates the cache directory if neccessary
  98.     *
  99.     * @param    array   Config options: ["cache_dir" => ..., "filename_prefix" => ...]
  100.     */
  101.      function Cache_Container_file($options ''{
  102.         if (is_array($options))
  103.             $this->setOptions($optionsarray_merge($this->allowed_optionsarray('cache_dir''filename_prefix''max_userdata_linelength')));
  104.         
  105.         clearstatcache();
  106.         if ($this->cache_dir)
  107.         {
  108.             // make relative paths absolute for use in deconstructor.
  109.             // it looks like the deconstructor has problems with relative paths
  110.             if (OS_UNIX && '/' != $this->cache_dir{0}  )
  111.                 $this->cache_dir = realpathgetcwd('/' $this->cache_dir'/';
  112.  
  113.             // check if a trailing slash is in cache_dir
  114.             if ($this->cache_dir{strlen($this->cache_dir)-1!= DIRECTORY_SEPARATOR)
  115.                  $this->cache_dir .= '/';
  116.  
  117.             if  (!file_exists($this->cache_dir|| !is_dir($this->cache_dir))
  118.                 mkdir($this->cache_dir0755);
  119.         }
  120.         $this->entries = array();
  121.         $this->group_dirs = array();
  122.                     
  123.     // end func contructor
  124.  
  125.     function fetch($id$group{
  126.         $file $this->getFilename($id$group);
  127.         if (!file_exists($file))
  128.             return array(NULLNULLNULL);
  129.  
  130.         // retrive the content
  131.         if (!($fh @fopen($file'rb')))
  132.             return new Cache_Error("Can't access cache file '$file'. Check access rights and path."__FILE____LINE__);
  133.  
  134.         // File locking (shared lock)
  135.         if ($this->fileLocking)
  136.             flock($fhLOCK_SH);
  137.  
  138.         // file format:
  139.         // 1st line: expiration date
  140.         // 2nd line: user data
  141.         // 3rd+ lines: cache data
  142.         $expire trim(fgets($fh12));
  143.         if ($this->max_userdata_linelength == 0 {
  144.             $userdata trim(fgets($fh));
  145.         else {
  146.             $userdata trim(fgets($fh$this->max_userdata_linelength));
  147.         }
  148.         $cachedata $this->decode(fread($fhfilesize($file)));
  149.  
  150.         // Unlocking
  151.         if ($this->fileLocking)
  152.             flock($fhLOCK_UN);
  153.  
  154.         fclose($fh);
  155.  
  156.         // last usage date used by the gc - maxlifetime
  157.         // touch without second param produced stupid entries...
  158.         touch($file,time());
  159.         clearstatcache();
  160.  
  161.         return array($expire$cachedata$userdata);
  162.     // end func fetch
  163.  
  164.     /**
  165.     * Stores a dataset.
  166.     *
  167.     * WARNING: If you supply userdata it must not contain any linebreaks,
  168.     * otherwise it will break the filestructure.
  169.     */
  170.     function save($id$cachedata$expires$group$userdata{
  171.         $this->flushPreload($id$group);
  172.  
  173.         $file $this->getFilename($id$group);
  174.         if (!($fh @fopen($file'wb')))
  175.             return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path."__FILE____LINE__);
  176.  
  177.         // File locking (exclusive lock)
  178.         if ($this->fileLocking)
  179.             flock($fhLOCK_EX);
  180.  
  181.         // file format:
  182.         // 1st line: expiration date
  183.         // 2nd line: user data
  184.         // 3rd+ lines: cache data
  185.         $expires $this->getExpiresAbsolute($expires);
  186.         fwrite($fh$expires "\n");
  187.         fwrite($fh$userdata "\n");
  188.         fwrite($fh$this->encode($cachedata));
  189.  
  190.         // File unlocking
  191.         if ($this->fileLocking)
  192.             flock($fhLOCK_UN);
  193.  
  194.         fclose($fh);
  195.  
  196.         // I'm not sure if we need this
  197.     // i don't think we need this (chregu)
  198.         // touch($file);
  199.  
  200.         return true;
  201.     // end func save
  202.  
  203.     function remove($id$group{
  204.         $this->flushPreload($id$group);
  205.  
  206.         $file $this->getFilename($id$group);
  207.         if (file_exists($file)) {
  208.  
  209.             $ok unlink($file);
  210.             clearstatcache();
  211.  
  212.             return $ok;
  213.         }
  214.  
  215.         return false;
  216.     // end func remove
  217.  
  218.     function flush($group{
  219.         $this->flushPreload();
  220.         $dir ($group$this->cache_dir . $group '/' $this->cache_dir;
  221.  
  222.         $num_removed $this->deleteDir($dir);
  223.         unset($this->group_dirs[$group]);
  224.         clearstatcache();
  225.  
  226.         return $num_removed;
  227.     // end func flush
  228.  
  229.     function idExists($id$group{
  230.  
  231.         return file_exists($this->getFilename($id$group));
  232.     // end func idExists
  233.  
  234.     /**
  235.     * Deletes all expired files.
  236.     *
  237.     * Garbage collection for files is a rather "expensive", "long time"
  238.     * operation. All files in the cache directory have to be examined which
  239.     * means that they must be opened for reading, the expiration date has to be
  240.     * read from them and if neccessary they have to be unlinked (removed).
  241.     * If you have a user comment for a good default gc probability please add it to
  242.     * to the inline docs.
  243.     *
  244.     * @param    integer Maximum lifetime in seconds of an no longer used/touched entry
  245.     * @throws   Cache_Error
  246.     */
  247.     function garbageCollection($maxlifetime{
  248.  
  249.         $this->flushPreload();
  250.         clearstatcache();
  251.  
  252.         $ok $this->doGarbageCollection($maxlifetime$this->cache_dir);
  253.  
  254.         // check the space used by the cache entries        
  255.         if ($this->total_size > $this->highwater{
  256.         
  257.             krsort($this->entries);
  258.             reset($this->entries);
  259.             
  260.             while ($this->total_size > $this->lowwater && list($lastmod$entryeach($this->entries)) {
  261.                 if (@unlink($entry['file']))
  262.                     $this->total_size -= $entry['size'];
  263.                 else
  264.                     new CacheError("Can't delete {$entry["file"]}. Check the permissions.");
  265.             }
  266.             
  267.         }
  268.         
  269.         $this->entries = array();
  270.         $this->total_size = 0;
  271.         
  272.         return $ok;
  273.     // end func garbageCollection
  274.     
  275.     /**
  276.     * Does the recursive gc procedure, protected.
  277.     *
  278.     * @param    integer Maximum lifetime in seconds of an no longer used/touched entry
  279.     * @param    string  directory to examine - don't sets this parameter, it's used for a
  280.     *                    recursive function call!
  281.     * @throws   Cache_Error
  282.     */
  283.     function doGarbageCollection($maxlifetime$dir{
  284.            
  285.         if (!($dh opendir($dir)))
  286.             return new Cache_Error("Can't access cache directory '$dir'. Check permissions and path."__FILE____LINE__);
  287.  
  288.         while ($file readdir($dh)) {
  289.             if ('.' == $file || '..' == $file)
  290.                 continue;
  291.  
  292.             $file $dir $file;
  293.             if (is_dir($file)) {
  294.                 $this->doGarbageCollection($maxlifetime,$file '/');
  295.                 continue;
  296.             }
  297.  
  298.             // skip trouble makers but inform the user
  299.             if (!($fh @fopen($file'rb'))) {
  300.                 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path."__FILE____LINE__);
  301.                 continue;
  302.             }
  303.  
  304.             $expire fgets($fh11);
  305.             fclose($fh);
  306.             $lastused filemtime($file);
  307.             
  308.             $this->entries[$lastused= array('file' => $file'size' => filesize($file));
  309.             $this->total_size += filesize($file);
  310.             
  311.             // remove if expired
  312.             if (( ($expire && $expire <= time()) || ($lastused <= (time($maxlifetime)) ) && !unlink($file))
  313.                 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path."__FILE____LINE__);
  314.         }
  315.  
  316.         closedir($dh);
  317.  
  318.         // flush the disk state cache
  319.         clearstatcache();
  320.  
  321.     // end func doGarbageCollection
  322.  
  323.     /**
  324.     * Returns the filename for the specified id.
  325.     *
  326.     * @param    string  dataset ID
  327.     * @param    string  cache group
  328.     * @return   string  full filename with the path
  329.     * @access   public
  330.     */
  331.     function getFilename($id$group{
  332.  
  333.         if (isset($this->group_dirs[$group]))
  334.             return $this->group_dirs[$group$this->filename_prefix . $id;
  335.  
  336.         $dir $this->cache_dir . $group '/';
  337.         if (!file_exists($dir)) {
  338.             mkdir($dir0755);
  339.             clearstatcache();
  340.         }
  341.  
  342.         $this->group_dirs[$group$dir;
  343.  
  344.         return $dir $this->filename_prefix . $id;
  345.     // end func getFilename
  346.  
  347.     /**
  348.     * Deletes a directory and all files in it.
  349.     *
  350.     * @param    string  directory
  351.     * @return   integer number of removed files
  352.     * @throws   Cache_Error
  353.     */
  354.     function deleteDir($dir{
  355.         if (!($dh opendir($dir)))
  356.             return new Cache_Error("Can't remove directory '$dir'. Check permissions and path."__FILE____LINE__);
  357.  
  358.         $num_removed = 0;
  359.  
  360.         while (false !== $file readdir($dh)) {
  361.             if ('.' == $file || '..' == $file)
  362.                 continue;
  363.  
  364.             $file $dir $file;
  365.             if (is_dir($file)) {
  366.                 $file .= '/';
  367.                 $num $this->deleteDir($file '/');
  368.                 if (is_int($num))
  369.                     $num_removed += $num;
  370.             else {
  371.                 if (unlink($file))
  372.                     $num_removed++;
  373.             }
  374.         }
  375.         // according to php-manual the following is needed for windows installations.
  376.         closedir($dh);
  377.         unset$dh);
  378.         if ($dir != $this->cache_dir{  //delete the sub-dir entries  itself also, but not the cache-dir.
  379.             rmDir($dir);
  380.             $num_removed++;
  381.         }
  382.  
  383.         return $num_removed;
  384.     // end func deleteDir
  385.     
  386. // end class file
  387. ?>

Documentation generated on Mon, 11 Mar 2019 10:14:24 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.