3 # This program is in the public domain within the United States. Additionally,
4 # we waive copyright and related rights in the work worldwide through the CC0
5 # 1.0 Universal public domain dedication, which can be found at
6 # http://creativecommons.org/publicdomain/zero/1.0/
9 # This is a simple template-handling system. You pass it a big data
10 # structure with key/value pairs, and a template string to fill out.
12 # Within a template, it recognizes tags of the form ~name [arg...]~,
13 # optionally wrapped in HTML comments (which will be removed along with
14 # the tag markers when the template is filled out).
16 # { and } as the final argument mark those tags as being the start and
17 # end of a sub-template (for optional or repeated sections). All other
18 # tags represent slots to be directly filled by data values. On a }
19 # tag, the name is optional, but must match the corresponding { tag if
22 # For a value tag, arguments represent encodings to be applied
23 # successively. For instance, ~foo html~ will encode it to be safe in
24 # HTML ('&' to '&', '<' to '<', and so on).
26 # { tags can take one argument, which will call the corresponding
27 # tem_auto_* function to munge the data, automating certain common use
28 # cases. See the comments on the tem_auto functions for more details.
30 require_once(__DIR__.'/'.'encode.php');
31 require_once(__DIR__.'/'.'file.php');
32 require_once(__DIR__.'/'.'misc.php');
38 function template($template, $data) {
39 return fill_template(parse_template($template), $data);
42 function template_file($filename, $data) {
43 return fill_template(parse_template_file($filename), $data);
46 function &parse_template_file($filename) {
47 return parse_template(file_get_contents($filename));
50 # We parse the template string into a tree of strings and sub-templates.
51 # A template is a hash with a name string, a pieces array, and possibly
54 function &parse_template($string) {
56 $tem['pieces'] = array();
57 $matches = preg_split('/(<!--)?(~[^~]*~)(?(1)-->)/', preg_replace('/<!--(~[^~]*~)-->/', '$1', $string), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
58 foreach($matches as $match) {
59 if($match == '~~') $match = '~';
60 if(substr($match,0,1) == '~' and strlen($match) > 2) {
61 $args = explode(' ', substr($match,1,-1));
63 if(count($args) == 1 and $args[0] == '}') $name = '';
64 else $name = array_shift($args);
66 if(count($args) && $args[count($args)-1] == '{') { # open block
67 array_pop($args); # drop '{'
68 $tem =& tem_push($tem); # create a new sub-template
69 $tem['parent']['pieces'][] =& $tem; # as a piece of the parent
71 $tem['pieces'] = array();
73 } elseif(count($args) && $args[count($args)-1] == '}') { # close block
74 array_pop($args); # drop '}'
76 if($name && $name != $cur) {
77 die("Invalid template: tried to close '$name', but '$cur' is current.");
79 $tem =& $tem['parent'];
81 $tem['pieces'][] = array('name' => $name, 'args' => $args);
83 } else { # static string
84 $tem['pieces'][] = $match;
90 function fill_template($template, &$data, &$context = NULL) {
91 $context =& tem_push($context);
92 $context['data'] =& $data;
95 foreach($template['pieces'] as $tem) {
96 if(is_string($tem)) $output .= $tem;
97 elseif(isset($tem['pieces'])) { # sub-template
98 $rows =& tem_row_data($tem, $context);
99 $context['rows'] =& $rows;
100 foreach($rows as $key => &$row) {
101 $context['cur'] = $key;
102 $output .= fill_template($tem, $row, $context);
105 $output .= tem_encoded_data($tem, $context);
108 $context =& $context['parent'];
117 # To track our position in the template and in the data, we use a linked
118 # stack structure. Each node is a hash with a reference to the parent
119 # node along with whatever other data you want to add. For each stack,
120 # you simply keep a variable with a reference to the top element. Then
121 # the push and pop operations are:
123 # $top =& tem_push($top);
124 # $top =& $top['parent'];
126 function &tem_push(&$stack = NULL) {
127 static $refs = array();
129 # Since a PHP reference is *not* a pointer to data, but a pointer to
130 # a variable (or array slot), we *have* to first put the new node in
131 # $refs, and then reference it from $new.
134 $new =& $refs[count($refs)-1];
135 if($stack) $new['parent'] =& $stack;
139 # To fill out a template, we do a depth-first traversal of the template
140 # tree, replacing all tags with the data values.
142 # The data starts out as a nested set of key/value pairs, where the
145 # a string to fill a value slot
146 # a hash to fill one instance of a sub-template
147 # an array of hashes to fill multiple instances of a sub-template
149 # The middle form will be converted to the last form as we use it.
151 function tem_data_as_rows($value, $key) {
152 if(is_array($value)) {
154 if(array_key_exists(0, $value)) {
155 if(is_array($value[0])) return $value; # already array of hashes.
156 else return columnize($value, $key);
157 # key/value pairs -- expand sub-template once.
158 } else return array($value);
159 } elseif($value || $value === 0 || $value === '0' || $value === '') {
160 # value -- expand sub-template once using only parent values
161 return array(array());
163 # empty value -- don't expand sub-template
168 # To look up a key, we check each namespace (starting with the
169 # innermost one) until a value is found.
171 function tem_data_scope($key, $context) {
172 static $refs = array();
176 if(array_key_exists($key, $scope['data'])) {
179 } while($scope = isset($scope['parent']) ? $scope['parent'] : null);
181 # not found; return empty scope.
184 $ret['parent'] =& $context;
185 $ret['data'] =& $refs[count($refs) - 1];
189 function tem_get_data($key, $context) {
190 $scope = tem_data_scope($key, $context);
191 if($scope) return isset($scope['data'][$key]) ? $scope['data'][$key] : null;
194 # Return the value for a tag as a set of rows to fill a sub-template.
195 # If $tag has an arg, call the tem_auto function to munge the data.
196 function &tem_row_data($tem, $context)
199 $scope = tem_data_scope($key, $context);
202 if(count($tem['args'])) {
203 $auto_func = "tem_auto_" . $tem['args'][0];
204 if (!function_exists($auto_func)) {
205 die("ERROR: template auto function '$auto_func' not found.<br>\n");
207 # NAMESPACIFY $auto_func
209 $value = isset($scope['data'][$key]) ? $scope['data'][$key] : null;
211 $value = $auto_func($value, $key, $scope, $tem['args']);
214 $rows = tem_data_as_rows($value, $key);
215 if(is_array($value)) {
216 $scope['data'][$key] = $rows;
222 # Return the value for a tag as an encoded string.
223 function tem_encoded_data($tag, $context)
226 $value = tem_get_data($key, $context);
227 foreach($tag['args'] as $encoding) {
228 $func = "enc_$encoding";
229 if (function_exists($func)) {
231 $value = $func($value, $key);
233 die("ERROR: encoder function '$func' not found.<br>\n");
240 function is_sub_template(&$piece) {
241 return is_array($piece) && isset($piece['pieces']);
244 function is_value_slot(&$piece) {
245 return is_array($piece) && !isset($piece['pieces']);
248 # Return a hash containing the top-level sub-templates of tem.
249 function top_sub_templates($tem, $is_sub = 'is_sub_template') {
250 function_exists($is_sub) or die("no such function '$is_sub'.");
252 foreach($tem['pieces'] as $piece) {
253 if($is_sub($piece)) {
254 $subs[$piece['name']] = $piece;
260 # merge $subs (sub_templates) into variables in $main (template)
261 function merge_sub_templates(&$main, &$subs) {
262 foreach($main['pieces'] as &$piece) {
263 if(is_array($piece)) { # not just text
264 if(isset($piece['pieces']) && $piece['pieces']) {
265 # a sub-template in main
266 merge_sub_templates($piece, $subs);
268 # a value-slot in main
269 $sub = isset($subs[$piece['name']]) ? $subs[$piece['name']] : null;
270 $arg0 = isset($sub['args'][0]) ? $sub['args'][0] : null;
271 if($sub && $arg0 != 'hide') {
272 $piece = $subs[$piece['name']];
273 $piece['parent'] =& $main;
280 # Replace values in $main with top-level templates from $tem.
281 function merge_templates(&$main, &$tem) {
282 $subs = top_sub_templates($tem);
284 merge_sub_templates($main, $subs);
292 # If a { tag has an argument, the corresponding tem_auto function is called.
293 # This allows it to mangle the data to automate some common cases.
295 # 'sep' (separator) sections will be shown for all but the last parent row.
300 # <!--~separator sep {~--><hr><!--~}~-->
304 function tem_auto_sep(&$value, $key, $context) {
305 $rows =& $context['parent']['parent'];
306 if($rows['cur'] != count($rows['rows'])-1) # last row?
307 return true; # show once
310 # auto-show once, only when this is the first row of the parent
311 function tem_auto_last(&$value, $key, $context) {
312 $rows =& $context['parent']['parent'];
313 if($rows['cur'] == count($rows['rows'])-1) # last row?
314 return true; # show once
317 # auto-show once, only when this is the last row of the parent
318 function tem_auto_first(&$value, $key, $context) {
319 $rows =& $context['parent']['parent'];
320 if($rows['cur'] == 0) # first row?
321 return true; # show once
324 # 'show' sections will be shown unless the corresponding data
326 function tem_auto_show(&$value) {
327 if($value === null) return true;
331 # 'empty' sections will be shown only if the corresponding data value is the
333 function tem_auto_empty(&$value) {
334 if($value === '') return true;
338 # 'nonempty' sections will not be shown if the corresponding data
339 # value is the empty string
340 function tem_auto_nonempty(&$value) {
341 if($value === '') return null;
345 # 'unset' sections will not be shown if the corresponding data
346 # value is not set (opposite of default)
347 function tem_auto_unset(&$value) {
348 if($value === null) {
355 # 'evenodd' sections are given an 'evenodd' attribute whose value
356 # alternates between 'even' and 'odd'.
357 function tem_auto_evenodd(&$values) {
359 if($values) foreach($values as &$value) {
360 $value['evenodd'] = $even ? 'even' : 'odd';
366 # 'once' sections are shown exactly once if the value is set (and not at all
367 # otherwise.) This is useful when an array value would otherwise cause the
368 # section to be displayed multiple times.
369 function tem_auto_once(&$value) {
370 if($value === null) return null;
374 function tem_auto_once_if(&$value) {
375 if($value) return true;
379 # 'once' sections are shown exactly once if php evaluates the value to false
380 # (and not at all otherwise.) This is useful when an array value would
381 # otherwise cause the section to be displayed multiple times.
382 function tem_auto_once_else(&$value) {
383 if($value) return null;
391 # Backward Compatibility
392 # ----------------------
394 function is_shown($piece) {
395 return isset($piece['args'][0]) && $piece['args'][0] == 'hide';
398 function is_shown_sub_template($piece) {
399 return is_sub_template($piece) and is_shown($piece);
402 # Old-style templates don't show unless explicitly requested.
403 function tem_auto_hide(&$value, $key, $context) {
404 unset($context['data'][$key]);
408 # The old API is being used with the named sub-template,
409 # so hide it and insert a value slot for its expansion(s).
410 function &tem_is_old_sub($name, &$template) {
411 foreach($template['pieces'] as $key => &$piece) {
412 if(is_sub_template($piece)) {
413 if($piece['name'] == $name) {
414 if(!is_shown($piece)) {
415 # hide template unless explicitly show()n.
416 $piece['args'] = array('hide');
417 # insert a value slot with the same name (for the expansion).
418 $var = array('name' => $name, 'args' => array());
419 array_splice($template['pieces'], $key, 0, array($var));
423 $tem = tem_is_old_sub($name, $piece);
424 if($tem) return $tem;
435 $this->template = array('pieces' => array());
436 $this->data = array();
439 function set($key, $value = true) {
440 $this->data[$key] = $value;
443 function sets($hash) {
444 foreach($hash as $key => $value) {
445 $this->set($key, $value);
449 function append($key, $value) {
450 if (!isset($this->data[$key])) {
451 $this->data[$key] = '';
453 $this->data[$key] .= $value;
456 function prepend($key, $value) {
457 $this->data[$key] = $value . $this->data[$key];
460 function clear($key) {
461 unset($this->data[$key]);
465 return $this->data[$key];
468 function show($name) {
469 $tem = tem_is_old_sub($name, $this->template);
471 if (!isset($this->data[$name])) {
472 $this->data[$name] = '';
474 $this->data[$name] .= fill_template($tem, $this->data);
478 function show_separated($name) {
479 if($this->get($name)) {
480 $this->show($name . '_sep');
485 function load_str($str) {
486 $this->template =& parse_template($str);
489 function load($filename) {
490 $this->template =& parse_template_file($filename);
493 function run($tem = false) {
495 if(strlen($tem < 150 && file_exists($tem))) $this->load($tem);
496 else $this->load_str($tem);
499 return fill_template($this->template, $this->data);
502 function output($tem = false) {
503 print($this->run($tem));
506 # merge top-level sub-templates of $tem (object) into $this,
507 # supporting both new and old semantics.
508 function merge($tem) {
509 # append expansions to $this->data (old style)
511 $subs = $tem->top_subs('is_shown_sub_template');
512 if($subs) foreach($subs as $name => $val) {
513 $this->append($name, $val);
514 unset($tem->data[$name]); # so array_merge() won't overwrite things
517 # merge the data arrays and template trees (new style)
518 $this->data = array_merge($this->data, $tem->data);
519 merge_templates($this->template, $tem->template);
523 function merge_file($filename) {
524 $other_tem = new tem();
525 $other_tem->load($filename);
526 $this->merge($other_tem);
529 function top_sub_names($is_sub = 'is_sub_template') {
530 return array_keys(top_sub_templates($this->template, $is_sub));
533 function top_subs($is_sub = 'is_sub_template') {
535 $names = $this->top_sub_names($is_sub);
536 foreach($names as $name) {
537 $ret[$name] = $this->get($name);
542 # old name for show (deprecated)
543 function sub($name) {
548 function tem_init() {
549 if(!$GLOBALS['wfpl_template']) {
550 $GLOBALS['wfpl_template'] = new tem();
554 function tem_append($key, $value) {
556 $GLOBALS['wfpl_template']->append($key, $value);
559 function tem_prepend($key, $value) {
561 $GLOBALS['wfpl_template']->prepend($key, $value);
564 function tem_set($key, $value = true) {
566 $GLOBALS['wfpl_template']->set($key, $value);
569 function tem_sets($hash) {
571 $GLOBALS['wfpl_template']->sets($hash);
574 function tem_get($key) {
576 return $GLOBALS['wfpl_template']->get($key);
579 function tem_run($tem = false) {
581 return $GLOBALS['wfpl_template']->run($tem);
584 function tem_show($name) {
586 return $GLOBALS['wfpl_template']->show($name);
589 function tem_show_separated($name) {
591 $GLOBALS['wfpl_template']->show_separated($name);
594 function tem_load($filename) {
596 $GLOBALS['wfpl_template']->load($filename);
599 function tem_merge($tem) {
601 $GLOBALS['wfpl_template']->merge($tem);
604 function tem_merge_file($filename) {
606 $GLOBALS['wfpl_template']->merge_file($filename);
609 function tem_output($filename = false) {
611 $GLOBALS['wfpl_template']->output($filename);
614 function tem_top_subs() {
616 return $GLOBALS['wfpl_template']->top_subs();
619 function tem_top_sub_names() {
621 return $GLOBALS['wfpl_template']->top_sub_names();
624 function tem_load_new($filename) {
625 $old = isset($GLOBALS['wfpl_template']) ? $GLOBALS['wfpl_template'] : null;
626 $GLOBALS['wfpl_template'] = new tem();
627 $GLOBALS['wfpl_template']->load($filename);
631 # deprecated (old name for show)
632 function tem_sub($name) {