JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
upload.php cleanup: really don't make dot files
[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         return false;
428 }
429
430 class tem {
431         var $template;
432         var $data; 
433
434         function tem() {
435                 $this->template = array('pieces' => array());
436                 $this->data = array();
437         }
438         
439         function set($key, $value = true) {
440                 $this->data[$key] = $value;
441         }
442
443         function sets($hash) {
444                 foreach($hash as $key => $value) {
445                         $this->set($key, $value);
446                 }
447         }
448
449         function append($key, $value) {
450                 if (!isset($this->data[$key])) {
451                         $this->data[$key] = '';
452                 }
453                 $this->data[$key] .= $value;
454         }
455
456         function prepend($key, $value) {
457                 $this->data[$key] = $value . $this->data[$key];
458         }
459
460         function clear($key) {
461                 unset($this->data[$key]);
462         }
463
464         function get($key) {
465                 return $this->data[$key];
466         }
467
468         function show($name) {
469                 $tem = tem_is_old_sub($name, $this->template);
470                 if($tem) {
471                         if (!isset($this->data[$name])) {
472                                 $this->data[$name] = '';
473                         }
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 = isset($GLOBALS['wfpl_template']) ? $GLOBALS['wfpl_template'] : null;
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 ?>