Adding check_isso_field() calls all over the place
[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 * @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:null-framework\']->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 * Sets an ISSO field
167 *
168 * @access public
169 *
170 * @param string Field name
171 * @param mixed Value of the field
172 */
173 function set($name, $value)
174 {
175 $this->registry->do_set($name, $value, '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 * @access public
184 *
185 * @param array List of template names to be cached
186 */
187 function cache($namearray)
188 {
189 if (sizeof($this->cache) > 0)
190 {
191 trigger_error('You cannot cache templates more than once per initialization', E_USER_WARNING);
192 }
193 else
194 {
195 $templates = $this->registry->modules[ISSO_DB_LAYER]->query("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " IN ('" . implode("', '", $namearray) . "')" . ($this->extrawhere ? $this->extrawhere : ''));
196 while ($template = $this->registry->modules[ISSO_DB_LAYER]->fetch_array($templates))
197 {
198 $this->cache[ $template[ $this->namecolumn ] ] = $this->_parse($template[ $this->datacolumn ]);
199 $this->usage[ $template[ $this->namecolumn ] ] = 0;
200 }
201 }
202 }
203
204 // ###################################################################
205 /**
206 * Loads a template from the cache or the _load function and stores the
207 * parsed version of it
208 *
209 * @access public
210 *
211 * @param string The name of the template
212 *
213 * @return string A parsed and loaded template
214 */
215 function fetch($name)
216 {
217 if (isset($this->cache["$name"]))
218 {
219 $template = $this->cache["$name"];
220 }
221 else
222 {
223 $this->uncached[] = $name;
224 $this->registry->debug("Manually loading template `$name`");
225 $template = $this->_load($name);
226 $template = $this->_parse($template);
227 }
228
229 if (!isset($this->usage["$name"]))
230 {
231 $this->usage["$name"] = 0;
232 }
233
234 $this->usage["$name"]++;
235
236 return $template;
237 }
238
239 // ###################################################################
240 /**
241 * Output a template fully compiled to the browser
242 *
243 * @access public
244 *
245 * @param string Compiled and ready template
246 */
247 function flush($template)
248 {
249 ob_start();
250
251 if (empty($template))
252 {
253 trigger_error('There was no output to print', E_USER_ERROR);
254 exit;
255 }
256
257 if ($this->registry->debug AND isset($_GET['query']))
258 {
259 if (is_array($this->registry->modules[ISSO_DB_LAYER]->history))
260 {
261 echo '<pre>';
262 foreach ($this->registry->modules[ISSO_DB_LAYER]->history AS $query)
263 {
264 echo $query . "\n\n<hr />\n\n";
265 }
266 echo '</pre>';
267 }
268 exit;
269 }
270
271 if ($this->doneflush)
272 {
273 trigger_error('A template has already been sent to the output buffer', E_USER_ERROR);
274 exit;
275 }
276
277 $template = str_replace('</body>', $this->registry->construct_debug_block(true) . '</body>', $template);
278
279 print($template);
280 }
281
282 // ###################################################################
283 /**
284 * Loads an additional template from the database
285 *
286 * @access private
287 *
288 * @param string The name of the template
289 *
290 * @return string Template data from the database
291 */
292 function _load($name)
293 {
294 if ($template = $this->registry->modules[ISSO_DB_LAYER]->query("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " = '$name'" . ($this->extrawhere ? $this->extrawhere : '')))
295 {
296 return $template[ $this->datacolumn ];
297 }
298 else
299 {
300 trigger_error("The template '$name' could not be loaded", E_USER_ERROR);
301 exit;
302 }
303 }
304
305 // ###################################################################
306 /**
307 * A wrapper for all the parsing functions and compiling functins
308 *
309 * @access protected
310 *
311 * @param string Unparsed template data
312 *
313 * @return string Parsed template data
314 */
315 function _parse($template)
316 {
317 $this->registry->check_isso_fields(get_class($this));
318
319 $template = str_replace('"', '\"', $template);
320
321 if (function_exists($this->pre_parse_hook))
322 {
323 $this->registry->debug("running pre-parse hook: {$this->pre_parse_hook}");
324 $template = call_user_func($this->pre_parse_hook, $template);
325 }
326
327 $template = $this->_parse_phrases($template);
328 $template = $this->_parse_conditionals($template);
329 return $template;
330 }
331
332 // ###################################################################
333 /**
334 * Prepares language and locale information inside templates
335 *
336 * @access private
337 *
338 * @param string Template data to be processed
339 *
340 * @return string Language-ready template data
341 */
342 function _parse_phrases($template)
343 {
344 $tag_start = '<lang ';
345 $tag_start_end = '\">';
346 $tag_end = '</lang>';
347
348 $location_start = -1;
349 $location_end = -1;
350
351 // Process the empty phrase objects -- do this now so we don't have to worry about it when we're parsing later
352 $template = preg_replace('#\{@\\\"(.*?)\\\"\}#ie', '$this->_phrase_string(\'$1\')', $template);
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 return $template;
411 }
412
413 // ###################################################################
414 /**
415 * Turns a localized phrase tag into a function call
416 *
417 * @access private
418 *
419 * @param string Phrase text
420 *
421 * @return string Function call for phrase text
422 */
423 function _phrase_string($text)
424 {
425 return '" . ' . $this->langcall . '(\'' . str_replace(array('\\\"', "'"), array('"', "\'"), $text) . '\') . "';
426 }
427
428 // ###################################################################
429 /**
430 * Parser for in-line template conditionals
431 *
432 * @access private
433 *
434 * @param string Template data awaiting processing
435 *
436 * @return string Parsed template data
437 */
438 function _parse_conditionals($template)
439 {
440 // tag data
441 $tag_start = '<if condition=\"';
442 $tag_start_end = '\">';
443 $tag_else = '<else />';
444 $tag_end = '</if>';
445
446 // tag stack
447 $stack = array();
448
449 // the information about the current active tag
450 $tag_full = array();
451 $parsed = array();
452
453 // start at 0
454 $offset = 0;
455
456 while (1)
457 {
458 if (strpos($template, $tag_start) === false)
459 {
460 break;
461 }
462
463 for ($i = $offset; $i < strlen($template); $i++)
464 {
465 // we've found ourselves a conditional!
466 if (substr($template, $i, strlen($tag_start)) == $tag_start)
467 {
468 // push the position into the tag stack
469 if ($tag_full)
470 {
471 array_push($stack, $i);
472 }
473 else
474 {
475 $tag_full['posi'] = $i;
476 }
477 }
478 // locate else tags
479 else if (substr($template, $i, strlen($tag_else)) == $tag_else)
480 {
481 if (count($stack) == 0 AND !isset($tag_full['else']))
482 {
483 $tag_full['else'] = $i;
484 }
485 }
486 // do we have an end tag?
487 else if (substr($template, $i, strlen($tag_end)) == $tag_end)
488 {
489 if (count($stack) != 0)
490 {
491 array_pop($stack);
492 continue;
493 }
494
495 // calculate the position of the end tag
496 $tag_full['posf'] = $i + strlen($tag_end) - 1;
497
498 // extract the entire conditional from the template
499 $fullspread = substr($template, $tag_full['posi'], $tag_full['posf'] - $tag_full['posi'] + 1);
500
501 // remove the beginning tag
502 $conditional = substr($fullspread, strlen($tag_start));
503
504 // find the end of the expression
505 $temp_end = strpos($conditional, $tag_start_end);
506
507 // save the expression
508 $parsed[0] = stripslashes(substr($conditional, 0, $temp_end));
509
510 // remove the expression from the conditional
511 $conditional = substr($conditional, strlen($parsed[0]) + strlen($tag_start_end));
512
513 // remove the tailing end tag
514 $conditional = substr($conditional, 0, strlen($conditional) - strlen($tag_end));
515
516 // handle the else
517 if (isset($tag_full['else']))
518 {
519 // now relative to the start of the <if>
520 $relpos = $tag_full['else'] - $tag_full['posi'];
521
522 // calculate the length of the expression and opening tag
523 $length = strlen($parsed[0]) + strlen($tag_start) + strlen($tag_start_end);
524
525 // relative to the start of iftrue
526 $elsepos = $relpos - $length;
527
528 $parsed[1] = substr($conditional, 0, $elsepos);
529 $parsed[2] = substr($conditional, $elsepos + strlen($tag_else));
530 }
531 // no else to handle
532 else
533 {
534 $parsed[1] = $conditional;
535 $parsed[2] = '';
536 }
537 #var_dump($parsed);
538
539 // final parsed output
540 $parsed = '" . ((' . stripslashes($parsed[0]) . ') ? "' . $parsed[1] . '" : "' . $parsed[2] . '") . "';
541
542 // replace the conditional
543 $template = str_replace($fullspread, $parsed, $template);
544
545 // reset the parser
546 $offset = $tag_full['posi'] + strlen($tag_start) + strlen($tag_start_end);
547 $tag_full = array();
548 $stack = array();
549 $parsed = array();
550 unset($fullspread, $conditional, $temp_end, $relpos, $length, $elsepos);
551 break;
552 }
553 }
554 }
555
556 return $template;
557 }
558 }
559
560 // ###################################################################
561 /**
562 * Debugging function used to print characters in a string that are
563 * around a certain position.
564 *
565 * @access private
566 *
567 * @param string The haystack string
568 * @param integer Position to print around
569 */
570 function print_around($str, $pos)
571 {
572 echo '>>> PA >>>>>>>>[';
573 echo htmlspecialchars($str[ $pos - 5 ]);
574 echo htmlspecialchars($str[ $pos - 4 ]);
575 echo htmlspecialchars($str[ $pos - 3 ]);
576 echo htmlspecialchars($str[ $pos - 2 ]);
577 echo htmlspecialchars($str[ $pos - 1 ]);
578 echo '©';
579 echo htmlspecialchars($str[ $pos + 0 ]);
580 echo htmlspecialchars($str[ $pos + 1 ]);
581 echo htmlspecialchars($str[ $pos + 2 ]);
582 echo htmlspecialchars($str[ $pos + 3 ]);
583 echo htmlspecialchars($str[ $pos + 4 ]);
584 echo htmlspecialchars($str[ $pos + 5 ]);
585 echo ']<<<<<<<< PA <<<';
586 }
587
588 /*=====================================================================*\
589 || ###################################################################
590 || # $HeadURL$
591 || # $Id$
592 || ###################################################################
593 \*=====================================================================*/
594 ?>