2 /*=====================================================================*\
3 || ###################################################################
4 || # Blue Static ISSO Framework
5 || # Copyright ©2002-[#]year[#] Blue Static
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.
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
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 \*=====================================================================*/
23 * Database-Driven Template System (template.php)
29 * Database-Driven Template System
31 * This framework is a backend to the database template engine and
32 * contains all the parsing algorithms.
35 * @copyright Copyright ©2002 - [#]year[#], Blue Static
43 * The database object to use
49 * Name of the database table templates are in
52 private $tableName = '';
55 * Name of the table column template names are in
58 private $nameColumn = '';
61 * Name of the table column templates are in
64 private $dataColumn = '';
67 * Additional WHERE clauses for the template fetch SQL
70 private $extraWhere = '';
73 * The name of the function phrases are fetched with
76 private $langcall = 'gettext';
79 * The name of the function phrases are sprintf() parsed with
82 private $langconst = 'sprintf';
85 * Array of pre-compiled templates that are stored to decrease server load
88 protected $cache = array();
91 * A list of the number of times each template has been used
94 protected $usage = array();
97 * A list of templates that weren't cached, but are still used
100 protected $uncached = array();
103 * Whether or not the page has been flush()'d already
106 private $doneflush = false;
109 * The name of a function that is called before template parsing of phrases and conditionals occurs
112 private $preParseHook = ':undefined:';
114 // ###################################################################
116 * Constructor: check required modules
118 public function __construct()
120 BSRegister
::RequiredModules(array('Db'));
123 // ###################################################################
125 * Sets the database object to use
127 * @param object Database object
129 public function setDatabase($db)
134 // ###################################################################
136 * Sets the table name and column information
138 * @param string The database table name
139 * @param string Name of the column that stores the name of the template
140 * @param string Name of the column that stores template data
142 public function setDatabaseTable($tableName, $nameColumn, $dataColumn)
144 $this->tableName
= $tableName;
145 $this->nameColumn
= $nameColumn;
146 $this->dataColumn
= $dataColumn;
149 // ###################################################################
151 * Sets the pre-parse hook method which is called before any other
152 * processing is done on the template.
154 * @param string Method name
156 public function setPreParseHook($hook)
158 $this->preParseHook
= $hook;
161 // ###################################################################
163 * Takes an array of template names, loads them, and then stores a
164 * parsed version for optimum speed.
166 * @param array List of template names to be cached
168 public function cache($namearray)
170 if (sizeof($this->cache
) > 0)
172 trigger_error('You cannot cache templates more than once per initialization');
176 $templates = $this->db
->query("SELECT * FROM " . $this->tableName
. " WHERE " . $this->nameColumn
. " IN ('" . implode("', '", $namearray) . "')" . ($this->extrawhere
? ' ' . $this->extrawhere
: ''));
177 while ($template = $this->db
->fetch_array($templates))
179 $this->cache
[ $template[ $this->nameColumn
] ] = $this->_parse($template[ $this->dataColumn
]);
180 $this->usage
[ $template[ $this->nameColumn
] ] = 0;
185 // ###################################################################
187 * Loads a template from the cache or the _load function and stores the
188 * parsed version of it
190 * @param string The name of the template
192 * @return string A parsed and loaded template
194 public function fetch($name)
196 if (isset($this->cache
["$name"]))
198 $template = $this->cache["$name"];
202 $this->uncached
[] = $name;
203 BSRegister
::Debug("Manually loading template '$name'");
204 $template = $this->_loadTemplate($name);
205 $template = $this->_parseTemplate($template);
208 if (!isset($this->usage["$name"]))
210 $this->usage
["$name"] = 0;
213 $this->usage["$name"]++
;
218 // ###################################################################
220 * Output a template fully compiled to the browser
222 * @param string Compiled and ready template
224 public function flush($template)
228 if (empty($template))
230 trigger_error('There was no output to print');
234 if ($this->doneflush
)
236 trigger_error('A template has already been sent to the output buffer');
241 if (BSRegister
::GetDebug())
243 if (defined('SVN') AND preg_match('#^\$Id:?#', constant('SVN')))
245 $debugBlock .= preg_replace('#\$' . 'Id: (.+?) ([0-9].+?) [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(.+?) (.+?) \$#', "\n<br />\n" . '<div align="center"><strong>\1</strong> — r\2</div>', constant('SVN'));
248 if (defined('ISSO_MT_START'))
250 $debugBlock .= "\n<div align=\"center\">Executed in " . round(BSFunctions
::FetchMicrotimeDiff(ISSO_MT_START
), 10) . ' seconds</div>';
253 $debugBlock .= "\n<br /><div align=\"center\">" . BSRegister
::GetDebugList() . "</div>";
257 foreach ($this->usage
AS $name => $count)
259 if (in_array($name, $this->uncached
))
261 $optlist[] = $name . '[' . $count . ']';
263 $usage[] = $name . " ($count)";
265 $sizeof = sizeof($this->uncached
);
268 $debugBlock .= "<br /><div style=\"color: red\" align=\"center\"><strong>Uncached Template(s):</strong> $sizeof ( " . implode(' ', $optlist) . " )</div>\n";
271 $debugBlock .= (sizeof($this->uncached
) < 1 ? "<br />\n" : '') . "<div align=\"center\"><select><option>Template Usage (" . array_sum($this->usage
) . ")</option>";
272 foreach ($usage AS $tpl)
274 $debugBlock .= "<option>--- $tpl</option>";
276 $debugBlock .= "</select></div>\n";
278 if (BSRegister
::GetType('Db'))
280 $queries = BSRegister
::GetType('Db')->getHistory();
282 $debugBlock .= "<br />\n" . '<table cellpadding="4" cellspacing="1" border="0" align="center" width="30%" style="background-color: rgb(60, 60, 60); color: white">' . "\n\t" . '<tr><td><strong>Query Debug</strong></td></tr>';
284 foreach ($queries AS $query)
286 $debugBlock .= "\n\t<tr style=\"background-color: rgb(230, 230, 230); color: black\">";
287 $debugBlock .= "\n\t\t<td>";
288 $debugBlock .= "\n\t\t\t$query[query]\n\n\t\t\t<div style=\"font-size: 9px;\">($query[time])</div>\n<!--\n$query[trace]\n-->\n\t\t</td>\n\t</tr>";
291 $debugBlock .= "\n</table>\n\n\n";
295 $template = str_replace('</body>', $debugBlock . '</body>', $template);
300 // ###################################################################
302 * Loads an additional template from the database
304 * @param string The name of the template
306 * @return string Template data from the database
308 protected function _loadTemplate($name)
310 if ($template = $this->db
->queryFirst("SELECT * FROM " . $this->tableName
. " WHERE " . $this->nameColumn
. " = '$name'" . ($this->extrawhere ? ' ' . $this->extrawhere : '')))
312 return $template[ $this->dataColumn ];
316 trigger_error("The template
'$name' could not be loaded");
321 // ###################################################################
323 * A wrapper for all the parsing functions and compiling functins
325 * @param string Unparsed template data
327 * @return string Parsed template data
329 protected function _parseTemplate($template)
331 $template = str_replace('"', '\"', $template);
333 if (function_exists($this->preParseHook))
335 $template = call_user_func($this->preParseHook, $template);
338 $template = $this->_parseBlocksAndTokens($template);
339 $template = $this->_parsePhrases($template);
340 $template = $this->_parseConditionals($template);
344 // ###################################################################
346 * Parses anything with curly braces {} (including phrases)
348 * @param string Template data
350 * @return string Parsed template data
352 private function _parseBlocksAndTokens($template)
359 for ($i = 0; $i < strlen($template); $i++)
361 // we've run through the template and there's nothing in the stack--done
362 if ($i == strlen($template) - 1 AND sizeof($stack) == 0)
367 if ($template[$i] == '{')
369 // ignore escaped sequences
370 if ($template[$i - 1] != '\\')
372 array_push($stack, $i);
375 else if ($template[$i] == '}')
377 // there's no stack so it was probably escaped
378 if (sizeof($stack) == 0)
382 // we're good and nested
383 else if (sizeof($stack) == 1)
385 $open = array_pop($stack);
386 $token = substr($template, $open, $i - $open + 1);
387 $template = str_replace($token, $this->_parseToken($token), $template);
400 // ###################################################################
402 * Parses a curly brace token {}
404 * @param string Token
406 * @return string Parsed value
408 private function _parseToken($token)
410 // knock of the braces
411 $token = substr($token, 1, strlen($token) - 2);
414 if ($token[0] == '@' AND $token[1] == '\\' AND $token[2] == '"')
416 return '" . ' . $this->langcall . '(\'' . str_replace(array('\\\"', "'"), array('"', "\'
"), substr($token, 3, strlen($token) - 5)) . '\')' . ' . "';
421 return '" . (' . $token . ') . "';
425 // ###################################################################
427 * Prepares language and locale information inside templates
429 * @param string Template data to be processed
431 * @return string Language-ready template data
433 private function _parsePhrases($template)
435 $tag_start = '<lang
';
436 $tag_start_end = '\"
>';
437 $tag_end = '</lang
>';
439 $location_start = -1;
444 // Find the start language object tag
445 $location_start = strpos($template, $tag_start, $location_end + 1);
446 if ($location_start === false)
452 $location_end = strpos($template, $tag_end, $location_end + strlen($tag_end));
453 if ($location_end === false)
458 // Extract the language object
459 $phrase_bunch = substr($template, $location_start, ($location_end + strlen($tag_end)) - $location_start);
461 // Find the close to the opening <lang>
462 $close_of_open = strpos($phrase_bunch, $tag_start_end);
463 if ($close_of_open === false)
468 // Extract the opening tag so it can be parsed
469 $init_tag = substr($phrase_bunch, 0, ($close_of_open + strlen($tag_start_end)));
470 $init_tag = str_replace($tag_start, '', $init_tag);
471 $init_tag = substr($init_tag, 0, strlen($init_tag) - 1);
473 // Get the args out of the tag
474 $args = preg_split('#([0-9].*?)=#', $init_tag);
475 foreach ($args AS $arg)
477 if ($arg AND $arg != ' ')
480 $arg = substr($arg, 2);
481 $arg = substr($arg, 0, strlen($arg) - 2);
486 // Just get the phrase name
487 $phrase_name = preg_replace('#<lang(.*?)>(.*?)</lang>#i', '$2', $phrase_bunch);
489 // Wrap the parsed data into the build function
490 $function_wrap = '" . ' . $this->langconst . '("' . $phrase_name . '", "' . implode('", "', $arglist) . '") . "';
492 // Replace the fully-parsed string back into the template
493 $template = substr_replace($template, $function_wrap, $location_start, $location_end + strlen($tag_end) - $location_start);
501 // ###################################################################
503 * Parser for in-line template conditionals
505 * @param string Template data awaiting processing
507 * @return string Parsed template data
509 private function _parseConditionals($template)
512 $tag_start = '<if condition
=\"';
513 $tag_start_end = '\"
>';
514 $tag_else = '<else />';
520 // the information about the current active tag
529 if (strpos($template, $tag_start) === false)
534 for ($i = $offset; $i < strlen($template); $i++)
536 // we've found ourselves a conditional
!
537 if (substr($template, $i, strlen($tag_start)) == $tag_start)
539 // push the position into the tag stack
542 array_push($stack, $i);
546 $tag_full['posi'] = $i;
550 else if (substr($template, $i, strlen($tag_else)) == $tag_else)
552 if (sizeof($stack) == 0 AND !isset($tag_full['else']))
554 $tag_full['else'] = $i;
557 // do we have an end tag?
558 else if (substr($template, $i, strlen($tag_end)) == $tag_end)
560 if (sizeof($stack) != 0)
566 // calculate the position of the end tag
567 $tag_full['posf'] = $i +
strlen($tag_end) - 1;
569 // extract the entire conditional from the template
570 $fullspread = substr($template, $tag_full['posi'], $tag_full['posf'] - $tag_full['posi'] +
1);
572 // remove the beginning tag
573 $conditional = substr($fullspread, strlen($tag_start));
575 // find the end of the expression
576 $temp_end = strpos($conditional, $tag_start_end);
578 // save the expression
579 $parsed[0] = stripslashes(substr($conditional, 0, $temp_end));
581 // remove the expression from the conditional
582 $conditional = substr($conditional, strlen($parsed[0]) +
strlen($tag_start_end));
584 // remove the tailing end tag
585 $conditional = substr($conditional, 0, strlen($conditional) - strlen($tag_end));
588 if (isset($tag_full['else']))
590 // now relative to the start of the <if>
591 $relpos = $tag_full['else'] - $tag_full['posi'];
593 // calculate the length of the expression and opening tag
594 $length = strlen($parsed[0]) +
strlen($tag_start) +
strlen($tag_start_end);
596 // relative to the start of iftrue
597 $elsepos = $relpos - $length;
599 $parsed[1] = substr($conditional, 0, $elsepos);
600 $parsed[2] = substr($conditional, $elsepos +
strlen($tag_else));
605 $parsed[1] = $conditional;
609 // final parsed output
610 $parsed = '" . ((' . stripslashes($parsed[0]) . ') ? "' . $parsed[1] . '" : "' . $parsed[2] . '") . "';
612 // replace the conditional
613 $template = str_replace($fullspread, $parsed, $template);
616 $offset = $tag_full['posi'] +
strlen($tag_start) +
strlen($tag_start_end);
620 unset($fullspread, $conditional, $temp_end, $relpos, $length, $elsepos);
630 // ###################################################################
632 * Debugging function used to print characters in a string that are
633 * around a certain position.
637 * @param string The haystack string
638 * @param integer Position to print around
640 function print_around($str, $pos)
642 echo '>>> PA >>>>>>>>[';
643 echo htmlspecialchars($str[ $pos - 5 ]);
644 echo htmlspecialchars($str[ $pos - 4 ]);
645 echo htmlspecialchars($str[ $pos - 3 ]);
646 echo htmlspecialchars($str[ $pos - 2 ]);
647 echo htmlspecialchars($str[ $pos - 1 ]);
649 echo htmlspecialchars($str[ $pos +
0 ]);
650 echo htmlspecialchars($str[ $pos +
1 ]);
651 echo htmlspecialchars($str[ $pos +
2 ]);
652 echo htmlspecialchars($str[ $pos +
3 ]);
653 echo htmlspecialchars($str[ $pos +
4 ]);
654 echo htmlspecialchars($str[ $pos +
5 ]);
655 echo ']<<<<<<<< PA <<<';
658 /*=====================================================================*\
659 || ###################################################################
662 || ###################################################################
663 \*=====================================================================*/