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 .= tem_apply_encodings($tem['name'], fill_template($tem, $row, $context), $tem['args']);
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 if (function_exists("enc_" . $tem['args'][0])) {
208 die("ERROR: template auto function '$auto_func' not found.<br>\n");
211 # NAMESPACIFY $auto_func
213 $value = isset($scope['data'][$key]) ? $scope['data'][$key] : null;
215 $value = $auto_func($value, $key, $scope, $tem['args']);
218 $rows = tem_data_as_rows($value, $key);
219 if(is_array($value)) {
220 $scope['data'][$key] = $rows;
226 function tem_apply_encodings ($key, $value, $encodings) {
227 if ($encodings) foreach($encodings as $encoding) {
228 $func = "enc_$encoding";
229 if (function_exists($func)) {
231 $value = $func($value, $key);
232 } elseif (!function_exists("tem_auto_$encoding")) {
233 die("ERROR: encoder function '$func' not found.<br>\n");
239 # Return the value for a tag as an encoded string.
240 function tem_encoded_data($tag, $context)
243 $value = tem_get_data($key, $context);
244 return tem_apply_encodings($key, $value, $tag['args']);
248 function is_sub_template(&$piece) {
249 return is_array($piece) && isset($piece['pieces']);
252 function is_value_slot(&$piece) {
253 return is_array($piece) && !isset($piece['pieces']);
256 # Return a hash containing the top-level sub-templates of tem.
257 function top_sub_templates($tem, $is_sub = 'is_sub_template') {
258 function_exists($is_sub) or die("no such function '$is_sub'.");
260 foreach($tem['pieces'] as $piece) {
261 if($is_sub($piece)) {
262 $subs[$piece['name']] = $piece;
268 # merge $subs (sub_templates) into variables in $main (template)
269 function merge_sub_templates(&$main, &$subs) {
270 foreach($main['pieces'] as &$piece) {
271 if(is_array($piece)) { # not just text
272 if(isset($piece['pieces']) && $piece['pieces']) {
273 # a sub-template in main
274 merge_sub_templates($piece, $subs);
276 # a value-slot in main
277 $sub = isset($subs[$piece['name']]) ? $subs[$piece['name']] : null;
278 $arg0 = isset($sub['args'][0]) ? $sub['args'][0] : null;
279 if($sub && $arg0 != 'hide') {
280 $piece = $subs[$piece['name']];
281 $piece['parent'] =& $main;
288 # Replace values in $main with top-level templates from $tem.
289 function merge_templates(&$main, &$tem) {
290 $subs = top_sub_templates($tem);
292 merge_sub_templates($main, $subs);
300 # If a { tag has an argument, the corresponding tem_auto function is called.
301 # This allows it to mangle the data to automate some common cases.
303 # 'sep' (separator) sections will be shown for all but the last parent row.
308 # <!--~separator sep {~--><hr><!--~}~-->
312 function tem_auto_sep(&$value, $key, $context) {
313 $rows =& $context['parent']['parent'];
314 if($rows['cur'] != count($rows['rows'])-1) # last row?
315 return true; # show once
318 # auto-show once, only when this is the first row of the parent
319 function tem_auto_last(&$value, $key, $context) {
320 $rows =& $context['parent']['parent'];
321 if($rows['cur'] == count($rows['rows'])-1) # last row?
322 return true; # show once
325 # auto-show once, only when this is the last row of the parent
326 function tem_auto_first(&$value, $key, $context) {
327 $rows =& $context['parent']['parent'];
328 if($rows['cur'] == 0) # first row?
329 return true; # show once
332 # 'show' sections will be shown unless the corresponding data
334 function tem_auto_show(&$value) {
335 if($value === null) return true;
339 # 'empty' sections will be shown only if the corresponding data value is the
341 function tem_auto_empty(&$value) {
342 if($value === '') return true;
346 # 'nonempty' sections will not be shown if the corresponding data
347 # value is the empty string
348 function tem_auto_nonempty(&$value) {
349 if($value === '') return null;
353 # 'unset' sections will not be shown if the corresponding data
354 # value is not set (opposite of default)
355 function tem_auto_unset(&$value) {
356 if($value === null) {
363 # 'evenodd' sections are given an 'evenodd' attribute whose value
364 # alternates between 'even' and 'odd'.
365 function tem_auto_evenodd(&$values) {
367 if($values) foreach($values as &$value) {
368 $value['evenodd'] = $even ? 'even' : 'odd';
374 # 'once' sections are shown exactly once if the value is set (and not at all
375 # otherwise.) This is useful when an array value would otherwise cause the
376 # section to be displayed multiple times.
377 function tem_auto_once(&$value) {
378 if($value === null) return null;
382 function tem_auto_once_if(&$value) {
383 if($value) return true;
387 # 'once' sections are shown exactly once if php evaluates the value to false
388 # (and not at all otherwise.) This is useful when an array value would
389 # otherwise cause the section to be displayed multiple times.
390 function tem_auto_once_else(&$value) {
391 if($value) return null;
399 # Backward Compatibility
400 # ----------------------
402 function is_shown($piece) {
403 return isset($piece['args'][0]) && $piece['args'][0] == 'hide';
406 function is_shown_sub_template($piece) {
407 return is_sub_template($piece) and is_shown($piece);
410 # Old-style templates don't show unless explicitly requested.
411 function tem_auto_hide(&$value, $key, $context) {
412 unset($context['data'][$key]);
416 # The old API is being used with the named sub-template,
417 # so hide it and insert a value slot for its expansion(s).
418 function &tem_is_old_sub($name, &$template) {
419 foreach($template['pieces'] as $key => &$piece) {
420 if(is_sub_template($piece)) {
421 if($piece['name'] == $name) {
422 if(!is_shown($piece)) {
423 # hide template unless explicitly show()n.
424 $piece['args'] = array('hide');
425 # insert a value slot with the same name (for the expansion).
426 $var = array('name' => $name, 'args' => array());
427 array_splice($template['pieces'], $key, 0, array($var));
431 $tem = tem_is_old_sub($name, $piece);
432 if($tem) return $tem;
444 $this->template = array('pieces' => array());
445 $this->data = array();
448 function set($key, $value = true) {
449 $this->data[$key] = $value;
452 function sets($hash) {
453 foreach($hash as $key => $value) {
454 $this->set($key, $value);
458 function append($key, $value) {
459 if (!isset($this->data[$key])) {
460 $this->data[$key] = '';
462 $this->data[$key] .= $value;
465 function prepend($key, $value) {
466 $this->data[$key] = $value . $this->data[$key];
469 function clear($key) {
470 unset($this->data[$key]);
474 if (isset($this->data[$key])) {
475 return $this->data[$key];
481 function show($name) {
482 $tem = tem_is_old_sub($name, $this->template);
484 if (!isset($this->data[$name])) {
485 $this->data[$name] = '';
487 $this->data[$name] .= fill_template($tem, $this->data);
491 function show_separated($name) {
492 if($this->get($name)) {
493 $this->show($name . '_sep');
498 function load_str($str) {
499 $this->template =& parse_template($str);
502 function load($filename) {
503 $this->template =& parse_template_file($filename);
506 function run($tem = false) {
508 if(strlen($tem < 150 && file_exists($tem))) $this->load($tem);
509 else $this->load_str($tem);
512 return fill_template($this->template, $this->data);
515 function output($tem = false) {
516 print($this->run($tem));
519 # merge top-level sub-templates of $tem (object) into $this,
520 # supporting both new and old semantics.
521 function merge($tem) {
522 # append expansions to $this->data (old style)
524 $subs = $tem->top_subs('is_shown_sub_template');
525 if($subs) foreach($subs as $name => $val) {
526 $this->append($name, $val);
527 unset($tem->data[$name]); # so array_merge() won't overwrite things
530 # merge the data arrays and template trees (new style)
531 $this->data = array_merge($this->data, $tem->data);
532 merge_templates($this->template, $tem->template);
536 function merge_file($filename) {
537 $other_tem = new tem();
538 $other_tem->load($filename);
539 $this->merge($other_tem);
542 function top_sub_names($is_sub = 'is_sub_template') {
543 return array_keys(top_sub_templates($this->template, $is_sub));
546 function top_subs($is_sub = 'is_sub_template') {
548 $names = $this->top_sub_names($is_sub);
549 foreach($names as $name) {
550 $ret[$name] = $this->get($name);
555 # old name for show (deprecated)
556 function sub($name) {
561 function tem_init() {
562 if(!isset($GLOBALS['wfpl_template']) || !$GLOBALS['wfpl_template']) {
563 $GLOBALS['wfpl_template'] = new tem();
567 function tem_append($key, $value) {
569 $GLOBALS['wfpl_template']->append($key, $value);
572 function tem_prepend($key, $value) {
574 $GLOBALS['wfpl_template']->prepend($key, $value);
577 function tem_set($key, $value = true) {
579 $GLOBALS['wfpl_template']->set($key, $value);
582 function tem_sets($hash) {
584 $GLOBALS['wfpl_template']->sets($hash);
587 function tem_get($key) {
589 return $GLOBALS['wfpl_template']->get($key);
592 function tem_run($tem = false) {
594 return $GLOBALS['wfpl_template']->run($tem);
597 function tem_show($name) {
599 return $GLOBALS['wfpl_template']->show($name);
602 function tem_show_separated($name) {
604 $GLOBALS['wfpl_template']->show_separated($name);
607 function tem_load($filename) {
609 $GLOBALS['wfpl_template']->load($filename);
612 function tem_merge($tem) {
614 $GLOBALS['wfpl_template']->merge($tem);
617 function tem_merge_file($filename) {
619 $GLOBALS['wfpl_template']->merge_file($filename);
622 function tem_output($filename = false) {
624 $GLOBALS['wfpl_template']->output($filename);
627 function tem_top_subs() {
629 return $GLOBALS['wfpl_template']->top_subs();
632 function tem_top_sub_names() {
634 return $GLOBALS['wfpl_template']->top_sub_names();
637 function tem_load_new($filename) {
638 $old = isset($GLOBALS['wfpl_template']) ? $GLOBALS['wfpl_template'] : null;
639 $GLOBALS['wfpl_template'] = new tem();
640 $GLOBALS['wfpl_template']->load($filename);
644 # deprecated (old name for show)
645 function tem_sub($name) {