+# For a value tag, arguments represent encodings to be applied
+# successively. For instance, ~foo html~ will encode it to be safe in
+# HTML ('&' to '&', '<' to '<', and so on).
+#
+# { tags can take one argument, which will call the corresponding
+# tem_auto_* function to munge the data, automating certain common use
+# cases. See the comments on the tem_auto functions for more details.
+
+require_once(__DIR__.'/'.'encode.php');
+require_once(__DIR__.'/'.'file.php');
+require_once(__DIR__.'/'.'misc.php');
+
+
+# Top-Level Functions
+# -------------------
+
+function template($template, $data) {
+ return fill_template(parse_template($template), $data);
+}
+
+function template_file($filename, $data) {
+ return fill_template(parse_template_file($filename), $data);
+}
+
+function &parse_template_file($filename) {
+ return parse_template(file_get_contents($filename));
+}
+
+# We parse the template string into a tree of strings and sub-templates.
+# A template is a hash with a name string, a pieces array, and possibly
+# an args array.
+
+function &parse_template($string) {
+ $tem =& tem_push();
+ $tem['pieces'] = array();
+ $matches = preg_split('/(<!--)?(~[^~]*~)(?(1)-->)/', preg_replace('/<!--(~[^~]*~)-->/', '$1', $string), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
+ foreach($matches as $match) {
+ if($match == '~~') $match = '~';
+ if(substr($match,0,1) == '~' and strlen($match) > 2) {
+ $args = explode(' ', substr($match,1,-1));
+
+ if(count($args) == 1 and $args[0] == '}') $name = '';
+ else $name = array_shift($args);
+
+ if(last($args) == '{') { # open block
+ array_pop($args); # drop '{'
+ $tem =& tem_push($tem); # create a new sub-template
+ $tem['parent']['pieces'][] =& $tem; # as a piece of the parent
+ $tem['name'] = $name;
+ $tem['pieces'] = array();
+ $tem['args'] = $args;
+ } elseif(last($args) == '}') { # close block
+ array_pop($args); # drop '}'
+ $cur = $tem['name'];
+ if($name && $name != $cur) {
+ die("Invalid template: tried to close '$name', but '$cur' is current.");
+ }
+ $tem =& $tem['parent'];
+ } else { # value slot
+ $tem['pieces'][] = array('name' => $name, 'args' => $args);
+ }
+ } else { # static string
+ $tem['pieces'][] = $match;
+ }
+ }
+ return $tem;
+}
+
+function fill_template($template, &$data, &$context = NULL) {
+ $context =& tem_push($context);
+ $context['data'] =& $data;
+
+ foreach($template['pieces'] as $tem) {
+ if(is_string($tem)) $output .= $tem;
+ elseif($tem['pieces']) { # sub-template
+ $rows =& tem_row_data($tem, $context);
+ $context['rows'] =& $rows;
+ foreach($rows as $key => &$row) {
+ $context['cur'] = $key;
+ $output .= fill_template($tem, $row, $context);
+ }
+ } else { # variable
+ $output .= tem_encoded_data($tem, $context);
+ }
+ }
+ $context =& $context['parent'];
+ return $output;
+}
+
+
+# Implementation
+# --------------
+
+
+# To track our position in the template and in the data, we use a linked
+# stack structure. Each node is a hash with a reference to the parent
+# node along with whatever other data you want to add. For each stack,
+# you simply keep a variable with a reference to the top element. Then
+# the push and pop operations are:
+
+# $top =& tem_push($top);
+# $top =& $top['parent'];
+
+function &tem_push(&$stack = NULL) {
+ static $refs = array();
+
+ # Since a PHP reference is *not* a pointer to data, but a pointer to
+ # a variable (or array slot), we *have* to first put the new node in
+ # $refs, and then reference it from $new.
+
+ $refs[] = array();
+ $new =& $refs[count($refs)-1];
+ if($stack) $new['parent'] =& $stack;
+ return $new;
+}
+
+# To fill out a template, we do a depth-first traversal of the template
+# tree, replacing all tags with the data values.
+
+# The data starts out as a nested set of key/value pairs, where the
+# values can be:
+
+ # a string to fill a value slot
+ # a hash to fill one instance of a sub-template
+ # an array of hashes to fill multiple instances of a sub-template
+
+# The middle form will be converted to the last form as we use it.
+
+function tem_data_as_rows($value, $key) {
+ if(is_array($value)) {
+ # numeric keys
+ if(array_key_exists(0, $value)) {
+ if(is_array($value[0])) return $value; # already array of hashes.
+ else return columnize($value, $key);
+ # key/value pairs -- expand sub-template once.
+ } else return array($value);
+ } elseif($value || $value === 0 || $value === '0' || $value === '') {
+ # value -- expand sub-template once using only parent values
+ return array(array());
+ } else {
+ # empty value -- don't expand sub-template
+ return array();
+ }
+}
+
+# To look up a key, we check each namespace (starting with the
+# innermost one) until a value is found.
+
+function tem_data_scope($key, $context) {
+ static $refs = array();
+
+ $scope = $context;
+ do{
+ if(array_key_exists($key, $scope['data'])) {
+ return $scope;
+ }
+ } while($scope = $scope['parent']);
+
+ # not found; return empty scope.
+ $refs[] = array();
+ $ret = array();
+ $ret['parent'] =& $context;
+ $ret['data'] =& last($refs);
+ return $ret;
+}
+
+function tem_get_data($key, $context) {
+ $scope = tem_data_scope($key, $context);
+ if($scope) return $scope['data'][$key];
+}
+
+# Return the value for a tag as a set of rows to fill a sub-template.
+# If $tag has an arg, call the tem_auto function to munge the data.
+function &tem_row_data($tem, $context)
+{
+ $key = $tem['name'];
+ $scope = tem_data_scope($key, $context);
+
+ if(count($tem['args'])) {
+ $auto_func = "tem_auto_" . $tem['args'][0];
+ if (!function_exists($auto_func)) {
+ die("ERROR: template auto function '$auto_func' not found.<br>\n");
+ }
+ # NAMESPACIFY $auto_func
+ }
+ if ($auto_func) {
+ $value = $auto_func($scope['data'][$key], $key, $scope, $tem['args']);
+ }
+ else $value = $scope['data'][$key];
+
+ $rows = tem_data_as_rows($value, $key);
+ if(is_array($value)) $scope['data'][$key] = $rows;
+
+ return $rows;
+}
+
+# Return the value for a tag as an encoded string.
+function tem_encoded_data($tag, $context)
+{
+ $key = $tag['name'];
+ $value = tem_get_data($key, $context);
+ foreach($tag['args'] as $encoding) {
+ $func = "enc_$encoding";
+ if (function_exists($func)) {
+ # NAMESPACIFY $func
+ $value = $func($value, $key);
+ } else {
+ die("ERROR: encoder function '$func' not found.<br>\n");
+ }
+ }
+ return $value;
+}
+
+
+function is_sub_template(&$piece) {
+ return is_array($piece) and $piece['pieces'];
+}
+
+function is_value_slot(&$piece) {
+ return is_array($piece) and !$piece['pieces'];
+}
+
+# Return a hash containing the top-level sub-templates of tem.
+function top_sub_templates($tem, $is_sub = 'is_sub_template') {
+ function_exists($is_sub) or die("no such function '$is_sub'.");
+ $subs = array();
+ foreach($tem['pieces'] as $piece) {
+ if($is_sub($piece)) {
+ $subs[$piece['name']] = $piece;
+ }
+ }
+ return $subs;
+}
+
+# merge $subs (sub_templates) into variables in $main (template)
+function merge_sub_templates(&$main, &$subs) {
+ foreach($main['pieces'] as &$piece) {
+ if(is_array($piece)) { # not just text
+ if($piece['pieces']) {
+ # a sub-template in main
+ merge_sub_templates($piece, $subs);
+ } else {
+ # a value-slot in main
+ $sub = $subs[$piece['name']];
+ if($sub and $sub['args'][0] != 'hide') {
+ $piece = $subs[$piece['name']];
+ $piece['parent'] =& $main;
+ }
+ }
+ }
+ }
+ return $out;
+}
+
+# Replace values in $main with top-level templates from $tem.
+function merge_templates(&$main, &$tem) {
+ $subs = top_sub_templates($tem);
+
+ merge_sub_templates($main, $subs);
+}
+
+
+
+# tem_auto functions
+# ------------------
+#
+# If a { tag has an argument, the corresponding tem_auto function is called.
+# This allows it to mangle the data to automate some common cases.
+
+# 'sep' (separator) sections will be shown for all but the last parent row.
+# Sample usage:
+# <!--~rows {~-->
+# <!--~row {~-->
+# row content...
+# <!--~separator sep {~--><hr><!--~}~-->
+# <!--~}~-->
+# <!--~}~-->
+#
+function tem_auto_sep(&$value, $key, $context) {
+ $rows =& $context['parent']['parent'];
+ if($rows['cur'] != count($rows['rows'])-1) # last row?
+ return true; # show once
+}
+
+# auto-show once, only when this is the first row of the parent
+function tem_auto_last(&$value, $key, $context) {
+ $rows =& $context['parent']['parent'];
+ if($rows['cur'] == count($rows['rows'])-1) # last row?
+ return true; # show once
+}
+
+# auto-show once, only when this is the last row of the parent
+function tem_auto_first(&$value, $key, $context) {
+ $rows =& $context['parent']['parent'];
+ if($rows['cur'] == 0) # first row?
+ return true; # show once
+}
+
+# 'show' sections will be shown unless the corresponding data
+# value === false
+function tem_auto_show(&$value) {
+ if($value === null) return true;
+ return $value;
+}