3 # Copyright (C) 2008,2009 Joshua Grams <josh@qualdan.com>
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 # This is a simple template-handling system. You pass it a big data
20 # structure with key/value pairs, and a template string to fill out.
22 # Within a template, it recognizes tags of the form ~name [arg...]~,
23 # optionally wrapped in HTML comments (which will be removed along with
24 # the tag markers when the template is filled out).
26 # { and } as the final argument mark those tags as being the start and
27 # end of a sub-template (for optional or repeated sections). All other
28 # tags represent slots to be directly filled by data values. On a }
29 # tag, the name is optional, but must match the corresponding { tag if
32 # For a value tag, arguments represent encodings to be applied
33 # successively. For instance, ~foo html~ will encode it to be safe in
34 # HTML ('&' to '&', '<' to '<', and so on).
36 # { tags can take one argument, which will call the corresponding
37 # tem_auto_* function to munge the data, automating certain common use
38 # cases. See the comments on the tem_auto functions for more details.
40 require_once('code/wfpl/encode.php');
41 require_once('code/wfpl/file.php');
42 require_once('code/wfpl/misc.php');
48 function template($template, $data) {
49 return fill_template(parse_template($template), $data);
52 function template_file($filename, $data) {
53 return fill_template(parse_template_file($filename), $data);
56 function parse_template_file($filename) {
57 return parse_template(file_get_contents($filename));
60 # We parse the template string into a tree of strings and sub-templates.
61 # A template is a hash with a name string, a pieces array, and possibly
64 function parse_template($string) {
66 $tem['pieces'] = array();
67 # note: for some reason this captures '<!--' but not '-->'.
68 $matches = preg_split("/(<!--)?(~[^~]*~)(?(1)-->)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
69 foreach($matches as $match) {
70 if($match == '~~') $match = '~';
71 if(substr($match,0,1) == '~' and strlen($match) > 2) {
72 $args = explode(' ', substr($match,1,-1));
74 if(count($args) == 1 and $args[0] == '}') $name = '';
75 else $name = array_shift($args);
77 if(last($args) == '{') { # open block
78 array_pop($args); # drop '{'
79 $tem =& tem_push($tem); # create a new sub-template
80 $tem['parent']['pieces'][] =& $tem; # as a piece of the parent
82 $tem['pieces'] = array();
84 } elseif(last($args) == '}') { # close block
85 array_pop($args); # drop '}'
87 if($name && $name != $cur) {
88 die("Invalid template: tried to close '$name', but '$cur' is current.");
90 $tem =& $tem['parent'];
92 $tem['pieces'][] = array('name' => $name, 'args' => $args);
94 } elseif($match and $match != '<!--') { # static string
95 $tem['pieces'][] = $match;
101 function fill_template($template, &$data, &$context = NULL) {
102 $context =& tem_push($context);
103 $context['data'] =& $data;
105 foreach($template['pieces'] as $tem) {
106 if(is_string($tem)) $output .= $tem;
107 elseif($tem['pieces']) { # sub-template
108 $rows =& tem_row_data($tem, $context);
109 $context['rows'] =& $rows;
110 foreach($rows as $key => &$row) {
111 $context['cur'] = $key;
112 $output .= fill_template($tem, $row, $context);
115 $output .= tem_encoded_data($tem, $context);
118 $context =& $context['parent'];
127 # To track our position in the template and in the data, we use a linked
128 # stack structure. Each node is a hash with a reference to the parent
129 # node along with whatever other data you want to add. For each stack,
130 # you simply keep a variable with a reference to the top element. Then
131 # the push and pop operations are:
133 # $top =& tem_push($top);
134 # $top =& $top['parent'];
136 function &tem_push(&$stack = NULL) {
137 static $refs = array();
139 # Since a PHP reference is *not* a pointer to data, but a pointer to
140 # a variable (or array slot), we *have* to first put the new node in
141 # $refs, and then reference it from $new.
144 $new =& $refs[count($refs)-1];
145 if($stack) $new['parent'] =& $stack;
149 # To fill out a template, we do a depth-first traversal of the template
150 # tree, replacing all tags with the data values.
152 # The data starts out as a nested set of key/value pairs, where the
155 # a string to fill a value slot
156 # a hash to fill one instance of a sub-template
157 # an array of hashes to fill multiple instances of a sub-template
159 # The middle form will be converted to the last form as we use it.
161 function tem_data_as_rows($value) {
162 if(is_array($value)) {
163 # numeric keys, is already array of arrays -- expand sub-template for each.
164 if(array_key_exists(0, $value)) return $value;
165 # key/value pairs -- expand sub-template once.
166 else return array($value);
168 # value -- expand sub-template once using only parent values
169 return array(array());
171 # empty value -- don't expand sub-template
176 # To look up a key, we check each namespace (starting with the
177 # innermost one) until a value is found.
179 function tem_data_scope($key, $context) {
180 static $refs = array();
184 if(array_key_exists($key, $scope['data'])) {
187 } while($scope = $scope['parent']);
189 # not found; return empty scope.
192 $ret['parent'] =& $context;
193 $ret['data'] =& last($refs);
197 function tem_get_data($key, $context) {
198 $scope = tem_data_scope($key, $context);
199 if($scope) return $scope['data'][$key];
202 # Return the value for a tag as a set of rows to fill a sub-template.
203 # If $tag has an arg, call the tem_auto function to munge the data.
204 function &tem_row_data($tem, $context)
207 $scope = tem_data_scope($key, $context);
209 if(count($tem['args'])) {
210 $auto_func = "tem_auto_" . $tem['args'][0];
211 function_exists($auto_func)
212 or die("ERROR: template auto function '$auto_func' not found.<br>\n");
214 if($auto_func) $value = $auto_func($scope['data'][$key], $key, $scope);
215 else $value = $scope['data'][$key];
217 $rows = tem_data_as_rows($value);
218 if(is_array($value)) $scope['data'][$key] = $rows;
223 # Return the value for a tag as an encoded string.
224 function tem_encoded_data($tag, $context)
227 $value = tem_get_data($key, $context);
228 foreach($tag['args'] as $encoding) {
229 $func = "enc_$encoding";
230 if(function_exists($func)) $value = $func($value, $key);
231 else die("ERROR: encoder function '$func' not found.<br>\n");
238 # Return a hash containing the top-level sub-templates of tem.
239 function top_sub_templates($tem) {
241 foreach($tem['pieces'] as $piece) {
242 if(is_array($piece) and $piece['pieces']) {
243 $subs[$piece['name']] = $piece;
249 # Replace top-level values in $main with top-level templates from $tem.
250 function merge_templates($main, $tem) {
251 $out = array('name' => $main['name'], 'pieces' => array());
253 $subs = top_sub_templates($tem);
255 foreach($main['pieces'] as $piece) {
256 $sub = $subs[$piece['name']];
257 if(is_array($piece) and !$piece['pieces'] and $sub and $sub['args'][0] != 'hide') {
258 $piece = $subs[$piece['name']];
260 $out['pieces'][] = $piece;
270 # If a { tag has an argument, the corresponding tem_auto function is called.
271 # This allows it to mangle the data to automate some common cases.
273 # 'sep' (separator) sections will be shown for all but the last parent row.
278 # <!--~separator sep {~--><hr><!--~}"-->
282 function tem_auto_sep(&$value, $key, $context) {
283 $rows =& $context['parent']['parent'];
284 if($rows['cur'] != count($rows['rows'])-1) # last row?
285 return $value = true; # show once
288 # 'show' sections will be shown unless the corresponding data value
289 # is false. We check only for false; 0 or '' will not work.
291 function tem_auto_show(&$value) {
292 if($value !== false) $value = array(array());
296 # 'evenodd' sections are given an 'evenodd' attribute whose value
297 # alternates between 'even' and 'odd'.
299 function tem_auto_evenodd(&$values) {
301 foreach($values as &$value) {
302 $value['evenodd'] = $even ? 'even' : 'odd';
312 # Backward Compatibility
313 # ----------------------
315 # Old-style templates don't show unless explicitly requested.
316 function tem_auto_hide(&$value, $key, $context) {
317 unset($context['data'][$key]);
321 # The old API is being used with the named sub-template,
322 # so hide it and insert a value slot for its expansion(s).
323 function &tem_is_old_sub($name, &$template) {
324 foreach($template['pieces'] as $key => &$piece) {
325 if(is_array($piece) and $piece['pieces']) {
326 if($piece['name'] == $name) {
327 if($piece['args'][0] != 'hide') { # if we haven't already
328 $piece['args'] = array('hide');
329 $var = array('name' => $name, 'args' => array());
330 array_splice($template['pieces'], $key, 0, array($var));
334 $tem = tem_is_old_sub($name, $piece);
335 if($tem) return $tem;
345 $this->template = array();
346 $this->data = array();
349 function set($key, $value) {
350 $this->data[$key] = $value;
353 function append($key, $value) {
354 $this->data[$key] .= $value;
357 function prepend($key, $value) {
358 $this->data[$key] = $value . $this->data[$key];
361 function clear($key) {
362 unset($this->data[$key]);
366 return $this->data[$key];
369 function show($name) {
370 $tem = tem_is_old_sub($name, $this->template);
371 $this->data[$name] .= fill_template($tem, $this->data);
374 function show_separated($name) {
375 if($this->get($name)) {
376 $this->show($name . '_sep');
381 function load_str($str) {
382 $this->template = parse_template($str);
385 function load($filename) {
386 $this->template = parse_template_file($filename);
389 function run($tem = false) {
391 if(strlen($tem < 150 && file_exists($tem))) $this->load($tem);
392 else $this->load_str($tem);
395 return fill_template($this->template, $this->data);
398 function output($tem = false) {
399 print($this->run($tem));
402 # merge top-level sub-templates of $tem (object) into $this,
403 # supporting both new and old semantics.
404 function merge($tem) {
405 # append expansions to $this->data (old style)
406 $subs = $tem->top_subs();
407 if($subs) foreach($subs as $name => $val) {
408 $this->append($name, $val);
409 unset($tem->data[$name]); # so array_merge() won't overwrite things
412 # merge the data arrays and template trees (new style)
413 $this->data = array_merge($this->data, $tem->data);
414 $this->template = merge_templates($this->template, $tem->template);
417 function top_sub_names() {
418 return array_keys(top_sub_templates($this->template));
421 function top_subs() {
423 $names = $this->top_sub_names();
424 foreach($names as $name) {
425 $ret[$name] = $this->get($name);
430 # old name for show (deprecated)
431 function sub($name) {
436 function tem_init() {
437 if(!$GLOBALS['wfpl_template']) {
438 $GLOBALS['wfpl_template'] = new tem();
442 function tem_append($key, $value) {
444 $GLOBALS['wfpl_template']->append($key, $value);
447 function tem_prepend($key, $value) {
449 $GLOBALS['wfpl_template']->prepend($key, $value);
452 function tem_set($key, $value) {
454 $GLOBALS['wfpl_template']->set($key, $value);
457 function tem_get($key) {
459 return $GLOBALS['wfpl_template']->get($key);
462 function tem_run($tem = false) {
464 return $GLOBALS['wfpl_template']->run($tem);
467 function tem_show($name) {
469 return $GLOBALS['wfpl_template']->show($name);
472 function tem_show_separated($name) {
474 $GLOBALS['wfpl_template']->show_separated($name);
477 function tem_load($filename) {
479 $GLOBALS['wfpl_template']->load($filename);
482 function tem_output($filename = false) {
484 $GLOBALS['wfpl_template']->output($filename);
487 function tem_top_subs() {
489 return $GLOBALS['wfpl_template']->top_subs();
492 function tem_top_sub_names() {
494 return $GLOBALS['wfpl_template']->top_sub_names();
497 function tem_load_new($filename) {
498 $old = $GLOBALS['wfpl_template'];
499 $GLOBALS['wfpl_template'] = new tem();
500 $GLOBALS['wfpl_template']->load($filename);
504 # deprecated (old name for show)
505 function tem_sub($name) {