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