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