http://www.zoned.net/~xkahn/php/fasttemplate Portions written by Benjamin Kahn Copyright (c) 2000 CyberSites, Inc; xkahn@cybersites.com, All Rights Reserved originally by: "JP" http://www.phpbuilder.com/columns/jprins20000201.php3 with code by: Spencer D. Mindlin http://www.phpbuilder.com/columns/spencer20000208.php3 Portions of this code are based on code from FastTemplate for PHP Copyright (c) 1999 CDI, cdi@thewebmasters.net, All Rights Reserved. */ class cachedFastTemplate extends FastTemplate { var $CACHE = array(); // An array of arrays which set // caching on a block // ************************************************************ function cachedFastTemplate ($pathToTemplates = "") { $this->FastTemplate ($pathToTemplates); } // end (new) FastTemplate () // ********************* // Function: is_cached // Input: RETURN, FileHandle (FIXME: Plural FileHandles are not supported.) // Return: true or false depending on whether a cache file is available. // Side Effects: assigns variables as if a parse call had been made // // Notes: // Find the cache name, and see if the file exists // If it doesn't, return FALSE // If it does, check is the file is current (see ~/src/php-cache.php) // If is isn't, return FALSE // check if the section is dynamic. If so, use clear_dynamic to insert contents of file // If not, assign file contents to ReturnVar // return TRUE function is_cached ( $ReturnVar, $FileTags ) { // Fixme: We should do something smart if $FileTags is an array $str_cache_file = $this->cache_file_name( $ReturnVar, $FileTags ); // This function will wait until a cache has been created. (Lock file cleared.) clearstatcache($str_cache_file); // Here we perform some error correction. If a lock file // is left over from a previous request, this ensures that // it is deleted. // FIXME: If this takes too long, we should turn caching off for this file, and return FALSE; while (file_exists($str_cache_file . '.lock')) { sleep(2); clearstatcache(); continue; } clearstatcache(); // If the cache file doesn't exist, it isn't cached. QED. if (!file_exists($str_cache_file)) { return FALSE; } // Now we need to find out if we are caching. $refresh = $this->CACHE[$FileTags]["refresh"]; $expires = $this->CACHE[$FileTags]["expire"]; $cache_read = 0; // Default to no read if (!refresh && !expires) // Do we have any set time? $expires = 600; if (isset ($expires)) { if ((filectime ($str_cache_file) + $expires) > date ( "U")) { $cache_read = 1; } } if (isset ($refresh)) { switch (strtoupper($refresh)) { case 'MINUTE': if (checkRefreshMinute(mktime(), filemtime($str_cache_file))) { $cache_read = 1; } break; case 'QUARTERHOUR': if (checkRefreshQuarterHour(mktime(), filemtime($str_cache_file))) { $cache_read = 1; } break; case 'HALFHOUR': if (checkRefreshHalfHour(mktime(), filemtime($str_cache_file))) { $cache_read = 1; } break; case 'HOUR': if (checkRefreshHour(mktime(), filemtime($str_cache_file))) { $cache_read = 1; } break; case 'HALFDAY': if (checkExpiredHalfDay(mktime(), filemtime($str_cache_file))) { $cache_read = 1; } break; case 'DAY': if (checkRefreshDay(mktime(), filemtime($str_cache_file))) { $cache_read = 1; } break; case 'MONTH': if (checkRefreshMonth(mktime(), filemtime($str_cache_file))) { $cache_read = 1; } } } if ($cache_read == 1) { // We have a cache file and we should read from it! if ($f = fopen ($str_cache_file, "r")) { $buf = ""; while ($str = fgets ($f, 4096)) { $buf .= $str; } fclose ($f); $this->LAST = $ReturnVar; // This is the part that actually does all the work. // The template and the parsed version are the same when caching $this->assign( array( $ReturnVar => $buf ) ); $this->$ReturnVar = $buf; $this->$FileTags = $buf; $this->LOADED[$FileTags] = "1"; // Make sure the template doesn't get loaded. // If we were supposed to be appending, maybe we should assume a dynamic block if ( (substr ($FileTags, 0, 1)) == '.' ) { $this->add_cache_dynamic ($ReturnVar, $buf); } return TRUE; } $this->ROOT = $root; } } // End set_root() // ********************* // Function: write_cache // Input: RETURN, FileHandle (FIXME: Plural FileHandles are not supported.) // Return: true or false depending on whether a cache file could be created // Side Effects: None // // Notes: // Find the cache name. // Write out the ReturnVar contents to the file // Return function write_cache ( $ReturnVar, $FileTags ) { // FIXME: I should do something clever if $FileTags is an array. $str_cache_file = $this->cache_file_name ( $ReturnVar, $FileTags ); $new = $this->parse_template_messy ($this->$FileTags, $this->PARSEVARS); // Time to write the cache -- but we need to look out for lock files // FIXME: I'm SURE there is a race condition here. while (file_exists($str_cache_file . '.lock')) { sleep(2); clearstatcache(); continue; } clearstatcache(); // We pray that nothing bad happens after this point. touch ($str_cache_file . '.lock'); $f = fopen ($str_cache_file, "w"); if (!$f) return FALSE; fputs ($f, $new); fclose ($f); // And remove the lock file. $this->remove_cache_lock ($str_cache_file); return TRUE; } // ********************* // Function: cache_expire // Input: RETURN, number_of_seconds // Return: None // Side Effects: Stores time to expire // // Notes: // tells in how many seconds the cached data will expire function cache_expire ( $ReturnVar, $seconds = 3000) { $this->CACHE[$ReturnVar]["expire"] = $seconds; } // ********************* // Function: cache_refresh // Input: RETURN, frequency // Return: None // Side Effects: Stores time to refresh // // Notes: // sets an event (turn of day) at which cache will expire function cache_refresh ( $ReturnVar, $freq = 'HOUR') { $this->CACHE[$ReturnVar]["refresh"] = $freq; } // ************************************************************ // All templates will be loaded from this "root" directory // Can be changed in mid-process by re-calling with a new // value. function set_root ($root) { $trailer = substr($root,-1); if(!$this->WIN32) { if( (ord($trailer)) != 47 ) { $root = "$root". chr(47); } if(is_dir($root)) { $this->ROOT = $root; } else { $this->ROOT = ""; $this->error("Specified ROOT dir [$root] is not a directory"); } } else { // WIN32 box - no testing if( (ord($trailer)) != 92 ) { $root = "$root" . chr(92); } $this->ROOT = $root; } } // End set_root() function parse_template_messy ($template, $tpl_array) { $a = strtok($template,"{"); $oldtemp = $template; while($a || $t) { $t = strtok("}"); if($t){ settype($tpl_array[$t],"string"); if(empty($tpl_array[$t])){ $toprint = $toprint . $a . "{". $t . "}"; // Recreate the substitution. } else { $toprint = $toprint . $a . $tpl_array[$t]; } } else { $toprint = $toprint . $a; } //print('T-' . $t . '
'); //print('value' . htmlentities($tpl_array[$t]) . '
'); //print('A-' . htmlentities($a) . '
'); $a = strtok("{"); } $template = $toprint; return $template; } // end parse_template_messy(); // ************************************************************ // Adds cached data to a DYNAMIC BLOCK from a template. function add_cache_dynamic ($Macro="", $cache_data="" ) { if(empty($Macro)) { return false; } // The file must already be in memory. $ParentTag = $this->DYNAMIC["$Macro"]; if( (!$this->$ParentTag) or (empty($this->$ParentTag)) ) { $fileName = $this->FILELIST[$ParentTag]; $this->$ParentTag = $this->get_template($fileName); $this->LOADED[$ParentTag] = 1; } if($this->$ParentTag) { $template = $this->$ParentTag; $DataArray = split("\n",$template); $newParent = ""; $outside = true; $start = false; $end = false; while ( list ($lineNum,$lineData) = each ($DataArray) ) { $lineTest = trim($lineData); if("" == "$lineTest" ) { $start = true; $end = false; $outside = false; } if("" == "$lineTest" ) { $start = false; $end = true; $outside = true; } if( ($outside) and (!$start) and (!$end) ) { $newParent .= "$lineData\n"; // Restore linebreaks } if ($end) { $newParent .= $cache_data; } // Next line please if($end) { $end = false; } if($start) { $start = false; } } // end While $this->$ParentTag = $newParent; return true; } else {// $ParentTag NOT loaded - MAJOR oopsie @error_log("ParentTag: [$ParentTag] not loaded!",0); $this->error("ParentTag: [$ParentTag] not loaded!",0); } return false; } // ************************************************************ // Caching system //*********************************/ // Some other functions function remove_cache_lock($str_cache_file) { clearstatcache(); if (file_exists($str_cache_file . '.lock')) { @unlink($str_cache_file . '.lock'); } } // Create the cache file name function cache_file_name ( $ReturnVar, $FileTags ) { // What are we going to do? $str_cache_root = "/tmp/"; $str_cache_dir = strtolower(getenv ("HTTP_HOST")) . getenv ("SCRIPT_URL"); if ( (substr ($FileTags, 0, 1)) == '.' ) { $str_cache_file = "/" . substr($FileTags,1); } else { $str_cache_file = "/" . $FileTags; } // First we need to make the directory the cache file is in if it doesn't already exist. if ($this->rmkdir ($str_cache_root . $str_cache_dir)) return $str_cache_root . $str_cache_dir . $str_cache_file; return; } // Create a directory tree function rmkdir ( $directory ) { // If we encounter this as a file, we can't make it a directory $type = filetype ( $directory ); if ($type != 'dir' && $type != 'FALSE' && !empty($type)) { return FALSE; } if ($type == 'dir') return TRUE; $pieces = explode ("/", $directory); for ($num = 0; $num < count($pieces); $num += 1) { $so_far = $so_far . "/" . $pieces[$num]; $type = filetype ( $so_far ); if ($type != 'dir' && $type != 'FALSE' && !empty($type)) { return FALSE; } if ($type == 'dir') { continue; } if (!mkdir ($so_far, 0700)) { return FALSE; } } return TRUE; } //*********************************/ // CACHE REFRESH CHECKING FUNCTIONS // Each function checks the next interval higher for verification function checkRefreshYear($systime, $filetime) { $sysYear = date( "y", $systime); $fileYear = date( "y", $filetime); if ($sysYear != $fileYear) { return false; } return true; } function checkRefreshMonth($systime, $filetime) { $sysMonth = date( "M", $systime); $fileMonth = date( "M", $filetime); if ($sysMonth != $fileMonth) { return false; } if (!(checkRefreshYear($systime, $filetime))) { return false; } return true; } function checkRefreshDay($systime, $filetime) { $sysDay = date( "j", $systime); $fileDay = date( "j", $filetime); if ($sysDay != $fileDay) { return false; } if (!(checkRefreshMonth($systime, $filetime))) { return false; } return true; } function checkRefreshDayHalf($systime, $filetime) { $sysHour = date( "H", $systime); $fileHour = date( "H", $filetime); if (($sysHour % 12) < ($fileHour % 12)) { return false; } if (!(checkRefreshDay($systime, $filetime))) { return false; } return true; } function checkRefreshHour($systime, $filetime) { $sysHour = date( "H", $systime); $fileHour = date( "H", $filetime); if ($sysHour != $fileHour) { return false; } if (!(checkRefreshDayHalf($systime, $filetime))) { return false; } return true; } function checkRefreshHalfHour($systime, $filetime) { $sysMin = date( "i", $systime); $fileMin = date( "i", $filetime); if (($sysMin % 30) < ($fileMin % 30)) { return false; } if (!(checkRefreshHour($systime, $filetime))) { return false; } return true; } function checkRefreshQuarterHour($systime, $filetime) { $sysMin = date( "i", $systime); $fileMin = date( "i", $filetime); if (($sysMin % 15) < ($fileMin % 15)) { return false; } if (!(checkRefreshHalfHour($systime, $filetime))) { return false; } return true; } function checkRefreshMinute($systime, $filetime) { $sysMin = date( "i", $systime); $fileMin = date( "i", $filetime); if ($sysMin != $fileMin) { return false; } if (!(checkRefreshQuarterHour($systime, $filetime))) { return false; } return true; } } // End class.cacheFastTemplate ?>