Capitalizing template.php
[isso.git] / Template.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework [#]issoversion[#]
5 || # Copyright ©2002-[#]year[#] 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 [#]gpl[#] 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 /**
29 * Database-Driven Template System
30 *
31 * This framework is a backend to the database template engine and
32 * contains all the parsing algorithms.
33 *
34 * @author Blue Static
35 * @copyright Copyright ©2002 - [#]year[#], Blue Static
36 * @version $Revision$
37 * @package ISSO
38 *
39 */
40 class BSTemplate
41 {
42 /**
43 * The database object to use
44 * @var object
45 */
46 private $db;
47
48 /**
49 * Name of the database table templates are in
50 * @var string
51 */
52 private $tableName = '';
53
54 /**
55 * Name of the table column template names are in
56 * @var string
57 */
58 private $nameColumn = '';
59
60 /**
61 * Name of the table column templates are in
62 * @var string
63 */
64 private $dataColumn = '';
65
66 /**
67 * Additional WHERE clauses for the template fetch SQL
68 * @var string
69 */
70 private $extraWhere = '';
71
72 /**
73 * The name of the function phrases are fetched with
74 * @var string
75 */
76 private $langcall = 'gettext';
77
78 /**
79 * The name of the function phrases are sprintf() parsed with
80 * @var string
81 */
82 private $langconst = 'sprintf';
83
84 /**
85 * Array of pre-compiled templates that are stored to decrease server load
86 * @var array
87 */
88 private $cache = array();
89
90 /**
91 * A list of the number of times each template has been used
92 * @var array
93 */
94 private $usage = array();
95
96 /**
97 * A list of templates that weren't cached, but are still used
98 * @var array
99 */
100 private $uncached = array();
101
102 /**
103 * Whether or not the page has been flush()'d already
104 * @var bool
105 */
106 private $doneflush = false;
107
108 /**
109 * The name of a function that is called before template parsing of phrases and conditionals occurs
110 * @var string
111 */
112 private $preParseHook = ':undefined:';
113
114 // ###################################################################
115 /**
116 * Constructor: check required modules
117 */
118 public function __construct()
119 {
120 BSRegister::RequiredModules(array('Db'));
121 }
122
123 // ###################################################################
124 /**
125 * Sets the database object to use
126 *
127 * @param object Database object
128 */
129 public function setDatabase($db)
130 {
131 $this->db = $db;
132 }
133
134 // ###################################################################
135 /**
136 * Sets the table name and column information
137 *
138 * @param string The database table name
139 * @param string Name of the column that stores the name of the template
140 * @param string Name of the column that stores template data
141 */
142 public function setDatabaseTable($tableName, $nameColumn, $dataColumn)
143 {
144 $this->tableName = $tableName;
145 $this->nameColumn = $nameColumn;
146 $this->dataColumn = $dataColumn;
147 }
148
149 // ###################################################################
150 /**
151 * Sets the pre-parse hook method which is called before any other
152 * processing is done on the template.
153 *
154 * @param string Method name
155 */
156 public function setPreParseHook($hook)
157 {
158 $this->preParseHook = $hook;
159 }
160
161 // ###################################################################
162 /**
163 * Takes an array of template names, loads them, and then stores a
164 * parsed version for optimum speed.
165 *
166 * @param array List of template names to be cached
167 */
168 public function cache($namearray)
169 {
170 if (sizeof($this->cache) > 0)
171 {
172 trigger_error('You cannot cache templates more than once per initialization');
173 }
174 else
175 {
176 $templates = $this->db->query("SELECT * FROM " . $this->tableName . " WHERE " . $this->nameColumn . " IN ('" . implode("', '", $namearray) . "')" . ($this->extrawhere ? ' ' . $this->extrawhere : ''));
177 while ($template = $this->db->fetch_array($templates))
178 {
179 $this->cache[ $template[ $this->nameColumn ] ] = $this->_parse($template[ $this->dataColumn ]);
180 $this->usage[ $template[ $this->nameColumn ] ] = 0;
181 }
182 }
183 }
184
185 // ###################################################################
186 /**
187 * Loads a template from the cache or the _load function and stores the
188 * parsed version of it
189 *
190 * @param string The name of the template
191 *
192 * @return string A parsed and loaded template
193 */
194 public function fetch($name)
195 {
196 if (isset($this->cache["$name"]))
197 {
198 $template = $this->cache["$name"];
199 }
200 else
201 {
202 $this->uncached[] = $name;
203 BSRegister::Debug("Manually loading template `$name`");
204 $template = $this->_loadTemplate($name);
205 $template = $this->_parseTemplate($template);
206 }
207
208 if (!isset($this->usage["$name"]))
209 {
210 $this->usage["$name"] = 0;
211 }
212
213 $this->usage["$name"]++;
214
215 return $template;
216 }
217
218 // ###################################################################
219 /**
220 * Output a template fully compiled to the browser
221 *
222 * @param string Compiled and ready template
223 */
224 public function flush($template)
225 {
226 ob_start();
227
228 if (empty($template))
229 {
230 trigger_error('There was no output to print');
231 exit;
232 }
233
234 if (BSRegister::GetDebug() AND isset($_GET['query']))
235 {
236 if (is_array($this->registry->modules[ISSO_DB_LAYER]->history))
237 {
238 foreach ($this->registry->modules[ISSO_DB_LAYER]->history AS $query)
239 {
240 echo $this->registry->modules[ISSO_DB_LAYER]->construct_query_debug($query);
241 }
242 }
243 exit;
244 }
245
246 if ($this->doneflush)
247 {
248 trigger_error('A template has already been sent to the output buffer');
249 exit;
250 }
251
252 $template = str_replace('</body>', $this->registry->construct_debug_block(true) . '</body>', $template);
253
254 print($template);
255 }
256
257 // ###################################################################
258 /**
259 * Loads an additional template from the database
260 *
261 * @param string The name of the template
262 *
263 * @return string Template data from the database
264 */
265 private function _loadTemplate($name)
266 {
267 if ($template = $this->db->query_first("SELECT * FROM " . $this->tableName . " WHERE " . $this->nameColumn . " = '$name'" . ($this->extrawhere ? ' ' . $this->extrawhere : '')))
268 {
269 return $template[ $this->dataColumn ];
270 }
271 else
272 {
273 trigger_error("The template '$name' could not be loaded");
274 exit;
275 }
276 }
277
278 // ###################################################################
279 /**
280 * A wrapper for all the parsing functions and compiling functins
281 *
282 * @param string Unparsed template data
283 *
284 * @return string Parsed template data
285 */
286 protected function _parseTemplate($template)
287 {
288 $template = str_replace('"', '\"', $template);
289
290 if (function_exists($this->preParseHook))
291 {
292 $template = call_user_func($this->preParseHook, $template);
293 }
294
295 $template = $this->_parsePhrases($template);
296 $template = $this->_parseConditionals($template);
297 return $template;
298 }
299
300 // ###################################################################
301 /**
302 * Prepares language and locale information inside templates
303 *
304 * @param string Template data to be processed
305 *
306 * @return string Language-ready template data
307 */
308 private function _parsePhrases($template)
309 {
310 $tag_start = '<lang ';
311 $tag_start_end = '\">';
312 $tag_end = '</lang>';
313
314 $location_start = -1;
315 $location_end = -1;
316
317 while (1)
318 {
319 // Find the start language object tag
320 $location_start = strpos($template, $tag_start, $location_end + 1);
321 if ($location_start === false)
322 {
323 break;
324 }
325
326 // Find the end tag
327 $location_end = strpos($template, $tag_end, $location_end + strlen($tag_end));
328 if ($location_end === false)
329 {
330 break;
331 }
332
333 // Extract the language object
334 $phrase_bunch = substr($template, $location_start, ($location_end + strlen($tag_end)) - $location_start);
335
336 // Find the close to the opening <lang>
337 $close_of_open = strpos($phrase_bunch, $tag_start_end);
338 if ($close_of_open === false)
339 {
340 break;
341 }
342
343 // Extract the opening tag so it can be parsed
344 $init_tag = substr($phrase_bunch, 0, ($close_of_open + strlen($tag_start_end)));
345 $init_tag = str_replace($tag_start, '', $init_tag);
346 $init_tag = substr($init_tag, 0, strlen($init_tag) - 1);
347
348 // Get the args out of the tag
349 $args = preg_split('#([0-9].*?)=#', $init_tag);
350 foreach ($args AS $arg)
351 {
352 if ($arg AND $arg != ' ')
353 {
354 $arg = trim($arg);
355 $arg = substr($arg, 2);
356 $arg = substr($arg, 0, strlen($arg) - 2);
357 $arglist[] = $arg;
358 }
359 }
360
361 // Just get the phrase name
362 $phrase_name = preg_replace('#<lang(.*?)>(.*?)</lang>#i', '$2', $phrase_bunch);
363
364 // Wrap the parsed data into the build function
365 $function_wrap = '" . ' . $this->langconst . '("' . $phrase_name . '", "' . implode('", "', $arglist) . '") . "';
366
367 // Replace the fully-parsed string back into the template
368 $template = substr_replace($template, $function_wrap, $location_start, $location_end + strlen($tag_end) - $location_start);
369
370 unset($arglist);
371 }
372
373 // Process the empty phrase objects -- do this now so we don't have to worry about it when we're parsing later
374 $template = preg_replace('#\{@\\\"(.*?)\\\"\}#ise', '$this->_templateString(\'$1\')', $template);
375
376 return $template;
377 }
378
379 // ###################################################################
380 /**
381 * Turns a localized phrase tag into a function call
382 *
383 * @param string Phrase text
384 *
385 * @return string Function call for phrase text
386 */
387 private function _templateString($text)
388 {
389 return '" . ' . $this->langcall . '(\'' . str_replace(array('\\\"', "'"), array('"', "\'"), $text) . '\') . "';
390 }
391
392 // ###################################################################
393 /**
394 * Parser for in-line template conditionals
395 *
396 * @param string Template data awaiting processing
397 *
398 * @return string Parsed template data
399 */
400 private function _parseConditionals($template)
401 {
402 // tag data
403 $tag_start = '<if condition=\"';
404 $tag_start_end = '\">';
405 $tag_else = '<else />';
406 $tag_end = '</if>';
407
408 // tag stack
409 $stack = array();
410
411 // the information about the current active tag
412 $tag_full = array();
413 $parsed = array();
414
415 // start at 0
416 $offset = 0;
417
418 while (1)
419 {
420 if (strpos($template, $tag_start) === false)
421 {
422 break;
423 }
424
425 for ($i = $offset; $i < strlen($template); $i++)
426 {
427 // we've found ourselves a conditional!
428 if (substr($template, $i, strlen($tag_start)) == $tag_start)
429 {
430 // push the position into the tag stack
431 if ($tag_full)
432 {
433 array_push($stack, $i);
434 }
435 else
436 {
437 $tag_full['posi'] = $i;
438 }
439 }
440 // locate else tags
441 else if (substr($template, $i, strlen($tag_else)) == $tag_else)
442 {
443 if (sizeof($stack) == 0 AND !isset($tag_full['else']))
444 {
445 $tag_full['else'] = $i;
446 }
447 }
448 // do we have an end tag?
449 else if (substr($template, $i, strlen($tag_end)) == $tag_end)
450 {
451 if (sizeof($stack) != 0)
452 {
453 array_pop($stack);
454 continue;
455 }
456
457 // calculate the position of the end tag
458 $tag_full['posf'] = $i + strlen($tag_end) - 1;
459
460 // extract the entire conditional from the template
461 $fullspread = substr($template, $tag_full['posi'], $tag_full['posf'] - $tag_full['posi'] + 1);
462
463 // remove the beginning tag
464 $conditional = substr($fullspread, strlen($tag_start));
465
466 // find the end of the expression
467 $temp_end = strpos($conditional, $tag_start_end);
468
469 // save the expression
470 $parsed[0] = stripslashes(substr($conditional, 0, $temp_end));
471
472 // remove the expression from the conditional
473 $conditional = substr($conditional, strlen($parsed[0]) + strlen($tag_start_end));
474
475 // remove the tailing end tag
476 $conditional = substr($conditional, 0, strlen($conditional) - strlen($tag_end));
477
478 // handle the else
479 if (isset($tag_full['else']))
480 {
481 // now relative to the start of the <if>
482 $relpos = $tag_full['else'] - $tag_full['posi'];
483
484 // calculate the length of the expression and opening tag
485 $length = strlen($parsed[0]) + strlen($tag_start) + strlen($tag_start_end);
486
487 // relative to the start of iftrue
488 $elsepos = $relpos - $length;
489
490 $parsed[1] = substr($conditional, 0, $elsepos);
491 $parsed[2] = substr($conditional, $elsepos + strlen($tag_else));
492 }
493 // no else to handle
494 else
495 {
496 $parsed[1] = $conditional;
497 $parsed[2] = '';
498 }
499
500 // final parsed output
501 $parsed = '" . ((' . stripslashes($parsed[0]) . ') ? "' . $parsed[1] . '" : "' . $parsed[2] . '") . "';
502
503 // replace the conditional
504 $template = str_replace($fullspread, $parsed, $template);
505
506 // reset the parser
507 $offset = $tag_full['posi'] + strlen($tag_start) + strlen($tag_start_end);
508 $tag_full = array();
509 $stack = array();
510 $parsed = array();
511 unset($fullspread, $conditional, $temp_end, $relpos, $length, $elsepos);
512 break;
513 }
514 }
515 }
516
517 return $template;
518 }
519 }
520
521 // ###################################################################
522 /**
523 * Debugging function used to print characters in a string that are
524 * around a certain position.
525 *
526 * @access private
527 *
528 * @param string The haystack string
529 * @param integer Position to print around
530 */
531 function print_around($str, $pos)
532 {
533 echo '>>> PA >>>>>>>>[';
534 echo htmlspecialchars($str[ $pos - 5 ]);
535 echo htmlspecialchars($str[ $pos - 4 ]);
536 echo htmlspecialchars($str[ $pos - 3 ]);
537 echo htmlspecialchars($str[ $pos - 2 ]);
538 echo htmlspecialchars($str[ $pos - 1 ]);
539 echo '©';
540 echo htmlspecialchars($str[ $pos + 0 ]);
541 echo htmlspecialchars($str[ $pos + 1 ]);
542 echo htmlspecialchars($str[ $pos + 2 ]);
543 echo htmlspecialchars($str[ $pos + 3 ]);
544 echo htmlspecialchars($str[ $pos + 4 ]);
545 echo htmlspecialchars($str[ $pos + 5 ]);
546 echo ']<<<<<<<< PA <<<';
547 }
548
549 /*=====================================================================*\
550 || ###################################################################
551 || # $HeadURL$
552 || # $Id$
553 || ###################################################################
554 \*=====================================================================*/
555 ?>