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