JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
clean up my urls
[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(__DIR__.'/'.'encode.php');
41 require_once(__DIR__.'/'.'file.php');
42 require_once(__DIR__.'/'.'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, $key) {
161         if(is_array($value)) {
162                 # numeric keys
163                 if(array_key_exists(0, $value)) {
164                         if(is_array($value[0])) return $value;  # already array of hashes.
165                         else return columnize($value, $key);
166                 # key/value pairs -- expand sub-template once.
167                 } else return array($value);
168         } elseif($value || $value === 0 || $value === '0' || $value === '') {
169                 # value -- expand sub-template once using only parent values
170                 return array(array());
171         } else {
172                 # empty value -- don't expand sub-template
173                 return array();
174         }
175 }
176
177 # To look up a key, we check each namespace (starting with the
178 # innermost one) until a value is found.
179
180 function tem_data_scope($key, $context) {
181         static $refs = array();
182
183         $scope = $context;
184         do{
185                 if(array_key_exists($key, $scope['data'])) {
186                         return $scope;
187                 }
188         } while($scope = $scope['parent']);
189
190         # not found; return empty scope.
191         $refs[] = array();
192         $ret = array();
193         $ret['parent'] =& $context;
194         $ret['data'] =& last($refs);
195         return $ret;
196 }
197
198 function tem_get_data($key, $context) {
199         $scope = tem_data_scope($key, $context);
200         if($scope) return $scope['data'][$key];
201 }
202
203 # Return the value for a tag as a set of rows to fill a sub-template.
204 # If $tag has an arg, call the tem_auto function to munge the data.
205 function &tem_row_data($tem, $context)
206 {
207         $key = $tem['name'];
208         $scope = tem_data_scope($key, $context);
209
210         if(count($tem['args'])) {
211                 $auto_func = "tem_auto_" . $tem['args'][0];
212                 if (!function_exists($auto_func)) {
213                         die("ERROR: template auto function '$auto_func' not found.<br>\n");
214                 }
215                 # NAMESPACIFY $auto_func
216         }
217         if ($auto_func) {
218                 $value = $auto_func($scope['data'][$key], $key, $scope, $tem['args']);
219         }
220         else $value = $scope['data'][$key];
221
222         $rows = tem_data_as_rows($value, $key);
223         if(is_array($value)) $scope['data'][$key] = $rows;
224
225         return $rows;
226 }
227
228 # Return the value for a tag as an encoded string.
229 function tem_encoded_data($tag, $context)
230 {
231         $key = $tag['name'];
232         $value = tem_get_data($key, $context);
233         foreach($tag['args'] as $encoding) {
234                 $func = "enc_$encoding";
235                 if (function_exists($func)) {
236                         # NAMESPACIFY $func
237                         $value = $func($value, $key);
238                 } else {
239                         die("ERROR: encoder function '$func' not found.<br>\n");
240                 }
241         }
242         return $value;
243 }
244
245
246 function is_sub_template(&$piece) {
247         return is_array($piece) and $piece['pieces'];
248 }
249
250 function is_value_slot(&$piece) {
251         return is_array($piece) and !$piece['pieces'];
252 }
253
254 # Return a hash containing the top-level sub-templates of tem.
255 function top_sub_templates($tem, $is_sub = 'is_sub_template') {
256         function_exists($is_sub) or die("no such function '$is_sub'.");
257         $subs = array();
258         foreach($tem['pieces'] as $piece) {
259                 if($is_sub($piece)) {
260                         $subs[$piece['name']] = $piece;
261                 }
262         }
263         return $subs;
264 }
265
266 # merge $subs (sub_templates) into variables in $main (template)
267 function merge_sub_templates(&$main, &$subs) {
268         foreach($main['pieces'] as &$piece) {
269                 if(is_array($piece)) { # not just text
270                         if($piece['pieces']) {
271                                 # a sub-template in main
272                                 merge_sub_templates($piece, $subs);
273                         } else {
274                                 # a value-slot in main
275                                 $sub = $subs[$piece['name']];
276                                 if($sub and $sub['args'][0] != 'hide') {
277                                         $piece = $subs[$piece['name']];
278                                         $piece['parent'] =& $main;
279                                 }
280                         }
281                 }
282         }
283         return $out;
284 }
285
286 # Replace values in $main with top-level templates from $tem.
287 function merge_templates(&$main, &$tem) {
288         $subs = top_sub_templates($tem);
289
290         merge_sub_templates($main, $subs);
291 }
292
293
294
295 # tem_auto functions
296 # ------------------
297 #
298 # If a { tag has an argument, the corresponding tem_auto function is called.
299 # This allows it to mangle the data to automate some common cases.
300
301 # 'sep' (separator) sections will be shown for all but the last parent row.
302 # Sample usage:
303 #       <!--~rows {~-->
304 #               <!--~row {~-->
305 #                       row content...
306 #                       <!--~separator sep {~--><hr><!--~}~-->
307 #               <!--~}~-->
308 #       <!--~}~-->
309 #
310 function tem_auto_sep(&$value, $key, $context) {
311         $rows =& $context['parent']['parent'];
312         if($rows['cur'] != count($rows['rows'])-1)  # last row?
313                 return true;  # show once
314 }
315
316 # auto-show once, only when this is the first row of the parent
317 function tem_auto_last(&$value, $key, $context) {
318         $rows =& $context['parent']['parent'];
319         if($rows['cur'] == count($rows['rows'])-1)  # last row?
320                 return true;  # show once
321 }
322
323 # auto-show once, only when this is the last row of the parent
324 function tem_auto_first(&$value, $key, $context) {
325         $rows =& $context['parent']['parent'];
326         if($rows['cur'] == 0)  # first row?
327                 return true;  # show once
328 }
329
330 # 'show' sections will be shown unless the corresponding data
331 # value === false
332 function tem_auto_show(&$value) {
333         if($value === null) return true;
334         return $value;
335 }
336
337 # 'empty' sections will be shown only if the corresponding data value is the
338 # empty string
339 function tem_auto_empty(&$value) {
340         if($value === '') return true;
341         return null;
342 }
343
344 # 'nonempty' sections will not be shown if the corresponding data
345 # value is the empty string
346 function tem_auto_nonempty(&$value) {
347         if($value === '') return null;
348         return $value;
349 }
350
351 # 'unset' sections will not be shown if the corresponding data
352 # value is not set (opposite of default)
353 function tem_auto_unset(&$value) {
354         if($value === null) {
355                 return '';
356         } else {
357                 return null;
358         }
359 }
360
361 # 'evenodd' sections are given an 'evenodd' attribute whose value
362 # alternates between 'even' and 'odd'.
363 function tem_auto_evenodd(&$values) {
364         $even = true;
365         if($values) foreach($values as &$value) {
366                 $value['evenodd'] = $even ? 'even' : 'odd';
367                 $even = !$even;
368         }
369         return $values;
370 }
371
372 # 'once' sections are shown exactly once if the value is set (and not at all
373 # otherwise.) This is useful when an array value would otherwise cause the
374 # section to be displayed multiple times.
375 function tem_auto_once(&$value) {
376         if($value === null) return null;
377         return true;
378 }
379
380 function tem_auto_once_if(&$value) {
381         if($value) return true;
382         return null;
383 }
384
385 # 'once' sections are shown exactly once if php evaluates the value to false
386 # (and not at all otherwise.) This is useful when an array value would
387 # otherwise cause the section to be displayed multiple times.
388 function tem_auto_once_else(&$value) {
389         if($value) return null;
390         return true;;
391 }
392
393
394
395
396
397 # Backward Compatibility
398 # ----------------------
399
400 function is_shown($piece) {
401         return $piece['args'][0] == 'hide';
402 }
403
404 function is_shown_sub_template($piece) {
405         return is_sub_template($piece) and is_shown($piece);
406 }
407
408 # Old-style templates don't show unless explicitly requested.
409 function tem_auto_hide(&$value, $key, $context) {
410         unset($context['data'][$key]);
411         return false;
412 }
413
414 # The old API is being used with the named sub-template,
415 # so hide it and insert a value slot for its expansion(s).
416 function &tem_is_old_sub($name, &$template) {
417         foreach($template['pieces'] as $key => &$piece) {
418                 if(is_sub_template($piece)) {
419                         if($piece['name'] == $name) {
420                                 if(!is_shown($piece)) {
421                                         # hide template unless explicitly show()n.
422                                         $piece['args'] = array('hide');
423                                         # insert a value slot with the same name (for the expansion).
424                                         $var = array('name' => $name, 'args' => array());
425                                         array_splice($template['pieces'], $key, 0, array($var));
426                                 }
427                                 return $piece;
428                         }
429                         $tem = tem_is_old_sub($name, $piece);
430                         if($tem) return $tem;
431                 }
432         }
433         return false;
434 }
435
436 class tem {
437         var $template;
438         var $data; 
439
440         function tem() {
441                 $this->template = array('pieces' => array());
442                 $this->data = array();
443         }
444         
445         function set($key, $value = true) {
446                 $this->data[$key] = $value;
447         }
448
449         function sets($hash) {
450                 foreach($hash as $key => $value) {
451                         $this->set($key, $value);
452                 }
453         }
454
455         function append($key, $value) {
456                 $this->data[$key] .= $value;
457         }
458
459         function prepend($key, $value) {
460                 $this->data[$key] = $value . $this->data[$key];
461         }
462
463         function clear($key) {
464                 unset($this->data[$key]);
465         }
466
467         function get($key) {
468                 return $this->data[$key];
469         }
470
471         function show($name) {
472                 $tem = tem_is_old_sub($name, $this->template);
473                 if($tem) {
474                         $this->data[$name] .= fill_template($tem, $this->data);
475                 }
476         }
477
478         function show_separated($name) {
479                 if($this->get($name)) {
480                         $this->show($name . '_sep');
481                 }
482                 $this->show($name);
483         }
484
485         function load_str($str) {
486                 $this->template =& parse_template($str);
487         }
488
489         function load($filename) {
490                 $this->template =& parse_template_file($filename);
491         }
492
493         function run($tem = false) {
494                 if($tem) {
495                         if(strlen($tem < 150 && file_exists($tem))) $this->load($tem);
496                         else $this->load_str($tem);
497                 }
498
499                 return fill_template($this->template, $this->data);
500         }
501
502         function output($tem = false) {
503                 print($this->run($tem));
504         }
505
506         # merge top-level sub-templates of $tem (object) into $this,
507         # supporting both new and old semantics.
508         function merge($tem) {
509                 # append expansions to $this->data (old style)
510
511                 $subs = $tem->top_subs('is_shown_sub_template');
512                 if($subs) foreach($subs as $name => $val) {
513                         $this->append($name, $val);
514                         unset($tem->data[$name]);  # so array_merge() won't overwrite things
515                 }
516
517                 # merge the data arrays and template trees (new style)
518                 $this->data = array_merge($this->data, $tem->data);
519                 merge_templates($this->template, $tem->template);
520         }
521
522         # see merge() above
523         function merge_file($filename) {
524                 $other_tem = new tem();
525                 $other_tem->load($filename);
526                 $this->merge($other_tem);
527         }
528
529         function top_sub_names($is_sub = 'is_sub_template') {
530                 return array_keys(top_sub_templates($this->template, $is_sub));
531         }
532
533         function top_subs($is_sub = 'is_sub_template') {
534                 $ret = array();
535                 $names = $this->top_sub_names($is_sub);
536                 foreach($names as $name) {
537                         $ret[$name] = $this->get($name);
538                 }
539                 return $ret;
540         }
541
542         # old name for show (deprecated)
543         function sub($name) {
544                 $this->show($name);
545         }
546 }
547
548 function tem_init() {
549         if(!$GLOBALS['wfpl_template']) {
550                 $GLOBALS['wfpl_template'] = new tem();
551         }
552 }
553
554 function tem_append($key, $value) {
555         tem_init();
556         $GLOBALS['wfpl_template']->append($key, $value);
557 }
558
559 function tem_prepend($key, $value) {
560         tem_init();
561         $GLOBALS['wfpl_template']->prepend($key, $value);
562 }
563
564 function tem_set($key, $value = true) {
565         tem_init();
566         $GLOBALS['wfpl_template']->set($key, $value);
567 }
568
569 function tem_sets($hash) {
570         tem_init();
571         $GLOBALS['wfpl_template']->sets($hash);
572 }
573
574 function tem_get($key) {
575         tem_init();
576         return $GLOBALS['wfpl_template']->get($key);
577 }
578
579 function tem_run($tem = false) {
580         tem_init();
581         return $GLOBALS['wfpl_template']->run($tem);
582 }
583
584 function tem_show($name) {
585         tem_init();
586         return $GLOBALS['wfpl_template']->show($name);
587 }
588
589 function tem_show_separated($name) {
590         tem_init();
591         $GLOBALS['wfpl_template']->show_separated($name);
592 }
593
594 function tem_load($filename) {
595         tem_init();
596         $GLOBALS['wfpl_template']->load($filename);
597 }
598
599 function tem_merge($tem) {
600         tem_init();
601         $GLOBALS['wfpl_template']->merge($tem);
602 }
603
604 function tem_merge_file($filename) {
605         tem_init();
606         $GLOBALS['wfpl_template']->merge_file($filename);
607 }
608
609 function tem_output($filename = false) {
610         tem_init();
611         $GLOBALS['wfpl_template']->output($filename);
612 }
613
614 function tem_top_subs() {
615         tem_init();
616         return $GLOBALS['wfpl_template']->top_subs();
617 }
618
619 function tem_top_sub_names() {
620         tem_init();
621         return $GLOBALS['wfpl_template']->top_sub_names();
622 }
623
624 function tem_load_new($filename) {
625         $old = $GLOBALS['wfpl_template'];
626         $GLOBALS['wfpl_template'] = new tem();
627         $GLOBALS['wfpl_template']->load($filename);
628         return $old;
629 }
630
631 # deprecated (old name for show)
632 function tem_sub($name) {
633         tem_show($name);
634 }
635
636 ?>