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