JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
* New template system.
[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 delimited by tildes (~).  When 
23 # the template is filled out, the tags will be replaced with the 
24 # corresponding data.  Tags ending with '?' and '.' mark the start and 
25 # end of a sub-template (for optional or repeated text), and can be 
26 # wrapped in HTML comments (which will be removed along with the tags
27 # when the template is filled out).
28
29 require_once('code/wfpl/encode.php');
30 require_once('code/wfpl/file.php');
31 require_once('code/wfpl/misc.php');
32
33
34 # Public functions
35 # ----------------
36
37 function template($data, $template) {
38         return fill_template($data, parse_template($template));
39 }
40
41 function template_file($data, $filename) {
42         return fill_template($data, parse_template_file($filename));
43 }
44
45 function parse_template_file($filename) {
46         return parse_template(file_get_contents($filename));
47 }
48
49 # First we take the template string and break it up into an array 
50 # of strings and sub-arrays.  The first item in a sub-array is the name
51 # of the value or sub-template.
52
53 function parse_template($string) {
54         # Don't mess with the $stack/$tem assignments!  Since
55         # PHP references point to the variable, not the data,
56         # it really does have to be written exactly like this.
57         $stack[] = array('name' => 'root', 'pieces' => array());
58         $tem = &last($stack);
59         # note: for some reason this captures '<!--' but not '-->'.
60         $matches = preg_split("/(<!--)?(~[^~]*~)(?(1)-->)/", $string, -1, PREG_SPLIT_DELIM_CAPTURE);
61         foreach($matches as $match) {
62                 if(substr($match,0,1) == '~') {
63                         $args = explode(' ', substr($match,1,-1));
64
65                         if(count($args) == 1 and $args[0] == '}') $name = '';
66                         else $name = array_shift($args);
67
68                         if(last($args) == '{') {  # open block
69                                 array_pop($args);
70                                 $stack[] = array('name' => $name, 'pieces' => array(), 'args' => $args);
71                                 $tem['pieces'][] = &last($stack);
72                                 $tem = &last($stack);
73                         } elseif(last($args) == '}') {  # close block
74                                 array_pop($args);
75                                 $cur = $stack[count($stack)-1]['name'];
76                                 if($name && $name != $cur) {
77                                         die("Invalid template: tried to close '$name', but '$cur' is current.");
78                                 }
79                                 array_pop($stack); $tem = &last($stack);
80                         } else {  # value slot
81                                 $tem['pieces'][] = array('name' => $name, 'args' => $args);
82                         }
83                 } elseif($match and $match != '<!--') {  # static string
84                         $tem['pieces'][] = $match;
85                 }
86         }
87         return $tem;
88 }
89
90 # Then we do a depth-first traversal of the template tree,
91 # replacing all tags with the data values.
92
93 function fill_template($data, $template, $context = NULL, $keychain = NULL) {
94         $context[] = $data;
95         foreach($template['pieces'] as $piece) {
96                 if(is_string($piece)) $output .= $piece;
97                 else {
98                         if($piece['pieces']) {  # sub-template
99                                 $keychain[] = $piece['name'];
100                                 $data = tem_get($piece, $context, $keychain);
101                                 foreach(template_rows($data) as $key => $row) {
102                                         $keychain[] = $key;
103                                         $output .= fill_template($row, $piece, $context, $keychain);
104                                         array_pop($keychain);
105                                 }
106                                 array_pop($keychain);
107                         } else $output .= tem_get_enc($piece, $context);
108                 }
109         }
110         return $output;
111 }
112
113
114 # Replace top-level values in $main with top-level templates from $tem.
115 function merge_templates($main, $tem) {
116         $out = array('name' => $main['name'], 'pieces' => array());
117
118         $subs = top_sub_templates($tem);
119
120         foreach($main['pieces'] as $piece) {
121                 if(is_array($piece) and !$piece['pieces'] and $subs[$piece['name']]) {
122                         $piece = $subs[$piece['name']];
123                 }
124                 $out['pieces'][] = $piece;
125         }
126         return $out;
127 }
128
129
130
131 # tem_auto functions
132 # ------------------
133 #
134 # If a { tag has an argument, the corresponding tem_auto function is called.
135 # This allows it to mangle the data to automate some common cases.
136
137 # 'sep' (separator) sections will be shown for all but the last parent row.
138 # Sample usage:
139 #       <!--~rows~-->
140 #               <!--~row~-->
141 #                       row content...
142 #                       <!--~separator sep {~--><hr><!--~separator }"-->
143 #               <!--~row~-->
144 #       <!--~rows~-->
145 #
146 function tem_auto_sep($piece, $context, $keychain) {
147         list($name, $index, $this_name) = array_slice($keychain, -3);
148         $array = _tem_get($name, $context);
149         if($index != count($array)-1) return true;
150 }
151
152 # 'once' sections will be shown once unless the corresponding data value
153 # is false.  We check only for false; 0 or '' will not work.
154
155 function tem_auto_once($piece, $context, $keychain) {
156         $value = _tem_get(array_pop($keychain), $context);
157         if($value !== false) return true;
158 }
159
160 # 'evenodd' sections are given an 'evenodd' attribute whose value
161 # alternates between 'even' and 'odd'.
162
163 function tem_auto_evenodd($piece, $context, $keychain) {
164         $rows = _tem_get(array_pop($keychain), $context);
165         $even = 0;
166         $text = array('even', 'odd');
167         foreach($rows as $key => $value) {
168                 $rows[$key]['evenodd'] = $text[$even];
169                 $even = 1 - $even;
170         }
171         return $rows;
172 }
173
174
175
176 # Internal functions
177 # ------------------
178 #
179 # Of course, nothing stops you from using these, but I don't know
180 # why you would want to...
181
182
183 # Convert value to array of hashes for use in sub-template expansion.
184 # This adds flexibility to how you represent your data.
185 function template_rows($value) {
186         if(is_array($value)) {
187                 # numeric keys, is already array of arrays -- expand sub-template for each.
188                 if(array_key_exists(0, $value)) return $value;
189                 # key/value pairs -- expand sub-template once.
190                 else return array($value);
191         } elseif($value) {
192                 # value -- expand sub-template once using only parent values
193                 return array(array());
194         } else {
195                 # empty value -- don't expand sub-template
196                 return array();
197         }
198 }
199
200 function _tem_get($key, $context) {
201         while($context) {
202                 $data = array_pop($context);
203                 if(array_key_exists($key, $data)) return $data[$key];
204         }
205 }
206
207 function tem_get($piece, $context, $keychain)
208 {
209         if(count($piece['args'])) {
210                 $func = "tem_auto_" . $piece['args'][0];
211                 if(function_exists($func)) return $func($piece, $context, $keychain);
212                 else die("ERROR: template auto function '$func' not found.<br>\n");
213         } else return _tem_get($piece['name'], $context);
214 }
215
216 # $tag is a hash with keys 'name' and 'args'.
217 function tem_get_enc($tag, $context)
218 {
219         $key = $tag['name'];
220         $value = _tem_get($key, $context);
221         foreach($tag['args'] as $encoding) {
222                 $func = "enc_$encoding";
223                 if(function_exists($func)) $value = $func($value, $key);
224                 else die("ERROR: encoder function '$func' not found.<br>\n");
225         }
226         return $value;
227 }
228
229 function top_sub_templates($tem) {
230         $subs = array();
231         foreach($tem['pieces'] as $piece) {
232                 if(is_array($piece) and $piece['pieces']) {
233                         $subs[$piece['name']] = $piece;
234                 }
235         }
236         return $subs;
237 }
238
239 ?>