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