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.17 2005/02/18 10:21:16 dufuz 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.17 2005/02/18 10:21:16 dufuz 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.         $cachedata $this->decode(fread($fhfilesize($file)));
  155.  
  156.         // Unlocking
  157.         if ($this->fileLocking{
  158.             flock($fhLOCK_UN);
  159.         }
  160.         fclose($fh);
  161.  
  162.         // last usage date used by the gc - maxlifetime
  163.         // touch without second param produced stupid entries...
  164.         touch($file,time());
  165.         clearstatcache();
  166.  
  167.         return array($expire$cachedata$userdata);
  168.     // end func fetch
  169.  
  170.     /**
  171.     * Stores a dataset.
  172.     *
  173.     * WARNING: If you supply userdata it must not contain any linebreaks,
  174.     * otherwise it will break the filestructure.
  175.     */
  176.     function save($id$cachedata$expires$group$userdata)
  177.     {
  178.         $this->flushPreload($id$group);
  179.  
  180.         $file $this->getFilename($id$group);
  181.         if (!($fh @fopen($file'wb'))) {
  182.             return new Cache_Error("Can't access '$file' to store cache data. Check access rights and path."__FILE____LINE__);
  183.         }
  184.  
  185.         // File locking (exclusive lock)
  186.         if ($this->fileLocking{
  187.             flock($fhLOCK_EX);
  188.         }
  189.         // file format:
  190.         // 1st line: expiration date
  191.         // 2nd line: user data
  192.         // 3rd+ lines: cache data
  193.         $expires $this->getExpiresAbsolute($expires);
  194.         fwrite($fh$expires "\n");
  195.         fwrite($fh$userdata "\n");
  196.         fwrite($fh$this->encode($cachedata));
  197.  
  198.         // File unlocking
  199.         if ($this->fileLocking{
  200.             flock($fhLOCK_UN);
  201.         }
  202.         fclose($fh);
  203.  
  204.         // I'm not sure if we need this
  205.     // i don't think we need this (chregu)
  206.         // touch($file);
  207.  
  208.         return true;
  209.     // end func save
  210.  
  211.     function remove($id$group)
  212.     {
  213.         $this->flushPreload($id$group);
  214.  
  215.         $file $this->getFilename($id$group);
  216.         if (PEAR::isError($file)) {
  217.             return $file;
  218.         }
  219.  
  220.         if (file_exists($file)) {
  221.             $ok unlink($file);
  222.             clearstatcache();
  223.  
  224.             return $ok;
  225.         }
  226.  
  227.         return false;
  228.     // end func remove
  229.  
  230.     function flush($group)
  231.     {
  232.         $this->flushPreload();
  233.         $dir ($group$this->cache_dir . $group '/' $this->cache_dir;
  234.  
  235.         $num_removed $this->deleteDir($dir);
  236.         unset($this->group_dirs[$group]);
  237.         clearstatcache();
  238.  
  239.         return $num_removed;
  240.     // end func flush
  241.  
  242.     function idExists($id$group)
  243.     {
  244.         return file_exists($this->getFilename($id$group));
  245.     // end func idExists
  246.  
  247.     /**
  248.     * Deletes all expired files.
  249.     *
  250.     * Garbage collection for files is a rather "expensive", "long time"
  251.     * operation. All files in the cache directory have to be examined which
  252.     * means that they must be opened for reading, the expiration date has to be
  253.     * read from them and if neccessary they have to be unlinked (removed).
  254.     * If you have a user comment for a good default gc probability please add it to
  255.     * to the inline docs.
  256.     *
  257.     * @param    integer Maximum lifetime in seconds of an no longer used/touched entry
  258.     * @throws   Cache_Error
  259.     */
  260.     function garbageCollection($maxlifetime)
  261.     {
  262.         $this->flushPreload();
  263.         clearstatcache();
  264.  
  265.         $ok $this->doGarbageCollection($maxlifetime$this->cache_dir);
  266.  
  267.         // check the space used by the cache entries        
  268.         if ($this->total_size > $this->highwater{
  269.         
  270.             krsort($this->entries);
  271.             reset($this->entries);
  272.             
  273.             while ($this->total_size > $this->lowwater && list($lastmod$entryeach($this->entries)) {
  274.                 if (@unlink($entry['file'])) {
  275.                     $this->total_size -= $entry['size'];
  276.                 else {
  277.                     new CacheError("Can't delete {$entry['file']}. Check the permissions.");
  278.                 }
  279.             }
  280.             
  281.         }
  282.         
  283.         $this->entries = array();
  284.         $this->total_size = 0;
  285.         
  286.         return $ok;
  287.     // end func garbageCollection
  288.     
  289.     /**
  290.     * Does the recursive gc procedure, protected.
  291.     *
  292.     * @param    integer Maximum lifetime in seconds of an no longer used/touched entry
  293.     * @param    string  directory to examine - don't sets this parameter, it's used for a
  294.     *                    recursive function call!
  295.     * @throws   Cache_Error
  296.     */
  297.     function doGarbageCollection($maxlifetime$dir)
  298.     {
  299.         if (!is_writable($dir|| !is_readable($dir|| !($dh opendir($dir))) {
  300.             return new Cache_Error("Can't remove directory '$dir'. Check permissions and path."__FILE____LINE__);
  301.         }
  302.  
  303.         while ($file readdir($dh)) {
  304.             if ('.' == $file || '..' == $file)
  305.                 continue;
  306.  
  307.             $file $dir $file;
  308.             if (is_dir($file)) {
  309.                 $this->doGarbageCollection($maxlifetime,$file '/');
  310.                 continue;
  311.             }
  312.  
  313.             // skip trouble makers but inform the user
  314.             if (!($fh @fopen($file'rb'))) {
  315.                 new Cache_Error("Can't access cache file '$file', skipping it. Check permissions and path."__FILE____LINE__);
  316.                 continue;
  317.             }
  318.  
  319.             $expire fgets($fh11);
  320.             fclose($fh);
  321.             $lastused filemtime($file);
  322.             
  323.             $this->entries[$lastused= array('file' => $file'size' => filesize($file));
  324.             $this->total_size += filesize($file);
  325.             
  326.             // remove if expired
  327.             if (( ($expire && $expire <= time()) || ($lastused <= (time($maxlifetime)) ) && !unlink($file)) {
  328.                 new Cache_Error("Can't unlink cache file '$file', skipping. Check permissions and path."__FILE____LINE__);
  329.             }
  330.         }
  331.  
  332.         closedir($dh);
  333.  
  334.         // flush the disk state cache
  335.         clearstatcache();
  336.  
  337.     // end func doGarbageCollection
  338.  
  339.     /**
  340.     * Returns the filename for the specified id.
  341.     *
  342.     * @param    string  dataset ID
  343.     * @param    string  cache group
  344.     * @return   string  full filename with the path
  345.     * @access   public
  346.     */
  347.     function getFilename($id$group)
  348.     {
  349.         if (isset($this->group_dirs[$group])) {
  350.             return $this->group_dirs[$group$this->filename_prefix . $id;
  351.         }
  352.  
  353.         $dir $this->cache_dir . $group '/';
  354.         if (is_writeable($this->cache_dir)) {
  355.             if (!file_exists($dir)) {
  356.                 mkdir($dir0755);
  357.                 clearstatcache();
  358.             }
  359.         else {
  360.             return new Cache_Error("Can't make directory '$dir'. Check permissions and path."__FILE____LINE__);
  361.         }
  362.         $this->group_dirs[$group$dir;
  363.  
  364.         return $dir $this->filename_prefix . $id;
  365.     // end func getFilename
  366.  
  367.     /**
  368.     * Deletes a directory and all files in it.
  369.     *
  370.     * @param    string  directory
  371.     * @return   integer number of removed files
  372.     * @throws   Cache_Error
  373.     */
  374.     function deleteDir($dir)
  375.     {
  376.         if (!is_writable($dir|| !is_readable($dir|| !($dh opendir($dir))) {
  377.             return new Cache_Error("Can't remove directory '$dir'. Check permissions and path."__FILE____LINE__);
  378.         }
  379.  
  380.         $num_removed = 0;
  381.  
  382.         while (false !== $file readdir($dh)) {
  383.             if ('.' == $file || '..' == $file)
  384.                 continue;
  385.  
  386.             $file $dir $file;
  387.             if (is_dir($file)) {
  388.                 $file .= '/';
  389.                 $num $this->deleteDir($file '/');
  390.                 if (is_int($num))
  391.                     $num_removed += $num;
  392.             else {
  393.                 if (unlink($file))
  394.                     $num_removed++;
  395.             }
  396.         }
  397.         // according to php-manual the following is needed for windows installations.
  398.         closedir($dh);
  399.         unset$dh);
  400.         if ($dir != $this->cache_dir{  //delete the sub-dir entries  itself also, but not the cache-dir.
  401.             rmDir($dir);
  402.             $num_removed++;
  403.         }
  404.  
  405.         return $num_removed;
  406.     // end func deleteDir
  407.     
  408. // end class file
  409. ?>

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