JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
* template.php: doc fixes.
[wfpl.git] / template.php
1 <?php
2
3 #  Copyright (C) 2008,2009 Joshua Grams <josh@qualdan.com>
4 #
5 #  This program is free software: you can redistribute it and/or modify
6 #  it under the terms of the GNU General Public License as published by
7 #  the Free Software Foundation, either version 3 of the License, or
8 #  (at your option) any later version.
9 #  
10 #  This program is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #  GNU General Public License for more details.
14 #  
15 #  You should have received a copy of the GNU General Public License
16 #  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18
19 # This is a simple template-handling system.  You pass it a big data 
20 # structure with key/value pairs, and a template string to fill out.
21 #
22 # Within a template, it recognizes tags of the form ~name [arg...]~, 
23 # optionally wrapped in HTML comments (which will be removed along with 
24 # the tag markers when the template is filled out).
25 #
26 # { and } as the final argument mark those tags as being the start and 
27 # end of a sub-template (for optional or repeated sections).  All other 
28 # tags represent slots to be directly filled by data values.  On a } 
29 # tag, the name is optional, but must match the corresponding { tag if 
30 # present.
31 #
32 # For a value tag, arguments represent encodings to be applied 
33 # successively.  For instance, ~foo html~ will encode it to be safe in 
34 # HTML ('&' to '&amp;', '<' to '&lt;', and so on).
35 #
36 # { tags can take one argument, which will call the corresponding 
37 # tem_auto_* function to munge the data, automating certain common use 
38 # cases.  See the comments on the tem_auto functions for more details.
39
40 require_once('code/wfpl/encode.php');
41 require_once('code/wfpl/file.php');
42 require_once('code/wfpl/misc.php');
43
44
45 # Public functions
46 # ----------------
47
48 function template($data, $template) {
49         return fill_template($data, parse_template($template));
50 }
51
52 function template_file($data, $filename) {
53         return fill_template($data, parse_template_file($filename));
54 }
55
56 function parse_template_file($filename) {
57         return parse_template(file_get_contents($filename));
58 }
59
60 # First we take the template string and convert it into a tree of
61 # strings and sub-templates.  A template is a hash with a name string,
62 # a pieces array, and possibly an args array.
63
64 function parse_template($string) {
65         # Don't mess with the $stack/$tem assignments!  Since
66         # PHP references point to the variable, not the data,
67         # it really does have to be written exactly like this.
68         $stack[] = array('name' => 'root', 'pieces' => array());
69         $tem = &last($stack);
70         # note: for some reason this captures '<!--' but not '-->'.
71         $matches = preg_split("/(<!--)?(~[^~]*~)(?(1)-->)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
72         foreach($matches as $match) {
73                 if(substr($match,0,1) == '~') {
74                         $args = explode(' ', substr($match,1,-1));
75
76                         if(count($args) == 1 and $args[0] == '}') $name = '';
77                         else $name = array_shift($args);
78
79                         if(last($args) == '{') {  # open block
80                                 array_pop($args);
81                                 $stack[] = array('name' => $name, 'pieces' => array(), 'args' => $args);
82                                 $tem['pieces'][] = &last($stack);
83                                 $tem = &last($stack);
84                         } elseif(last($args) == '}') {  # close block
85                                 array_pop($args);
86                                 $cur = $stack[count($stack)-1]['name'];
87                                 if($name && $name != $cur) {
88                                         die("Invalid template: tried to close '$name', but '$cur' is current.");
89                                 }
90                                 array_pop($stack); $tem = &last($stack);
91                         } else {  # value slot
92                                 $tem['pieces'][] = array('name' => $name, 'args' => $args);
93                         }
94                 } elseif($match and $match != '<!--') {  # static string
95                         $tem['pieces'][] = $match;
96                 }
97         }
98         return $tem;
99 }
100
101 # Then we do a depth-first traversal of the template tree,
102 # replacing all tags with the data values.
103
104 function fill_template($data, $template, $context = NULL, $keychain = NULL) {
105         $context[] = $data;
106         foreach($template['pieces'] as $piece) {
107                 if(is_string($piece)) $output .= $piece;
108                 else {
109                         if($piece['pieces']) {  # sub-template
110                                 $keychain[] = $piece['name'];
111                                 $rows = tem_get_rows($piece, $context, $keychain);
112                                 foreach($rows as $key => $row) {
113                                         $keychain[] = $key;
114                                         $output .= fill_template($row, $piece, $context, $keychain);
115                                         array_pop($keychain);
116                                 }
117                                 array_pop($keychain);
118                         } else {  # variable
119                                 $output .= tem_get_enc($piece, $context);
120                         }
121                 }
122         }
123         return $output;
124 }
125
126
127 # Replace top-level values in $main with top-level templates from $tem.
128 function merge_templates($main, $tem) {
129         $out = array('name' => $main['name'], 'pieces' => array());
130
131         $subs = top_sub_templates($tem);
132
133         foreach($main['pieces'] as $piece) {
134                 if(is_array($piece) and !$piece['pieces'] and $subs[$piece['name']]) {
135                         $piece = $subs[$piece['name']];
136                 }
137                 $out['pieces'][] = $piece;
138         }
139         return $out;
140 }
141
142
143
144 # tem_auto functions
145 # ------------------
146 #
147 # If a { tag has an argument, the corresponding tem_auto function is called.
148 # This allows it to mangle the data to automate some common cases.
149
150 # 'sep' (separator) sections will be shown for all but the last parent row.
151 # Sample usage:
152 #       <!--~rows~-->
153 #               <!--~row~-->
154 #                       row content...
155 #                       <!--~separator sep {~--><hr><!--~separator }"-->
156 #               <!--~row~-->
157 #       <!--~rows~-->
158 #
159 function tem_auto_sep($piece, $context, $keychain) {
160         list($name, $index, $this_name) = array_slice($keychain, -3);
161         $array = tem_get($name, $context);
162         if($index != count($array)-1) return true;
163 }
164
165 # 'once' sections will be shown once unless the corresponding data value
166 # is false.  We check only for false; 0 or '' will not work.
167
168 function tem_auto_once($piece, $context, $keychain) {
169         $value = tem_get(array_pop($keychain), $context);
170         if($value !== false) return true;
171 }
172
173 # 'evenodd' sections are given an 'evenodd' attribute whose value
174 # alternates between 'even' and 'odd'.
175
176 function tem_auto_evenodd($piece, $context, $keychain) {
177         $rows = tem_get(array_pop($keychain), $context);
178         $even = 0;
179         $text = array('even', 'odd');
180         foreach($rows as $key => $value) {
181                 $rows[$key]['evenodd'] = $text[$even];
182                 $even = 1 - $even;
183         }
184         return $rows;
185 }
186
187
188
189 # Internal functions
190 # ------------------
191 #
192 # Of course, nothing stops you from using these, but I don't know
193 # why you would want to...
194
195
196 # Convert value to array of hashes for use in sub-template expansion.
197 # This adds flexibility to how you represent your data.
198 function tem_value_as_rows($value) {
199         if(is_array($value)) {
200                 # numeric keys, is already array of arrays -- expand sub-template for each.
201                 if(array_key_exists(0, $value)) return $value;
202                 # key/value pairs -- expand sub-template once.
203                 else return array($value);
204         } elseif($value) {
205                 # value -- expand sub-template once using only parent values
206                 return array(array());
207         } else {
208                 # empty value -- don't expand sub-template
209                 return array();
210         }
211 }
212
213 # Search the current context and return the value for key.
214 function tem_get($key, $context) {
215         while($context) {
216                 $data = array_pop($context);
217                 if(array_key_exists($key, $data)) return $data[$key];
218         }
219 }
220
221 # Return the value for a tag as a set of rows to fill a sub-template.
222 # If $tag has an arg, call the tem_auto function to munge the data.
223 function tem_get_rows($tag, $context, $keychain)
224 {
225         if(count($tag['args'])) {
226                 $func = "tem_auto_" . $tag['args'][0];
227                 if(function_exists($func)) $value = $func($tag, $context, $keychain);
228                 else die("ERROR: template auto function '$func' not found.<br>\n");
229         } else $value = tem_get($tag['name'], $context);
230
231         return tem_value_as_rows($value);
232 }
233
234 # Return the value for a tag as an encoded string.
235 function tem_get_enc($tag, $context)
236 {
237         $key = $tag['name'];
238         $value = tem_get($key, $context);
239         foreach($tag['args'] as $encoding) {
240                 $func = "enc_$encoding";
241                 if(function_exists($func)) $value = $func($value, $key);
242                 else die("ERROR: encoder function '$func' not found.<br>\n");
243         }
244         return $value;
245 }
246
247 function top_sub_templates($tem) {
248         $subs = array();
249         foreach($tem['pieces'] as $piece) {
250                 if(is_array($piece) and $piece['pieces']) {
251                         $subs[$piece['name']] = $piece;
252                 }
253         }
254         return $subs;
255 }
256
257 ?>