1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
|
<?php
namespace ste;
class TextNode
{
public $text;
}
class TagNode
{
public $name;
public $params;
public $sub;
}
class VariableNode
{
public $name;
public $arrayfields;
public function transcompile()
{
$varaccess = '@$ste->vars[' . (is_numeric($this->name) ? $this->name : '\'' . escape_text($this->name) . '\''). ']';
foreach($this->arrayfields as $af)
{
if((count($af) == 1) and ($af[0] instanceof TextNode) and is_numeric($af->text))
$varaccess .= '[' . $af->text . ']';
else
$varaccess .= '[' . implode(".",
array_map(
function($node)
{
if($node instanceof TextNode)
return "'" . escape_text($node->text) . "'";
else if($node instanceof VariableNode)
return $node->transcompile;
}, $af
)
). ']';
}
return $varaccess;
}
}
/* $text must start after the first opening bracket */
function find_closing_bracket($text, $opening, $closing)
{
$counter = 1;
$len = strlen($text);
for($i = 0; $i < $len; ++$i)
{
switch($text[$i])
{
case $opening:
++$counter;
break;
case $closing:
--$counter;
break;
}
if($counter == 0)
break;
}
if($counter > 0)
throw new Exception("Missing closing \"$closing\". Stop.");
return $i;
}
function unescape_text($text)
{
$text = preg_replace("/(?:(?<!\\\\)\\\\\\\$)/s", "$", $text);
return str_replace("\\\\", "\\", $text);
}
function tokenize_text($text)
{
$tokens = array();
/* Find next non-escaped $-char */
if(preg_match("/(?:(?<!\\\\)\\$)/s", $text, $match, PREG_OFFSET_CAPTURE) == 0)
{
$node = new TextNode();
$node->text = unescape_text($text);
return (strlen($node->text) == 0) ? array() : array($node);
}
if($match[0][1] > 0)
{
$node = new TextNode();
$node->text = unescape_text(substr($text, 0, $match[0][1]));
$tokens[] = $node;
}
if($text[$match[0][1] + 1] == "{")
{
$varend = find_closing_bracket(substr($text, $match[0][1] + 2), "{", "}") + $match[0][1] + 2;
return array_merge(
$tokens,
tokenize_text("\$" . substr($text, $match[0][1] + 2, ($varend - 1) - ($match[0][1] + 1))),
tokenize_text(substr($text, $varend + 1))
);
}
$text = substr($text, $match[0][1] + 1);
if(preg_match("/^[a-zA-Z0-9_]+/s", $text, $match, PREG_OFFSET_CAPTURE) == 0)
{
$nexttokens = tokenize_text($text);
if($nexttokens[0] instanceof Text)
$nexttokens[0]->text = "\$" . $nexttokens[0]->text;
else
{
$node = new TextNode();
$node->text = "\$";
$tokens[] = $node;
}
return array_merge($tokens, $nexttokens);
}
$node = new VariableNode();
$node->name = $match[0][0];
$node->arrayfields = array();
$text = substr($text, $match[0][1] + strlen($match[0][0]));
while(@$text[0] == "[")
{
$text = substr($text, 1);
$fieldend = find_closing_bracket($text, "[", "]");
$node->arrayfields[] = tokenize_text(substr($text, 0, $fieldend));
$text = substr($text, $fieldend + 1);
}
$tokens[] = $node;
return strlen($text) > 0 ? array_merge($tokens, tokenize_text($text)) : $tokens;
}
function mk_ast($code)
{
$ast = array();
if(preg_match("/\\<\\s*ste:([a-zA-Z0-9_]*)/s", $code, $matches, PREG_OFFSET_CAPTURE) == 0)
return tokenize_text($code);
$ast = tokenize_text(substr($code, 0, $matches[0][1]));
$tag = new TagNode();
$tag->name = $matches[1][0];
$code = substr($code, $matches[0][1] + strlen($matches[0][0]));
$tag->params = array();
while(preg_match("/^\\s+([a-zA-Z0-9_]+)=((?:\"(?:.*?)(?<!\\\\)\")|(?:'(?:.*?)(?<!\\\\)'))/s", $code, $matches, PREG_OFFSET_CAPTURE) > 0)
{
$paramval = substr($code, $matches[2][1] + 1, strlen($matches[2][0]) - 2);
$paramval = str_replace("\\\"", "\"", $paramval);
$paramval = str_replace("\\'", "'", $paramval);
$tag->params[$matches[1][0]] = tokenize_text($paramval);
$code = substr($code, strlen($matches[0][0]));
}
if(preg_match("/^\\s*([\\/]?)\\s*\\>/s", $code, $matches) == 0)
throw new Exception("Missing closing '>' in \"" . $tag->name . "\"-Tag. Stop. (:::CODE START:::$code:::CODE END:::)");
$code = substr($code, strlen($matches[0]));
$tag->sub = array();
if($matches[1][0] != "/")
{
$tags_open = 1;
$off = 0;
$last_tag_start = 0;
while(preg_match("/\\<((?:\\s*)|(?:\\s*\\/\\s*))ste:([a-zA-Z0-9_]*)(?:\\s+(?:[a-zA-Z0-9_]+)=(?:(?:\"(?:.*?)(?<!\\\\)\")|(?:'(?:.*?)(?<!\\\\)')))*((?:\\s*)|(?:\\s*\\/\\s*))\\>/s", $code, $matches, PREG_OFFSET_CAPTURE, $off) > 0) /* RegEx from hell! Matches all <ste:> Tags. Opening, closing and self-closing ones. */
{
if(trim($matches[3][0]) != "/")
{
$closingtag = trim($matches[1][0]);
if($closingtag[0] == "/")
$tags_open--;
else
$tags_open++;
}
$last_tag_start = $matches[0][1];
$off = $last_tag_start + strlen($matches[0][0]);
if($tags_open == 0)
break;
}
if(($tags_open != 0) or ($tag->name != $matches[2][0]))
throw new Exception("Missing closing \"ste:" . $tag->name . "\"-Tag. Stop.");
if($tag->name == "rawtext")
{
$tag = new TextNode();
$tag->text = substr($code, 0, $last_tag_start);
}
else
$tag->sub = mk_ast(substr($code, 0, $last_tag_start));
$code = substr($code, $off);
}
$ast[] = $tag;
return array_merge($ast, strlen($code) > 0 ? mk_ast($code) : array());
}
function parse($code)
{
/* Precompiling... */
$code = preg_replace("/\\<\\s*ste:comment\\s*\\>.*?\\<\\s*\\/\\s*ste:comment\\s*\\>/s", "", $code); /* Remove comments */
$code = preg_replace( /* Transform short form of if-clause (?{cond|then|else}) to long form */
"/(?:(?<!\\\\)\\?)(?:(?<!\\\\)\\{)(.*?)(?:(?<!\\\\)\\|)(.*?)(?:(?<!\\\\)\\|)(.*?)(?:(?<!\\\\)\\})/s",
"<ste:if>\$1<ste:then>\$2</ste:then><ste:else>\$3</ste:else></ste:if>",
$code
);
/* Unescape \? \{ \} \| */
$code = preg_replace("/(?:(?<!\\\\)\\\\\\?)/s", "?", $code);
$code = preg_replace("/(?:(?<!\\\\)\\\\\\{)/s", "{", $code);
$code = preg_replace("/(?:(?<!\\\\)\\\\\\})/s", "}", $code);
$code = preg_replace("/(?:(?<!\\\\)\\\\\\|)/s", "|", $code);
/* Create abstract syntax tree */
return mk_ast($code);
}
define("MODE_SOURCE", 0);
define("MODE_TRANSCOMPILED", 1);
interface StorageAccess
{
public function load($tpl, &$mode);
public function save($tpl, $data, $mode);
}
class FilesystemStorageAccess implements StorageAccess
{
protected $sourcedir;
protected $transcompileddir;
public function __construct($src, $transc)
{
$this->sourcedir = $src;
$this->transcompileddir = $transc;
}
public function load($tpl, &$mode)
{
$src_fn = $this->sourcedir . "/" . $tpl;
$transc_fn = $this->transcompileddir . "/" . $tpl;
if($mode == MODE_SOURCE)
{
$content = @file_get_contents($src_fn);
if($content === False)
throw new Exception("Template not found.");
return $content;
}
$src_stat = @stat($src_fn);
$transc_stat = @stat($transc_fn);
if(($src_stat === False) and ($transc_stat === False))
throw new Exception("Template not found.");
else if($transc_stat === False)
{
$mode = MODE_SOURCE;
return file_get_contents($src_fn);
}
else if($src_stat === False)
{
include($transc_fn);
return $transcompile_fx;
}
else
{
if($src_stat["mtime"] > $transc_stat["mtime"])
{
$mode = MODE_SOURCE;
return file_get_contents($src_fn);
}
else
{
include($transc_fn);
return $transcompile_fx;
}
}
}
public function save($tpl, $data, $mode)
{
file_put_contents((($mode == MODE_SOURCE) ? $this->sourcedir : $this->transcompileddir) . "/" . $tpl, $data);
}
}
function indent_code($code)
{
return implode(
"\n",
array_map(
function($line) { return "\t$line"; },
explode("\n", $code)
)
);
}
/* We could also just eval() the $infix_math code, but this is much cooler :-D (Parser inception) */
function shunting_yard($infix_math)
{
$operators = array(
"+" => array("l", 2),
"-" => array("l", 2),
"*" => array("l", 3),
"/" => array("l", 3),
"^" => array("r", 4),
"_" => array("r", 5),
"(" => array("", 0),
")" => array("", 0)
);
preg_match_all("/\s*(?:(?:[+\\-\\*\\/\\^\\(\\)])|(\\d*[\\.]?\\d*))\\s*/s", $infix_math, $tokens, PREG_PATTERN_ORDER);
$tokens_raw = array_filter(array_map('trim', $tokens[0]), function($x) { return !empty($x); });
$output_queue = array();
$op_stack = array();
$lastpriority = NULL;
/* Make - unary, if neccessary */
$tokens = array();
foreach($tokens_raw as $token)
{
$priority = isset($operators[$token]) ? $operators[$token][1] : -1;
if(($token == "-") and (($lastpriority === NULL) or ($lastpriority >= 0)))
{
$priority = $operators["_"][1];
$tokens[] = "_";
}
else
$tokens[] = $token;
$lastpriority = $priority;
}
while(!empty($tokens))
{
$token = array_shift($tokens);
if(is_numeric($token))
$output_queue[] = $token;
else if($token == "(")
$op_stack[] = $token;
else if($token == ")")
{
$lbr_found = False;
while(!empty($op_stack))
{
$op = array_pop($op_stack);
if($op == "(")
{
$lbr_found = True;
break;
}
$output_queue[] = $op;
}
if(!$lbr_found)
throw new Exception("Bracket mismatch.");
}
else if(!isset($operators[$token]))
throw new Exception("Invalid token ($token): Not a number, bracket or operator. Stop.");
else
{
$priority = $operators[$token][1];
if($operators[$token][0] == "l")
while((!empty($op_stack)) and ($priority <= $operators[$op_stack[count($op_stack)-1]][1]))
$output_queue[] = array_pop($op_stack);
else
while((!empty($op_stack)) and ($priority < $operators[$op_stack[count($op_stack)-1]][1]))
$output_queue[] = array_pop($op_stack);
$op_stack[] = $token;
}
}
while(!empty($op_stack))
{
$op = array_pop($op_stack);
if($op == "(")
throw new Exception("Bracket mismatch...");
$output_queue[] = $op;
}
return $output_queue;
}
function pop2(&$array)
{
$rv = array(array_pop($array), array_pop($array));
if(array_search(NULL, $rv, True) === False)
throw new Exception("Not enough numbers on stack. Invalid formula.");
return $rv;
}
function calc_rpn($rpn)
{
$stack = array();
foreach($rpn as $token)
{
switch($token)
{
case "+":
list($b, $a) = pop2($stack);
$stack[] = $a + $b;
break;
case "-":
list($b, $a) = pop2($stack);
$stack[] = $a - $b;
break;
case "*":
list($b, $a) = pop2($stack);
$stack[] = $a * $b;
break;
case "/":
list($b, $a) = pop2($stack);
$stack[] = $a / $b;
break;
case "^":
list($b, $a) = pop2($stack);
$stack[] = pow($a, $b);
break;
case "_":
$a = array_pop($stack);
if($a === NULL)
throw new Exception("Not enough numbers on stack. Invalid formula.");
$stack[] = -$a;
break;
default:
$stack[] = $token;
break;
}
}
return array_pop($stack);
}
$ste_builtins = array(
"if" => function($ast)
{
$output = "";
$condition = array();
$then = array();
$else = array();
foreach($ast->sub as $node)
{
if(($node instanceof TagNode) and ($node->name == "then"))
$then = $node->sub;
else if(($node instanceof TagNode) and ($node->name == "else"))
$else = $node->sub;
else
$condition[] = $node;
}
if(empty($then))
throw new Exception("Transcompile error: Missing <ste:else> in <ste:if>. Stop.");
$output .= "\$outputstack[] = \"\";\n\$outputstack_i++;\n";
$output .= _transcompile($condition);
$output .= "\$outputstack_i--;\nif(\$ste->bool(array_pop(\$outputstack)))\n{\n";
$output .= indent_code(transcompile($then));
$output .= "}\n";
if(!empty($else))
{
$output .= "else\n{\n";
$output .= indent_code(transcompile($else));
$output .= "}\n";
}
return $output;
},
"cmp" => function($ast)
{
$code = "";
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
if(isset($ast->params["var_b"]))
{
$code .= _transcompile($ast->params["var_b"]);
$b = '$ste->get_var_by_name(array_pop($outputstack))';
}
else if(isset($ast->params["text_b"]))
{
$code .= _transcompile($ast->params["text_b"]);
$b = 'array_pop($outputstack)';
}
else
throw new Exception("Transcompile error: neiter var_b nor text_b set in <ste:cmp>. Stop.");
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
if(isset($ast->params["var_a"]))
{
$code .= _transcompile($ast->params["var_a"]);
$a = '$ste->get_var_by_name(array_pop($outputstack))';
}
else if(isset($ast->params["text_a"]))
{
$code .= _transcompile($ast->params["text_a"]);
$a = 'array_pop($outputstack)';
}
else
throw new Exception("Transcompile error: neiter var_a nor text_a set in <ste:cmp>. Stop.");
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
if(isset($ast->params["op"]))
$code .= _transcompile($ast->params["op"]);
else
throw new Exception("Transcompile error: op not given in <ste:cmp>. Stop.");
$code .= "\$outputstack_i -= 3;\nswitch(trim(array_pop(\$outputstack)))\n{\n\t";
$code .= implode("", array_map(
function($op) use ($a,$b)
{
list($op_stetpl, $op_php) = $op;
return "case '$op_stetpl':\n\t\$outputstack[\$outputstack_i] .= (($a) $op_php ($b)) ? 'yes' : '';\n\tbreak;\n\t";
},
array(
array('eq', '=='),
array('neq', '!='),
array('lt', '<'),
array('lte', '<='),
array('gt', '>'),
array('gte', '>=')
)
));
$code .= "default: throw new Exception('Runtime Error: Unknown operator in <ste:cmp>.');\n}\n";
return $code;
},
"not" => function($ast)
{
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->sub);
$code .= "\$outputstack_i--;\n\$outputstack[\$outputstack_i] .= (!\$ste->bool(array_pop(\$outputstack))) ? 'yes' : '';\n";
return $code;
},
"even" => function($ast)
{
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->sub);
$code .= "\$outputstack_i--;\$tmp_even = array_pop(\$outputstack);\n\$outputstack[] .= (is_numeric(\$tmp_even) and (\$tmp_even % 2 == 0)) ? 'yes' : '';\n";
},
"for" => function($ast)
{
$code = "";
$loopname = "forloop_" . str_replace(".", "_", uniqid("",True));
if(empty($ast->params["start"]))
throw new Exception("Transcompile error: Missing 'start' parameter in <ste:for>. Stop.");
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["start"]);
$code .= "\$outputstack_i--;\n\$${loopname}_start = array_pop(\$outputstack);\n";
if(empty($ast->params["end"]))
throw new Exception("Transcompile error: Missing 'end' parameter in <ste:for>. Stop.");
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["end"]);
$code .= "\$outputstack_i--;\n\$${loopname}_end = array_pop(\$outputstack);\n";
if(empty($ast->params["step"]))
$code .= "\$${loopname}_step = 1;\n";
else
{
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["step"]);
$code .= "\$outputstack_i--;\n\$${loopname}_step = array_pop(\$outputstack);\n";
}
if(!empty($ast->params["counter"]))
{
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["counter"]);
$code .= "\$outputstack_i--;\n\$${loopname}_countername = array_pop(\$outputstack);\n";
}
$loopbody = empty($ast->params["counter"]) ? "\$ste->set_var_by_name(\$${loopname}_countername, \$${loopname}_counter);\n\n" : "";
$loopbody .= _transcompile($ast->sub);
$loopbody = indent_code("{\n" . indent_code($loopbody) . "}\n");
$code .= "if(\$${loopname}_step == 0)\n\tthrow new Exception('Runtime Error: step can not be 0 in <ste:for>. Stop.');\n";
$code .= "if(\$${loopname}_step > 0)\n{\n";
$code .= "\tfor(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_start <= \$${loopname}_end; \$${loopname}_start += \$${loopname}_step)\n";
$code .= $loopbody;
$code .= "\n}\nelse\n{\n";
$code .= "\tfor(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_start >= \$${loopname}_end; \$${loopname}_start += \$${loopname}_step)\n";
$code .= $loopbody;
$code .= "\n}\n";
return $code;
},
"foreach" => function($ast)
{
$loopname = "foreachloop_" . str_replace(".", "_", uniqid("",True));
$code = "";
if(empty($ast->params["array"]))
throw new Exception("Transcompile Error: array not givein in <ste:foreach>. Stop.");
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["array"]);
$code .= "\$outputstack_i--;\n\$${loopname}_arrayvar = array_pop(\$outputstack);\n";
if(empty($ast->params["value"]))
throw new Exception("Transcompile Error: value not givein in <ste:foreach>. Stop.");
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["value"]);
$code .= "\$outputstack_i--;\n\$${loopname}_valuevar = array_pop(\$outputstack);\n";
if(!empty($ast->params["key"]))
{
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["key"]);
$code .= "\$outputstack_i--;\n\$${loopname}_keyvar = array_pop(\$outputstack);\n";
}
if(!empty($ast->params["counter"]))
{
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["counter"]);
$code .= "\$outputstack_i--;\n\$${loopname}_countervar = array_pop(\$outputstack);\n";
}
$code .= "\$${loopname}_array = \$ste->get_var_by_name(\$${loopname}_arrayvar);\n";
$code .= "\$${loopname}_counter = 0;\n";
$loopbody = "\$${loopname}_counter++;\n\$ste->set_var_by_name(\$${loopname}_valuevar, \$${loopname}_value);\n";
if(!empty($ast->params["key"]))
$loopbody .= "\$ste->set_var_by_name(\$${loopname}_keyvar, \$${loopname}_key);\n";
if(!empty($ast->params["counter"]))
$loopbody .= "\$ste->set_var_by_name(\$${loopname}_countervar, \$${loopname}_counter);\n";
$loopbody .= "\n";
$loopbody .= _transcompile($ast->sub);
$loopbody = "{\n" . indent_code($loopbody) . "}\n";
$code .= "foreach(\$${loopname}_array as \$${loopname}_key => \$${loopname}_value)\n$loopbody\n";
return $code;
},
"infloop" => function($ast)
{
return "while(True)\n{\n" . indent_code(_transcompile($ast->sub)) . "}\n";
},
"break" => function($ast)
{
return "break;\n";
},
"continue" => function($ast)
{
return "continue;\n";
},
"block" => function($ast)
{
if(empty($ast->name))
throw new Exception("Transcompile Error: name missing in <ste:block>. Stop.");
$blknamevar = "blockname_" . str_replace(".", "_", uniqid("", True));
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->name);
$code .= "\$outputstack_i--;\n\$${blknamevar} = array_pop(\$outputstack);\n";
$tmpblk = uniqid("", True);
$code .= "\$ste->blocks['$tmpblk'] = array_pop(\$outputstack);\n\$ste->blockorder[] = '$tmpblk';\n\$outputstack = array('');\n\$outputstack_i = 0;\n";
$code .= _transcompile($ast->sub);
$code .= "\$ste->blocks[\$${blknamevar}] = array_pop(\$outputstack);\n";
$code .= "if(array_search(\$${blknamevar}, \$ste->blockorder) === FALSE)\n\t\$ste->blockorder[] = '$tmpblk';\n\$outputstack = array('');\n\$outputstack_i = 0;\n";
return $code;
},
"load" => function($ast)
{
if(empty($ast->params["name"]))
throw new Exception("Transcompile Error: name missing in <ste:load>. Stop.");
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["name"]);
$code .= "\$outputstack_i--;\n\$outputstack[\$outputstack_i] .= \$ste->load(array_pop(\$outputstack));\n";
return $code;
},
"mktag" => function($ast)
{
if(empty($ast->params["name"]))
throw new Exception("Transcompile Error: name missing in <ste:mktag>. Stop.");
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["name"]);
$code .= "\$outputstack_i--;\n\$tagname = array_pop(\$outputstack);\n";
$fxbody = "\$outputstack = array(); \$outputstack_i = 0;\$ste->vars['_tag_parameters'] = \$params;\n";
if(!empty($ast->params["mandatory"]))
{
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["mandatory"]);
$code .= "\$outputstack_i--;\n\$mandatory_params = explode('|', array_pop(\$outputstack));\n";
$fxbody .= "foreach(\$mandatory_params as \$mp)\n{\n\tif(!isset(\$params[\$mp]))\n\t\tthrow new Exception(\"Runtime Error: \$mp missing in <ste:\$tagname>. Stop.\");\n}";
}
$fxbody .= _transcompile($ast->sub);
$fxbody .= "return array_pop(\$outputstack);";
$code .= "\$tag_fx = function(\$ste, \$params, \$sub) use (\$tagname, \$mandatory_params)\n{\n" . indent_code($fxbody) . "\n}\n";
$code .= "\$ste->register_tag(\$tagname, \$tag_fx);";
return $code;
},
"tagcontent" => function($ast)
{
return "\$outputstack[\$outputstack_i] .= \$sub(\$ste);";
},
"set" => function($ast)
{
if(empty($ast->params["var"]))
throw new Exception("Transcompile Error: var missing in <ste:set>. Stop.");
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->params["var"]);
$code -= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->sub);
$code .= "\$outputstack_i -= 2;\n\$newvartext = array_pop(\$outputstack);\n\$varname = array_pop(\$outputstack);\n";
$code .= "\$ste->set_var_by_name(\$varname, \$newvartext);\n";
return $code;
},
"calc" => function($ast)
{
$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($ast->sub);
$code .= "\$outputstack_i--;\n\$outputstack[\$outputstack_i] .= \$ste->calc(array_pop(\$outputstack));\n";
return $code;
}
);
function escape_text($text)
{
return addcslashes($text, "\0.\x1f\r\n\t\\'\x7f..\xff");
}
function _transcompile($ast) /* The real transcompile function, does not add boilerplate code. */
{
$code = "";
global $ste_builtins;
foreach($ast as $node)
{
if($node instanceof TextNode)
$code .= "\$outputstack[\$outputstack_i] .= '" . escape_text($node->text) . "';\n";
else if($node instanceof VariableNode)
$code .= "\$outputstack[\$outputstack_i] .= " . $node->transcompile() . ";\n";
else if($node instanceof TagNode)
{
if(isset($ste_builtins[$node->name]))
$code .= $ste_builtins[$node->name]($node);
else
{
$paramarray = "parameters_" . str_replace(".", "_", uniqid("", True));
$code .= "\$$paramarray = array();\n";
foreach($node->params as $pname => $pcontent)
{
$code .= "\$outputstack[] = '';\n\$outputstack_i++;\n";
$code .= _transcompile($pcontent);
$code .= "\$outputstack_i--;\n\$${paramarray}['" . escape_text($pname) . "'] = array_pop(\$outputstack);\n";
}
$code .= "\$outputstack[\$outputstack_i] .= \$ste->call_tag('" . escape_text($node->name) . "', \$${paramarray}, " . transcompile($node->sub) . ");";
}
}
}
return $code;
}
$ste_transc_boilerplate = "\$outputstack = array('');\n\$outputstack_i = 0;\n";
function transcompile($ast) /* Transcompile and add some boilerplate code. */
{
return "function(\$ste)\n{\n" . indent_code($ste_transc_boilerplate . _transcompile($ast) . "return array_pop(\$outputstack);") . "\n}";
}
class STECore
{
private $tags;
private $storage_access;
private $cur_tpl_dir;
public $blocks;
public $blockorder;
public $vars;
public function __construct($storage_access)
{
$this->storage_access = $storage_access;
$this->cur_tpl_dir = "/";
STEStandardLibrary->_register_lib($this);
$this->vars = array();
}
public function register_tag($name, $callback)
{
if(!is_callable($callback))
throw new Exception("Can not register tag \"$name\", not callable.");
if(empty($name))
throw new Exception("Can not register tag, empty name.");
$this->tags[$name] = $callback;
}
public function call_tag($name, $params, $sub)
{
if(!isset($this->tags[$name]))
throw new Exception("Can not call tag \"$name\": Does not exist.");
return $this->tags[$name]($this, $params, $sub);
}
public function calc($expression)
{
return calc_rpn(shunting_yard($expression));
}
public function exectemplate($tpl)
{
$output = "";
$lastblock = $this->load($tpl);
foreach($this->blockorder as $blockname)
$output .= $this->blocks[$blockname];
return $output . $lastblock;
}
private function get_var_reference(&$from, $name, $create_if_not_exist)
{
$bracket_open = strpos($name, "[");
if($bracket_open === False)
{
if(isset($from[$name]) or $create_if_not_exist)
return &$from[$name];
else
return NULL;
}
else
{
$old_varname = $varname;
$bracket_close = strpos($name, "]", $bracket_open);
if($bracket_close === FALSE)
throw new Excpeption("Runtime Error: Invalid varname \"$varname\". Missing closing \"]\".");
$varname = substr($name, 0, $bracket_open);
$name = substr($name, $bracket_open + 1, $bracket_close - $bracket_open - 1) . substr($name, $bracket_close + 1);
if(!is_array($from[$varname]))
{
if($create_if_not_exist)
$from[$varname] = array();
else
return NULL;
}
try
{
return $self->get_var_reference($from[$varname], $name, $create_if_not_exist);
}
catch(Exception $e)
{
throw new Excpeption("Runtime Error: Invalid varname \"$old_varname\". Missing closing \"]\".");
}
}
}
public function set_var_by_name($name, $val)
{
$ref = $this->get_var_reference($this->vars, $name, True);
$ref = (string) $val;
}
public function get_var_by_name($name)
{
$ref = $this->get_var_reference($this->vars, $name, False);
return $ref === NULL ? "" : (string) $ref;
}
public function load($tpl, $quiet=False)
{
$tpldir_b4 = $this->cur_tpl_dir;
/* Resolve ".", ".." and protect from possible LFI */
$tpl = str_replace("\\", "/", $tpl);
if($tpl[0] != "/")
$tpl = $this->cur_tpl_dir . "/" . $tpl;
$pathex = array_filter(array_slice(explode("/", $tpl), 1), function($s) { return $s != "."; });
while(($i = array_search("..", $pathex)) !== False)
{
if($i == 0)
$pathex = array_slice($pathex, 1);
else
$pathex = array_merge(array_slice($pathex, 0, $i), array_slice($pathex, $i + 2));
}
$tpl = implode("/", $pathex);
if($quiet)
{
$blocks_back = clone $this->blocks;
$blockorder_back = clone $this->blockorder;
}
$mode = MODE_TRANSCOMPILED;
$content = $this->storage_access->load($tpl, $mode);
if($mode == MODE_SOURCE)
{
$ast = parse($content);
$transc = transcompile($ast);
$this->storage_access->save($tpl, $transc, MODE_TRANSCOMPILED);
eval("\$content = $transc;");
}
$output = $content($ste);
$this->cur_tpl_dir = $tpldir_b4;
if($quiet)
{
$this->blocks = $blocks_back;
$this->blockorder = $blockorder_back;
}
else
return $output;
}
}
class STEStandardLibrary
{
static public function _register_lib($ste)
{
foreach(get_class_methods(__CLASS__) as $method)
if($method[0] != "_")
$ste->register_tag($method, array(__CLASS__, $method));
}
static public function escape($ste, $params, $sub)
{
return htmlentities($sub($ste), ENT_QUOTES, "UTF-8");
}
static public function strlen($ste, $params, $sub)
{
return strlen($sub($ste));
}
static public function array_len($ste, $params, $sub)
{
if(empty($params["var"]))
throw new Exception("Runtime Error: missing var parameter in <ste:array_len>.");
$a = $ste->get_var_by_name($params["var"]);
return (is_array($a)) ? count($a) : "";
}
}
?>
|