Need this block optimized! Code is from 2003.. WILL PAY ASAP

  Post new topicReply to topicPrintable Version
<< View previous topic View next topic >>
Share: Del.icio.us  Digg  Google  Spurl  Blink  Furl  Y! MyWeb  
#1   Need this block optimized! Code is from 2003.. WILL PAY ASAP
unmgroup
CZ Newbie
unmgroup has been a member for over 17 year's 17 Year Member
Gender: Male
Status: Offline
Joined: Aug 27, 2006
0.00 posts per day
Posts: 2
Points: 0
   
Hi,

I recently decided to setup a remote dedicated database server (on the same network as my dedicated webserver) to handle the increased popularity of my nuke site. However, this block is causing page load times of 17 seconds. Which leads me to believe it's not optimized. Whenever I remove this block from the front page, the site loads in 1 second. All other portions of the site load in under a second as well. So could somebody please optimize this code, or tell me where I can get a more up-to-date version of this center forum block??

The code is here:

<?php

/************************************************************************************/
/*                                                                                  */
/* CENTER BLOCK: block-phpBB_Forums.php                                             */
/* For PHP-Nuke 6.5                                                                 */
/* v1.5  06-04-2003                                                                 */
/*                                                                                  */
/* by: Maty Scripts (webmaster@matyscripts.com)                                     */
/* http://www.matyscripts.com                                                       */
/*                                                                                  */
/* This program is free software. You can redistribute it and/or modify             */
/* it under the terms of the GNU General Public License as published by             */
/* the Free Software Foundation; either version 2 of the License.                   */
/*                                                                                  */
/************************************************************************************/


if( eregi( "block-phpBB_Forums.php", $_SERVER['PHP_SELF'])) {
   Header("Location: index.php");
   die();
}

// include the Cache-Lite package
require_once("includes/Cache_Lite/Lite.php");

// set some variables
$options = array(
  "cacheDir" => "C:/Cache/",
  "lifeTime" => 10
);

// create a Cache_Lite object
$objCache = new Cache_Lite($options);

// test if there exists a valid cache,
// the ID will be the basename of the block
$fileid = basename($blockfile,".php");
if ($content = $objCache->get($fileid)) {
}
else
{
  // do the block's work here...

global $prefix, $user_prefix, $db, $sitename, $bgcolor1, $bgcolor2;


/**********************************/
/*                                */
/* Configuration parameters       */
/*                                */
/**********************************/
// When set to 1 then Forums permissions which View and/or Read are NOT set to 'ALL' will NOT be displayed in the center block
$HideViewReadOnly = 0;
// Show only 5 last new topics
$Last_New_Topics  = 75;                           
// Icon that is displayed in Center Block in front of Topic
$IconPath         = "modules/Forums/templates/subSilver/images/icon_mini_message.gif";

/**********************************/
/*                                */
/* Don't Edit Below !             */
/*                                */
/**********************************/
$border           = 0;
$cellspacing      = 0;
$cellstyle        = "style="border-left-width: 1; border-right-width: 1; border-top-width: 1; border-bottom-style: solid; border-bottom-width: 1"";

/* Total Amount of Topics */
$result = $db->sql_query( "SELECT * FROM ".$prefix."_bbtopics" );
$Amount_Of_Topics = $db->sql_numrows( $result );

/* Total Amount of Posts */
$result = $db->sql_query( "SELECT * FROM ".$prefix."_bbposts" );
$Amount_Of_Posts = $db->sql_numrows( $result );

/* Total Amount of Topic Views */
$Amount_Of_Topic_Views = 1;
$result = $db->sql_query( "SELECT topic_views FROM ".$prefix."_bbtopics" );
while( list( $topic_views ) = $db->sql_fetchrow( $result ) )
{
   $Amount_Of_Topic_Views = $Amount_Of_Topic_Views + $topic_views;
}

/* Total Amount of Topic Replies */
$Amount_Of_Topic_Replies = 1;
$result = $db->sql_query( "SELECT topic_replies FROM ".$prefix."_bbtopics" );
while( list( $topic_replies ) = $db->sql_fetchrow( $result ) )
{
   $Amount_Of_Topic_Replies = $Amount_Of_Topic_Replies + $topic_replies;
}

/* Total Amount of Members */
$result = $db->sql_query( "SELECT * FROM ".$user_prefix."_users" );
$Amount_Of_Members = $db->sql_numrows( $result ) - 1;
/* Last X New Topics */
$Count_Topics = 0;
$Topic_Buffer="";
$content  =  "<center><a href="/modules.php?name=Forums"><img src="images/boards.gif" border="0"></a></center>";
$content  .=  "<center><b>Below is just a snap shot of our popular Message Boards:</b> <br><br>To view all topics, please click the icon above to enter the full<br> message board. Once inside, you can see all topics that have been recently<br> posted. The list below is generated automatically by the most recent posts.</center>";
$content  .=  "<br>";
$content  .=  "<br>";
$content  .=  "<center><font color=006699><b><big><big>Over 42,195+ Posts!</big></big></center></font>";
$content  .=  "<br>";
$content  .=  "<center><font color=gray><b>Some Topics Can Only Be Viewed By Members Logged In.</center></font>";
$content .= "<table><table><tr><td><table width="550" border="0" cellspacing="0" cellpadding="0"><tr><td bgcolor="#CAC8C8"><table width="100%" border="0" cellpadding="1" cellspacing="1" ><tr> ";
$content .= "<th height="20" colspan="2" align="center" nowrap background="images/cellpic69.gif" class="thcornerl"><font color="#FFFFFF"><strong>Topics</strong></font></th>";
$content .= "   <th width="50" align="center" nowrap background="images/cellpic69.gif" class="thtop"><font color="#FFFFFF"><strong>&nbsp;Replies&nbsp;</strong></font></th>";
$content .= "    <th width="75" align="center" nowrap background="images/cellpic69.gif" class="thtop"><font color="#FFFFFF"><strong>&nbsp;Author&nbsp;</strong></font></th>";
$content .= "  <th width="50" align="center" nowrap background="images/cellpic69.gif" class="thtop"><font color="#FFFFFF"><strong>&nbsp;Views&nbsp;</strong></font></th>";
$content .= "  <th align="center" nowrap background="/images/cellpic69.gif" class="thcornerr"><font color="#FFFFFF"><strong>&nbsp;Last Post&nbsp;</strong></font></th>";
$content .= "   </tr>   ";

$result1 = $db->sql_query( "SELECT topic_id, forum_id, topic_last_post_id, topic_title, topic_poster, topic_views, topic_replies, topic_moved_id FROM ".$prefix."_bbtopics ORDER BY topic_last_post_id DESC" );
while( list( $topic_id, $forum_id, $topic_last_post_id, $topic_title, $topic_poster, $topic_views, $topic_replies, $topic_moved_id ) = sql_fetch_row( $result1, $dbi ) )
{
   $skip_display = 0;
   if( $HideViewReadOnly == 1 )
   {
      $result5 = $db->sql_query( "SELECT auth_view, auth_read FROM ".$prefix."_bbforums where forum_id = '$forum_id'" );
      list( $auth_view, $auth_read ) = $db->sql_fetchrow( $result5 );
      if( ( $auth_view != 0 ) or ( $auth_read != 0 ) ) { $skip_display = 1; }
   }
   
   if( $topic_moved_id != 0 )
   {
     // Shadow Topic !!
      $skip_display = 0;
   }
   
   if( $skip_display ==0 )
   {
     $Count_Topics += 1;
      $result2 = $db->sql_query( "SELECT topic_id, poster_id, FROM_UNIXTIME( post_time,'%b %d, %Y at %T') as post_time FROM ".$prefix."_bbposts where post_id = '$topic_last_post_id'" );
      list( $topic_id, $poster_id, $post_time ) = $db->sql_fetchrow( $result2 );

      $result3 = $db->sql_query( "SELECT username, user_id FROM ".$user_prefix."_users where user_id='$poster_id'" );
      list( $uname, $uid ) = $db->sql_fetchrow( $result3 );
      $LastPoster = "<A HREF="modules.php?name=Forums&file=profile&mode=viewprofile&u=$uid"STYLE="text-decoration: none"> $uname </a>";
     
      $result4 = $db->sql_query( "SELECT username, user_id FROM ".$user_prefix."_users where user_id='$topic_poster'" );
      list( $uname, $uid ) = $db->sql_fetchrow( $result4 );
      $OrigPoster = "<A HREF="modules.php?name=Forums&file=profile&mode=viewprofile&u=$uid"STYLE="text-decoration: none"> $uname </a>";
   
      $TopicImage = "<img src="$IconPath" border="0" alt="">";
      $TopicTitleShow = "<a href="modules.php?name=Forums&amp;file=viewtopic&amp;p=$topic_last_post_id#$topic_last_post_id"STYLE="text-decoration: none">$topic_title</a>";


$content .= "<tr><td align="center" height="30" width="30" nowrap bgcolor="#F4F6FB" class="row1"><img src="images/envelope691.gif" border="0" /></td>";
$content .= "<td width="100%" bgcolor="#F4F6FB" class="row1">&nbsp;$TopicTitleShow</td>";
$content .= "<td align="center" bgcolor="#F4F6FB" class="row2">$topic_replies</td>";
$content .= "<td align="center" bgcolor="#F4F6FB" class="row3">$OrigPoster</td>";
$content .= "<td align="center" bgcolor="#F4F6FB" class="row2">$topic_views</td>";
$content .= "<td width="100%" align="center" nowrap bgcolor="#F4F6FB" class="row3"><font size="-2"><i>$post_time</i></font><BR>$LastPoster&nbsp;<a href="modules.php?name=Forums&amp;file=viewtopic&amp;p=$topic_last_post_id#$topic_last_post_id"STYLE="text-decoration: none"><img src="modules/Forums/templates/subSilver/images/icon_newest_reply.gif" border="0" alt="Latest Post"></a></td></tr>   ";

   }
   
   if( $Last_New_Topics == $Count_Topics ) { break 1; }
   
}
$content .= "   <tr> <td bgcolor="#F4F6FB" height="15" colspan="6" align="center" class="cat" background="images/cellpic3.gif">&nbsp;</td>";
$content .= "  </tr>";
$content .= "</table>";
$content .="  </td>      </tr></table></table>";
$content  .=  "<br>";
$content  .=  "<center><a href="/modules.php?name=Forums"><img src="images/enter.png" border="0"></a></center>";
$content  .=  "<br>";
$content .= "<center><b><font color=gray><u>Please Note</u>: The message boards are not moderated, or controlled by the staff!</font></center></b>";
$content  .=  "<br>";
$content  .=  "<br>";

// ...and save it in the cache for future use
  $objCache->save($content, $fileid);
}
?>


Please E-Mail me at: [ Register or login to view links on this board. ] , ICQ Me: 282-055-087, IM me on AOL: PlayBoy4u2c , Yahoo: HollaMayne . I need this done ASAP! And I will pay TOP DOLLAR!


Back to top Reply with quote
#2   re: Need this block optimized! Code is from 2003.. WILL PAY
x-caliber
CZ Newbie
x-caliber has been a member for over 19 year's 19 Year Member
usa.gif ohio.gif
Status: Offline
Joined: Aug 21, 2004
0.00 posts per day
Posts: 25
Points: 1,558
   
First make sure the cache directory is right.

// set some variables
$options = array(
"cacheDir" => "C:/Cache/",
"lifeTime" => 10
);

This file would need looked at also.

includes/Cache_Lite/Lite.php



Back to top Reply with quote
#3   Re: re: Need this block optimized! Code is from 2003.. WILL
unmgroup
CZ Newbie
unmgroup has been a member for over 17 year's 17 Year Member
Gender: Male
Status: Offline
Joined: Aug 27, 2006
0.00 posts per day
Posts: 2
Points: 0
   
The cache directory is right. I have all blocks cached except the user login, and they all work fine. This problem doesn't happen when I use the localhost database server, as opposed to the remote database server. Both servers have 0 loads, because the site isn't online yet.

When running the site using the localhost database, and this block enabled, the load times is around 1 second.

However, when running the site using the remote database, and this block enabled, the load times on the index page is 17 seconds. All other pages on the site is under a second using the remote database server. So I decided to see if it was the block that was causing the issue, and when I disabled the block... the load time on the index page was 1 second using the remote database server. Once enabled it jumps back up to 17 seconds, so it is definitely the block.

Here is the code for lite.php (Which I know is NOT the problem)

<?php

/**
* Fast, light and safe Cache Class
*
* Cache_Lite is a fast, light and safe cache system. It's optimized
* for file containers. It is fast and safe (because it uses file
* locking and/or anti-corruption tests).
*
* There are some examples in the 'docs/examples' file
* Technical choices are described in the 'docs/technical' file
*
* Memory Caching is from an original idea of
* Mike BENOIT <ipso@snappymail.ca>
*
* Nota : A chinese documentation (thanks to RainX <china_1982@163.com>) is
* available at :
* http://rainx.phpmore.com/manual/cache_lite.html
*
* @package Cache_Lite
* @category Caching
* @version $Id: Lite.php,v 1.45 2006/06/03 08:10:33 fab Exp $
* @author Fabien MARTY <fab@php.net>
*/

define('CACHE_LITE_ERROR_RETURN', 1);
define('CACHE_LITE_ERROR_DIE', 8);

class Cache_Lite
{

    // --- Private properties ---

    /**
    * Directory where to put the cache files
    * (make sure to add a trailing slash)
    *
    * @var string $_cacheDir
    */
    var $_cacheDir = 'C:/cache/';

    /**
    * Enable / disable caching
    *
    * (can be very usefull for the debug of cached scripts)
    *
    * @var boolean $_caching
    */
    var $_caching = true;

    /**
    * Cache lifetime (in seconds)
    *
    * If null, the cache is valid forever.
    *
    * @var int $_lifeTime
    */
    var $_lifeTime = 3600;

    /**
    * Enable / disable fileLocking
    *
    * (can avoid cache corruption under bad circumstances)
    *
    * @var boolean $_fileLocking
    */
    var $_fileLocking = true;

    /**
    * Timestamp of the last valid cache
    *
    * @var int $_refreshTime
    */
    var $_refreshTime;

    /**
    * File name (with path)
    *
    * @var string $_file
    */
    var $_file;
   
    /**
    * File name (without path)
    *
    * @var string $_fileName
    */
    var $_fileName;

    /**
    * Enable / disable write control (the cache is read just after writing to detect corrupt entries)
    *
    * Enable write control will lightly slow the cache writing but not the cache reading
    * Write control can detect some corrupt cache files but maybe it's not a perfect control
    *
    * @var boolean $_writeControl
    */
    var $_writeControl = true;

    /**
    * Enable / disable read control
    *
    * If enabled, a control key is embeded in cache file and this key is compared with the one
    * calculated after the reading.
    *
    * @var boolean $_writeControl
    */
    var $_readControl = true;

    /**
    * Type of read control (only if read control is enabled)
    *
    * Available values are :
    * 'md5' for a md5 hash control (best but slowest)
    * 'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
    * 'strlen' for a length only test (fastest)
    *
    * @var boolean $_readControlType
    */
    var $_readControlType = 'crc32';

    /**
    * Pear error mode (when raiseError is called)
    *
    * (see PEAR doc)
    *
    * @see setToDebug()
    * @var int $_pearErrorMode
    */
    var $_pearErrorMode = CACHE_LITE_ERROR_RETURN;
   
    /**
    * Current cache id
    *
    * @var string $_id
    */
    var $_id;

    /**
    * Current cache group
    *
    * @var string $_group
    */
    var $_group;

    /**
    * Enable / Disable "Memory Caching"
    *
    * NB : There is no lifetime for memory caching !
    *
    * @var boolean $_memoryCaching
    */
    var $_memoryCaching = false;

    /**
    * Enable / Disable "Only Memory Caching"
    * (be carefull, memory caching is "beta quality")
    *
    * @var boolean $_onlyMemoryCaching
    */
    var $_onlyMemoryCaching = false;

    /**
    * Memory caching array
    *
    * @var array $_memoryCachingArray
    */
    var $_memoryCachingArray = array();

    /**
    * Memory caching counter
    *
    * @var int $memoryCachingCounter
    */
    var $_memoryCachingCounter = 0;

    /**
    * Memory caching limit
    *
    * @var int $memoryCachingLimit
    */
    var $_memoryCachingLimit = 1000;
   
    /**
    * File Name protection
    *
    * if set to true, you can use any cache id or group name
    * if set to false, it can be faster but cache ids and group names
    * will be used directly in cache file names so be carefull with
    * special characters...
    *
    * @var boolean $fileNameProtection
    */
    var $_fileNameProtection = true;
   
    /**
    * Enable / disable automatic serialization
    *
    * it can be used to save directly datas which aren't strings
    * (but it's slower)   
    *
    * @var boolean $_serialize
    */
    var $_automaticSerialization = false;
   
    /**
    * Disable / Tune the automatic cleaning process
    *
    * The automatic cleaning process destroy too old (for the given life time)
    * cache files when a new cache file is written.
    * 0               => no automatic cache cleaning
    * 1               => systematic cache cleaning
    * x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
    *
    * @var int $_automaticCleaning
    */
    var $_automaticCleaningFactor = 1;
   
    /**
    * Nested directory level
    *
    * Set the hashed directory structure level. 0 means "no hashed directory
    * structure", 1 means "one level of directory", 2 means "two levels"...
    * This option can speed up Cache_Lite only when you have many thousands of
    * cache file. Only specific benchs can help you to choose the perfect value
    * for you. Maybe, 1 or 2 is a good start.
    *
    * @var int $_hashedDirectoryLevel
    */
    var $_hashedDirectoryLevel = 1;
   
    /**
    * Umask for hashed directory structure
    *
    * @var int $_hashedDirectoryUmask
    */
    var $_hashedDirectoryUmask = 0700;
   
    /**
     * API break for error handling in CACHE_LITE_ERROR_RETURN mode
     *
     * In CACHE_LITE_ERROR_RETURN mode, error handling was not good because
     * for example save() method always returned a boolean (a PEAR_Error object
     * would be better in CACHE_LITE_ERROR_RETURN mode). To correct this without
     * breaking the API, this option (false by default) can change this handling.
     *
     * @var boolean
     */
    var $_errorHandlingAPIBreak = false;
   
    // --- Public methods ---

    /**
    * Constructor
    *
    * $options is an assoc. Available options are :
    * $options = array(
    *     'cacheDir' => directory where to put the cache files (string),
    *     'caching' => enable / disable caching (boolean),
    *     'lifeTime' => cache lifetime in seconds (int),
    *     'fileLocking' => enable / disable fileLocking (boolean),
    *     'writeControl' => enable / disable write control (boolean),
    *     'readControl' => enable / disable read control (boolean),
    *     'readControlType' => type of read control 'crc32', 'md5', 'strlen' (string),
    *     'pearErrorMode' => pear error mode (when raiseError is called) (cf PEAR doc) (int),
    *     'memoryCaching' => enable / disable memory caching (boolean),
    *     'onlyMemoryCaching' => enable / disable only memory caching (boolean),
    *     'memoryCachingLimit' => max nbr of records to store into memory caching (int),
    *     'fileNameProtection' => enable / disable automatic file name protection (boolean),
    *     'automaticSerialization' => enable / disable automatic serialization (boolean),
    *     'automaticCleaningFactor' => distable / tune automatic cleaning process (int),
    *     'hashedDirectoryLevel' => level of the hashed directory system (int),
    *     'hashedDirectoryUmask' => umask for hashed directory structure (int),
    *     'errorHandlingAPIBreak' => API break for better error handling ? (boolean)
    * );
    *
    * @param array $options options
    * @access public
    */
    function Cache_Lite($options = array(NULL))
    {
        foreach($options as $key => $value) {
            $this->setOption($key, $value);
        }
    }
   
    /**
    * Generic way to set a Cache_Lite option
    *
    * see Cache_Lite constructor for available options
    *
    * @var string $name name of the option
    * @var mixed $value value of the option
    * @access public
    */
    function setOption($name, $value)
    {
        $availableOptions = array('errorHandlingAPIBreak', 'hashedDirectoryUmask', 'hashedDirectoryLevel', 'automaticCleaningFactor', 'automaticSerialization', 'fileNameProtection', 'memoryCaching', 'onlyMemoryCaching', 'memoryCachingLimit', 'cacheDir', 'caching', 'lifeTime', 'fileLocking', 'writeControl', 'readControl', 'readControlType', 'pearErrorMode');
        if (in_array($name, $availableOptions)) {
            $property = '_'.$name;
            $this->$property = $value;
        }
    }
   
    /**
    * Test if a cache is available and (if yes) return it
    *
    * @param string $id cache id
    * @param string $group name of the cache group
    * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
    * @return string data of the cache (else : false)
    * @access public
    */
    function get($id, $group = 'default', $doNotTestCacheValidity = false)
    {
        $this->_id = $id;
        $this->_group = $group;
        $data = false;
        if ($this->_caching) {
            $this->_setRefreshTime();
            $this->_setFileName($id, $group);
            clearstatcache();
            if ($this->_memoryCaching) {
                if (isset($this->_memoryCachingArray[$this->_file])) {
                    if ($this->_automaticSerialization) {
                        return unserialize($this->_memoryCachingArray[$this->_file]);
                    }
                    return $this->_memoryCachingArray[$this->_file];
                }
                if ($this->_onlyMemoryCaching) {
                    return false;
                }               
            }
            if (($doNotTestCacheValidity) || (is_null($this->_refreshTime))) {
                if (file_exists($this->_file)) {
                    $data = $this->_read();
                }
            } else {
                if ((file_exists($this->_file)) && (@filemtime($this->_file) > $this->_refreshTime)) {
                    $data = $this->_read();
                }
            }
            if (($data) and ($this->_memoryCaching)) {
                $this->_memoryCacheAdd($data);
            }
            if (($this->_automaticSerialization) and (is_string($data))) {
                $data = unserialize($data);
            }
            return $data;
        }
        return false;
    }
   
    /**
    * Save some data in a cache file
    *
    * @param string $data data to put in cache (can be another type than strings if automaticSerialization is on)
    * @param string $id cache id
    * @param string $group name of the cache group
    * @return boolean true if no problem (else : false or a PEAR_Error object)
    * @access public
    */
    function save($data, $id = NULL, $group = 'default')
    {
        if ($this->_caching) {
            if ($this->_automaticSerialization) {
                $data = serialize($data);
            }
            if (isset($id)) {
                $this->_setFileName($id, $group);
            }
            if ($this->_memoryCaching) {
                $this->_memoryCacheAdd($data);
                if ($this->_onlyMemoryCaching) {
                    return true;
                }
            }
            if ($this->_automaticCleaningFactor>0) {
                $rand = rand(1, $this->_automaticCleaningFactor);
                if ($rand==1) {
                    $this->clean(false, 'old');
                }
            }
            if ($this->_writeControl) {
                $res = $this->_writeAndControl($data);
                if (is_bool($res)) {
                    if ($res) {
                        return true; 
                    }
                    // if $res if false, we need to invalidate the cache
                    @touch($this->_file, time() - 2*abs($this->_lifeTime));
                    return false;
                }           
            } else {
                $res = $this->_write($data);
            }
            if (is_object($res)) {
              // $res is a PEAR_Error object
                if (!($this->_errorHandlingAPIBreak)) {   
                   return false; // we return false (old API)
               }
           }
            return $res;
        }
        return false;
    }

    /**
    * Remove a cache file
    *
    * @param string $id cache id
    * @param string $group name of the cache group
    * @return boolean true if no problem
    * @access public
    */
    function remove($id, $group = 'default')
    {
        $this->_setFileName($id, $group);
        if ($this->_memoryCaching) {
            if (isset($this->_memoryCachingArray[$this->_file])) {
                unset($this->_memoryCachingArray[$this->_file]);
                $this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
            }
            if ($this->_onlyMemoryCaching) {
                return true;
            }
        }
        return $this->_unlink($this->_file);
    }

    /**
    * Clean the cache
    *
    * if no group is specified all cache files will be destroyed
    * else only cache files of the specified group will be destroyed
    *
    * @param string $group name of the cache group
    * @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
    *                                        'callback_myFunction'
    * @return boolean true if no problem
    * @access public
    */
    function clean($group = false, $mode = 'ingroup')
    {
        return $this->_cleanDir($this->_cacheDir, $group, $mode);
    }
       
    /**
    * Set to debug mode
    *
    * When an error is found, the script will stop and the message will be displayed
    * (in debug mode only).
    *
    * @access public
    */
    function setToDebug()
    {
        $this->setOption('pearErrorMode', CACHE_LITE_ERROR_DIE);
    }

    /**
    * Set a new life time
    *
    * @param int $newLifeTime new life time (in seconds)
    * @access public
    */
    function setLifeTime($newLifeTime)
    {
        $this->_lifeTime = $newLifeTime;
        $this->_setRefreshTime();
    }

    /**
    * Save the state of the caching memory array into a cache file cache
    *
    * @param string $id cache id
    * @param string $group name of the cache group
    * @access public
    */
    function saveMemoryCachingState($id, $group = 'default')
    {
        if ($this->_caching) {
            $array = array(
                'counter' => $this->_memoryCachingCounter,
                'array' => $this->_memoryCachingState
            );
            $data = serialize($array);
            $this->save($data, $id, $group);
        }
    }

    /**
    * Load the state of the caching memory array from a given cache file cache
    *
    * @param string $id cache id
    * @param string $group name of the cache group
    * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
    * @access public
    */
    function getMemoryCachingState($id, $group = 'default', $doNotTestCacheValidity = false)
    {
        if ($this->_caching) {
            if ($data = $this->get($id, $group, $doNotTestCacheValidity)) {
                $array = unserialize($data);
                $this->_memoryCachingCounter = $array['counter'];
                $this->_memoryCachingArray = $array['array'];
            }
        }
    }
   
    /**
    * Return the cache last modification time
    *
    * BE CAREFUL : THIS METHOD IS FOR HACKING ONLY !
    *
    * @return int last modification time
    */
    function lastModified()
    {
        return @filemtime($this->_file);
    }
   
    /**
    * Trigger a PEAR error
    *
    * To improve performances, the PEAR.php file is included dynamically.
    * The file is so included only when an error is triggered. So, in most
    * cases, the file isn't included and perfs are much better.
    *
    * @param string $msg error message
    * @param int $code error code
    * @access public
    */
    function raiseError($msg, $code)
    {
        include_once('PEAR.php');
        return PEAR::raiseError($msg, $code, $this->_pearErrorMode);
    }
   
    /**
     * Extend the life of a valid cache file
     *
     * see http://pear.php.net/bugs/bug.php?id=6681
     *
     * @access public
     */
    function extendLife()
    {
        @touch($this->_file);
    }
   
    // --- Private methods ---
   
    /**
    * Compute & set the refresh time
    *
    * @access private
    */
    function _setRefreshTime()
    {
        if (is_null($this->_lifeTime)) {
            $this->_refreshTime = null;
        } else {
            $this->_refreshTime = time() - $this->_lifeTime;
        }
    }
   
    /**
    * Remove a file
    *
    * @param string $file complete file path and name
    * @return boolean true if no problem
    * @access private
    */
    function _unlink($file)
    {
        if (!@unlink($file)) {
            return $this->raiseError('Cache_Lite : Unable to remove cache !', -3);
        }
        return true;       
    }

    /**
    * Recursive function for cleaning cache file in the given directory
    *
    * @param string $dir directory complete path (with a trailing slash)
    * @param string $group name of the cache group
    * @param string $mode flush cache mode : 'old', 'ingroup', 'notingroup',
                                             'callback_myFunction'
    * @return boolean true if no problem
    * @access private
    */
    function _cleanDir($dir, $group = false, $mode = 'ingroup')     
    {
        if ($this->_fileNameProtection) {
            $motif = ($group) ? 'cache_'.md5($group).'_' : 'cache_';
        } else {
            $motif = ($group) ? 'cache_'.$group.'_' : 'cache_';
        }
        if ($this->_memoryCaching) {
            while (list($key, ) = each($this->_memoryCachingArray)) {
                if (strpos($key, $motif, 0)) {
                    unset($this->_memoryCachingArray[$key]);
                    $this->_memoryCachingCounter = $this->_memoryCachingCounter - 1;
                }
            }
            if ($this->_onlyMemoryCaching) {
                return true;
            }
        }
        if (!($dh = opendir($dir))) {
            return $this->raiseError('Cache_Lite : Unable to open cache directory !', -4);
        }
        $result = true;
        while ($file = readdir($dh)) {
            if (($file != '.') && ($file != '..')) {
                if (substr($file, 0, 6)=='cache_') {
                    $file2 = $dir . $file;
                    if (is_file($file2)) {
                        switch (substr($mode, 0, 9)) {
                            case 'old':
                                // files older than lifeTime get deleted from cache
                                if (!is_null($this->_lifeTime)) {
                                    if ((mktime() - @filemtime($file2)) > $this->_lifeTime) {
                                        $result = ($result and ($this->_unlink($file2)));
                                    }
                                }
                                break;
                            case 'notingrou':
                                if (!strpos($file2, $motif, 0)) {
                                    $result = ($result and ($this->_unlink($file2)));
                                }
                                break;
                            case 'callback_':
                                $func = substr($mode, 9, strlen($mode) - 9);
                                if ($func($file2, $group)) {
                                    $result = ($result and ($this->_unlink($file2)));
                                }
                                break;
                            case 'ingroup':
                            default:
                                if (strpos($file2, $motif, 0)) {
                                    $result = ($result and ($this->_unlink($file2)));
                                }
                                break;
                        }
                    }
                    if ((is_dir($file2)) and ($this->_hashedDirectoryLevel>0)) {
                        $result = ($result and ($this->_cleanDir($file2 . '/', $group, $mode)));
                    }
                }
            }
        }
        return $result;
    }
     
    /**
    * Add some date in the memory caching array
    *
    * @param string $data data to cache
    * @access private
    */
    function _memoryCacheAdd($data)
    {
        $this->_memoryCachingArray[$this->_file] = $data;
        if ($this->_memoryCachingCounter >= $this->_memoryCachingLimit) {
            list($key, ) = each($this->_memoryCachingArray);
            unset($this->_memoryCachingArray[$key]);
        } else {
            $this->_memoryCachingCounter = $this->_memoryCachingCounter + 1;
        }
    }

    /**
    * Make a file name (with path)
    *
    * @param string $id cache id
    * @param string $group name of the group
    * @access private
    */
    function _setFileName($id, $group)
    {
       
        if ($this->_fileNameProtection) {
            $suffix = 'cache_'.md5($group).'_'.md5($id);
        } else {
            $suffix = 'cache_'.$group.'_'.$id;
        }
        $root = $this->_cacheDir;
        if ($this->_hashedDirectoryLevel>0) {
            $hash = md5($suffix);
            for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
                $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
            }   
        }
        $this->_fileName = $suffix;
        $this->_file = $root.$suffix;
    }
   
    /**
    * Read the cache file and return the content
    *
    * @return string content of the cache file (else : false or a PEAR_Error object)
    * @access private
    */
    function _read()
    {
        $fp = @fopen($this->_file, "rb");
        if ($this->_fileLocking) @flock($fp, LOCK_SH);
        if ($fp) {
            clearstatcache();
            $length = @filesize($this->_file);
            $mqr = get_magic_quotes_runtime();
            set_magic_quotes_runtime(0);
            if ($this->_readControl) {
                $hashControl = @fread($fp, 32);
                $length = $length - 32;
            }
            if ($length) {
                $data = @fread($fp, $length);
            } else {
                $data = '';
            }
            set_magic_quotes_runtime($mqr);
            if ($this->_fileLocking) @flock($fp, LOCK_UN);
            @fclose($fp);
            if ($this->_readControl) {
                $hashData = $this->_hash($data, $this->_readControlType);
                if ($hashData != $hashControl) {
                    if (!(is_null($this->_lifeTime))) {
                        @touch($this->_file, time() - 2*abs($this->_lifeTime));
                    } else {
                        @unlink($this->_file);
                    }
                    return false;
                }
            }
            return $data;
        }
        return $this->raiseError('Cache_Lite : Unable to read cache !', -2);
    }
   
    /**
    * Write the given data in the cache file
    *
    * @param string $data data to put in cache
    * @return boolean true if ok (a PEAR_Error object else)
    * @access private
    */
    function _write($data)
    {
        if ($this->_hashedDirectoryLevel > 0) {
            $hash = md5($this->_fileName);
            $root = $this->_cacheDir;
            for ($i=0 ; $i<$this->_hashedDirectoryLevel ; $i++) {
                $root = $root . 'cache_' . substr($hash, 0, $i + 1) . '/';
                if (!(@is_dir($root))) {
                    @mkdir($root, $this->_hashedDirectoryUmask);
                }
            }
        }
        $fp = @fopen($this->_file, "wb");
        if ($fp) {
            if ($this->_fileLocking) @flock($fp, LOCK_EX);
            if ($this->_readControl) {
                @fwrite($fp, $this->_hash($data, $this->_readControlType), 32);
            }
            $len = strlen($data);
            @fwrite($fp, $data, $len);
            if ($this->_fileLocking) @flock($fp, LOCK_UN);
            @fclose($fp);
            return true;
        }     
        return $this->raiseError('Cache_Lite : Unable to write cache file : '.$this->_file, -1);
    }
       
    /**
    * Write the given data in the cache file and control it just after to avoir corrupted cache entries
    *
    * @param string $data data to put in cache
    * @return boolean true if the test is ok (else : false or a PEAR_Error object)
    * @access private
    */
    function _writeAndControl($data)
    {
        $result = $this->_write($data);
        if (is_object($result)) {
            return $result; #Â We return the PEAR_Error object
        }
        $dataRead = $this->_read();
        if (is_object($dataRead)) {
            return $result; #Â We return the PEAR_Error object
        }
        if ((is_bool($dataRead)) && (!$dataRead)) {
            return false;
        }
        return ($dataRead==$data);
    }
   
    /**
    * Make a control key with the string containing datas
    *
    * @param string $data data
    * @param string $controlType type of control 'md5', 'crc32' or 'strlen'
    * @return string control key
    * @access private
    */
    function _hash($data, $controlType)
    {
        switch ($controlType) {
        case 'md5':
            return md5($data);
        case 'crc32':
            return sprintf('% 32d', crc32($data));
        case 'strlen':
            return sprintf('% 32d', strlen($data));
        default:
            return $this->raiseError('Unknown controlType ! (available values are only 'md5', 'crc32', 'strlen')', -5);
        }
    }
   
}

?>





Originally posted by x-caliber @ Sun Oct 08, 2006 11:26 pm:

First make sure the cache directory is right.

// set some variables
$options = array(
"cacheDir" => "C:/Cache/",
"lifeTime" => 10
);

This file would need looked at also.

includes/Cache_Lite/Lite.php



Back to top Reply with quote
Display posts from previous:      
Add To: Del.icio.us  Digg  Google  Spurl  Blink  Furl  Y! MyWeb  
<< View previous topic View next topic >>
Post new topicReply to topic

Jump to 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum