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