-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathXTemplate.php
More file actions
1991 lines (1829 loc) · 68.5 KB
/
Copy pathXTemplate.php
File metadata and controls
1991 lines (1829 loc) · 68.5 KB
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
<?php
/**
* XTemplate SE class library. A fast and lightweight block template engine.
* This implementation is inspired by and derived from the CoTemplate class
* of the Cotonti project (https://www.cotonti.com), licensed under the
* BSD 3-Clause "New" License (https://github.com/Cotonti/Cotonti/blob/master/License.txt).
* While maintaining compatibility with the original XTemplate concept
* (http://www.phpxtemplate.org), this version extends functionality with
* additional features such as enhanced expression parsing, advanced
* caching mechanisms, and improved debugging capabilities, tailored
* for broader use cases while preserving the lightweight and efficient
* design philosophy of CoTemplate.
*
* Copyright (c) 2024-2025, Seditio Team
* Copyright (c) 2008-2025, Cotonti Team
* Copyright (c) 2001-2008, Neocrome
*
* This software is licensed under the BSD 3-Clause License. See the LICENSE
* file in the root of this project for details.
*
* @package API - XTemplate SE
* @version 1.2.1
* @license BSD 3-Clause License
*/
class XTemplate
{
// Instance properties
/** @var string $filename Path to the template file */
public $filename = '';
/** @var array $vars Associative array of assigned variables */
public $vars = array();
/** @var array $blocks Array of parsed template blocks */
protected $blocks = array();
/** @var array $displayed_blocks Tracks blocks displayed for debugging */
protected $displayed_blocks = array();
/** @var array $index Index mapping block names to their paths */
protected $index = array();
/** @var array|null $tags Cached array of tags used in the template */
protected $tags = null;
/** @var bool $cacheEnabled Global flag for enabling/disabling caching */
protected static $cacheEnabled = false;
/** @var string $cacheDir Directory path for cache storage */
protected static $cacheDir = '';
/** @var bool $debug Instance-specific debug mode flag */
public $debug = false;
/** @var bool $debugOutput Instance-specific debug output flag */
public $debugOutput = false;
/** @var bool $cleanupEnabled Global flag for enabling/disabling HTML cleanup */
private static $cleanupEnabled = false;
/** @var bool $found Flag indicating if blocks were found during compilation */
private $found = false;
/** @var XtplCache|null $cache Cache handler instance */
private $cache = null;
/** @var bool $defaultDebug Default debug mode for new instances */
protected static $defaultDebug = false;
/** @var bool $defaultDebugOutput Default debug output for new instances */
protected static $defaultDebugOutput = false;
// New properties for function filter management
/**
* @var string $functionFilterMode Defines the mode for filtering function calls:
* - 'all': All functions are allowed (default, matches current behavior).
* - 'whitelist': Only functions in $allowedFunctions are permitted.
* - 'blacklist': Functions in $disallowedFunctions are blocked, others are allowed.
*/
public static $functionFilterMode = 'blacklist';
/**
* @var array $allowedFunctions List of functions permitted in 'whitelist' mode.
*/
public static $allowedFunctions = [
'strtoupper', 'strtolower', 'ucwords', 'ucfirst', 'strrev', 'str_word_count', 'strlen',
'str_replace', 'str_ireplace', 'preg_replace', 'strip_tags', 'stripcslashes', 'stripslashes', 'substr',
'str_pad', 'str_repeat', 'strtr', 'trim', 'ltrim', 'rtrim', 'nl2br', 'wordwrap', 'printf', 'sprintf',
'addslashes', 'addcslashes',
'htmlentities', 'html_entity_decode', 'htmlspecialchars', 'htmlspecialchars_decode',
'urlencode', 'urldecode',
'date', 'idate', 'strtotime', 'strftime', 'getdate', 'gettimeofday',
'number_format', 'money_format',
'var_dump', 'print_r'
];
/**
* @var array $disallowedFunctions List of functions blocked in 'blacklist' mode.
* Default includes common dangerous functions for security.
*/
public static $disallowedFunctions = [
'eval', 'system', 'exec', 'shell_exec', 'passthru', 'proc_open', 'popen', 'phpinfo', 'unlink',
'fopen', 'file_put_contents', 'readfile', 'chmod', 'chown', 'chgrp', 'file_get_contents', 'file',
'fsockopen', 'pfsockopen', 'curl_exec', 'curl_multi_exec', 'parse_ini_file', 'show_source', 'ini_set',
'ini_get', 'ob_start', 'ob_end_flush', 'ob_get_clean', 'ob_get_contents', 'getimagesize', 'set_time_limit',
'assert', 'proc_terminate', 'proc_close', 'stream_socket_server', 'stream_socket_accept', 'proc_nice', 'dl'
];
/**
* Configures global settings for XTemplate instances. Must be called before creating instances.
*
* @param array $settings Associative array of settings:
* - 'cacheEnabled' (bool): Enable/disable caching.
* - 'cacheDir' (string): Cache storage directory path.
* - 'debug' (bool): Enable/disable debug mode for all instances.
* - 'debugOutput' (bool): Enable/disable debug output for all instances.
* - 'cleanupEnabled' (bool): Enable/disable HTML cleanup.
* - 'functionFilterMode' (string): Mode for function filtering.
* - 'allowedFunctions' (array): Functions allowed in whitelist mode.
* - 'disallowedFunctions' (array): Functions blocked in blacklist mode.
*/
public static function configure(array $settings = [])
{
// Use current static property values as defaults, override with provided settings
$currentSettings = [
'cacheEnabled' => self::$cacheEnabled,
'cacheDir' => self::$cacheDir,
'debug' => self::$defaultDebug,
'debugOutput' => self::$defaultDebugOutput,
'cleanupEnabled' => self::$cleanupEnabled,
'functionFilterMode' => self::$functionFilterMode,
'allowedFunctions' => self::$allowedFunctions,
'disallowedFunctions' => self::$disallowedFunctions,
];
// Merge user-provided settings with current values
$settings = array_merge($currentSettings, $settings);
// Apply settings to static properties
self::$cacheEnabled = $settings['cacheEnabled'];
self::$cacheDir = $settings['cacheDir'];
self::$defaultDebug = $settings['debug'];
self::$defaultDebugOutput = $settings['debugOutput'];
self::$cleanupEnabled = $settings['cleanupEnabled'];
self::$functionFilterMode = $settings['functionFilterMode'];
self::$allowedFunctions = $settings['allowedFunctions'];
self::$disallowedFunctions = $settings['disallowedFunctions'];
}
/**
* Constructs an XTemplate instance, optionally initializing with a template file path.
*
* @param string|null $path The path to the template file. If provided, the template is loaded immediately.
*/
public function __construct($path = null)
{
// Set default values for instance properties
$this->debug = self::$defaultDebug;
$this->debugOutput = self::$defaultDebugOutput;
if (self::$cacheEnabled) {
$this->cache = new XtplCache(self::$cacheDir);
}
if (is_string($path)) {
$this->restart($path);
}
}
/**
* Converts the template blocks to a string representation.
*
* @return string The string representation of all template blocks.
*/
public function __toString()
{
$str = '';
foreach ($this->blocks as $name => $block) {
$str .= "<!-- BEGIN: $name -->\n" . $block->__toString() . "<!-- END: $name -->\n";
}
return $str;
}
/**
* Assigns variables to the template for use in rendering.
*
* @param string|array $name The variable name or an associative array of variables.
* @param mixed|null $val The value to assign if $name is a string.
* @param string $prefix A prefix to prepend to variable names.
* @return XTemplate Returns the current instance for method chaining.
*/
public function assign($name, $val = null, $prefix = '')
{
if (is_array($name)) {
foreach ($name as $key => $val) {
$this->vars[$prefix . $key] = $val;
}
} else {
$this->vars[$prefix . $name] = $val;
}
return $this;
}
/**
* Retrieves the debug data collected by the debugger.
*
* @return array The debug data array.
*/
public static function debugData()
{
return XtplDebugger::$data;
}
/**
* Formats a variable for debug output in HTML list format.
*
* @param string $name The name of the variable.
* @param mixed $value The value of the variable to debug.
* @return string The HTML-formatted debug output.
*/
public static function debugVar($name, $value)
{
if (is_numeric($value)) {
$val_disp = (string) $value;
} elseif (is_object($value)) {
$val_disp = get_class($value) . ' ' . json_encode((array) $value);
} elseif (is_array($value)) {
$val_disp = '<ul>';
foreach ($value as $key => $subValue) {
$val_disp .= self::debugVar($name . '.' . $key, $subValue);
}
$val_disp .= '</ul>';
} else {
$val_disp = '"' . htmlspecialchars((string) $value) . '"';
}
return '<li>{' . htmlspecialchars($name) . '} => <em>' . $val_disp . '</em></li>';
}
/**
* Retrieves the value of a specific template variable.
*
* @param string $name The name of the variable to retrieve.
* @return mixed The value of the variable, or null if not set.
*/
public function get($name)
{
return $this->vars[$name];
}
/**
* Gets all unique tags used in the template blocks.
*
* @return array An array of tag names.
*/
public function getTags()
{
if (is_null($this->tags)) {
$this->tags = array();
foreach ($this->blocks as $block) {
$this->tags = array_merge($this->tags, $block->getTags());
}
}
return array_keys($this->tags);
}
/**
* Checks if a block exists in the template.
*
* @param string $name The name of the block to check.
* @return bool True if the block exists, false otherwise.
*/
public function hasBlock($name)
{
return isset($this->index[$name]);
}
/**
* Checks if a tag exists in the template.
*
* @param string $name The name of the tag to check.
* @return bool True if the tag exists, false otherwise.
*/
public function hasTag($name)
{
if (is_null($this->tags)) {
$this->getTags();
}
return isset($this->tags[$name]);
}
/**
* Processes include file directives in the template code recursively.
*
* @param array $m The regex match array containing the file directive.
* @return string The processed content of the included file or the original filename.
*/
private static function restartIncludeFiles($m)
{
$fname = preg_replace_callback('`\{((?:[\w\.\-]+)(?:\|.+?)?)\}`', 'XTemplate::substituteVar', $m[2]);
if (preg_match('`\.tpl$`i', $fname) && file_exists($fname)) {
$code = self::readFile($fname);
if ($code[0] == chr(0xEF) && $code[1] == chr(0xBB) && $code[2] == chr(0xBF)) {
$code = mb_substr($code, 0);
}
$code = preg_replace_callback('`\{FILE\s+("|\')(.+?)\1\}`', 'XTemplate::restartIncludeFiles', $code);
return $code;
}
return $fname;
}
/**
* Registers a root block during template compilation.
*
* @param array $m The regex match array containing block name and content.
* @return string An empty string to remove the processed block from the code.
*/
private function restartRootBlocks($m)
{
$name = $m[1];
$text = trim($m[2]);
$this->index[$name] = array($name);
$this->blocks[$name] = new XtplBlock($text, $this->index, array($name));
$this->found = true;
return '';
}
/**
* Initializes or reinitializes the template with a new file path.
*
* @param string $path The path to the template file.
* @return XTemplate Returns the current instance for method chaining.
* @throws Exception If the template file does not exist.
*/
public function restart($path)
{
if (!file_exists($path)) {
throw new Exception("Template file not found: $path");
}
$this->filename = $path;
$this->vars = array();
$this->blocks = array();
$this->index = array();
$this->tags = null;
$code = self::readFile($path);
$code = $this->prepare($code);
$hash = md5($code);
if (self::$cacheEnabled && $this->cache) {
$cached = $this->cache->load($path, $hash);
if ($cached !== null) {
list($this->blocks, $this->index, $this->tags) = $cached;
return $this;
}
}
$this->compile($code);
if (self::$cacheEnabled && $this->cache) {
$this->cache->save($path, array($this->blocks, $this->index, $this->tags), $hash);
}
return $this;
}
/**
* Prepares the template code by handling file includes and BOM removal.
*
* @param string $code The raw template code.
* @return string The prepared template code.
*/
private function prepare($code)
{
if ($code[0] == chr(0xEF) && $code[1] == chr(0xBB) && $code[2] == chr(0xBF)) {
$code = mb_substr($code, 0);
}
return preg_replace_callback('`\{FILE\s+("|\')(.+?)\1\}`', 'XTemplate::restartIncludeFiles', $code);
}
/**
* Compiles the template code into blocks.
*
* @param string $code The template code to compile.
* @return XTemplate Returns the current instance for method chaining.
*/
public function compile($code)
{
if (self::$cleanupEnabled) {
$code = $this->cleanup($code);
}
do {
$this->found = false;
$code = preg_replace_callback(
'`<!--\s*BEGIN:\s*([\w_]+)\s*-->(.*?)<!--\s*END:\s*\1\s*-->`s',
array($this, 'restartRootBlocks'),
$code
);
} while ($this->found);
return $this;
}
/**
* Cleans up HTML code by normalizing whitespace and formatting.
*
* @param string $html The HTML code to clean up.
* @return string The cleaned-up HTML code.
*/
private function cleanup($html)
{
$html = join("\n", array_map('trim', explode("\n", $html)));
$html = preg_replace('#[\r\n\t]+<#', ' <', $html);
$html = preg_replace('#>[\r\n\t]+#', '>', $html);
$html = preg_replace('/[\t\f]+/', ' ', $html);
$html = preg_replace('/ {2,}/', ' ', $html);
$regexp = "/<\/?\w+((\s+(\w|\w[\w-]*\w)(\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)+\s*|\s*)\/?>/i";
preg_match_all($regexp, $html, $matches);
foreach ($matches[0] as $match) {
$newHtml = preg_replace('/\s+/', ' ', $match);
$html = str_replace($match, $newHtml, $html);
}
return $html;
}
/**
* Substitutes a variable placeholder with its evaluated value.
*
* @param array $m The regex match array containing the variable name.
* @return string The evaluated value of the variable.
*/
private static function substituteVar($m)
{
$var = new XtplVar($m[1]);
return $var->evaluate();
}
/**
* Outputs the rendered content of a block, with optional debug output.
*
* @param string $block The name of the block to output (default: 'MAIN').
* @return XTemplate Returns the current instance for method chaining.
*/
public function out($block = 'MAIN')
{
if ($this->debug && $this->debugOutput) {
echo XtplDebugger::display(basename($this->filename));
} else {
echo $this->text($block);
}
return $this;
}
/**
* Parses a block, preparing it for rendering.
*
* @param string $block The name of the block to parse (default: 'MAIN').
* @return XTemplate Returns the current instance for method chaining.
*/
public function parse($block = 'MAIN')
{
$path = isset($this->index[$block]) ? $this->index[$block] : null;
if ($path) {
$blockIndex = array_shift($path);
$blk = isset($this->blocks[$blockIndex]) ? $this->blocks[$blockIndex] : null;
if (!empty($blk)) {
foreach ($path as $node) {
if (is_array($blk)) {
$blk = $blk[$node];
} else {
$blk = $blk->blocks[$node];
}
}
$blk->parse($this);
}
}
if ($this->debug && !in_array($block, $this->displayed_blocks)) {
XtplDebugger::collect(basename($this->filename), $block, $this->vars);
$this->displayed_blocks[] = $block;
}
return $this;
}
/**
* Resets the parsed data of a block.
*
* @param string $block The name of the block to reset (default: 'MAIN').
* @return XTemplate Returns the current instance for method chaining.
*/
public function reset($block = 'MAIN')
{
$path = $this->index[$block];
if ($path) {
$blk = $this->blocks[array_shift($path)];
foreach ($path as $node) {
if (is_object($blk)) {
$blk = &$blk->blocks[$node];
} else {
$blk = &$blk[$node];
}
}
$blk->reset();
}
return $this;
}
/**
* Retrieves the rendered text of a block.
*
* @param string $block The name of the block to render (default: 'MAIN').
* @return string The rendered text of the block.
*/
public function text($block = 'MAIN')
{
$path = isset($this->index[$block]) ? $this->index[$block] : null;
if (empty($path)) {
return '';
}
$blockIndex = array_shift($path);
$blk = isset($this->blocks[$blockIndex]) ? $this->blocks[$blockIndex] : null;
if (empty($blk)) {
return '';
}
foreach ($path as $node) {
if (is_object($blk)) {
$blk = &$blk->blocks[$node];
} else {
$blk = &$blk[$node];
}
}
return $blk->text($this);
}
/**
* Reads the contents of a file.
*
* @param string $path The path to the file to read.
* @return string The contents of the file.
*/
public static function readFile($path)
{
$fp = fopen($path, 'r');
$size = filesize($path);
$code = $size > 0 ? fread($fp, $size) : '';
fclose($fp);
return $code;
}
/**
* Glues a path array into a string index, skipping numeric keys after the first.
*
* @param array $path The path array to glue.
* @return string The glued index string.
*/
public static function indexGlue($path)
{
$str = array_shift($path);
foreach ($path as $node) {
if (!is_numeric($node)) {
$str .= '.' . $node;
}
}
return $str;
}
/**
* Splits a string into tokens, respecting delimiters, quotes, and brackets.
*
* @param string $str The input string to tokenize.
* @param array $delim Array of delimiter characters (default: [' ']).
* @param bool $trimQuotes Whether to trim quotes and brackets (default: true).
* @return array An array of tokens.
*/
public static function tokenize($str, $delim = [' '], $trimQuotes = true)
{
$tokens = [0 => ''];
$idx = 0;
$quote = '';
$quotePairs = ['"' => '"', "'" => "'", '{' => '}'];
$prevWasDelim = false;
$len = mb_strlen($str);
for ($i = 0; $i < $len; $i++) {
$char = mb_substr($str, $i, 1);
if (array_key_exists($char, $quotePairs) && !$quote) {
$quote = $char;
if (!$trimQuotes) {
$tokens[$idx] .= $char;
}
$prevWasDelim = false;
continue;
}
if ($quote && $char === $quotePairs[$quote]) {
$quote = '';
if (!$trimQuotes) {
$tokens[$idx] .= $char;
}
$prevWasDelim = false;
continue;
}
if (in_array($char, $delim, true)) {
if ($quote) {
$tokens[$idx] .= $char;
} elseif (!$prevWasDelim) {
$tokens[++$idx] = '';
$prevWasDelim = true;
}
continue;
}
$tokens[$idx] .= $char;
$prevWasDelim = false;
}
return array_filter($tokens, 'strlen');
}
/**
* Converts a string argument to its appropriate data type or object.
*
* @param string $argument The input argument string.
* @return mixed The converted value (bool, int, float, string, or XtplVar).
*/
public static function parseArgument($argument)
{
if ($argument === '') {
return '';
}
static $literals = [
'true' => true,
'false' => false,
'null' => null,
];
$argLC = mb_strtolower($argument);
if (array_key_exists($argLC, $literals)) {
return $literals[$argLC];
}
if (is_numeric($argument)) {
return strpos($argument, '.') === false ? (int) $argument : (float) $argument;
}
$len = mb_strlen($argument);
if ($len < 2) {
return $argument;
}
$first = mb_substr($argument, 0, 1);
$last = mb_substr($argument, -1, 1);
if ($first === '{' && $last === '}') {
return new XtplVar(mb_substr($argument, 1, $len - 2));
}
if ($first === $last && in_array($first, ['"', "'"], true)) {
return mb_substr($argument, 1, $len - 2);
}
return $argument;
}
}
class XtplBlock
{
protected $data = array();
public $blocks = array();
/**
* Constructs an XtplBlock instance and compiles the provided code.
*
* @param string $code The block code to compile.
* @param array &$index Reference to the template index array.
* @param array $path The path to this block in the template hierarchy.
*/
public function __construct($code, &$index, $path)
{
$this->compile($code, $this->blocks, $index, $path);
}
/**
* Converts the block and its sub-blocks to a string representation.
*
* @return string The string representation of the block.
*/
public function __toString()
{
return $this->blocks_toString($this->blocks);
}
/**
* Converts an array of blocks to a string representation.
*
* @param array &$blocks Reference to the array of blocks.
* @return string The string representation of the blocks.
*/
protected function blocks_toString(&$blocks)
{
$str = '';
foreach ($blocks as $name => $block) {
if (is_string($name) && !is_numeric($name)) {
$str .= "<!-- BEGIN: $name -->\n" . $block->__toString() . "<!-- END: $name -->\n";
} else {
$str .= $block->__toString();
}
}
return $str;
}
/**
* Compiles the block code into a structure of sub-blocks and data.
*
* @param string $code The code to compile.
* @param array &$blocks Reference to the array where compiled blocks are stored.
* @param array &$index Reference to the template index array.
* @param array $path The path to this block in the template hierarchy.
*/
protected function compile($code, &$blocks, &$index, $path)
{
$i = 0;
while (!empty($code)) {
$construct = $this->detectNextConstruct($code);
if ($construct === null && !empty($code)) {
$blocks[$i++] = new XtplData($code);
$code = '';
continue;
}
list($constructCode, $remainingCode) = $this->extractConstruct($code, $construct);
$code = $remainingCode;
if (!empty($constructCode['before'])) {
$blocks[$i++] = new XtplData($constructCode['before']);
}
$this->compileConstruct($constructCode, $construct, $blocks, $index, $path, $i);
}
}
/**
* Detects the type of the next construct in the code (BEGIN, FOR, IF).
*
* @param string $code The input code to analyze.
* @return string|null The type of the next construct or null if none found.
*/
private function detectNextConstruct($code)
{
if (preg_match('`<!--\s*(?:(BEGIN):\s*([\w_]+)|(FOR|IF)\s+).+?-->.*?<!--\s*(?:END:\s*\2|END\3)\s*-->`s', $code, $mt)) {
if (!empty($mt[1])) {
return 'BEGIN';
} elseif (!empty($mt[3])) {
return $mt[3];
}
}
return null;
}
/**
* Extracts a construct from the code, separating it from the remaining code.
*
* @param string $code The input code containing the construct.
* @param string $type The type of construct to extract (BEGIN, FOR, IF).
* @return array An array containing construct data and remaining code.
* @throws Exception If the construct type is unknown.
*/
private function extractConstruct($code, $type)
{
$patterns = [
'BEGIN' => '`(?:(?:(?<=\n|\r)[^\S\n\r]*)(?=<!--\s*BEGIN:\s*(?:[\w_]+)\s*-->(?:\s*(?:\r?\n|\r))))?<!--\s*BEGIN:\s*([\w_]+)\s*-->(?:\s*(?:\r?\n|\r))?((?:.*?))?((?<=\n|\r)[^\S\n\r]*)?<!--\s*END:\s*\1\s*-->(?(3)(\s*(?:\r?\n|\r))?)`s',
'FOR' => '`((?:(?<=\n|\r)[^\S\n\r]*)(?=<!--\s*FOR\s+[^>]+\s*-->(?:\s*(?:\r?\n|\r))))?<!--\s*FOR\s+(.+?)\s*-->(?(1)(?:\s*(?:\r?\n|\r))?)`',
'IF' => '`((?:(?<=\n|\r)[^\S\n\r]*)(?=<!--\s*IF\s+[^>]+\s*-->(?:\s*(?:\r?\n|\r))))?<!--\s*IF\s+(.+?)\s*-->(?(1)(?:\s*(?:\r?\n|\r))?)`',
];
if (!isset($patterns[$type])) {
throw new Exception("Unknown construct type: $type");
}
preg_match($patterns[$type], $code, $mt);
$startPos = mb_strpos($code, $mt[0]);
$startLen = mb_strlen($mt[0]);
$constructData = [
'before' => $startPos > 0 ? mb_substr($code, 0, $startPos) : '',
'header' => $mt[2],
'content' => '',
'elseContent' => '',
];
$code = mb_substr($code, $startPos + $startLen);
if ($type === 'BEGIN') {
$constructData['content'] = $mt[2];
$constructData['name'] = $mt[1];
return [$constructData, $code];
}
list($mainContent, $elseContent, $remainingCode) = $this->extractNestedContent($code, $type);
$constructData['content'] = $mainContent;
$constructData['elseContent'] = $elseContent;
return [$constructData, $remainingCode];
}
/**
* Extracts nested content for FOR or IF constructs, handling ELSE for IF.
*
* @param string $code The code following the construct header.
* @param string $type The type of construct (FOR or IF).
* @return array An array containing main content, else content, and remaining code.
* @throws Exception If the construct block is not properly closed.
*/
private function extractNestedContent($code, $type)
{
$endTag = "END{$type}";
$scope = 1;
$mainContent = '';
$elseContent = '';
$hasElse = false;
$pattern = "`((?:(?<=\n|\r)[^\S\n\r]*)(?=<!--\s*(?:{$type}\s+[^>]+?|ELSE|{$endTag})\s*-->(?:\s*(?:\r?\n|\r))))?<!--\s*({$type}\s+.+?|ELSE|{$endTag})\s*-->(?(1)(?:\s*(?:\r?\n|\r))?)`";
while ($scope > 0 && preg_match($pattern, $code, $m)) {
$mPos = mb_strpos($code, $m[0]);
$mLen = mb_strlen($m[0]);
if ($m[2] === $endTag) {
$scope--;
} elseif ($type === 'IF' && $m[2] === 'ELSE' && $scope === 1) {
$mainContent .= mb_substr($code, 0, $mPos);
$hasElse = true;
$code = mb_substr($code, $mPos + $mLen);
continue;
} elseif (preg_match("/^{$type}\s+/", $m[2])) {
$scope++;
}
$postfixLen = $scope === 0 ? 0 : $mLen;
if (!$hasElse) {
$mainContent .= mb_substr($code, 0, $mPos + $postfixLen);
} else {
$elseContent .= mb_substr($code, 0, $mPos + $postfixLen);
}
$code = mb_substr($code, $mPos + $mLen);
}
if ($scope !== 0) {
throw new Exception("$type block not closed");
}
return [$mainContent, $elseContent, $code];
}
/**
* Compiles a specific construct and adds it to the blocks array.
*
* @param array $constructData Data about the construct to compile.
* @param string $type The type of construct (BEGIN, FOR, IF).
* @param array &$blocks Reference to the array of blocks.
* @param array &$index Reference to the template index array.
* @param array $path The current path in the template hierarchy.
* @param int &$i Reference to the block counter.
* @throws Exception If the construct type is unknown.
*/
private function compileConstruct($constructData, $type, &$blocks, &$index, $path, &$i)
{
$bpath = $path;
switch ($type) {
case 'BEGIN':
$blockName = $constructData['name'];
array_push($bpath, $blockName);
$index[XTemplate::indexGlue($bpath)] = $bpath;
$blocks[$blockName] = new XtplBlock($constructData['content'], $index, $bpath);
break;
case 'FOR':
array_push($bpath, $i);
$blocks[$i++] = new XtplLoop($constructData['header'], $constructData['content'], $index, $bpath);
break;
case 'IF':
array_push($bpath, $i);
$blocks[$i++] = new XtplLogical($constructData['header'], $constructData['content'], $constructData['elseContent'], $index, $bpath);
break;
default:
throw new Exception("Unknown construct type: $type");
}
}
/**
* Retrieves all tags used within this block.
*
* @return array An associative array of tag names.
*/
public function getTags()
{
$list = array();
foreach ($this->blocks as $block) {
if ($block instanceof XtplData || $block instanceof XtplBlock) {
$list = array_merge($list, $block->getTags());
}
}
return $list;
}
/**
* Parses the block, rendering its content into the data array.
*
* @param XTemplate $tpl The template instance to use for parsing.
*/
public function parse($tpl)
{
$data = '';
foreach ($this->blocks as $block) {
$data .= $block->text($tpl);
}
$this->data[] = $data;
}
/**
* Resets the parsed data of the block.
*
* @param array $path Optional path parameter (unused in this implementation).
*/
public function reset($path = array())
{
$this->data = array();
}
/**
* Renders the block's text content.
*
* @param XTemplate $tpl The template instance to use for rendering.
* @return string The rendered text of the block.
*/
public function text($tpl)
{
$text = implode('', $this->data);
$this->data = array();
return $text;
}
}
class XtplData
{
protected $chunks = array();
/**
* Constructs an XtplData instance by splitting code into chunks.
*
* @param string $code The code to process into data chunks.
*/
public function __construct($code)
{
$chunks = $this->splitToChunks($code);
if (!empty($chunks)) {
foreach ($chunks as $chunk) {
$firstSymbol = mb_substr($chunk, 0, 1);
$lastSymbol = mb_substr($chunk, -1, 1);
if ($firstSymbol === '{' && $lastSymbol === '}') {
$this->chunks[] = new XtplVar(mb_substr($chunk, 1, mb_strlen($chunk) - 2));
} elseif ($chunk !== '' && $chunk !== null) {
$this->chunks[] = $chunk;
}
}
}
}
/**
* Splits the code into chunks, separating variables from static content.
*
* @param string $code The input code to split.
* @return array An array of code chunks.
*/
private function splitToChunks($code)
{
return preg_split(
'`(\{[A-Z0-9_$](?>[^{}]|(?0))*?[\w)]})`',
$code,
-1,
PREG_SPLIT_DELIM_CAPTURE
);
}
/**
* Converts the data chunks to a string representation.
*
* @return string The string representation of the data.
*/
public function __toString()
{
$str = '';
foreach ($this->chunks as $chunk) {
if ($chunk instanceof XtplVar) {
$str .= $chunk->__toString();
} else {
$str .= $chunk;
}
}
return $str . "\n";
}
/**