Fixed template parser, I guess we broke it with r127
[isso.git] / template.php
1 <?php
2 /*=====================================================================*\
3 || ################################################################### ||
4 || # Iris Studios Shared Object Framework [#]version[#]
5 || # --------------------------------------------------------------- # ||
6 || # Copyright ©2002-[#]year[#] by Iris Studios, Inc. All Rights Reserved. # ||
7 || # This file may not be reproduced in any way without permission. # ||
8 || # --------------------------------------------------------------- # ||
9 || # User License Agreement at http://www.iris-studios.com/license/ # ||
10 || ################################################################### ||
11 \*=====================================================================*/
12
13 /**
14 * Database-Driven Template System
15 * template.php
16 *
17 * @package ISSO
18 */
19
20 $OBJECT = 'Database Template System';
21 $CLASS = 'DB_Template';
22 $OBJ = 'template';
23
24 /**
25 * Database-Driven Template System
26 *
27 * This framework is a backend to the database template engine and
28 * contains all the parsing algorithms.
29 *
30 * @author Iris Studios, Inc.
31 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
32 * @version $Revision$
33 * @package ISSO
34 *
35 */
36 class DB_Template
37 {
38 /**
39 * Name of the database table templates are in
40 * @var str
41 * @see _load()
42 */
43 var $templatetable = '';
44
45 /**
46 * Name of the table column template names are in
47 * @var str
48 * @see $templatetable, _load()
49 */
50 var $namecolumn = '';
51
52 /**
53 * Name of the table column templates are in
54 * @var str
55 * @see templatetable, _load()
56 */
57 var $datacolumn = '';
58
59 /**
60 * Additional WHERE clauses for the template fetch SQL
61 * @var str
62 * @see _load(), cache()
63 */
64 var $extrawhere = '';
65
66 /**
67 * The name of the function phrases are fetched with
68 * @var str
69 * @see _parse_phrases()
70 */
71 var $langcall = 'fetch_phrase';
72
73 /**
74 * The name of the function phrases are sprintf() parsed with
75 * @var str
76 * @see _parse_phrases()
77 */
78 var $langconst = 'construct_phrase';
79
80 /**
81 * Array of pre-compiled templates that are stored to decrease server load
82 * @var array
83 * @see cache()
84 */
85 var $cache = array();
86
87 /**
88 * A list of the number of times each template has been used
89 * @var array
90 * @see fetch()
91 */
92 var $usage = array();
93
94 /**
95 * A list of templates that weren't cached, but are still used
96 * @var array
97 * @see fetch()
98 */
99 var $uncached = array();
100
101 /**
102 * Whether or not the page has been flush()'d already
103 * @var bool
104 * @see flush()
105 */
106 var $doneflush = false;
107
108 /**
109 * Takes an array of template names, loads them, and then stores
110 * a parsed version for optimum speed.
111 *
112 * @param array List of template names to be cached
113 */
114 function cache($namearray)
115 {
116 global $_isso;
117
118 if (sizeof($this->cache) > 0)
119 {
120 trigger_error('You cannot cache templates more than once per initialization', ERR_WARNING);
121 }
122 else
123 {
124 $templates = $_isso->db->query("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " IN ('" . implode("', '", $namearray) . "')" . (($this->extrawhere) ? $this->extrawhere : ''));
125 while ($template = $_isso->db->fetch_array($templates))
126 {
127 $template = $this->_parse($template);
128 $this->cache[ $template[ $this->namecolumn ] ] = $template[ $this->datacolumn ];
129 $this->usage["$name"] = 0;
130 }
131 }
132 }
133
134 /**
135 * Loads a template from the cache or the _load function and
136 * stores the parsed version of it
137 *
138 * @param str The name of the template
139 *
140 * @return str A parsed and loaded template
141 */
142 function fetch($name)
143 {
144 global $_isso;
145
146 if (isset($this->cache["$name"]))
147 {
148 $template = $this->cache["$name"];
149 }
150 else
151 {
152 $this->uncached[] = $name;
153 $_isso->debug("Manually loading template `$name`");
154 $template = $this->_load($name);
155 $template = $this->_parse($template);
156 }
157
158 if (!isset($this->usage["$name"]))
159 {
160 $this->usage["$name"] = 0;
161 }
162
163 $this->usage["$name"]++;
164
165 return $template;
166 }
167
168 /**
169 * Output a template fully compiled to the browser
170 *
171 * @param str Compiled and ready template
172 */
173 function flush($template)
174 {
175 global $_isso;
176
177 ob_start();
178
179 if (empty($template))
180 {
181 trigger_error('There was no output to print', E_USER_ERROR);
182 exit;
183 }
184
185 if ($_isso->debug AND isset($_GET['query']))
186 {
187 if (is_array($_isso->db->history))
188 {
189 echo '<pre>';
190 foreach ($_isso->db->history AS $query)
191 {
192 echo $query . "\n\n<hr />\n\n";
193 }
194 echo '</pre>';
195 }
196 exit;
197 }
198
199 if ($this->doneflush)
200 {
201 trigger_error('A template has already been sent to the output buffer', E_USER_ERROR);
202 exit;
203 }
204
205 if ($_isso->debug)
206 {
207 // --- START
208 $debug = "\n<ul>";
209
210 // templates
211 $optlist = array();
212 $usage = array();
213 foreach ($this->usage AS $name => $count)
214 {
215 if (in_array($name, $this->uncached))
216 {
217 $optlist[] = $name . '[' . $count . ']';
218 }
219 $usage[] = $name . " ($count)";
220 }
221
222 $sizeof = sizeof($this->uncached);
223 if ($sizeof > 0)
224 {
225 $debug .= "\n\t<li><strong style=\"color: red\">Uncached Template(s):</strong> $sizeof ( " . implode(' &nbsp; ', $optlist) . " )</li>";
226 }
227
228 // source control
229 $scinfo = 'Not Under Source Control';
230 $possiblescms = array('cvs', 'svn', 'cvs_information', 'svn_information', 'scm', 'sc_information', 'scm_information');
231 foreach ($possiblescms AS $scm)
232 {
233 if (defined(strtoupper($scm)))
234 {
235 $scinfo = constant(strtoupper($scm));
236
237 $type = '';
238 // CVS
239 if (strpos($scinfo, 'RCSfile:') !== false)
240 {
241 $type = 'cvs';
242 }
243 else if (strpos($scinfo, ',v ') !== false)
244 {
245 $type = 'cvs';
246 }
247 // SVN
248 else if (strpos($scinfo, 'URL:') !== false)
249 {
250 $type = 'svn';
251 }
252 else if (strpos($scinfo, 'https://') !== false OR strpos($scinfo, 'http://') !== false)
253 {
254 $type= 'svn';
255 }
256 // not found so just return it
257 // try a SVN ID tag as we can't really tell if we're using it
258 else
259 {
260 $test = preg_replace('#\$' . 'Id: (.+?) (.+?) [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(.+?) (.+?) \$#', '\\1 - SVN \\2', $scinfo);
261 if ($test == '$' . 'Id: $')
262 {
263 $scinfo = 'Not Under Source Control';
264 }
265 else
266 {
267 $scinfo = $test;
268 }
269 break;
270 }
271
272 if ($type == 'cvs')
273 {
274 $scinfo = preg_replace('#\$' . 'RCSfile: (.+?) \$#', '\\1', $scinfo);
275 $scinfo = preg_replace('#\$' . 'Revision: (.+?) \$#', 'CVS \\1', $scinfo);
276 $scinfo = preg_replace('#\$' . 'Id: (.+?) (.+?) [0-9]{4}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} (.+?) (.+?) \$#', '\\1 - CVS \\2', $scinfo);
277 }
278 else if ($type == 'svn')
279 {
280 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
281 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
282 $scinfo = preg_replace('#\$' . 'Id: (.+?) ([0-9].+?) [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(.+?) (.+?) \$#', '\\1 - SVN \\2', $scinfo);
283 }
284 else
285 {
286 $scinfo = 'Not Under Source Control';
287 }
288 break;
289 }
290 }
291 $scinfo = trim($scinfo);
292 $debug .= "\n\t<li><strong>Source Control:</strong> $scinfo</li>";
293
294 // query information
295 $debug .= "\n\t<li><strong>Total Queries:</strong> " . sizeof($_isso->db->history) . " (<a href=\"" . $_isso->sanitize($_SERVER['REQUEST_URI']) . ((strpos($_SERVER['REQUEST_URI'], '?') !== false) ? '&amp;query=1' : '?query=1') . "\">?</a>)</li>";
296
297 // total execution time
298 if (defined('ISSO_MT_START'))
299 {
300 $_isso->load('functions');
301 $debug .= "\n\t<li><strong>Total Execution Time:</strong> " . round($_isso->funct->fetch_microtime_diff(ISSO_MT_START), 10) . "</li>";
302 }
303
304 // debug notices
305 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Debug Notices (" . sizeof($_isso->debuginfo) . ")</option>";
306 foreach ((array)$_isso->debuginfo AS $msg)
307 {
308 $debug .= "\n\t\t\t<option>--- $msg</option>";
309 }
310 $debug .= "\n\t\t</select>\n\t</li>";
311
312 // loaded modules
313 $modules = $_isso->show_modules(true);
314 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Loaded Modules (" . sizeof($modules) . ")</option>";
315 foreach ($modules AS $mod)
316 {
317 $debug .= "\n\t\t\t<option>--- $mod</option>";
318 }
319 $debug .= "\n\t\t</select>\n\t</li>";
320
321 // template usage
322 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Template Usage (" . array_sum($this->usage) . ")</option>";
323 foreach ($usage AS $tpl)
324 {
325 $debug .= "\n\t\t\t<option>--- $tpl</option>";
326 }
327 $debug .= "\n\t\t</select>\n\t</li>";
328
329 // --- END
330 $debug .= "\n</ul>";
331
332 $debug = "\n<hr />\n" . $_isso->_message('Debug Information', $debug, 1, true);
333 $template = str_replace('</body>', "\n\n<!-- dev debug -->\n<div align=\"center\">\n$debug\n</div>\n<!-- / dev debug -->\n\n</body>", $template);
334 }
335
336 print(stripslashes($template));
337 }
338
339 /**
340 * Loads an additional template from the database
341 *
342 * @param str The name of the template
343 *
344 * @return str Template data from the database
345 */
346 function _load($name)
347 {
348 global $_isso;
349 if ($template = $_isso->db->query("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " = '$name'" . (($this->extrawhere) ? $this->extrawhere : '')))
350 {
351 return $template[ $this->datacolumn ];
352 }
353 else
354 {
355 trigger_error("The template '$name' could not be loaded", E_USER_ERROR);
356 exit;
357 }
358 }
359
360 /**
361 * A wrapper for all the parsing functions and compiling functins
362 *
363 * @param str Unparsed template data
364 *
365 * @return str Parsed template data
366 */
367 function _parse($template)
368 {
369 $template = stripslashes($template);
370 $template = str_replace('"', '\"', $template);
371 $template = $this->_parse_phrases($template);
372 $template = $this->_parse_conditionals($template);
373 return $template;
374 }
375
376 /**
377 * Prepares language and locale information inside templates
378 *
379 * @param str Template data to be processed
380 *
381 * @return str Language-ready template data
382 */
383 function _parse_phrases($template)
384 {
385 $tag_start = '<lang ';
386 $tag_start_end = '">';
387 $tag_end = '</lang>';
388
389 $location_start = -1;
390 $location_end = -1;
391
392 // Process the empty phrase objects -- do this now so we don't have to worry about it when we're parsing later
393 $template = preg_replace('#\{lang\.(.*?)\}#i', '" . ' . $this->langcall . '(\'$1\') . "', $template);
394
395 while (1)
396 {
397 // Find the start language object tag
398 $location_start = strpos($template, $tag_start, $location_end + 1);
399 if ($location_start === false)
400 {
401 break;
402 }
403
404 // Find the end tag
405 $location_end = strpos($template, $tag_end, $location_end + strlen($tag_end));
406 if ($location_end === false)
407 {
408 break;
409 }
410
411 // Extract the language object
412 $phrase_bunch = substr($template, $location_start, ($location_end + strlen($tag_end)) - $location_start);
413
414 // Find the close to the opening <lang>
415 $close_of_open = strpos($phrase_bunch, $tag_start_end);
416 if ($close_of_open === false)
417 {
418 break;
419 }
420
421 // Extract the opening tag so it can be parsed
422 $init_tag = substr($phrase_bunch, 0, ($close_of_open + strlen($tag_start_end)));
423 $init_tag = str_replace($tag_start, '', $init_tag);
424 $init_tag = substr($init_tag, 0, strlen($init_tag) - 1);
425
426 // Get the args out of the tag
427 $args = preg_split('#([0-9].*?)=#', $init_tag);
428 foreach ($args AS $arg)
429 {
430 if ($arg AND $arg != ' ')
431 {
432 $arg = trim($arg);
433 $arg = substr($arg, 2);
434 $arg = substr($arg, 0, strlen($arg) - 2);
435 $arglist[] = $arg;
436 }
437 }
438
439 // Just get the phrase name
440 $phrase_name = preg_replace('#<lang(.*?)>(.*?)</lang>#i', '$2', $phrase_bunch);
441
442 // Wrap the parsed data into the build function
443 $function_wrap = '" . ' . $this->langconst . '(\'' . $phrase_name . '\', "' . implode('", "', $arglist) . '") . "';
444
445 // Replace the fully-parsed string back into the template
446 $template = substr_replace($template, $function_wrap, $location_start, $location_end + strlen($tag_end) - $location_start);
447
448 unset($arglist);
449 }
450
451 return $template;
452 }
453
454 /**
455 * Parser for in-line template conditionals
456 *
457 * @param str Template data awaiting processing
458 *
459 * @return str Parsed template data
460 */
461 function _parse_conditionals($template)
462 {
463 global $_isso;
464
465 // tag data
466 $tag_start = '<if condition=\"';
467 $tag_start_end = '\">';
468 $tag_else = '<else />';
469 $tag_end = '</if>';
470
471 // tag stack
472 $stack = array();
473
474 // the information about the current active tag
475 $tag_full = array();
476 $parsed = array();
477
478 // start at 0
479 $offset = 0;
480
481 while (1)
482 {
483 if (strpos($template, $tag_start) === false)
484 {
485 break;
486 }
487
488 for ($i = $offset; $i < strlen($template); $i++)
489 {
490 // we've found ourselves a conditional!
491 if (substr($template, $i, strlen($tag_start)) == $tag_start)
492 {
493 // push the position into the tag stack
494 if ($tag_full)
495 {
496 array_push($stack, $i);
497 }
498 else
499 {
500 $tag_full['posi'] = $i;
501 }
502 }
503 // locate else tags
504 else if (substr($template, $i, strlen($tag_else)) == $tag_else)
505 {
506 if (count($stack) == 0 AND !isset($tag_full['else']))
507 {
508 $tag_full['else'] = $i;
509 }
510 }
511 // do we have an end tag?
512 else if (substr($template, $i, strlen($tag_end)) == $tag_end)
513 {
514 if (count($stack) != 0)
515 {
516 array_pop($stack);
517 continue;
518 }
519
520 // calculate the position of the end tag
521 $tag_full['posf'] = $i + strlen($tag_end) - 1;
522
523 // extract the entire conditional from the template
524 $fullspread = substr($template, $tag_full['posi'], $tag_full['posf'] - $tag_full['posi'] + 1);
525
526 // remove the beginning tag
527 $conditional = substr($fullspread, strlen($tag_start));
528
529 // find the end of the expression
530 $temp_end = strpos($conditional, $tag_start_end);
531
532 // save the expression
533 $parsed[0] = stripslashes(substr($conditional, 0, $temp_end));
534
535 // remove the expression from the conditional
536 $conditional = substr($conditional, strlen($parsed[0]) + strlen($tag_start_end));
537
538 // remove the tailing end tag
539 $conditional = substr($conditional, 0, strlen($conditional) - strlen($tag_end));
540
541 // handle the else
542 if (isset($tag_full['else']))
543 {
544 // now relative to the start of the <if>
545 $relpos = $tag_full['else'] - $tag_full['posi'];
546
547 // calculate the length of the expression and opening tag
548 $length = strlen($parsed[0]) + strlen($tag_start) + strlen($tag_start_end);
549
550 // relative to the start of iftrue
551 $elsepos = $relpos - $length;
552
553 $parsed[1] = substr($conditional, 0, $elsepos);
554 $parsed[2] = substr($conditional, $elsepos + strlen($tag_else));
555 }
556 // no else to handle
557 else
558 {
559 $parsed[1] = $conditional;
560 $parsed[2] = '';
561 }
562 #var_dump($parsed);
563
564 // final parsed output
565 $parsed = '" . ((' . stripslashes($parsed[0]) . ') ? "' . $parsed[1] . '" : "' . $parsed[2] . '") . "';
566
567 // replace the conditional
568 $template = str_replace($fullspread, $parsed, $template);
569
570 // reset the parser
571 $offset = $tag_full['posi'] + strlen($tag_start) + strlen($tag_start_end);
572 $tag_full = array();
573 $stack = array();
574 $parsed = array();
575 unset($fullspread, $conditional, $temp_end, $relpos, $length, $elsepos);
576 break;
577 }
578 }
579 }
580
581 return $template;
582 }
583 }
584
585 /**
586 * Debugging function used to print characters
587 * in a string that are around a certain position.
588 *
589 * @param string The haystack string
590 * @param integer Position to print around
591 */
592 function print_around($str, $pos)
593 {
594 echo '>>> PA >>>>>>>>[';
595 echo htmlspecialchars($str[ $pos - 5 ]);
596 echo htmlspecialchars($str[ $pos - 4 ]);
597 echo htmlspecialchars($str[ $pos - 3 ]);
598 echo htmlspecialchars($str[ $pos - 2 ]);
599 echo htmlspecialchars($str[ $pos - 1 ]);
600 echo '©';
601 echo htmlspecialchars($str[ $pos + 0 ]);
602 echo htmlspecialchars($str[ $pos + 1 ]);
603 echo htmlspecialchars($str[ $pos + 2 ]);
604 echo htmlspecialchars($str[ $pos + 3 ]);
605 echo htmlspecialchars($str[ $pos + 4 ]);
606 echo htmlspecialchars($str[ $pos + 5 ]);
607 echo ']<<<<<<<< PA <<<';
608 }
609
610 /*=====================================================================*\
611 || ###################################################################
612 || # $HeadURL$
613 || # $Id$
614 || ###################################################################
615 \*=====================================================================*/
616 ?>