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