2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2005-2009 Blue Static
7 || # This program is free software; you can redistribute it and/or modify
8 || # it under the terms of the GNU General Public License as published by
9 || # the Free Software Foundation; version 2 of the License.
11 || # This program is distributed in the hope that it will be useful, but
12 || # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 || # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 || # You should have received a copy of the GNU General Public License along
17 || # with this program; if not, write to the Free Software Foundation, Inc.,
18 || # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
19 || ###################################################################
20 \*=====================================================================*/
23 * Database-Driven Template System (template.php)
28 require_once(ISSO
. '/Functions.php');
31 * File-Based Template System
33 * This framework merely replaces the template loading functions with
34 * file-system based ones. It has an optional caching system in which
35 * template data will remain stored in the database as long as the filesystem
36 * file is modified. To do this, pass a table name to setDatabaseCache() and make sure
37 * there's a DB module that has access to a table with this schema:
39 * CREATE TABLE template (filename VARCHAR (250) NOT NULL, template TEXT NOT NULL, timestamp INT NOT NULL);
42 * @copyright Copyright (c)2005 - 2009, Blue Static
49 * The name of a function that is called before template parsing of phrases and conditionals occurs
52 public static $preParseHook = ':undefined:';
55 * The database table name for the template cache
58 public static $dbCacheTable = null
;
61 * The name of the function phrases are fetched with
64 public static $langcall = 'gettext';
67 * The template path pattern; for instance, this could be: ./templates/%s.tpl
70 public static $templatePath = '%s';
73 * Array of pre-compiled templates that are stored for optimization
76 protected static $cache = array();
79 * The name of the function phrases are sprintf() parsed with
82 public static $langconst = 'sprintf';
85 * Template variables to populate
88 public $vars = array();
94 public static $globalVars = array();
97 * The path of the template file
103 * The name of the template
115 * Takes an array of template names, loads them, and then stores a
116 * parsed version for optimum speed.
118 * @param array List of template names to be cached
120 public static function cache($namearray)
122 if (!self
::$dbCacheTable)
124 return; // there's no point in pre-caching file templates
127 $namearray = array_map(array('self', '_path'), $namearray);
128 $cache = BSApp
::$db->query("SELECT * FROM " . self
::$dbCacheTable . " WHERE filename IN ('" . implode("', '", $namearray) . "')");
129 while ($tpl = $cache->fetchArray())
131 self
::$cache[$tpl['filename']] = $tpl;
136 * Fluent interface-compatible constructor
138 public static function fetch()
140 $obj = new ReflectionClass(__CLASS__
);
141 $args = func_get_args();
142 return $obj->newInstanceArgs($args);
148 * @param string File name
150 public function __construct($name)
153 $this->path
= self
::_path($name);
155 // checks to see if the template has been cached
156 if (isset(self
::$cache[$this->path
]))
158 if (!self
::$dbCacheTable ||
filemtime($this->path
) <= self
::$cache[$this->path
]['timestamp'])
160 $this->template
= self
::$cache[$this->path
]['template'];
165 // it hasn't been cached
166 if (!is_file($this->path
) ||
!is_readable($this->path
))
168 throw new Exception("Could not load the template {$this->path}");
170 $this->template
= $this->_parseTemplate(file_get_contents($this->path
));
171 self
::$cache[$this->path
]['template'] = $this->template
;
173 // store the template in the database
174 if (self
::$dbCacheTable)
176 BSApp
::$db->query("REPLACE INTO " . self
::$dbCacheTable . " SET template = '" . BSApp
::$db->escapeString($this->template
) . "', timestamp = " . TIMENOW
. ", filename = '" . $this->path
. "'");
177 self
::$cache[$this->path
]['time'] = TIMENOW
;
182 * Returns the template data
184 * @return string Final template data
186 public function getTemplate()
188 return $this->template
;
192 * This function globalizes/extracts the assigned variables and then
193 * returns the output buffer
195 * @param string Unevaluated template
197 * @return fluent interface
199 public function evaluate()
201 extract($this->vars
);
202 extract(self
::$globalVars);
205 $this->template
= str_replace(array('$this->', 'self::'), 'null', $this->template
); // don't want internal access coming from a template
206 $this->template
= '?>' . $this->template
;
207 $test = eval($this->template
);
208 $output = ob_get_clean();
209 if ($output === false
)
211 throw new Exception('A parse error was encountered while evaluating the template');
214 $this->template
= $output;
220 * Output a template fully compiled to the browser
222 public function flush()
226 if (empty($this->template
))
228 throw new Exception('There is no output to print');
231 echo $this->template
;
235 * Returns the debug block
239 public static function get_debug_block()
241 if (!BSApp
::get_debug())
246 $debugBlock = "\n<div align=\"center\">Executed in " . round(BSFunctions
::fetch_microtime_diff('0 ' . $_SERVER['REQUEST_TIME']), 10) . ' seconds</div>';
247 $debugBlock .= "\n<br /><div align=\"center\">" . BSApp
::get_debug_list() . "</div>";
251 $queries = BSApp
::$db->getHistory();
253 $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>';
255 foreach ($queries as $query)
257 $debugBlock .= "\n\t<tr style=\"background-color: rgb(230, 230, 230); color: black\">";
258 $debugBlock .= "\n\t\t<td>";
259 $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>";
262 $debugBlock .= "\n</table>\n\n\n";
269 * A wrapper for all the parsing functions and compiling functins
271 * @param string Unparsed template data
273 * @return string Parsed template data
275 protected function _parseTemplate($template)
277 if (function_exists(self
::$preParseHook))
279 $template = call_user_func(self
::$preParseHook, $template, $this);
282 $template = $this->_parseTokens($template);
287 * Parses tokens <% %>
289 * @param string Template data
291 * @return string Parsed template data
293 protected function _parseTokens($template)
298 for ($i = 0; $i < strlen($template); $i++
)
301 if ($template[$i] == '<' && $template[$i +
1] == '%')
303 array_push($stack, $i);
306 else if ($template[$i] == '%' && $template[$i +
1] == '>')
308 // there's no stack, so it's a bad template
309 if (sizeof($stack) == 0)
311 throw new Exception('Malformed template data: unexpected closing substitution tag');
313 // we're good and nested
314 else if (sizeof($stack) == 1)
316 $open = array_pop($stack);
317 $echo = ($template[$open +
2] == '-' ?
'echo ' : '');
318 $replace = '<?php ' . $echo . BSFunctions
::substring($template, $open +
($echo ?
3 : 2), $i) . ' ?>';
319 $template = substr_replace($template, $replace, $open, ($i +
2) - $open);
333 * Returns the full path of a template given a name
335 * @param string Template name
337 * @return string Template path
339 protected static function _path($name)
341 return sprintf(self
::$templatePath, $name);