source: trunk/include/template.php @ 1587

Last change on this file since 1587 was 1587, checked in by rvelices, 18 years ago

template improvement: added merge_block_vars method (instead of creating a
new block iteration, it merges given variables with the last block). This
is a trick available to plugins (it will avoid calling trigger_event
every 2 lines).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 18.6 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2005 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $RCSfile$
9// | last update   : $Date: 2006-10-31 03:39:39 +0000 (Tue, 31 Oct 2006) $
10// | last modifier : $Author: rvelices $
11// | revision      : $Revision: 1587 $
12// +-----------------------------------------------------------------------+
13// | This program is free software; you can redistribute it and/or modify  |
14// | it under the terms of the GNU General Public License as published by  |
15// | the Free Software Foundation                                          |
16// |                                                                       |
17// | This program is distributed in the hope that it will be useful, but   |
18// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
19// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
20// | General Public License for more details.                              |
21// |                                                                       |
22// | You should have received a copy of the GNU General Public License     |
23// | along with this program; if not, write to the Free Software           |
24// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
25// | USA.                                                                  |
26// +-----------------------------------------------------------------------+
27
28/**
29 * Template class. By Nathan Codding of the phpBB group. The interface was
30 * originally inspired by PHPLib templates, and the template file formats
31 * are quite similar.
32 */
33
34class Template {
35
36  var $classname = "Template";
37
38  // variable that holds all the data we'll be substituting into
39  // the compiled templates.
40  // ...
41  // This will end up being a multi-dimensional array like this :
42  // $this->_tpldata[block.][iteration#][child.][iteration#][child2.][iteration#][variablename] == value
43  // if it's a root-level variable, it'll be like this:
44  // $this->_tpldata[.][0][varname] == value
45  var $_tpldata = array();
46
47  // Hash of filenames for each template handle.
48  var $files = array();
49
50  // Root template directory.
51  var $root = "";
52
53  // this will hash handle names to the compiled code for that handle.
54  var $compiled_code = array();
55
56  // This will hold the uncompiled code for that handle.
57  var $uncompiled_code = array();
58
59  // output
60  var $output = '';
61
62  var $themeconf = array();
63
64  /**
65   * Constructor. Simply sets the root dir.
66   *
67   */
68  function Template($root = ".", $theme= "")
69    {
70      if ( $this->set_rootdir($root) )
71      {
72        if ( !empty( $theme ) )
73        {
74          include($root.'/theme/'.$theme.'/themeconf.inc.php');
75          $this->themeconf = $themeconf;
76        }
77      }
78    }
79
80  /**
81   * Destroys this template object. Should be called when you're done with
82   * it, in order to clear out the template data so you can load/parse a new
83   * template set.
84   */
85  function destroy()
86    {
87      $this->_tpldata = array();
88    }
89
90  /**
91   * Sets the template root directory for this Template object.
92   */
93  function set_rootdir($dir)
94    {
95      if (!is_dir($dir))
96      {
97        return false;
98      }
99
100      $this->root = $dir;
101      return true;
102    }
103
104  /**
105   * Sets the template filenames for handles. $filename_array should be a
106   * hash of handle => filename pairs.
107   */
108  function set_filenames($filename_array)
109    {
110      if (!is_array($filename_array))
111      {
112        return false;
113      }
114
115      reset($filename_array);
116      while(list($handle, $filename) = each($filename_array))
117      {
118        $this->files[$handle] = $this->make_filename($filename);
119      }
120
121      return true;
122    }
123
124
125  /**
126   * Load the file for the handle, compile the file, and run the compiled
127   * code. This will print out the results of executing the template.
128   */
129  function pparse($handle)
130    {
131      if (!$this->loadfile($handle))
132      {
133        die("Template->pparse(): Couldn't load template file for handle $handle");
134      }
135
136      // actually compile the template now.
137      if (!isset($this->compiled_code[$handle]) || empty($this->compiled_code[$handle]))
138      {
139        // Actually compile the code now.
140        $this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle]);
141      }
142
143      // Run the compiled code.
144      //echo ("<!-- ".$this->compiled_code[$handle]." -->");
145      eval($this->compiled_code[$handle]);
146      return true;
147    }
148
149  /**
150   * fills $output template var
151   */
152  function parse($handle)
153    {
154      if (!$this->loadfile($handle))
155      {
156        die("Template->pparse(): Couldn't load template file for handle $handle");
157      }
158
159      // actually compile the template now.
160      if (!isset($this->compiled_code[$handle]) || empty($this->compiled_code[$handle]))
161      {
162        // Actually compile the code now.
163        $this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle], true, '_str');
164      }
165
166      // Run the compiled code.
167      $_str = '';
168      eval($this->compiled_code[$handle]);
169      $this->output.= $_str;
170
171      return true;
172    }
173
174  /**
175   * prints $output template var
176   */
177  function p()
178    {
179      echo $this->output;
180    }
181
182  /**
183   * Inserts the uncompiled code for $handle as the value of $varname in the
184   * root-level. This can be used to effectively include a template in the
185   * middle of another template.
186   *
187   * Note that all desired assignments to the variables in $handle should be
188   * done BEFORE calling this function.
189   */
190  function assign_var_from_handle($varname, $handle)
191    {
192      if (!$this->loadfile($handle))
193      {
194        die("Template->assign_var_from_handle(): Couldn't load template file for handle $handle");
195      }
196
197      // Compile it, with the "no echo statements" option on.
198      $_str = "";
199      $code = $this->compile($this->uncompiled_code[$handle], true, '_str');
200
201      // evaluate the variable assignment.
202      eval($code);
203      // assign the value of the generated variable to the given varname.
204      $this->assign_var($varname, $_str);
205
206      return true;
207    }
208
209  /**
210   * Block-level variable assignment. Adds a new block iteration with the
211   * given variable assignments. Note that this should only be called once
212   * per block iteration.
213   */
214  function assign_block_vars($blockname, $vararray)
215    {
216      if (strstr($blockname, '.'))
217      {
218        // Nested block.
219        $blocks = explode('.', $blockname);
220        $blockcount = sizeof($blocks) - 1;
221        $str = '$this->_tpldata';
222        for ($i = 0; $i < $blockcount; $i++)
223        {
224          $str .= '[\'' . $blocks[$i] . '.\']';
225          eval('$lastiteration = isset('.$str.') ? sizeof('.$str.')-1:0;');
226          $str .= '[' . $lastiteration . ']';
227        }
228        // Now we add the block that we're actually assigning to.
229        // We're adding a new iteration to this block with the given
230        // variable assignments.
231        $str .= '[\'' . $blocks[$blockcount] . '.\'][] = $vararray;';
232
233        // Now we evaluate this assignment we've built up.
234        eval($str);
235      }
236      else
237      {
238        // Top-level block. Add a new iteration to this block with the
239        // variable assignments we were given.
240        $this->_tpldata[$blockname . '.'][] = $vararray;
241      }
242
243      return true;
244    }
245
246  /**
247   * Block-level variable merge. Merge given variables to the last block
248   * iteration. This can be called several times per block iteration.
249   */
250  function merge_block_vars($blockname, $vararray)
251    {
252      $blocks = explode('.', $blockname);
253      $blockcount = count($blocks);
254      $str = '$this->_tpldata';
255      for ($i = 0; $i < $blockcount; $i++)
256      {
257        $str .= '[\'' . $blocks[$i] . '.\']';
258        eval('$lastiteration = isset('.$str.') ? sizeof('.$str.')-1:-1;');
259        if ($lastiteration==-1)
260        {
261          return false;
262        }
263        $str .= '[' . $lastiteration . ']';
264      }
265      $str = $str.'=array_merge('.$str.', $vararray);';
266      eval($str);
267      return true;
268    }
269
270  /**
271   * Root-level variable assignment. Adds to current assignments, overriding
272   * any existing variable assignment with the same name.
273   */
274  function assign_vars($vararray)
275    {
276      reset ($vararray);
277      while (list($key, $val) = each($vararray))
278      {
279        $this->_tpldata['.'][0][$key] = $val;
280      }
281
282      return true;
283    }
284
285  /**
286   * Root-level variable assignment. Adds to current assignments, overriding
287   * any existing variable assignment with the same name.
288   */
289  function assign_var($varname, $varval)
290    {
291      $this->_tpldata['.'][0][$varname] = $varval;
292
293      return true;
294    }
295
296
297  /**
298   * Generates a full path+filename for the given filename, which can either
299   * be an absolute name, or a name relative to the rootdir for this
300   * Template object.
301   */
302  function make_filename($filename)
303    {
304      // Check if it's an absolute or relative path.
305      if (substr($filename, 0, 1) != '/'
306          and substr($filename, 0, 1) != '\\' //Windows UNC path
307          and !preg_match('/^[a-z]:\\\/i', $filename) )
308      {
309        $filename = $this->root.'/'.$filename;
310      }
311
312      if (!file_exists($filename))
313      {
314        die("Template->make_filename(): Error - file $filename does not exist");
315      }
316
317      return $filename;
318    }
319
320
321  /**
322   * If not already done, load the file for the given handle and populate
323   * the uncompiled_code[] hash with its code. Do not compile.
324   */
325  function loadfile($handle)
326    {
327      // If the file for this handle is already loaded and compiled, do
328      // nothing.
329      if (isset($this->uncompiled_code[$handle])
330          and !empty($this->uncompiled_code[$handle]))
331      {
332        return true;
333      }
334
335      // If we don't have a file assigned to this handle, die.
336      if (!isset($this->files[$handle]))
337      {
338        die("Template->loadfile(): No file specified for handle $handle");
339      }
340
341      $filename = $this->files[$handle];
342
343      $str = implode("", @file($filename));
344
345      if (empty($str))
346      {
347        die("Template->loadfile(): File $filename for handle $handle is empty");
348      }
349
350      $this->uncompiled_code[$handle] = $str;
351
352      return true;
353    }
354
355
356
357  /**
358   * Compiles the given string of code, and returns the result in a string.
359   *
360   * If "do_not_echo" is true, the returned code will not be directly
361   * executable, but can be used as part of a variable assignment for use in
362   * assign_code_from_handle().
363   */
364  function compile($code, $do_not_echo = false, $retvar = '')
365    {
366      // PWG specific : communication between template and $lang
367      $code = preg_replace('/\{lang:([^}]+)\}/e', "l10n('$1')", $code);
368      // PWG specific : expand themeconf.inc.php variables
369      $code = preg_replace('/\{themeconf:([^}]+)\}/e', '$this->get_themeconf(\'$1\')', $code);
370      $code = preg_replace('/\{pwg_root\}/e', "get_root_url()", $code);
371
372      // replace \ with \\ and then ' with \'.
373      $code = str_replace('\\', '\\\\', $code);
374      $code = str_replace('\'', '\\\'', $code);
375
376      // change template varrefs into PHP varrefs
377
378      // This one will handle varrefs WITH namespaces
379      $varrefs = array();
380      preg_match_all('#\{(([a-z0-9\-_]+?\.)+?)([a-z0-9\-_]+?)\}#is', $code, $varrefs);
381      $varcount = sizeof($varrefs[1]);
382      for ($i = 0; $i < $varcount; $i++)
383      {
384        $namespace = $varrefs[1][$i];
385        $varname = $varrefs[3][$i];
386        $new = $this->generate_block_varref($namespace, $varname);
387
388        $code = str_replace($varrefs[0][$i], $new, $code);
389      }
390
391      // This will handle the remaining root-level varrefs
392      $code = preg_replace('#\{([a-z0-9\-_]*?)\}#is', '\' . ( ( isset($this->_tpldata[\'.\'][0][\'\1\']) ) ? $this->_tpldata[\'.\'][0][\'\1\'] : \'\' ) . \'', $code);
393
394      // Break it up into lines.
395      $code_lines = explode("\n", $code);
396
397      $block_nesting_level = 0;
398      $block_names = array();
399      $block_names[0] = ".";
400
401      // Second: prepend echo ', append ' . "\n"; to each line.
402      $line_count = sizeof($code_lines);
403      for ($i = 0; $i < $line_count; $i++)
404      {
405        $code_lines[$i] = chop($code_lines[$i]);
406        if (preg_match('#<!-- BEGIN (.*?) -->#', $code_lines[$i], $m))
407        {
408          $n[0] = $m[0];
409          $n[1] = $m[1];
410
411          // Added: dougk_ff7-Keeps templates from bombing if begin is on
412          // the same line as end.. I think. :)
413          if ( preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $n) )
414          {
415            $block_nesting_level++;
416            $block_names[$block_nesting_level] = $m[1];
417            if ($block_nesting_level < 2)
418            {
419              // Block is not nested.
420              $code_lines[$i] = '$_' . $n[1] . '_count = ( isset($this->_tpldata[\'' . $n[1] . '.\']) ) ?  sizeof($this->_tpldata[\'' . $n[1] . '.\']) : 0;';
421              $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
422              $code_lines[$i] .= "\n" . '{';
423            }
424            else
425            {
426              // This block is nested.
427
428              // Generate a namespace string for this block.
429              $namespace = implode('.', $block_names);
430              // strip leading period from root level..
431              $namespace = substr($namespace, 2);
432              // Get a reference to the data array for this block that depends on the
433              // current indices of all parent blocks.
434              $varref = $this->generate_block_data_ref($namespace, false);
435              // Create the for loop code to iterate over this block.
436              $code_lines[$i] = '$_' . $n[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
437              $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
438              $code_lines[$i] .= "\n" . '{';
439            }
440
441            // We have the end of a block.
442            unset($block_names[$block_nesting_level]);
443            $block_nesting_level--;
444            $code_lines[$i] .= '} // END ' . $n[1];
445            $m[0] = $n[0];
446            $m[1] = $n[1];
447          }
448          else
449          {
450            // We have the start of a block.
451            $block_nesting_level++;
452            $block_names[$block_nesting_level] = $m[1];
453            if ($block_nesting_level < 2)
454            {
455              // Block is not nested.
456              $code_lines[$i] = '$_' . $m[1] . '_count = ( isset($this->_tpldata[\'' . $m[1] . '.\']) ) ? sizeof($this->_tpldata[\'' . $m[1] . '.\']) : 0;';
457              $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
458              $code_lines[$i] .= "\n" . '{';
459            }
460            else
461            {
462              // This block is nested.
463
464              // Generate a namespace string for this block.
465              $namespace = implode('.', $block_names);
466              // strip leading period from root level..
467              $namespace = substr($namespace, 2);
468              // Get a reference to the data array for this block that
469              // depends on the current indices of all parent blocks.
470              $varref = $this->generate_block_data_ref($namespace, false);
471              // Create the for loop code to iterate over this block.
472              $code_lines[$i] = '$_' . $m[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
473              $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
474              $code_lines[$i] .= "\n" . '{';
475            }
476          }
477        }
478        else if (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $m))
479        {
480          // We have the end of a block.
481          unset($block_names[$block_nesting_level]);
482          $block_nesting_level--;
483          $code_lines[$i] = '} // END ' . $m[1];
484        }
485        else
486        {
487          // We have an ordinary line of code.
488          if (!$do_not_echo)
489          {
490            $code_lines[$i] = 'echo \'' . $code_lines[$i] . '\' . "\\n";';
491          }
492          else
493          {
494            $code_lines[$i] = '$' . $retvar . '.= \'' . $code_lines[$i] . '\' . "\\n";';
495          }
496        }
497      }
498
499      // Bring it back into a single string of lines of code.
500      $code = implode("\n", $code_lines);
501      return $code      ;
502
503    }
504
505
506  /**
507   * Generates a reference to the given variable inside the given (possibly
508   * nested) block namespace. This is a string of the form: '
509   * . $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['varname']
510   * . ' It's ready to be inserted into an "echo" line in one of the
511   * templates.  NOTE: expects a trailing "." on the namespace.
512   */
513  function generate_block_varref($namespace, $varname)
514    {
515      // Strip the trailing period.
516      $namespace = substr($namespace, 0, strlen($namespace) - 1);
517
518      // Get a reference to the data block for this namespace.
519      $varref = $this->generate_block_data_ref($namespace, true);
520      // Prepend the necessary code to stick this in an echo line.
521
522      // Append the variable reference.
523      $varref .= '[\'' . $varname . '\']';
524
525      $varref = '\' . ( ( isset(' . $varref . ') ) ? ' . $varref . ' : \'\' ) . \'';
526
527      return $varref;
528
529    }
530
531
532  /**
533   * Generates a reference to the array of data values for the given
534   * (possibly nested) block namespace. This is a string of the form:
535   * $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['$childN']
536   *
537   * If $include_last_iterator is true, then [$_childN_i] will be appended
538   * to the form shown above.  NOTE: does not expect a trailing "." on the
539   * blockname.
540   */
541  function generate_block_data_ref($blockname, $include_last_iterator)
542    {
543      // Get an array of the blocks involved.
544      $blocks = explode(".", $blockname);
545      $blockcount = sizeof($blocks) - 1;
546      $varref = '$this->_tpldata';
547      // Build up the string with everything but the last child.
548      for ($i = 0; $i < $blockcount; $i++)
549      {
550        $varref .= '[\'' . $blocks[$i] . '.\'][$_' . $blocks[$i] . '_i]';
551      }
552      // Add the block reference for the last child.
553      $varref .= '[\'' . $blocks[$blockcount] . '.\']';
554      // Add the iterator for the last child if requried.
555      if ($include_last_iterator)
556      {
557              $varref .= '[$_' . $blocks[$blockcount] . '_i]';
558      }
559
560      return $varref;
561    }
562
563    function get_themeconf($key)
564    {
565      return isset($this->themeconf[$key]) ? $this->themeconf[$key] : '';
566    }
567}
568
569?>
Note: See TracBrowser for help on using the repository browser.