/*=====================================================================*\
|| ###################################################################
|| # Blue Static ISSO Framework
-|| # Copyright ©2002-[#]year[#] Blue Static
+|| # Copyright (c)2005-2009 Blue Static
|| #
|| # 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; version [#]gpl[#] of the License.
+|| # the Free Software Foundation; version 2 of the License.
|| #
|| # This program is distributed in the hope that it will be useful, but
|| # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
\*=====================================================================*/
/**
-* Database-Driven Template System (template.php)
-*
-* @package ISSO
-*/
+ * Database-Driven Template System (template.php)
+ *
+ * @package ISSO
+ */
-require_once('ISSO/Functions.php');
+require_once(ISSO . '/Functions.php');
/**
-* File-Based Template System
-*
-* This framework merely replaces the template loading functions with
-* file-system based ones. It has an optional caching system in which
-* template data will remain stored in the database as long as the filesystem
-* file is modified. To do this, pass a table name to setDatabaseCache() and make sure
-* there's a DB module that has access to a table with this schema:
-*
-* CREATE TABLE template (filename VARCHAR (250) NOT NULL, template TEXT NOT NULL, timestamp INT NOT NULL);
-*
-* @author Blue Static
-* @copyright Copyright ©2002 - [#]year[#], Blue Static
-* @version $Revision$
-* @package ISSO
-*
-*/
+ * File-Based Template System
+ *
+ * This framework merely replaces the template loading functions with
+ * file-system based ones. It has an optional caching system in which
+ * template data will remain stored in the database as long as the filesystem
+ * file is modified. To do this, pass a table name to setDatabaseCache() and make sure
+ * there's a DB module that has access to a table with this schema:
+ *
+ * CREATE TABLE template (filename VARCHAR (250) NOT NULL, template TEXT NOT NULL, timestamp INT NOT NULL);
+ *
+ * @author Blue Static
+ * @copyright Copyright (c)2005 - 2009, Blue Static
+ * @package ISSO
+ *
+ */
class BSTemplate
{
/**
- * The path, from the path of the application, where templates are stored
- * @var string
- */
- private $templateDir = '';
-
- /**
- * The extension all the template files have
- * @var string
- */
- private $extension = 'tpl';
-
- /**
- * The database table name for the template cache
- * @var string
- */
- private $dbCacheTable = null;
-
+ * The name of a function that is called before template parsing of phrases and conditionals occurs
+ * @var string
+ */
+ public static $preParseHook = ':undefined:';
+
/**
- * The name of the function phrases are fetched with
- * @var string
- */
- private $langcall = 'gettext';
+ * The database table name for the template cache
+ * @var string
+ */
+ public static $dbCacheTable = null;
/**
- * The name of the function phrases are sprintf() parsed with
- * @var string
- */
- private $langconst = 'sprintf';
+ * The name of the function phrases are fetched with
+ * @var string
+ */
+ public static $langcall = 'gettext';
/**
- * Array of pre-compiled templates that are stored to decrease server load
- * @var array
- */
- protected $cache = array();
+ * The template path pattern; for instance, this could be: ./templates/%s.tpl
+ * @var string
+ */
+ public static $templatePath = '%s';
/**
- * A list of templates that weren't cached, but are still used
- * @var array
- */
- protected $uncached = array();
+ * Array of pre-compiled templates that are stored for optimization
+ * @var array
+ */
+ protected static $cache = array();
/**
- * Whether or not the page has been flush()'d already
- * @var bool
- */
- private $doneflush = false;
+ * The name of the function phrases are sprintf() parsed with
+ * @var string
+ */
+ public static $langconst = 'sprintf';
/**
- * The name of a function that is called before template parsing of phrases and conditionals occurs
- * @var string
- */
- private $preParseHook = ':undefined:';
+ * Template variables to populate
+ * @var array
+ */
+ public $vars = array();
- // ###################################################################
/**
- * Sets the template directory name
- *
- * @param string Template directory name
- */
- public function setTemplateDirectory($dir)
- {
- $this->templateDir = BSFunctions::FetchSourcePath($dir);
- }
+ * Global variables
+ * @var array
+ */
+ public static $globalVars = array();
- // ###################################################################
/**
- * Sets the file extension for the templates
- *
- * @param string File extension
- */
- public function setExtension($ext)
- {
- $this->extension = $ext;
- }
+ * The path of the template file
+ * @var string
+ */
+ protected $path;
- // ###################################################################
/**
- * Sets the name of the table to access for the datbase cache
- *
- * @param string DB table name
- */
- public function setDatabaseCache($table)
- {
- $this->dbCacheTable = $table;
- }
+ * The name of the template
+ * @var string
+ */
+ protected $name;
- // ###################################################################
/**
- * Sets the pre-parse hook method which is called before any other
- * processing is done on the template.
- *
- * @param string Method name
- */
- public function setPreParseHook($hook)
- {
- $this->preParseHook = $hook;
- }
+ * Template contents
+ * @var string
+ */
+ protected $template;
- // ###################################################################
/**
- * Takes an array of template names, loads them, and then stores a
- * parsed version for optimum speed.
- *
- * @param array List of template names to be cached
- */
- public function cache($namearray)
+ * Takes an array of template names, loads them, and then stores a
+ * parsed version for optimum speed.
+ *
+ * @param array List of template names to be cached
+ */
+ public static function cache($namearray)
{
- if (sizeof($this->cache) > 0)
+ if (!self::$dbCacheTable)
{
- throw new Exception('You cannot cache templates more than once per initialization');
+ return; // there's no point in pre-caching file templates
}
- else
+
+ $namearray = array_map(array('self', '_path'), $namearray);
+ $cache = BSApp::$db->query("SELECT * FROM " . self::$dbCacheTable . " WHERE filename IN ('" . implode("', '", $namearray) . "')");
+ while ($tpl = $cache->fetchArray())
{
- $dbCache = array();
- if ($this->dbCacheTable)
- {
- $db =& BSApp::Registry()->getType('Db');
- $cache = $db->query("SELECT * FROM {$this->dbCacheTable} WHERE filename IN ('" . implode("', '", $namearray) . "')");
- while ($tpl = $db->fetchArray($cache))
- {
- $time = filemtime($this->templateDir . $tpl['filename'] . '.' . $this->extension);
- $template = $tpl['template'];
- if ($time > $tpl['timestamp'])
- {
- $template = $this->_parseTemplate($this->_loadTemplate($tpl['filename']));
- $db->query("UPDATE {$this->dbCacheTable} SET template = '" . $db->escapeString($template) . "', timestamp = " . TIMENOW . " WHERE filename = '" . $tpl['filename'] . "'");
- $tpl['template'] = $template;
- }
- $dbCache["$tpl[filename]"] = $template;
- }
- }
- foreach ($namearray AS $name)
- {
- if ($this->dbCacheTable)
- {
- if (isset($dbCache["$name"]))
- {
- $template = $dbCache["$name"];
- }
- else
- {
- $template = $this->_parseTemplate($this->_loadTemplate($name));
- $db->query("INSERT INTO {$this->dbCacheTable} (filename, template, timestamp) VALUES ('$name', '" . $db->escapeString($template) . "', " . TIMENOW . ")");
- }
- }
- else
- {
- $template = $this->_parseTemplate($this->_loadTemplate($name));
- }
-
- $this->cache[$name] = $template;
- }
+ self::$cache[$tpl['filename']] = $tpl;
}
}
- // ###################################################################
/**
- * Loads a template from the cache or the _load function and stores the
- * parsed version of it
- *
- * @param string The name of the template
- *
- * @return string A parsed and loaded template
- */
- public function fetch($name)
+ * Fluent interface-compatible constructor
+ */
+ public static function fetch()
{
- if (isset($this->cache[$name]))
- {
- $template = $this->cache[$name];
- }
- else
- {
- $this->uncached[$name]++;
- BSApp::Debug("Manually loading template '$name'");
- $template = $this->_loadTemplate($name);
- $template = $this->_parseTemplate($template);
- }
-
- return $template;
+ $obj = new ReflectionClass(__CLASS__);
+ $args = func_get_args();
+ return $obj->newInstanceArgs($args);
}
- // ###################################################################
/**
- * Output a template fully compiled to the browser
- *
- * @param string Compiled and ready template
- */
- public function flush($template)
+ * Constructor
+ *
+ * @param string File name
+ */
+ public function __construct($name)
{
- ob_start();
+ $this->name = $name;
+ $this->path = self::_path($name);
- if (empty($template))
+ // checks to see if the template has been cached
+ if (isset(self::$cache[$this->path]))
{
- throw new Exception('There was no output to print');
- }
-
- if ($this->doneflush)
- {
- throw new Exception('A template has already been sent to the output buffer');
- }
-
- $debugBlock = '';
- if (BSApp::GetDebug())
- {
- $debugBlock .= "\n<div align=\"center\">Executed in " . round(BSFunctions::FetchMicrotimeDiff($_SERVER['REQUEST_TIME']), 10) . ' seconds</div>';
- $debugBlock .= "\n<br /><div align=\"center\">" . BSApp::GetDebugList() . "</div>";
-
- if (sizeof($this->uncached) > 0)
+ if (!self::$dbCacheTable || filemtime($this->path) <= self::$cache[$this->path]['timestamp'])
{
- foreach ($this->uncached AS $name => $count)
- {
- $tpls[] = $name . "($count)";
- }
- $debugBlock .= "<br /><div style=\"color: red\" align=\"center\"><strong>Uncached Templates:</strong>" . implode(', ', $tpls) . " )</div>\n";
- }
-
- if (BSApp::GetType('Db'))
- {
- $queries = BSApp::GetType('Db')->getHistory();
-
- $debugBlock .= "<br />\n" . '<table cellpadding="4" cellspacing="1" border="0" align="center" width="30%" style="background-color: rgb(60, 60, 60); color: white">' . "\n\t" . '<tr><td><strong>Query Debug</strong></td></tr>';
-
- foreach ($queries AS $query)
- {
- $debugBlock .= "\n\t<tr style=\"background-color: rgb(230, 230, 230); color: black\">";
- $debugBlock .= "\n\t\t<td>";
- $debugBlock .= "\n\t\t\t$query[query]\n\n\t\t\t<div style=\"font-size: 9px;\">($query[time])</div>\n<!--\n$query[trace]\n-->\n\t\t</td>\n\t</tr>";
- }
-
- $debugBlock .= "\n</table>\n\n\n";
+ $this->template = self::$cache[$this->path]['template'];
+ return;
}
}
- $template = str_replace('</body>', $debugBlock . '</body>', $template);
+ // it hasn't been cached
+ if (!is_file($this->path) || !is_readable($this->path))
+ {
+ throw new Exception("Could not load the template {$this->path}");
+ }
+ $this->template = $this->_parseTemplate(file_get_contents($this->path));
+ self::$cache[$this->path]['template'] = $this->template;
- print($template);
+ // store the template in the database
+ if (self::$dbCacheTable)
+ {
+ BSApp::$db->query("REPLACE INTO " . self::$dbCacheTable . " SET template = '" . BSApp::$db->escapeString($this->template) . "', timestamp = " . TIMENOW . ", filename = '" . $this->path . "'");
+ self::$cache[$this->path]['time'] = TIMENOW;
+ }
}
- // ###################################################################
/**
- * Loads an additional template from the database
- *
- * @param string The name of the template
- *
- * @return string Template data from the database
- */
- protected function _loadTemplate($name)
+ * Evaluates and returns the template. This is equivalent to calling:
+ * $tpl->evaluate()->getTemplate()
+ *
+ * @return string
+ */
+ public function __toString()
{
- $path = $this->templateDir . $name . '.' . $this->extension;
- if (is_file($path) AND is_readable($path))
- {
- return @file_get_contents($path);
- }
- else
- {
- throw new Exception("Could not load the template '$path'");
- }
+ return $this->evaluate()->getTemplate();
}
- // ###################################################################
/**
- * A wrapper for all the parsing functions and compiling functins
- *
- * @param string Unparsed template data
- *
- * @return string Parsed template data
- */
- protected function _parseTemplate($template)
+ * Returns the template data
+ *
+ * @return string Final template data
+ */
+ public function getTemplate()
{
- $template = str_replace('"', '\"', $template);
-
- if (function_exists($this->preParseHook))
- {
- $template = call_user_func($this->preParseHook, $template);
- }
-
- $template = $this->_parseBlocksAndTokens($template);
- $template = $this->_parsePhrases($template);
- $template = $this->_parseConditionals($template);
- return $template;
+ return $this->template;
}
- // ###################################################################
/**
- * Parses anything with curly braces {} (including phrases)
- *
- * @param string Template data
- *
- * @return string Parsed template data
- */
- private function _parseBlocksAndTokens($template)
+ * This function globalizes/extracts the assigned variables and then
+ * returns the output buffer
+ *
+ * @param string Unevaluated template
+ *
+ * @return fluent interface
+ */
+ public function evaluate()
{
- $stack = array();
- $tokens = array();
+ extract($this->vars);
+ extract(self::$globalVars);
- while (1)
+ ob_start();
+ $this->template = str_replace(array('$this->', 'self::'), 'null', $this->template); // don't want internal access coming from a template
+ $this->template = '?>' . $this->template;
+ $test = eval($this->template);
+ $output = ob_get_clean();
+ if ($output === false)
{
- for ($i = 0; $i < strlen($template); $i++)
- {
- // we've run through the template and there's nothing in the stack--done
- if ($i == strlen($template) - 1 AND sizeof($stack) == 0)
- {
- return $template;
- }
-
- if ($template[$i] == '{')
- {
- // ignore escaped sequences
- if ($template[$i - 1] != '\\')
- {
- array_push($stack, $i);
- }
- }
- else if ($template[$i] == '}')
- {
- // there's no stack so it was probably escaped
- if (sizeof($stack) == 0)
- {
- continue;
- }
- // we're good and nested
- else if (sizeof($stack) == 1)
- {
- $open = array_pop($stack);
- $token = substr($template, $open, $i - $open + 1);
- $template = str_replace($token, $this->_parseToken($token), $template);
- break;
- }
- // just pop it off
- else
- {
- array_pop($stack);
- }
- }
- }
+ throw new Exception('A parse error was encountered while evaluating the template');
}
+
+ $this->template = $output;
+
+ return $this;
}
- // ###################################################################
/**
- * Parses a curly brace token {}
- *
- * @param string Token
- *
- * @return string Parsed value
- */
- private function _parseToken($token)
+ * Output a template fully compiled to the browser
+ */
+ public function flush()
{
- // knock of the braces
- $token = substr($token, 1, strlen($token) - 2);
+ ob_start();
- // language token
- if ($token[0] == '@' AND $token[1] == '\\' AND $token[2] == '"')
+ if (empty($this->template))
{
- return '" . ' . $this->langcall . '(\'' . str_replace(array('\\\"', "'"), array('"', "\'"), substr($token, 3, strlen($token) - 5)) . '\')' . ' . "';
- }
- // normal PHP code
- else
- {
- return '" . (' . $token . ') . "';
+ throw new Exception('There is no output to print');
}
+
+ echo $this->template;
}
- // ###################################################################
/**
- * Prepares language and locale information inside templates
- *
- * @param string Template data to be processed
- *
- * @return string Language-ready template data
- */
- private function _parsePhrases($template)
+ * Returns the debug block
+ *
+ * @return string
+ */
+ public static function get_debug_block()
{
- $tagStart = '<lang ';
- $tagEnd = '</lang>';
-
- $start = -1; // start of open tag
- $end = -1; // start of the close tag
- $varEnd = -1; // end of the open tag
-
- while ($start <= strlen($template))
+ if (!BSApp::get_debug())
{
- // reset
- $varMap = array(); // storage for all the substitution indices
-
- // Find the start language object tag
- $start = strpos($template, $tagStart, $end + 1);
- if ($start === false)
- {
- break;
- }
-
- // look ahead to parse out all the variables
- $i = $start + strlen($tagStart); // current position
- $capture = ''; // current capture
- $capturePos = $i; // the place to start capturing
- $varNum = -1; // variable placeholder index
- while ($i < strlen($template))
- {
- if ($template[$i] == '=')
- {
- // backtrack to find the previous variable substitution
- $backPos = $i;
- while ($backPos >= $start)
- {
- if ($template[$backPos] == '"')
- {
- // startPosition + length(startTag) + length(=\")
- $varMap[intval($varNum)] = BSFunctions::Substring($template, $capturePos + 3, $backPos - 1);
- // remove our old substitution from the capture
- $capture = BSFunctions::Substring($template, $backPos + 1, $i);
- break;
- }
- $backPos--;
- }
+ return;
+ }
+
+ $debugBlock = "\n<div align=\"center\">Executed in " . round(BSFunctions::fetch_microtime_diff('0 ' . $_SERVER['REQUEST_TIME']), 10) . ' seconds</div>';
+ $debugBlock .= "\n<br /><div align=\"center\">" . BSApp::get_debug_list() . "</div>";
- // do we have a valid index?
- if (intval($capture) > 0)
- {
- // set aside the index and restart capturing
- $varNum = $capture;
- $capture = '';
- $capturePos = $i;
- }
- else
- {
- throw new Exception('Invalid language variable index "' . $capture . '"');
- }
- }
- else if ($template[$i] == '>' AND $template[$i - 1] == '"')
- {
- // the final variable substitution
- $varMap[intval($varNum)] = BSFunctions::Substring($template, $capturePos + 3, $i - 2);
- $varEnds = $i;
- break;
- }
-
- $capture .= $template[$i];
- $i++;
- }
-
- // locate the end tag
- $end = strpos($template, $tagEnd, $i);
- if ($end === false)
- {
- break;
- }
-
- // this is the string that gets variable replacement
- $str = BSFunctions::Substring($template, $varEnds + 1, $end);
+ if (BSApp::$db)
+ {
+ $queries = BSApp::$db->getHistory();
- // create the complete varmap
+ $debugBlock .= "<br />\n" . '<table cellpadding="4" cellspacing="1" border="0" align="center" width="30%" style="background-color: rgb(60, 60, 60); color: white">' . "\n\t" . '<tr><td><strong>Query Debug</strong></td></tr>';
- for ($i = max(array_keys($varMap)); $i > 0; $i--)
+ foreach ($queries as $query)
{
- if (!isset($varMap[$i]))
- {
- $varMap[$i] = '<strong>[MISSING SUBSTITUTION INDEX: ' . $i . ']</strong>';
- }
+ $debugBlock .= "\n\t<tr style=\"background-color: rgb(230, 230, 230); color: black\">";
+ $debugBlock .= "\n\t\t<td>";
+ $debugBlock .= "\n\t\t\t$query[query]\n\n\t\t\t<div style=\"font-size: 9px;\">($query[time])</div>\n<!--\n$query[trace]\n-->\n\t\t</td>\n\t</tr>";
}
- // put all the keys in corresponding argument order
- ksort($varMap);
-
- // FINALLY, construct the call to sprintf()
- $template = substr_replace($template, '" . ' . $this->langconst . '(\'' . $str . '\', "' . implode('", "', $varMap) . '") . "', $start, ($end + strlen($tagEnd)) - $start);
+ $debugBlock .= "\n</table>\n\n\n";
}
- return $template;
+ return $debugBlock;
}
- // ###################################################################
/**
- * Parser for in-line template conditionals
- *
- * @param string Template data awaiting processing
- *
- * @return string Parsed template data
- */
- private function _parseConditionals($template)
+ * A wrapper for all the parsing functions and compiling functins
+ *
+ * @param string Unparsed template data
+ *
+ * @return string Parsed template data
+ */
+ protected function _parseTemplate($template)
{
- // tag data
- $tag_start = '<if condition=\"';
- $tag_start_end = '\">';
- $tag_else = '<else />';
- $tag_end = '</if>';
+ if (function_exists(self::$preParseHook))
+ {
+ $template = call_user_func(self::$preParseHook, $template, $this);
+ }
- // tag stack
+ $template = $this->_parseTokens($template);
+ return $template;
+ }
+
+ /**
+ * Parses tokens <% %>
+ *
+ * @param string Template data
+ *
+ * @return string Parsed template data
+ */
+ protected function _parseTokens($template)
+ {
$stack = array();
+ $tokens = array();
- // the information about the current active tag
- $tag_full = array();
- $parsed = array();
-
- // start at 0
- $offset = 0;
-
- while (1)
+ for ($i = 0; $i < strlen($template); $i++)
{
- if (strpos($template, $tag_start) === false)
+ // opening tag
+ if ($template[$i] == '<' && $template[$i + 1] == '%')
{
- break;
+ array_push($stack, $i);
}
-
- for ($i = $offset; $i < strlen($template); $i++)
+ // closing tag
+ else if ($template[$i] == '%' && $template[$i + 1] == '>')
{
- // we've found ourselves a conditional!
- if (substr($template, $i, strlen($tag_start)) == $tag_start)
+ // there's no stack, so it's a bad template
+ if (sizeof($stack) == 0)
{
- // push the position into the tag stack
- if ($tag_full)
- {
- array_push($stack, $i);
- }
- else
- {
- $tag_full['posi'] = $i;
- }
+ throw new Exception('Malformed template data: unexpected closing substitution tag');
}
- // locate else tags
- else if (substr($template, $i, strlen($tag_else)) == $tag_else)
+ // we're good and nested
+ else if (sizeof($stack) == 1)
{
- if (sizeof($stack) == 0 AND !isset($tag_full['else']))
- {
- $tag_full['else'] = $i;
- }
+ $open = array_pop($stack);
+ $echo = ($template[$open + 2] == '-' ? 'echo ' : '');
+ $replace = '<?php ' . $echo . BSFunctions::substring($template, $open + ($echo ? 3 : 2), $i) . ' ?>';
+ $template = substr_replace($template, $replace, $open, ($i + 2) - $open);
}
- // do we have an end tag?
- else if (substr($template, $i, strlen($tag_end)) == $tag_end)
+ // just pop it off
+ else
{
- if (sizeof($stack) != 0)
- {
- array_pop($stack);
- continue;
- }
-
- // calculate the position of the end tag
- $tag_full['posf'] = $i + strlen($tag_end) - 1;
-
- // extract the entire conditional from the template
- $fullspread = substr($template, $tag_full['posi'], $tag_full['posf'] - $tag_full['posi'] + 1);
-
- // remove the beginning tag
- $conditional = substr($fullspread, strlen($tag_start));
-
- // find the end of the expression
- $temp_end = strpos($conditional, $tag_start_end);
-
- // save the expression
- $parsed[0] = stripslashes(substr($conditional, 0, $temp_end));
-
- // remove the expression from the conditional
- $conditional = substr($conditional, strlen($parsed[0]) + strlen($tag_start_end));
-
- // remove the tailing end tag
- $conditional = substr($conditional, 0, strlen($conditional) - strlen($tag_end));
-
- // handle the else
- if (isset($tag_full['else']))
- {
- // now relative to the start of the <if>
- $relpos = $tag_full['else'] - $tag_full['posi'];
-
- // calculate the length of the expression and opening tag
- $length = strlen($parsed[0]) + strlen($tag_start) + strlen($tag_start_end);
-
- // relative to the start of iftrue
- $elsepos = $relpos - $length;
-
- $parsed[1] = substr($conditional, 0, $elsepos);
- $parsed[2] = substr($conditional, $elsepos + strlen($tag_else));
- }
- // no else to handle
- else
- {
- $parsed[1] = $conditional;
- $parsed[2] = '';
- }
-
- // final parsed output
- $parsed = '" . ((' . stripslashes($parsed[0]) . ') ? "' . $parsed[1] . '" : "' . $parsed[2] . '") . "';
-
- // replace the conditional
- $template = str_replace($fullspread, $parsed, $template);
-
- // reset the parser
- $offset = $tag_full['posi'] + strlen($tag_start) + strlen($tag_start_end);
- $tag_full = array();
- $stack = array();
- $parsed = array();
- unset($fullspread, $conditional, $temp_end, $relpos, $length, $elsepos);
- break;
- }
- }
- }
-
+ array_pop($stack);
+ } // end else
+ } // end if
+ } // end for
+
return $template;
}
+
+ /**
+ * Returns the full path of a template given a name
+ *
+ * @param string Template name
+ *
+ * @return string Template path
+ */
+ protected static function _path($name)
+ {
+ return sprintf(self::$templatePath, $name);
+ }
}
-/*=====================================================================*\
-|| ###################################################################
-|| # $HeadURL$
-|| # $Id$
-|| ###################################################################
-\*=====================================================================*/
?>
\ No newline at end of file