Make Pagination->page and Pagination->perpage be public and not protected
[isso.git] / Template.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright (c)2005-2008 Blue Static
6 || #
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.
10 || #
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
14 || # more details.
15 || #
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 \*=====================================================================*/
21
22 /**
23 * Database-Driven Template System (template.php)
24 *
25 * @package ISSO
26 */
27
28 require_once(ISSO . '/Functions.php');
29
30 /**
31 * File-Based Template System
32 *
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:
38 *
39 * CREATE TABLE template (filename VARCHAR (250) NOT NULL, template TEXT NOT NULL, timestamp INT NOT NULL);
40 *
41 * @author Blue Static
42 * @copyright Copyright (c)2005 - 2008, Blue Static
43 * @package ISSO
44 *
45 */
46 class BSTemplate
47 {
48 /**
49 * The name of a function that is called before template parsing of phrases and conditionals occurs
50 * @var string
51 */
52 public static $preParseHook = ':undefined:';
53
54 /**
55 * The database table name for the template cache
56 * @var string
57 */
58 public static $dbCacheTable = null;
59
60 /**
61 * The name of the function phrases are fetched with
62 * @var string
63 */
64 public static $langcall = 'gettext';
65
66 /**
67 * The template path pattern; for instance, this could be: ./templates/%s.tpl
68 * @var string
69 */
70 public static $templatePath = '%s';
71
72 /**
73 * Array of pre-compiled templates that are stored for optimization
74 * @var array
75 */
76 protected static $cache = array();
77
78 /**
79 * The name of the function phrases are sprintf() parsed with
80 * @var string
81 */
82 public static $langconst = 'sprintf';
83
84 /**
85 * Template variables to populate
86 * @var array
87 */
88 public $vars = array();
89
90 /**
91 * The file name of the template
92 * @var string
93 */
94 protected $filename;
95
96 /**
97 * Template contents
98 * @var string
99 */
100 protected $template;
101
102 /**
103 * Takes an array of template names, loads them, and then stores a
104 * parsed version for optimum speed.
105 *
106 * @param array List of template names to be cached
107 */
108 public static function cache($namearray)
109 {
110 if (!self::$dbCacheTable)
111 {
112 return; // there's no point in pre-caching file templates
113 }
114
115 $cache = BSApp::$db->query("SELECT * FROM " . self::$dbCacheTable . " WHERE filename IN ('" . implode("', '", $namearray) . "')");
116 while ($tpl = $cache->fetchArray())
117 {
118 self::$cache[$tpl['filename']] = $tpl;
119 }
120 }
121
122 /**
123 * Fluent interface-compatible constructor
124 */
125 public static function fetch()
126 {
127 $obj = new ReflectionClass(__CLASS__);
128 $args = func_get_args();
129 return $obj->newInstanceArgs($args);
130 }
131
132 /**
133 * Constructor
134 *
135 * @param string File name
136 */
137 public function __construct($path)
138 {
139 $this->file = $path;
140
141 // checks to see if the template has been cached
142 if (isset(self::$cache[$this->file]))
143 {
144 if (!self::$dbCacheTable || filemtime(sprintf(self::$templatePath, $this->file)) <= self::$cache[$this->file]['timestamp'])
145 {
146 $this->template = self::$cache[$this->file]['template'];
147 return;
148 }
149 }
150
151 // it hasn't been cached
152 $path = sprintf(self::$templatePath, $this->file);
153 if (!is_file($path) || !is_readable($path))
154 {
155 throw new Exception("Could not load the template $path");
156 }
157 $this->template = $this->_parseTemplate(file_get_contents($path));
158 self::$cache[$this->file]['template'] = $this->template;
159
160 // store the template in the database
161 if (self::$dbCacheTable)
162 {
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;
165 }
166 }
167
168 /**
169 * Returns the template data
170 *
171 * @return string Final template data
172 */
173 public function getTemplate()
174 {
175 return $this->template;
176 }
177
178 /**
179 * This function globalizes/extracts the assigned variables and then
180 * returns the output buffer
181 *
182 * @param string Unevaluated template
183 *
184 * @return fluent interface
185 */
186 public function evaluate()
187 {
188 extract($this->vars);
189
190 ob_start();
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();
195 ob_end_clean();
196
197 return $this;
198 }
199
200 /**
201 * Output a template fully compiled to the browser
202 */
203 public function flush()
204 {
205 ob_start();
206
207 if (empty($this->template))
208 {
209 throw new Exception('There is no output to print');
210 }
211
212 $template = $this->template;
213
214 $debugBlock = '';
215 if (BSApp::get_debug() && strpos($template, '</body>') !== false)
216 {
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>";
219
220 if (BSApp::$db)
221 {
222 $queries = BSApp::$db->getHistory();
223
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>';
225
226 foreach ($queries as $query)
227 {
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>";
231 }
232
233 $debugBlock .= "\n</table>\n\n\n";
234 }
235
236 $template = str_replace('</body>', $debugBlock . '</body>', $template);
237 }
238
239 print($template);
240 }
241
242 /**
243 * A wrapper for all the parsing functions and compiling functins
244 *
245 * @param string Unparsed template data
246 *
247 * @return string Parsed template data
248 */
249 protected function _parseTemplate($template)
250 {
251 if (function_exists(self::$preParseHook))
252 {
253 $template = call_user_func(self::$preParseHook, $template);
254 }
255
256 $template = $this->_parseTokens($template);
257 return $template;
258 }
259
260 /**
261 * Parses tokens <% %>
262 *
263 * @param string Template data
264 *
265 * @return string Parsed template data
266 */
267 protected function _parseTokens($template)
268 {
269 $stack = array();
270 $tokens = array();
271
272 for ($i = 0; $i < strlen($template); $i++)
273 {
274 // opening tag
275 if ($template[$i] == '<' && $template[$i + 1] == '%')
276 {
277 array_push($stack, $i);
278 }
279 // closing tag
280 else if ($template[$i] == '%' && $template[$i + 1] == '>')
281 {
282 // there's no stack, so it's a bad template
283 if (sizeof($stack) == 0)
284 {
285 throw new Exception('Malformed template data: unexpected closing substitution tag');
286 }
287 // we're good and nested
288 else if (sizeof($stack) == 1)
289 {
290 $open = array_pop($stack);
291 $echo = ($template[$open + 2] == '-' ? 'echo ' : '');
292 $replace = '<?php ' . $echo . BSFunctions::substring($template, $open + ($echo ? 3 : 2), $i) . ' ?>';
293 $template = substr_replace($template, $replace, $open, ($i + 2) - $open);
294 }
295 // just pop it off
296 else
297 {
298 array_pop($stack);
299 } // end else
300 } // end if
301 } // end for
302
303 return $template;
304 }
305 }
306
307 ?>