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