JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
silence some notices
[wfpl.git] / template.php
1 <?php
2
3 # This program is in the public domain within the United States. Additionally,
4 # we waive copyright and related rights in the work worldwide through the CC0
5 # 1.0 Universal public domain dedication, which can be found at
6 # http://creativecommons.org/publicdomain/zero/1.0/
7
8
9 # This is a simple template-handling system.  You pass it a big data 
10 # structure with key/value pairs, and a template string to fill out.
11 #
12 # Within a template, it recognizes tags of the form ~name [arg...]~, 
13 # optionally wrapped in HTML comments (which will be removed along with 
14 # the tag markers when the template is filled out).
15 #
16 # { and } as the final argument mark those tags as being the start and 
17 # end of a sub-template (for optional or repeated sections).  All other 
18 # tags represent slots to be directly filled by data values.  On a } 
19 # tag, the name is optional, but must match the corresponding { tag if 
20 # present.
21 #
22 # For a value tag, arguments represent encodings to be applied 
23 # successively.  For instance, ~foo html~ will encode it to be safe in 
24 # HTML ('&' to '&amp;', '<' to '&lt;', and so on).
25 #
26 # { tags can take one argument, which will call the corresponding 
27 # tem_auto_* function to munge the data, automating certain common use 
28 # cases.  See the comments on the tem_auto functions for more details.
29
30 require_once(__DIR__.'/'.'encode.php');
31 require_once(__DIR__.'/'.'file.php');
32 require_once(__DIR__.'/'.'misc.php');
33
34
35 # Top-Level Functions
36 # -------------------
37
38 function template($template, $data) {
39         return fill_template(parse_template($template), $data);
40 }
41
42 function template_file($filename, $data) {
43         return fill_template(parse_template_file($filename), $data);
44 }
45
46 function &parse_template_file($filename) {
47         return parse_template(file_get_contents($filename));
48 }
49
50 # We parse the template string into a tree of strings and sub-templates.
51 # A template is a hash with a name string, a pieces array, and possibly 
52 # an args array.
53
54 function &parse_template($string) {
55         $tem =& tem_push();
56         $tem['pieces'] = array();
57         $matches = preg_split('/(<!--)?(~[^~]*~)(?(1)-->)/', preg_replace('/<!--(~[^~]*~)-->/', '$1', $string), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
58         foreach($matches as $match) {
59                 if($match == '~~') $match = '~';
60                 if(substr($match,0,1) == '~' and strlen($match) > 2) {
61                         $args = explode(' ', substr($match,1,-1));
62
63                         if(count($args) == 1 and $args[0] == '}') $name = '';
64                         else $name = array_shift($args);
65
66                         if(count($args) && $args[count($args)-1] == '{') {  # open block
67                                 array_pop($args);  # drop '{'
68                                 $tem =& tem_push($tem);              # create a new sub-template
69                                 $tem['parent']['pieces'][] =& $tem;  # as a piece of the parent
70                                 $tem['name'] = $name;
71                                 $tem['pieces'] = array();
72                                 $tem['args'] = $args;
73                         } elseif(count($args) && $args[count($args)-1] == '}') {  # close block
74                                 array_pop($args);  # drop '}'
75                                 $cur = $tem['name'];
76                                 if($name && $name != $cur) {
77                                         die("Invalid template: tried to close '$name', but '$cur' is current.");
78                                 }
79                                 $tem =& $tem['parent'];
80                         } else {  # value slot
81                                 $tem['pieces'][] = array('name' => $name, 'args' => $args);
82                         }
83                 } else {  # static string
84                         $tem['pieces'][] = $match;
85                 }
86         }
87         return $tem;
88 }
89
90 function fill_template($template, &$data, &$context = NULL) {
91         $context =& tem_push($context);
92         $context['data'] =& $data;
93         $output = '';
94
95         foreach($template['pieces'] as $tem) {
96                 if(is_string($tem)) $output .= $tem;
97                 elseif(isset($tem['pieces'])) {  # sub-template
98                         $rows =& tem_row_data($tem, $context);
99                         $context['rows'] =& $rows;
100                         foreach($rows as $key => &$row) {
101                                 $context['cur'] = $key;
102                                 $output .= fill_template($tem, $row, $context);
103                         }
104                 } else {  # variable
105                         $output .= tem_encoded_data($tem, $context);
106                 }
107         }
108         $context =& $context['parent'];
109         return $output;
110 }
111
112
113 # Implementation
114 # --------------
115
116
117 # To track our position in the template and in the data, we use a linked 
118 # stack structure.  Each node is a hash with a reference to the parent 
119 # node along with whatever other data you want to add.  For each stack, 
120 # you simply keep a variable with a reference to the top element.  Then 
121 # the push and pop operations are:
122
123 # $top =& tem_push($top);
124 # $top =& $top['parent'];
125
126 function &tem_push(&$stack = NULL) {
127         static $refs = array();
128
129         # Since a PHP reference is *not* a pointer to data, but a pointer to 
130         # a variable (or array slot), we *have* to first put the new node in
131         # $refs, and then reference it from $new.
132
133         $refs[] = array();
134         $new =& $refs[count($refs)-1];
135         if($stack) $new['parent'] =& $stack;
136         return $new;
137 }
138
139 # To fill out a template, we do a depth-first traversal of the template 
140 # tree, replacing all tags with the data values.
141
142 # The data starts out as a nested set of key/value pairs, where the 
143 # values can be:
144
145         # a string to fill a value slot
146         # a hash to fill one instance of a sub-template
147         # an array of hashes to fill multiple instances of a sub-template
148
149 # The middle form will be converted to the last form as we use it.
150
151 function tem_data_as_rows($value, $key) {
152         if(is_array($value)) {
153                 # numeric keys
154                 if(array_key_exists(0, $value)) {
155                         if(is_array($value[0])) return $value;  # already array of hashes.
156                         else return columnize($value, $key);
157                 # key/value pairs -- expand sub-template once.
158                 } else return array($value);
159         } elseif($value || $value === 0 || $value === '0' || $value === '') {
160                 # value -- expand sub-template once using only parent values
161                 return array(array());
162         } else {
163                 # empty value -- don't expand sub-template
164                 return array();
165         }
166 }
167
168 # To look up a key, we check each namespace (starting with the
169 # innermost one) until a value is found.
170
171 function tem_data_scope($key, $context) {
172         static $refs = array();
173
174         $scope = $context;
175         do{
176                 if(array_key_exists($key, $scope['data'])) {
177                         return $scope;
178                 }
179         } while($scope = isset($scope['parent']) ? $scope['parent'] : null);
180
181         # not found; return empty scope.
182         $refs[] = array();
183         $ret = array();
184         $ret['parent'] =& $context;
185         $ret['data'] =& $refs[count($refs) - 1];
186         return $ret;
187 }
188
189 function tem_get_data($key, $context) {
190         $scope = tem_data_scope($key, $context);
191         if($scope) return isset($scope['data'][$key]) ? $scope['data'][$key] : null;
192 }
193
194 # Return the value for a tag as a set of rows to fill a sub-template.
195 # If $tag has an arg, call the tem_auto function to munge the data.
196 function &tem_row_data($tem, $context)
197 {
198         $key = $tem['name'];
199         $scope = tem_data_scope($key, $context);
200         $auto_func = false;
201
202         if(count($tem['args'])) {
203                 $auto_func = "tem_auto_" . $tem['args'][0];
204                 if (!function_exists($auto_func)) {
205                         die("ERROR: template auto function '$auto_func' not found.<br>\n");
206                 }
207                 # NAMESPACIFY $auto_func
208         }
209         $value = isset($scope['data'][$key]) ? $scope['data'][$key] : null;
210         if ($auto_func) {
211                 $value = $auto_func($value, $key, $scope, $tem['args']);
212         }
213
214         $rows = tem_data_as_rows($value, $key);
215         if(is_array($value)) {
216                 $scope['data'][$key] = $rows;
217         }
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)) {
230                         # NAMESPACIFY $func
231                         $value = $func($value, $key);
232                 } else {
233                         die("ERROR: encoder function '$func' not found.<br>\n");
234                 }
235         }
236         return $value;
237 }
238
239
240 function is_sub_template(&$piece) {
241         return is_array($piece) && isset($piece['pieces']);
242 }
243
244 function is_value_slot(&$piece) {
245         return is_array($piece) && !isset($piece['pieces']);
246 }
247
248 # Return a hash containing the top-level sub-templates of tem.
249 function top_sub_templates($tem, $is_sub = 'is_sub_template') {
250         function_exists($is_sub) or die("no such function '$is_sub'.");
251         $subs = array();
252         foreach($tem['pieces'] as $piece) {
253                 if($is_sub($piece)) {
254                         $subs[$piece['name']] = $piece;
255                 }
256         }
257         return $subs;
258 }
259
260 # merge $subs (sub_templates) into variables in $main (template)
261 function merge_sub_templates(&$main, &$subs) {
262         foreach($main['pieces'] as &$piece) {
263                 if(is_array($piece)) { # not just text
264                         if(isset($piece['pieces']) && $piece['pieces']) {
265                                 # a sub-template in main
266                                 merge_sub_templates($piece, $subs);
267                         } else {
268                                 # a value-slot in main
269                                 $sub = isset($subs[$piece['name']]) ? $subs[$piece['name']] : null;
270                                 $arg0 = isset($sub['args'][0]) ? $sub['args'][0] : null;
271                                 if($sub && $arg0 != 'hide') {
272                                         $piece = $subs[$piece['name']];
273                                         $piece['parent'] =& $main;
274                                 }
275                         }
276                 }
277         }
278 }
279
280 # Replace values in $main with top-level templates from $tem.
281 function merge_templates(&$main, &$tem) {
282         $subs = top_sub_templates($tem);
283
284         merge_sub_templates($main, $subs);
285 }
286
287
288
289 # tem_auto functions
290 # ------------------
291 #
292 # If a { tag has an argument, the corresponding tem_auto function is called.
293 # This allows it to mangle the data to automate some common cases.
294
295 # 'sep' (separator) sections will be shown for all but the last parent row.
296 # Sample usage:
297 #       <!--~rows {~-->
298 #               <!--~row {~-->
299 #                       row content...
300 #                       <!--~separator sep {~--><hr><!--~}~-->
301 #               <!--~}~-->
302 #       <!--~}~-->
303 #
304 function tem_auto_sep(&$value, $key, $context) {
305         $rows =& $context['parent']['parent'];
306         if($rows['cur'] != count($rows['rows'])-1)  # last row?
307                 return true;  # show once
308 }
309
310 # auto-show once, only when this is the first row of the parent
311 function tem_auto_last(&$value, $key, $context) {
312         $rows =& $context['parent']['parent'];
313         if($rows['cur'] == count($rows['rows'])-1)  # last row?
314                 return true;  # show once
315 }
316
317 # auto-show once, only when this is the last row of the parent
318 function tem_auto_first(&$value, $key, $context) {
319         $rows =& $context['parent']['parent'];
320         if($rows['cur'] == 0)  # first row?
321                 return true;  # show once
322 }
323
324 # 'show' sections will be shown unless the corresponding data
325 # value === false
326 function tem_auto_show(&$value) {
327         if($value === null) return true;
328         return $value;
329 }
330
331 # 'empty' sections will be shown only if the corresponding data value is the
332 # empty string
333 function tem_auto_empty(&$value) {
334         if($value === '') return true;
335         return null;
336 }
337
338 # 'nonempty' sections will not be shown if the corresponding data
339 # value is the empty string
340 function tem_auto_nonempty(&$value) {
341         if($value === '') return null;
342         return $value;
343 }
344
345 # 'unset' sections will not be shown if the corresponding data
346 # value is not set (opposite of default)
347 function tem_auto_unset(&$value) {
348         if($value === null) {
349                 return '';
350         } else {
351                 return null;
352         }
353 }
354
355 # 'evenodd' sections are given an 'evenodd' attribute whose value
356 # alternates between 'even' and 'odd'.
357 function tem_auto_evenodd(&$values) {
358         $even = true;
359         if($values) foreach($values as &$value) {
360                 $value['evenodd'] = $even ? 'even' : 'odd';
361                 $even = !$even;
362         }
363         return $values;
364 }
365
366 # 'once' sections are shown exactly once if the value is set (and not at all
367 # otherwise.) This is useful when an array value would otherwise cause the
368 # section to be displayed multiple times.
369 function tem_auto_once(&$value) {
370         if($value === null) return null;
371         return true;
372 }
373
374 function tem_auto_once_if(&$value) {
375         if($value) return true;
376         return null;
377 }
378
379 # 'once' sections are shown exactly once if php evaluates the value to false
380 # (and not at all otherwise.) This is useful when an array value would
381 # otherwise cause the section to be displayed multiple times.
382 function tem_auto_once_else(&$value) {
383         if($value) return null;
384         return true;;
385 }
386
387
388
389
390
391 # Backward Compatibility
392 # ----------------------
393
394 function is_shown($piece) {
395         return isset($piece['args'][0]) && $piece['args'][0] == 'hide';
396 }
397
398 function is_shown_sub_template($piece) {
399         return is_sub_template($piece) and is_shown($piece);
400 }
401
402 # Old-style templates don't show unless explicitly requested.
403 function tem_auto_hide(&$value, $key, $context) {
404         unset($context['data'][$key]);
405         return false;
406 }
407
408 # The old API is being used with the named sub-template,
409 # so hide it and insert a value slot for its expansion(s).
410 function &tem_is_old_sub($name, &$template) {
411         foreach($template['pieces'] as $key => &$piece) {
412                 if(is_sub_template($piece)) {
413                         if($piece['name'] == $name) {
414                                 if(!is_shown($piece)) {
415                                         # hide template unless explicitly show()n.
416                                         $piece['args'] = array('hide');
417                                         # insert a value slot with the same name (for the expansion).
418                                         $var = array('name' => $name, 'args' => array());
419                                         array_splice($template['pieces'], $key, 0, array($var));
420                                 }
421                                 return $piece;
422                         }
423                         $tem = tem_is_old_sub($name, $piece);
424                         if($tem) return $tem;
425                 }
426         }
427         $false = false;
428         return $false;
429 }
430
431 class tem {
432         var $template;
433         var $data; 
434
435         function tem() {
436                 $this->template = array('pieces' => array());
437                 $this->data = array();
438         }
439         
440         function set($key, $value = true) {
441                 $this->data[$key] = $value;
442         }
443
444         function sets($hash) {
445                 foreach($hash as $key => $value) {
446                         $this->set($key, $value);
447                 }
448         }
449
450         function append($key, $value) {
451                 if (!isset($this->data[$key])) {
452                         $this->data[$key] = '';
453                 }
454                 $this->data[$key] .= $value;
455         }
456
457         function prepend($key, $value) {
458                 $this->data[$key] = $value . $this->data[$key];
459         }
460
461         function clear($key) {
462                 unset($this->data[$key]);
463         }
464
465         function get($key) {
466                 return $this->data[$key];
467         }
468
469         function show($name) {
470                 $tem = tem_is_old_sub($name, $this->template);
471                 if($tem) {
472                         if (!isset($this->data[$name])) {
473                                 $this->data[$name] = '';
474                         }
475                         $this->data[$name] .= fill_template($tem, $this->data);
476                 }
477         }
478
479         function show_separated($name) {
480                 if($this->get($name)) {
481                         $this->show($name . '_sep');
482                 }
483                 $this->show($name);
484         }
485
486         function load_str($str) {
487                 $this->template =& parse_template($str);
488         }
489
490         function load($filename) {
491                 $this->template =& parse_template_file($filename);
492         }
493
494         function run($tem = false) {
495                 if($tem) {
496                         if(strlen($tem < 150 && file_exists($tem))) $this->load($tem);
497                         else $this->load_str($tem);
498                 }
499
500                 return fill_template($this->template, $this->data);
501         }
502
503         function output($tem = false) {
504                 print($this->run($tem));
505         }
506
507         # merge top-level sub-templates of $tem (object) into $this,
508         # supporting both new and old semantics.
509         function merge($tem) {
510                 # append expansions to $this->data (old style)
511
512                 $subs = $tem->top_subs('is_shown_sub_template');
513                 if($subs) foreach($subs as $name => $val) {
514                         $this->append($name, $val);
515                         unset($tem->data[$name]);  # so array_merge() won't overwrite things
516                 }
517
518                 # merge the data arrays and template trees (new style)
519                 $this->data = array_merge($this->data, $tem->data);
520                 merge_templates($this->template, $tem->template);
521         }
522
523         # see merge() above
524         function merge_file($filename) {
525                 $other_tem = new tem();
526                 $other_tem->load($filename);
527                 $this->merge($other_tem);
528         }
529
530         function top_sub_names($is_sub = 'is_sub_template') {
531                 return array_keys(top_sub_templates($this->template, $is_sub));
532         }
533
534         function top_subs($is_sub = 'is_sub_template') {
535                 $ret = array();
536                 $names = $this->top_sub_names($is_sub);
537                 foreach($names as $name) {
538                         $ret[$name] = $this->get($name);
539                 }
540                 return $ret;
541         }
542
543         # old name for show (deprecated)
544         function sub($name) {
545                 $this->show($name);
546         }
547 }
548
549 function tem_init() {
550         if(!isset($GLOBALS['wfpl_template']) || !$GLOBALS['wfpl_template']) {
551                 $GLOBALS['wfpl_template'] = new tem();
552         }
553 }
554
555 function tem_append($key, $value) {
556         tem_init();
557         $GLOBALS['wfpl_template']->append($key, $value);
558 }
559
560 function tem_prepend($key, $value) {
561         tem_init();
562         $GLOBALS['wfpl_template']->prepend($key, $value);
563 }
564
565 function tem_set($key, $value = true) {
566         tem_init();
567         $GLOBALS['wfpl_template']->set($key, $value);
568 }
569
570 function tem_sets($hash) {
571         tem_init();
572         $GLOBALS['wfpl_template']->sets($hash);
573 }
574
575 function tem_get($key) {
576         tem_init();
577         return $GLOBALS['wfpl_template']->get($key);
578 }
579
580 function tem_run($tem = false) {
581         tem_init();
582         return $GLOBALS['wfpl_template']->run($tem);
583 }
584
585 function tem_show($name) {
586         tem_init();
587         return $GLOBALS['wfpl_template']->show($name);
588 }
589
590 function tem_show_separated($name) {
591         tem_init();
592         $GLOBALS['wfpl_template']->show_separated($name);
593 }
594
595 function tem_load($filename) {
596         tem_init();
597         $GLOBALS['wfpl_template']->load($filename);
598 }
599
600 function tem_merge($tem) {
601         tem_init();
602         $GLOBALS['wfpl_template']->merge($tem);
603 }
604
605 function tem_merge_file($filename) {
606         tem_init();
607         $GLOBALS['wfpl_template']->merge_file($filename);
608 }
609
610 function tem_output($filename = false) {
611         tem_init();
612         $GLOBALS['wfpl_template']->output($filename);
613 }
614
615 function tem_top_subs() {
616         tem_init();
617         return $GLOBALS['wfpl_template']->top_subs();
618 }
619
620 function tem_top_sub_names() {
621         tem_init();
622         return $GLOBALS['wfpl_template']->top_sub_names();
623 }
624
625 function tem_load_new($filename) {
626         $old = isset($GLOBALS['wfpl_template']) ? $GLOBALS['wfpl_template'] : null;
627         $GLOBALS['wfpl_template'] = new tem();
628         $GLOBALS['wfpl_template']->load($filename);
629         return $old;
630 }
631
632 # deprecated (old name for show)
633 function tem_sub($name) {
634         tem_show($name);
635 }