JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
* template.php: changed arg order, new context stack implementation.
[wfpl.git] / template.php
1 <?php
2
3 #  Copyright (C) 2008,2009 Joshua Grams <josh@qualdan.com>
4 #
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.
9 #  
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.
14 #  
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/>.
17
18
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.
21 #
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).
25 #
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 
30 # present.
31 #
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 '&amp;', '<' to '&lt;', and so on).
35 #
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.
39
40 require_once('code/wfpl/encode.php');
41 require_once('code/wfpl/file.php');
42 require_once('code/wfpl/misc.php');
43
44
45 # Public functions
46 # ----------------
47
48 function template($template, $data) {
49         return fill_template(parse_template($template), $data);
50 }
51
52 function template_file($filename, $data) {
53         return fill_template(parse_template_file($filename), $data);
54 }
55
56 function parse_template_file($filename) {
57         return parse_template(file_get_contents($filename));
58 }
59
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.
63
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());
69         $tem = &last($stack);
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));
75
76                         if(count($args) == 1 and $args[0] == '}') $name = '';
77                         else $name = array_shift($args);
78
79                         if(last($args) == '{') {  # open block
80                                 array_pop($args);
81                                 $stack[] = array('name' => $name, 'pieces' => array(), 'args' => $args);
82                                 $tem['pieces'][] = &last($stack);
83                                 $tem = &last($stack);
84                         } elseif(last($args) == '}') {  # close block
85                                 array_pop($args);
86                                 $cur = $stack[count($stack)-1]['name'];
87                                 if($name && $name != $cur) {
88                                         die("Invalid template: tried to close '$name', but '$cur' is current.");
89                                 }
90                                 array_pop($stack); $tem = &last($stack);
91                         } else {  # value slot
92                                 $tem['pieces'][] = array('name' => $name, 'args' => $args);
93                         }
94                 } elseif($match and $match != '<!--') {  # static string
95                         $tem['pieces'][] = $match;
96                 }
97         }
98         return $tem;
99 }
100
101 # To fill out a template, we do a depth-first traversal of the template 
102 # tree, replacing all tags with the data values.
103
104 # The data starts out as a nested set of key/value pairs, where the 
105 # values can be:
106
107         # a string to fill a value slot
108         # a hash to fill one instance of a sub-template
109         # an array of hashes to fill multiple instances of a sub-template
110
111 # The middle form will be converted to the last form as we use it.
112
113 function tem_data_as_rows($value) {
114         if(is_array($value)) {
115                 # numeric keys, is already array of arrays -- expand sub-template for each.
116                 if(array_key_exists(0, $value)) return $value;
117                 # key/value pairs -- expand sub-template once.
118                 else return array($value);
119         } elseif($value) {
120                 # value -- expand sub-template once using only parent values
121                 return array(array());
122         } else {
123                 # empty value -- don't expand sub-template
124                 return array();
125         }
126 }
127
128
129
130 # We use dynamic scoping, so we keep a stack of namespaces.
131 # Each scope references a hash and the parent scope.
132
133 function &tem_scope(&$data, $push = true) {
134         static $stack = array();
135
136         if($push) {
137                 $parent =& last($stack);
138                 $stack[] = array();
139
140                 $scope =& last($stack);
141                 $scope['data'] =& $data;
142                 if($parent) $scope['parent'] =& $parent;
143         } else { # pop
144                 array_pop($stack);
145         }
146         return last($stack);
147 }
148
149 function &tem_end_scope() { return tem_scope($x, false); }
150
151 # To look up a key, we check each namespace (starting with the
152 # innermost one) until a value is found.
153
154 function tem_find_scope($key, $context) {
155         $scope = $context;
156         do{
157                 if(array_key_exists($key, $scope['data'])) {
158                         return $scope;
159                 }
160         } while($scope = $scope['parent']);
161
162         # not found; return empty scope.
163         return array('parent' => $context);
164 }
165
166 function tem_get($key, $context) {
167         $scope = tem_find_scope($key, $context);
168         if($scope) return $scope['data'][$key];
169 }
170
171 # Return the value for a tag as a set of rows to fill a sub-template.
172 # If $tag has an arg, call the tem_auto function to munge the data.
173 function &tem_get_rows($tag, $context)
174 {
175         $key = $tag['name'];
176         if(count($tag['args'])) {
177                 $func = "tem_auto_" . $tag['args'][0];
178                 function_exists($func)
179                         or die("ERROR: template auto function '$func' not found.<br>\n");
180         }
181         $scope = tem_find_scope($key, $context);
182
183         if($func) $value = $func($key, $scope);
184         else $value = $scope['data'][$key];
185
186         $rows = tem_data_as_rows($value);
187         if(is_array($value)) $scope['data'][$key] = $rows;
188
189         return $rows;
190 }
191
192 # Return the value for a tag as an encoded string.
193 function tem_get_enc($tag, $context)
194 {
195         $key = $tag['name'];
196         $value = tem_get($key, $context);
197         foreach($tag['args'] as $encoding) {
198                 $func = "enc_$encoding";
199                 if(function_exists($func)) $value = $func($value, $key);
200                 else die("ERROR: encoder function '$func' not found.<br>\n");
201         }
202         return $value;
203 }
204
205 function fill_template($template, &$data, &$context = NULL) {
206         if(!$context) $context =& tem_scope($data);
207         foreach($template['pieces'] as $tem) {
208                 if(is_string($tem)) $output .= $tem;
209                 elseif($tem['pieces']) {  # sub-template
210                         $rows =& tem_get_rows($tem, $context);
211                         foreach($rows as $key => &$row) {
212                                 $context =& tem_scope($row);
213                                 $context['rows'] =& $rows;
214                                         $output .= fill_template($tem, $row, $context);
215                                 $context =& tem_end_scope();
216
217                         }
218                 } else {  # variable
219                         $output .= tem_get_enc($tem, $context);
220                 }
221         }
222         return $output;
223 }
224
225
226
227 # Return a hash containing the top-level sub-templates of tem.
228 function top_sub_templates($tem) {
229         $subs = array();
230         foreach($tem['pieces'] as $piece) {
231                 if(is_array($piece) and $piece['pieces']) {
232                         $subs[$piece['name']] = $piece;
233                 }
234         }
235         return $subs;
236 }
237
238 # Replace top-level values in $main with top-level templates from $tem.
239 function merge_templates($main, $tem) {
240         $out = array('name' => $main['name'], 'pieces' => array());
241
242         $subs = top_sub_templates($tem);
243
244         foreach($main['pieces'] as $piece) {
245                 if(is_array($piece) and !$piece['pieces'] and $subs[$piece['name']]) {
246                         $piece = $subs[$piece['name']];
247                 }
248                 $out['pieces'][] = $piece;
249         }
250         return $out;
251 }
252
253
254
255 # tem_auto functions
256 # ------------------
257 #
258 # If a { tag has an argument, the corresponding tem_auto function is called.
259 # This allows it to mangle the data to automate some common cases.
260
261 # 'sep' (separator) sections will be shown for all but the last parent row.
262 # Sample usage:
263 #       <!--~rows~-->
264 #               <!--~row~-->
265 #                       row content...
266 #                       <!--~separator sep {~--><hr><!--~separator }"-->
267 #               <!--~row~-->
268 #       <!--~rows~-->
269 #
270 function tem_auto_sep($key, $context) {
271         $rows =& $context['parent']['rows'];
272         if(key($rows)) return true;
273         # else we are on the last row (cursor has hit the end and reset).
274 }
275
276 # 'once' sections will be shown once unless the corresponding data value
277 # is false.  We check only for false; 0 or '' will not work.
278
279 function tem_auto_once($key, $context) {
280         if($context['data'][$key] !== false)
281                 return tem_data_as_rows(true);
282 }
283
284 # 'evenodd' sections are given an 'evenodd' attribute whose value
285 # alternates between 'even' and 'odd'.
286
287 function tem_auto_evenodd($key, $context) {
288         $rows = $context['data'][$key];
289         $even = 0;
290         $text = array('even', 'odd');
291         foreach($rows as $key => $value) {
292                 $rows[$key]['evenodd'] = $text[$even];
293                 $even = 1 - $even;
294         }
295         return tem_data_as_rows($rows);
296 }
297
298 ?>