JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
* template.php (parse_template): every tag preceded by string.
[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 # 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         # note: for some reason this captures '<!--' but not '-->'.
68         $matches = preg_split("/(<!--)?(~[^~]*~)(?(1)-->)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
69         foreach($matches as $match) {
70                 if($match == '~~') $match = '~';
71                 if(substr($match,0,1) == '~' and strlen($match) > 2) {
72                         $args = explode(' ', substr($match,1,-1));
73
74                         if(count($args) == 1 and $args[0] == '}') $name = '';
75                         else $name = array_shift($args);
76
77                         if(last($args) == '{') {  # open block
78                                 array_pop($args);  # drop '{'
79                                 if(!is_string(last($tem['pieces']))) $tem['pieces'][] = '';
80                                 $tem =& tem_push($tem);              # create a new sub-template
81                                 $tem['parent']['pieces'][] =& $tem;  # as a piece of the parent
82                                 $tem['name'] = $name;
83                                 $tem['pieces'] = array();
84                                 $tem['args'] = $args;
85                         } elseif(last($args) == '}') {  # close block
86                                 array_pop($args);  # drop '}'
87                                 $cur = $tem['name'];
88                                 if($name && $name != $cur) {
89                                         die("Invalid template: tried to close '$name', but '$cur' is current.");
90                                 }
91                                 $tem =& $tem['parent'];
92                         } else {  # value slot
93                                 $tem['pieces'][] = array('name' => $name, 'args' => $args);
94                         }
95                 } elseif($match and $match != '<!--') {  # static string
96                         $tem['pieces'][] = $match;
97                 }
98         }
99         return $tem;
100 }
101
102 function fill_template($template, &$data, &$context = NULL) {
103         if(!$context) {
104                 $context =& tem_push($context);
105                 $context['data'] =& $data;
106         }
107
108         foreach($template['pieces'] as $tem) {
109                 if(is_string($tem)) $output .= $tem;
110                 elseif($tem['pieces']) {  # sub-template
111                         $rows =& tem_row_data($tem, $context);
112                         foreach($rows as $key => &$row) {
113                                 $context =& tem_push($context);
114                                 $context['data'] =& $row;
115                                 $context['rows'] =& $rows;
116                                         $output .= fill_template($tem, $row, $context);
117                                 $context =& $context['parent'];
118
119                         }
120                 } else {  # variable
121                         $output .= tem_encoded_data($tem, $context);
122                 }
123         }
124         return $output;
125 }
126
127
128 # Implementation
129 # --------------
130
131
132 # To track our position in the template and in the data, we use a linked 
133 # stack structure.  Each node is a hash with a reference to the parent 
134 # node along with whatever other data you want to add.  For each stack, 
135 # you simply keep a variable with a reference to the top element.  Then 
136 # the push and pop operations are:
137
138 # $top =& tem_push($top);
139 # $top =& $top['parent'];
140
141 function &tem_push(&$stack = NULL) {
142         static $refs = array();
143
144         # Since a PHP reference is *not* a pointer to data, but a pointer to 
145         # a variable (or array slot), we *have* to first put the new node in
146         # $refs, and then reference it from $new.
147
148         $refs[] = array();
149         $new =& $refs[count($refs)-1];
150         if($stack) $new['parent'] =& $stack;
151         return $new;
152 }
153
154 # To fill out a template, we do a depth-first traversal of the template 
155 # tree, replacing all tags with the data values.
156
157 # The data starts out as a nested set of key/value pairs, where the 
158 # values can be:
159
160         # a string to fill a value slot
161         # a hash to fill one instance of a sub-template
162         # an array of hashes to fill multiple instances of a sub-template
163
164 # The middle form will be converted to the last form as we use it.
165
166 function tem_data_as_rows($value) {
167         if(is_array($value)) {
168                 # numeric keys, is already array of arrays -- expand sub-template for each.
169                 if(array_key_exists(0, $value)) return $value;
170                 # key/value pairs -- expand sub-template once.
171                 else return array($value);
172         } elseif($value) {
173                 # value -- expand sub-template once using only parent values
174                 return array(array());
175         } else {
176                 # empty value -- don't expand sub-template
177                 return array();
178         }
179 }
180
181 # To look up a key, we check each namespace (starting with the
182 # innermost one) until a value is found.
183
184 function tem_data_scope($key, $context) {
185         $scope = $context;
186         do{
187                 if(array_key_exists($key, $scope['data'])) {
188                         return $scope;
189                 }
190         } while($scope = $scope['parent']);
191
192         # not found; return empty scope.
193         return array('parent' => $context);
194 }
195
196 function tem_get_data($key, $context) {
197         $scope = tem_data_scope($key, $context);
198         if($scope) return $scope['data'][$key];
199 }
200
201 # Return the value for a tag as a set of rows to fill a sub-template.
202 # If $tag has an arg, call the tem_auto function to munge the data.
203 function &tem_row_data($tag, $context)
204 {
205         $key = $tag['name'];
206         if(count($tag['args'])) {
207                 $func = "tem_auto_" . $tag['args'][0];
208                 function_exists($func)
209                         or die("ERROR: template auto function '$func' not found.<br>\n");
210         }
211         $scope = tem_data_scope($key, $context);
212
213         if($func) $value = $func($key, $scope);
214         else $value = $scope['data'][$key];
215
216         $rows = tem_data_as_rows($value);
217         if(is_array($value)) $scope['data'][$key] = $rows;
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)) $value = $func($value, $key);
230                 else die("ERROR: encoder function '$func' not found.<br>\n");
231         }
232         return $value;
233 }
234
235
236
237 # Return a hash containing the top-level sub-templates of tem.
238 function top_sub_templates($tem) {
239         $subs = array();
240         foreach($tem['pieces'] as $piece) {
241                 if(is_array($piece) and $piece['pieces']) {
242                         $subs[$piece['name']] = $piece;
243                 }
244         }
245         return $subs;
246 }
247
248 # Replace top-level values in $main with top-level templates from $tem.
249 function merge_templates($main, $tem) {
250         $out = array('name' => $main['name'], 'pieces' => array());
251
252         $subs = top_sub_templates($tem);
253
254         foreach($main['pieces'] as $piece) {
255                 if(is_array($piece) and !$piece['pieces'] and $subs[$piece['name']]) {
256                         $piece = $subs[$piece['name']];
257                 }
258                 $out['pieces'][] = $piece;
259         }
260         return $out;
261 }
262
263
264
265 # tem_auto functions
266 # ------------------
267 #
268 # If a { tag has an argument, the corresponding tem_auto function is called.
269 # This allows it to mangle the data to automate some common cases.
270
271 # 'sep' (separator) sections will be shown for all but the last parent row.
272 # Sample usage:
273 #       <!--~rows~-->
274 #               <!--~row~-->
275 #                       row content...
276 #                       <!--~separator sep {~--><hr><!--~separator }"-->
277 #               <!--~row~-->
278 #       <!--~rows~-->
279 #
280 function tem_auto_sep($key, $context) {
281         $rows =& $context['parent']['rows'];
282         if(key($rows)) return true;
283         # else we are on the last row (cursor has hit the end and reset).
284 }
285
286 # 'show' sections will be shown unless the corresponding data value
287 # is false.  We check only for false; 0 or '' will not work.
288
289 function tem_auto_show($key, $context) {
290         if($context['data'][$key] !== false)
291                 return tem_data_as_rows(true);
292 }
293
294 # 'evenodd' sections are given an 'evenodd' attribute whose value
295 # alternates between 'even' and 'odd'.
296
297 function tem_auto_evenodd($key, $context) {
298         $rows = $context['data'][$key];
299         $even = 0;
300         $text = array('even', 'odd');
301         foreach($rows as $key => $value) {
302                 $rows[$key]['evenodd'] = $text[$even];
303                 $even = 1 - $even;
304         }
305         return tem_data_as_rows($rows);
306 }
307
308 ?>