Rewrote the <lang> tag parser in BSTemplate::_parsePhrases():
[isso.git] / Template.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
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 protected $cache = array();
89
90 /**
91 * A list of the number of times each template has been used
92 * @var array
93 */
94 protected $usage = array();
95
96 /**
97 * A list of templates that weren't cached, but are still used
98 * @var array
99 */
100 protected $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 ($this->doneflush)
235 {
236 trigger_error('A template has already been sent to the output buffer');
237 exit;
238 }
239
240 $debugBlock = '';
241 if (BSRegister::GetDebug())
242 {
243 if (defined('SVN') AND preg_match('#^\$Id:?#', constant('SVN')))
244 {
245 $debugBlock .= preg_replace('#\$' . 'Id: (.+?) ([0-9].+?) [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(.+?) (.+?) \$#', "\n<br />\n" . '<div align="center"><strong>\1</strong> &mdash; r\2</div>', constant('SVN'));
246 }
247
248 if (defined('ISSO_MT_START'))
249 {
250 $debugBlock .= "\n<div align=\"center\">Executed in " . round(BSFunctions::FetchMicrotimeDiff(ISSO_MT_START), 10) . ' seconds</div>';
251 }
252
253 $debugBlock .= "\n<br /><div align=\"center\">" . BSRegister::GetDebugList() . "</div>";
254
255 $optlist = array();
256 $usage = array();
257 foreach ($this->usage AS $name => $count)
258 {
259 if (in_array($name, $this->uncached))
260 {
261 $optlist[] = $name . '[' . $count . ']';
262 }
263 $usage[] = $name . " ($count)";
264 }
265 $sizeof = sizeof($this->uncached);
266 if ($sizeof > 0)
267 {
268 $debugBlock .= "<br /><div style=\"color: red\" align=\"center\"><strong>Uncached Template(s):</strong> $sizeof ( " . implode(' &nbsp; ', $optlist) . " )</div>\n";
269 }
270
271 $debugBlock .= (sizeof($this->uncached) < 1 ? "<br />\n" : '') . "<div align=\"center\"><select><option>Template Usage (" . array_sum($this->usage) . ")</option>";
272 foreach ($usage AS $tpl)
273 {
274 $debugBlock .= "<option>--- $tpl</option>";
275 }
276 $debugBlock .= "</select></div>\n";
277
278 if (BSRegister::GetType('Db'))
279 {
280 $queries = BSRegister::GetType('Db')->getHistory();
281
282 $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>';
283
284 foreach ($queries AS $query)
285 {
286 $debugBlock .= "\n\t<tr style=\"background-color: rgb(230, 230, 230); color: black\">";
287 $debugBlock .= "\n\t\t<td>";
288 $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>";
289 }
290
291 $debugBlock .= "\n</table>\n\n\n";
292 }
293 }
294
295 $template = str_replace('</body>', $debugBlock . '</body>', $template);
296
297 print($template);
298 }
299
300 // ###################################################################
301 /**
302 * Loads an additional template from the database
303 *
304 * @param string The name of the template
305 *
306 * @return string Template data from the database
307 */
308 protected function _loadTemplate($name)
309 {
310 if ($template = $this->db->queryFirst("SELECT * FROM " . $this->tableName . " WHERE " . $this->nameColumn . " = '$name'" . ($this->extrawhere ? ' ' . $this->extrawhere : '')))
311 {
312 return $template[ $this->dataColumn ];
313 }
314 else
315 {
316 trigger_error("The template '$name' could not be loaded");
317 exit;
318 }
319 }
320
321 // ###################################################################
322 /**
323 * A wrapper for all the parsing functions and compiling functins
324 *
325 * @param string Unparsed template data
326 *
327 * @return string Parsed template data
328 */
329 protected function _parseTemplate($template)
330 {
331 $template = str_replace('"', '\"', $template);
332
333 if (function_exists($this->preParseHook))
334 {
335 $template = call_user_func($this->preParseHook, $template);
336 }
337
338 $template = $this->_parseBlocksAndTokens($template);
339 $template = $this->_parsePhrases($template);
340 $template = $this->_parseConditionals($template);
341 return $template;
342 }
343
344 // ###################################################################
345 /**
346 * Parses anything with curly braces {} (including phrases)
347 *
348 * @param string Template data
349 *
350 * @return string Parsed template data
351 */
352 private function _parseBlocksAndTokens($template)
353 {
354 $stack = array();
355 $tokens = array();
356
357 while (1)
358 {
359 for ($i = 0; $i < strlen($template); $i++)
360 {
361 // we've run through the template and there's nothing in the stack--done
362 if ($i == strlen($template) - 1 AND sizeof($stack) == 0)
363 {
364 return $template;
365 }
366
367 if ($template[$i] == '{')
368 {
369 // ignore escaped sequences
370 if ($template[$i - 1] != '\\')
371 {
372 array_push($stack, $i);
373 }
374 }
375 else if ($template[$i] == '}')
376 {
377 // there's no stack so it was probably escaped
378 if (sizeof($stack) == 0)
379 {
380 continue;
381 }
382 // we're good and nested
383 else if (sizeof($stack) == 1)
384 {
385 $open = array_pop($stack);
386 $token = substr($template, $open, $i - $open + 1);
387 $template = str_replace($token, $this->_parseToken($token), $template);
388 break;
389 }
390 // just pop it off
391 else
392 {
393 array_pop($stack);
394 }
395 }
396 }
397 }
398 }
399
400 // ###################################################################
401 /**
402 * Parses a curly brace token {}
403 *
404 * @param string Token
405 *
406 * @return string Parsed value
407 */
408 private function _parseToken($token)
409 {
410 // knock of the braces
411 $token = substr($token, 1, strlen($token) - 2);
412
413 // language token
414 if ($token[0] == '@' AND $token[1] == '\\' AND $token[2] == '"')
415 {
416 return '" . ' . $this->langcall . '(\'' . str_replace(array('\\\"', "'"), array('"', "\'"), substr($token, 3, strlen($token) - 5)) . '\')' . ' . "';
417 }
418 // normal PHP code
419 else
420 {
421 return '" . (' . $token . ') . "';
422 }
423 }
424
425 // ###################################################################
426 /**
427 * Prepares language and locale information inside templates
428 *
429 * @param string Template data to be processed
430 *
431 * @return string Language-ready template data
432 */
433 private function _parsePhrases($template)
434 {
435 $tagStart = '<lang ';
436 $tagEnd = '</lang>';
437
438 $start = -1; // start of open tag
439 $end = -1; // start of the close tag
440 $varEnd = -1; // end of the open tag
441
442 while ($start <= strlen($template))
443 {
444 // reset
445 $varMap = array(); // storage for all the substitution indices
446
447 // Find the start language object tag
448 $start = strpos($template, $tagStart, $end + 1);
449 if ($start === false)
450 {
451 break;
452 }
453
454 // look ahead to parse out all the variables
455 $i = $start + strlen($tagStart); // current position
456 $capture = ''; // current capture
457 $capturePos = $i; // the place to start capturing
458 $varNum = -1; // variable placeholder index
459 while ($i < strlen($template))
460 {
461 if ($template[$i] == '=')
462 {
463 // backtrack to find the previous variable substitution
464 $backPos = $i;
465 while ($backPos >= $start)
466 {
467 if ($template[$backPos] == '"')
468 {
469 // startPosition + length(startTag) + length(=\")
470 $varMap[intval($varNum)] = BSFunctions::Substring($template, $capturePos + 3, $backPos - 1);
471 // remove our old substitution from the capture
472 $capture = BSFunctions::Substring($template, $backPos + 1, $i);
473 break;
474 }
475 $backPos--;
476 }
477
478 // do we have a valid index?
479 if (intval($capture) > 0)
480 {
481 // set aside the index and restart capturing
482 $varNum = $capture;
483 $capture = '';
484 $capturePos = $i;
485 }
486 else
487 {
488 trigger_error('Invalid language variable index "' . $capture . '"');
489 }
490 }
491 else if ($template[$i] == '>' AND $template[$i - 1] == '"')
492 {
493 // the final variable substitution
494 $varMap[intval($varNum)] = BSFunctions::Substring($template, $capturePos + 3, $i - 2);
495 $varEnds = $i;
496 break;
497 }
498
499 $capture .= $template[$i];
500 $i++;
501 }
502
503 // locate the end tag
504 $end = strpos($template, $tagEnd, $i);
505 if ($end === false)
506 {
507 break;
508 }
509
510 // this is the string that gets variable replacement
511 $str = BSFunctions::Substring($template, $varEnds + 1, $end);
512
513 // create the complete varmap
514
515 for ($i = max(array_keys($varMap)); $i > 0; $i--)
516 {
517 if (!isset($varMap[$i]))
518 {
519 $varMap[$i] = '<strong>[MISSING SUBSTITUTION INDEX: ' . $i . ']</strong>';
520 }
521 }
522
523 // put all the keys in corresponding argument order
524 ksort($varMap);
525
526 // FINALLY, construct the call to sprintf()
527 $template = substr_replace($template, '" . ' . $this->langconst . '(\'' . $str . '\', "' . implode('", "', $varMap) . '") . "', $start, ($end + strlen($tagEnd)) - $start);
528 }
529
530 return $template;
531 }
532
533 // ###################################################################
534 /**
535 * Parser for in-line template conditionals
536 *
537 * @param string Template data awaiting processing
538 *
539 * @return string Parsed template data
540 */
541 private function _parseConditionals($template)
542 {
543 // tag data
544 $tag_start = '<if condition=\"';
545 $tag_start_end = '\">';
546 $tag_else = '<else />';
547 $tag_end = '</if>';
548
549 // tag stack
550 $stack = array();
551
552 // the information about the current active tag
553 $tag_full = array();
554 $parsed = array();
555
556 // start at 0
557 $offset = 0;
558
559 while (1)
560 {
561 if (strpos($template, $tag_start) === false)
562 {
563 break;
564 }
565
566 for ($i = $offset; $i < strlen($template); $i++)
567 {
568 // we've found ourselves a conditional!
569 if (substr($template, $i, strlen($tag_start)) == $tag_start)
570 {
571 // push the position into the tag stack
572 if ($tag_full)
573 {
574 array_push($stack, $i);
575 }
576 else
577 {
578 $tag_full['posi'] = $i;
579 }
580 }
581 // locate else tags
582 else if (substr($template, $i, strlen($tag_else)) == $tag_else)
583 {
584 if (sizeof($stack) == 0 AND !isset($tag_full['else']))
585 {
586 $tag_full['else'] = $i;
587 }
588 }
589 // do we have an end tag?
590 else if (substr($template, $i, strlen($tag_end)) == $tag_end)
591 {
592 if (sizeof($stack) != 0)
593 {
594 array_pop($stack);
595 continue;
596 }
597
598 // calculate the position of the end tag
599 $tag_full['posf'] = $i + strlen($tag_end) - 1;
600
601 // extract the entire conditional from the template
602 $fullspread = substr($template, $tag_full['posi'], $tag_full['posf'] - $tag_full['posi'] + 1);
603
604 // remove the beginning tag
605 $conditional = substr($fullspread, strlen($tag_start));
606
607 // find the end of the expression
608 $temp_end = strpos($conditional, $tag_start_end);
609
610 // save the expression
611 $parsed[0] = stripslashes(substr($conditional, 0, $temp_end));
612
613 // remove the expression from the conditional
614 $conditional = substr($conditional, strlen($parsed[0]) + strlen($tag_start_end));
615
616 // remove the tailing end tag
617 $conditional = substr($conditional, 0, strlen($conditional) - strlen($tag_end));
618
619 // handle the else
620 if (isset($tag_full['else']))
621 {
622 // now relative to the start of the <if>
623 $relpos = $tag_full['else'] - $tag_full['posi'];
624
625 // calculate the length of the expression and opening tag
626 $length = strlen($parsed[0]) + strlen($tag_start) + strlen($tag_start_end);
627
628 // relative to the start of iftrue
629 $elsepos = $relpos - $length;
630
631 $parsed[1] = substr($conditional, 0, $elsepos);
632 $parsed[2] = substr($conditional, $elsepos + strlen($tag_else));
633 }
634 // no else to handle
635 else
636 {
637 $parsed[1] = $conditional;
638 $parsed[2] = '';
639 }
640
641 // final parsed output
642 $parsed = '" . ((' . stripslashes($parsed[0]) . ') ? "' . $parsed[1] . '" : "' . $parsed[2] . '") . "';
643
644 // replace the conditional
645 $template = str_replace($fullspread, $parsed, $template);
646
647 // reset the parser
648 $offset = $tag_full['posi'] + strlen($tag_start) + strlen($tag_start_end);
649 $tag_full = array();
650 $stack = array();
651 $parsed = array();
652 unset($fullspread, $conditional, $temp_end, $relpos, $length, $elsepos);
653 break;
654 }
655 }
656 }
657
658 return $template;
659 }
660 }
661
662 // ###################################################################
663 /**
664 * Debugging function used to print characters in a string that are
665 * around a certain position.
666 *
667 * @access private
668 *
669 * @param string The haystack string
670 * @param integer Position to print around
671 */
672 function print_around($str, $pos)
673 {
674 echo '>>> PA >>>>>>>>[';
675 echo htmlspecialchars($str[ $pos - 5 ]);
676 echo htmlspecialchars($str[ $pos - 4 ]);
677 echo htmlspecialchars($str[ $pos - 3 ]);
678 echo htmlspecialchars($str[ $pos - 2 ]);
679 echo htmlspecialchars($str[ $pos - 1 ]);
680 echo '©';
681 echo htmlspecialchars($str[ $pos + 0 ]);
682 echo htmlspecialchars($str[ $pos + 1 ]);
683 echo htmlspecialchars($str[ $pos + 2 ]);
684 echo htmlspecialchars($str[ $pos + 3 ]);
685 echo htmlspecialchars($str[ $pos + 4 ]);
686 echo htmlspecialchars($str[ $pos + 5 ]);
687 echo ']<<<<<<<< PA <<<';
688 }
689
690 /*=====================================================================*\
691 || ###################################################################
692 || # $HeadURL$
693 || # $Id$
694 || ###################################################################
695 \*=====================================================================*/
696 ?>