Source

php-bootstrap-boilerplate / lib / 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
<?php

/**
	Template engine for the PHP Fat-Free Framework

	The contents of this file are subject to the terms of the GNU General
	Public License Version 3.0. You may not use this file except in
	compliance with the license. Any of the license terms and conditions
	can be waived if you get permission from the copyright holder.

	Copyright (c) 2009-2012 F3::Factory
	Bong Cosca <bong.cosca@yahoo.com>

		@package Template
		@version 2.0.13
**/

//! Template engine
class Template extends Base {

	//@{ Locale-specific error/exception messages
	const
		TEXT_Render='Template %s cannot be rendered';
	//@}

	private static
		//! Custom tags
		$tags=array();

	/**
		Extend template engine with custom tags
			@param $tag string
			@param $func mixed
			@public
	**/
	static function extend($tag,$func) {
		self::$tags[$tag]=$func;
	}

	/**
		Render template
			@return string
			@param $file string
			@param $mime string
			@param $globals boolean
			@param $syms array
			@public
	**/
	static function serve($file,
		$mime='text/html',$globals=TRUE,$syms=array()) {
		$file=self::resolve($file);
		$found=FALSE;
		foreach (preg_split('/[\|;,]/',self::$vars['GUI'],0,
			PREG_SPLIT_NO_EMPTY) as $gui) {
			if (is_file($view=self::fixslashes($gui.$file))) {
				$found=TRUE;
				break;
			}
		}
		if (!$found) {
			trigger_error(sprintf(self::TEXT_Render,$file));
			return '';
		}
		if (PHP_SAPI!='cli' && !headers_sent())
			// Send HTTP header with appropriate character set
			header(self::HTTP_Content.': '.$mime.'; '.
				'charset='.self::$vars['ENCODING']);
		$hash='tpl.'.self::hash($view);
		$cached=Cache::cached($hash);
		if ($cached && filemtime($view)<$cached) {
			if (self::$vars['CACHE'])
				// Retrieve PHP-compiled template from cache
				$text=Cache::get($hash);
		}
		else {
			// Parse raw template
			$doc=new F3markup($mime,$globals);
			foreach (self::$tags as $tag=>$func)
				$doc->extend($tag,$func);
			$text=$doc->load(self::getfile($view),$syms);
			if (self::$vars['CACHE'] && $doc::$cache)
				// Save PHP-compiled template to cache
				Cache::set($hash,$text);
		}
		// Render in a sandbox
		$instance=new F3instance;
		ob_start();
		if (ini_get('allow_url_fopen') && ini_get('allow_url_include'))
			// Stream wrap
			$instance->sandbox('data:text/plain,'.urlencode($text),$syms);
		else {
			// Save PHP-equivalent file in temporary folder
			if (!is_dir(self::$vars['TEMP']))
				self::mkdir(self::$vars['TEMP']);
			$temp=self::$vars['TEMP'].$_SERVER['SERVER_NAME'].'.'.$hash;
			if (!$cached || !is_file($temp) ||
				filemtime($temp)<Cache::cached($view)) {
				// Create semaphore
				$hash='sem.'.self::hash($view);
				while ($cached=Cache::cached($hash))
					// Locked by another process
					usleep(mt_rand(0,100));
				Cache::set($hash,TRUE);
				self::putfile($temp,$text);
				// Remove semaphore
				Cache::clear($hash);
			}
			$instance->sandbox($temp,$syms);
		}
		$out=ob_get_clean();
		unset($instance);
		return self::$vars['TIDY']?self::tidy($out):$out;
	}

}

//! Markup loader/parser/builder
class F3markup extends Base {

	//@{ Locale-specific error/exception messages
	const
		TEXT_AttribMissing='Missing attribute: %s',
		TEXT_AttribInvalid='Invalid attribute: %s',
		TEXT_Global='Use of global variable %s is not allowed',
		TEXT_CustomTag='Invalid custom tag handler: %s';
	//@}

	public
		//! MIME type
		$mime,
		//! Enable/disable PHP globals
		$globals=TRUE;
	static
		//! Enable/disable template caching
		$cache=TRUE;

	private
		//! Parsed markup string
		$tree=array(),
		//! Symbol table for repeat/loop blocks
		$syms=array(),
		//! Custom tags
		$tags=array();

	/**
		Convert template expression to PHP code
			@return string
			@param $str string
			@param $echo boolean
			@public
	**/
	function expr($str,$echo=FALSE) {
		$self=$this;
		$syms=&$this->syms;
		$regex='/(?!\w)@(\w+(?:\[[^\]]+\]|\.\w+(?![\w\(]))*'.
			'(?:\s*->\s*\w+)?)(\s*\([^\)]*\))?(?:\s*\\\(.+))?/';
		return preg_replace_callback(
			'/{{(.+?)}}/s',
			function($expr) use(&$syms,$self,$echo,$regex) {
				$out=preg_replace_callback($regex,
					function($var) use(&$syms,$self,$regex) {
						//Return stringified framework variable
						preg_match('/^(\w+)\b(.*)/',$var[1],$match);
						if (!$self->globals &&
							preg_match('/'.$self::PHP_Globals.'/',
							$match[1])) {
							trigger_error(
								sprintf($self::TEXT_Global,$match[1])
							);
							return FALSE;
						}
						$isfunc=isset($var[2]) && $var[2];
						if (array_key_exists('_'.$match[1],$syms))
							return '$_'.(is_int(strpos($var[1],'@'))?
								$self->expr('{{'.$var[1].'}}'):
								$self->remix($var[1])).
								($isfunc?$self->expr('{{'.$var[2].'}}'):'');
						$str='F3::get('.$self::stringify($var[1]).')';
						if ($isfunc) {
							preg_match_all($regex,$var[2],$parts,
								PREG_SET_ORDER);
							$args='';
							if ($parts) {
								foreach ($parts as $part)
									$args.=($args?',':'').
										$self->expr('{{'.$part[0].'}}');
								$args='('.$args.')';
							}
							else
								$args=$var[2];
							if (isset($match[2]) &&
								method_exists(F3::get($match[1]),
								$temp=str_replace('->','',$match[2])))
								$str='array(F3::get('.
									$self::stringify($match[1]).'),'.
									$self::stringify($temp).')';
							$str='call_user_func_array('.
								'$_'.$match[1].'='.$str.',array'.$args.')';
						}
						elseif (isset($var[3]))
							$str=str_replace(')',',array('.
								$self->expr('{{'.$var[3].'}}').'))',$str);
						if (!$match[2] &&
							!preg_match('/('.$self::PHP_Globals.')\b/',
								$match[1])) {
							if (!$isfunc)
								$str='($_'.$match[1].
									(array_key_exists('_'.$match[1],$syms)?
										'':('='.$str)).')';
							$syms['_'.$match[1]]=NULL;
						}
						$str='(F3::get(\'ESCAPE\')?'.
							'F3::htmlencode('.$str.'):'.$str.')';
						return $str;
					},
					$expr[1]
				);
				return $echo?('<?php echo '.$out.'; ?>'):$out;
			},
			$str
		);
	}

	/**
		Return TRUE if all mandatory attributes are present
			@return boolean
			@param $key string
			@param $tags array
			@param $attrs array
			@public
	**/
	function isdef($key,array $tags,array $attrs) {
		$ok=TRUE;
		foreach ($attrs as $attr)
			if (!isset($tags['@attrib'][$attr])) {
				$ok=FALSE;
				break;
			}
		if ($ok)
			return TRUE;
		$out='<'.$key;
		if (isset($tags['@attrib']))
			foreach ($tags['@attrib'] as $akey=>$aval)
				$out.=' '.$akey.'="'.$aval.'"';
		$out.='>';
		trigger_error(sprintf(self::TEXT_AttribMissing,$out));
		return FALSE;

	}

	/**
		Reassemble markup string and insert appropriate PHP code
			@return string
			@param $node mixed
			@public
	**/
	function build($node) {
		$out='';
		if (is_array($node)) {
			foreach ($node as $nkey=>$nval)
				if (is_int($nkey))
					$out.=$this->build($nval);
				else {
					$count=count($this->syms);
					switch ($nkey) {
						case '@attrib':
						case 'exclude':
							break;
						case 'include':
							// <include> directive
							if (!$this->isdef($nkey,$nval,array('href')))
								return;
							$hvar=$nval['@attrib']['href'];
							if (isset($nval['@attrib']['if'])) {
								$ival=$nval['@attrib']['if'];
								$cond=$this->expr($ival);
								// Syntax check
								if ($cond==$ival) {
									trigger_error(sprintf(
										self::TEXT_AttribInvalid,
										'if="'.addcslashes($ival,'"').'"'));
									return;
								}
							}
							$doc=new F3markup($this->mime,$this->globals);
							$file=self::resolve($hvar);
							if ($hvar!=$file)
								self::$cache=FALSE;
							$nested=FALSE;
							foreach (array_keys($this->syms) as $pvar)
								if (strstr($hvar,$pvar))
									$nested=TRUE;
							if ($nested) {
								$inc_var=preg_split("/[\s]*[}}{{][\s]*/i",
									$hvar,-1,PREG_SPLIT_NO_EMPTY);
								foreach ($inc_var as &$pval)
									if ($pval[0]=='@')
										$pval=preg_replace(
											array(
												'/<\?php echo /',
												'/; \?>/'
											),'',
											self::expr('{{'.$pval.'}}')
										);
									else
										$pval=self::stringify($pval);
								$text='<?php echo Template::serve('.
									implode('.',$inc_var).',\'text/html\','.
									'TRUE,'.self::stringify($this->syms).
									'); ?>';
								$out.= isset($ival)?
									('<?php if ('.trim($cond).'): ?>'.$text.
									'<?php endif; ?>'):$text;
							}
							else
								foreach (self::split(self::$vars['GUI'])
									as $gui)
									if (is_file($view=$gui.$file)) {
										$text=$doc->load(
											self::getfile($view),
											$this->syms
										);
										$out.=isset($ival)?
											('<?php if ('.trim($cond).'): ?>'.
												$text.'<?php endif; ?>'):
											$text;
										break;
									}
							break;
						case 'loop':
							// <loop> directive
							if (!$this->isdef($nkey,$nval,
								array('counter','from','to')))
								return;
							$cvar=self::remix(
								preg_replace('/{{\s*@(.+?)\s*}}/','\1',
									$nval['@attrib']['counter']));
							foreach ($nval['@attrib'] as $akey=>$aval) {
								${$akey[0].'att'}=$aval;
								${$akey[0].'str'}=$this->expr($aval);
								// Syntax check
								if (${$akey[0].'str'}==$aval) {
									trigger_error(sprintf(
										self::TEXT_AttribInvalid,$akey.'="'.
											addcslashes($aval,'"').'"'));
									return;
								}
							}
							unset($nval['@attrib']);
							if (!array_key_exists('_'.$cvar,$this->syms))
								$this->syms['_'.$cvar]=
									eval('return '.$fstr.';');
							$out.='<?php for ('.
								'$_'.$cvar.'='.$fstr.';'.
								'$_'.$cvar.'<='.$tstr.';'.
								'$_'.$cvar.'+='.
									// step attribute
									(isset($satt)?$sstr:'1').'): ?>'.
								$this->build($nval).
								'<?php endfor; ?>';
							break;
						case 'repeat':
							// <repeat> directive
							if (!$this->isdef($nkey,$nval,array('group')) &&
								(!$this->isdef($nkey,$nval,array('key')) ||
								!$this->isdef($nkey,$nval,array('value'))))
								return;
							$gval=$nval['@attrib']['group'];
							$gstr=trim($this->expr($gval));
							// Syntax check
							if ($gstr==$gval) {
								trigger_error(sprintf(
									self::TEXT_AttribInvalid,
									'group="'.addcslashes($gval,'"').'"'));
								return;
							}
							foreach ($nval['@attrib'] as $akey=>$aval) {
								${$akey[0].'var'}=self::remix(
									preg_replace('/{{\s*@(.+?)\s*}}/',
										'\1',$aval));
								// Syntax check
								if (${$akey[0].'var'}==$aval) {
									trigger_error(sprintf(
										self::TEXT_AttribInvalid,
										$akey.'='.
											'"'.addcslashes($aval,'"').'"'));
									return;
								}
							}
							unset($nval['@attrib']);
							if (isset($vvar))
								$this->syms['_'.$vvar]=NULL;
							else
								$vvar=self::hash($gvar);
							if (isset($kvar))
								$this->syms['_'.$kvar]=NULL;
							if (isset($cvar))
								$this->syms['_'.$cvar]=NULL;
							$out.='<?php '.
								(isset($cvar)?('$_'.$cvar.'=0; '):'').
								'if (is_array('.$gstr.')):'.
								'foreach (('.$gstr.'?:array()) as '.
								(isset($kvar)?('$_'.$kvar.'=>'):'').
									'$_'.$vvar.'):'.
								(isset($cvar)?('$_'.$cvar.'++; '):'').
								'?>'.
								$this->build($nval).
								'<?php '.
									'endforeach;'.
									'endif;'.
								'?>';
							break;
						case 'check':
							// <check> directive
							if (!$this->isdef($nkey,$nval,array('if')))
								return;
							$ival=$nval['@attrib']['if'];
							$cond=$this->expr($ival);
							// Syntax check
							if ($cond==$ival) {
								trigger_error(sprintf(
									self::TEXT_AttribInvalid,
									'if="'.addcslashes($ival,'"').'"'));
								return;
							}
							// Is <true> is defined ahead of <false>?
							foreach ($nval as $pos=>$blk)
								if (is_array($blk))
									foreach ($blk as $ckey=>$cval)
										if (preg_match('/(?:F3:)?'.
											'(?:true|false)/i',$ckey))
											${$ckey[0].'block'}=
												array($pos,$blk);
							if (isset($tblock) && isset($fblock) &&
								$tblock[0]>$fblock[0])
								// Swap <true> and <false> blocks
								// <false> is defined ahead of <true>
								list($nval[$tblock[0]],$nval[$fblock[0]])=
									array($fblock[1],$tblock[1]);
							$out.='<?php if ('.trim($cond).'): ?>'.
								$this->build($nval).
								'<?php endif; ?>';
							break;
						case 'true':
							// <true> block of <check> directive
							$out.=$this->build($nval);
							break;
						case 'false':
							// <false> block of <check> directive
							$out.='<?php else: ?>'.
								$this->build($nval);
							break;
						default:
							// Custom template tag
							if (is_string($this->tags[$nkey])) {
								if (preg_match('/(.+)\s*(->|::)\s*(.+)/s',
									$this->tags[$nkey],$match)) {
									if (!class_exists($match[1]) ||
										!method_exists($match[1],'__call') &&
										!method_exists($match[1],$match[3])) {
										trigger_error(
											sprintf($self::TEXT_CustomTag,
											$match[1])
										);
										return FALSE;
									}
									$this->tags[$nkey]=array($match[2]=='->'?
										new $match[1]:$match[1],$match[3]);
								}
								elseif (!function_exists($this->tags[$nkey])) {
									trigger_error(
										sprintf($self::TEXT_CustomTag,
										$match[1])
									);
									return FALSE;
								}
							}
							if (!is_callable($this->tags[$nkey])) {
								trigger_error(
									sprintf($self::TEXT_CustomTag,
									$this->tags[$nkey])
								);
								return FALSE;
							}
							$out.=call_user_func($this->tags[$nkey],$nval);
							break;
					}
					// Reset scope
					while (count($this->syms)>$count) {
						end($this->syms);
						unset($this->syms[key($this->syms)]);
					}
				}
		}
		else
			$out.=preg_match('/<\?php/',$node)?$node:$this->expr($node,TRUE);
		return $out;
	}

	/**
		Load markup from string
			@return string
			@param $text string
			@param $syms array
			@public
	**/
	function load($text,array $syms=array()) {
		$this->syms=$syms;
		// Remove PHP code and alternative exclude-tokens
		$text=preg_replace(
			'/<\?(?:php)?.+?\?>|{{\*.+?\*}}/is','',$text);
		// Define root node
		$node=&$this->tree;
		// Define stack and depth variables
		$stack=array();
		$depth=0;
		// Define string parser variables
		$len=strlen($text);
		$ptr=0;
		$temp='';
		while ($ptr<$len)
			if (preg_match('/^<(\/?)(?:F3:)?'.
				'(include|exclude|loop|repeat|check|true|false'.
				($this->tags?('|'.implode('|',array_keys($this->tags))):'').
				')\b((?:\s+\w+s*=\s*(?:"(?:.+?)"|\'(?:.+?)\'))*)\s*(\/?)>/is',
				substr($text,$ptr),$match)) {
				if (strlen($temp))
					$node[]=$temp;
				// Element node
				if ($match[1]) {
					// Find matching start tag
					$save=$depth;
					$found=FALSE;
					while ($depth>0) {
						$depth--;
						foreach ($stack[$depth] as $item)
							if (is_array($item) && isset($item[$match[2]])) {
								// Start tag found
								$found=TRUE;
								break 2;
							}
					}
					if (!$found)
						// Unbalanced tag
						$depth=$save;
					$node=&$stack[$depth];
				}
				else {
					// Start tag
					$stack[$depth]=&$node;
					$node=&$node[][$match[2]];
					if ($match[3]) {
						// Process attributes
						preg_match_all('/\s+(\w+)\s*=\s*'.
							'(?:"(.+?)"|\'(.+?)\')/s',$match[3],$attr,
							PREG_SET_ORDER);
						foreach ($attr as $kv)
							$node['@attrib'][$kv[1]]=$kv[2]?:$kv[3];
					}
					if ($match[4] || $match[1]=='include')
						// Empty tag
						$node=&$stack[$depth];
					else
						$depth++;
				}
				$temp='';
				$ptr+=strlen($match[0]);
			}
			else {
				// Text node
				$temp.=$text[$ptr];
				$ptr++;
			}
		if (strlen($temp))
			$node[]=$temp;
		unset($node);
		unset($stack);
		return $this->build($this->tree);
	}

	/**
		Extend template engine with custom tags
			@param $tag string
			@param $func mixed
			@public
	**/
	function extend($tag,$func) {
		$this->tags[$tag]=$func;
	}

	/**
		Override base constructor
			@param $mime string
			@param $globals boolean
			@public
	**/
	function __construct($mime,$globals) {
		$this->mime=$mime;
		$this->globals=$globals;
	}

}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.