Template updated
[isso.git] / template.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework [#]issoversion[#]
5 || # Copyright ©2002-[#]year[#] Blue Static
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 * Hooks:
36 * $this->pre_parse_hook - Name of the function to execute on
37 * a template before the parsing occurs
38 *
39 * @author Blue Static
40 * @copyright Copyright ©2002 - [#]year[#], Blue Static
41 * @version $Revision$
42 * @package ISSO
43 *
44 */
45 class Template
46 {
47 /**
48 * Framework registry object
49 * @var object
50 * @access private
51 */
52 var $registry = null;
53
54 /**
55 * Name of the database table templates are in
56 * @var string
57 * @access private
58 */
59 var $tablename = '';
60
61 /**
62 * Name of the table column template names are in
63 * @var string
64 * @access private
65 */
66 var $namecolumn = '';
67
68 /**
69 * Name of the table column templates are in
70 * @var string
71 * @access private
72 */
73 var $datacolumn = '';
74
75 /**
76 * Additional WHERE clauses for the template fetch SQL
77 * @var string
78 * @access private
79 */
80 var $extrawhere = '';
81
82 /**
83 * The name of the function phrases are fetched with
84 * @var string
85 * @access private
86 */
87 var $langcall = 'gettext';
88
89 /**
90 * The name of the function phrases are sprintf() parsed with
91 * @var string
92 * @access private
93 */
94 var $langconst = 'sprintf';
95
96 /**
97 * Array of pre-compiled templates that are stored to decrease server load
98 * @var array
99 * @access private
100 */
101 var $cache = array();
102
103 /**
104 * A list of the number of times each template has been used
105 * @var array
106 * @access private
107 */
108 var $usage = array();
109
110 /**
111 * A list of templates that weren't cached, but are still used
112 * @var array
113 * @access private
114 */
115 var $uncached = array();
116
117 /**
118 * Whether or not the page has been flush()'d already
119 * @var bool
120 * @access private
121 */
122 var $doneflush = false;
123
124 /**
125 * The name of a function that is called before template parsing of phrases and conditionals occurs
126 * @var string
127 * @access private
128 */
129 var $pre_parse_hook = ':=NO METHOD=:';
130
131 // ###################################################################
132 /**
133 * Constructor
134 */
135 function __construct(&$registry)
136 {
137 $this->registry =& $registry;
138 }
139
140 // ###################################################################
141 /**
142 * (PHP 4) Constructor
143 */
144 function Template(&$registry)
145 {
146 $this->__construct($registry);
147 }
148
149 // ###################################################################
150 /**
151 * Initializes the class and all subclasses under a common package name
152 *
153 * @access protected
154 *
155 * @return string The package name
156 */
157 function init_as_package()
158 {
159 return 'template';
160 }
161
162 // ###################################################################
163 /**
164 * Sets tablename
165 *
166 * @access public
167 *
168 * @param string Table name
169 */
170 function setTableName($name)
171 {
172 $this->tablename = $name;
173 }
174
175 // ###################################################################
176 /**
177 * Sets namecolumn
178 *
179 * @access public
180 *
181 * @param string Name column name
182 */
183 function setNameColumn($name)
184 {
185 $this->namecolumn = $name;
186 }
187
188 // ###################################################################
189 /**
190 * Sets datacolumn
191 *
192 * @access public
193 *
194 * @param string Data column name
195 */
196 function setDataColumn($name)
197 {
198 $this->datacolumn = $name;
199 }
200
201 // ###################################################################
202 /**
203 * Sets extrawhere
204 *
205 * @access public
206 *
207 * @param string Extra WHERE SQL clause
208 */
209 function setExtraWhere($sql)
210 {
211 $this->extrawhere = $sql;
212 }
213
214 // ###################################################################
215 /**
216 * Sets the pre-parse hook
217 *
218 * @access public
219 *
220 * @param string Method name
221 */
222 function setPreParseHook($name)
223 {
224 $this->pre_parse_hook = $name;
225 }
226
227 // ###################################################################
228 /**
229 * Takes an array of template names, loads them, and then stores a
230 * parsed version for optimum speed.
231 *
232 * @access public
233 *
234 * @param array List of template names to be cached
235 */
236 function cache($namearray)
237 {
238 if (sizeof($this->cache) > 0)
239 {
240 trigger_error('You cannot cache templates more than once per initialization', E_USER_WARNING);
241 }
242 else
243 {
244 $templates = $this->registry->modules[ISSO_DB_LAYER]->query("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " IN ('" . implode("', '", $namearray) . "')" . ($this->extrawhere ? ' ' . $this->extrawhere : ''));
245 while ($template = $this->registry->modules[ISSO_DB_LAYER]->fetch_array($templates))
246 {
247 $this->cache[ $template[ $this->namecolumn ] ] = $this->_parse($template[ $this->datacolumn ]);
248 $this->usage[ $template[ $this->namecolumn ] ] = 0;
249 }
250 }
251 }
252
253 // ###################################################################
254 /**
255 * Loads a template from the cache or the _load function and stores the
256 * parsed version of it
257 *
258 * @access public
259 *
260 * @param string The name of the template
261 *
262 * @return string A parsed and loaded template
263 */
264 function fetch($name)
265 {
266 if (isset($this->cache["$name"]))
267 {
268 $template = $this->cache["$name"];
269 }
270 else
271 {
272 $this->uncached[] = $name;
273 $this->registry->debug("Manually loading template `$name`");
274 $template = $this->_load($name);
275 $template = $this->_parse($template);
276 }
277
278 if (!isset($this->usage["$name"]))
279 {
280 $this->usage["$name"] = 0;
281 }
282
283 $this->usage["$name"]++;
284
285 return $template;
286 }
287
288 // ###################################################################
289 /**
290 * Output a template fully compiled to the browser
291 *
292 * @access public
293 *
294 * @param string Compiled and ready template
295 */
296 function flush($template)
297 {
298 ob_start();
299
300 if (empty($template))
301 {
302 trigger_error('There was no output to print', E_USER_ERROR);
303 exit;
304 }
305
306 if ($this->registry->debug AND isset($_GET['query']))
307 {
308 if (is_array($this->registry->modules[ISSO_DB_LAYER]->history))
309 {
310 foreach ($this->registry->modules[ISSO_DB_LAYER]->history AS $query)
311 {
312 echo $this->registry->modules[ISSO_DB_LAYER]->construct_query_debug($query);
313 }
314 }
315 exit;
316 }
317
318 if ($this->doneflush)
319 {
320 trigger_error('A template has already been sent to the output buffer', E_USER_ERROR);
321 exit;
322 }
323
324 $template = str_replace('</body>', $this->registry->construct_debug_block(true) . '</body>', $template);
325
326 print($template);
327 }
328
329 // ###################################################################
330 /**
331 * Loads an additional template from the database
332 *
333 * @access private
334 *
335 * @param string The name of the template
336 *
337 * @return string Template data from the database
338 */
339 function _load($name)
340 {
341 if ($template = $this->registry->modules[ISSO_DB_LAYER]->query_first("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " = '$name'" . ($this->extrawhere ? ' ' . $this->extrawhere : '')))
342 {
343 return $template[ $this->datacolumn ];
344 }
345 else
346 {
347 trigger_error("The template '$name' could not be loaded", E_USER_ERROR);
348 exit;
349 }
350 }
351
352 // ###################################################################
353 /**
354 * A wrapper for all the parsing functions and compiling functins
355 *
356 * @access protected
357 *
358 * @param string Unparsed template data
359 *
360 * @return string Parsed template data
361 */
362 function _parse($template)
363 {
364 $this->registry->check_isso_fields(get_class($this));
365
366 $template = str_replace('"', '\"', $template);
367
368 if (function_exists($this->pre_parse_hook))
369 {
370 $template = call_user_func($this->pre_parse_hook, $template);
371 }
372
373 $template = $this->_parse_phrases($template);
374 $template = $this->_parse_conditionals($template);
375 return $template;
376 }
377
378 // ###################################################################
379 /**
380 * Prepares language and locale information inside templates
381 *
382 * @access private
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 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 . '("' . /*str_replace(array('\"', "'"), array('"', "\'"),*/ $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 // Process the empty phrase objects -- do this now so we don't have to worry about it when we're parsing later
454 $template = preg_replace('#\{@\\\"(.*?)\\\"\}#ise', '$this->_phrase_string(\'$1\')', $template);
455
456 return $template;
457 }
458
459 // ###################################################################
460 /**
461 * Turns a localized phrase tag into a function call
462 *
463 * @access private
464 *
465 * @param string Phrase text
466 *
467 * @return string Function call for phrase text
468 */
469 function _phrase_string($text)
470 {
471 return '" . ' . $this->langcall . '(\'' . str_replace(array('\\\"', "'"), array('"', "\'"), $text) . '\') . "';
472 }
473
474 // ###################################################################
475 /**
476 * Parser for in-line template conditionals
477 *
478 * @access private
479 *
480 * @param string Template data awaiting processing
481 *
482 * @return string Parsed template data
483 */
484 function _parse_conditionals($template)
485 {
486 // tag data
487 $tag_start = '<if condition=\"';
488 $tag_start_end = '\">';
489 $tag_else = '<else />';
490 $tag_end = '</if>';
491
492 // tag stack
493 $stack = array();
494
495 // the information about the current active tag
496 $tag_full = array();
497 $parsed = array();
498
499 // start at 0
500 $offset = 0;
501
502 while (1)
503 {
504 if (strpos($template, $tag_start) === false)
505 {
506 break;
507 }
508
509 for ($i = $offset; $i < strlen($template); $i++)
510 {
511 // we've found ourselves a conditional!
512 if (substr($template, $i, strlen($tag_start)) == $tag_start)
513 {
514 // push the position into the tag stack
515 if ($tag_full)
516 {
517 array_push($stack, $i);
518 }
519 else
520 {
521 $tag_full['posi'] = $i;
522 }
523 }
524 // locate else tags
525 else if (substr($template, $i, strlen($tag_else)) == $tag_else)
526 {
527 if (sizeof($stack) == 0 AND !isset($tag_full['else']))
528 {
529 $tag_full['else'] = $i;
530 }
531 }
532 // do we have an end tag?
533 else if (substr($template, $i, strlen($tag_end)) == $tag_end)
534 {
535 if (sizeof($stack) != 0)
536 {
537 array_pop($stack);
538 continue;
539 }
540
541 // calculate the position of the end tag
542 $tag_full['posf'] = $i + strlen($tag_end) - 1;
543
544 // extract the entire conditional from the template
545 $fullspread = substr($template, $tag_full['posi'], $tag_full['posf'] - $tag_full['posi'] + 1);
546
547 // remove the beginning tag
548 $conditional = substr($fullspread, strlen($tag_start));
549
550 // find the end of the expression
551 $temp_end = strpos($conditional, $tag_start_end);
552
553 // save the expression
554 $parsed[0] = stripslashes(substr($conditional, 0, $temp_end));
555
556 // remove the expression from the conditional
557 $conditional = substr($conditional, strlen($parsed[0]) + strlen($tag_start_end));
558
559 // remove the tailing end tag
560 $conditional = substr($conditional, 0, strlen($conditional) - strlen($tag_end));
561
562 // handle the else
563 if (isset($tag_full['else']))
564 {
565 // now relative to the start of the <if>
566 $relpos = $tag_full['else'] - $tag_full['posi'];
567
568 // calculate the length of the expression and opening tag
569 $length = strlen($parsed[0]) + strlen($tag_start) + strlen($tag_start_end);
570
571 // relative to the start of iftrue
572 $elsepos = $relpos - $length;
573
574 $parsed[1] = substr($conditional, 0, $elsepos);
575 $parsed[2] = substr($conditional, $elsepos + strlen($tag_else));
576 }
577 // no else to handle
578 else
579 {
580 $parsed[1] = $conditional;
581 $parsed[2] = '';
582 }
583 #var_dump($parsed);
584
585 // final parsed output
586 $parsed = '" . ((' . stripslashes($parsed[0]) . ') ? "' . $parsed[1] . '" : "' . $parsed[2] . '") . "';
587
588 // replace the conditional
589 $template = str_replace($fullspread, $parsed, $template);
590
591 // reset the parser
592 $offset = $tag_full['posi'] + strlen($tag_start) + strlen($tag_start_end);
593 $tag_full = array();
594 $stack = array();
595 $parsed = array();
596 unset($fullspread, $conditional, $temp_end, $relpos, $length, $elsepos);
597 break;
598 }
599 }
600 }
601
602 return $template;
603 }
604 }
605
606 // ###################################################################
607 /**
608 * Debugging function used to print characters in a string that are
609 * around a certain position.
610 *
611 * @access private
612 *
613 * @param string The haystack string
614 * @param integer Position to print around
615 */
616 function print_around($str, $pos)
617 {
618 echo '>>> PA >>>>>>>>[';
619 echo htmlspecialchars($str[ $pos - 5 ]);
620 echo htmlspecialchars($str[ $pos - 4 ]);
621 echo htmlspecialchars($str[ $pos - 3 ]);
622 echo htmlspecialchars($str[ $pos - 2 ]);
623 echo htmlspecialchars($str[ $pos - 1 ]);
624 echo '©';
625 echo htmlspecialchars($str[ $pos + 0 ]);
626 echo htmlspecialchars($str[ $pos + 1 ]);
627 echo htmlspecialchars($str[ $pos + 2 ]);
628 echo htmlspecialchars($str[ $pos + 3 ]);
629 echo htmlspecialchars($str[ $pos + 4 ]);
630 echo htmlspecialchars($str[ $pos + 5 ]);
631 echo ']<<<<<<<< PA <<<';
632 }
633
634 /*=====================================================================*\
635 || ###################################################################
636 || # $HeadURL$
637 || # $Id$
638 || ###################################################################
639 \*=====================================================================*/
640 ?>