2 require_once 'object/TemplateEngine.php';
4 define("KEY_NOT_EXISTS", '^R_key_not_Exists^');
6 class Template implements ITemplateEngine {
7 static $name ="internal";
19 private function _preg_error() {
21 switch (preg_last_error()) {
22 case PREG_INTERNAL_ERROR: echo('PREG_INTERNAL_ERROR');
24 case PREG_BACKTRACK_LIMIT_ERROR: echo('PREG_BACKTRACK_LIMIT_ERROR');
26 case PREG_RECURSION_LIMIT_ERROR: echo('PREG_RECURSION_LIMIT_ERROR');
28 case PREG_BAD_UTF8_ERROR: echo('PREG_BAD_UTF8_ERROR');
30 // This is only valid for php > 5.3, not certain how to code around it for unit tests
31 // case PREG_BAD_UTF8_OFFSET_ERROR: echo('PREG_BAD_UTF8_OFFSET_ERROR'); break;
33 //die("Unknown preg error.");
37 debug_print_backtrace();
41 private function _push_stack() {
42 $this->stack[] = array($this->r, $this->nodes);
45 private function _pop_stack() {
46 list($this->r, $this->nodes) = array_pop($this->stack);
49 private function _get_var($name, $retNoKey = false) {
50 $keys = array_map('trim', explode(".", $name));
51 if ($retNoKey && !array_key_exists($keys[0], $this->r))
52 return KEY_NOT_EXISTS;
54 foreach ($keys as $k) {
55 $val = (isset($val[$k]) ? $val[$k] : null);
63 * {{ if <$var> }}...[{{ else }} ...] {{ endif }}
64 * {{ if <$var>==<val|$var> }}...[{{ else }} ...]{{ endif }}
65 * {{ if <$var>!=<val|$var> }}...[{{ else }} ...]{{ endif }}
67 private function _replcb_if($args) {
68 if (strpos($args[2], "==") > 0) {
69 list($a, $b) = array_map("trim", explode("==", $args[2]));
70 $a = $this->_get_var($a);
72 $b = $this->_get_var($b);
74 } else if (strpos($args[2], "!=") > 0) {
75 list($a, $b) = array_map("trim", explode("!=", $args[2]));
76 $a = $this->_get_var($a);
78 $b = $this->_get_var($b);
81 $val = $this->_get_var($args[2]);
83 $x = preg_split("|{{ *else *}}|", $args[3]);
84 return ( $val ? $x[0] : (isset($x[1]) ? $x[1] : ""));
90 * {{ for <$var> as $name }}...{{ endfor }}
91 * {{ for <$var> as $key=>$name }}...{{ endfor }}
93 private function _replcb_for($args) {
94 $m = array_map('trim', explode(" as ", $args[2]));
95 $x = explode("=>", $m[1]);
100 list($keyname, $varname) = $x;
102 if ($m[0] == "" || $varname == "" || is_null($varname))
103 die("template error: 'for " . $m[0] . " as " . $varname . "'");
104 //$vals = $this->r[$m[0]];
105 $vals = $this->_get_var($m[0]);
107 if (!is_array($vals))
109 foreach ($vals as $k => $v) {
110 $this->_push_stack();
114 $r[$keyname] = (($k === 0) ? '0' : $k);
115 $ret .= $this->replace($args[3], $r);
124 * {{ inc <templatefile> [with $var1=$var2] }}{{ endinc }}
126 private function _replcb_inc($args) {
127 if (strpos($args[2], "with")) {
128 list($tplfile, $newctx) = array_map('trim', explode("with", $args[2]));
130 $tplfile = trim($args[2]);
134 if ($tplfile[0] == "$")
135 $tplfile = $this->_get_var($tplfile);
137 $this->_push_stack();
139 if (!is_null($newctx)) {
140 list($a, $b) = array_map('trim', explode("=", $newctx));
141 $r[$a] = $this->_get_var($b);
143 $this->nodes = Array();
144 $tpl = get_markup_template($tplfile);
145 $ret = $this->replace($tpl, $r);
153 * {{ debug $var [$var [$var [...]]] }}{{ enddebug }}
155 * replace node with <pre>var_dump($var, $var, ...);</pre>
157 private function _replcb_debug($args) {
158 $vars = array_map('trim', explode(" ", $args[2]));
162 foreach ($vars as $var) {
163 $ret .= htmlspecialchars(var_export($this->_get_var($var), true));
170 private function _replcb_node($m) {
171 $node = $this->nodes[$m[1]];
172 if (method_exists($this, "_replcb_" . $node[1])) {
173 $s = call_user_func(array($this, "_replcb_" . $node[1]), $node);
177 $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
181 private function _replcb($m) {
182 //var_dump(array_map('htmlspecialchars', $m));
184 $this->nodes[] = (array) $m;
185 return "||" . (count($this->nodes) - 1) . "||";
188 private function _build_nodes($s) {
190 while (!$this->done) {
192 $s = preg_replace_callback('|{{ *([a-z]*) *([^}]*)}}([^{]*({{ *else *}}[^{]*)?){{ *end\1 *}}|', array($this, "_replcb"), $s);
194 $this->_preg_error();
196 //({{ *else *}}[^{]*)?
197 krsort($this->nodes);
201 private function var_replace($s) {
205 * (\[)? optional open square bracket
206 * ([a-zA-Z0-9-_]+\.?)+ var name, followed by optional
207 * dot, repeated at least 1 time
208 * (|[a-zA-Z0-9-_:]+)* pipe followed by filter name and args, zero or many
209 * (?(1)\]) if there was opened square bracket
210 * (subgrup 1), match close bracket
212 if (preg_match_all('/\$(\[)?([a-zA-Z0-9-_]+\.?)+(\|[a-zA-Z0-9-_:]+)*(?(1)\])/', $s, $m)) {
213 foreach ($m[0] as $var) {
215 $exp = str_replace(array("[", "]"), array("", ""), $var);
216 $exptks = explode("|", $exp);
220 $val = $this->_get_var($varn, true);
221 if ($val != KEY_NOT_EXISTS) {
224 * Filter are in form of:
225 * filtername:arg:arg:arg
227 * "filtername" is function name
228 * "arg"s are optional, var value is appended to the end
229 * if one "arg"==='x' , is replaced with var value
232 * $item.body|htmlspecialchars // escape html chars
233 * $item.body|htmlspecialchars|strtoupper // escape html and uppercase result
234 * $item.created|date:%Y %M %j // format date (created is a timestamp)
235 * $item.body|str_replace:cat:dog // replace all "cat" with "dog"
236 * $item.body|str_replace:cat:dog:x:1 // replace one "cat" with "dog"
239 foreach ($exptks as $filterstr) {
240 $filter = explode(":", $filterstr);
241 $filtername = $filter[0];
243 $valkey = array_search("x", $filter);
244 if ($valkey === false) {
247 $filter[$valkey] = $val;
249 if (function_exists($filtername)) {
250 $val = call_user_func_array($filtername, $filter);
253 $s = str_replace($var, $val, $s);
261 // TemplateEngine interface
262 public function replace_macros($s, $r) {
265 // remove comments block
266 $s = preg_replace('/{#(.*?\s*?)*?#}/', "", $s);
268 $s = $this->_build_nodes($s);
270 $s = preg_replace_callback('/\|\|([0-9]+)\|\|/', array($this, "_replcb_node"), $s);
272 $this->_preg_error();
274 // replace strings recursively (limit to 10 loops)
277 while ($os != $s && $count < 10) {
280 $s = $this->var_replace($s);
282 return template_unescape($s);
285 public function get_template_file($file, $root='') {
287 $template_file = get_template_file($a, $file, $root);
288 $content = file_get_contents($template_file);
295 function template_escape($s) {
297 return str_replace(array('$', '{{'), array('!_Doll^Ars1Az_!', '!_DoubLe^BraceS4Rw_!'), $s);
300 function template_unescape($s) {
302 return str_replace(array('!_Doll^Ars1Az_!', '!_DoubLe^BraceS4Rw_!'), array('$', '{{'), $s);