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