summaryrefslogtreecommitdiff
path: root/stupid_template_engine.php
blob: c67b1fd7dfa2dd735b5e2d37d28919109328afb1 (plain)
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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
<?php

/*
 * File: stupid_template_engine.php
 * The implementation of the Stupid Template Engine.
 * 
 * About: License
 * This file is licensed under the MIT/X11 License.
 * See COPYING for more details.
 */

/*
 * Namespace: ste
 * Everything in this file is in this namespace.
 */
namespace ste;

abstract class ASTNode
{
	public $tpl;
	public $offset;
	public function __construct($tpl, $off)
	{
		$this->tpl    = $tpl;
		$this->offset = $off;
	}
}

class TextNode extends ASTNode
{
	public $text;
	public function __construct($tpl, $off, $text = "") {
		parent::__construct($tpl, $off);
		$this->text = $text;
	}
}

class TagNode extends ASTNode
{
	public $name;
	public $params;
	public $sub;
}

class VariableNode extends ASTNode
{
	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;
	}
}

class ParseCompileError extends \Exception
{
	public $msg;
	public $tpl;
	public $off;
	
	public function __construct($msg, $tpl, $offset, $code = 0, $previous = NULL)
	{
		$this->msg = $msg;
		$this->tpl = $tpl;
		$this->off = $offset;
		$this->message = "$msg (Template $tpl, Offset $offset)";
	}
	
	public function rewrite($code)
	{
		$line = substr_count(str_replace("\r\n", "\n", substr($code, 0, $this->off)), "\n") + 1;
		$this->message = "{$this->msg} (Template {$this->tpl}, Line $line)";
		$this->is_rewritten = True;
	}
}

/*
 * Class: RuntimeError
 * An Exception that a tag can throw, if a non-fatal runtime error occurred.
 * By default this will return in no output at all. But if <STECore::$mute_runtime_errors> is false, this will generate a error message instead of the tag's output.
 */
class RuntimeError      extends \Exception {}

/*
 * Class: FatalRuntimeError
 * An Exception a tag can throw, if a fatal (irreparable) runtime error occurred.
 * This Exception will always "bubble up" so you probably want to catch them. Remember that this exception is also in the namespace ste!
 */
class FatalRuntimeError extends \Exception {}

class Parser {
	private $text;
	private $name;
	private $off;
	private $len;
	
	const PARSE_SHORT = 1;
	const PARSE_TAG   = 2;
	
	const ESCAPES_DEFAULT = '$?~{}|\\';
	
	private function __construct($text, $name) {
		$this->text = $text;
		$this->name = $name;
		$this->off  = 0;
		$this->len  = mb_strlen($text);
	}
	
	private function next($n = 1) {
		if($n <= 0) {
			throw new \InvalidArgumentException("\$n must be > 0");
		}
		$c = mb_substr($this->text, $this->off, $n);
		$this->off = min($this->off + $n, $this->len);
		return $c;
	}
	
	
	private function back($n = 1) {
		if($n <= 0) {
			throw new \InvalidArgumentException("\$n must be > 0");
		}
		$this->off = max($this->off - $n, 0);
	}
	
	private function search_off($needle) {
		return mb_strpos($this->text, $needle, $this->off);
	}
	
	private function search_multi($needles) {
		$oldoff = $this->off;
		
		$minoff = $this->len;
		$which = NULL;
		
		foreach($needles as $key => $needle) {
			if(($off = $this->search_off($needle)) === false) {
				continue;
			}

			if($off < $minoff) {
				$minoff = $off;
				$which = $key;
			}
		}
		
		$this->off = $minoff + (($which === NULL) ? 0 : mb_strlen((string) $needles[$which]));
		
		return array($which, $minoff, mb_substr($this->text, $oldoff, $minoff - $oldoff), $oldoff);
	}
	
	private function search($needle) {
		$oldoff = $this->off;
		
		$off = $this->search_off($needle);
		if($off === false) {
			$this->off = $this->len;
			return array(false, mb_substr($this->text, $oldoff), $oldoff);
		}
		
		$this->off = $off + mb_strlen($needle);
		return array($off, mb_substr($this->text, $oldoff, $off - $oldoff), $oldoff);
	}
	
	private function take_while($cb) {
		$s = "";
		while($c = $this->next()) {
			if(!call_user_func($cb, $c)) {
				$this->back();
				return $s;
			}
			$s .= $c;
		}
		return $s;
	}
	
	private function skip_ws() {
		$this->take_while("ctype_space");
	}
	
	private function get_name() {
		$off = $this->off;
		$name = $this->take_while(function($c) { return ctype_alnum($c) || ($c == "_"); });
		if(mb_strlen($name) == 0) {
			throw new ParseCompileError("Expected a name (alphanumeric chars + '_', at least one char)");
		}
		return $name;
	}
	
	public static function parse($text, $name) {
		$obj = new self($text, $name);
		$res = $obj->parse_text(
			self::ESCAPES_DEFAULT, /* Escapes */
			self::PARSE_SHORT | self::PARSE_TAG /* Flags */
		);
		return $res[0];
	}
	
	private function parse_text($escapes, $flags, $breakon = NULL, $separator = NULL, $nullaction = NULL, $opentag = NULL, $openedat = -1) {
		$elems = array();
		$astlist = array();
		
		$needles = array(
			"commentopen" => "<ste:comment>",
			"rawopen" => "<ste:rawtext>",
			"escape" => '\\',
			"varcurlyopen" => '${',
			"var" => '$',
		);
		
		if($flags & self::PARSE_TAG) {
			$needles["tagopen"] = '<ste:';
			$needles["closetagopen"] = '</ste:';
		}
		if($flags & self::PARSE_SHORT) {
			$needles["shortifopen"] = '?{';
			$needles["shortcompopen"] = '~{';
		}
		
		if($separator !== NULL) {
			$needles["sep"] = $separator;
		}
		if($breakon !== NULL) {
			$needles["break"] = $breakon;
		}
		
		for(;;) {
			list($which, $off, $before, $offbefore) = $this->search_multi($needles);
			
			$astlist[] = new TextNode($this->name, $offbefore, $before);
			
			switch($which) {
			case NULL:
				if($nullaction === NULL) {
					$elems[] = $astlist;
					return $elems;
				} else {
					call_user_func($nullaction);
				}
				break;
			case "commentopen":
				list($off, $before, $offbefore) = $this->search("</ste:comment>");
				if($off === false) {
					throw new ParseCompileError("ste:comment was not closed", $this->name, $offbefore);
				}
				break;
			case "rawopen":
				$off_start = $off;
				list($off, $before, $offbefore) = $this->search("</ste:rawtext>");
				if($off === false) {
					throw new ParseCompileError("ste:rawtext was not closed", $this->name, $off_start);
				}
				$astlist[] = new TextNode($this->name, $off_start, $before);
				break;
			case "tagopen":
				$astlist[] = $this->parse_tag($off);
				break;
			case "closetagopen":
				$off_start = $off;
				$name = $this->get_name();
				$this->skip_ws();
				$off = $this->off;
				if($this->next() != ">") {
					throw new ParseCompileError("Expected '>' in closing ste-Tag", $this->name, $off);
				}
				
				if($opentag === NULL) {
					throw new ParseCompileError("Found closing ste:$name tag, but no tag was opened", $this->name, $off_start);
				}
				if($opentag != $name) {
					throw new ParseCompileError("Open ste:$opentag was not closed", $this->name, $openedat);
				}
				
				$elems[] = $astlist;
				return $elems;
			case "escape":
				$c = $this->next();
				if(mb_strpos($escapes, $c) !== false) {
					$astlist[] = new TextNode($this->name, $off, $c);
				} else {
					$astlist[] = new TextNode($this->name, $off, '\\');
					$this->back();
				}
				break;
			case "shortifopen":
				$shortelems = $this->parse_short("?{", $off);
				if(count($shortelems) != 3) {
					throw new ParseCompileError("A short if tag must have the form ?{..|..|..}", $this->name, $off);
				}
				
				list($cond, $then, $else) = $shortelems;
				$thentag = new TagNode($this->name, $off);
				$thentag->name = "then";
				$thentag->sub = $then;
				
				$elsetag = new TagNode($this->name, $off);
				$elsetag->name = "else";
				$elsetag->sub = $else;
				
				$iftag = new TagNode($this->name, $off);
				$iftag->name = "if";
				$iftag->sub = $cond;
				$iftag->sub[] = $thentag;
				$iftag->sub[] = $elsetag;
				
				$astlist[] = $iftag;
				break;
			case "shortcompopen":
				$shortelems = $this->parse_short("~{", $off);
				if(count($shortelems) != 3) {
					throw new ParseCompileError("A short comparasion tag must have the form ~{..|..|..}", $this->name, $off);
				}
				
				// TODO: What will happen, if a tag was in one of the elements?
				list($a, $op, $b) = $shortelems;
				$cmptag = new TagNode($this->name, $off);
				$cmptag->name = "cmp";
				$cmptag->params["text_a"] = $a;
				$cmptag->params["op"] = $op;
				$cmptag->params["text_b"] = $b;
				
				$astlist[] = $cmptag;
				break;
			case "sep":
				$elems[] = $astlist;
				$astlist = array();
				break;
			case "varcurlyopen":
				$astlist[] = $this->parse_var($off, true);
				break;
			case "var":
				$astlist[] = $this->parse_var($off, false);
				break;
			case "break":
				$elems[] = $astlist;
				return $elems;
			}
		}
		
		$elems[] = $astlist;
		return $elems;
	}
	
	private function parse_short($shortname, $openedat) {
		$tplname = $this->name;
		
		return $this->parse_text(
			self::ESCAPES_DEFAULT, /* Escapes */
			self::PARSE_SHORT | self::PARSE_TAG, /* Flags */
			'}', /* Break on */
			'|', /* Separator */
			function() use ($shortname, $tplname, $openedat) { /* NULL action */
				throw new ParseCompileError("Unclosed $shortname", $tplname, $openedat);
			},
			NULL, /* Open tag */
			$openedat /* Opened at */
		);
	}
	
	private function parse_var($openedat, $curly) {
		$varnode = new VariableNode($this->name, $openedat);
		$varnode->name = $this->get_name();
		$varnode->arrayfields = $this->parse_array();
		
		if(!$curly) {
			return $varnode;
		}
		
		if($this->next() != "}") {
			throw new ParseCompileError("Unclosed '\${'", $this->name, $openedat);
		}
		$varnode->arrayfields = array_merge($varnode->arrayfields, $this->parse_array());
		return $varnode;
	}
	
	private function parse_array() {
		$tplname = $this->name;
		
		$arrayfields = array();
		
		while($this->next() == "[") {
			$openedat = $this->off - 1;
			$res = $this->parse_text(
				self::ESCAPES_DEFAULT, /* Escapes */
				0, /* Flags */
				']', /* Break on */
				NULL, /* Separator */
				function() use ($tplname, $openedat) { /* NULL action */
					throw new ParseCompileError("Unclosed array access '[...]'", $tplname, $openedat);
				},
				NULL, /* Open tag */
				$openedat /* Opened at */
			);
			$arrayfields[] = $res[0];
		}
		
		$this->back();
		return $arrayfields;
	}
	
	private function parse_tag($openedat) {
		$tplname = $this->name;
		
		$this->skip_ws();
		$tag = new TagNode($this->name, $openedat);
		$name = $tag->name = $this->get_name();
		$tag->params = array();
		$tag->sub = array();
		
		for(;;) {
			$this->skip_ws();
			
			switch($this->next()) {
			case '/': /* Self-closing tag */
				$this->skip_ws();
				if($this->next() != '>') {
					throw new ParseCompileError("Unclosed opening <ste: tag (expected >)", $this->name, $openedat);
				}
				
				return $tag;
			case '>':
				$tag->sub = $this->parse_text(
					self::ESCAPES_DEFAULT, /* Escapes */
					self::PARSE_SHORT | self::PARSE_TAG, /* Flags */
					NULL, /* Break on */
					NULL, /* Separator */
					function() use ($name, $tplname, $openedat) { /* NULL action */
						throw new ParseCompileError("Open ste:$name tag was not closed", $tplname, $openedat);
					},
					$tag->name, /* Open tag */
					$openedat /* Opened at */
				);
				return $tag;
			default:
				$this->back();
				
				$param = $this->get_name();
				
				$this->skip_ws();
				if($this->next() != '=') {
					throw new ParseCompileError("Expected '=' after tag parameter name", $this->name, $this->off - 1);
				}
				$this->skip_ws();
				
				$quot = $this->next();
				if(($quot != '"') && ($quot != "'")) {
					throw new ParseCompileError("Expected ' or \" after '=' of tag parameter", $this->name, $this->off - 1);
				}
				
				$off = $this->off - 1;
				$tag->params[$param] = $this->parse_text(
					self::ESCAPES_DEFAULT . $quot, /* Escapes */
					0, /* Flags */
					$quot, /* Break on */
					NULL, /* Separator */
					function() use ($quot, $tplname, $off) { /* NULL action */
						throw new ParseCompileError("Open tag parameter value ($quot) was not closed", $tplname, $off);
					},
					NULL, /* Open tag */
					$off /* Opened at */
				);
			}
		}
	}
}

/*
 * Function: parse
 * Parsing a STE T/PL template.
 * You only need this function, if you want to manually transcompile a template.
 * 
 * Parameters:
 * 	$code - The STE T/PL code.
 * 	$tpl  - The name of the template.
 * 
 * Returns:
 * 	An abstract syntax tree, which can be used with <transcompile>.
 */
function parse($code, $tpl)
{
	return mk_ast($code, $tpl, 0);
}

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 ($x === "0") or (!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 RuntimeError("Bracket mismatch.");
		}
		else if(!isset($operators[$token]))
			throw new RuntimeError("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 RuntimeError("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 RuntimeError("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 RuntimeError("Not enough numbers on stack. Invalid formula.");
				$stack[] = -$a;
				break;
			default:
				$stack[] = $token;
				break;
		}
	}
	return array_pop($stack);
}

function loopbody($code)
{
	return "try\n{\n" . indent_code($code) . "\n}\ncatch(\ste\BreakException \$e) { break; }\ncatch(\ste\ContinueException \$e) { continue; }\n";
}

$ste_builtins = array(
	"if" => function($ast)
	{
		$output = "";
		$condition = array();
		$then = NULL;
		$else = NULL;
		
		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($then === NULL)
			throw new ParseCompileError("Transcompile error: Missing <ste:then> in <ste:if>.", $ast->tpl, $ast->offset);
		
		$output .= "\$outputstack[] = \"\";\n\$outputstack_i++;\n";
		$output .= _transcompile($condition);
		$output .= "\$outputstack_i--;\nif(\$ste->evalbool(array_pop(\$outputstack)))\n{\n";
		$output .= indent_code(_transcompile($then));
		$output .= "\n}\n";
		if($else !== NULL)
		{
			$output .= "else\n{\n";
			$output .= indent_code(_transcompile($else));
			$output .= "\n}\n";
		}
		return $output;
	},
	"cmp" => function($ast)
	{
		$operators = array(
			array('eq', '=='),
			array('neq', '!='),
			array('lt', '<'),
			array('lte', '<='),
			array('gt', '>'),
			array('gte', '>=')
		);
		
		$code = "";
		
		if(isset($ast->params["var_b"]))
			$b = '$ste->get_var_by_name(' . _transcompile($ast->params["var_b"], True) . ')';
		else if(isset($ast->params["text_b"]))
			$b = _transcompile($ast->params["text_b"], True);
		else
			throw new ParseCompileError("Transcompile error: neiter var_b nor text_b set in <ste:cmp>.", $ast->tpl, $ast->offset);
		
		if(isset($ast->params["var_a"]))
			$a = '$ste->get_var_by_name(' . _transcompile($ast->params["var_a"], True) . ')';
		else if(isset($ast->params["text_a"]))
			$a = _transcompile($ast->params["text_a"], True);
		else
			throw new ParseCompileError("Transcompile error: neiter var_a nor text_a set in <ste:cmp>.", $ast->tpl, $ast->offset);
		
		if(!isset($ast->params["op"]))
			throw new ParseCompileError("Transcompile error: op not given in <ste:cmp>.", $ast->tpl, $ast->offset);
		if((count($ast->params["op"]) == 1) and ($ast->params["op"][0] instanceof TextNode))
		{
			/* Operator is known at compile time, this saves *a lot* of output code! */
			$op = trim($ast->params["op"][0]->text);
			$op_php = NULL;
			foreach($operators as $v)
			{
				if($v[0] == $op)
				{
					$op_php = $v[1];
					break;
				}
			}
			if($op_php === NULL)
				throw new ParseCompileError("Transcompile Error: Unknown operator in <ste:cmp>", $ast->tpl, $ast->offset);
			$code .= "\$outputstack[\$outputstack_i] .= (($a) $op_php ($b)) ? 'yes' : '';\n";
		}
		else
		{
			$code .= "switch(trim(" . _transcompile($ast->params["op"], True) . "))\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";
					}, $operators
				));
			$code .= "default: throw new \\ste\\RuntimeError('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->evalbool(array_pop(\$outputstack))) ? 'yes' : '';\n";
		return $code;
	},
	"even" => function($ast)
	{
		$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
		$code .= _transcompile($ast->sub);
		$code .= "\$outputstack_i--;\n\$tmp_even = array_pop(\$outputstack);\n\$outputstack[\$outputstack_i] .= (is_numeric(\$tmp_even) and (\$tmp_even % 2 == 0)) ? 'yes' : '';\n";
		return $code;
	},
	"for" => function($ast)
	{
		$code = "";
		$loopname = "forloop_" . str_replace(".", "_", uniqid("",True));
		if(empty($ast->params["start"]))
			throw new ParseCompileError("Transcompile error: Missing 'start' parameter in <ste:for>.", $ast->tpl, $ast->offset);
		$code .= "\$${loopname}_start = " . _transcompile($ast->params["start"], True) . ";\n";
		
		if(empty($ast->params["stop"]))
			throw new ParseCompileError("Transcompile error: Missing 'end' parameter in <ste:for>.", $ast->tpl, $ast->offset);
		$code .= "\$${loopname}_stop = " . _transcompile($ast->params["stop"], True) . ";\n";
		
		$step = NULL; /* i.e. not known at compilation time */
		if(empty($ast->params["step"]))
			$step = 1;
		else if((count($ast->params["step"]) == 1) and ($ast->params["step"][0] instanceof TextNode))
			$step = $ast->params["step"][0]->text + 0;
		else
			$code .= "\$${loopname}_step = " . _transcompile($ast->params["step"], True) . ";\n";
		
		if(!empty($ast->params["counter"]))
			$code .= "\$${loopname}_countername = " . _transcompile($ast->params["counter"], True) . ";\n";
		
		$loopbody = empty($ast->params["counter"]) ? "" : "\$ste->set_var_by_name(\$${loopname}_countername, \$${loopname}_counter);\n";
		$loopbody .= _transcompile($ast->sub);
		$loopbody = indent_code("{\n" . loopbody(indent_code($loopbody)) . "\n}\n");
		
		if($step === NULL)
		{
			$code .= "if(\$${loopname}_step == 0)\n\tthrow new \\ste\\RuntimeError('step can not be 0 in <ste:for>.');\n";
			$code .= "if(\$${loopname}_step > 0)\n{\n";
			$code .= "\tfor(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_counter <= \$${loopname}_stop; \$${loopname}_counter += \$${loopname}_step)\n";
			$code .= $loopbody;
			$code .= "\n}\nelse\n{\n";
			$code .= "\tfor(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_counter >= \$${loopname}_stop; \$${loopname}_counter += \$${loopname}_step)\n";
			$code .= $loopbody;
			$code .= "\n}\n";
		}
		else if($step == 0)
			throw new ParseCompileError("Transcompile Error: step can not be 0 in <ste:for>.", $ast->tpl, $ast->offset);
		else if($step > 0)
			$code .= "for(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_counter <= \$${loopname}_stop; \$${loopname}_counter += $step)\n$loopbody\n";
		else
			$code .= "for(\$${loopname}_counter = \$${loopname}_start; \$${loopname}_counter >= \$${loopname}_stop; \$${loopname}_counter += $step)\n$loopbody\n";
		
		return $code;
	},
	"foreach" => function($ast)
	{
		$loopname = "foreachloop_" . str_replace(".", "_", uniqid("",True));
		$code = "";
		
		if(empty($ast->params["array"]))
			throw new ParseCompileError("Transcompile Error: array not given in <ste:foreach>.", $ast->tpl, $ast->offset);
		$code .= "\$${loopname}_arrayvar = " . _transcompile($ast->params["array"], True) . ";\n";
		
		if(empty($ast->params["value"]))
			throw new ParseCompileError("Transcompile Error: value not given in <ste:foreach>.", $ast->tpl, $ast->offset);
		$code .= "\$${loopname}_valuevar = " . _transcompile($ast->params["value"], True) . ";\n";
		
		if(!empty($ast->params["key"]))
			$code .= "\$${loopname}_keyvar = " . _transcompile($ast->params["key"], True) . ";\n";
		
		if(!empty($ast->params["counter"]))
			$code .= "\$${loopname}_countervar = " . _transcompile($ast->params["counter"], True) . ";\n";
		
		$loopbody = "";
		$code .= "\$${loopname}_array = \$ste->get_var_by_name(\$${loopname}_arrayvar);\n";
		$code .= "if(!is_array(\$${loopname}_array))\n\t\$${loopname}_array = array();\n";
		if(!empty($ast->params["counter"]))
		{
			$code .= "\$${loopname}_counter = -1;\n";
			$loopbody .= "\$${loopname}_counter++;\n\$ste->set_var_by_name(\$${loopname}_countervar, \$${loopname}_counter);\n";
		}
		
		$loopbody .= "\$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";
		$loopbody .= "\n";
		$loopbody .= _transcompile($ast->sub);
		$loopbody = "{\n" . loopbody(indent_code($loopbody)) . "\n}\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(loopbody(indent_code(_transcompile($ast->sub)))) . "\n}\n";
	},
	"break" => function($ast)
	{
		return "throw new \\ste\\BreakException();\n";
	},
	"continue" => function($ast)
	{
		return "throw new \\ste\\ContinueException();\n";
	},
	"block" => function($ast)
	{
		if(empty($ast->params["name"]))
			throw new ParseCompileError("Transcompile Error: name missing in <ste:block>.", $ast->tpl, $ast->offset);
		
		$blknamevar = "blockname_" . str_replace(".", "_", uniqid("", True));
		
		$code = "\$${blknamevar} = " . _transcompile($ast->params["name"], True) . ";\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[] = \$${blknamevar};\n\$outputstack = array('');\n\$outputstack_i = 0;\n";
		
		return $code;
	},
	"load" => function($ast)
	{
		if(empty($ast->params["name"]))
			throw new ParseCompileError("Transcompile Error: name missing in <ste:load>.", $ast->tpl, $ast->offset);
		
		return "\$outputstack[\$outputstack_i] .= \$ste->load(" . _transcompile($ast->params["name"], True) . ");\n";
	},
	"mktag" => function($ast)
	{
		if(empty($ast->params["name"]))
			throw new ParseCompileError("Transcompile Error: name missing in <ste:mktag>.", $ast->tpl, $ast->offset);
		
		$tagname = _transcompile($ast->params["name"], True);
		
		$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 \\ste\\RuntimeError(\"\$mp missing in <ste:\" . $tagname . \">.\");\n}";
		}
		
		$fxbody .= _transcompile($ast->sub);
		$fxbody .= "return array_pop(\$outputstack);";
		
		$code .= "\$tag_fx = function(\$ste, \$params, \$sub) use (\$mandatory_params)\n{\n" . indent_code($fxbody) . "\n};\n";
		$code .= "\$ste->register_tag($tagname, \$tag_fx);\n";
		
		return $code;
	},
	"tagcontent" => function($ast)
	{
		return "\$outputstack[\$outputstack_i] .= \$sub(\$ste);";
	},
	"set" => function($ast)
	{
		if(empty($ast->params["var"]))
			throw new ParseCompileError("Transcompile Error: var missing in <ste:set>.", $ast->tpl, $ast->offset);
		
		$code = "\$outputstack[] = '';\n\$outputstack_i++;\n";
		$code .= _transcompile($ast->sub);
		$code .= "\$outputstack_i--;\n";
		
		$code .= "\$ste->set_var_by_name(" . _transcompile($ast->params["var"], True) . ", array_pop(\$outputstack));\n";
		
		return $code;
	},
	"get" => function($ast)
	{
		if(empty($ast->params["var"]))
			throw new ParseCompileError("Transcompile Error: var missing in <ste:get>.", $ast->tpl, $ast->offset);
		
		return "\$outputstack[\$outputstack_i] .= \$ste->get_var_by_name(" . _transcompile($ast->params["var"],  True) . ");";
	},
	"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, "\r\n\t\$\0..\x1f\\\"\x7f..\xff");
}

function _transcompile($ast, $no_outputstack = False) /* The real transcompile function, does not add boilerplate code. */
{
	$code = "";
	global $ste_builtins;
	
	$text_and_var_buffer = array();
	
	foreach($ast as $node)
	{
		if($node instanceof TextNode)
			$text_and_var_buffer[] = '"' . escape_text($node->text) . '"';
		else if($node instanceof VariableNode)
			$text_and_var_buffer[] = $node->transcompile();
		else if($node instanceof TagNode)
		{
			if(!empty($text_and_var_buffer))
			{
				$code .= "\$outputstack[\$outputstack_i] .= " . implode (" . ", $text_and_var_buffer) . ";\n";
				$text_and_var_buffer = array();
			}
			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 .= "\$${paramarray}['" . escape_text($pname) . "'] = " . _transcompile($pcontent, True) . ";\n";
				
				$code .= "\$outputstack[\$outputstack_i] .= \$ste->call_tag('" . escape_text($node->name) . "', \$${paramarray}, ";
				$code .= empty($node->sub) ? "function(\$ste) { return ''; }" : transcompile($node->sub);
				$code .= ");\n";
			}
		}
	}
	
	if(!empty($text_and_var_buffer))
	{
		if(!$no_outputstack)
			$code .= "\$outputstack[\$outputstack_i] .= ";
		$code .= implode (" . ", $text_and_var_buffer);
		if(!$no_outputstack)
			$code .= ";\n";
		$text_and_var_buffer = array();
	}
	else if($no_outputstack)
	{
		$code = "\"\"";
	}
	
	return $code;
}

$ste_transc_boilerplate = "\$outputstack = array('');\n\$outputstack_i = 0;\n";

/*
 * Function: transcompile
 * Transcompiles an abstract syntax tree to PHP.
 * You only need this function, if you want to manually transcompile a template.
 * 
 * Parameters:
 * 	$ast - The abstract syntax tree to transcompile.
 * 
 * Returns:
 * 	PHP code. The PHP code is an anonymous function expecting a <STECore> instance as its parameter and returns a string (everything that was not pached into a section).
 */
function transcompile($ast) /* Transcompile and add some boilerplate code. */
{
	global $ste_transc_boilerplate;
	return "function(\$ste)\n{\n" . indent_code($ste_transc_boilerplate . _transcompile($ast) . "return array_pop(\$outputstack);") . "\n}";
}

/*
 * Constants: Template modes
 * 
 * MODE_SOURCE - The Templates source
 * MODE_TRANSCOMPILED - The transcompiled template
 */
const MODE_SOURCE        = 0;
const MODE_TRANSCOMPILED = 1;

abstract class StorageAccessFailure extends \Exception { }

/*
 * Class: CantLoadTemplate
 * An exception that a <StorageAccess> implementation can throw, if it is unable to load a template.
 */
class CantLoadTemplate extends StorageAccessFailure { }

/*
 * Class: CantSaveTemplate
 * An exception that a <StorageAccess> implementation can throw, if it is unable to save a template.
 */
class CantSaveTemplate extends StorageAccessFailure { }

/*
 * Class: StorageAccess
 * An interface.
 * A StorageAccess implementation is used to access the templates from any storage.
 * This means, that you are not limited to store the Templates inside directories, you can also use a database or something else.
 */
interface StorageAccess
{
	/*
	 * Function: load
	 * Loading a template.
	 * 
	 * Parameters:
	 * 	$tpl - The name of the template.
	 * 	&$mode - Which mode is preferred? One of the <Template modes>.
	 * 	         If <MODE_SOURCE>, the raw sourcecode is expected, if <MODE_TRANSCOMPILED> the transcompiled template *as a callable function* (expecting an <STECore> instance as first parameter) is expected.
	 * 	         If the transcompiled version is not available or older than the source, you can set this parameter to <MODE_SOURCE> and return the source.
	 * 
	 * Throws:
	 * 	A <CantLoadTemplate> exception if the template could not be loaded.
	 * 
	 * Returns:
	 * 	Either the sourcecode or a callable function (first, and only parameter: an <STECore> instance).
	 */
	public function load($tpl, &$mode);
	
	/*
	 * Function: save
	 * Saves a template.
	 * 
	 * Throws:
	 * 	A <CantSaveTemplate> exception if the template could not be saved.
	 * 
	 * Parameters:
	 * 	$tpl -The name of the template.
	 * 	$data - The data to be saved.
	 * 	$mode - A <Template mode> constant.
	 */
	public function save($tpl, $data, $mode);
}

/*
 * Class: FilesystemStorageAccess
 * The default <StorageAccess> implementation for loading / saving templates into a directory structure.
 */
class FilesystemStorageAccess implements StorageAccess
{
	protected $sourcedir;
	protected $transcompileddir;
	
	/*
	 * Constructor: __construct
	 * 
	 * Parameters:
	 * 	$src - The directory with the sources (Writing permissions are not mandatory, because STE does not save template sources).
	 * 	$transc - The directory with the transcompiled templates (the PHP instance / the HTTP Server needs writing permissions to this directory).
	 */
	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 . ".php";
		
		if($mode == MODE_SOURCE)
		{
			$content = @file_get_contents($src_fn);
			if($content === False)
				throw new CantLoadTemplate("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 CantLoadTemplate("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)
	{
		$fn = (($mode == MODE_SOURCE) ? $this->sourcedir : $this->transcompileddir) . "/" . $tpl . (($mode == MODE_TRANSCOMPILED) ? ".php" : "");
		@mkdir(dirname($fn), 0777, True);
		if(file_put_contents($fn, "<?php \$transcompile_fx = $data; ?>") === False)
			throw new CantSaveTemplate("Unable to save template.");
			
	}
}

class BreakException    extends \Exception { }
class ContinueException extends \Exception { }

/*
 * Class: STECore
 * The Core of STE
 */
class STECore
{
	private $tags;
	private $storage_access;
	private $cur_tpl_dir;
	
	/*
	 * Variables: Public variables
	 * 
	 * $blocks - Associative array of blocks (see the language definition).
	 * $blockorder - The order of the blocks (an array)
	 * $vars - Associative array of all template variables. Use this to pass data to your templates.
	 * $mute_runtime_errors - If True (default) a <RuntimeError> exception will result in no output from the tag, if False a error message will be written to output.
	 * $fatal_error_on_missing_tag - If True, STE will throw a <FatalRuntimeError> if a tag was called that was not registered, otherwise (default) a regular <RuntimeError> will be thrown and automatically handled by STE (see <$mute_runtime_errors>).
	 */
	public $blocks;
	public $blockorder;
	public $vars;
	public $mute_runtime_errors = True;
	public $fatal_error_on_missing_tag = False;
	
	/*
	 * Constructor: __construct
	 * 
	 * Parameters:
	 * 	$storage_access - An Instance of a <StorageAccess> implementation.
	 */
	public function __construct($storage_access)
	{
		$this->storage_access = $storage_access;
		$this->cur_tpl_dir = "/";
		STEStandardLibrary::_register_lib($this);
		$this->vars = array();
		$this->blockorder = array();
		$this->blocks = array();
	}
	
	/*
	 * Function: register_tag
	 * Register a custom tag.
	 * 
	 * Parameters:
	 * 	$name - The name of the tag.
	 * 	$callback - A callable function (This must take three parameters: The <STECore> instance, an associative array of parameters, and a function representing the tags content(This expects the <STECore> instance as its only parameter and returns its text result, i.e to get the text, you neeed to call this function with the <STECore> instance as a parameter)).
	 * 
	 * Throws:
	 * 	An Exception if the tag could not be registered (if $callback is not callable or if $name is empty)
	 */
	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;
	}
	
	/*
	 * Function: call_tag
	 * Calling a custom tag (builtin ones can not be called)
	 * 
	 * Parameters:
	 * 	$name - The Tag's name
	 * 	$params - Associative array of parameters
	 * 	$sub - A callable function (expecting an <STECore> instance as it's parameter) that represents the tag's content.
	 * 
	 * Throws:
	 * 	Might throw a <FatalRuntimeError> (see <$fatal_error_on_missing_tag>.
	 * 
	 * Returns:
	 * 	The output of the tag or, if a <RuntimeError> was thrown, the appropiate result (see <$mute_runtime_errors>).
	 */
	public function call_tag($name, $params, $sub)
	{
		try
		{
			if(!isset($this->tags[$name]))
			{
				if($this->fatal_error_on_missing_tag)
					throw new FatalRuntimeError("Can not call tag \"$name\": Does not exist.");
				else
					throw new RuntimeError("Can not call tag \"$name\": Does not exist.");
			}
			return call_user_func($this->tags[$name], $this, $params, $sub);
		}
		catch(RuntimeError $e)
		{
			if(!$this->mute_runtime_errors)
				return "RuntimeError occurred on tag '$name': " . $e->getMessage();
		}
	}
	
	public function calc($expression)
	{
		return calc_rpn(shunting_yard($expression));
	}
	
	/*
	 * Function: exectemplate
	 * Executes a template and returns the result. The huge difference to <load> is that this function will also output all blocks.
	 * 
	 * Parameters:
	 * 	$tpl - The name of the template to execute.
	 * 
	 * Throws:
	 * 	* A <CantLoadTemplate> exception if the template could not be loaded.
	 * 	* A <ParseCompileError> if the template could not be parsed or transcompiled.
	 * 	* A <FatalRuntimeError> if a tag threw it or if a tag was not found and <$fatal_error_on_missing_tag> is true.
	 * 	* Might also throw different exceptions, if a external tag threw it (but they should use <RuntimeError> or <FatalRuntimeError> to make it possible for STE to handle them correctly).
	 * 
	 * Returns:
	 * 	The output of the template.
	 */
	public function exectemplate($tpl)
	{
		$output = "";
		$lastblock = $this->load($tpl);
		
		foreach($this->blockorder as $blockname)
			$output .= $this->blocks[$blockname];
		
		return $output . $lastblock;
	}
	
	/*
	 * Function: get_var_reference
	 * Get a reference to a template variable using a variable name.
	 * This can be used,if your custom tag takes a variable name as a parameter.
	 * 
	 * Parameters:
	 * 	$name - The variables name.
	 * 	$create_if_not_exist - Should the variable be created, if it does not exist? Otherwise NULL will be returned, if the variable does not exist.
	 * 
	 * Throws:
	 * 	<RuntimeError> if the variable name can not be parsed (e.g. unbalanced brackets).
	 * 
	 * Returns:
	 * 	A Reference to the variable.
	 */
	
	public function &get_var_reference($name, $create_if_not_exist)
	{
		$ref = &$this->_get_var_reference($this->vars, $name, $create_if_not_exist);
		return $ref;
	}
	
	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)
			{
				$ref = &$from[$name];
				return $ref;
			}
			else
				return NULL;
		}
		else
		{
			$old_varname = $varname;
			$bracket_close = strpos($name, "]", $bracket_open);
			if($bracket_close === FALSE)
				throw new RuntimeError("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
			{
				$ref = &$this->_get_var_reference($from[$varname], $name, $create_if_not_exist);
				return $ref;
			}
			catch(Exception $e)
			{
				throw new RuntimeError("Invalid varname \"$old_varname\". Missing closing \"]\".");
			}
		}
	}
	
	/*
	 * Function: set_var_by_name
	 * Set a template variable by its name.
	 * This can be used,if your custom tag takes a variable name as a parameter.
	 * 
	 * Parameters:
	 * 	$name - The variables name.
	 * 	$val - The new value.
	 * 
	 * Throws:
	 * 	<RuntimeError> if the variable name can not be parsed (e.g. unbalanced brackets).
	 */
	public function set_var_by_name($name, $val)
	{
		$ref = &$this->_get_var_reference($this->vars, $name, True);
		$ref = $val;
	}
	
	/*
	 * Function: get_var_by_name
	 * Get a template variable by its name.
	 * This can be used,if your custom tag takes a variable name as a parameter.
	 * 
	 * Parameters:
	 * 	$name - The variables name.
	 * 
	 * Throws:
	 * 	<RuntimeError> if the variable name can not be parsed (e.g. unbalanced brackets).
	 * 
	 * Returns:
	 * 	The variables value.
	 */
	public function get_var_by_name($name)
	{
		$ref = $this->_get_var_reference($this->vars, $name, False);
		return $ref === NULL ? "" : $ref;
	}
	
	/*
	 * Function: load
	 * Load a template and return its result (blocks not included, use <exectemplate> for this).
	 * 
	 * Parameters:
	 * 	$tpl - The name of the template to be loaded.
	 * 	$quiet - If true, do not output anything and do notmodify the blocks. This can be useful to load custom tags that are programmed in STE T/PL. Default: false.
	 * 
	 * Throws:
	 * 	* A <CantLoadTemplate> exception if the template could not be loaded.
	 * 	* A <ParseCompileError> if the template could not be parsed or transcompiled.
	 * 	* A <FatalRuntimeError> if a tag threw it or if a tag was not found and <$fatal_error_on_missing_tag> is true.
	 * 	* Might also throw different exceptions, if a external tag threw it (but they should use <RuntimeError> or <FatalRuntimeError> to make it possible for STE to handle them correctly).
	 * 
	 * Returns:
	 * 	The result of the template (if $quiet == false).
	 */
	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(explode("/", $tpl), function($s) { return ($s != ".") and (!empty($s)); });
		$pathex = array_merge($pathex);
		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);
		$this->cur_tpl_dir = dirname($tpl);
		
		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)
		{
			try
			{
				$ast     = Parser::parse($content, $tpl);
				$transc  = transcompile($ast);
			}
			catch(ParseCompileError $e)
			{
				$e->rewrite($content);
				throw $e;
			}
			$this->storage_access->save($tpl, $transc, MODE_TRANSCOMPILED);
			eval("\$content = $transc;");
		}
		
		$output = $content($this);
		
		$this->cur_tpl_dir = $tpldir_b4;
		
		if($quiet)
		{
			$this->blocks     = $blocks_back;
			$this->blockorder = $blockorder_back;
		}
		else
			return $output;
	}
	
	/*
	 * Function: evalbool
	 * Test, if a text represents false (an empty / only whitespace text) or true (everything else).
	 * 
	 * Parameters:
	 * 	$txt - The text to test.
	 * 
	 * Returns:
	 * 	true/false.
	 */
	public function evalbool($txt)
	{
		return trim($txt . "") != "";
	}
}

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)
	{
		if($ste->evalbool($params["lines"]))
			return nl2br(htmlspecialchars(str_replace("\r\n", "\n", $sub($ste))));
		else
			return htmlspecialchars($sub($ste));
	}
	
	static public function strlen($ste, $params, $sub)
	{
		return strlen($sub($ste));
	}
	
	static public function arraylen($ste, $params, $sub)
	{
		if(empty($params["array"]))
			throw new RuntimeError("Missing array parameter in <ste:arraylen>.");
		$a = $ste->get_var_by_name($params["array"], False);
		return (is_array($a)) ? count($a) : "";
	}
	
	static public function inc($ste, $params, $sub)
	{
		if(empty($params["var"]))
			throw new RuntimeError("Missing var parameter in <ste:inc>.");
		$ref = &$ste->get_var_reference($params["var"], True);
		$ref++;
	}
	
	static public function dec($ste, $params, $sub)
	{
		if(empty($params["var"]))
			throw new RuntimeError("Missing var parameter in <ste:dec>.");
		$ref = &$ste->get_var_reference($params["var"], True);
		$ref--;
	}
	
	static public function date($ste, $params, $sub)
	{
		return @strftime($sub($ste), empty($params["timestamp"]) ? @time() : (int) $params["timestamp"]);
	}
	
	static public function in_array($ste, $params, $sub)
	{
		if(empty($params["array"]))
			throw new RuntimeError("Missing array parameter in <ste:in_array>.");
		$ar = &$ste->get_var_reference($params["array"], False);
		if(!is_array($ar))
			return "";
		return in_array($sub($ste), $ar) ? "y" : "";
	}
	
	static public function join($ste, $params, $sub)
	{
		if(empty($params["array"]))
			throw new RuntimeError("Missing array parameter in <ste:join>.");
		return implode($sub($ste), $ste->get_var_by_name($params["array"]));
	}
	
	static public function split($ste, $params, $sub)
	{
		if(empty($params["array"]))
			throw new RuntimeError("Missing array parameter in <ste:split>.");
		if(empty($params["delim"]))
			throw new RuntimeError("Missing delim parameter in <ste:split>.");
		$ste->set_var_by_name($params["array"], explode($params["delim"], $sub($ste)));
	}
	
	static public function array_add($ste, $params, $sub)
	{
		if(empty($params["array"]))
			throw new RuntimeError("Missing array parameter in <ste:array_add>.");
		
		$ar = &$ste->get_var_reference($params["array"], True);
		if(empty($params["key"]))
			$ar[] = $sub($ste);
		else
			$ar[$params["key"]] = $sub($ste);
	}
	
	static public function array_filter($ste, $params, $sub)
	{
		if(empty($params["array"]))
			throw new RuntimeError("Missing array parameter in <ste:array_filter>.");
		
		$ar = $ste->get_var_by_name($params["array"]);
		if(!is_array($ar))
			throw new RuntimeError("Variable at 'array' is not an array.");
		
		$keys = array_keys($ar);
		
		if(!empty($params["keep_by_keys"]))
		{
			$keep_by_keys = &$ste->get_var_reference($params["keep_by_keys"], False);
			if(!is_array($keep_by_keys))
				throw new RuntimeError("Variable at 'keep_by_keys' is not an array.");
			$delkeys = array_filter($keys, function($k) use ($keep_by_keys) { return !in_array($k, $keep_by_keys); });
			foreach($delkeys as $dk)
				unset($ar[$dk]);
			$keys = array_keys($ar);
		}
		if(!empty($params["keep_by_values"]))
		{
			$keep_by_values = &$ste->get_var_reference($params["keep_by_values"], False);
			if(!is_array($keep_by_values))
				throw new RuntimeError("Variable at 'keep_by_values' is not an array.");
			$ar = array_filter($ar, function($v) use ($keep_by_values) { return in_array($v, $keep_by_values); });
			$keys = array_keys($ar);
		}
		if(!empty($params["delete_by_keys"]))
		{
			$delete_by_keys = &$ste->get_var_reference($params["delete_by_keys"], False);
			if(!is_array($delete_by_keys))
				throw new RuntimeError("Variable at 'delete_by_keys' is not an array.");
			$delkeys = array_filter($keys, function($k) use ($delete_by_keys) { return in_array($k, $delete_by_keys); });
			foreach($delkeys as $dk)
				unset($ar[$dk]);
			$keys = array_keys($ar);
		}
		if(!empty($params["delete_by_values"]))
		{
			$delete_by_values = &$ste->get_var_reference($params["delete_by_values"], False);
			if(!is_array($delete_by_values))
				throw new RuntimeError("Variable at 'delete_by_values' is not an array.");
			$ar = array_filter($ar, function($v) use ($delete_by_values) { return !in_array($v, $delete_by_values); });
			$keys = array_keys($ar);
		}
		
		$ste->set_var_by_name($params["array"], $ar);
	}
}

?>