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