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