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