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