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