JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
added tem_auto_last() and tem_auto_first()
[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 # We parse the template string into a tree of strings and sub-templates.
61 # A template is a hash with a name string, a pieces array, and possibly 
62 # an args array.
63
64 function parse_template($string) {
65         $tem =& tem_push();
66         $tem['pieces'] = array();
67         # note: for some reason this captures '<!--' but not '-->'.
68         $matches = preg_split("/(<!--)?(~[^~]*~)(?(1)-->)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
69         foreach($matches as $match) {
70                 if($match == '~~') $match = '~';
71                 if(substr($match,0,1) == '~' and strlen($match) > 2) {
72                         $args = explode(' ', substr($match,1,-1));
73
74                         if(count($args) == 1 and $args[0] == '}') $name = '';
75                         else $name = array_shift($args);
76
77                         if(last($args) == '{') {  # open block
78                                 array_pop($args);  # drop '{'
79                                 $tem =& tem_push($tem);              # create a new sub-template
80                                 $tem['parent']['pieces'][] =& $tem;  # as a piece of the parent
81                                 $tem['name'] = $name;
82                                 $tem['pieces'] = array();
83                                 $tem['args'] = $args;
84                         } elseif(last($args) == '}') {  # close block
85                                 array_pop($args);  # drop '}'
86                                 $cur = $tem['name'];
87                                 if($name && $name != $cur) {
88                                         die("Invalid template: tried to close '$name', but '$cur' is current.");
89                                 }
90                                 $tem =& $tem['parent'];
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 function fill_template($template, &$data, &$context = NULL) {
102         $context =& tem_push($context);
103         $context['data'] =& $data;
104
105         foreach($template['pieces'] as $tem) {
106                 if(is_string($tem)) $output .= $tem;
107                 elseif($tem['pieces']) {  # sub-template
108                         $rows =& tem_row_data($tem, $context);
109                         $context['rows'] =& $rows;
110                         foreach($rows as $key => &$row) {
111                                 $context['cur'] = $key;
112                                 $output .= fill_template($tem, $row, $context);
113                         }
114                 } else {  # variable
115                         $output .= tem_encoded_data($tem, $context);
116                 }
117         }
118         $context =& $context['parent'];
119         return $output;
120 }
121
122
123 # Implementation
124 # --------------
125
126
127 # To track our position in the template and in the data, we use a linked 
128 # stack structure.  Each node is a hash with a reference to the parent 
129 # node along with whatever other data you want to add.  For each stack, 
130 # you simply keep a variable with a reference to the top element.  Then 
131 # the push and pop operations are:
132
133 # $top =& tem_push($top);
134 # $top =& $top['parent'];
135
136 function &tem_push(&$stack = NULL) {
137         static $refs = array();
138
139         # Since a PHP reference is *not* a pointer to data, but a pointer to 
140         # a variable (or array slot), we *have* to first put the new node in
141         # $refs, and then reference it from $new.
142
143         $refs[] = array();
144         $new =& $refs[count($refs)-1];
145         if($stack) $new['parent'] =& $stack;
146         return $new;
147 }
148
149 # To fill out a template, we do a depth-first traversal of the template 
150 # tree, replacing all tags with the data values.
151
152 # The data starts out as a nested set of key/value pairs, where the 
153 # values can be:
154
155         # a string to fill a value slot
156         # a hash to fill one instance of a sub-template
157         # an array of hashes to fill multiple instances of a sub-template
158
159 # The middle form will be converted to the last form as we use it.
160
161 function tem_data_as_rows($value) {
162         if(is_array($value)) {
163                 # numeric keys, is already array of arrays -- expand sub-template for each.
164                 if(array_key_exists(0, $value)) return $value;
165                 # key/value pairs -- expand sub-template once.
166                 else return array($value);
167         } elseif($value) {
168                 # value -- expand sub-template once using only parent values
169                 return array(array());
170         } else {
171                 # empty value -- don't expand sub-template
172                 return array();
173         }
174 }
175
176 # To look up a key, we check each namespace (starting with the
177 # innermost one) until a value is found.
178
179 function tem_data_scope($key, $context) {
180         static $refs = array();
181
182         $scope = $context;
183         do{
184                 if(array_key_exists($key, $scope['data'])) {
185                         return $scope;
186                 }
187         } while($scope = $scope['parent']);
188
189         # not found; return empty scope.
190         $refs[] = array();
191         $ret = array();
192         $ret['parent'] =& $context;
193         $ret['data'] =& last($refs);
194         return $ret;
195 }
196
197 function tem_get_data($key, $context) {
198         $scope = tem_data_scope($key, $context);
199         if($scope) return $scope['data'][$key];
200 }
201
202 # Return the value for a tag as a set of rows to fill a sub-template.
203 # If $tag has an arg, call the tem_auto function to munge the data.
204 function &tem_row_data($tem, $context)
205 {
206         $key = $tem['name'];
207         $scope = tem_data_scope($key, $context);
208
209         if(count($tem['args'])) {
210                 $auto_func = "tem_auto_" . $tem['args'][0];
211                 function_exists($auto_func)
212                         or die("ERROR: template auto function '$auto_func' not found.<br>\n");
213         }
214         if($auto_func) $value = $auto_func($scope['data'][$key], $key, $scope);
215         else $value = $scope['data'][$key];
216
217         $rows = tem_data_as_rows($value);
218         if(is_array($value)) $scope['data'][$key] = $rows;
219
220         return $rows;
221 }
222
223 # Return the value for a tag as an encoded string.
224 function tem_encoded_data($tag, $context)
225 {
226         $key = $tag['name'];
227         $value = tem_get_data($key, $context);
228         foreach($tag['args'] as $encoding) {
229                 $func = "enc_$encoding";
230                 if(function_exists($func)) $value = $func($value, $key);
231                 else die("ERROR: encoder function '$func' not found.<br>\n");
232         }
233         return $value;
234 }
235
236
237 function is_sub_template($piece) {
238         return is_array($piece) and $piece['pieces'];
239 }
240
241 # Return a hash containing the top-level sub-templates of tem.
242 function top_sub_templates($tem, $is_sub = 'is_sub_template') {
243         function_exists($is_sub) or die("no such function '$is_sub'.");
244         $subs = array();
245         foreach($tem['pieces'] as $piece) {
246                 if($is_sub($piece)) {
247                         $subs[$piece['name']] = $piece;
248                 }
249         }
250         return $subs;
251 }
252
253 # Replace top-level values in $main with top-level templates from $tem.
254 function merge_templates($main, $tem) {
255         $out = array('name' => $main['name'], 'pieces' => array());
256
257         $subs = top_sub_templates($tem);
258
259         foreach($main['pieces'] as $piece) {
260                 $sub = $subs[$piece['name']];
261                 if(is_array($piece) and !$piece['pieces'] and $sub and $sub['args'][0] != 'hide') {
262                         $piece = $subs[$piece['name']];
263                 }
264                 $out['pieces'][] = $piece;
265         }
266         return $out;
267 }
268
269
270
271 # tem_auto functions
272 # ------------------
273 #
274 # If a { tag has an argument, the corresponding tem_auto function is called.
275 # This allows it to mangle the data to automate some common cases.
276
277 # 'sep' (separator) sections will be shown for all but the last parent row.
278 # Sample usage:
279 #       <!--~rows {~-->
280 #               <!--~row {~-->
281 #                       row content...
282 #                       <!--~separator sep {~--><hr><!--~}~-->
283 #               <!--~}~-->
284 #       <!--~}~-->
285 #
286 function tem_auto_sep(&$value, $key, $context) {
287         $rows =& $context['parent']['parent'];
288         if($rows['cur'] != count($rows['rows'])-1)  # last row?
289                 return $value = true;  # show once
290 }
291
292 # auto-show once, only when this is the first row of the parent
293 function tem_auto_last(&$value, $key, $context) {
294         $rows =& $context['parent']['parent'];
295         if($rows['cur'] == count($rows['rows'])-1)  # last row?
296                 return $value = true;  # show once
297 }
298
299 # auto-show once, only when this is the last row of the parent
300 function tem_auto_first(&$value, $key, $context) {
301         $rows =& $context['parent']['parent'];
302         if($rows['cur'] == 0)  # first row?
303                 return $value = true;  # show once
304 }
305
306 # 'show' sections will be shown unless the corresponding data value
307 # is false (only false, not 0 or '' or array()).
308
309 function tem_auto_show(&$value) {
310         if($value !== false) $value = array(array());
311         return $value;
312 }
313
314 # 'evenodd' sections are given an 'evenodd' attribute whose value
315 # alternates between 'even' and 'odd'.
316
317 function tem_auto_evenodd(&$values) {
318         $even = true;
319         if($values) foreach($values as &$value) {
320                 $value['evenodd'] = $even ? 'even' : 'odd';
321                 $even = !$even;
322         }
323         return $values;
324 }
325
326
327
328
329
330 # Backward Compatibility
331 # ----------------------
332
333 function is_shown($piece) {
334         return $piece['args'][0] == 'hide';
335 }
336
337 function is_shown_sub_template($piece) {
338         return is_sub_template($piece) and is_shown($piece);
339 }
340
341 # Old-style templates don't show unless explicitly requested.
342 function tem_auto_hide(&$value, $key, $context) {
343         unset($context['data'][$key]);
344         return false;
345 }
346
347 # The old API is being used with the named sub-template,
348 # so hide it and insert a value slot for its expansion(s).
349 function &tem_is_old_sub($name, &$template) {
350         foreach($template['pieces'] as $key => &$piece) {
351                 if(is_sub_template($piece)) {
352                         if($piece['name'] == $name) {
353                                 if(!is_shown($piece)) {
354                                         # hide template unless explicitly show()n.
355                                         $piece['args'] = array('hide');
356                                         # insert a value slot with the same name (for the expansion).
357                                         $var = array('name' => $name, 'args' => array());
358                                         array_splice($template['pieces'], $key, 0, array($var));
359                                 }
360                                 return $piece;
361                         }
362                         $tem = tem_is_old_sub($name, $piece);
363                         if($tem) return $tem;
364                 }
365         }
366         return false;
367 }
368
369 class tem {
370         var $template;
371         var $data; 
372
373         function tem() {
374                 $this->template = array('pieces' => array());
375                 $this->data = array();
376         }
377         
378         function set($key, $value) {
379                 $this->data[$key] = $value;
380         }
381
382         function append($key, $value) {
383                 $this->data[$key] .= $value;
384         }
385
386         function prepend($key, $value) {
387                 $this->data[$key] = $value . $this->data[$key];
388         }
389
390         function clear($key) {
391                 unset($this->data[$key]);
392         }
393
394         function get($key) {
395                 return $this->data[$key];
396         }
397
398         function show($name) {
399                 $tem = tem_is_old_sub($name, $this->template);
400                 if($tem) {
401                         $this->data[$name] .= fill_template($tem, $this->data);
402                 }
403         }
404
405         function show_separated($name) {
406                 if($this->get($name)) {
407                         $this->show($name . '_sep');
408                 }
409                 $this->show($name);
410         }
411
412         function load_str($str) {
413                 $this->template = parse_template($str);
414         }
415
416         function load($filename) {
417                 $this->template = parse_template_file($filename);
418         }
419
420         function run($tem = false) {
421                 if($tem) {
422                         if(strlen($tem < 150 && file_exists($tem))) $this->load($tem);
423                         else $this->load_str($tem);
424                 }
425
426                 return fill_template($this->template, $this->data);
427         }
428
429         function output($tem = false) {
430                 print($this->run($tem));
431         }
432
433         # merge top-level sub-templates of $tem (object) into $this,
434         # supporting both new and old semantics.
435         function merge($tem) {
436                 # append expansions to $this->data (old style)
437
438                 $subs = $tem->top_subs('is_shown_sub_template');
439                 if($subs) foreach($subs as $name => $val) {
440                         $this->append($name, $val);
441                         unset($tem->data[$name]);  # so array_merge() won't overwrite things
442                 }
443
444                 # merge the data arrays and template trees (new style)
445                 $this->data = array_merge($this->data, $tem->data);
446                 $this->template = merge_templates($this->template, $tem->template);
447         }
448
449         function top_sub_names($is_sub = 'is_sub_template') {
450                 return array_keys(top_sub_templates($this->template, $is_sub));
451         }
452
453         function top_subs($is_sub = 'is_sub_template') {
454                 $ret = array();
455                 $names = $this->top_sub_names($is_sub);
456                 foreach($names as $name) {
457                         $ret[$name] = $this->get($name);
458                 }
459                 return $ret;
460         }
461
462         # old name for show (deprecated)
463         function sub($name) {
464                 $this->show($name);
465         }
466 }
467
468 function tem_init() {
469         if(!$GLOBALS['wfpl_template']) {
470                 $GLOBALS['wfpl_template'] = new tem();
471         }
472 }
473
474 function tem_append($key, $value) {
475         tem_init();
476         $GLOBALS['wfpl_template']->append($key, $value);
477 }
478
479 function tem_prepend($key, $value) {
480         tem_init();
481         $GLOBALS['wfpl_template']->prepend($key, $value);
482 }
483
484 function tem_set($key, $value) {
485         tem_init();
486         $GLOBALS['wfpl_template']->set($key, $value);
487 }
488
489 function tem_get($key) {
490         tem_init();
491         return $GLOBALS['wfpl_template']->get($key);
492 }
493
494 function tem_run($tem = false) {
495         tem_init();
496         return $GLOBALS['wfpl_template']->run($tem);
497 }
498
499 function tem_show($name) {
500         tem_init();
501         return $GLOBALS['wfpl_template']->show($name);
502 }
503
504 function tem_show_separated($name) {
505         tem_init();
506         $GLOBALS['wfpl_template']->show_separated($name);
507 }
508
509 function tem_load($filename) {
510         tem_init();
511         $GLOBALS['wfpl_template']->load($filename);
512 }
513
514 function tem_output($filename = false) {
515         tem_init();
516         $GLOBALS['wfpl_template']->output($filename);
517 }
518
519 function tem_top_subs() {
520         tem_init();
521         return $GLOBALS['wfpl_template']->top_subs();
522 }
523
524 function tem_top_sub_names() {
525         tem_init();
526         return $GLOBALS['wfpl_template']->top_sub_names();
527 }
528
529 function tem_load_new($filename) {
530         $old = $GLOBALS['wfpl_template'];
531         $GLOBALS['wfpl_template'] = new tem();
532         $GLOBALS['wfpl_template']->load($filename);
533         return $old;
534 }
535
536 # deprecated (old name for show)
537 function tem_sub($name) {
538         tem_show($name);
539 }
540
541 ?>