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($data, $template) {
49 return fill_template($data, parse_template($template));
52 function template_file($data, $filename) {
53 return fill_template($data, parse_template_file($filename));
56 function parse_template_file($filename) {
57 return parse_template(file_get_contents($filename));
60 # First we take the template string and convert it into a tree of
61 # strings and sub-templates. A template is a hash with a name string,
62 # a pieces array, and possibly an args array.
64 function parse_template($string) {
65 # Don't mess with the $stack/$tem assignments! Since
66 # PHP references point to the variable, not the data,
67 # it really does have to be written exactly like this.
68 $stack[] = array('name' => 'root', 'pieces' => array());
70 # note: for some reason this captures '<!--' but not '-->'.
71 $matches = preg_split("/(<!--)?(~[^~]*~)(?(1)-->)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
72 foreach($matches as $match) {
73 if(substr($match,0,1) == '~') {
74 $args = explode(' ', substr($match,1,-1));
76 if(count($args) == 1 and $args[0] == '}') $name = '';
77 else $name = array_shift($args);
79 if(last($args) == '{') { # open block
81 $stack[] = array('name' => $name, 'pieces' => array(), 'args' => $args);
82 $tem['pieces'][] = &last($stack);
84 } elseif(last($args) == '}') { # close block
86 $cur = $stack[count($stack)-1]['name'];
87 if($name && $name != $cur) {
88 die("Invalid template: tried to close '$name', but '$cur' is current.");
90 array_pop($stack); $tem = &last($stack);
92 $tem['pieces'][] = array('name' => $name, 'args' => $args);
94 } elseif($match and $match != '<!--') { # static string
95 $tem['pieces'][] = $match;
101 # Then we do a depth-first traversal of the template tree,
102 # replacing all tags with the data values.
104 function fill_template($data, $template, $context = NULL, $keychain = NULL) {
106 foreach($template['pieces'] as $piece) {
107 if(is_string($piece)) $output .= $piece;
109 if($piece['pieces']) { # sub-template
110 $keychain[] = $piece['name'];
111 $rows = tem_get_rows($piece, $context, $keychain);
112 foreach($rows as $key => $row) {
114 $output .= fill_template($row, $piece, $context, $keychain);
115 array_pop($keychain);
117 array_pop($keychain);
119 $output .= tem_get_enc($piece, $context);
127 # Replace top-level values in $main with top-level templates from $tem.
128 function merge_templates($main, $tem) {
129 $out = array('name' => $main['name'], 'pieces' => array());
131 $subs = top_sub_templates($tem);
133 foreach($main['pieces'] as $piece) {
134 if(is_array($piece) and !$piece['pieces'] and $subs[$piece['name']]) {
135 $piece = $subs[$piece['name']];
137 $out['pieces'][] = $piece;
147 # If a { tag has an argument, the corresponding tem_auto function is called.
148 # This allows it to mangle the data to automate some common cases.
150 # 'sep' (separator) sections will be shown for all but the last parent row.
155 # <!--~separator sep {~--><hr><!--~separator }"-->
159 function tem_auto_sep($piece, $context, $keychain) {
160 list($name, $index, $this_name) = array_slice($keychain, -3);
161 $array = tem_get($name, $context);
162 if($index != count($array)-1) return true;
165 # 'once' sections will be shown once unless the corresponding data value
166 # is false. We check only for false; 0 or '' will not work.
168 function tem_auto_once($piece, $context, $keychain) {
169 $value = tem_get(array_pop($keychain), $context);
170 if($value !== false) return true;
173 # 'evenodd' sections are given an 'evenodd' attribute whose value
174 # alternates between 'even' and 'odd'.
176 function tem_auto_evenodd($piece, $context, $keychain) {
177 $rows = tem_get(array_pop($keychain), $context);
179 $text = array('even', 'odd');
180 foreach($rows as $key => $value) {
181 $rows[$key]['evenodd'] = $text[$even];
192 # Of course, nothing stops you from using these, but I don't know
193 # why you would want to...
196 # Convert value to array of hashes for use in sub-template expansion.
197 # This adds flexibility to how you represent your data.
198 function tem_value_as_rows($value) {
199 if(is_array($value)) {
200 # numeric keys, is already array of arrays -- expand sub-template for each.
201 if(array_key_exists(0, $value)) return $value;
202 # key/value pairs -- expand sub-template once.
203 else return array($value);
205 # value -- expand sub-template once using only parent values
206 return array(array());
208 # empty value -- don't expand sub-template
213 # Search the current context and return the value for key.
214 function tem_get($key, $context) {
216 $data = array_pop($context);
217 if(array_key_exists($key, $data)) return $data[$key];
221 # Return the value for a tag as a set of rows to fill a sub-template.
222 # If $tag has an arg, call the tem_auto function to munge the data.
223 function tem_get_rows($tag, $context, $keychain)
225 if(count($tag['args'])) {
226 $func = "tem_auto_" . $tag['args'][0];
227 if(function_exists($func)) $value = $func($tag, $context, $keychain);
228 else die("ERROR: template auto function '$func' not found.<br>\n");
229 } else $value = tem_get($tag['name'], $context);
231 return tem_value_as_rows($value);
234 # Return the value for a tag as an encoded string.
235 function tem_get_enc($tag, $context)
238 $value = tem_get($key, $context);
239 foreach($tag['args'] as $encoding) {
240 $func = "enc_$encoding";
241 if(function_exists($func)) $value = $func($value, $key);
242 else die("ERROR: encoder function '$func' not found.<br>\n");
247 function top_sub_templates($tem) {
249 foreach($tem['pieces'] as $piece) {
250 if(is_array($piece) and $piece['pieces']) {
251 $subs[$piece['name']] = $piece;