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

Documentation generated on Mon, 11 Mar 2019 15:25:50 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.