JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
* template.php: switch to generic linked stack.
[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 # Top-Level 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 # See also parse_template and fill_template.
61
62
63 # To track our position in the template and in the data, we use a linked 
64 # stack structure.  Each node is a hash with a reference to the parent 
65 # node along with whatever other data you want to add.  For each stack, 
66 # you simply keep a variable with a reference to the top element.  Then 
67 # the push and pop operations are:
68
69 # $top =& tem_push($top);
70 # $top =& $top['parent'];
71
72 function &tem_push(&$stack = NULL) {
73         static $refs = array();
74
75         # Since a PHP reference is *not* a pointer to data, but a pointer to 
76         # a variable (or array slot), we *have* to first put the new node in
77         # $refs, and then reference it from $new.
78
79         $refs[] = array();
80         $new =& $refs[count($refs)-1];
81         if($stack) $new['parent'] =& $stack;
82         return $new;
83 }
84
85
86 # First we take the template string and convert it into a tree of
87 # strings and sub-templates.  A template is a hash with a name string,
88 # a pieces array, and possibly an args array.
89
90 function parse_template($string) {
91         $tem =& tem_push();
92         $tem['pieces'] = array();
93         # note: for some reason this captures '<!--' but not '-->'.
94         $matches = preg_split("/(<!--)?(~[^~]*~)(?(1)-->)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
95         foreach($matches as $match) {
96                 if(substr($match,0,1) == '~') {
97                         $args = explode(' ', substr($match,1,-1));
98
99                         if(count($args) == 1 and $args[0] == '}') $name = '';
100                         else $name = array_shift($args);
101
102                         if(last($args) == '{') {  # open block
103                                 array_pop($args);
104                                 # create a new sub-template
105                                 # and add it to the parent.
106                                 $tem =& tem_push($tem);
107                                 $tem['parent']['pieces'][] =& $tem;
108                                 $tem['name'] = $name;
109                                 $tem['pieces'] = array();
110                                 $tem['args'] = $args;
111                         } elseif(last($args) == '}') {  # close block
112                                 array_pop($args);
113                                 $cur = $tem['name'];
114                                 if($name && $name != $cur) {
115                                         die("Invalid template: tried to close '$name', but '$cur' is current.");
116                                 }
117                                 $tem =& $tem['parent'];
118                         } else {  # value slot
119                                 $tem['pieces'][] = array('name' => $name, 'args' => $args);
120                         }
121                 } elseif($match and $match != '<!--') {  # static string
122                         $tem['pieces'][] = $match;
123                 }
124         }
125         return $tem;
126 }
127
128 # To fill out a template, we do a depth-first traversal of the template 
129 # tree, replacing all tags with the data values.
130
131 # The data starts out as a nested set of key/value pairs, where the 
132 # values can be:
133
134         # a string to fill a value slot
135         # a hash to fill one instance of a sub-template
136         # an array of hashes to fill multiple instances of a sub-template
137
138 # The middle form will be converted to the last form as we use it.
139
140 function tem_data_as_rows($value) {
141         if(is_array($value)) {
142                 # numeric keys, is already array of arrays -- expand sub-template for each.
143                 if(array_key_exists(0, $value)) return $value;
144                 # key/value pairs -- expand sub-template once.
145                 else return array($value);
146         } elseif($value) {
147                 # value -- expand sub-template once using only parent values
148                 return array(array());
149         } else {
150                 # empty value -- don't expand sub-template
151                 return array();
152         }
153 }
154
155 # To look up a key, we check each namespace (starting with the
156 # innermost one) until a value is found.
157
158 function tem_find_scope($key, $context) {
159         $scope = $context;
160         do{
161                 if(array_key_exists($key, $scope['data'])) {
162                         return $scope;
163                 }
164         } while($scope = $scope['parent']);
165
166         # not found; return empty scope.
167         return array('parent' => $context);
168 }
169
170 function tem_get($key, $context) {
171         $scope = tem_find_scope($key, $context);
172         if($scope) return $scope['data'][$key];
173 }
174
175 # Return the value for a tag as a set of rows to fill a sub-template.
176 # If $tag has an arg, call the tem_auto function to munge the data.
177 function &tem_get_rows($tag, $context)
178 {
179         $key = $tag['name'];
180         if(count($tag['args'])) {
181                 $func = "tem_auto_" . $tag['args'][0];
182                 function_exists($func)
183                         or die("ERROR: template auto function '$func' not found.<br>\n");
184         }
185         $scope = tem_find_scope($key, $context);
186
187         if($func) $value = $func($key, $scope);
188         else $value = $scope['data'][$key];
189
190         $rows = tem_data_as_rows($value);
191         if(is_array($value)) $scope['data'][$key] = $rows;
192
193         return $rows;
194 }
195
196 # Return the value for a tag as an encoded string.
197 function tem_get_enc($tag, $context)
198 {
199         $key = $tag['name'];
200         $value = tem_get($key, $context);
201         foreach($tag['args'] as $encoding) {
202                 $func = "enc_$encoding";
203                 if(function_exists($func)) $value = $func($value, $key);
204                 else die("ERROR: encoder function '$func' not found.<br>\n");
205         }
206         return $value;
207 }
208
209 function fill_template($template, &$data, &$context = NULL) {
210         if(!$context) {
211                 $context =& tem_push($context);
212                 $context['data'] =& $data;
213         }
214
215         foreach($template['pieces'] as $tem) {
216                 if(is_string($tem)) $output .= $tem;
217                 elseif($tem['pieces']) {  # sub-template
218                         $rows =& tem_get_rows($tem, $context);
219                         foreach($rows as $key => &$row) {
220                                 $context =& tem_push($context);
221                                 $context['data'] =& $row;
222                                 $context['rows'] =& $rows;
223                                         $output .= fill_template($tem, $row, $context);
224                                 $context =& $context['parent'];
225
226                         }
227                 } else {  # variable
228                         $output .= tem_get_enc($tem, $context);
229                 }
230         }
231         return $output;
232 }
233
234
235
236 # Return a hash containing the top-level sub-templates of tem.
237 function top_sub_templates($tem) {
238         $subs = array();
239         foreach($tem['pieces'] as $piece) {
240                 if(is_array($piece) and $piece['pieces']) {
241                         $subs[$piece['name']] = $piece;
242                 }
243         }
244         return $subs;
245 }
246
247 # Replace top-level values in $main with top-level templates from $tem.
248 function merge_templates($main, $tem) {
249         $out = array('name' => $main['name'], 'pieces' => array());
250
251         $subs = top_sub_templates($tem);
252
253         foreach($main['pieces'] as $piece) {
254                 if(is_array($piece) and !$piece['pieces'] and $subs[$piece['name']]) {
255                         $piece = $subs[$piece['name']];
256                 }
257                 $out['pieces'][] = $piece;
258         }
259         return $out;
260 }
261
262
263
264 # tem_auto functions
265 # ------------------
266 #
267 # If a { tag has an argument, the corresponding tem_auto function is called.
268 # This allows it to mangle the data to automate some common cases.
269
270 # 'sep' (separator) sections will be shown for all but the last parent row.
271 # Sample usage:
272 #       <!--~rows~-->
273 #               <!--~row~-->
274 #                       row content...
275 #                       <!--~separator sep {~--><hr><!--~separator }"-->
276 #               <!--~row~-->
277 #       <!--~rows~-->
278 #
279 function tem_auto_sep($key, $context) {
280         $rows =& $context['parent']['rows'];
281         if(key($rows)) return true;
282         # else we are on the last row (cursor has hit the end and reset).
283 }
284
285 # 'once' sections will be shown once unless the corresponding data value
286 # is false.  We check only for false; 0 or '' will not work.
287
288 function tem_auto_once($key, $context) {
289         if($context['data'][$key] !== false)
290                 return tem_data_as_rows(true);
291 }
292
293 # 'evenodd' sections are given an 'evenodd' attribute whose value
294 # alternates between 'even' and 'odd'.
295
296 function tem_auto_evenodd($key, $context) {
297         $rows = $context['data'][$key];
298         $even = 0;
299         $text = array('even', 'odd');
300         foreach($rows as $key => $value) {
301                 $rows[$key]['evenodd'] = $text[$even];
302                 $even = 1 - $even;
303         }
304         return tem_data_as_rows($rows);
305 }
306
307 ?>