5
* @version $Id: functions_template.php,v 1.47 2007/10/05 14:30:10 acydburn Exp $
6
* @copyright (c) 2005 phpBB Group, sections (c) 2001 ispi of Lincoln Inc
7
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
14
if (!defined('IN_PHPBB'))
20
* Extension of template class - Functions needed for compiling templates only.
22
* psoTFX, phpBB Development Team - Completion of file caching, decompilation
23
* routines and implementation of conditionals/keywords and associated changes
25
* The interface was inspired by PHPLib templates, and the template file (formats are
28
* The keyword/conditional implementation is currently based on sections of code from
29
* the Smarty templating engine (c) 2001 ispi of Lincoln, Inc. which is released
30
* (on its own and in whole) under the LGPL. Section 3 of the LGPL states that any code
31
* derived from an LGPL application may be relicenced under the GPL, this applies
34
* DEFINE directive inspired by a request by Cyberalien
38
class template_compile
42
// Various storage arrays
43
var $block_names = array();
44
var $block_else_level = array();
49
function template_compile(&$template)
51
$this->template = &$template;
55
* Load template source from file
58
function _tpl_load_file($handle, $store_in_db = false)
60
// Try and open template for read
61
if (!file_exists($this->template->files[$handle]))
63
trigger_error("template->_tpl_load_file(): File {$this->template->files[$handle]} does not exist or is empty", E_USER_ERROR);
66
$this->template->compiled_code[$handle] = $this->compile(trim(@file_get_contents($this->template->files[$handle])));
68
// Actually compile the code now.
69
$this->compile_write($handle, $this->template->compiled_code[$handle]);
71
// Store in database if required...
77
'template_id' => $user->theme['template_id'],
78
'template_filename' => $this->template->filename[$handle],
79
'template_included' => '',
80
'template_mtime' => time(),
81
'template_data' => trim(@file_get_contents($this->template->files[$handle])),
84
$sql = 'INSERT INTO ' . STYLES_TEMPLATE_DATA_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
90
* Remove any PHP tags that do not belong, these regular expressions are derived from
91
* the ones that exist in zend_language_scanner.l
94
function remove_php_tags(&$code)
96
// This matches the information gathered from the internal PHP lexer
98
'#<([\?%])=?.*?\1>#s',
99
'#<script\s+language\s*=\s*(["\']?)php\1\s*>.*?</script\s*>#s',
100
'#<\?php(?:\r\n?|[ \n\t]).*?\?>#s'
103
$code = preg_replace($match, '', $code);
107
* The all seeing all doing compile method. Parts are inspired by or directly from Smarty
110
function compile($code, $no_echo = false, $echo_var = '')
119
// Remove any "loose" php ... we want to give admins the ability
120
// to switch on/off PHP for a given template. Allowing unchecked
121
// php is a no-no. There is a potential issue here in that non-php
122
// content may be removed ... however designers should use entities
123
// if they wish to display < and >
124
$this->remove_php_tags($code);
126
// Pull out all block/statement level elements and separate plain text
127
preg_match_all('#<!-- PHP -->(.*?)<!-- ENDPHP -->#s', $code, $matches);
128
$php_blocks = $matches[1];
129
$code = preg_replace('#<!-- PHP -->.*?<!-- ENDPHP -->#s', '<!-- PHP -->', $code);
131
preg_match_all('#<!-- INCLUDE ([a-zA-Z0-9\_\-\+\./]+) -->#', $code, $matches);
132
$include_blocks = $matches[1];
133
$code = preg_replace('#<!-- INCLUDE [a-zA-Z0-9\_\-\+\./]+ -->#', '<!-- INCLUDE -->', $code);
135
preg_match_all('#<!-- INCLUDEPHP ([a-zA-Z0-9\_\-\+\./]+) -->#', $code, $matches);
136
$includephp_blocks = $matches[1];
137
$code = preg_replace('#<!-- INCLUDEPHP [a-zA-Z0-9\_\-\+\./]+ -->#', '<!-- INCLUDEPHP -->', $code);
139
preg_match_all('#<!-- ([^<].*?) (.*?)? ?-->#', $code, $blocks, PREG_SET_ORDER);
141
$text_blocks = preg_split('#<!-- [^<].*? (?:.*?)? ?-->#', $code);
143
for ($i = 0, $j = sizeof($text_blocks); $i < $j; $i++)
145
$this->compile_var_tags($text_blocks[$i]);
147
$compile_blocks = array();
149
for ($curr_tb = 0, $tb_size = sizeof($blocks); $curr_tb < $tb_size; $curr_tb++)
151
$block_val = &$blocks[$curr_tb];
153
switch ($block_val[1])
156
$this->block_else_level[] = false;
157
$compile_blocks[] = '<?php ' . $this->compile_tag_block($block_val[2]) . ' ?>';
161
$this->block_else_level[sizeof($this->block_else_level) - 1] = true;
162
$compile_blocks[] = '<?php }} else { ?>';
166
array_pop($this->block_names);
167
$compile_blocks[] = '<?php ' . ((array_pop($this->block_else_level)) ? '}' : '}}') . ' ?>';
171
$compile_blocks[] = '<?php ' . $this->compile_tag_if($block_val[2], false) . ' ?>';
175
$compile_blocks[] = '<?php } else { ?>';
179
$compile_blocks[] = '<?php ' . $this->compile_tag_if($block_val[2], true) . ' ?>';
183
$compile_blocks[] = '<?php } ?>';
187
$compile_blocks[] = '<?php ' . $this->compile_tag_define($block_val[2], true) . ' ?>';
191
$compile_blocks[] = '<?php ' . $this->compile_tag_define($block_val[2], false) . ' ?>';
195
$temp = array_shift($include_blocks);
196
$compile_blocks[] = '<?php ' . $this->compile_tag_include($temp) . ' ?>';
197
$this->template->_tpl_include($temp, false);
201
$compile_blocks[] = ($config['tpl_allow_php']) ? '<?php ' . $this->compile_tag_include_php(array_shift($includephp_blocks)) . ' ?>' : '';
205
$compile_blocks[] = ($config['tpl_allow_php']) ? '<?php ' . array_shift($php_blocks) . ' ?>' : '';
209
$this->compile_var_tags($block_val[0]);
210
$trim_check = trim($block_val[0]);
211
$compile_blocks[] = (!$no_echo) ? ((!empty($trim_check)) ? $block_val[0] : '') : ((!empty($trim_check)) ? $block_val[0] : '');
217
for ($i = 0, $size = sizeof($text_blocks); $i < $size; $i++)
219
$trim_check_text = trim($text_blocks[$i]);
220
$template_php .= (!$no_echo) ? (($trim_check_text != '') ? $text_blocks[$i] : '') . ((isset($compile_blocks[$i])) ? $compile_blocks[$i] : '') : (($trim_check_text != '') ? $text_blocks[$i] : '') . ((isset($compile_blocks[$i])) ? $compile_blocks[$i] : '');
223
// There will be a number of occasions where we switch into and out of
224
// PHP mode instantaneously. Rather than "burden" the parser with this
225
// we'll strip out such occurences, minimising such switching
226
$template_php = str_replace(' ?><?php ', ' ', $template_php);
228
return (!$no_echo) ? $template_php : "\$$echo_var .= '" . $template_php . "'";
235
function compile_var_tags(&$text_blocks)
237
// change template varrefs into PHP varrefs
240
// This one will handle varrefs WITH namespaces
241
preg_match_all('#\{((?:[a-z0-9\-_]+\.)+)(\$)?([A-Z0-9\-_]+)\}#', $text_blocks, $varrefs, PREG_SET_ORDER);
243
foreach ($varrefs as $var_val)
245
$namespace = $var_val[1];
246
$varname = $var_val[3];
247
$new = $this->generate_block_varref($namespace, $varname, true, $var_val[2]);
249
$text_blocks = str_replace($var_val[0], $new, $text_blocks);
252
// This will handle the remaining root-level varrefs
253
// transform vars prefixed by L_ into their language variable pendant if nothing is set within the tpldata array
254
if (strpos($text_blocks, '{L_') !== false)
256
$text_blocks = preg_replace('#\{L_([a-z0-9\-_]*)\}#is', "<?php echo ((isset(\$this->_rootref['L_\\1'])) ? \$this->_rootref['L_\\1'] : ((isset(\$user->lang['\\1'])) ? \$user->lang['\\1'] : '{ \\1 }')); ?>", $text_blocks);
259
// Handle addslashed language variables prefixed with LA_
260
// If a template variable already exist, it will be used in favor of it...
261
if (strpos($text_blocks, '{LA_') !== false)
263
$text_blocks = preg_replace('#\{LA_([a-z0-9\-_]*)\}#is', "<?php echo ((isset(\$this->_rootref['LA_\\1'])) ? \$this->_rootref['LA_\\1'] : ((isset(\$this->_rootref['L_\\1'])) ? addslashes(\$this->_rootref['L_\\1']) : ((isset(\$user->lang['\\1'])) ? addslashes(\$user->lang['\\1']) : '{ \\1 }'))); ?>", $text_blocks);
266
// Handle remaining varrefs
267
$text_blocks = preg_replace('#\{([a-z0-9\-_]*)\}#is', "<?php echo (isset(\$this->_rootref['\\1'])) ? \$this->_rootref['\\1'] : ''; ?>", $text_blocks);
268
$text_blocks = preg_replace('#\{\$([a-z0-9\-_]*)\}#is', "<?php echo (isset(\$this->_tpldata['DEFINE']['.']['\\1'])) ? \$this->_tpldata['DEFINE']['.']['\\1'] : ''; ?>", $text_blocks);
277
function compile_tag_block($tag_args)
281
// Is the designer wanting to call another loop in a loop?
282
if (strpos($tag_args, '!') === 0)
284
// Count the number if ! occurrences (not allowed in vars)
285
$no_nesting = substr_count($tag_args, '!');
286
$tag_args = substr($tag_args, $no_nesting);
289
// Allow for control of looping (indexes start from zero):
290
// foo(2) : Will start the loop on the 3rd entry
291
// foo(-2) : Will start the loop two entries from the end
292
// foo(3,4) : Will start the loop on the fourth entry and end it on the fifth
293
// foo(3,-4) : Will start the loop on the fourth entry and end it four from last
294
if (preg_match('#^([^()]*)\(([\-\d]+)(?:,([\-\d]+))?\)$#', $tag_args, $match))
296
$tag_args = $match[1];
300
$loop_start = '($_' . $tag_args . '_count ' . $match[2] . ' < 0 ? 0 : $_' . $tag_args . '_count ' . $match[2] . ')';
304
$loop_start = '($_' . $tag_args . '_count < ' . $match[2] . ' ? $_' . $tag_args . '_count : ' . $match[2] . ')';
307
if (strlen($match[3]) < 1 || $match[3] == -1)
309
$loop_end = '$_' . $tag_args . '_count';
311
else if ($match[3] >= 0)
313
$loop_end = '(' . ($match[3] + 1) . ' > $_' . $tag_args . '_count ? $_' . $tag_args . '_count : ' . ($match[3] + 1) . ')';
315
else //if ($match[3] < -1)
317
$loop_end = '$_' . $tag_args . '_count' . ($match[3] + 1);
323
$loop_end = '$_' . $tag_args . '_count';
326
$tag_template_php = '';
327
array_push($this->block_names, $tag_args);
329
if ($no_nesting !== false)
331
// We need to implode $no_nesting times from the end...
332
$block = array_slice($this->block_names, -$no_nesting);
336
$block = $this->block_names;
339
if (sizeof($block) < 2)
341
// Block is not nested.
342
$tag_template_php = '$_' . $tag_args . "_count = (isset(\$this->_tpldata['$tag_args'])) ? sizeof(\$this->_tpldata['$tag_args']) : 0;";
343
$varref = "\$this->_tpldata['$tag_args']";
347
// This block is nested.
348
// Generate a namespace string for this block.
349
$namespace = implode('.', $block);
351
// Get a reference to the data array for this block that depends on the
352
// current indices of all parent blocks.
353
$varref = $this->generate_block_data_ref($namespace, false);
355
// Create the for loop code to iterate over this block.
356
$tag_template_php = '$_' . $tag_args . '_count = (isset(' . $varref . ')) ? sizeof(' . $varref . ') : 0;';
359
$tag_template_php .= 'if ($_' . $tag_args . '_count) {';
362
* The following uses foreach for iteration instead of a for loop, foreach is faster but requires PHP to make a copy of the contents of the array which uses more memory
366
* $tag_template_php .= 'foreach (' . $varref . ' as $_' . $tag_args . '_i => $_' . $tag_args . '_val){';
371
$tag_template_php .= 'for ($_' . $tag_args . '_i = ' . $loop_start . '; $_' . $tag_args . '_i < ' . $loop_end . '; ++$_' . $tag_args . '_i){';
372
$tag_template_php .= '$_'. $tag_args . '_val = &' . $varref . '[$_'. $tag_args. '_i];';
374
return $tag_template_php;
378
* Compile IF tags - much of this is from Smarty with
379
* some adaptions for our block level methods
382
function compile_tag_if($tag_args, $elseif)
384
// Tokenize args for 'if' tag.
386
"[^"\\\\]*(?:\\\\.[^"\\\\]*)*" |
387
\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' |
389
[^\s(),]+)/x', $tag_args, $match);
392
$is_arg_stack = array();
394
for ($i = 0, $size = sizeof($tokens); $i < $size; $i++)
396
$token = &$tokens[$i];
472
array_push($is_arg_stack, $i);
476
$is_arg_start = ($tokens[$i-1] == ')') ? array_pop($is_arg_stack) : $i-1;
477
$is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start));
479
$new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));
481
array_splice($tokens, $is_arg_start, sizeof($tokens), $new_tokens);
488
if (preg_match('#^((?:[a-z0-9\-_]+\.)+)?(\$)?(?=[A-Z])([A-Z0-9\-_]+)#s', $token, $varrefs))
490
$token = (!empty($varrefs[1])) ? $this->generate_block_data_ref(substr($varrefs[1], 0, -1), true, $varrefs[2]) . '[\'' . $varrefs[3] . '\']' : (($varrefs[2]) ? '$this->_tpldata[\'DEFINE\'][\'.\'][\'' . $varrefs[3] . '\']' : '$this->_rootref[\'' . $varrefs[3] . '\']');
492
else if (preg_match('#^\.((?:[a-z0-9\-_]+\.?)+)$#s', $token, $varrefs))
494
// Allow checking if loops are set with .loopname
495
// It is also possible to check the loop count by doing <!-- IF .loopname > 1 --> for example
496
$blocks = explode('.', $varrefs[1]);
498
// If the block is nested, we have a reference that we can grab.
499
// If the block is not nested, we just go and grab the block from _tpldata
500
if (sizeof($blocks) > 1)
502
$block = array_pop($blocks);
503
$namespace = implode('.', $blocks);
504
$varref = $this->generate_block_data_ref($namespace, true);
506
// Add the block reference for the last child.
507
$varref .= "['" . $block . "']";
511
$varref = '$this->_tpldata';
513
// Add the block reference for the last child.
514
$varref .= "['" . $blocks[0] . "']";
516
$token = "sizeof($varref)";
523
return (($elseif) ? '} else if (' : 'if (') . (implode(' ', $tokens) . ') { ');
527
* Compile DEFINE tags
530
function compile_tag_define($tag_args, $op)
532
preg_match('#^((?:[a-z0-9\-_]+\.)+)?\$(?=[A-Z])([A-Z0-9_\-]*)(?: = (\'?)([^\']*)(\'?))?$#', $tag_args, $match);
534
if (empty($match[2]) || (!isset($match[4]) && $op))
541
return 'unset(' . (($match[1]) ? $this->generate_block_data_ref(substr($match[1], 0, -1), true, true) . '[\'' . $match[2] . '\']' : '$this->_tpldata[\'DEFINE\'][\'.\'][\'' . $match[2] . '\']') . ');';
545
if ($match[3] && $match[5])
547
$match[4] = str_replace(array('\\\'', '\\\\', '\''), array('\'', '\\', '\\\''), $match[4]);
549
// Compile reference, we allow template variables in defines...
550
$match[4] = $this->compile($match[4]);
552
// Now replace the php code
553
$match[4] = "'" . str_replace(array('<?php echo ', '; ?>'), array("' . ", " . '"), $match[4]) . "'";
557
preg_match('#true|false|\.#i', $match[4], $type);
559
switch (strtolower($type[0]))
563
$match[4] = strtoupper($match[4]);
567
$match[4] = doubleval($match[4]);
571
$match[4] = intval($match[4]);
576
return (($match[1]) ? $this->generate_block_data_ref(substr($match[1], 0, -1), true, true) . '[\'' . $match[2] . '\']' : '$this->_tpldata[\'DEFINE\'][\'.\'][\'' . $match[2] . '\']') . ' = ' . $match[4] . ';';
580
* Compile INCLUDE tag
583
function compile_tag_include($tag_args)
585
return "\$this->_tpl_include('$tag_args');";
589
* Compile INCLUDE_PHP tag
592
function compile_tag_include_php($tag_args)
594
return "include('" . $tag_args . "');";
599
* This is from Smarty
602
function _parse_is_expr($is_arg, $tokens)
605
$negate_expr = false;
607
if (($first_token = array_shift($tokens)) == 'not')
610
$expr_type = array_shift($tokens);
614
$expr_type = $first_token;
620
if (@$tokens[$expr_end] == 'by')
623
$expr_arg = $tokens[$expr_end++];
624
$expr = "!(($is_arg / $expr_arg) % $expr_arg)";
628
$expr = "!($is_arg & 1)";
633
if (@$tokens[$expr_end] == 'by')
636
$expr_arg = $tokens[$expr_end++];
637
$expr = "(($is_arg / $expr_arg) % $expr_arg)";
641
$expr = "($is_arg & 1)";
646
if (@$tokens[$expr_end] == 'by')
649
$expr_arg = $tokens[$expr_end++];
650
$expr = "!($is_arg % $expr_arg)";
660
array_splice($tokens, 0, $expr_end, $expr);
666
* Generates a reference to the given variable inside the given (possibly nested)
667
* block namespace. This is a string of the form:
668
* ' . $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['varname'] . '
669
* It's ready to be inserted into an "echo" line in one of the templates.
670
* NOTE: expects a trailing "." on the namespace.
673
function generate_block_varref($namespace, $varname, $echo = true, $defop = false)
675
// Strip the trailing period.
676
$namespace = substr($namespace, 0, -1);
678
// Get a reference to the data block for this namespace.
679
$varref = $this->generate_block_data_ref($namespace, true, $defop);
680
// Prepend the necessary code to stick this in an echo line.
682
// Append the variable reference.
683
$varref .= "['$varname']";
684
$varref = ($echo) ? "<?php echo $varref; ?>" : ((isset($varref)) ? $varref : '');
690
* Generates a reference to the array of data values for the given
691
* (possibly nested) block namespace. This is a string of the form:
692
* $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['$childN']
694
* If $include_last_iterator is true, then [$_childN_i] will be appended to the form shown above.
695
* NOTE: does not expect a trailing "." on the blockname.
698
function generate_block_data_ref($blockname, $include_last_iterator, $defop = false)
700
// Get an array of the blocks involved.
701
$blocks = explode('.', $blockname);
702
$blockcount = sizeof($blocks) - 1;
704
// DEFINE is not an element of any referenced variable, we must use _tpldata to access it
707
$varref = '$this->_tpldata[\'DEFINE\']';
708
// Build up the string with everything but the last child.
709
for ($i = 0; $i < $blockcount; $i++)
711
$varref .= "['" . $blocks[$i] . "'][\$_" . $blocks[$i] . '_i]';
713
// Add the block reference for the last child.
714
$varref .= "['" . $blocks[$blockcount] . "']";
715
// Add the iterator for the last child if requried.
716
if ($include_last_iterator)
718
$varref .= '[$_' . $blocks[$blockcount] . '_i]';
722
else if ($include_last_iterator)
724
return '$_'. $blocks[$blockcount] . '_val';
728
return '$_'. $blocks[$blockcount - 1] . '_val[\''. $blocks[$blockcount]. '\']';
733
* Write compiled file to cache directory
736
function compile_write($handle, $data)
740
$filename = $this->template->cachepath . str_replace('/', '.', $this->template->filename[$handle]) . '.' . $phpEx;
742
if ($fp = @fopen($filename, 'wb'))
744
@flock($fp, LOCK_EX);
745
@fwrite ($fp, $data);
746
@flock($fp, LOCK_UN);
749
@chmod($filename, 0666);
b'\\ No newline at end of file'