source: branches/branch-1_7/include/template.php @ 2054

Last change on this file since 2054 was 2035, checked in by rub, 17 years ago

Enhancement for the plugin development:

o Add footer block
o Add useful triggers on template object

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 20.0 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-2007 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $Id: template.php 2035 2007-06-13 05:14:54Z rub $
9// | last update   : $Date: 2007-06-13 05:14:54 +0000 (Wed, 13 Jun 2007) $
10// | last modifier : $Author: rub $
11// | revision      : $Revision: 2035 $
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 filename for handle.
106   */
107  function set_filename($handle, $filename)
108    {
109      return $this->set_filenames( array($handle=>$filename) );
110    }
111
112  /**
113   * Sets the template filenames for handles. $filename_array should be a
114   * hash of handle => filename pairs.
115   */
116  function set_filenames($filename_array)
117    {
118      $filename_array = trigger_event('loc_tpl_set_filenames', $filename_array, array(&$this));
119
120      if (!is_array($filename_array))
121      {
122        return false;
123      }
124
125      reset($filename_array);
126      while(list($handle, $filename) = each($filename_array))
127      {
128        if (is_null($filename))
129        {
130          unset( $this->files[$handle] );
131        }
132        else
133        {
134          $this->files[$handle] = $this->make_filename($filename);
135        }
136        unset($this->compiled_code[$handle]);
137        unset($this->uncompiled_code[$handle]);
138      }
139
140      return true;
141    }
142
143
144  /**
145   * Load the file for the handle, compile the file, and run the compiled
146   * code. This will print out the results of executing the template.
147   */
148  function pparse($handle)
149    {
150      if (!$this->loadfile($handle))
151      {
152        die("Template->pparse(): Couldn't load template file for handle $handle");
153      }
154
155      // actually compile the template now.
156      if (!isset($this->compiled_code[$handle]) || empty($this->compiled_code[$handle]))
157      {
158        trigger_action('loc_before_tpl_pparse', $handle, array(&$this));
159        // Actually compile the code now.
160        $this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle]);
161      }
162
163      // Run the compiled code.
164      //echo ("<!-- ".$this->compiled_code[$handle]." -->");
165      eval($this->compiled_code[$handle]);
166      return true;
167    }
168
169  /**
170   * fills $output template var by default or returns the content
171   */
172  function parse($handle, $return=false)
173    {
174      if (!$this->loadfile($handle))
175      {
176        die("Template->pparse(): Couldn't load template file for handle $handle");
177      }
178
179      // actually compile the template now.
180      if (!isset($this->compiled_code[$handle]) || empty($this->compiled_code[$handle]))
181      {
182        trigger_action('loc_before_tpl_parse', $handle, array(&$this));
183        // Actually compile the code now.
184        $this->compiled_code[$handle] = $this->compile($this->uncompiled_code[$handle], true, '_str');
185      }
186
187      // Run the compiled code.
188      $_str = '';
189      eval($this->compiled_code[$handle]);
190      if ($return)
191      {
192        return $_str;
193      }
194      $this->output.= $_str;
195
196      return true;
197    }
198
199  /**
200   * prints $output template var
201   */
202  function p()
203    {
204      echo $this->output;
205    }
206
207  /**
208   * Inserts the uncompiled code for $handle as the value of $varname in the
209   * root-level. This can be used to effectively include a template in the
210   * middle of another template.
211   *
212   * Note that all desired assignments to the variables in $handle should be
213   * done BEFORE calling this function.
214   */
215  function assign_var_from_handle($varname, $handle)
216    {
217      if (!$this->loadfile($handle))
218      {
219        die("Template->assign_var_from_handle(): Couldn't load template file for handle $handle");
220      }
221
222      trigger_action('loc_before_tpl_assign_var_from_handle', $handle, array(&$this));
223      // Compile it, with the "no echo statements" option on.
224      $_str = "";
225      $code = $this->compile($this->uncompiled_code[$handle], true, '_str');
226
227      // evaluate the variable assignment.
228      eval($code);
229      // assign the value of the generated variable to the given varname.
230      $this->assign_var($varname, $_str);
231
232      return true;
233    }
234
235  /**
236   * Block-level variable assignment. Adds a new block iteration with the
237   * given variable assignments. Note that this should only be called once
238   * per block iteration.
239   */
240  function assign_block_vars($blockname, $vararray)
241    {
242      if (strstr($blockname, '.'))
243      {
244        // Nested block.
245        $blocks = explode('.', $blockname);
246        $blockcount = sizeof($blocks) - 1;
247        $str = '$this->_tpldata';
248        for ($i = 0; $i < $blockcount; $i++)
249        {
250          $str .= '[\'' . $blocks[$i] . '.\']';
251          eval('$lastiteration = isset('.$str.') ? sizeof('.$str.')-1:0;');
252          $str .= '[' . $lastiteration . ']';
253        }
254        // Now we add the block that we're actually assigning to.
255        // We're adding a new iteration to this block with the given
256        // variable assignments.
257        $str .= '[\'' . $blocks[$blockcount] . '.\'][] = $vararray;';
258
259        // Now we evaluate this assignment we've built up.
260        eval($str);
261      }
262      else
263      {
264        // Top-level block. Add a new iteration to this block with the
265        // variable assignments we were given.
266        $this->_tpldata[$blockname . '.'][] = $vararray;
267      }
268
269      return true;
270    }
271
272  /**
273   * Block-level variable merge. Merge given variables to the last block
274   * iteration. This can be called several times per block iteration.
275   */
276  function merge_block_vars($blockname, $vararray)
277    {
278      $blocks = explode('.', $blockname);
279      $blockcount = count($blocks);
280      $str = '$this->_tpldata';
281      for ($i = 0; $i < $blockcount; $i++)
282      {
283        $str .= '[\'' . $blocks[$i] . '.\']';
284        eval('$lastiteration = isset('.$str.') ? sizeof('.$str.')-1:-1;');
285        if ($lastiteration==-1)
286        {
287          return false;
288        }
289        $str .= '[' . $lastiteration . ']';
290      }
291      $str = $str.'=array_merge('.$str.', $vararray);';
292      eval($str);
293      return true;
294    }
295
296  /**
297   * Root-level variable assignment. Adds to current assignments, overriding
298   * any existing variable assignment with the same name.
299   */
300  function assign_vars($vararray)
301    {
302      reset ($vararray);
303      while (list($key, $val) = each($vararray))
304      {
305        $this->_tpldata['.'][0][$key] = $val;
306      }
307
308      return true;
309    }
310
311  /**
312   * Root-level variable assignment. Adds to current assignments, overriding
313   * any existing variable assignment with the same name.
314   */
315  function assign_var($varname, $varval)
316    {
317      $this->_tpldata['.'][0][$varname] = $varval;
318      return true;
319    }
320
321  /**
322   * Root-level variable concatenation. Appends a  string to an existing
323   * variable assignment with the same name.
324   */
325  function concat_var($varname, $varval)
326    {
327      if ( isset($this->_tpldata['.'][0][$varname]) )
328      {
329        $this->_tpldata['.'][0][$varname] .= $varval;
330      }
331      else
332      {
333        $this->_tpldata['.'][0][$varname] = $varval;
334      }
335      return true;
336    }
337
338  /**
339   * Returns a root-level variable value
340   */
341  function get_var($varname, $default=null)
342    {
343      if ( isset($this->_tpldata['.'][0][$varname]) )
344      {
345        return $this->_tpldata['.'][0][$varname];
346      }
347      return $default;
348    }
349
350  /**
351   * Generates a full path+filename for the given filename, which can either
352   * be an absolute name, or a name relative to the rootdir for this
353   * Template object.
354   */
355  function make_filename($filename)
356    {
357      // Check if it's an absolute or relative path.
358      // if (substr($filename, 0, 1) != '/')
359      if (preg_match('/^[a-z_][^:]/i', $filename) )
360      {
361        $filename = $this->root.'/'.$filename;
362      }
363
364      if (!file_exists($filename))
365      {
366        die("Template->make_filename(): Error - file $filename does not exist");
367      }
368
369      return $filename;
370    }
371
372
373  /**
374   * If not already done, load the file for the given handle and populate
375   * the uncompiled_code[] hash with its code. Do not compile.
376   */
377  function loadfile($handle)
378    {
379      // If the file for this handle is already loaded and compiled, do
380      // nothing.
381      if (isset($this->uncompiled_code[$handle])
382          and !empty($this->uncompiled_code[$handle]))
383      {
384        return true;
385      }
386
387      // If we don't have a file assigned to this handle, die.
388      if (!isset($this->files[$handle]))
389      {
390        die("Template->loadfile(): No file specified for handle $handle");
391      }
392
393      $filename = $this->files[$handle];
394
395      $str = implode("", @file($filename));
396
397      if (empty($str))
398      {
399        die("Template->loadfile(): File $filename for handle $handle is empty");
400      }
401
402      $this->uncompiled_code[$handle] = trigger_event('tpl_load_file', $str, $handle, array(&$this));
403
404      return true;
405    }
406
407
408
409  /**
410   * Compiles the given string of code, and returns the result in a string.
411   *
412   * If "do_not_echo" is true, the returned code will not be directly
413   * executable, but can be used as part of a variable assignment for use in
414   * assign_code_from_handle().
415   */
416  function compile($code, $do_not_echo = false, $retvar = '')
417    {
418      // PWG specific : communication between template and $lang
419      $code = preg_replace('/\{lang:([^}]+)\}/e', "l10n('$1')", $code);
420      // PWG specific : expand themeconf.inc.php variables
421      $code = preg_replace('/\{themeconf:([^}]+)\}/e', '$this->get_themeconf(\'$1\')', $code);
422      $code = preg_replace('/\{pwg_root\}/e', "get_root_url()", $code);
423
424      // replace \ with \\ and then ' with \'.
425      $code = str_replace('\\', '\\\\', $code);
426      $code = str_replace('\'', '\\\'', $code);
427
428      // change template varrefs into PHP varrefs
429
430      // This one will handle varrefs WITH namespaces
431      $varrefs = array();
432      preg_match_all('#\{(([a-z0-9\-_]+?\.)+?)([a-z0-9\-_]+?)\}#is', $code, $varrefs);
433      $varcount = sizeof($varrefs[1]);
434      for ($i = 0; $i < $varcount; $i++)
435      {
436        $namespace = $varrefs[1][$i];
437        $varname = $varrefs[3][$i];
438        $new = $this->generate_block_varref($namespace, $varname);
439
440        $code = str_replace($varrefs[0][$i], $new, $code);
441      }
442
443      // This will handle the remaining root-level varrefs
444      $code = preg_replace('#\{([a-z0-9\-_]*?)\}#is', '\' . ( ( isset($this->_tpldata[\'.\'][0][\'\1\']) ) ? $this->_tpldata[\'.\'][0][\'\1\'] : \'\' ) . \'', $code);
445
446      // Break it up into lines.
447      $code_lines = explode("\n", $code);
448
449      $block_nesting_level = 0;
450      $block_names = array();
451      $block_names[0] = ".";
452
453      // Second: prepend echo ', append ' . "\n"; to each line.
454      $line_count = sizeof($code_lines);
455      for ($i = 0; $i < $line_count; $i++)
456      {
457        $code_lines[$i] = chop($code_lines[$i]);
458        if (preg_match('#<!-- BEGIN (.*?) -->#', $code_lines[$i], $m))
459        {
460          $n[0] = $m[0];
461          $n[1] = $m[1];
462
463          // Added: dougk_ff7-Keeps templates from bombing if begin is on
464          // the same line as end.. I think. :)
465          if ( preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $n) )
466          {
467            $block_nesting_level++;
468            $block_names[$block_nesting_level] = $m[1];
469            if ($block_nesting_level < 2)
470            {
471              // Block is not nested.
472              $code_lines[$i] = '$_' . $n[1] . '_count = ( isset($this->_tpldata[\'' . $n[1] . '.\']) ) ?  sizeof($this->_tpldata[\'' . $n[1] . '.\']) : 0;';
473              $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
474              $code_lines[$i] .= "\n" . '{';
475            }
476            else
477            {
478              // This block is nested.
479
480              // Generate a namespace string for this block.
481              $namespace = implode('.', $block_names);
482              // strip leading period from root level..
483              $namespace = substr($namespace, 2);
484              // Get a reference to the data array for this block that depends on the
485              // current indices of all parent blocks.
486              $varref = $this->generate_block_data_ref($namespace, false);
487              // Create the for loop code to iterate over this block.
488              $code_lines[$i] = '$_' . $n[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
489              $code_lines[$i] .= "\n" . 'for ($_' . $n[1] . '_i = 0; $_' . $n[1] . '_i < $_' . $n[1] . '_count; $_' . $n[1] . '_i++)';
490              $code_lines[$i] .= "\n" . '{';
491            }
492
493            // We have the end of a block.
494            unset($block_names[$block_nesting_level]);
495            $block_nesting_level--;
496            $code_lines[$i] .= '} // END ' . $n[1];
497            $m[0] = $n[0];
498            $m[1] = $n[1];
499          }
500          else
501          {
502            // We have the start of a block.
503            $block_nesting_level++;
504            $block_names[$block_nesting_level] = $m[1];
505            if ($block_nesting_level < 2)
506            {
507              // Block is not nested.
508              $code_lines[$i] = '$_' . $m[1] . '_count = ( isset($this->_tpldata[\'' . $m[1] . '.\']) ) ? sizeof($this->_tpldata[\'' . $m[1] . '.\']) : 0;';
509              $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
510              $code_lines[$i] .= "\n" . '{';
511            }
512            else
513            {
514              // This block is nested.
515
516              // Generate a namespace string for this block.
517              $namespace = implode('.', $block_names);
518              // strip leading period from root level..
519              $namespace = substr($namespace, 2);
520              // Get a reference to the data array for this block that
521              // depends on the current indices of all parent blocks.
522              $varref = $this->generate_block_data_ref($namespace, false);
523              // Create the for loop code to iterate over this block.
524              $code_lines[$i] = '$_' . $m[1] . '_count = ( isset(' . $varref . ') ) ? sizeof(' . $varref . ') : 0;';
525              $code_lines[$i] .= "\n" . 'for ($_' . $m[1] . '_i = 0; $_' . $m[1] . '_i < $_' . $m[1] . '_count; $_' . $m[1] . '_i++)';
526              $code_lines[$i] .= "\n" . '{';
527            }
528          }
529        }
530        else if (preg_match('#<!-- END (.*?) -->#', $code_lines[$i], $m))
531        {
532          // We have the end of a block.
533          unset($block_names[$block_nesting_level]);
534          $block_nesting_level--;
535          $code_lines[$i] = '} // END ' . $m[1];
536        }
537        else
538        {
539          // We have an ordinary line of code.
540          if (!$do_not_echo)
541          {
542            $code_lines[$i] = 'echo \'' . $code_lines[$i] . '\' . "\\n";';
543          }
544          else
545          {
546            $code_lines[$i] = '$' . $retvar . '.= \'' . $code_lines[$i] . '\' . "\\n";';
547          }
548        }
549      }
550
551      // Bring it back into a single string of lines of code.
552      $code = implode("\n", $code_lines);
553      return $code      ;
554
555    }
556
557
558  /**
559   * Generates a reference to the given variable inside the given (possibly
560   * nested) block namespace. This is a string of the form: '
561   * . $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['varname']
562   * . ' It's ready to be inserted into an "echo" line in one of the
563   * templates.  NOTE: expects a trailing "." on the namespace.
564   */
565  function generate_block_varref($namespace, $varname)
566    {
567      // Strip the trailing period.
568      $namespace = substr($namespace, 0, strlen($namespace) - 1);
569
570      // Get a reference to the data block for this namespace.
571      $varref = $this->generate_block_data_ref($namespace, true);
572      // Prepend the necessary code to stick this in an echo line.
573
574      // Append the variable reference.
575      $varref .= '[\'' . $varname . '\']';
576
577      $varref = '\' . ( ( isset(' . $varref . ') ) ? ' . $varref . ' : \'\' ) . \'';
578
579      return $varref;
580
581    }
582
583
584  /**
585   * Generates a reference to the array of data values for the given
586   * (possibly nested) block namespace. This is a string of the form:
587   * $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['$childN']
588   *
589   * If $include_last_iterator is true, then [$_childN_i] will be appended
590   * to the form shown above.  NOTE: does not expect a trailing "." on the
591   * blockname.
592   */
593  function generate_block_data_ref($blockname, $include_last_iterator)
594    {
595      // Get an array of the blocks involved.
596      $blocks = explode(".", $blockname);
597      $blockcount = sizeof($blocks) - 1;
598      $varref = '$this->_tpldata';
599      // Build up the string with everything but the last child.
600      for ($i = 0; $i < $blockcount; $i++)
601      {
602        $varref .= '[\'' . $blocks[$i] . '.\'][$_' . $blocks[$i] . '_i]';
603      }
604      // Add the block reference for the last child.
605      $varref .= '[\'' . $blocks[$blockcount] . '.\']';
606      // Add the iterator for the last child if requried.
607      if ($include_last_iterator)
608      {
609              $varref .= '[$_' . $blocks[$blockcount] . '_i]';
610      }
611
612      return $varref;
613    }
614
615    function get_themeconf($key)
616    {
617      return isset($this->themeconf[$key]) ? $this->themeconf[$key] : '';
618    }
619}
620
621?>
Note: See TracBrowser for help on using the repository browser.