Remove annoying pre-parse hook debug log
[isso.git] / template.php
1 <?php
2 /*=====================================================================*\
3 || ###################################################################
4 || # Iris Studios Shared Object Framework [#]issoversion[#]
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 * Hooks:
36 * $this->pre_parse_hook - Name of the function to execute on
37 * a template before the parsing occurs
38 *
39 * @author Iris Studios, Inc.
40 * @copyright Copyright ©2002 - [#]year[#], Iris Studios, Inc.
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 = '$GLOBALS[\'isso:callback\']->modules[\'localize\']->string';
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 * Fields array that is used in this module
133 * @var array
134 * @access private
135 */
136 var $fields = array(
137 'tablename' => array(REQ_YES, null, false),
138 'namecolumn' => array(REQ_YES, null, false),
139 'datacolumn' => array(REQ_YES, null, false),
140 'extrawhere' => array(REQ_NO, null, false),
141 'langcall' => array(REQ_YES, null, true),
142 'langconst' => array(REQ_YES, null, true),
143 'pre_parse_hook' => array(REQ_NO, null, false)
144 );
145
146 // ###################################################################
147 /**
148 * Constructor
149 */
150 function __construct(&$registry)
151 {
152 $this->registry =& $registry;
153 }
154
155 // ###################################################################
156 /**
157 * (PHP 4) Constructor
158 */
159 function Template(&$registry)
160 {
161 $this->__construct($registry);
162 }
163
164 // ###################################################################
165 /**
166 * Initializes the class and all subclasses under a common package name
167 *
168 * @access protected
169 *
170 * @return string The package name
171 */
172 function init_as_package()
173 {
174 return 'template';
175 }
176
177 // ###################################################################
178 /**
179 * Sets an ISSO field
180 *
181 * @access public
182 *
183 * @param string Field name
184 * @param mixed Value of the field
185 */
186 function set($name, $value)
187 {
188 $this->registry->do_set($name, $value, 'template');
189 }
190
191 // ###################################################################
192 /**
193 * Gets an ISSO field
194 *
195 * @access public
196 *
197 * @param string Field name
198 *
199 * @return mixed Value of the field
200 */
201 function get($fieldname)
202 {
203 return $this->registry->do_get($fieldname, 'template');
204 }
205
206 // ###################################################################
207 /**
208 * Takes an array of template names, loads them, and then stores a
209 * parsed version for optimum speed.
210 *
211 * @access public
212 *
213 * @param array List of template names to be cached
214 */
215 function cache($namearray)
216 {
217 if (sizeof($this->cache) > 0)
218 {
219 trigger_error('You cannot cache templates more than once per initialization', E_USER_WARNING);
220 }
221 else
222 {
223 $templates = $this->registry->modules[ISSO_DB_LAYER]->query("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " IN ('" . implode("', '", $namearray) . "')" . ($this->extrawhere ? ' ' . $this->extrawhere : ''));
224 while ($template = $this->registry->modules[ISSO_DB_LAYER]->fetch_array($templates))
225 {
226 $this->cache[ $template[ $this->namecolumn ] ] = $this->_parse($template[ $this->datacolumn ]);
227 $this->usage[ $template[ $this->namecolumn ] ] = 0;
228 }
229 }
230 }
231
232 // ###################################################################
233 /**
234 * Loads a template from the cache or the _load function and stores the
235 * parsed version of it
236 *
237 * @access public
238 *
239 * @param string The name of the template
240 *
241 * @return string A parsed and loaded template
242 */
243 function fetch($name)
244 {
245 if (isset($this->cache["$name"]))
246 {
247 $template = $this->cache["$name"];
248 }
249 else
250 {
251 $this->uncached[] = $name;
252 $this->registry->debug("Manually loading template `$name`");
253 $template = $this->_load($name);
254 $template = $this->_parse($template);
255 }
256
257 if (!isset($this->usage["$name"]))
258 {
259 $this->usage["$name"] = 0;
260 }
261
262 $this->usage["$name"]++;
263
264 return $template;
265 }
266
267 // ###################################################################
268 /**
269 * Output a template fully compiled to the browser
270 *
271 * @access public
272 *
273 * @param string Compiled and ready template
274 */
275 function flush($template)
276 {
277 ob_start();
278
279 if (empty($template))
280 {
281 trigger_error('There was no output to print', E_USER_ERROR);
282 exit;
283 }
284
285 if ($this->registry->debug AND isset($_GET['query']))
286 {
287 if (is_array($this->registry->modules[ISSO_DB_LAYER]->history))
288 {
289 foreach ($this->registry->modules[ISSO_DB_LAYER]->history AS $query)
290 {
291 echo $this->registry->modules[ISSO_DB_LAYER]->construct_query_debug($query);
292 }
293 }
294 exit;
295 }
296
297 if ($this->doneflush)
298 {
299 trigger_error('A template has already been sent to the output buffer', E_USER_ERROR);
300 exit;
301 }
302
303 $template = str_replace('</body>', $this->registry->construct_debug_block(true) . '</body>', $template);
304
305 print($template);
306 }
307
308 // ###################################################################
309 /**
310 * Loads an additional template from the database
311 *
312 * @access private
313 *
314 * @param string The name of the template
315 *
316 * @return string Template data from the database
317 */
318 function _load($name)
319 {
320 if ($template = $this->registry->modules[ISSO_DB_LAYER]->query_first("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " = '$name'" . ($this->extrawhere ? ' ' . $this->extrawhere : '')))
321 {
322 return $template[ $this->datacolumn ];
323 }
324 else
325 {
326 trigger_error("The template '$name' could not be loaded", E_USER_ERROR);
327 exit;
328 }
329 }
330
331 // ###################################################################
332 /**
333 * A wrapper for all the parsing functions and compiling functins
334 *
335 * @access protected
336 *
337 * @param string Unparsed template data
338 *
339 * @return string Parsed template data
340 */
341 function _parse($template)
342 {
343 $this->registry->check_isso_fields(get_class($this));
344
345 $template = str_replace('"', '\"', $template);
346
347 if (function_exists($this->pre_parse_hook))
348 {
349 $template = call_user_func($this->pre_parse_hook, $template);
350 }
351
352 $template = $this->_parse_phrases($template);
353 $template = $this->_parse_conditionals($template);
354 return $template;
355 }
356
357 // ###################################################################
358 /**
359 * Prepares language and locale information inside templates
360 *
361 * @access private
362 *
363 * @param string Template data to be processed
364 *
365 * @return string Language-ready template data
366 */
367 function _parse_phrases($template)
368 {
369 $tag_start = '<lang ';
370 $tag_start_end = '\">';
371 $tag_end = '</lang>';
372
373 $location_start = -1;
374 $location_end = -1;
375
376 while (1)
377 {
378 // Find the start language object tag
379 $location_start = strpos($template, $tag_start, $location_end + 1);
380 if ($location_start === false)
381 {
382 break;
383 }
384
385 // Find the end tag
386 $location_end = strpos($template, $tag_end, $location_end + strlen($tag_end));
387 if ($location_end === false)
388 {
389 break;
390 }
391
392 // Extract the language object
393 $phrase_bunch = substr($template, $location_start, ($location_end + strlen($tag_end)) - $location_start);
394
395 // Find the close to the opening <lang>
396 $close_of_open = strpos($phrase_bunch, $tag_start_end);
397 if ($close_of_open === false)
398 {
399 break;
400 }
401
402 // Extract the opening tag so it can be parsed
403 $init_tag = substr($phrase_bunch, 0, ($close_of_open + strlen($tag_start_end)));
404 $init_tag = str_replace($tag_start, '', $init_tag);
405 $init_tag = substr($init_tag, 0, strlen($init_tag) - 1);
406
407 // Get the args out of the tag
408 $args = preg_split('#([0-9].*?)=#', $init_tag);
409 foreach ($args AS $arg)
410 {
411 if ($arg AND $arg != ' ')
412 {
413 $arg = trim($arg);
414 $arg = substr($arg, 2);
415 $arg = substr($arg, 0, strlen($arg) - 2);
416 $arglist[] = $arg;
417 }
418 }
419
420 // Just get the phrase name
421 $phrase_name = preg_replace('#<lang(.*?)>(.*?)</lang>#i', '$2', $phrase_bunch);
422
423 // Wrap the parsed data into the build function
424 $function_wrap = '" . ' . $this->langconst . '("' . /*str_replace(array('\"', "'"), array('"', "\'"),*/ $phrase_name/*)*/ . '", "' . implode('", "', $arglist) . '") . "';
425
426 // Replace the fully-parsed string back into the template
427 $template = substr_replace($template, $function_wrap, $location_start, $location_end + strlen($tag_end) - $location_start);
428
429 unset($arglist);
430 }
431
432 // Process the empty phrase objects -- do this now so we don't have to worry about it when we're parsing later
433 $template = preg_replace('#\{@\\\"(.*?)\\\"\}#ise', '$this->_phrase_string(\'$1\')', $template);
434
435 return $template;
436 }
437
438 // ###################################################################
439 /**
440 * Turns a localized phrase tag into a function call
441 *
442 * @access private
443 *
444 * @param string Phrase text
445 *
446 * @return string Function call for phrase text
447 */
448 function _phrase_string($text)
449 {
450 return '" . ' . $this->langcall . '(\'' . str_replace(array('\\\"', "'"), array('"', "\'"), $text) . '\') . "';
451 }
452
453 // ###################################################################
454 /**
455 * Parser for in-line template conditionals
456 *
457 * @access private
458 *
459 * @param string Template data awaiting processing
460 *
461 * @return string Parsed template data
462 */
463 function _parse_conditionals($template)
464 {
465 // tag data
466 $tag_start = '<if condition=\"';
467 $tag_start_end = '\">';
468 $tag_else = '<else />';
469 $tag_end = '</if>';
470
471 // tag stack
472 $stack = array();
473
474 // the information about the current active tag
475 $tag_full = array();
476 $parsed = array();
477
478 // start at 0
479 $offset = 0;
480
481 while (1)
482 {
483 if (strpos($template, $tag_start) === false)
484 {
485 break;
486 }
487
488 for ($i = $offset; $i < strlen($template); $i++)
489 {
490 // we've found ourselves a conditional!
491 if (substr($template, $i, strlen($tag_start)) == $tag_start)
492 {
493 // push the position into the tag stack
494 if ($tag_full)
495 {
496 array_push($stack, $i);
497 }
498 else
499 {
500 $tag_full['posi'] = $i;
501 }
502 }
503 // locate else tags
504 else if (substr($template, $i, strlen($tag_else)) == $tag_else)
505 {
506 if (sizeof($stack) == 0 AND !isset($tag_full['else']))
507 {
508 $tag_full['else'] = $i;
509 }
510 }
511 // do we have an end tag?
512 else if (substr($template, $i, strlen($tag_end)) == $tag_end)
513 {
514 if (sizeof($stack) != 0)
515 {
516 array_pop($stack);
517 continue;
518 }
519
520 // calculate the position of the end tag
521 $tag_full['posf'] = $i + strlen($tag_end) - 1;
522
523 // extract the entire conditional from the template
524 $fullspread = substr($template, $tag_full['posi'], $tag_full['posf'] - $tag_full['posi'] + 1);
525
526 // remove the beginning tag
527 $conditional = substr($fullspread, strlen($tag_start));
528
529 // find the end of the expression
530 $temp_end = strpos($conditional, $tag_start_end);
531
532 // save the expression
533 $parsed[0] = stripslashes(substr($conditional, 0, $temp_end));
534
535 // remove the expression from the conditional
536 $conditional = substr($conditional, strlen($parsed[0]) + strlen($tag_start_end));
537
538 // remove the tailing end tag
539 $conditional = substr($conditional, 0, strlen($conditional) - strlen($tag_end));
540
541 // handle the else
542 if (isset($tag_full['else']))
543 {
544 // now relative to the start of the <if>
545 $relpos = $tag_full['else'] - $tag_full['posi'];
546
547 // calculate the length of the expression and opening tag
548 $length = strlen($parsed[0]) + strlen($tag_start) + strlen($tag_start_end);
549
550 // relative to the start of iftrue
551 $elsepos = $relpos - $length;
552
553 $parsed[1] = substr($conditional, 0, $elsepos);
554 $parsed[2] = substr($conditional, $elsepos + strlen($tag_else));
555 }
556 // no else to handle
557 else
558 {
559 $parsed[1] = $conditional;
560 $parsed[2] = '';
561 }
562 #var_dump($parsed);
563
564 // final parsed output
565 $parsed = '" . ((' . stripslashes($parsed[0]) . ') ? "' . $parsed[1] . '" : "' . $parsed[2] . '") . "';
566
567 // replace the conditional
568 $template = str_replace($fullspread, $parsed, $template);
569
570 // reset the parser
571 $offset = $tag_full['posi'] + strlen($tag_start) + strlen($tag_start_end);
572 $tag_full = array();
573 $stack = array();
574 $parsed = array();
575 unset($fullspread, $conditional, $temp_end, $relpos, $length, $elsepos);
576 break;
577 }
578 }
579 }
580
581 return $template;
582 }
583 }
584
585 // ###################################################################
586 /**
587 * Debugging function used to print characters in a string that are
588 * around a certain position.
589 *
590 * @access private
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 ?>