/
Template.php
633 lines (572 loc) · 19.8 KB
/
Template.php
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
<?php
/**
* Class for manage simple templates
*
* @category Layout
* @package Core
* @author Jonathan Hernandez <ion@suavizado.com>
* @author Ali Fazelzadeh <afz@php.net>
* @copyright 2005-2015 Jaws Development Group
* @license http://www.gnu.org/copyleft/lesser.html
*/
/**
* Structure for a block
*/
class Jaws_TemplateBlock
{
var $Name = '';
var $Content = '';
var $RawContent = '';
var $Parsed = '';
var $Vars = array();
var $InnerBlock = array();
}
/**
* Template engine class
*/
class Jaws_Template
{
var $Content;
var $IdentifierRegExp;
var $BlockRegExp;
var $NewBlockRegExp;
var $VarsRegExp;
var $IsBlockRegexp;
var $MainBlock;
var $CurrentBlock;
var $Blocks = array();
var $tplString = '';
var $globalVariables = array();
var $theme = null;
var $rawStore = null;
var $loadFromTheme = false;
var $loadRTLDirection = null;
/**
* Class constructor
*
* @access public
* @param bool $loadFromTheme Try to load template from theme
* @param bool $loadGlobalVariables Fetch and set global variables
* @return void
*/
function Jaws_Template($loadFromTheme = false, $loadGlobalVariables = true)
{
$this->IdentifierRegExp = '[\.[:digit:][:lower:]_-]+';
$this->BlockRegExp = '@<!--\s+begin\s+('.$this->IdentifierRegExp.')\s+([^>]*)-->(.*)<!--\s+end\s+\1\s+-->@sim';
$this->VarsRegExp = '@{{\s*('.$this->IdentifierRegExp.')\s*}}@sim';
$this->IsBlockRegExp = '@##\s*('.$this->IdentifierRegExp.')\s*##@sim';
$namexp = '[[:digit:][:lower:]_]+';
$this->NewBlockRegExp = '@<!--\s+begin\s+('.$namexp.')\s+'.
'(?:if\((!)?('.$namexp.')\)\s+|)'.
'(?:loop\(('.$namexp.')\)\s+|)'.
'-->(.*)<!--\s+end\s+\1\s+-->@sim';
$this->globalVariables['theme_url'] = '';
$this->globalVariables['.dir'] = _t('GLOBAL_LANG_DIRECTION') == 'rtl'? '.rtl' : '';
$this->globalVariables['base_url'] = Jaws_Utils::getBaseURL('/');
$this->globalVariables['requested_url'] = Jaws_Utils::getRequestURL();
$this->globalVariables['base_script'] = BASE_SCRIPT;
if ($loadGlobalVariables) {
$this->loadFromTheme = $loadFromTheme;
$this->theme = $GLOBALS['app']->GetTheme();
$browser = $GLOBALS['app']->GetBrowserFlag();
$this->globalVariables['theme_url'] = $this->theme['url'];
$this->globalVariables['data_url'] = $GLOBALS['app']->getDataURL();
$this->globalVariables['.browser'] = empty($browser)? '' : ".$browser";
$this->globalVariables['main_index'] = $GLOBALS['app']->mainIndex? 'index' : '';
$this->globalVariables['main_gadget'] = strtolower($GLOBALS['app']->mainGadget);
$this->globalVariables['main_action'] = strtolower($GLOBALS['app']->mainAction);
} else {
$this->loadFromTheme = false;
}
}
/**
* Returns template without any process
*
* @access public
*/
function GetContent()
{
return $this->Content;
}
/**
* Loads a template from a file
*
* @access public
* @param string $fname File name
* @param string $fpath File path
* @param bool $return Return content?
* @return mixed Template content or void(based on $return parameter)
*/
function Load($fname, $fpath = '', $return = false)
{
$filePath = rtrim($fpath, '/');
$fileExtn = strrchr($fname, '.');
$fileName = substr($fname, 0, -strlen($fileExtn));
// load from theme
if ($this->loadFromTheme && file_exists($this->theme['path']. $filePath. '/'. $fname)) {
$filePath = $this->theme['path']. $filePath;
}
$prefix = '';
if ($this->loadRTLDirection ||
(is_null($this->loadRTLDirection) && function_exists('_t') && _t('GLOBAL_LANG_DIRECTION') == 'rtl'))
{
$prefix = '.rtl';
}
$tplFile = $filePath. '/'. $fileName. $prefix. $fileExtn;
$tplExists = file_exists($tplFile);
if (!$tplExists && !empty($prefix)) {
$tplFile = $filePath. '/'. $fileName. $fileExtn;
$tplExists = file_exists($tplFile);
}
if (!$tplExists) {
Jaws_Error::Fatal('Template '. $tplFile. ' doesn\'t exists');
}
$content = @file_get_contents($tplFile);
if (empty($content)) {
Jaws_Error::Fatal('There was a problem while reading the template file: '. $tplFile);
}
if (preg_match_all("#<!-- INCLUDE (.*) -->#i", $content, $includes, PREG_SET_ORDER)) {
foreach ($includes as $key => $include) {
@list($incl_fname, $incl_fpath) = preg_split('#\s#', $include[1]);
if (empty($incl_fpath)) {
$incl_fpath = $fpath;
}
$replacement = $this->Load($incl_fname, $incl_fpath, true);
$content = str_replace($include[0], $replacement, $content);
}
}
if ($return) {
return $content;
}
$this->loadFromString($content);
}
/**
* Loads a template from a string
*
* @param $tplString String that contains a template structure
* @access public
*/
function loadFromString($tplString)
{
$this->tplString = preg_replace('@\r?\n\s*<!--@sim', '<!--', $tplString);
$this->Content = $this->tplString;
$this->Blocks = $this->GetBlocks($this->Content);
$this->MainBlock = $this->GetMainBlock();
}
/**
* Returns the main block, sub-blocks are replaced with ##subblock##
*
* @access public
*/
function GetMainBlock()
{
$result = $this->Content;
foreach ($this->Blocks as $k => $iblock) {
$pattern = '@<!--\s+begin\s+'.$iblock->Name.'\s+([^>]*)-->(.*)<!--\s+end\s+'.$iblock->Name.'\s+-->@sim';
$result = preg_replace($pattern, '##'.$iblock->Name.'##' , $result);
}
return $result;
}
/**
* Return the sub-blocks structure for a given block
*
* @param $contentString Block string
* @access public
*/
function GetBlocks($contentString)
{
$blocks = array();
if (preg_match_all($this->BlockRegExp, $contentString, $regs, PREG_SET_ORDER)) {
foreach ($regs as $key => $match) {
$wblock = new Jaws_TemplateBlock();
$wblock->Name = $match[1];
$wblock->Content = $match[3];
$wblock->RawContent = $this->rawStore? $match[3] : null;
$wblock->InnerBlock = $this->GetBlocks($wblock->Content);
foreach ($wblock->InnerBlock as $k => $iblock) {
$pattern = '@<!--\s+begin\s+'.$iblock->Name.'\s+([^>]*)-->(.*)<!--\s+end\s+'.$iblock->Name.'\s+-->@sim';
$wblock->Content = preg_replace($pattern, '##'.$iblock->Name.'##' , $wblock->Content);
}
$wblock->Vars = $this->GetVariables($wblock->Content);
$blocks[$wblock->Name] = $wblock;
}
}
return $blocks;
}
/**
* Fetch parsed template
*
* @param $vars Variables
* @param $content Template string
* @param $root Root block of template?
* @access public
*/
function fetch($vars = array(), $content = '', $root = true)
{
if (empty($content)) {
$vars = $vars + $this->globalVariables;
$content = $this->tplString;
}
if (preg_match_all($this->NewBlockRegExp, $content, $regs, PREG_SET_ORDER)) {
foreach ($regs as $match) {
$exchange = '';
$blockName = $match[1];
if (!empty($match[3]) &&
((bool)$match[2]? (bool)$vars[$match[3]] : !(bool)$vars[$match[3]]))
{
// condition for parsing block
$exchange = '';
} elseif ((!empty($match[4]) && !empty($vars[$match[4]]))) {
// passed array for loop block must be an array
if (!isset($vars[$blockName]) || !is_array($vars[$blockName])) {
$vars[$blockName] = array();
}
// parse loop block
if (!Jaws_Error::IsError($vars[$match[4]])) {
foreach ($vars[$match[4]] as $loopVars) {
$exchange.= $this->fetch($loopVars + $vars[$blockName], $match[5], false);
}
}
} elseif (isset($vars[$blockName])) {
if (is_array($vars[$blockName])) {
// parse simple block
$exchange = $this->fetch($vars[$blockName], $match[5], false);
} else {
// replace block with given variable
$exchange = (string)$vars[$blockName];
}
}
$content = str_replace($match[0], $exchange, $content);
}
}
if ($root) {
// Merge global variables and input variables together
$vars = $vars + $this->globalVariables;
}
// set variables
foreach($vars as $key => $value) {
if (!is_array($value)) {
$content = str_replace('{{'.$key.'}}', $value, $content);
}
}
return $content;
}
/**
* Return the variables array of a given block
*
* @param $blockContent Block string
* @access public
*/
function GetVariables($blockContent)
{
$vars = array();
if (preg_match_all($this->VarsRegExp, $blockContent, $regs, PREG_SET_ORDER)) {
foreach ($regs as $k => $match) {
$vars[$match[1]] = '';
switch (strtolower($match[1])) {
case 'theme_url':
if (isset($GLOBALS['app'])) {
$theme = $GLOBALS['app']->GetTheme();
$vars[$match[1]] = $this->globalVariables['theme_url'];
}
break;
case 'base_url':
$vars[$match[1]] = $this->globalVariables['base_url'];
break;
case 'data_url':
if (isset($GLOBALS['app'])) {
$vars[$match[1]] = $this->globalVariables['data_url'];
}
break;
case 'requested_url':
$vars[$match[1]] = $this->globalVariables['requested_url'];
break;
case 'main_index':
if (isset($GLOBALS['app'])) {
$vars[$match[1]] = $this->globalVariables['main_index'];
}
break;
case '.dir':
$vars[$match[1]] = $this->globalVariables['.dir'];
break;
case '.browser':
if (isset($GLOBALS['app'])) {
$vars[$match[1]] = $this->globalVariables['.browser'];
}
break;
case 'base_script':
$vars[$match[1]] = $this->globalVariables['base_script'];
break;
case 'main_gadget':
if (isset($GLOBALS['app'])) {
$vars[$match[1]] = $this->globalVariables['main_gadget'];
}
break;
case 'main_action':
if (isset($GLOBALS['app'])) {
$vars[$match[1]] = $this->globalVariables['main_action'];
}
break;
}
}
}
return $vars;
}
/**
* Returns the processed template(parsed blocks)
*
* @access public
*/
function Get()
{
$result = str_replace('\\\\', '\\', $this->MainBlock);
if (preg_match_all($this->IsBlockRegExp, $result, $regs, PREG_SET_ORDER)) {
foreach ($regs as $blockToReplace) {
$pattern = '@##\s*(' . $blockToReplace[1] . ')\s*##@sim';
$result = preg_replace($pattern, str_replace('$', '\$', $this->Blocks[$blockToReplace[1]]->Parsed) , $result);
}
}
return $result;
}
/**
* Returns the content of the current block
*
* @access public
* @return string Content
*/
function GetCurrentBlockContent()
{
return is_null($this->CurrentBlock)? '' : $this->CurrentBlock->Content;
}
/**
* Returns the raw content of a block
*
* @access public
* @param string $pathString Block path if empty use current block
* @return string Content
*/
function GetRawBlockContent($pathString = '', $block_include = true)
{
if (empty($pathString)) {
if (is_null($this->CurrentBlock)) {
return '';
} elseif ($block_include) {
return "<!-- BEGIN {$this->CurrentBlock->Name} -->".
$this->CurrentBlock->RawContent.
"<!-- END {$this->CurrentBlock->Name} -->";
} else {
return $this->CurrentBlock->RawContent;
}
} else {
$block =& $this->GetBlockObject($pathString);
if (is_null($block)) {
return '';
} elseif ($block_include) {
return "<!-- BEGIN {$block->Name} -->".
$block->RawContent.
"<!-- END {$block->Name} -->";
} else {
return $block->RawContent;
}
}
}
/**
* Set the content of the current block
*
* @param $content Block content
* @access public
*/
function SetCurrentBlockContent($content)
{
$this->CurrentBlock->Content = $content;
}
/**
* Parse a given block, replacing its variables and parsed sub-blocks
*
* @access public
* @param $blockString Block string
* @param $ignore Ignore block parsed content
* @return string Parsed content
*/
function ParseBlock($blockString = '', $ignore = false)
{
$result = '';
$block = &$this->GetBlockObject($blockString);
if (isset($block->Content)) {
$result = $block->Content;
foreach ($block->Vars as $k => $v) {
if (!is_array($v)) {
$v = str_replace('\\', '\\\\', $v);
$result = str_replace('{{'.$k.'}}', $v, $result);
}
}
if (preg_match_all($this->IsBlockRegExp, $result, $regs, PREG_SET_ORDER)) {
foreach ($regs as $blockToReplace) {
$search = '##' . $blockToReplace[1] . '##';
$replace = $block->InnerBlock[$blockToReplace[1]]->Parsed;
$result = str_replace($search, $replace , $result);
}
}
$block->Parsed .= ($ignore? '' : $result);
}
$blockString = substr($blockString, 0, strrpos($blockString, '/'));
$this->SetBlock($blockString, false);
return $result;
}
/**
* Get a template variable in current block
*
* @param string $key Variable name
* @access public
*/
function GetVariable($key)
{
return $this->CurrentBlock->Vars[$key];
}
/**
* Sets a template variable in current block
*
* @param string $key Variable name
* @param string $value Variable value
* @access public
*/
function SetVariable($key, $value)
{
$this->CurrentBlock->Vars[$key] = $value;
}
/**
* Returns the block object of a given path
*
* @param string $pathString Block path
* @access public
*/
function &GetBlockObject($pathString)
{
if ($pathString == '') {
return $this->CurrentBlock;
}
$blockDeep = 1;
$path = explode('/', $pathString);
foreach ($path as $b) {
if ($blockDeep === 1) {
$block = &$this->Blocks[$b];
} else {
$block = &$block->InnerBlock[$b];
}
$blockDeep++;
}
return $block;
}
/**
* Changes the current block to the given path
*
* @param string $pathString Block path
* @access public
*/
function SetBlock($pathString, $init = true)
{
$this->CurrentBlock = &$this->GetBlockObject($pathString);
if ($init === true) {
$this->InitializeSubBlock($this->CurrentBlock);
}
}
/**
* Initialize subblocks of a given block object
*
* @param object $block Block object
* @access public
*/
function InitializeSubBlock(&$block)
{
if (
is_object($block) && isset($block->Content) &&
preg_match_all($this->IsBlockRegExp, $block->Content, $regs, PREG_SET_ORDER)
) {
foreach ($regs as $subBlock) {
$block->InnerBlock[$subBlock[1]]->Parsed = '';
$this->InitializeSubBlock($block->InnerBlock[$subBlock[1]]);
}
}
}
/**
* Set variables from a given associative array
*
* @param array $variablesArray Associative array to replace
* @access public
*/
function SetVariablesArray($variablesArray)
{
foreach ($variablesArray as $key => $value) {
$this->CurrentBlock->Vars[$key] = $value;
}
}
/**
* Resets a variable in a previous block
*
* @access public
* @param string $variable Variable's name
* @param string $value Variable's value
* @param string $block Block's name
*/
function ResetVariable($variable, $value, $block)
{
if (isset($this->Blocks[$block])) {
$this->Blocks[$block]->Vars[$variable] = $value;
}
}
/**
* Check if a given block exists
*
* @param string $pathString Block path
* @return bool True if block is found, otherwise false.
* @access public
*/
function BlockExists($pathString)
{
$blockDeep = 1;
$consPath = '';
foreach (explode('/', $pathString) as $b) {
if ($blockDeep == 1) {
if (!isset($this->Blocks[$b])) {
break;
}
$block = &$this->Blocks[$b];
$consPath = $b;
} else {
if (!isset($block->InnerBlock[$b])) {
break;
}
$block = &$block->InnerBlock[$b];
$consPath .= '/'.$b;
}
$blockDeep++;
}
return($pathString == $consPath);
}
/**
* Check if a variable exists in curren block
*
* @param string $variable Variable name
* @return True if variable found, otherwise false
* @access public
*/
function VariableExists($variable)
{
return stristr($this->CurrentBlock->Content, '{{'.$variable.'}}');
}
/**
* Resets the values and updates
*
* @access public
*/
function ResetValues()
{
$this->rawStore = false;
$this->loadFromTheme = null;
$this->loadRTLDirection = null;
$this->Content = '';
$this->MainBlock = '';
$this->Blocks = array();
$this->CurrentBlock = '';
}
}