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