2 /***************************************************************************
5 * begin : Saturday, Feb 13, 2001
6 * copyright : (C) 2001 The phpBB Group
7 * email : support@phpbb.com
9 * $Id: template.php,v 1.7 2002/01/28 19:12:37 psotfx Exp $
12 ***************************************************************************/
14 /***************************************************************************
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 2 of the License, or
19 * (at your option) any later version.
21 ***************************************************************************/
24 * Template class. By Nathan Codding of the phpBB group.
25 * The interface was originally inspired by PHPLib templates,
26 * and the template file formats are quite similar.
31 var $classname = "Template";
33 // variable that holds all the data we'll be substituting into
34 // the compiled templates.
36 // This will end up being a multi-dimensional array like this:
37 // $this->_tpldata[block.][iteration#][child.][iteration#][child2.][iteration#][variablename] == value
38 // if it's a root-level variable, it'll be like this:
39 // $this->_tpldata[.][0][varname] == value
40 var $_tpldata = array();
42 // Hash of filenames for each template handle.
45 // Root template directory.
48 // this will hash handle names to the compiled code for that handle.
49 var $compiled_code = array();
51 // This will hold the uncompiled code for that handle.
52 var $uncompiled_code = array();
55 * Constructor. Simply sets the root dir.
58 function Template($root = '.')
62 $this->set_rootdir($root);
65 $this->pparse_order = array();
69 * Destroys this template object. Should be called when you're done with it, in order
70 * to clear out the template data so you can load/parse a new template set.
74 $this->_tpldata = array();
78 * Sets the template root directory for this Template object.
80 function set_rootdir($dir)
92 * Sets the template filenames for handles. $filename_array
93 * should be a hash of handle => filename pairs.
95 function set_filenames($filename_array)
99 if ( !is_array($filename_array) )
104 $template_names = '';
105 @reset($filename_array);
106 while ( list($handle, $filename) = @each($filename_array) )
108 $this->files[$handle] = $this->make_filename($filename);
109 $template_names .= ( $template_names != '' ) ? ", '" . addslashes($this->files[$handle]) . "'" : "'" . addslashes($this->files[$handle]) . "'";
113 FROM " . $table_prefix . "template_cache
114 WHERE template_name IN ($template_names)";
115 if ( $result = $this->db->sql_query($sql) )
117 while( $row = $this->db->sql_fetchrow($result) )
119 if( $row['template_cached'] == filemtime($row['template_name']) )
121 $this->compiled_code[$row['template_handle']] = $row['template_compile'];
122 $this->echo_compiled[$row['template_handle']] = $row['template_echo'];
127 $this->db->sql_freeresult();
134 * Load the file for the handle, compile the file,
135 * and run the compiled code. This will print out
136 * the results of executing the template.
138 function pparse($handle)
140 global $table_prefix;
142 if( empty($this->compiled_code[$handle]) )
144 if ( !$this->loadfile($handle) )
146 die("Template->pparse(): Couldn't load template file for handle $handle");
150 // Actually compile the code now.
152 $this->echo_compiled[$handle] = 1;
153 $this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle]);
155 $sql = "REPLACE INTO " . $table_prefix . "template_cache (template_name, template_handle, template_cached, template_compile) VALUES ('" . addslashes($this->files[$handle]) . "', '" . addslashes($handle) . "', " . filemtime($this->files[$handle]) . ", '" . addslashes($this->compiled_code[$handle]) . "')";
156 if ( !($result = $this->db->sql_query($sql)) )
158 die("Couldn't insert template into cache!");
164 eval($this->compiled_code[$handle]);
175 * Inserts the uncompiled code for $handle as the
176 * value of $varname in the root-level. This can be used
177 * to effectively include a template in the middle of another
179 * Note that all desired assignments to the variables in $handle should be done
180 * BEFORE calling this function.
182 function assign_var_from_handle($varname, $handle)
184 global $table_prefix;
186 if( empty($this->compiled_code[$handle]) )
188 if ( !$this->loadfile($handle) )
190 die("Template->pparse(): Couldn't load template file for handle $handle");
193 $code = $this->compile($this->uncompiled_code[$handle], true, '_str');
195 $sql = "REPLACE INTO " . $table_prefix . "template_cache (template_name, template_handle, template_echo, template_cached, template_compile) VALUES ('" . addslashes($this->files[$handle]) . "', '" . addslashes($handle) . "', 0, " . filemtime($this->files[$handle]) . ", '" . addslashes($code) . "')";
196 if ( !($result = $this->db->sql_query($sql)) )
198 die("Couldn't insert template into cache!");
203 $code = $this->compiled_code[$handle];
206 // Compile It, With The "no Echo Statements" Option On.
208 // evaluate the variable assignment.
210 // assign the value of the generated variable to the given varname.
211 $this->assign_var($varname, $_str);
217 * Block-level variable assignment. Adds a new block iteration with the given
218 * variable assignments. Note that this should only be called once per block
221 function assign_block_vars($blockname, $vararray)
223 if (strstr($blockname, '.'))
226 $blocks = explode('.', $blockname);
227 $blockcount = sizeof($blocks) - 1;
228 $str = '$this->_tpldata';
229 for ($i = 0; $i < $blockcount; $i++)
231 $str .= '[\'' . $blocks[$i] . '.\']';
232 eval('$lastiteration = sizeof(' . $str . ') - 1;');
233 $str .= '[' . $lastiteration . ']';
235 // Now we add the block that we're actually assigning to.
236 // We're adding a new iteration to this block with the given
237 // variable assignments.
238 $str .= '[\'' . $blocks[$blockcount] . '.\'][] = $vararray;';
240 // Now we evaluate this assignment we've built up.
246 // Add a new iteration to this block with the variable assignments
248 $this->_tpldata[$blockname . '.'][] = $vararray;
255 * Root-level variable assignment. Adds to current assignments, overriding
256 * any existing variable assignment with the same name.
258 function assign_vars($vararray)
261 while (list($key, $val) = each($vararray))
263 $this->_tpldata['.'][0][$key] = $val;
270 * Root-level variable assignment. Adds to current assignments, overriding
271 * any existing variable assignment with the same name.
273 function assign_var($varname, $varval)
275 $this->_tpldata['.'][0][$varname] = $varval;
282 * Generates a full path+filename for the given filename, which can either
283 * be an absolute name, or a name relative to the rootdir for this Template
286 function make_filename($filename)
288 // Check if it's an absolute or relative path.
289 if (substr($filename, 0, 1) != '/')
291 $filename = $this->root . '/' . $filename;
294 if (!file_exists($filename))
296 die("Template->make_filename(): Error - file $filename does not exist");
304 * If not already done, load the file for the given handle and populate
305 * the uncompiled_code[] hash with its code. Do not compile.
307 function loadfile($handle)
309 // If the file for this handle is already loaded and compiled, do nothing.
310 if ( !empty($this->uncompiled_code[$handle]) )
315 // If we don't have a file assigned to this handle, die.
316 if (!isset($this->files[$handle]))
318 die("Template->loadfile(): No file specified for handle $handle");
321 $filename = $this->files[$handle];
323 $str = implode("", @file($filename));
326 die("Template->loadfile(): File $filename for handle $handle is empty");
329 $this->uncompiled_code[$handle] = $str;
337 * Compiles the given string of code, and returns
338 * the result in a string.
339 * If "do_not_echo" is true, the returned code will not be directly
340 * executable, but can be used as part of a variable assignment
341 * for use in assign_code_from_handle().
343 function compile($code, $do_not_echo = false, $retvar = '')
345 // replace \ with \\ and then ' with \'.
346 $code = str_replace('\\', '\\\\', $code);
347 $code = str_replace('\'', '\\\'', $code);
349 // change template varrefs into PHP varrefs
351 // This one will handle varrefs WITH namespaces
353 preg_match_all('#\{(([a-z0-9\-_]+?\.)+?)([a-z0-9\-_]+?)\}#is', $code, $varrefs);
354 $varcount = sizeof($varrefs[1]);
355 for ($i = 0; $i < $varcount; $i++)
357 $namespace = $varrefs[1][$i];
358 $varname = $varrefs[3][$i];
359 $new = $this->generate_block_varref($namespace, $varname);
361 $code = str_replace($varrefs[0][$i], $new, $code);
364 // This will handle the remaining root-level varrefs
365 $code = preg_replace('#\{([a-z0-9\-_]*?)\}#is', '\' . ( ( isset($this->_tpldata[\'.\'][0][\'\1\']) ) ? $this->_tpldata[\'.\'][0][\'\1\'] : \'\' ) . \'', $code);
367 // Break it up into lines.
368 $code_lines = explode("\n", $code);
370 $block_nesting_level = 0;
371 $block_names = array();
372 $block_names[0] = ".";
374 // Second: prepend echo ', append ' . "\n"; to each line.
375 $line_count = sizeof($code_lines);
376 for ($i = 0; $i < $line_count; $i++)
378 $code_lines[$i] = chop($code_lines[$i]);
379 if (preg_match('#<!-- BEGIN (.*?) -->#', $code_lines[$i], $m))
384 // Added: dougk_ff7-Keeps templates from bombing if begin is on the same line as end.. I think. :)
385 if ( preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $n) )
387 $block_nesting_level++;
388 $block_names[$block_nesting_level] = $m[1];
389 if ($block_nesting_level < 2)
391 // Block is not nested.
392 $code_lines[$i] = '$_' . $a[1] . '_count = ( isset($this->_tpldata[\'' . $n[1] . '.\']) ) ? sizeof($this->_tpldata[\'' . $n[1] . '.\']) : 0;';
393 $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
394 $code_lines[$i] .= "\n" . '{';
398 // This block is nested.
400 // Generate a namespace string for this block.
401 $namespace = implode('.', $block_names);
402 // strip leading period from root level..
403 $namespace = substr($namespace, 2);
404 // Get a reference to the data array for this block that depends on the
405 // current indices of all parent blocks.
406 $varref = $this->generate_block_data_ref($namespace, false);
407 // Create the for loop code to iterate over this block.
408 $code_lines[$i] = '$_' . $a[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
409 $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
410 $code_lines[$i] .= "\n" . '{';
413 // We have the end of a block.
414 unset($block_names[$block_nesting_level]);
415 $block_nesting_level--;
416 $code_lines[$i] .= '} // END ' . $n[1];
422 // We have the start of a block.
423 $block_nesting_level++;
424 $block_names[$block_nesting_level] = $m[1];
425 if ($block_nesting_level < 2)
427 // Block is not nested.
428 $code_lines[$i] = '$_' . $m[1] . '_count = ( isset($this->_tpldata[\'' . $m[1] . '.\']) ) ? sizeof($this->_tpldata[\'' . $m[1] . '.\']) : 0;';
429 $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
430 $code_lines[$i] .= "\n" . '{';
434 // This block is nested.
436 // Generate a namespace string for this block.
437 $namespace = implode('.', $block_names);
438 // strip leading period from root level..
439 $namespace = substr($namespace, 2);
440 // Get a reference to the data array for this block that depends on the
441 // current indices of all parent blocks.
442 $varref = $this->generate_block_data_ref($namespace, false);
443 // Create the for loop code to iterate over this block.
444 $code_lines[$i] = '$_' . $m[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
445 $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
446 $code_lines[$i] .= "\n" . '{';
450 else if (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $m))
452 // We have the end of a block.
453 unset($block_names[$block_nesting_level]);
454 $block_nesting_level--;
455 $code_lines[$i] = '} // END ' . $m[1];
459 // We have an ordinary line of code.
462 $code_lines[$i] = 'echo \'' . $code_lines[$i] . '\' . "\\n";';
466 $code_lines[$i] = '$' . $retvar . '.= \'' . $code_lines[$i] . '\' . "\\n";';
471 // Bring it back into a single string of lines of code.
472 $code = implode("\n", $code_lines);
479 * Generates a reference to the given variable inside the given (possibly nested)
480 * block namespace. This is a string of the form:
481 * ' . $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['varname'] . '
482 * It's ready to be inserted into an "echo" line in one of the templates.
483 * NOTE: expects a trailing "." on the namespace.
485 function generate_block_varref($namespace, $varname)
487 // Strip the trailing period.
488 $namespace = substr($namespace, 0, strlen($namespace) - 1);
490 // Get a reference to the data block for this namespace.
491 $varref = $this->generate_block_data_ref($namespace, true);
492 // Prepend the necessary code to stick this in an echo line.
494 // Append the variable reference.
495 $varref .= '[\'' . $varname . '\']';
497 $varref = '\' . ( ( isset(' . $varref . ') ) ? ' . $varref . ' : \'\' ) . \'';
505 * Generates a reference to the array of data values for the given
506 * (possibly nested) block namespace. This is a string of the form:
507 * $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['$childN']
509 * If $include_last_iterator is true, then [$_childN_i] will be appended to the form shown above.
510 * NOTE: does not expect a trailing "." on the blockname.
512 function generate_block_data_ref($blockname, $include_last_iterator)
514 // Get an array of the blocks involved.
515 $blocks = explode(".", $blockname);
516 $blockcount = sizeof($blocks) - 1;
517 $varref = '$this->_tpldata';
518 // Build up the string with everything but the last child.
519 for ($i = 0; $i < $blockcount; $i++)
521 $varref .= '[\'' . $blocks[$i] . '.\'][$_' . $blocks[$i] . '_i]';
523 // Add the block reference for the last child.
524 $varref .= '[\'' . $blocks[$blockcount] . '.\']';
525 // Add the iterator for the last child if requried.
526 if ($include_last_iterator)
528 $varref .= '[$_' . $blocks[$blockcount] . '_i]';