Removed iff() from use in ISSO. Placed notice on the function to state that it's...
[isso.git] / template.php
1 <?php
2 /*=====================================================================*\
3 || ################################################################### ||
4 || # Iris Studios Shared Object Framework [#]version[#]
5 || # --------------------------------------------------------------- # ||
6 || # All parts of this file are ©2003-[#]year[#] Iris Studios, Inc. No # ||
7 || # part of this file may be reproduced in any way: part or whole. # ||
8 || # --------------------------------------------------------------- # ||
9 || # ©2003 - [#]year[#] Iris Studios, Inc. | http://www.iris-studios.com # ||
10 || ################################################################### ||
11 \*=====================================================================*/
12
13 $OBJECT = 'Database Template System';
14 $CLASS = 'DB_Template';
15 $OBJ = 'template';
16
17 /**
18 * Database-Driven Template System
19 *
20 * This framework is a backend to the database template engine and
21 * contains all the parsing algorithms.
22 *
23 * @author Iris Studios, Inc.
24 * @copyright Copyright ©2003 - [#]year[#], Iris Studios, Inc.
25 * @version $Revision$
26 *
27 */
28 class DB_Template
29 {
30 /**
31 * Global environment variables
32 *
33 * This stores all of the cached and parsed template data
34 *
35 * @var tablename The name of the database table templates are in
36 * @var namecolumn The name of the database column template names are in
37 * @var datacolumn The name of the database column template data is stored in
38 * @var extrawhere Additional information for the WHERE clause in template loading
39 * @var langcall Function wrapper for phrase fetching system
40 * @var langconst Function that constructs a phrase with sprintf()
41 * @var cache Stores all fettched templates
42 * @var usage Counter for template usage
43 * @var uncached List of uncached templates
44 * @var doneflush Variable to check and see if output has been sent
45 */
46 var $templatetable = '';
47 var $namecolumn = '';
48 var $datacolumn = '';
49 var $extrawhere = '';
50 var $langcall = 'fetch_phrase';
51 var $langconst = 'construct_phrase';
52 var $cache = array();
53 var $usage = array();
54 var $uncached = array();
55 var $doneflush = false;
56
57 /**
58 * Takes an array of template names, loads them, and then stores
59 * a parsed version for optimum speed.
60 *
61 * @var array List of template names to be cached
62 */
63 function cache($namearray)
64 {
65 global $_isso;
66
67 if (sizeof($this->cache) > 0)
68 {
69 trigger_error('You cannot cache templates more than once per initialization', ERR_WARNING);
70 }
71 else
72 {
73 $templates = $_isso->db->query("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " IN ('" . implode("', '", $namearray) . "')" . (($this->extrawhere) ? $this->extrawhere : ''));
74 while ($template = $_isso->db->fetch_array($templates))
75 {
76 $template = $this->_parse($template);
77 $this->cache[ $template[ $this->namecolumn ] ] = $template[ $this->datacolumn ];
78 $this->usage["$name"] = 0;
79 }
80 }
81 }
82
83 /**
84 * Loads a template from the cache or the _load function and
85 * stores the parsed version of it
86 *
87 * @param str The name of the template
88 *
89 * @return str A parsed and loaded template
90 */
91 function fetch($name)
92 {
93 global $_isso;
94
95 if (isset($this->cache["$name"]))
96 {
97 $template = $this->cache["$name"];
98 }
99 else
100 {
101 $this->uncached[] = $name;
102 $_isso->debug("Manually loading template `$name`");
103 $template = $this->_load($name);
104 $template = $this->_parse($template);
105 }
106
107 if (!isset($this->usage["$name"]))
108 {
109 $this->usage["$name"] = 0;
110 }
111
112 $this->usage["$name"]++;
113
114 return $template;
115 }
116
117 /**
118 * Output a template fully compiled to the browser
119 *
120 * @param str Compiled and ready template
121 */
122 function flush($template)
123 {
124 global $_isso;
125
126 ob_start();
127
128 if (empty($template))
129 {
130 trigger_error('There was no output to print', ERR_FATAL);
131 exit;
132 }
133
134 if ($_isso->debug AND isset($_GET['query']))
135 {
136 if (is_array($_isso->db->history))
137 {
138 echo '<pre>';
139 foreach ($_isso->db->history AS $query)
140 {
141 echo $query . "\n\n<hr />\n\n";
142 }
143 echo '</pre>';
144 }
145 exit;
146 }
147
148 if ($this->doneflush)
149 {
150 trigger_error('A template has already been sent to the output buffer', ERR_FATAL);
151 exit;
152 }
153
154 if ($_isso->debug)
155 {
156 // --- START
157 $debug = "\n<ul>";
158
159 // templates
160 $optlist = array();
161 $usage = array();
162 foreach ($this->usage AS $name => $count)
163 {
164 if (in_array($name, $this->uncached))
165 {
166 $optlist[] = $name . '[' . $count . ']';
167 }
168 $usage[] = $name . " ($count)";
169 }
170
171 $sizeof = sizeof($this->uncached);
172 if ($sizeof > 0)
173 {
174 $debug .= "\n\t<li><strong style=\"color: red\">Uncached Template(s):</strong> $sizeof ( " . implode(' &nbsp; ', $optlist) . " )</li>";
175 }
176
177 // source control
178 $scinfo = 'Not Under Source Control';
179 $possiblescms = array('cvs', 'svn', 'cvs_information', 'svn_information', 'scm', 'sc_information', 'scm_information');
180 foreach ($possiblescms AS $scm)
181 {
182 if (defined(strtoupper($scm)))
183 {
184 $scinfo = constant(strtoupper($scm));
185
186 $type = '';
187 // CVS
188 if (strpos($scinfo, 'RCSfile:') !== false)
189 {
190 $type = 'cvs';
191 }
192 else if (strpos($scinfo, ',v ') !== false)
193 {
194 $type = 'cvs';
195 }
196 // SVN
197 else if (strpos($scinfo, 'URL:') !== false)
198 {
199 $type = 'svn';
200 }
201 else if (strpos($scinfo, 'https://') !== false OR strpos($scinfo, 'http://') !== false)
202 {
203 $type= 'svn';
204 }
205 // not found so just return it
206 // try a SVN ID tag as we can't really tell if we're using it
207 else
208 {
209 $test = preg_replace('#\$' . 'Id: (.+?) (.+?) [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(.+?) (.+?) \$#', '\\1 - SVN \\2', $scinfo);
210 if ($test == '$' . 'Id: $')
211 {
212 $scinfo = 'Not Under Source Control';
213 }
214 else
215 {
216 $scinfo = $test;
217 }
218 break;
219 }
220
221 if ($type == 'cvs')
222 {
223 $scinfo = preg_replace('#\$' . 'RCSfile: (.+?) \$#', '\\1', $scinfo);
224 $scinfo = preg_replace('#\$' . 'Revision: (.+?) \$#', 'CVS \\1', $scinfo);
225 $scinfo = preg_replace('#\$' . 'Id: (.+?) (.+?) [0-9]{4}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} (.+?) (.+?) \$#', '\\1 - CVS \\2', $scinfo);
226 }
227 else if ($type == 'svn')
228 {
229 $scinfo = preg_replace('#\$' . '(Head)?URL: (.+?) \$#e', "end(explode('/', '\\2'))", $scinfo);
230 $scinfo = preg_replace('#\$' . '(LastModified)?Revision: (.+?) \$#', 'SVN \\2', $scinfo);
231 $scinfo = preg_replace('#\$' . 'Id: (.+?) ([0-9].+?) [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(.+?) (.+?) \$#', '\\1 - SVN \\2', $scinfo);
232 }
233 else
234 {
235 $scinfo = 'Not Under Source Control';
236 }
237 break;
238 }
239 }
240 $scinfo = trim($scinfo);
241 $debug .= "\n\t<li><strong>Source Control:</strong> $scinfo</li>";
242
243 // query information
244 $debug .= "\n\t<li><strong>Total Queries:</strong> " . sizeof($_isso->db->history) . " (<a href=\"" . $_isso->sanitize($_SERVER['REQUEST_URI']) . ((strpos($_SERVER['REQUEST_URI'], '?') !== false) ? '&amp;query=1' : '?query=1') . "\">?<a/>)</li>";
245
246 // debug notices
247 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Debug Notices (" . sizeof($_isso->debuginfo) . ")</option>";
248 foreach ((array)$_isso->debuginfo AS $msg)
249 {
250 $debug .= "\n\t\t\t<option>--- $msg</option>";
251 }
252 $debug .= "\n\t\t</select>\n\t</li>";
253
254 // loaded modules
255 $modules = $_isso->show_modules(true);
256 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Loaded Modules (" . sizeof($modules) . ")</option>";
257 foreach ($modules AS $mod)
258 {
259 $debug .= "\n\t\t\t<option>--- $mod</option>";
260 }
261 $debug .= "\n\t\t</select>\n\t</li>";
262
263 // template usage
264 $debug .= "\n\t<li>\n\t\t<select>\n\t\t\t<option>Template Usage (" . array_sum($this->usage) . ")</option>";
265 foreach ($usage AS $tpl)
266 {
267 $debug .= "\n\t\t\t<option>--- $tpl</option>";
268 }
269 $debug .= "\n\t\t</select>\n\t</li>";
270
271 // --- END
272 $debug .= "\n</ul>";
273
274 $debug = "\n<hr />\n" . $_isso->_message('Debug Information', $debug, 1, true);
275 $template = str_replace('</body>', "\n\n<!-- dev debug -->\n<div align=\"center\">\n$debug\n</div>\n<!-- / dev debug -->\n\n</body>", $template);
276 }
277
278 print(stripslashes($template));
279 }
280
281 /**
282 * Loads an additional template from the database
283 *
284 * @param str The name of the template
285 *
286 * @return str Template data from the database
287 */
288 function _load($name)
289 {
290 global $_isso;
291 if ($template = $_isso->db->query("SELECT * FROM " . $this->tablename . " WHERE " . $this->namecolumn . " = '$name'" . (($this->extrawhere) ? $this->extrawhere : '')))
292 {
293 return $template[ $this->datacolumn ];
294 }
295 else
296 {
297 trigger_error("The template '$name' could not be loaded", ERR_FATAL);
298 exit;
299 }
300 }
301
302 /**
303 * A wrapper for all the parsing functions and compiling functins
304 *
305 * @param str Unparsed template data
306 *
307 * @return str Parsed template data
308 */
309 function _parse($template)
310 {
311 $template = stripslashes($template);
312 $template = str_replace('"', '\"', $template);
313 $template = $this->_parse_phrases($template);
314 $template = $this->_parse_conditionals($template);
315 return $template;
316 }
317
318 /**
319 * Prepares language and locale information inside templates
320 *
321 * @param str Template data to be processed
322 *
323 * @return str Language-ready template data
324 */
325 function _parse_phrases($template)
326 {
327 $tag_start = '<lang ';
328 $tag_start_end = '">';
329 $tag_end = '</lang>';
330
331 $location_start = -1;
332 $location_end = -1;
333
334 // Process the empty phrase objects -- do this now so we don't have to worry about it when we're parsing later
335 $template = preg_replace('#\{lang\.(.*?)\}#i', '" . ' . $this->langcall . '(\'$1\') . "', $template);
336
337 while (1)
338 {
339 // Find the start language object tag
340 $location_start = strpos($template, $tag_start, $location_end + 1);
341 if ($location_start === false)
342 {
343 break;
344 }
345
346 // Find the end tag
347 $location_end = strpos($template, $tag_end, $location_end + strlen($tag_end));
348 if ($location_end === false)
349 {
350 break;
351 }
352
353 // Extract the language object
354 $phrase_bunch = substr($template, $location_start, ($location_end + strlen($tag_end)) - $location_start);
355
356 // Find the close to the opening <lang>
357 $close_of_open = strpos($phrase_bunch, $tag_start_end);
358 if ($close_of_open === false)
359 {
360 break;
361 }
362
363 // Extract the opening tag so it can be parsed
364 $init_tag = substr($phrase_bunch, 0, ($close_of_open + strlen($tag_start_end)));
365 $init_tag = str_replace($tag_start, '', $init_tag);
366 $init_tag = substr($init_tag, 0, strlen($init_tag) - 1);
367
368 // Get the args out of the tag
369 $args = preg_split('#([0-9].*?)=#', $init_tag);
370 foreach ($args AS $arg)
371 {
372 if ($arg AND $arg != ' ')
373 {
374 $arg = trim($arg);
375 $arg = substr($arg, 2);
376 $arg = substr($arg, 0, strlen($arg) - 2);
377 $arglist[] = $arg;
378 }
379 }
380
381 // Just get the phrase name
382 $phrase_name = preg_replace('#<lang(.*?)>(.*?)</lang>#i', '$2', $phrase_bunch);
383
384 // Wrap the parsed data into the build function
385 $function_wrap = '" . ' . $this->langconst . '(\'' . $phrase_name . '\', "' . implode('", "', $arglist) . '") . "';
386
387 // Replace the fully-parsed string back into the template
388 $template = substr_replace($template, $function_wrap, $location_start, $location_end + strlen($tag_end) - $location_start);
389
390 unset($arglist);
391 }
392
393 return $template;
394 }
395
396 /**
397 * Parser for in-line template conditionals
398 *
399 * @param str Template data awaiting processing
400 *
401 * @return str Parsed template data
402 */
403 function _parse_conditionals($template)
404 {
405 global $_isso;
406
407 // tag data
408 $tag_start = '<if condition=\"';
409 $tag_start_end = '\">';
410 $tag_else = '<else />';
411 $tag_end = '</if>';
412
413 // tag stack
414 $stack = array();
415 $parsed = array();
416
417 for ($i = 0; $i < strlen($template); $i++)
418 {
419 // we've found ourselves a conditional!
420 if (substr($template, $i, strlen($tag_start)) == $tag_start)
421 {
422 // where do we end the conditional
423 $end = strpos($template, $tag_start_end, $i);
424 $end += strlen($tag_start_end);
425
426 // complete the open
427 array_push($stack, $i);
428
429 //echo "OPEN `$i`: " . print_r($stack, true);
430 }
431 // do we have an end tag?
432 else if (substr($template, $i, strlen($tag_end)) == $tag_end)
433 {
434 // calculate the position of the end tag
435 $end = $i + strlen($tag_end);
436
437 // find the most recently opened condition
438 $last = array_pop($stack);
439
440 // how deep are we nested?
441 $depth = count($stack);
442
443 //echo "CLOSE `$last`: " . print_r($stack, true);
444
445 // get the full conditional
446 $fullspread = substr($template, $last, $end - $last);
447
448 // remove the beginning tag
449 $conditional = substr($fullspread, strlen($tag_start));
450
451 // find the end of the expression
452 $temp_end = strpos($conditional, $tag_start_end);
453
454 // save the expression
455 $expression = stripslashes(substr($conditional, 0, $temp_end));
456
457 // remove the expression from the broken conditional
458 $conditional = substr($conditional, strlen($expression) + strlen($tag_start_end));
459
460 // remove the tailing end tag
461 $conditional = substr($conditional, 0, strlen($conditional) - strlen($tag_end));
462
463 // save all the data for later so we can do a quick replacement
464 $parsed["$depth"]["$last"] = array(
465 'raw' => $fullspread,
466 'parsed' => ''
467 );
468
469 if (substr_count($conditional, $tag_else) == 0)
470 {
471 $parsed["$depth"]["$last"]['parsed'] = '" . ((' . stripslashes($expression) . ') ? "' . $conditional . '" : "") . "';
472 }
473 else
474 {
475 $parsed["$depth"]["$last"]['parsed'] = '" . ((' . stripslashes($expression) . ') ? "' . $conditional . '") . "';
476 }
477 }
478 }
479
480 // sort so the top-most ones are done first
481 ksort($parsed);
482 foreach ($parsed AS $depth => $conditionals)
483 {
484 // sort so we do them in order
485 ksort($conditionals);
486 foreach ($conditionals AS $parsed)
487 {
488 // replace the old with the new
489 $template = str_replace($parsed['raw'], $parsed['parsed'], $template);
490 }
491 }
492 // hackish way to get end tags working
493 $template = str_replace($tag_else, '" : "', $template);
494
495 return $template;
496 }
497 }
498
499 /*=====================================================================*\
500 || ###################################################################
501 || # $HeadURL$
502 || # $Id$
503 || ###################################################################
504 \*=====================================================================*/
505 ?>