/[pliva-si]/inc/Smarty.class.php
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /inc/Smarty.class.php

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1 by ravilov, Mon Jun 25 09:57:25 2001 UTC revision 1.2 by dpavlin, Tue Jul 3 12:37:17 2001 UTC
# Line 1  Line 1 
1  <?  <?php
2  /*  /*
3   * Project:             Smarty: the PHP compiling template engine   * Project:     Smarty: the PHP compiling template engine
4   * File:                Smarty.class.php   * File:        Smarty.class.php
5   * Author:              Monte Ohrt <monte@ispi.net>   * Author:      Monte Ohrt <monte@ispi.net>
6   *              Andrei Zmievski <andrei@ispi.net>   *              Andrei Zmievski <andrei@ispi.net>
7   *   *
8   * Version:             1.2.2   * Version:             1.3.0
9   * Copyright:           2001 ispi of Lincoln, Inc.   * Copyright:           2001 ispi of Lincoln, Inc.
10   *                                 *              
11   * This program is free software; you can redistribute it and/or   * This library is free software; you can redistribute it and/or
12   * modify it under the terms of the GNU General Public License   * modify it under the terms of the GNU Lesser General Public
13   * as published by the Free Software Foundation; either version 2   * License as published by the Free Software Foundation; either
14   * of the License, or (at your option) any later version.   * version 2.1 of the License, or (at your option) any later version.
15   *   *
16   * This program is distributed in the hope that it will be useful,   * This library is distributed in the hope that it will be useful,
17   * but WITHOUT ANY WARRANTY; without even the implied warranty of   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19   * GNU General Public License for more details.   * Lesser General Public License for more details.
20   *   *
21   * You should have received a copy of the GNU General Public License   * You should have received a copy of the GNU Lesser General Public
22   * along with this program; if not, write to the Free Software   * License along with this library; if not, write to the Free Software
23   * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24   *   *
25   * You may contact the authors of Smarty by e-mail at:   * You may contact the authors of Smarty by e-mail at:
26   * monte@ispi.net   * monte@ispi.net
# Line 37  Line 37 
37   *   *
38   */   */
39    
40  require("Smarty.addons.php");  require('Smarty.addons.php');
41  require("Smarty.local.php");  require("Smarty.local.php");
42    
43    define("SMARTY_PHP_PASSTHRU",0);
44    define("SMARTY_PHP_QUOTE",1);
45    define("SMARTY_PHP_REMOVE",2);
46    define("SMARTY_PHP_ALLOW",3);
47    
48  class Smarty  class Smarty
49  {  {
50    
51          // public vars      // public vars
52          var     $compile_check  =       true;   // whether to check for compiling step or not:      var $template_dir    =  './templates';     // name of directory for templates  
53                                                                          // This is generally set to false once the      var $compile_dir     =  './templates_c';   // name of directory for compiled templates
54                                                                          // application is entered into production and      var $config_dir      =  './configs';       // directory where config files are located
55                                                                          // initially compiled. Leave set to true  
56                                                                          // during development.      var $global_assign   =  array('SCRIPT_NAME'); // variables from the GLOBALS array
57                                                      // that are implicitly assigned
58          var $template_dir                       =       "./templates"; // name of directory for templates                                                          // to all templates  
59          var $compile_dir                        =       "./templates_c"; // name of directory for compiled templates          var $compile_check   =  true;       // whether to check for compiling step or not:
60                                                    // This is generally set to false once the
61                                                    // application is entered into production and
62          var $tpl_file_ext                       =       ".tpl"; // template file extentions                                          // initially compiled. Leave set to true
63                                                    // during development. true/false default true.
64          var $allow_php                          =       false;          // whether or not to allow embedded php  
65                                                                                                  // in the templates. By default, php tags      var $force_compile   =  false;      // force templates to compile every time.
66                                                                                                  // are escaped.                                          // if cache file exists, it will
67          var $left_delimiter                     =       "{";            // template tag delimiters.                                          // override compile_check and force_compile.
68          var $right_delimiter            =       "}";                                          // true/false. default false.
69        var $caching         =  false;      // whether to use caching or not. true/false
70          var $config_dir                         =       "./configs";    // directory where config files are located      var $cache_dir       =  './cache';  // name of directory for template cache
71        var $cache_lifetime  =  3600;       // number of seconds cached content will persist.
72          var $custom_funcs                       =       array(  'html_options'          => 'smarty_func_html_options',                                          // 0 = never expires. default is one hour (3600)
73                                                                                          'html_select_date'      => 'smarty_func_html_select_date',  
74                                                                                  //----- local      var $tpl_file_ext    =  '.tpl';     // template file extention
75        
76        var $php_handling    =  SMARTY_PHP_PASSTHRU; // how smarty handles php tags
77                                            // possible values:
78                                            // SMARTY_PHP_PASSTHRU -> echo tags as is
79                                            // SMARTY_PHP_QUOTE    -> escape tags as entities
80                                            // SMARTY_PHP_REMOVE   -> remove php tags
81                                            // SMARTY_PHP_ALLOW    -> execute php tags
82                                            // default: SMARTY_PHP_PASSTHRU
83    
84        var $left_delimiter  =  '{';        // template tag delimiters.
85        var $right_delimiter =  '}';
86    
87    
88        var $custom_funcs    =  array(  'html_options'      => 'smarty_func_html_options',
89                                        'html_select_date'  => 'smarty_func_html_select_date',
90                                        'header'            => 'smarty_func_header',
91    
92    //----- local custom_funcs
93          'img'           => 'smarty_func_img',          'img'           => 'smarty_func_img',
94          'html_checkboxes' => 'smarty_func_html_checkboxes',          'html_checkboxes' => 'smarty_func_html_checkboxes',
95          'input'         => 'smarty_func_input',          'input'         => 'smarty_func_input',
96          'rinput'        => 'smarty_func_rinput',          'rinput'        => 'smarty_func_rinput',
97                                                                                   );  
98                                             );
99          var $custom_mods                        =       array(  'lower'                 => 'strtolower',      
100                                                                                          'upper'                 => 'strtoupper',      var $custom_mods     =  array(  'lower'         => 'strtolower',
101                                                                                          'capitalize'    => 'ucwords',                                      'upper'         => 'strtoupper',
102                                                                                          'escape'                => 'smarty_mod_escape',                                      'capitalize'    => 'ucwords',
103                                                                                          'truncate'              => 'smarty_mod_truncate',                                      'escape'        => 'smarty_mod_escape',
104                                                                                          'spacify'               => 'smarty_mod_spacify',                                      'truncate'      => 'smarty_mod_truncate',
105                                                                                          'date_format'   => 'smarty_mod_date_format',                                      'spacify'       => 'smarty_mod_spacify',
106                                                                                          'string_format' => 'smarty_mod_string_format',                                      'date_format'   => 'smarty_mod_date_format',
107                                                                                          'replace'               => 'smarty_mod_replace',                                      'string_format' => 'smarty_mod_string_format',
108                                                                                          'strip_tags'    => 'smarty_mod_strip_tags',                                      'replace'       => 'smarty_mod_replace',
109                                                                                          'default'               => 'smarty_mod_default',                                      'strip_tags'    => 'smarty_mod_strip_tags',
110                                                                                  //----- local                                      'default'       => 'smarty_mod_default',
111                                                                                          'filesize' => 'smarty_mod_filesize',  
112                                                                                   );  //----- local custom_mods
113          var $global_assign                      =       array(  'SCRIPT_NAME'          'filesize' => 'smarty_mod_filesize',
114                                                                                   );  
115                                             );
116          // internal vars      
117          var $_error_msg                         =       false;          // error messages      // internal vars
118          var $_tpl_vars                          =       array();      var $_error_msg             =   false;      // error messages. true/false
119          var $_sectionelse_stack         =       array();        // keeps track of whether section had 'else' part      var $_tpl_vars              =   array();
120          var $_literal_blocks            =       array();        // keeps literal template blocks      var $_sectionelse_stack     =   array();    // keeps track of whether section had 'else' part
121          var $_current_file                      =       null;           // the current template being compiled      var $_literal_blocks        =   array();    // keeps literal template blocks
122          var $_current_line_no           =       1;                      // line number for error messages      var $_current_file          =   null;       // the current template being compiled
123        var $_current_line_no       =   1;          // line number for error messages
124                var $_smarty_md5            =   'f8d698aea36fcbead2b9d5359ffca76f'; // md5 checksum of the string 'Smarty'
125  /*======================================================================*\  
126          Function: Smarty      
127          Purpose:  Constructor  /*======================================================================*\
128  \*======================================================================*/      Function: Smarty
129          function Smarty()      Purpose:  Constructor
130          {  \*======================================================================*/
131                  foreach ($this->global_assign as $var_name)      function Smarty()
132                          $this->assign($var_name, $GLOBALS[$var_name]);      {
133          }          foreach ($this->global_assign as $var_name)
134                $this->assign($var_name, $GLOBALS[$var_name]);
135        }
136  /*======================================================================*\  
137          Function:       assign()  
138          Purpose:        assigns values to template variables  /*======================================================================*\
139  \*======================================================================*/      Function:   assign()
140        Purpose:    assigns values to template variables
141          function assign($tpl_var, $value = NULL)  \*======================================================================*/
142          {  
143                  if (is_array($tpl_var)){      function assign($tpl_var, $value = NULL)
144                          foreach ($tpl_var as $key => $val) {      {
145                                  if (!empty($key))          if (is_array($tpl_var)){
146                                          $this->_tpl_vars[$key] = $val;              foreach ($tpl_var as $key => $val) {
147                          }                  if (!empty($key))
148                  } else {                      $this->_tpl_vars[$key] = $val;
149                          if (!empty($tpl_var) && isset($value))              }
150                                  $this->_tpl_vars[$tpl_var] = $value;          } else {
151                  }              if (!empty($tpl_var) && isset($value))
152          }                  $this->_tpl_vars[$tpl_var] = $value;
153            }
154                }
155  /*======================================================================*\  
156          Function: append      
157          Purpose:  appens values to template variables  /*======================================================================*\
158  \*======================================================================*/      Function: append
159          function append($tpl_var, $value = NULL)      Purpose:  appens values to template variables
160          {  \*======================================================================*/
161                  if (is_array($tpl_var)) {      function append($tpl_var, $value = NULL)
162                          foreach ($tpl_var as $key => $val) {      {
163                                  if (!empty($key)) {          if (is_array($tpl_var)) {
164                                          if (!is_array($this->_tpl_vars[$key]))              foreach ($tpl_var as $key => $val) {
165                                                  settype($this->_tpl_vars[$key], 'array');                  if (!empty($key)) {
166                                          $this->_tpl_vars[$key][] = $val;                      if (!is_array($this->_tpl_vars[$key]))
167                                  }                          settype($this->_tpl_vars[$key], 'array');
168                          }                      $this->_tpl_vars[$key][] = $val;
169                  } else {                  }
170                          if (!empty($tpl_var) && isset($value)) {              }
171                                  if (!is_array($this->_tpl_vars[$tpl_var]))          } else {
172                                          settype($this->_tpl_vars[$tpl_var], 'array');              if (!empty($tpl_var) && isset($value)) {
173                                  $this->_tpl_vars[$tpl_var][] = $value;                  if (!is_array($this->_tpl_vars[$tpl_var]))
174                          }                      settype($this->_tpl_vars[$tpl_var], 'array');
175                  }                  $this->_tpl_vars[$tpl_var][] = $value;
176          }              }
177            }
178        }
179  /*======================================================================*\  
180          Function:       clear_assign()  
181          Purpose:        clear the given assigned template variable.  /*======================================================================*\
182  \*======================================================================*/      Function:   clear_assign()
183        Purpose:    clear the given assigned template variable.
184          function clear_assign($tpl_var)  \*======================================================================*/
185          {  
186                  unset($this->_tpl_vars[$tpl_var]);      function clear_assign($tpl_var)
187          }      {
188            if(is_array($tpl_var))
189  /*======================================================================*\              foreach($tpl_var as $curr_var)
190          Function:       clear_all_assign()                  unset($this->_tpl_vars[$curr_var]);
191          Purpose:        clear all the assigned template variables.          else
192  \*======================================================================*/              unset($this->_tpl_vars[$tpl_var]);
193        }
194          function clear_all_assign()  
195          {      
196                  $this->_tpl_vars = array();  /*======================================================================*\
197          }      Function: register_function
198        Purpose:  Registers custom function to be used in templates
199    \*======================================================================*/
200  /*======================================================================*\      function register_function($function, $function_impl)
201          Function: get_template_vars      {
202          Purpose:  Returns an array containing template variables          $this->custom_funcs[$function] = $function_impl;
203  \*======================================================================*/      }
204          function &get_template_vars()  
205          {      
206                  return $this->_tpl_vars;  /*======================================================================*\
207          }      Function: register_modifier
208        Purpose:  Registers modifier to be used in templates
209    \*======================================================================*/
210  /*======================================================================*\      function register_modifier($modifier, $modifier_impl)
211          Function:       display()      {
212          Purpose:        executes & displays the template results          $this->custom_mods[$modifier] = $modifier_impl;
213  \*======================================================================*/      }
214    
215          function display($tpl_file)      
216          {  /*======================================================================*\
217                  // compile files      Function:   clear_cache()
218                  $this->_compile($this->template_dir);      Purpose:    clear cached content for the given template and cache id
219                  //assemble compile directory path to file  \*======================================================================*/
220                  $_compile_file = $this->compile_dir.'/'.$tpl_file.'.php';  
221                        function clear_cache($tpl_file, $cache_id = null)
222                  extract($this->_tpl_vars);                    {
223                  include($_compile_file);          $cache_tpl_md5 = md5(realpath($this->template_dir.'/'.$tpl_file));
224          }                $cache_dir = $this->cache_dir.'/'.$cache_tpl_md5;
225                            
226  /*======================================================================*\          if (!is_dir($cache_dir))
227          Function:       fetch()              return false;
228          Purpose:        executes & returns the template results  
229  \*======================================================================*/          if (isset($cache_id)) {
230                $cache_id_md5 = md5($cache_id);
231          function fetch($tpl_file)              $cache_id_dir = substr($cache_id_md5, 0, 2);
232          {              $cache_file = "$cache_dir/$cache_id_dir/{$cache_tpl_md5}_$cache_id_md5.cache";
233                  ob_start();              return (bool)(is_file($cache_file) && unlink($cache_file));
234                  $this->display($tpl_file);          } else
235                  $results = ob_get_contents();              return $this->_clear_tpl_cache_dir($cache_tpl_md5);
236                  ob_end_clean();      }
237                  return $results;      
238          }      
239    /*======================================================================*\
240  /*======================================================================*\      Function:   clear_all_cache()
241          Function:       compile()      Purpose:    clear the entire contents of cache (all templates)
242          Purpose:        called to compile the templates  \*======================================================================*/
243  \*======================================================================*/  
244        function clear_all_cache()
245          function _compile($tpl_dir)      {
246          {          if (!is_dir($this->cache_dir))
247                  if($this->compile_check)              return false;
248                  {  
249                          if($this->_traverse_files($tpl_dir, 0))          $dir_handle = opendir($this->cache_dir);
250                                  return true;          while ($curr_dir = readdir($dir_handle)) {
251                          else              if ($curr_dir == '.' || $curr_dir == '..' ||
252                                  return false;                  !is_dir($this->cache_dir.'/'.$curr_dir))
253                  }                  continue;
254                  else  
255                          return false;              $this->_clear_tpl_cache_dir($curr_dir);
256          }          }
257            closedir($dir_handle);
258  /*======================================================================*\  
259          Function:       _traverse_files()          return true;
260          Purpose:        traverse the template files & process each one      }
261  \*======================================================================*/  
262    
263          function _traverse_files($tpl_dir, $depth)  /*======================================================================*\
264          {      Function:   is_cached()
265                  if(is_dir($tpl_dir)) {      Purpose:    test to see if valid cache exists for this template
266                          if($tpl_dir)  \*======================================================================*/
267                                  $dir_handle = opendir($tpl_dir);  
268        function is_cached($tpl_file, $cache_id = null)
269                          while($curr_file = readdir($dir_handle)) {      {
270                                  if ($curr_file == '.' || $curr_file == '..')          if (!$this->caching)
271                                          continue;              return false;
272    
273                                  $filepath = $tpl_dir."/".$curr_file;          // cache name = template path + cache_id
274                                  if(is_readable($filepath)) {          $cache_tpl_md5 = md5(realpath($this->template_dir.'/'.$tpl_file));
275                                          if(is_file($filepath) && preg_match('!' . preg_quote($this->tpl_file_ext, '!') . '$!', $curr_file)) {          $cache_id_md5 = md5($cache_id);
276                                                  if(!$this->_process_file($filepath))          $cache_id_dir = substr($cache_id_md5, 0, 2);
277                                                          return false;          $cache_file = $this->cache_dir."/$cache_tpl_md5/$cache_id_dir/{$cache_tpl_md5}_$cache_id_md5.cache";
278                                          } else if(is_dir($filepath)) {  
279                                                  if(!$this->_traverse_files($filepath, $depth + 1))          if (file_exists($cache_file) &&
280                                                          return false;              ($this->cache_lifetime == 0 ||
281                                          } else {               (time() - filemtime($cache_file) <= $this->cache_lifetime)))
282                                                  // invalid file type, skipping              return true;
283                                                  $this->_set_error_msg("Invalid filetype for $filepath, skipping");          else
284                                                  continue;              return false;
285                                          }          
286                                  }      }
287                          }      
288                  } else {          
289                          $this->_set_error_msg("Directory \"$tpl_dir\" does not exist or is not a directory.");  /*======================================================================*\
290                          return false;      Function:   clear_all_assign()
291                  }      Purpose:    clear all the assigned template variables.
292    \*======================================================================*/
293                  return true;  
294          }      function clear_all_assign()
295        {
296  /*======================================================================*\          $this->_tpl_vars = array();
297          Function:       _process_file()      }
298          Input:          test template files for modifications  
299                                  and execute the compilation for each  
300                                  one requiring it.  /*======================================================================*\
301  \*======================================================================*/      Function: get_template_vars
302        Purpose:  Returns an array containing template variables
303          function _process_file($filepath)  \*======================================================================*/
304          {      function &get_template_vars()
305                  if(preg_match("/^(.+)\/([^\/]+)$/", $filepath, $match)) {      {
306                          $tpl_file_dir = $match[1];                                return $this->_tpl_vars;
307                          $tpl_file_name = $match[2] . ".php";      }
308    
309                          $compile_dir = preg_replace('!^' . preg_quote($this->template_dir, '!') . '!',  
310                                                                                  $this->compile_dir, $match[1]);  /*======================================================================*\
311        Function:   display()
312                          //create directory if none exists      Purpose:    executes & displays the template results
313                          if(!file_exists($compile_dir)) {  \*======================================================================*/
314                                  $compile_dir_parts = preg_split('!/+!', $compile_dir);  
315                                  $new_dir = "";      function display($tpl_file, $cache_id = null)
316                                  foreach ($compile_dir_parts as $dir_part) {      {
317                                          $new_dir .= $dir_part."/";          $this->fetch($tpl_file, $cache_id, true);
318                                          if (!file_exists($new_dir) && !mkdir($new_dir, 0755)) {      }  
319                                                  $this->_set_error_msg("problem creating directory \"$compile_dir\"");          
320                                                  return false;                            /*======================================================================*\
321                                          }      Function:   fetch()
322                                  }      Purpose:    executes & returns or displays the template results
323                          }  \*======================================================================*/
324    
325                          // compile the template file if none exists or has been modified      function fetch($tpl_file, $cache_id = null, $display = false)
326                          if (!file_exists($compile_dir."/".$tpl_file_name) ||      {
327                                  ($this->_modified_file($filepath, $compile_dir."/".$tpl_file_name))) {          global $HTTP_SERVER_VARS;
328                                  if (!$this->_compile_file($filepath, $compile_dir."/".$tpl_file_name))  
329                                          return false;                                    if ($this->caching) {
330                          } else {              // cache name = template path + cache_id
331                                  // no compilation needed              $cache_tpl_md5 = md5(realpath($this->template_dir.'/'.$tpl_file));
332                                  return true;              $cache_id_md5 = md5($cache_id);
333                          }              $cache_id_dir = substr($cache_id_md5, 0, 2);
334                  } else {              $cache_file = $this->cache_dir."/$cache_tpl_md5/$cache_id_dir/{$cache_tpl_md5}_$cache_id_md5.cache";
335                          $this->_set_error_msg("problem matching \"$filepath.\"");              
336                          return false;              if (file_exists($cache_file) &&
337                  }                  ($this->cache_lifetime == 0 ||
338                     (time() - filemtime($cache_file) <= $this->cache_lifetime))) {
339                  return true;                  $results = $this->_read_file($cache_file);
340          }                  $results = $this->_process_cached_inserts($results);
341                    if ($display) {
342  /*======================================================================*\                      echo $results;
343          Function:       _modified_file()                      return;
344          Input:          return comparison of modification times of files                  } else
345  \*======================================================================*/                      return $results;
346                }
347          function _modified_file($filepath, $compilepath)          }
348          {  
349                  if(filemtime($filepath) >= filemtime($compilepath))          // compile files
350                          return true;          $this->_compile($this->template_dir);
351                  return false;          //assemble compile directory path to file
352          }          $_compile_file = $this->compile_dir."/".$tpl_file.".php";
353    
354  /*======================================================================*\          extract($this->_tpl_vars);
355          Function:       _compile_file()  
356          Input:          compile a template file          // if we just need to display the results, don't perform output
357  \*======================================================================*/          // buffering - for speed
358            if ($display && !$this->caching)
359          function _compile_file($filepath, $compilepath)              include($_compile_file);
360          {          else {
361                  if (!($template_contents = $this->_read_file($filepath)))              ob_start();
362                          return false;              include($_compile_file);
363                $results = ob_get_contents();
364                  $this->_current_file = str_replace($this->template_dir . "/", "", $filepath);              ob_end_clean();
365                  $this->_current_line_no = 1;          }
366                  $ldq = preg_quote($this->left_delimiter, '!');  
367                  $rdq = preg_quote($this->right_delimiter, '!');          if($this->caching) {
368                $this->_write_file($cache_file, $results, true);
369                  /* Pull out the literal blocks. */              $results = $this->_process_cached_inserts($results);
370                  preg_match_all("!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s", $template_contents, $match);          }
371                  $this->_literal_blocks = $match[1];  
372                  $template_contents = preg_replace("!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s",          if ($display) {
373                                                                                    '{literal}', $template_contents);              echo $results;
374                return;
375                  /* Gather all template tags. */          } else
376                  preg_match_all("!{$ldq}\s*(.*?)\s*{$rdq}!s", $template_contents, $match);              return $results;
377                  $template_tags = $match[1];      }  
378                  /* Split content by template tags to obtain non-template content. */      
379                  $text_blocks = preg_split("!{$ldq}.*?{$rdq}!s", $template_contents);  /*======================================================================*\
380                  if(!$this->allow_php) {      Function:   compile()
381                          /* Escape php tags. */      Purpose:    called to compile the templates
382                          $text_blocks = preg_replace('!<\?([^?]*?)\?>!', '&lt;?$1?&gt;', $text_blocks);  \*======================================================================*/
383                  }  
384        function _compile($tpl_dir)
385                  /* Compile the template tags into PHP code. */      {
386                  $compiled_tags = array();          if($this->compile_check || $this->force_compile)
387                  for ($i = 0; $i < count($template_tags); $i++) {          {
388                          $this->_current_line_no += substr_count($text_blocks[$i], "\n");              if($this->_traverse_files($tpl_dir, 0))
389                          $compiled_tags[] = $this->_compile_tag($template_tags[$i]);                  return true;
390                          $this->_current_line_no += substr_count($template_tags[$i], "\n");              else
391                  }                  return false;
392            } else
393                  $compiled_contents = "";              return false;
394                        }  
395                  /* Interleave the compiled contents and text blocks to get the final result. */      
396                  for ($i = 0; $i < count($compiled_tags); $i++) {  /*======================================================================*\
397                          $compiled_contents .= $text_blocks[$i].$compiled_tags[$i];      Function:   _traverse_files()
398                  }      Purpose:    traverse the template files & process each one
399                  $compiled_contents .= $text_blocks[$i];  \*======================================================================*/
400                    
401                  /* Reformat data between 'strip' and '/strip' tags, removing spaces, tabs and newlines. */      function _traverse_files($tpl_dir, $depth)
402                  if (preg_match_all("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s", $compiled_contents, $match)) {      {
403                          $strip_tags = $match[0];          $retval = true;
404                          $strip_tags_modified = preg_replace("!{$ldq}/?strip{$rdq}|[\t ]+$|^[\t ]+!m", '', $strip_tags);  
405                          $strip_tags_modified = preg_replace('![\r\n]+!m', '', $strip_tags_modified);          if (is_dir($tpl_dir)) {
406                          for ($i = 0; $i < count($strip_tags); $i++)              $dir_handle = opendir($tpl_dir);
407                                  $compiled_contents = preg_replace("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s",              while ($curr_file = readdir($dir_handle)) {
408                                                                                                    $strip_tags_modified[$i], $compiled_contents, 1);                  if ($curr_file == '.' || $curr_file == '..')
409                  }                      continue;
410    
411                  if(!$this->_write_file($compilepath, $compiled_contents))                  $filepath = $tpl_dir.'/'.$curr_file;
412                          return false;                  if (is_readable($filepath)) {
413                        if (is_file($filepath) && substr($curr_file, -strlen($this->tpl_file_ext)) == $this->tpl_file_ext) {
414                  return true;                          if (!$this->_process_file($filepath)) {
415          }                              $retval = false;
416                                break;
417          function _compile_tag($template_tag)                          }
418          {                      } else if (is_dir($filepath)) {
419                  /* Matched comment. */                          if (!$this->_traverse_files($filepath, $depth + 1)) {
420                  if ($template_tag{0} == '*' && $template_tag{strlen($template_tag)-1} == '*')                              $retval = false;
421                          return "";                              break;
422                            }
423                  /* Split tag into two parts: command and the arguments. */                      } else {
424                  preg_match('/^(                          // invalid file type, skipping
425                                             (?:"[^"\\\\]*(?:\\\\.[^"\\\\]*)*" | \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' | (?>[^"\'\s]+))+                          $this->_set_error_msg("Invalid filetype for $filepath, skipping");
426                                            )                          continue;
427                                        (?:\s+(.*))?                      }
428                                          /xs', $template_tag, $match);                  }
429                  list(, $tag_command, $tag_args) = $match;              }
430    
431                  /* If the tag name matches a variable or section property definition,              closedir($dir_handle);
432                     we simply process it. */              return $retval;
433                  if (preg_match('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:[^|]+)?)*$!', $tag_command) ||      // if a variable          } else {
434                          preg_match('!^#(\w+)#(?>\|@?\w+(:[^|]+)?)*$!', $tag_command)            ||  // or a configuration variable              $this->_set_error_msg("Directory \"$tpl_dir\" does not exist or is not a directory.");
435                          preg_match('!^%\w+\.\w+%(?>\|@?\w+(:[^|]+)?)*$!', $tag_command)) {    // or a section property              return false;
436                          settype($tag_command, 'array');          }
437                          $this->_parse_vars_props($tag_command);      }
438                          return "<?php print $tag_command[0]; ?>";  
439                  }  /*======================================================================*\
440        Function:   _process_file()
441                  switch ($tag_command) {      Input:      test template files for modifications
442                          case 'include':                  and execute the compilation for each
443                                  return $this->_compile_include_tag($tag_args);                  one requiring it.
444    \*======================================================================*/
445                          case 'if':  
446                                  return $this->_compile_if_tag($tag_args);      function _process_file($filepath)
447        {
448                          case 'else':          if(preg_match("/^(.+)\/([^\/]+)$/", $filepath, $match)) {
449                                  return '<?php else: ?>';              $tpl_file_dir = $match[1];          
450                $tpl_file_name = $match[2] . '.php';
451                          case 'elseif':  
452                                  return $this->_compile_if_tag($tag_args, true);              $compile_dir = preg_replace('!^' . preg_quote($this->template_dir, '!') . '!',
453                                            $this->compile_dir, $match[1]);
454                          case '/if':  
455                                  return '<?php endif; ?>';              //create directory if none exists
456                $this->_create_dir_structure($compile_dir);
457                          case 'ldelim':  
458                                  return $this->left_delimiter;              // compile the template file if none exists or has been modified or recompile is forced
459                if ($this->force_compile || !file_exists($compile_dir."/".$tpl_file_name) ||
460                          case 'rdelim':                  ($this->_modified_file($filepath, $compile_dir."/".$tpl_file_name))) {
461                                  return $this->right_delimiter;                  if (!$this->_compile_file($filepath, $compile_dir."/".$tpl_file_name))
462                        return false;
463                          case 'section':              } else {
464                                  array_push($this->_sectionelse_stack, false);                  // no compilation needed
465                                  return $this->_compile_section_start($tag_args);                  return true;
466                }
467                          case 'sectionelse':          } else {
468                                  $this->_sectionelse_stack[count($this->_sectionelse_stack)-1] = true;              $this->_set_error_msg("problem matching \"$filepath.\"");
469                                  return "<?php endfor; else: ?>";              return false;
470            }
471                          case '/section':  
472                                  if (array_pop($this->_sectionelse_stack))          return true;
473                                          return "<?php endif; ?>";      }
474                                  else  
475                                          return "<?php endfor; endif; ?>";  /*======================================================================*\
476        Function: _create_dir_structure
477                          case 'config_load':      Purpose:  create full directory structure
478                                  return $this->_compile_config_load_tag($tag_args);  \*======================================================================*/
479        function _create_dir_structure($dir)
480                          case 'strip':      {
481                          case '/strip':          if (!file_exists($dir)) {
482                                  return $this->left_delimiter.$tag_command.$this->right_delimiter;              $dir_parts = preg_split('!/+!', $dir, -1, PREG_SPLIT_NO_EMPTY);
483                $new_dir = ($dir{0} == '/') ? '/' : '';
484                          case 'literal':              foreach ($dir_parts as $dir_part) {
485                                  list (,$literal_block) = each($this->_literal_blocks);                  $new_dir .= $dir_part;
486                                  $this->_current_line_no += substr_count($literal_block, "\n");                  if (!file_exists($new_dir) && !mkdir($new_dir, 0755)) {
487                                  return $literal_block;                      $this->_set_error_msg("problem creating directory \"$dir\"");
488                        return false;              
489                          case 'insert':                  }
490                                  return $this->_compile_insert_tag($tag_args);                  $new_dir .= '/';
491                }
492                          default:          }
493                                  if (isset($this->custom_funcs[$tag_command])) {      }
494                                          return $this->_compile_custom_tag($tag_command, $tag_args);  
495                                  } else {  /*======================================================================*\
496                                          $this->_syntax_error("unknown tag - '$tag_command'", E_USER_WARNING);      Function:   _modified_file()
497                                          return "";      Input:      return comparison of modification times of files
498                                  }  \*======================================================================*/
499                  }  
500          }      function _modified_file($filepath, $compilepath)
501        {
502            if (filemtime($filepath) >= filemtime($compilepath))
503          function _compile_custom_tag($tag_command, $tag_args)              return true;
504          {          return false;
505                  $attrs = $this->_parse_attrs($tag_args);      }
506                  $function = $this->custom_funcs[$tag_command];  
507                  foreach ($attrs as $arg_name => $arg_value) {  /*======================================================================*\
508                          if (is_bool($arg_value))      Function:   _compile_file()
509                                  $arg_value = $arg_value ? 'true' : 'false';      Input:      compile a template file
510                          $arg_list[] = "'$arg_name' => $arg_value";  \*======================================================================*/
511                  }  
512        function _compile_file($filepath, $compilepath)
513                  return "<?php $function(array(".implode(',', (array)$arg_list).")); ?>";      {
514          }          if (!($template_contents = $this->_read_file($filepath)))
515                return false;
516    
517          function _compile_insert_tag($tag_args)          $this->_current_file = str_replace($this->template_dir . '/', '', $filepath);
518          {          $this->_current_line_no = 1;
519                  $attrs = $this->_parse_attrs($tag_args);          $ldq = preg_quote($this->left_delimiter, '!');
520                  $name = substr($attrs['name'], 1, -1);          $rdq = preg_quote($this->right_delimiter, '!');
521    
522                  if (empty($name)) {          /* Pull out the literal blocks. */
523                          $this->_syntax_error("missing insert name");          preg_match_all("!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s", $template_contents, $match);
524                  }          $this->_literal_blocks = $match[1];
525            $template_contents = preg_replace("!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s",
526                  foreach ($attrs as $arg_name => $arg_value) {                                            '{literal}', $template_contents);
527                          if ($arg_name == 'name') continue;  
528                          if (is_bool($arg_value))          /* Gather all template tags. */
529                                  $arg_value = $arg_value ? 'true' : 'false';          preg_match_all("!{$ldq}\s*(.*?)\s*{$rdq}!s", $template_contents, $match);
530                          $arg_list[] = "'$arg_name' => $arg_value";          $template_tags = $match[1];
531                  }          /* Split content by template tags to obtain non-template content. */
532            $text_blocks = preg_split("!{$ldq}.*?{$rdq}!s", $template_contents);
533                  return "<?php print insert_$name(array(".implode(',', (array)$arg_list).")); ?>";  
534          }          /* TODO: speed up the following with preg_replace and /F once we require that version of PHP */
535            
536            /* loop through text blocks */
537          function _compile_config_load_tag($tag_args)          for ($curr_tb = 0; $curr_tb <= count($text_blocks); $curr_tb++) {
538          {              /* match anything within <? ?> */
539                  $attrs = $this->_parse_attrs($tag_args);              if (preg_match_all('!(<\?[^?]*?\?>|<script\s+language\s*=\s*[\"\']?php[\"\']?\s*>)!is', $text_blocks[$curr_tb], $sp_match)) {
540                    /* found at least one match, loop through each one */
541                  if (empty($attrs['file'])) {                  for ($curr_sp = 0; $curr_sp < count($sp_match[0]); $curr_sp++) {
542                          $this->_syntax_error("missing 'file' attribute in config_load tag");                      if (preg_match('!^(<\?(php\s|\s|=\s)|<script\s*language\s*=\s*[\"\']?php[\"\']?\s*>)!is', $sp_match[0][$curr_sp])) {
543                  }                          /* php tag */
544                            if ($this->php_handling == SMARTY_PHP_PASSTHRU) {
545                  $output  = "<?php if (!class_exists('Config_File'))\n" .                              /* echo php contents */
546                                     "    include_once 'Config_File.class.php';\n" .                              $text_blocks[$curr_tb] = str_replace($sp_match[0][$curr_sp], '<?php echo \''.str_replace("'", "\'", $sp_match[0][$curr_sp]).'\'; ?>'."\n", $text_blocks[$curr_tb]);
547                             "if (!is_object(\$_conf_obj) || get_class(\$_conf_obj) != 'config_file') {\n" .                         } else if ($this->php_handling == SMARTY_PHP_QUOTE) {
548                                     "    \$_conf_obj  = new Config_File('".$this->config_dir."');\n" .                              /* quote php tags */
549                             "}\n" .                              $text_blocks[$curr_tb] = str_replace($sp_match[0][$curr_sp], htmlspecialchars($sp_match[0][$curr_sp]), $text_blocks[$curr_tb]);
550                                     "\$_config = array_merge((array)\$_config, \$_conf_obj->get(".$attrs['file']."));\n";                          } else if ($this->php_handling == SMARTY_PHP_REMOVE) {
551                                /* remove php tags */
552                  if (!empty($attrs['section']))                              if (substr($sp_match[0][$curr_sp], 0, 2) == '<?')
553                          $output .= '$_config = array_merge((array)$_config, $_conf_obj->get('.$attrs['file'].', '.$attrs['section'].')); ';                                  $text_blocks[$curr_tb] = str_replace($sp_match[0][$curr_sp], '', $text_blocks[$curr_tb]);
554                                else
555                  $output .= '?>';                                  /* attempt to remove everything between <script ...> and </script> */
556                                    $text_blocks[$curr_tb] = preg_replace('!'.preg_quote($sp_match[0][$curr_sp], '!').'.*?</script\s*>!is', '', $text_blocks[$curr_tb]);
557                  return $output;                          }
558          }                      } else
559                            /* echo the non-php tags */
560                            $text_blocks[$curr_tb] = str_replace($sp_match[0][$curr_sp], '<?php echo \''.str_replace("'", "\'", $sp_match[0][$curr_sp]).'\'; ?>'."\n", $text_blocks[$curr_tb]);
561          function _compile_include_tag($tag_args)                  }
562          {              }
563                  $attrs = $this->_parse_attrs($tag_args);          }
564                          
565                  if (empty($attrs['file'])) {          /* Compile the template tags into PHP code. */
566                          $this->_syntax_error("missing 'file' attribute in include tag");          $compiled_tags = array();
567                  } else          for ($i = 0; $i < count($template_tags); $i++) {
568                          $attrs['file'] = $this->_dequote($attrs['file']);              $this->_current_line_no += substr_count($text_blocks[$i], "\n");
569                $compiled_tags[] = $this->_compile_tag($template_tags[$i]);
570                  if (count($attrs) > 1) {              $this->_current_line_no += substr_count($template_tags[$i], "\n");
571                          $include_func_name = uniqid("_include_");          }
572                          $include_file_name = $this->compile_dir.'/'.$attrs['file'];  
573            $compiled_contents = '';
574                          foreach ($attrs as $arg_name => $arg_value) {          
575                                  if ($arg_name == 'file') continue;          /* Interleave the compiled contents and text blocks to get the final result. */
576                                  if (is_bool($arg_value))          for ($i = 0; $i < count($compiled_tags); $i++) {
577                                          $arg_value = $arg_value ? 'true' : 'false';              $compiled_contents .= $text_blocks[$i].$compiled_tags[$i];
578                                  $arg_list[] = "'$arg_name' => $arg_value";          }
579                          }          $compiled_contents .= $text_blocks[$i];
580            
581                          return  "<?php " .          /* Reformat data between 'strip' and '/strip' tags, removing spaces, tabs and newlines. */
582                                          "function $include_func_name(\$file_name, \$def_vars, \$include_vars)\n" .          if (preg_match_all("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s", $compiled_contents, $match)) {
583                                          "{\n" .              $strip_tags = $match[0];
584                                          "       extract(\$def_vars);\n" .              $strip_tags_modified = preg_replace("!{$ldq}/?strip{$rdq}|[\t ]+$|^[\t ]+!m", '', $strip_tags);
585                                          "       extract(\$include_vars);\n" .              $strip_tags_modified = preg_replace('![\r\n]+!m', '', $strip_tags_modified);
586                                          "       include \"\$file_name.php\";\n" .              for ($i = 0; $i < count($strip_tags); $i++)
587                                          "}\n" .                  $compiled_contents = preg_replace("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s",
588                                          "$include_func_name(\"$include_file_name\", get_defined_vars(), array(".implode(',', (array)$arg_list)."));\n?>\n";                                                    $strip_tags_modified[$i], $compiled_contents, 1);
589                  } else          }
590                           return '<?php include "'.$this->compile_dir.'/'.$attrs['file'].'.php"; ?>';  
591          }          if(!$this->_write_file($compilepath, $compiled_contents))
592                return false;
593          function _compile_section_start($tag_args)  
594          {          return true;
595                  $attrs = $this->_parse_attrs($tag_args);      }
596    
597                  $output = "<?php ";  /*======================================================================*\
598                  $section_name = $attrs['name'];      Function: _process_cached_inserts
599                  if (empty($section_name)) {      Purpose:  Replace cached inserts with the actual results
600                          $this->_syntax_error("missing section name");  \*======================================================================*/
601                  }      function _process_cached_inserts($results)
602        {
603                  $output .= "unset(\$_sections[$section_name]);\n";          preg_match_all('!'.$this->_smarty_md5.'{insert_cache (.*)}'.$this->_smarty_md5.'!Uis',
604                  $section_props = "\$_sections[$section_name]['properties']";                         $results, $match);
605            list($cached_inserts, $insert_args) = $match;
606                  foreach ($attrs as $attr_name => $attr_value) {  
607                          switch ($attr_name) {          for ($i = 0; $i < count($cached_inserts); $i++) {
608                                  case 'loop':              $args = unserialize($insert_args[$i]);
609                                          $output .= "{$section_props}['loop'] = is_array($attr_value) ? count($attr_value) : $attr_value;\n";              $name = $args['name'];
610                                          break;              unset($args['name']);
611    
612                                  case 'show':              $function_name = 'insert_' . $name;
613                                          if (is_bool($attr_value))              $replace = $function_name($args);
614                                                  $attr_value = $attr_value ? 'true' : 'false';  
615                                          $output .= "{$section_props}['$attr_name'] = $attr_value;\n";              $results = str_replace($cached_inserts[$i], $replace, $results);
616                                          break;          }
617    
618                                  default:          return $results;
619                                          $output .= "{$section_props}['$attr_name'] = $attr_value;\n";      }  
620                                          break;  
621                          }  
622                  }  /*======================================================================*\
623        Function: _compile_tag
624                  if (isset($attrs['loop'])) {      Purpose:  Compile a template tag
625                          $loop_check_code = "{$section_props}['loop'] > 0 && ";  \*======================================================================*/
626                  } else {      function _compile_tag($template_tag)
627                          $output .= "{$section_props}['loop'] = 1; #-fix- \n";      {
628                  }          /* Matched comment. */
629            if ($template_tag{0} == '*' && $template_tag{strlen($template_tag)-1} == '*')
630                  if (isset($attrs['show'])) {              return '';
631                          $show_check_code = "{$section_props}['show'] && ";  
632                  } else {          $qstr_regexp = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'';
633                          $output .= "{$section_props}['show'] = {$section_props}['loop'] > 0;\n";  
634                  }          /* Split tag into two parts: command and the arguments. */
635            preg_match('/^(
636                  $output .= "if ($loop_check_code $show_check_code true): ";                         (?: ' . $qstr_regexp . ' | (?>[^"\'\s]+))+
637                          )
638                  $output .= "                        (?:\s+(.*))?
639                          for ({$section_props}['index'] = 0;                      /xs', $template_tag, $match);
640                                   {$section_props}['index'] < {$section_props}['loop'];          list(, $tag_command, $tag_args) = $match;
641                                   {$section_props}['index']++):\n";  
642                  $output .= "{$section_props}['rownum'] = {$section_props}['index'] + 1;\n";          /* If the tag name matches a variable or section property definition,
643               we simply process it. */
644                  $output .= "?>\n";          if (preg_match('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:(?>' . $qstr_regexp . '|[^|]+))*)*$!', $tag_command) ||   // if a variable
645                preg_match('!^#(\w+)#(?>\|@?\w+(:(?>' . $qstr_regexp . '|[^|]+))*)*$!', $tag_command)     ||  // or a configuration variable
646                  return $output;              preg_match('!^%\w+\.\w+%(?>\|@?\w+(:(?>' . $qstr_regexp . '|[^|]+))*)*$!', $tag_command)) {    // or a section property
647          }              settype($tag_command, 'array');
648                $this->_parse_vars_props($tag_command);
649          function _compile_if_tag($tag_args, $elseif = false)              return "<?php echo $tag_command[0]; ?>\n";
650          {          }
651                  /* Tokenize args for 'if' tag. */  
652                  preg_match_all('/(?:          switch ($tag_command) {
653                                                   "[^"\\\\]*(?:\\\\.[^"\\\\]*)*"                 | # match all double quoted strings allowed escaped double quotes              case 'include':
654                                                   \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'             | # match all single quoted strings allowed escaped single quotes                  return $this->_compile_include_tag($tag_args);
655                                                   [()]                                                                   | # match parentheses  
656                                                   [^"\'\s()]+                                                      # match any other token that is not any of the above              case 'if':
657                                                  )/x', $tag_args, $match);                  return $this->_compile_if_tag($tag_args);
658                  $tokens = $match[0];  
659                case 'else':
660                  $this->_parse_vars_props($tokens);                  return '<?php else: ?>';
661    
662                  $is_arg_stack = array();              case 'elseif':
663                                    return $this->_compile_if_tag($tag_args, true);
664                  for ($i = 0; $i < count($tokens); $i++) {  
665                          $token = &$tokens[$i];              case '/if':
666                          switch ($token) {                  return '<?php endif; ?>';
667                                  case 'eq':  
668                                          $token = '==';              case 'ldelim':
669                                          break;                  return $this->left_delimiter;
670    
671                                  case 'ne':              case 'rdelim':
672                                  case 'neq':                  return $this->right_delimiter;
673                                          $token = '!=';  
674                                          break;              case 'section':
675                    array_push($this->_sectionelse_stack, false);
676                                  case 'lt':                  return $this->_compile_section_start($tag_args);
677                                          $token = '<';  
678                                          break;              case 'sectionelse':
679                    $this->_sectionelse_stack[count($this->_sectionelse_stack)-1] = true;
680                                  case 'le':                  return "<?php endfor; else: ?>";
681                                  case 'lte':  
682                                          $token = '<=';              case '/section':
683                                          break;                  if (array_pop($this->_sectionelse_stack))
684                        return "<?php endif; ?>";
685                                  case 'gt':                  else
686                                          $token = '>';                      return "<?php endfor; endif; ?>";
687                                          break;  
688                                                case 'config_load':
689                                  case 'ge':                  return $this->_compile_config_load_tag($tag_args);
690                                  case 'gte':  
691                                          $token = '>=';              case 'strip':
692                                          break;              case '/strip':
693                    return $this->left_delimiter.$tag_command.$this->right_delimiter;
694                                  case 'and':  
695                                          $token = '&&';              case 'literal':
696                                          break;                  list (,$literal_block) = each($this->_literal_blocks);
697                    $this->_current_line_no += substr_count($literal_block, "\n");
698                                  case 'or':                  return $literal_block;
699                                          $token = '||';  
700                                          break;              case 'insert':
701                    return $this->_compile_insert_tag($tag_args);
702                                  case 'not':  
703                                          $token = '!';              default:
704                                          break;                  if (isset($this->custom_funcs[$tag_command])) {
705                        return $this->_compile_custom_tag($tag_command, $tag_args);
706                                  case 'mod':                  } else {
707                                          $token = '%';                      $this->_syntax_error("unknown tag - '$tag_command'", E_USER_WARNING);
708                                          break;                      return;
709                    }
710                                  case '(':          }
711                                          array_push($is_arg_stack, $i);      }
712                                          break;  
713        function _compile_custom_tag($tag_command, $tag_args)
714                                  case 'is':      {
715                                          /* If last token was a ')', we operate on the parenthesized          $function = $this->custom_funcs[$tag_command];
716                                             expression. The start of the expression is on the stack.  
717                                             Otherwise, we operate on the last encountered token. */          if (!function_exists($function)) {
718                                          if ($tokens[$i-1] == ')')              $this->_syntax_error("custom function '$tag_command' is not implemented", E_USER_WARNING);
719                                                  $is_arg_start = array_pop($is_arg_stack);              return;
720                                          else          }
721                                                  $is_arg_start = $i-1;          
722                                          /* Construct the argument for 'is' expression, so it knows          $attrs = $this->_parse_attrs($tag_args);
723                                             what to operate on. */          foreach ($attrs as $arg_name => $arg_value) {
724                                          $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start));              if (is_bool($arg_value))
725                    $arg_value = $arg_value ? 'true' : 'false';
726                                          /* Pass all tokens from next one until the end to the              $arg_list[] = "'$arg_name' => $arg_value";
727                                             'is' expression parsing function. The function will          }
728                                             return modified tokens, where the first one is the result  
729                                             of the 'is' expression and the rest are the tokens it          return "<?php $function(array(".implode(',', (array)$arg_list).")); ?>";
730                                             didn't touch. */      }
731                                          $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));  
732    
733                                          /* Replace the old tokens with the new ones. */  /*======================================================================*\
734                                          array_splice($tokens, $is_arg_start, count($tokens), $new_tokens);      Function: _compile_insert_tag
735        Purpose:  Compile {insert ...} tag
736                                          /* Adjust argument start so that it won't change from the  \*======================================================================*/
737                                             current position for the next iteration. */      function _compile_insert_tag($tag_args)
738                                          $i = $is_arg_start;      {
739                                          break;          $attrs = $this->_parse_attrs($tag_args);
740                          }          $name = substr($attrs['name'], 1, -1);
741                  }  
742            if (empty($name)) {
743                  if ($elseif)              $this->_syntax_error("missing insert name");
744                          return '<?php elseif ('.implode(' ', $tokens).'): ?>';          }
745                  else  
746                          return '<?php if ('.implode(' ', $tokens).'): ?>';          foreach ($attrs as $arg_name => $arg_value) {
747          }              if (is_bool($arg_value))
748                    $arg_value = $arg_value ? 'true' : 'false';
749          function _parse_is_expr($is_arg, $tokens)              $arg_list[] = "'$arg_name' => $arg_value";
750          {          }
751                  $expr_end = 0;  
752            return "<?php echo _smarty_insert_handler(array(".implode(', ', (array)$arg_list)."), \$this->caching, \$this->_smarty_md5); ?>\n";
753                  if (($first_token = array_shift($tokens)) == 'not') {      }  
754                          $negate_expr = true;  
755                          $expr_type = array_shift($tokens);  
756                  } else  /*======================================================================*\
757                          $expr_type = $first_token;      Function: _compile_config_load_tag
758        Purpose:  Compile {config_load ...} tag
759                  switch ($expr_type) {  \*======================================================================*/
760                          case 'even':      function _compile_config_load_tag($tag_args)
761                                  if ($tokens[$expr_end] == 'by') {      {
762                                          $expr_end++;          $attrs = $this->_parse_attrs($tag_args);
763                                          $expr_arg = $tokens[$expr_end++];  
764                                          $expr = "!(($is_arg / $expr_arg) % $expr_arg)";          if (empty($attrs['file'])) {
765                                  }              $this->_syntax_error("missing 'file' attribute in config_load tag");
766                                  else          }
767                                          $expr = "!($is_arg % 2)";  
768                                  break;          $output  = "<?php if (!class_exists('Config_File'))\n" .
769                       "    include_once 'Config_File.class.php';\n" .
770                          case 'odd':                     "if (!is_object(\$_conf_obj) || get_class(\$_conf_obj) != 'config_file') {\n" .
771                                  if ($tokens[$expr_end] == 'by') {                     "    \$_conf_obj  = new Config_File('".$this->config_dir."');\n" .
772                                          $expr_end++;                     "}\n" .
773                                          $expr_arg = $tokens[$expr_end++];                     "\$_config = array_merge((array)\$_config, \$_conf_obj->get(".$attrs['file']."));\n";
774                                          $expr = "(($is_arg / $expr_arg) % $expr_arg)";  
775                                  }          if (!empty($attrs['section']))
776                                  else              $output .= '$_config = array_merge((array)$_config, $_conf_obj->get('.$attrs['file'].', '.$attrs['section'].')); ';
777                                          $expr = "($is_arg % 2)";  
778                                  break;          $output .= '?>';
779    
780                          case 'div':          return $output;
781                                  if ($tokens[$expr_end] == 'by') {      }
782                                          $expr_end++;  
783                                          $expr_arg = $tokens[$expr_end++];  
784                                          $expr = "!($is_arg % $expr_arg)";  /*======================================================================*\
785                                  } else {      Function: _compile_include_tag
786                                          $this->_syntax_error("expecting 'by' after 'div'");      Purpose:  Compile {include ...} tag
787                                  }  \*======================================================================*/
788                                  break;      function _compile_include_tag($tag_args)
789        {
790                          default:          $attrs = $this->_parse_attrs($tag_args);
791                                  $this->_syntax_error("unknown 'is' expression - '$expr_type'");  
792                                  break;          if (empty($attrs['file'])) {
793                  }              $this->_syntax_error("missing 'file' attribute in include tag");
794            } else
795                  if ($negate_expr) {              $attrs['file'] = $this->_dequote($attrs['file']);
796                          $expr = "!($expr)";  
797                  }          if (count($attrs) > 1) {
798                $include_func_name = uniqid("_include_");
799                  array_splice($tokens, 0, $expr_end, $expr);              $include_file_name = $this->compile_dir.'/'.$attrs['file'];
800    
801                  return $tokens;              foreach ($attrs as $arg_name => $arg_value) {
802          }                  if ($arg_name == 'file') continue;
803                    if (is_bool($arg_value))
804          function _parse_attrs($tag_args)                      $arg_value = $arg_value ? 'true' : 'false';
805          {                  $arg_list[] = "'$arg_name' => $arg_value";
806                  /* Tokenize tag attributes. */              }
807                  preg_match_all('/(?:"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"       |  
808                                                    \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'     | (?>[^"\'=\s]+)              return  "<?php " .
809                                                   )+ |                      "if (!function_exists('$include_func_name')) {\n".
810                                                   [=]                      "   function $include_func_name(\$file_name, \$def_vars, \$include_vars)\n" .
811                                              /x', $tag_args, $match);                      "   {\n" .
812                  $tokens = $match[0];                      "       extract(\$def_vars);\n" .
813                  $var_delims = array('$', '#', '%');                      "       extract(\$include_vars);\n" .
814                        "       include \"\$file_name.php\";\n" .
815                  $attrs = array();                      "   }\n" .
816                  /* Parse state:                      "}\n" .
817                          0 - expecting attr name                      "$include_func_name(\"$include_file_name\", get_defined_vars(), array(".implode(',', (array)$arg_list)."));\n?>";
818                          1 - expecting '=' or another attr name          } else
819                          2 - expecting attr value (not '=') */               return '<?php include "'.$this->compile_dir.'/'.$attrs['file'].'.php"; ?>';
820                  $state = 0;      }
821    
822                  foreach ($tokens as $token) {  
823                          switch ($state) {  /*======================================================================*\
824                                  case 0:      Function: _compile_section_start
825                                          /* If the token is a valid identifier, we set attribute name      Purpose:  Compile {section ...} tag
826                                             and go to state 1. */  \*======================================================================*/
827                                          if (preg_match('!\w+!', $token)) {      function _compile_section_start($tag_args)
828                                                  $attr_name = $token;      {
829                                                  $state = 1;          $attrs = $this->_parse_attrs($tag_args);
830                                          } else  
831                                                  $this->_syntax_error("invalid attribute name - '$token'");          $output = "<?php ";
832                                          break;          $section_name = $attrs['name'];
833            if (empty($section_name)) {
834                                  case 1:              $this->_syntax_error("missing section name");
835                                          /* If the token is a valid identifier, the previously set          }
836                                             attribute name does not need an argument. We put it in  
837                                             the attrs array, set the new attribute name to the          $output .= "unset(\$_sections[$section_name]);\n";
838                                             current token and don't switch state.          $section_props = "\$_sections[$section_name]['properties']";
839    
840                                             If the token is '=', then we go to state 2. */          foreach ($attrs as $attr_name => $attr_value) {
841                                          if ($token == '=') {              switch ($attr_name) {
842                                                  $state = 2;                  case 'loop':
843                                          } else                      $output .= "{$section_props}['loop'] = is_array($attr_value) ? count($attr_value) : $attr_value;\n";
844                                                  $this->_syntax_error("expecting '=' after attribute name");                      break;
845                                          break;  
846                    case 'show':
847                                  case 2:                      if (is_bool($attr_value))
848                                          /* If token is not '=', we set the attribute value and go to                          $attr_value = $attr_value ? 'true' : 'false';
849                                             state 0. */                      $output .= "{$section_props}['$attr_name'] = $attr_value;\n";
850                                          if ($token != '=') {                      break;
851                                                  /* We booleanize the token if it's a non-quoted possible  
852                                                     boolean value. */                  default:
853                                                  if (preg_match('!^(on|yes|true)$!', $token))                      $output .= "{$section_props}['$attr_name'] = $attr_value;\n";
854                                                          $token = true;                      break;
855                                                  else if (preg_match('!^(off|no|false)$!', $token))              }
856                                                          $token = false;          }
857                                                  /* If the token is not variable (doesn't start with  
858                                                     '$', '#', or '%') and not enclosed in single or          if (isset($attrs['loop'])) {
859                                                     double quotes we single-quote it. */              $loop_check_code = "{$section_props}['loop'] > 0 && ";
860                                                  else if (!in_array($token{0}, $var_delims) &&          } else {
861                                                                   !(($token{0} == '"' || $token[0] == "'") &&              $output .= "{$section_props}['loop'] = 1;\n";
862                                                                   $token{strlen($token)-1} == $token{0}))          }
863                                                          $token = "'".$token."'";  
864            if (isset($attrs['show'])) {
865                                                  $attrs[$attr_name] = $token;              $show_check_code = "{$section_props}['show'] && ";
866                                                  $state = 0;          } else {
867                                          } else              $output .= "{$section_props}['show'] = {$section_props}['loop'] > 0;\n";
868                                                  $this->_syntax_error("'=' cannot be an attribute value");          }
869                                          break;  
870                          }          $output .= "if ($loop_check_code $show_check_code true): ";
871                  }  
872            $output .= "
873                  $this->_parse_vars_props($attrs);              for ({$section_props}['index'] = 0;
874                     {$section_props}['index'] < {$section_props}['loop'];
875                  return $attrs;                   {$section_props}['index']++):\n";
876          }          $output .= "{$section_props}['rownum'] = {$section_props}['index'] + 1;\n";
877    
878          function _preg_grep($pattern, $array)          $output .= "?>";
879          {  
880                  $result = array();          return $output;
881        }
882                  foreach ($array as $key => $entry) {  
883                          if (preg_match($pattern, $entry))  
884                                  $result[$key] = $entry;  /*======================================================================*\
885                  }      Function: _compile_if_tag
886        Purpose:  Compile {if ...} tag
887                  return $result;  \*======================================================================*/
888          }      function _compile_if_tag($tag_args, $elseif = false)
889                {
890          function _parse_vars_props(&$tokens)          /* Tokenize args for 'if' tag. */
891          {          preg_match_all('/(?:
892                  /* preg_grep() was fixed to return keys properly in 4.0.4 and later. To                           "[^"\\\\]*(?:\\\\.[^"\\\\]*)*"         | # match all double quoted strings allowed escaped double quotes
893                     allow people to use older versions of PHP we emulate preg_grep() and                           \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'     | # match all single quoted strings allowed escaped single quotes
894                     use the version check to see what function to call. */                           [()]                                   | # match parentheses
895                  if (strnatcmp(PHP_VERSION, '4.0.4') >= 0) {                           [^"\'\s()]+                              # match any other token that is not any of the above
896                          $var_exprs = preg_grep('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:[^|]+)?)*$!', $tokens);                          )/x', $tag_args, $match);
897                          $conf_var_exprs = preg_grep('!^#(\w+)#(?>\|@?\w+(:[^|]+)?)*$!', $tokens);          $tokens = $match[0];
898                          $sect_prop_exprs = preg_grep('!^%\w+\.\w+%(?>\|@?\w+(:[^|]+)?)*$!', $tokens);  
899                  } else {          $this->_parse_vars_props($tokens);
900                          $var_exprs = $this->_preg_grep('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:[^|]+)?)*$!', $tokens);  
901                          $conf_var_exprs = $this->_preg_grep('!^#(\w+)#(?>\|@?\w+(:[^|]+)?)*$!', $tokens);          $is_arg_stack = array();
902                          $sect_prop_exprs = $this->_preg_grep('!^%\w+\.\w+%(?>\|@?\w+(:[^|]+)?)*$!', $tokens);          
903                  }          for ($i = 0; $i < count($tokens); $i++) {
904                $token = &$tokens[$i];
905                  if (count($var_exprs)) {              switch ($token) {
906                          foreach ($var_exprs as $expr_index => $var_expr) {                  case 'eq':
907                                  $tokens[$expr_index] = $this->_parse_var($var_expr);                      $token = '==';
908                          }                      break;
909                  }  
910                                    case 'ne':
911                  if (count($conf_var_exprs)) {                  case 'neq':
912                          foreach ($conf_var_exprs as $expr_index => $var_expr) {                      $token = '!=';
913                                  $tokens[$expr_index] = $this->_parse_conf_var($var_expr);                      break;
914                          }  
915                  }                  case 'lt':
916                        $token = '<';
917                  if (count($sect_prop_exprs)) {                      break;
918                          foreach ($sect_prop_exprs as $expr_index => $section_prop_expr) {  
919                                  $tokens[$expr_index] = $this->_parse_section_prop($section_prop_expr);                  case 'le':
920                          }                  case 'lte':
921                  }                      $token = '<=';
922          }                      break;
923    
924          function _parse_var($var_expr)                  case 'gt':
925          {                      $token = '>';
926                  $modifiers = explode('|', substr($var_expr, 1));                      break;
927                    
928                  $sections = explode('/', array_shift($modifiers));                  case 'ge':
929                  $props = explode('.', array_pop($sections));                  case 'gte':
930                  $var_name = array_shift($props);                      $token = '>=';
931                        break;
932                  $output = "\$$var_name";  
933                    case 'and':
934                  foreach ($sections as $section) {                      $token = '&&';
935                          $output .= "[\$_sections['$section']['properties']['index']]";                      break;
936                  }  
937                  foreach ($props as $prop) {                  case 'or':
938                          $output .= "['$prop']";                      $token = '||';
939                  }                      break;
940    
941                  $this->_parse_modifiers($output, $modifiers);                  case 'not':
942                        $token = '!';
943                  return $output;                      break;
944          }  
945                    case 'mod':
946          function _parse_conf_var($conf_var_expr)                      $token = '%';
947          {                      break;
948                  $modifiers = explode('|', $conf_var_expr);  
949                    case '(':
950                  $var_name = substr(array_shift($modifiers), 1, -1);                      array_push($is_arg_stack, $i);
951                        break;
952                  $output = "\$_config['$var_name']";  
953                    case 'is':
954                  $this->_parse_modifiers($output, $modifiers);                      /* If last token was a ')', we operate on the parenthesized
955                           expression. The start of the expression is on the stack.
956                  return $output;                         Otherwise, we operate on the last encountered token. */
957          }                      if ($tokens[$i-1] == ')')
958                            $is_arg_start = array_pop($is_arg_stack);
959          function _parse_section_prop($section_prop_expr)                      else
960          {                          $is_arg_start = $i-1;
961                  $modifiers = explode('|', $section_prop_expr);                      /* Construct the argument for 'is' expression, so it knows
962                           what to operate on. */
963                  preg_match('!%(\w+)\.(\w+)%!', array_shift($modifiers), $match);                      $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start));
964                  $section_name = $match[1];  
965                  $prop_name = $match[2];                      /* Pass all tokens from next one until the end to the
966                           'is' expression parsing function. The function will
967                  $output = "\$_sections['$section_name']['properties']['$prop_name']";                         return modified tokens, where the first one is the result
968                           of the 'is' expression and the rest are the tokens it
969                  $this->_parse_modifiers($output, $modifiers);                         didn't touch. */
970                        $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));
971                  return $output;  
972          }                      /* Replace the old tokens with the new ones. */
973                        array_splice($tokens, $is_arg_start, count($tokens), $new_tokens);
974          function _parse_modifiers(&$output, $modifiers)  
975          {                      /* Adjust argument start so that it won't change from the
976                  foreach ($modifiers as $modifier) {                         current position for the next iteration. */
977                          $modifier = explode(':', $modifier);                      $i = $is_arg_start;
978                          $modifier_name = array_shift($modifier);                      break;
979                }
980                          if ($modifier_name{0} == '@') {          }
981                                  $map_array = 'false';  
982                                  $modifier_name = substr($modifier_name, 1);          if ($elseif)
983                          } else              return '<?php elseif ('.implode(' ', $tokens).'): ?>';
984                                  $map_array = 'true';          else
985                return '<?php if ('.implode(' ', $tokens).'): ?>';
986                          /*      }
987                           * First we lookup the modifier function name in the registered  
988                           * modifiers table.      function _parse_is_expr($is_arg, $tokens)
989                           */      {
990                          $mod_func_name = $this->custom_mods[$modifier_name];          $expr_end = 0;
991    
992                          /*          if (($first_token = array_shift($tokens)) == 'not') {
993                           * If we don't find that modifier there, we assume it's just a PHP              $negate_expr = true;
994                           * function name.              $expr_type = array_shift($tokens);
995                           */          } else
996                          if (!isset($mod_func_name))              $expr_type = $first_token;
997                                  $mod_func_name = $modifier_name;  
998            switch ($expr_type) {
999                          $this->_parse_vars_props($modifier);              case 'even':
1000                    if ($tokens[$expr_end] == 'by') {
1001                          if (count($modifier) > 0)                      $expr_end++;
1002                                  $modifier_args = ', '.implode(', ', $modifier);                      $expr_arg = $tokens[$expr_end++];
1003                          else                      $expr = "!(($is_arg / $expr_arg) % $expr_arg)";
1004                                  $modifier_args = '';                  }
1005                    else
1006                          $output = "_smarty_mod_handler('$mod_func_name', $map_array, $output$modifier_args)";                      $expr = "!($is_arg % 2)";
1007                  }                  break;
1008          }  
1009                        case 'odd':
1010                    if ($tokens[$expr_end] == 'by') {
1011  /*======================================================================*\                      $expr_end++;
1012          Function: _dequote                      $expr_arg = $tokens[$expr_end++];
1013          Purpose:  Remove starting and ending quotes from the string                      $expr = "(($is_arg / $expr_arg) % $expr_arg)";
1014  \*======================================================================*/                  }
1015          function _dequote($string)                  else
1016          {                      $expr = "($is_arg % 2)";
1017                  if (($string{0} == "'" || $string{0} == '"') &&                  break;
1018                          $string{strlen($string)-1} == $string{0})  
1019                          return substr($string, 1, -1);              case 'div':
1020          }                  if ($tokens[$expr_end] == 'by') {
1021                        $expr_end++;
1022                                $expr_arg = $tokens[$expr_end++];
1023  /*======================================================================*\                      $expr = "!($is_arg % $expr_arg)";
1024          Function:       _read_file()                  } else {
1025          Purpose:        read in a file                      $this->_syntax_error("expecting 'by' after 'div'");
1026  \*======================================================================*/                  }
1027                    break;
1028          function _read_file($filename)  
1029          {              default:
1030                  if(!($fd = fopen($filename, 'r'))) {                  $this->_syntax_error("unknown 'is' expression - '$expr_type'");
1031                          $this->_set_error_msg("problem reading '$filename.'");                  break;
1032                          return false;          }
1033                  }  
1034                  $contents = fread($fd, filesize($filename));          if ($negate_expr) {
1035                  fclose($fd);              $expr = "!($expr)";
1036                  return $contents;          }
1037          }  
1038            array_splice($tokens, 0, $expr_end, $expr);
1039  /*======================================================================*\  
1040          Function:       _write_file()          return $tokens;
1041          Purpose:        write out a file      }
1042  \*======================================================================*/  
1043    
1044          function _write_file($filename,$contents)  /*======================================================================*\
1045          {      Function: _parse_attrs
1046                  if(!($fd = fopen($filename, 'w'))) {      Purpose:  Parse attribute string
1047                          $this->_set_error_msg("problem writing '$filename.'");  \*======================================================================*/
1048                          return false;      function _parse_attrs($tag_args, $quote = true)
1049                  }      {
1050                  fwrite($fd, $contents);          /* Tokenize tag attributes. */
1051                  fclose($fd);          preg_match_all('/(?:"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"       |
1052                  return true;                            \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'     | (?>[^"\'=\s]+)
1053          }                           )+ |
1054                             [=]
1055  /*======================================================================*\                          /x', $tag_args, $match);
1056          Function:       _set_error_msg()          $tokens       = $match[0];
1057          Purpose:        set the error message          $var_delims   = array('$', '#', '%');
1058  \*======================================================================*/  
1059            $attrs = array();
1060          function _set_error_msg($error_msg)          /* Parse state:
1061          {              0 - expecting attribute name
1062                  $this->_error_msg="smarty error: $error_msg";              1 - expecting '='
1063                  return true;              2 - expecting attribute value (not '=') */
1064          }          $state = 0;
1065    
1066  /*======================================================================*\          foreach ($tokens as $token) {
1067          Function: _syntax_error              switch ($state) {
1068          Purpose:  display Smarty syntax error                  case 0:
1069  \*======================================================================*/                      /* If the token is a valid identifier, we set attribute name
1070          function _syntax_error($error_msg, $error_type = E_USER_ERROR)                         and go to state 1. */
1071          {                      if (preg_match('!^\w+$!', $token)) {
1072                  trigger_error("Smarty: [in " . $this->_current_file . " line " .                          $attr_name = $token;
1073                                            $this->_current_line_no . "]: syntax error: $error_msg", $error_type);                          $state = 1;
1074          }                      } else
1075                            $this->_syntax_error("invalid attribute name - '$token'");
1076                        break;
1077    
1078                    case 1:
1079                        /* If the token is '=', then we go to state 2. */
1080                        if ($token == '=') {
1081                            $state = 2;
1082                        } else
1083                            $this->_syntax_error("expecting '=' after attribute name");
1084                        break;
1085    
1086                    case 2:
1087                        /* If token is not '=', we set the attribute value and go to
1088                           state 0. */
1089                        if ($token != '=') {
1090                            /* We booleanize the token if it's a non-quoted possible
1091                               boolean value. */
1092                            if (preg_match('!^(on|yes|true)$!', $token))
1093                                $token = true;
1094                            else if (preg_match('!^(off|no|false)$!', $token))
1095                                $token = false;
1096                            /* If the token is not variable (doesn't start with
1097                               '$', '#', or '%') and not enclosed in single or
1098                               double quotes we single-quote it. */
1099                            else if ($quote && !in_array($token{0}, $var_delims) &&
1100                                     !(($token{0} == '"' || $token[0] == "'") &&
1101                                     $token{strlen($token)-1} == $token{0}))
1102                                $token = "'".$token."'";
1103    
1104                            $attrs[$attr_name] = $token;
1105                            $state = 0;
1106                        } else
1107                            $this->_syntax_error("'=' cannot be an attribute value");
1108                        break;
1109                }
1110            }
1111    
1112            $this->_parse_vars_props($attrs);
1113    
1114            return $attrs;
1115        }
1116    
1117    
1118    /*======================================================================*\
1119        Function: _preg_grep
1120        Purpose:  Emulate PHP's preg_grep()
1121    \*======================================================================*/
1122        function _preg_grep($pattern, $array)
1123        {
1124            $result = array();
1125    
1126            foreach ($array as $key => $entry) {
1127                if (preg_match($pattern, $entry))
1128                    $result[$key] = $entry;
1129            }
1130    
1131            return $result;
1132        }
1133        
1134        function _parse_vars_props(&$tokens)
1135        {
1136            $qstr_regexp = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'';
1137    
1138            /* preg_grep() was fixed to return keys properly in 4.0.4 and later. To
1139               allow people to use older versions of PHP we emulate preg_grep() and
1140               use the version check to see what function to call. */
1141            if (strnatcmp(PHP_VERSION, '4.0.4') >= 0) {
1142                $var_exprs = preg_grep('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:(?>' .  $qstr_regexp . '|[^|]+))*)*$!', $tokens);
1143                $conf_var_exprs = preg_grep('!^#(\w+)#(?>\|@?\w+(:(?>' . $qstr_regexp . '|[^|]+))*)*$!', $tokens);
1144                $sect_prop_exprs = preg_grep('!^%\w+\.\w+%(?>\|@?\w+(:(?>' .  $qstr_regexp .  '|[^|]+))*)*$!', $tokens);
1145            } else {
1146                $var_exprs = $this->_preg_grep('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:(?>' .  $qstr_regexp .  '|[^|]+))*)*$!', $tokens);
1147                $conf_var_exprs = $this->_preg_grep('!^#(\w+)#(?>\|@?\w+(:(?>' . $qstr_regexp . '|[^|]+))*)*$!', $tokens);
1148                $sect_prop_exprs = $this->_preg_grep('!^%\w+\.\w+%(?>\|@?\w+(:(?>' .  $qstr_regexp .  '|[^|]+))*)*$!', $tokens);
1149            }
1150    
1151            if (count($var_exprs)) {
1152                foreach ($var_exprs as $expr_index => $var_expr) {
1153                    $tokens[$expr_index] = $this->_parse_var($var_expr);
1154                }
1155            }
1156            
1157            if (count($conf_var_exprs)) {
1158                foreach ($conf_var_exprs as $expr_index => $var_expr) {
1159                    $tokens[$expr_index] = $this->_parse_conf_var($var_expr);
1160                }
1161            }
1162    
1163            if (count($sect_prop_exprs)) {
1164                foreach ($sect_prop_exprs as $expr_index => $section_prop_expr) {
1165                    $tokens[$expr_index] = $this->_parse_section_prop($section_prop_expr);
1166                }
1167            }
1168        }
1169    
1170        function _parse_var($var_expr)
1171        {
1172            list($var_ref, $modifiers) = explode('|', substr($var_expr, 1), 2);
1173    
1174            $sections = explode('/', $var_ref);
1175            $props = explode('.', array_pop($sections));
1176            $var_name = array_shift($props);
1177    
1178            $output = "\$$var_name";
1179    
1180            foreach ($sections as $section) {
1181                $output .= "[\$_sections['$section']['properties']['index']]";
1182            }
1183            foreach ($props as $prop) {
1184                $output .= "['$prop']";
1185            }
1186    
1187            $this->_parse_modifiers($output, $modifiers);
1188    
1189            return $output;
1190        }
1191    
1192        function _parse_conf_var($conf_var_expr)
1193        {
1194            list($var_ref, $modifiers) = explode('|', $conf_var_expr, 2);
1195    
1196            $var_name = substr($var_ref, 1, -1);
1197    
1198            $output = "\$_config['$var_name']";
1199    
1200            $this->_parse_modifiers($output, $modifiers);
1201    
1202            return $output;
1203        }
1204    
1205        function _parse_section_prop($section_prop_expr)
1206        {
1207            list($var_ref, $modifiers) = explode('|', $section_prop_expr, 2);
1208    
1209            preg_match('!%(\w+)\.(\w+)%!', $var_ref, $match);
1210            $section_name = $match[1];
1211            $prop_name = $match[2];
1212    
1213            $output = "\$_sections['$section_name']['properties']['$prop_name']";
1214    
1215            $this->_parse_modifiers($output, $modifiers);
1216    
1217            return $output;
1218        }
1219    
1220        function _parse_modifiers(&$output, $modifier_string)
1221        {
1222            $qstr_regexp = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'';
1223            preg_match_all('!\|(@?\w+)((?>:(?:'. $qstr_regexp . '|[^|]+))*)!', '|' . $modifier_string, $match);
1224            list(, $modifiers, $modifier_arg_strings) = $match;
1225    
1226            for ($i = 0; $i < count($modifiers); $i++) {
1227                $modifier_name = $modifiers[$i];
1228                preg_match_all('!:(' . $qstr_regexp . '|[^:]+)!', $modifier_arg_strings[$i], $match);
1229                $modifier_args = $match[1];
1230    
1231                if ($modifier_name{0} == '@') {
1232                    $map_array = 'false';
1233                    $modifier_name = substr($modifier_name, 1);
1234                } else
1235                    $map_array = 'true';
1236    
1237                /*
1238                 * First we lookup the modifier function name in the registered
1239                 * modifiers table.
1240                 */
1241                $mod_func_name = $this->custom_mods[$modifier_name];
1242    
1243                /*
1244                 * If we don't find that modifier there, we assume it's just a PHP
1245                 * function name.
1246                 */
1247                if (!isset($mod_func_name))
1248                    $mod_func_name = $modifier_name;
1249    
1250                if (!function_exists($mod_func_name)) {
1251                    $this->_syntax_error("modifier '$modifier_name' is not implemented", E_USER_WARNING);
1252                    continue;
1253                }
1254    
1255                $this->_parse_vars_props($modifier_args);
1256    
1257                if (count($modifier_args) > 0)
1258                    $modifier_args = ', '.implode(', ', $modifier_args);
1259                else
1260                    $modifier_args = '';
1261    
1262                $output = "_smarty_mod_handler('$mod_func_name', $map_array, $output$modifier_args)";
1263            }
1264        }
1265        
1266    
1267    /*======================================================================*\
1268        Function: _dequote
1269        Purpose:  Remove starting and ending quotes from the string
1270    \*======================================================================*/
1271        function _dequote($string)
1272        {
1273            if (($string{0} == "'" || $string{0} == '"') &&
1274                $string{strlen($string)-1} == $string{0})
1275                return substr($string, 1, -1);
1276            else
1277                return $string;
1278        }
1279    
1280        
1281    /*======================================================================*\
1282        Function:   _read_file()
1283        Purpose:    read in a file
1284    \*======================================================================*/
1285    
1286        function _read_file($filename)
1287    
1288        {
1289            if (!($fd = fopen($filename, 'r'))) {
1290                $this->_set_error_msg("problem reading '$filename.'");
1291                return false;
1292            }
1293            flock($fd, LOCK_SH);
1294            $contents = fread($fd, filesize($filename));
1295            fclose($fd);
1296            return $contents;
1297        }
1298    
1299    /*======================================================================*\
1300        Function:   _write_file()
1301        Purpose:    write out a file
1302    \*======================================================================*/
1303    
1304        function _write_file($filename, $contents, $create_dirs = false)
1305        {
1306            if($create_dirs)
1307                $this->_create_dir_structure(dirname($filename));
1308            
1309            if (!($fd = fopen($filename, 'a'))) {
1310                $this->_set_error_msg("problem writing '$filename.'");
1311                return false;
1312            }
1313            flock($fd, LOCK_EX);
1314    
1315            $fd_safe = fopen($filename, 'w');
1316    
1317            fwrite($fd_safe, $contents);
1318            fclose($fd_safe);
1319            fclose($fd);
1320    
1321            return true;
1322        }    
1323    
1324    
1325    /*======================================================================*\
1326        Function: _clear_tpl_cache_dir
1327        Purpose:  Clear the specified template cache
1328    \*======================================================================*/
1329        function _clear_tpl_cache_dir($cache_tpl_md5)
1330        {
1331            $cache_dir = $this->cache_dir.'/'.$cache_tpl_md5;
1332    
1333            if (!is_dir($cache_dir))
1334                return false;
1335    
1336            $dir_handle = opendir($cache_dir);
1337            while ($curr_dir = readdir($dir_handle)) {
1338                $cache_path_dir = $cache_dir.'/'.$curr_dir;
1339                if ($curr_dir == '.' || $curr_dir == '..' ||
1340                    !is_dir($cache_path_dir))
1341                    continue;
1342    
1343                $dir_handle2 = opendir($cache_path_dir);
1344                while ($curr_file = readdir($dir_handle2)) {
1345                    if ($curr_file == '.' || $curr_file == '..')
1346                        continue;
1347    
1348                    $cache_file = $cache_path_dir.'/'.$curr_file;
1349                    if (is_file($cache_file))
1350                        unlink($cache_file);
1351                }
1352                closedir($dir_handle2);
1353                @rmdir($cache_path_dir);
1354            }
1355            closedir($dir_handle);
1356            @rmdir($cache_dir);
1357    
1358            return true;
1359        }
1360    
1361    
1362    /*======================================================================*\
1363        Function:   _set_error_msg()
1364        Purpose:    set the error message
1365    \*======================================================================*/
1366    
1367        function _set_error_msg($error_msg)
1368        {
1369            $this->_error_msg="smarty error: $error_msg";
1370            return true;
1371        }
1372    
1373    /*======================================================================*\
1374        Function: _syntax_error
1375        Purpose:  display Smarty syntax error
1376    \*======================================================================*/
1377        function _syntax_error($error_msg, $error_type = E_USER_ERROR)
1378        {
1379            trigger_error("Smarty: [in " . $this->_current_file . " line " .
1380                          $this->_current_line_no . "]: syntax error: $error_msg", $error_type);
1381        }
1382  }  }
1383    
1384    /* vim: set expandtab: */
1385    
1386  ?>  ?>

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.2

  ViewVC Help
Powered by ViewVC 1.1.26