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