2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2005-2008 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 - 2008, 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();
91 * The file name of the template
103 * Takes an array of template names, loads them, and then stores a
104 * parsed version for optimum speed.
106 * @param array List of template names to be cached
108 public static function cache($namearray)
110 if (!self
::$dbCacheTable)
112 return; // there's no point in pre-caching file templates
115 $cache = BSApp
::$db->query("SELECT * FROM " . self
::$dbCacheTable . " WHERE filename IN ('" . implode("', '", $namearray) . "')");
116 while ($tpl = $cache->fetchArray())
118 self
::$cache[$tpl['filename']] = $tpl;
123 * Fluent interface-compatible constructor
125 public static function fetch()
127 $obj = new ReflectionClass(__CLASS__
);
128 $args = func_get_args();
129 return $obj->newInstanceArgs($args);
135 * @param string File name
137 public function __construct($path)
141 // checks to see if the template has been cached
142 if (isset(self
::$cache[$this->file
]))
144 if (!self
::$dbCacheTable ||
filemtime(sprintf(self
::$templatePath, $this->file
)) <= self
::$cache[$this->file
]['timestamp'])
146 $this->template
= self
::$cache[$this->file
]['template'];
151 // it hasn't been cached
152 $path = sprintf(self
::$templatePath, $this->file
);
153 if (!is_file($path) ||
!is_readable($path))
155 throw new Exception("Could not load the template $path");
157 $this->template
= $this->_parseTemplate(file_get_contents($path));
158 self
::$cache[$this->file
]['template'] = $this->template
;
160 // store the template in the database
161 if (self
::$dbCacheTable)
163 BSApp
::$db->query("REPLACE INTO " . self
::$dbCacheTable . " SET template = '" . BSApp
::$db->escapeString($this->template
) . "', timestamp = " . TIMENOW
. ", filename = '" . $this->file
. "'");
164 self
::$cache[$this->file
]['time'] = TIMENOW
;
169 * Returns the template data
171 * @return string Final template data
173 public function getTemplate()
175 return $this->template
;
179 * This function globalizes/extracts the assigned variables and then
180 * returns the output buffer
182 * @param string Unevaluated template
184 * @return fluent interface
186 public function evaluate()
188 extract($this->vars
);
191 $this->template
= str_replace(array('$this->', 'self::'), 'null', $this->template
); // don't want internal access coming from a template
192 $this->template
= '?>' . $this->template
;
193 eval($this->template
);
194 $this->template
= ob_get_clean();
201 * Output a template fully compiled to the browser
203 public function flush()
207 if (empty($this->template
))
209 throw new Exception('There is no output to print');
212 $template = $this->template
;
215 if (BSApp
::get_debug() && strpos($template, '</body>') !== false
)
217 $debugBlock .= "\n<div align=\"center\">Executed in " . round(BSFunctions
::fetch_microtime_diff('0 ' . $_SERVER['REQUEST_TIME']), 10) . ' seconds</div>';
218 $debugBlock .= "\n<br /><div align=\"center\">" . BSApp
::get_debug_list() . "</div>";
222 $queries = BSApp
::$db->getHistory();
224 $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>';
226 foreach ($queries as $query)
228 $debugBlock .= "\n\t<tr style=\"background-color: rgb(230, 230, 230); color: black\">";
229 $debugBlock .= "\n\t\t<td>";
230 $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>";
233 $debugBlock .= "\n</table>\n\n\n";
236 $template = str_replace('</body>', $debugBlock . '</body>', $template);
243 * A wrapper for all the parsing functions and compiling functins
245 * @param string Unparsed template data
247 * @return string Parsed template data
249 protected function _parseTemplate($template)
251 if (function_exists(self
::$preParseHook))
253 $template = call_user_func(self
::$preParseHook, $template);
256 $template = $this->_parseTokens($template);
261 * Parses tokens <% %>
263 * @param string Template data
265 * @return string Parsed template data
267 protected function _parseTokens($template)
272 for ($i = 0; $i < strlen($template); $i++
)
275 if ($template[$i] == '<' && $template[$i +
1] == '%')
277 array_push($stack, $i);
280 else if ($template[$i] == '%' && $template[$i +
1] == '>')
282 // there's no stack, so it's a bad template
283 if (sizeof($stack) == 0)
285 throw new Exception('Malformed template data: unexpected closing substitution tag');
287 // we're good and nested
288 else if (sizeof($stack) == 1)
290 $open = array_pop($stack);
291 $replace = '<?php ' . BSFunctions
::substring($template, $open +
2, $i) . ' ?>';
292 $template = substr_replace($template, $replace, $open, ($i +
2) - $open);