/[corp_html]/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.1.1 by dpavlin, Mon Feb 19 18:12:21 2001 UTC revision 1.5 by dpavlin, Mon Jul 9 14:22:07 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");
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                                                                                          'img'   => 'smarty_func_img'      var $tpl_file_ext    =  '.tpl';     // template file extention
75                                                                                   );      
76                var $php_handling    =  SMARTY_PHP_PASSTHRU; // how smarty handles php tags
77          var $custom_mods                        =       array(  'lower'                 => 'strtolower',                                          // possible values:
78                                                                                          'upper'                 => 'strtoupper',                                          // SMARTY_PHP_PASSTHRU -> echo tags as is
79                                                                                          'capitalize'    => 'ucwords',                                          // SMARTY_PHP_QUOTE    -> escape tags as entities
80                                                                                          'escape'                => 'smarty_mod_escape',                                          // SMARTY_PHP_REMOVE   -> remove php tags
81                                                                                          'truncate'              => 'smarty_mod_truncate',                                          // SMARTY_PHP_ALLOW    -> execute php tags
82                                                                                          'spacify'               => 'smarty_mod_spacify',                                          // default: SMARTY_PHP_PASSTHRU
83                                                                                          'date_format'   => 'smarty_mod_date_format',  
84                                                                                          'string_format' => 'smarty_mod_string_format',      var $left_delimiter  =  '{';        // template tag delimiters.
85                                                                                          'replace'               => 'smarty_mod_replace',      var $right_delimiter =  '}';
86                                                                                          'strip_tags'    => 'smarty_mod_strip_tags',  
87                                                                                          'default'               => 'smarty_mod_default'  
88                                                                                   );      var $custom_funcs    =  array(  'html_options'      => 'smarty_func_html_options',
89          var $global_assign                      =       array(  'SCRIPT_NAME'                                      'html_select_date'  => 'smarty_func_html_select_date',
90                                                                                   );                                      'header'            => 'smarty_func_header',
91            
92          // internal vars  //----- local custom_funcs
93          var $_error_msg                         =       false;          // error messages          'img'           => 'smarty_func_img',
94          var $_tpl_vars                          =       array();          'html_checkboxes' => 'smarty_func_html_checkboxes',
95          var $_sectionelse_stack         =       array();        // keeps track of whether section had 'else' part          'input'         => 'smarty_func_input',
96          var $_literal_blocks            =       array();        // keeps literal template blocks          'rinput'        => 'smarty_func_rinput',
97          var $_current_file                      =       null;           // the current template being compiled  
98          var $_current_line_no           =       1;                      // line number for error messages                                   );
99        
100                var $custom_mods     =  array(  'lower'         => 'strtolower',
101  /*======================================================================*\                                      'upper'         => 'strtoupper',
102          Function: Smarty                                      'capitalize'    => 'ucwords',
103          Purpose:  Constructor                                      'escape'        => 'smarty_mod_escape',
104  \*======================================================================*/                                      'truncate'      => 'smarty_mod_truncate',
105          function Smarty()                                      'spacify'       => 'smarty_mod_spacify',
106          {                                      'date_format'   => 'smarty_mod_date_format',
107                  foreach ($this->global_assign as $var_name)                                      'string_format' => 'smarty_mod_string_format',
108                          $this->assign($var_name, $GLOBALS[$var_name]);                                      'replace'       => 'smarty_mod_replace',
109          }                                      'strip_tags'    => 'smarty_mod_strip_tags',
110                                        'default'       => 'smarty_mod_default',
111    
112  /*======================================================================*\  //----- local custom_mods
113          Function:       assign()          'filesize' => 'smarty_mod_filesize',
114          Purpose:        assigns values to template variables  
115  \*======================================================================*/                                   );
116        
117          function assign($tpl_var, $value = NULL)      // internal vars
118          {      var $_error_msg             =   false;      // error messages. true/false
119                  if (is_array($tpl_var)){      var $_tpl_vars              =   array();
120                          foreach ($tpl_var as $key => $val) {      var $_sectionelse_stack     =   array();    // keeps track of whether section had 'else' part
121                                  if (!empty($key))      var $_literal_blocks        =   array();    // keeps literal template blocks
122                                          $this->_tpl_vars[$key] = $val;      var $_current_file          =   null;       // the current template being compiled
123                          }      var $_current_line_no       =   1;          // line number for error messages
124                  } else {      var $_smarty_md5            =   'f8d698aea36fcbead2b9d5359ffca76f'; // md5 checksum of the string 'Smarty'
125                          if (!empty($tpl_var) && isset($value))  
126                                  $this->_tpl_vars[$tpl_var] = $value;      
127                  }  /*======================================================================*\
128          }      Function: Smarty
129        Purpose:  Constructor
130            \*======================================================================*/
131  /*======================================================================*\      function Smarty()
132          Function: append      {
133          Purpose:  appens values to template variables          foreach ($this->global_assign as $var_name)
134  \*======================================================================*/              $this->assign($var_name, $GLOBALS[$var_name]);
135          function append($tpl_var, $value = NULL)      }
136          {  
137                  if (is_array($tpl_var)) {  
138                          foreach ($tpl_var as $key => $val) {  /*======================================================================*\
139                                  if (!empty($key)) {      Function:   assign()
140                                          if (!is_array($this->_tpl_vars[$key]))      Purpose:    assigns values to template variables
141                                                  settype($this->_tpl_vars[$key], 'array');  \*======================================================================*/
142                                          $this->_tpl_vars[$key][] = $val;  
143                                  }      function assign($tpl_var, $value = NULL)
144                          }      {
145                  } else {          if (is_array($tpl_var)){
146                          if (!empty($tpl_var) && isset($value)) {              foreach ($tpl_var as $key => $val) {
147                                  if (!is_array($this->_tpl_vars[$tpl_var]))                  if (!empty($key))
148                                          settype($this->_tpl_vars[$tpl_var], 'array');                      $this->_tpl_vars[$key] = $val;
149                                  $this->_tpl_vars[$tpl_var][] = $value;              }
150                          }          } else {
151                  }              if (!empty($tpl_var) && isset($value))
152          }                  $this->_tpl_vars[$tpl_var] = $value;
153            }
154        }
155  /*======================================================================*\  
156          Function:       clear_assign()      
157          Purpose:        clear the given assigned template variable.  /*======================================================================*\
158  \*======================================================================*/      Function: append
159        Purpose:  appens values to template variables
160          function clear_assign($tpl_var)  \*======================================================================*/
161          {      function append($tpl_var, $value = NULL)
162                  unset($this->_tpl_vars[$tpl_var]);      {
163          }          if (is_array($tpl_var)) {
164                foreach ($tpl_var as $key => $val) {
165  /*======================================================================*\                  if (!empty($key)) {
166          Function:       clear_all_assign()                      if (!is_array($this->_tpl_vars[$key]))
167          Purpose:        clear all the assigned template variables.                          settype($this->_tpl_vars[$key], 'array');
168  \*======================================================================*/                      $this->_tpl_vars[$key][] = $val;
169                    }
170          function clear_all_assign()              }
171          {          } else {
172                  $this->_tpl_vars = array();              if (!empty($tpl_var) && isset($value)) {
173          }                  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          Function: get_template_vars          }
178          Purpose:  Returns an array containing template variables      }
179  \*======================================================================*/  
180          function &get_template_vars()  
181          {  /*======================================================================*\
182                  return $this->_tpl_vars;      Function:   clear_assign()
183          }      Purpose:    clear the given assigned template variable.
184    \*======================================================================*/
185    
186  /*======================================================================*\      function clear_assign($tpl_var)
187          Function:       display()      {
188          Purpose:        executes & displays the template results          if(is_array($tpl_var))
189  \*======================================================================*/              foreach($tpl_var as $curr_var)
190                    unset($this->_tpl_vars[$curr_var]);
191          function display($tpl_file)          else
192          {              unset($this->_tpl_vars[$tpl_var]);
193                  // compile files      }
194                  $this->_compile($this->template_dir);  
195                  //assemble compile directory path to file      
196                  $_compile_file = $this->compile_dir.'/'.$tpl_file.'.php';  /*======================================================================*\
197                        Function: register_function
198                  extract($this->_tpl_vars);                    Purpose:  Registers custom function to be used in templates
199                  include($_compile_file);  \*======================================================================*/
200          }            function register_function($function, $function_impl)
201                        {
202  /*======================================================================*\          $this->custom_funcs[$function] = $function_impl;
203          Function:       fetch()      }
204          Purpose:        executes & returns the template results  
205  \*======================================================================*/      
206    /*======================================================================*\
207          function fetch($tpl_file)      Function: register_modifier
208          {      Purpose:  Registers modifier to be used in templates
209                  ob_start();  \*======================================================================*/
210                  $this->display($tpl_file);      function register_modifier($modifier, $modifier_impl)
211                  $results = ob_get_contents();      {
212                  ob_end_clean();          $this->custom_mods[$modifier] = $modifier_impl;
213                  return $results;      }
214          }  
215        
216  /*======================================================================*\  /*======================================================================*\
217          Function:       compile()      Function:   clear_cache()
218          Purpose:        called to compile the templates      Purpose:    clear cached content for the given template and cache id
219  \*======================================================================*/  \*======================================================================*/
220    
221          function _compile($tpl_dir)      function clear_cache($tpl_file, $cache_id = null)
222          {      {
223                  if($this->compile_check)          $cache_tpl_md5 = md5(realpath($this->template_dir.'/'.$tpl_file));
224                  {          $cache_dir = $this->cache_dir.'/'.$cache_tpl_md5;
225                          if($this->_traverse_files($tpl_dir, 0))          
226                                  return true;          if (!is_dir($cache_dir))
227                          else              return false;
228                                  return false;  
229                  }          if (isset($cache_id)) {
230                  else              $cache_id_md5 = md5($cache_id);
231                          return false;              $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                return (bool)(is_file($cache_file) && unlink($cache_file));
234  /*======================================================================*\          } else
235          Function:       _traverse_files()              return $this->_clear_tpl_cache_dir($cache_tpl_md5);
236          Purpose:        traverse the template files & process each one      }
237  \*======================================================================*/      
238        
239          function _traverse_files($tpl_dir, $depth)  /*======================================================================*\
240          {      Function:   clear_all_cache()
241                  if(is_dir($tpl_dir)) {      Purpose:    clear the entire contents of cache (all templates)
242                          if($tpl_dir)  \*======================================================================*/
243                                  $dir_handle = opendir($tpl_dir);  
244        function clear_all_cache()
245                          while($curr_file = readdir($dir_handle)) {      {
246                                  if ($curr_file == '.' || $curr_file == '..')          if (!is_dir($this->cache_dir))
247                                          continue;              return false;
248    
249                                  $filepath = $tpl_dir."/".$curr_file;          $dir_handle = opendir($this->cache_dir);
250                                  if(is_readable($filepath)) {          while ($curr_dir = readdir($dir_handle)) {
251                                          if(is_file($filepath) && preg_match('!' . preg_quote($this->tpl_file_ext, '!') . '$!', $curr_file)) {              if ($curr_dir == '.' || $curr_dir == '..' ||
252                                                  if(!$this->_process_file($filepath))                  !is_dir($this->cache_dir.'/'.$curr_dir))
253                                                          return false;                  continue;
254                                          } else if(is_dir($filepath)) {  
255                                                  if(!$this->_traverse_files($filepath, $depth + 1))              $this->_clear_tpl_cache_dir($curr_dir);
256                                                          return false;          }
257                                          } else {          closedir($dir_handle);
258                                                  // invalid file type, skipping  
259                                                  $this->_set_error_msg("Invalid filetype for $filepath, skipping");          return true;
260                                                  continue;      }
261                                          }  
262                                  }  
263                          }  /*======================================================================*\
264                  } else {      Function:   is_cached()
265                          $this->_set_error_msg("Directory \"$tpl_dir\" does not exist or is not a directory.");      Purpose:    test to see if valid cache exists for this template
266                          return false;  \*======================================================================*/
267                  }  
268        function is_cached($tpl_file, $cache_id = null)
269                  return true;      {
270          }          if (!$this->caching)
271                return false;
272  /*======================================================================*\  
273          Function:       _process_file()          // cache name = template path + cache_id
274          Input:          test template files for modifications          $cache_tpl_md5 = md5(realpath($this->template_dir.'/'.$tpl_file));
275                                  and execute the compilation for each          $cache_id_md5 = md5($cache_id);
276                                  one requiring it.          $cache_id_dir = substr($cache_id_md5, 0, 2);
277  \*======================================================================*/          $cache_file = $this->cache_dir."/$cache_tpl_md5/$cache_id_dir/{$cache_tpl_md5}_$cache_id_md5.cache";
278    
279          function _process_file($filepath)          if (file_exists($cache_file) &&
280          {              ($this->cache_lifetime == 0 ||
281                  if(preg_match("/^(.+)\/([^\/]+)$/", $filepath, $match)) {               (time() - filemtime($cache_file) <= $this->cache_lifetime)))
282                          $tpl_file_dir = $match[1];                                    return true;
283                          $tpl_file_name = $match[2] . ".php";          else
284                return false;
285                          $compile_dir = preg_replace('!^' . preg_quote($this->template_dir, '!') . '!',          
286                                                                                  $this->compile_dir, $match[1]);      }
287        
288                          //create directory if none exists          
289                          if(!file_exists($compile_dir)) {  /*======================================================================*\
290                                  $compile_dir_parts = preg_split('!/+!', $compile_dir);      Function:   clear_all_assign()
291                                  $new_dir = "";      Purpose:    clear all the assigned template variables.
292                                  foreach ($compile_dir_parts as $dir_part) {  \*======================================================================*/
293                                          $new_dir .= $dir_part."/";  
294                                          if (!file_exists($new_dir) && !mkdir($new_dir, 0755)) {      function clear_all_assign()
295                                                  $this->_set_error_msg("problem creating directory \"$compile_dir\"");      {
296                                                  return false;                                    $this->_tpl_vars = array();
297                                          }      }
298                                  }  
299                          }  
300    /*======================================================================*\
301                          // compile the template file if none exists or has been modified      Function: get_template_vars
302                          if (!file_exists($compile_dir."/".$tpl_file_name) ||      Purpose:  Returns an array containing template variables
303                                  ($this->_modified_file($filepath, $compile_dir."/".$tpl_file_name))) {  \*======================================================================*/
304                                  if (!$this->_compile_file($filepath, $compile_dir."/".$tpl_file_name))      function &get_template_vars()
305                                          return false;                                {
306                          } else {          return $this->_tpl_vars;
307                                  // no compilation needed      }
308                                  return true;  
309                          }  
310                  } else {  /*======================================================================*\
311                          $this->_set_error_msg("problem matching \"$filepath.\"");      Function:   display()
312                          return false;      Purpose:    executes & displays the template results
313                  }  \*======================================================================*/
314    
315                  return true;      function display($tpl_file, $cache_id = null)
316          }      {
317            $this->fetch($tpl_file, $cache_id, true);
318  /*======================================================================*\      }  
319          Function:       _modified_file()          
320          Input:          return comparison of modification times of files  /*======================================================================*\
321  \*======================================================================*/      Function:   fetch()
322        Purpose:    executes & returns or displays the template results
323          function _modified_file($filepath, $compilepath)  \*======================================================================*/
324          {  
325                  if(filemtime($filepath) >= filemtime($compilepath))      function fetch($tpl_file, $cache_id = null, $display = false)
326                          return true;      {
327                  return false;          global $HTTP_SERVER_VARS;
328          }  
329            if ($this->caching) {
330  /*======================================================================*\              // cache name = template path + cache_id
331          Function:       _compile_file()              $cache_tpl_md5 = md5(realpath($this->template_dir.'/'.$tpl_file));
332          Input:          compile a template file              $cache_id_md5 = md5($cache_id);
333  \*======================================================================*/              $cache_id_dir = substr($cache_id_md5, 0, 2);
334                $cache_file = $this->cache_dir."/$cache_tpl_md5/$cache_id_dir/{$cache_tpl_md5}_$cache_id_md5.cache";
335          function _compile_file($filepath, $compilepath)              
336          {              if (file_exists($cache_file) &&
337                  if (!($template_contents = $this->_read_file($filepath)))                  ($this->cache_lifetime == 0 ||
338                          return false;                   (time() - filemtime($cache_file) <= $this->cache_lifetime))) {
339                    $results = $this->_read_file($cache_file);
340                  $this->_current_file = str_replace($this->template_dir . "/", "", $filepath);                  $results = $this->_process_cached_inserts($results);
341                  $this->_current_line_no = 1;                  if ($display) {
342                  $ldq = preg_quote($this->left_delimiter, '!');                      echo $results;
343                  $rdq = preg_quote($this->right_delimiter, '!');                      return;
344                    } else
345                  /* Pull out the literal blocks. */                      return $results;
346                  preg_match_all("!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s", $template_contents, $match);              }
347                  $this->_literal_blocks = $match[1];          }
348                  $template_contents = preg_replace("!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s",  
349                                                                                    '{literal}', $template_contents);          // compile files
350            $this->_compile($this->template_dir);
351                  /* Gather all template tags. */          //assemble compile directory path to file
352                  preg_match_all("!{$ldq}\s*(.*?)\s*{$rdq}!s", $template_contents, $match);          $_compile_file = $this->compile_dir."/".$tpl_file.".php";
353                  $template_tags = $match[1];  
354                  /* Split content by template tags to obtain non-template content. */          extract($this->_tpl_vars);
355                  $text_blocks = preg_split("!{$ldq}.*?{$rdq}!s", $template_contents);  
356                  if(!$this->allow_php) {          // if we just need to display the results, don't perform output
357                          /* Escape php tags. */          // buffering - for speed
358                          $text_blocks = preg_replace('!<\?([^?]*?)\?>!', '&lt;?$1?&gt;', $text_blocks);          if ($display && !$this->caching)
359                  }              include($_compile_file);
360            else {
361                  /* Compile the template tags into PHP code. */              ob_start();
362                  $compiled_tags = array();              include($_compile_file);
363                  for ($i = 0; $i < count($template_tags); $i++) {              $results = ob_get_contents();
364                          $this->_current_line_no += substr_count($text_blocks[$i], "\n");              ob_end_clean();
365                          $compiled_tags[] = $this->_compile_tag($template_tags[$i]);          }
366                          $this->_current_line_no += substr_count($template_tags[$i], "\n");  
367                  }          if($this->caching) {
368                $this->_write_file($cache_file, $results, true);
369                  $compiled_contents = "";              $results = $this->_process_cached_inserts($results);
370                            }
371                  /* Interleave the compiled contents and text blocks to get the final result. */  
372                  for ($i = 0; $i < count($compiled_tags); $i++) {          if ($display) {
373                          $compiled_contents .= $text_blocks[$i].$compiled_tags[$i];              echo $results;
374                  }              return;
375                  $compiled_contents .= $text_blocks[$i];          } else
376                                return $results;
377                  /* Reformat data between 'strip' and '/strip' tags, removing spaces, tabs and newlines. */      }  
378                  if (preg_match_all("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s", $compiled_contents, $match)) {      
379                          $strip_tags = $match[0];  /*======================================================================*\
380                          $strip_tags_modified = preg_replace("!{$ldq}/?strip{$rdq}|[\t ]+$|^[\t ]+!m", '', $strip_tags);      Function:   compile()
381                          $strip_tags_modified = preg_replace('![\r\n]+!m', '', $strip_tags_modified);      Purpose:    called to compile the templates
382                          for ($i = 0; $i < count($strip_tags); $i++)  \*======================================================================*/
383                                  $compiled_contents = preg_replace("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s",  
384                                                                                                    $strip_tags_modified[$i], $compiled_contents, 1);      function _compile($tpl_dir)
385                  }      {
386            if($this->compile_check || $this->force_compile)
387                  if(!$this->_write_file($compilepath, $compiled_contents))          {
388                          return false;              if($this->_traverse_files($tpl_dir, 0))
389                    return true;
390                  return true;              else
391          }                  return false;
392            } else
393          function _compile_tag($template_tag)              return false;
394          {      }  
395                  /* Matched comment. */      
396                  if ($template_tag{0} == '*' && $template_tag{strlen($template_tag)-1} == '*')  /*======================================================================*\
397                          return "";      Function:   _traverse_files()
398        Purpose:    traverse the template files & process each one
399                  /* Split tag into two parts: command and the arguments. */  \*======================================================================*/
400                  preg_match('/^(  
401                                             (?:"[^"\\\\]*(?:\\\\.[^"\\\\]*)*" | \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\' | (?>[^"\'\s]+))+      function _traverse_files($tpl_dir, $depth)
402                                            )      {
403                                        (?:\s+(.*))?          $retval = true;
404                                          /xs', $template_tag, $match);  
405                  list(, $tag_command, $tag_args) = $match;          if (is_dir($tpl_dir)) {
406                $dir_handle = opendir($tpl_dir);
407                  /* If the tag name matches a variable or section property definition,              while ($curr_file = readdir($dir_handle)) {
408                     we simply process it. */                  if ($curr_file == '.' || $curr_file == '..')
409                  if (preg_match('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:[^|]+)?)*$!', $tag_command) ||      // if a variable                      continue;
410                          preg_match('!^#(\w+)#(?>\|@?\w+(:[^|]+)?)*$!', $tag_command)            ||  // or a configuration variable  
411                          preg_match('!^%\w+\.\w+%(?>\|@?\w+(:[^|]+)?)*$!', $tag_command)) {    // or a section property                  $filepath = $tpl_dir.'/'.$curr_file;
412                          settype($tag_command, 'array');                  if (is_readable($filepath)) {
413                          $this->_parse_vars_props($tag_command);                      if (is_file($filepath) && substr($curr_file, -strlen($this->tpl_file_ext)) == $this->tpl_file_ext) {
414                          return "<?php print $tag_command[0]; ?>";                          if (!$this->_process_file($filepath)) {
415                  }                              $retval = false;
416                                break;
417                  switch ($tag_command) {                          }
418                          case 'include':                      } else if (is_dir($filepath)) {
419                                  return $this->_compile_include_tag($tag_args);                          if (!$this->_traverse_files($filepath, $depth + 1)) {
420                                $retval = false;
421                          case 'if':                              break;
422                                  return $this->_compile_if_tag($tag_args);                          }
423                        } else {
424                          case 'else':                          // invalid file type, skipping
425                                  return '<?php else: ?>';                          $this->_set_error_msg("Invalid filetype for $filepath, skipping");
426                            continue;
427                          case 'elseif':                      }
428                                  return $this->_compile_if_tag($tag_args, true);                  }
429                }
430                          case '/if':  
431                                  return '<?php endif; ?>';              closedir($dir_handle);
432                return $retval;
433                          case 'ldelim':          } else {
434                                  return $this->left_delimiter;              $this->_set_error_msg("Directory \"$tpl_dir\" does not exist or is not a directory.");
435                return false;
436                          case 'rdelim':          }
437                                  return $this->right_delimiter;      }
438    
439                          case 'section':  /*======================================================================*\
440                                  array_push($this->_sectionelse_stack, false);      Function:   _process_file()
441                                  return $this->_compile_section_start($tag_args);      Input:      test template files for modifications
442                    and execute the compilation for each
443                          case 'sectionelse':                  one requiring it.
444                                  $this->_sectionelse_stack[count($this->_sectionelse_stack)-1] = true;  \*======================================================================*/
445                                  return "<?php endfor; else: ?>";  
446        function _process_file($filepath)
447                          case '/section':      {
448                                  if (array_pop($this->_sectionelse_stack))          if(preg_match("/^(.+)\/([^\/]+)$/", $filepath, $match)) {
449                                          return "<?php endif; ?>";              $tpl_file_dir = $match[1];          
450                                  else              $tpl_file_name = $match[2] . '.php';
451                                          return "<?php endfor; endif; ?>";  
452                $compile_dir = preg_replace('!^' . preg_quote($this->template_dir, '!') . '!',
453                          case 'config_load':                                          $this->compile_dir, $match[1]);
454                                  return $this->_compile_config_load_tag($tag_args);  
455                //create directory if none exists
456                          case 'strip':              $this->_create_dir_structure($compile_dir);
457                          case '/strip':  
458                                  return $this->left_delimiter.$tag_command.$this->right_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 'literal':                  ($this->_modified_file($filepath, $compile_dir."/".$tpl_file_name))) {
461                                  list (,$literal_block) = each($this->_literal_blocks);                  if (!$this->_compile_file($filepath, $compile_dir."/".$tpl_file_name))
462                                  $this->_current_line_no += substr_count($literal_block, "\n");                      return false;
463                                  return $literal_block;              } else {
464                    // no compilation needed
465                          case 'insert':                  return true;
466                                  return $this->_compile_insert_tag($tag_args);              }
467            } else {
468                          default:              $this->_set_error_msg("problem matching \"$filepath.\"");
469                                  if (isset($this->custom_funcs[$tag_command])) {              return false;
470                                          return $this->_compile_custom_tag($tag_command, $tag_args);          }
471                                  } else {  
472                                          $this->_syntax_error("unknown tag - '$tag_command'", E_USER_WARNING);          return true;
473                                          return "";      }
474                                  }  
475                  }  /*======================================================================*\
476          }      Function: _create_dir_structure
477        Purpose:  create full directory structure
478    \*======================================================================*/
479          function _compile_custom_tag($tag_command, $tag_args)      function _create_dir_structure($dir)
480          {      {
481                  $attrs = $this->_parse_attrs($tag_args);          if (!file_exists($dir)) {
482                  $function = $this->custom_funcs[$tag_command];              $dir_parts = preg_split('!/+!', $dir, -1, PREG_SPLIT_NO_EMPTY);
483                  foreach ($attrs as $arg_name => $arg_value) {              $new_dir = ($dir{0} == '/') ? '/' : '';
484                          if (is_bool($arg_value))              foreach ($dir_parts as $dir_part) {
485                                  $arg_value = $arg_value ? 'true' : 'false';                  $new_dir .= $dir_part;
486                          $arg_list[] = "'$arg_name' => $arg_value";                  if (!file_exists($new_dir) && !mkdir($new_dir, 0755)) {
487                  }                      $this->_set_error_msg("problem creating directory \"$dir\"");
488                        return false;              
489                  return "<?php $function(array(".implode(',', (array)$arg_list).")); ?>";                  }
490          }                  $new_dir .= '/';
491                }
492            }
493          function _compile_insert_tag($tag_args)      }
494          {  
495                  $attrs = $this->_parse_attrs($tag_args);  /*======================================================================*\
496                  $name = substr($attrs['name'], 1, -1);      Function:   _modified_file()
497        Input:      return comparison of modification times of files
498                  if (empty($name)) {  \*======================================================================*/
499                          $this->_syntax_error("missing insert name");  
500                  }      function _modified_file($filepath, $compilepath)
501        {
502                  foreach ($attrs as $arg_name => $arg_value) {          if (filemtime($filepath) >= filemtime($compilepath))
503                          if ($arg_name == 'name') continue;              return true;
504                          if (is_bool($arg_value))          return false;
505                                  $arg_value = $arg_value ? 'true' : 'false';      }
506                          $arg_list[] = "'$arg_name' => $arg_value";  
507                  }  /*======================================================================*\
508        Function:   _compile_file()
509                  return "<?php print insert_$name(array(".implode(',', (array)$arg_list).")); ?>";      Input:      compile a template file
510          }  \*======================================================================*/
511    
512        function _compile_file($filepath, $compilepath)
513          function _compile_config_load_tag($tag_args)      {
514          {          if (!($template_contents = $this->_read_file($filepath)))
515                  $attrs = $this->_parse_attrs($tag_args);              return false;
516    
517                  if (empty($attrs['file'])) {          $this->_current_file = str_replace($this->template_dir . '/', '', $filepath);
518                          $this->_syntax_error("missing 'file' attribute in config_load tag");          $this->_current_line_no = 1;
519                  }          $ldq = preg_quote($this->left_delimiter, '!');
520            $rdq = preg_quote($this->right_delimiter, '!');
521                  $output  = "<?php if (!class_exists('Config_File'))\n" .  
522                                     "    include_once 'Config_File.class.php';\n" .          /* Pull out the literal blocks. */
523                             "if (!is_object(\$_conf_obj) || get_class(\$_conf_obj) != 'config_file') {\n" .          preg_match_all("!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s", $template_contents, $match);
524                                     "    \$_conf_obj  = new Config_File('".$this->config_dir."');\n" .          $this->_literal_blocks = $match[1];
525                             "}\n" .          $template_contents = preg_replace("!{$ldq}literal{$rdq}(.*?){$ldq}/literal{$rdq}!s",
526                                     "\$_config = array_merge((array)\$_config, \$_conf_obj->get(".$attrs['file']."));\n";                                            '{literal}', $template_contents);
527    
528                  if (!empty($attrs['section']))          /* Gather all template tags. */
529                          $output .= '$_config = array_merge((array)$_config, $_conf_obj->get('.$attrs['file'].', '.$attrs['section'].')); ';          preg_match_all("!{$ldq}\s*(.*?)\s*{$rdq}!s", $template_contents, $match);
530            $template_tags = $match[1];
531                  $output .= '?>';          /* Split content by template tags to obtain non-template content. */
532            $text_blocks = preg_split("!{$ldq}.*?{$rdq}!s", $template_contents);
533                  return $output;  
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_include_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 include tag");                      if (preg_match('!^(<\?(php\s|\s|=\s)|<script\s*language\s*=\s*[\"\']?php[\"\']?\s*>)!is', $sp_match[0][$curr_sp])) {
543                  } else                          /* php tag */
544                          $attrs['file'] = $this->_dequote($attrs['file']);                          if ($this->php_handling == SMARTY_PHP_PASSTHRU) {
545                                /* echo php contents */
546                  if (count($attrs) > 1) {                              $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                          $include_func_name = uniqid("_include_");                         } else if ($this->php_handling == SMARTY_PHP_QUOTE) {
548                          $include_file_name = $this->compile_dir.'/'.$attrs['file'];                              /* quote php tags */
549                                $text_blocks[$curr_tb] = str_replace($sp_match[0][$curr_sp], htmlspecialchars($sp_match[0][$curr_sp]), $text_blocks[$curr_tb]);
550                          foreach ($attrs as $arg_name => $arg_value) {                          } else if ($this->php_handling == SMARTY_PHP_REMOVE) {
551                                  if ($arg_name == 'file') continue;                              /* remove php tags */
552                                  if (is_bool($arg_value))                              if (substr($sp_match[0][$curr_sp], 0, 2) == '<?')
553                                          $arg_value = $arg_value ? 'true' : 'false';                                  $text_blocks[$curr_tb] = str_replace($sp_match[0][$curr_sp], '', $text_blocks[$curr_tb]);
554                                  $arg_list[] = "'$arg_name' => $arg_value";                              else
555                          }                                  /* 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  "<?php " .                          }
558                                          "function $include_func_name(\$file_name, \$def_vars, \$include_vars)\n" .                      } else
559                                          "{\n" .                          /* echo the non-php tags */
560                                          "       extract(\$def_vars);\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]);
561                                          "       extract(\$include_vars);\n" .                  }
562                                          "       include \"\$file_name.php\";\n" .              }
563                                          "}\n" .          }
564                                          "$include_func_name(\"$include_file_name\", get_defined_vars(), array(".implode(',', (array)$arg_list)."));\n?>\n";                        
565                  } else          /* Compile the template tags into PHP code. */
566                           return '<?php include "'.$this->compile_dir.'/'.$attrs['file'].'.php"; ?>';          $compiled_tags = array();
567          }          for ($i = 0; $i < count($template_tags); $i++) {
568                $this->_current_line_no += substr_count($text_blocks[$i], "\n");
569          function _compile_section_start($tag_args)              $compiled_tags[] = $this->_compile_tag($template_tags[$i]);
570          {              $this->_current_line_no += substr_count($template_tags[$i], "\n");
571                  $attrs = $this->_parse_attrs($tag_args);          }
572    
573                  $output = "<?php ";          $compiled_contents = '';
574                  $section_name = $attrs['name'];          
575                  if (empty($section_name)) {          /* Interleave the compiled contents and text blocks to get the final result. */
576                          $this->_syntax_error("missing section name");          for ($i = 0; $i < count($compiled_tags); $i++) {
577                  }              $compiled_contents .= $text_blocks[$i].$compiled_tags[$i];
578            }
579                  $output .= "unset(\$_sections[$section_name]);\n";          $compiled_contents .= $text_blocks[$i];
580                  $section_props = "\$_sections[$section_name]['properties']";          
581            /* Reformat data between 'strip' and '/strip' tags, removing spaces, tabs and newlines. */
582                  foreach ($attrs as $attr_name => $attr_value) {          if (preg_match_all("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s", $compiled_contents, $match)) {
583                          switch ($attr_name) {              $strip_tags = $match[0];
584                                  case 'loop':              $strip_tags_modified = preg_replace("!{$ldq}/?strip{$rdq}|[\t ]+$|^[\t ]+!m", '', $strip_tags);
585                                          $output .= "{$section_props}['loop'] = is_array($attr_value) ? count($attr_value) : $attr_value;\n";              $strip_tags_modified = preg_replace('![\r\n]+!m', '', $strip_tags_modified);
586                                          break;              for ($i = 0; $i < count($strip_tags); $i++)
587                    $compiled_contents = preg_replace("!{$ldq}strip{$rdq}.*?{$ldq}/strip{$rdq}!s",
588                                  case 'show':                                                    $strip_tags_modified[$i], $compiled_contents, 1);
589                                          if (is_bool($attr_value))          }
590                                                  $attr_value = $attr_value ? 'true' : 'false';  
591                                          $output .= "{$section_props}['$attr_name'] = $attr_value;\n";          if(!$this->_write_file($compilepath, $compiled_contents))
592                                          break;              return false;
593    
594                                  default:          return true;
595                                          $output .= "{$section_props}['$attr_name'] = $attr_value;\n";      }
596                                          break;  
597                          }  /*======================================================================*\
598                  }      Function: _process_cached_inserts
599        Purpose:  Replace cached inserts with the actual results
600                  if (isset($attrs['loop'])) {  \*======================================================================*/
601                          $loop_check_code = "{$section_props}['loop'] > 0 && ";      function _process_cached_inserts($results)
602                  } else {      {
603                          $output .= "{$section_props}['loop'] = 1; #-fix- \n";          preg_match_all('!'.$this->_smarty_md5.'{insert_cache (.*)}'.$this->_smarty_md5.'!Uis',
604                  }                         $results, $match);
605            list($cached_inserts, $insert_args) = $match;
606                  if (isset($attrs['show'])) {  
607                          $show_check_code = "{$section_props}['show'] && ";          for ($i = 0; $i < count($cached_inserts); $i++) {
608                  } else {              $args = unserialize($insert_args[$i]);
609                          $output .= "{$section_props}['show'] = {$section_props}['loop'] > 0;\n";              $name = $args['name'];
610                  }              unset($args['name']);
611    
612                  $output .= "if ($loop_check_code $show_check_code true): ";              $function_name = 'insert_' . $name;
613                $replace = $function_name($args);
614                  $output .= "  
615                          for ({$section_props}['index'] = 0;              $results = str_replace($cached_inserts[$i], $replace, $results);
616                                   {$section_props}['index'] < {$section_props}['loop'];          }
617                                   {$section_props}['index']++):\n";  
618                  $output .= "{$section_props}['rownum'] = {$section_props}['index'] + 1;\n";          return $results;
619        }  
620                  $output .= "?>\n";  
621    
622                  return $output;  /*======================================================================*\
623          }      Function: _compile_tag
624        Purpose:  Compile a template tag
625          function _compile_if_tag($tag_args, $elseif = false)  \*======================================================================*/
626          {      function _compile_tag($template_tag)
627                  /* Tokenize args for 'if' tag. */      {
628                  preg_match_all('/(?:          /* Matched comment. */
629                                                   "[^"\\\\]*(?:\\\\.[^"\\\\]*)*"                 | # match all double quoted strings allowed escaped double quotes          if ($template_tag{0} == '*' && $template_tag{strlen($template_tag)-1} == '*')
630                                                   \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'             | # match all single quoted strings allowed escaped single quotes              return '';
631                                                   [()]                                                                   | # match parentheses  
632                                                   [^"\'\s()]+                                                      # match any other token that is not any of the above          $qstr_regexp = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'';
633                                                  )/x', $tag_args, $match);  
634                  $tokens = $match[0];          /* Split tag into two parts: command and the arguments. */
635            preg_match('/^(
636                  $this->_parse_vars_props($tokens);                         (?: ' . $qstr_regexp . ' | (?>[^"\'\s]+))+
637                          )
638                  $is_arg_stack = array();                        (?:\s+(.*))?
639                                        /xs', $template_tag, $match);
640                  for ($i = 0; $i < count($tokens); $i++) {          list(, $tag_command, $tag_args) = $match;
641                          $token = &$tokens[$i];  
642                          switch ($token) {          /* If the tag name matches a variable or section property definition,
643                                  case 'eq':             we simply process it. */
644                                          $token = '==';          if (preg_match('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:(?>' . $qstr_regexp . '|[^|]+))*)*$!', $tag_command) ||   // if a variable
645                                          break;              preg_match('!^#(\w+)#(?>\|@?\w+(:(?>' . $qstr_regexp . '|[^|]+))*)*$!', $tag_command)     ||  // or a configuration variable
646                preg_match('!^%\w+\.\w+%(?>\|@?\w+(:(?>' . $qstr_regexp . '|[^|]+))*)*$!', $tag_command)) {    // or a section property
647                                  case 'ne':              settype($tag_command, 'array');
648                                  case 'neq':              $this->_parse_vars_props($tag_command);
649                                          $token = '!=';              return "<?php echo $tag_command[0]; ?>\n";
650                                          break;          }
651    
652                                  case 'lt':          switch ($tag_command) {
653                                          $token = '<';              case 'include':
654                                          break;                  return $this->_compile_include_tag($tag_args);
655    
656                                  case 'le':              case 'if':
657                                  case 'lte':                  return $this->_compile_if_tag($tag_args);
658                                          $token = '<=';  
659                                          break;              case 'else':
660                    return '<?php else: ?>';
661                                  case 'gt':  
662                                          $token = '>';              case 'elseif':
663                                          break;                  return $this->_compile_if_tag($tag_args, true);
664                                    
665                                  case 'ge':              case '/if':
666                                  case 'gte':                  return '<?php endif; ?>';
667                                          $token = '>=';  
668                                          break;              case 'ldelim':
669                    return $this->left_delimiter;
670                                  case 'and':  
671                                          $token = '&&';              case 'rdelim':
672                                          break;                  return $this->right_delimiter;
673    
674                                  case 'or':              case 'section':
675                                          $token = '||';                  array_push($this->_sectionelse_stack, false);
676                                          break;                  return $this->_compile_section_start($tag_args);
677    
678                                  case 'not':              case 'sectionelse':
679                                          $token = '!';                  $this->_sectionelse_stack[count($this->_sectionelse_stack)-1] = true;
680                                          break;                  return "<?php endfor; else: ?>";
681    
682                                  case 'mod':              case '/section':
683                                          $token = '%';                  if (array_pop($this->_sectionelse_stack))
684                                          break;                      return "<?php endif; ?>";
685                    else
686                                  case '(':                      return "<?php endfor; endif; ?>";
687                                          array_push($is_arg_stack, $i);  
688                                          break;              case 'config_load':
689                    return $this->_compile_config_load_tag($tag_args);
690                                  case 'is':  
691                                          /* If last token was a ')', we operate on the parenthesized              case 'strip':
692                                             expression. The start of the expression is on the stack.              case '/strip':
693                                             Otherwise, we operate on the last encountered token. */                  return $this->left_delimiter.$tag_command.$this->right_delimiter;
694                                          if ($tokens[$i-1] == ')')  
695                                                  $is_arg_start = array_pop($is_arg_stack);              case 'literal':
696                                          else                  list (,$literal_block) = each($this->_literal_blocks);
697                                                  $is_arg_start = $i-1;                  $this->_current_line_no += substr_count($literal_block, "\n");
698                                          /* Construct the argument for 'is' expression, so it knows                  return $literal_block;
699                                             what to operate on. */  
700                                          $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start));              case 'insert':
701                    return $this->_compile_insert_tag($tag_args);
702                                          /* Pass all tokens from next one until the end to the  
703                                             'is' expression parsing function. The function will              default:
704                                             return modified tokens, where the first one is the result                  if (isset($this->custom_funcs[$tag_command])) {
705                                             of the 'is' expression and the rest are the tokens it                      return $this->_compile_custom_tag($tag_command, $tag_args);
706                                             didn't touch. */                  } else {
707                                          $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));                      $this->_syntax_error("unknown tag - '$tag_command'", E_USER_WARNING);
708                        return;
709                                          /* Replace the old tokens with the new ones. */                  }
710                                          array_splice($tokens, $is_arg_start, count($tokens), $new_tokens);          }
711        }
712                                          /* Adjust argument start so that it won't change from the  
713                                             current position for the next iteration. */      function _compile_custom_tag($tag_command, $tag_args)
714                                          $i = $is_arg_start;      {
715                                          break;          $function = $this->custom_funcs[$tag_command];
716                          }  
717                  }          if (!function_exists($function)) {
718                $this->_syntax_error("custom function '$tag_command' is not implemented", E_USER_WARNING);
719                  if ($elseif)              return;
720                          return '<?php elseif ('.implode(' ', $tokens).'): ?>';          }
721                  else          
722                          return '<?php if ('.implode(' ', $tokens).'): ?>';          $attrs = $this->_parse_attrs($tag_args);
723          }          foreach ($attrs as $arg_name => $arg_value) {
724                if (is_bool($arg_value))
725          function _parse_is_expr($is_arg, $tokens)                  $arg_value = $arg_value ? 'true' : 'false';
726          {              $arg_list[] = "'$arg_name' => $arg_value";
727                  $expr_end = 0;          }
728    
729                  if (($first_token = array_shift($tokens)) == 'not') {          return "<?php $function(array(".implode(',', (array)$arg_list).")); ?>";
730                          $negate_expr = true;      }
731                          $expr_type = array_shift($tokens);  
732                  } else  
733                          $expr_type = $first_token;  /*======================================================================*\
734        Function: _compile_insert_tag
735                  switch ($expr_type) {      Purpose:  Compile {insert ...} tag
736                          case 'even':  \*======================================================================*/
737                                  if ($tokens[$expr_end] == 'by') {      function _compile_insert_tag($tag_args)
738                                          $expr_end++;      {
739                                          $expr_arg = $tokens[$expr_end++];          $attrs = $this->_parse_attrs($tag_args);
740                                          $expr = "!(($is_arg / $expr_arg) % $expr_arg)";          $name = substr($attrs['name'], 1, -1);
741                                  }  
742                                  else          if (empty($name)) {
743                                          $expr = "!($is_arg % 2)";              $this->_syntax_error("missing insert name");
744                                  break;          }
745    
746                          case 'odd':          foreach ($attrs as $arg_name => $arg_value) {
747                                  if ($tokens[$expr_end] == 'by') {              if (is_bool($arg_value))
748                                          $expr_end++;                  $arg_value = $arg_value ? 'true' : 'false';
749                                          $expr_arg = $tokens[$expr_end++];              $arg_list[] = "'$arg_name' => $arg_value";
750                                          $expr = "(($is_arg / $expr_arg) % $expr_arg)";          }
751                                  }  
752                                  else          return "<?php echo _smarty_insert_handler(array(".implode(', ', (array)$arg_list)."), \$this->caching, \$this->_smarty_md5); ?>\n";
753                                          $expr = "($is_arg % 2)";      }  
754                                  break;  
755    
756                          case 'div':  /*======================================================================*\
757                                  if ($tokens[$expr_end] == 'by') {      Function: _compile_config_load_tag
758                                          $expr_end++;      Purpose:  Compile {config_load ...} tag
759                                          $expr_arg = $tokens[$expr_end++];  \*======================================================================*/
760                                          $expr = "!($is_arg % $expr_arg)";      function _compile_config_load_tag($tag_args)
761                                  } else {      {
762                                          $this->_syntax_error("expecting 'by' after 'div'");          $attrs = $this->_parse_attrs($tag_args);
763                                  }  
764                                  break;          if (empty($attrs['file'])) {
765                $this->_syntax_error("missing 'file' attribute in config_load tag");
766                          default:          }
767                                  $this->_syntax_error("unknown 'is' expression - '$expr_type'");  
768                                  break;          $output  = "<?php if (!class_exists('Config_File'))\n" .
769                  }                     "    include_once 'Config_File.class.php';\n" .
770                       "if (!is_object(\$_conf_obj) || get_class(\$_conf_obj) != 'config_file') {\n" .
771                  if ($negate_expr) {                     "    \$_conf_obj  = new Config_File('".$this->config_dir."');\n" .
772                          $expr = "!($expr)";                     "}\n" .
773                  }                     "\$_config = array_merge((array)\$_config, \$_conf_obj->get(".$attrs['file']."));\n";
774    
775                  array_splice($tokens, 0, $expr_end, $expr);          if (!empty($attrs['section']))
776                $output .= '$_config = array_merge((array)$_config, $_conf_obj->get('.$attrs['file'].', '.$attrs['section'].')); ';
777                  return $tokens;  
778          }          $output .= '?>';
779    
780          function _parse_attrs($tag_args)          return $output;
781          {      }
782                  /* Tokenize tag attributes. */  
783                  preg_match_all('/(?:"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"       |  
784                                                    \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'     | (?>[^"\'=\s]+)  /*======================================================================*\
785                                                   )+ |      Function: _compile_include_tag
786                                                   [=]      Purpose:  Compile {include ...} tag
787                                              /x', $tag_args, $match);  \*======================================================================*/
788                  $tokens = $match[0];      function _compile_include_tag($tag_args)
789                  $var_delims = array('$', '#', '%');      {
790            $attrs = $this->_parse_attrs($tag_args);
791                  $attrs = array();  
792                  /* Parse state:          if (empty($attrs['file'])) {
793                          0 - expecting attr name              $this->_syntax_error("missing 'file' attribute in include tag");
794                          1 - expecting '=' or another attr name          } else
795                          2 - expecting attr value (not '=') */              $attrs['file'] = $this->_dequote($attrs['file']);
796                  $state = 0;  
797            if (count($attrs) > 1) {
798                  foreach ($tokens as $token) {              $include_func_name = uniqid("_include_");
799                          switch ($state) {              $include_file_name = $this->compile_dir.'/'.$attrs['file'];
800                                  case 0:  
801                                          /* If the token is a valid identifier, we set attribute name              foreach ($attrs as $arg_name => $arg_value) {
802                                             and go to state 1. */                  if ($arg_name == 'file') continue;
803                                          if (preg_match('!\w+!', $token)) {                  if (is_bool($arg_value))
804                                                  $attr_name = $token;                      $arg_value = $arg_value ? 'true' : 'false';
805                                                  $state = 1;                  $arg_list[] = "'$arg_name' => $arg_value";
806                                          } else              }
807                                                  $this->_syntax_error("invalid attribute name - '$token'");  
808                                          break;              return  "<?php " .
809                        "if (!function_exists('$include_func_name')) {\n".
810                                  case 1:                      "   function $include_func_name(\$file_name, \$def_vars, \$include_vars)\n" .
811                                          /* If the token is a valid identifier, the previously set                      "   {\n" .
812                                             attribute name does not need an argument. We put it in                      "       extract(\$def_vars);\n" .
813                                             the attrs array, set the new attribute name to the                      "       extract(\$include_vars);\n" .
814                                             current token and don't switch state.                      "       include \"\$file_name.php\";\n" .
815                        "   }\n" .
816                                             If the token is '=', then we go to state 2. */                      "}\n" .
817                                          if ($token == '=') {                      "$include_func_name(\"$include_file_name\", get_defined_vars(), array(".implode(',', (array)$arg_list)."));\n?>";
818                                                  $state = 2;          } else
819                                          } else               return '<?php include "'.$this->compile_dir.'/'.$attrs['file'].'.php"; ?>';
820                                                  $this->_syntax_error("expecting '=' after attribute name");      }
821                                          break;  
822    
823                                  case 2:  /*======================================================================*\
824                                          /* If token is not '=', we set the attribute value and go to      Function: _compile_section_start
825                                             state 0. */      Purpose:  Compile {section ...} tag
826                                          if ($token != '=') {  \*======================================================================*/
827                                                  /* We booleanize the token if it's a non-quoted possible      function _compile_section_start($tag_args)
828                                                     boolean value. */      {
829                                                  if (preg_match('!^(on|yes|true)$!', $token))          $attrs = $this->_parse_attrs($tag_args);
830                                                          $token = true;  
831                                                  else if (preg_match('!^(off|no|false)$!', $token))          $output = "<?php ";
832                                                          $token = false;          $section_name = $attrs['name'];
833                                                  /* If the token is not variable (doesn't start with          if (empty($section_name)) {
834                                                     '$', '#', or '%') and not enclosed in single or              $this->_syntax_error("missing section name");
835                                                     double quotes we single-quote it. */          }
836                                                  else if (!in_array($token{0}, $var_delims) &&  
837                                                                   !(($token{0} == '"' || $token[0] == "'") &&          $output .= "unset(\$_sections[$section_name]);\n";
838                                                                   $token{strlen($token)-1} == $token{0}))          $section_props = "\$_sections[$section_name]['properties']";
839                                                          $token = "'".$token."'";  
840            foreach ($attrs as $attr_name => $attr_value) {
841                                                  $attrs[$attr_name] = $token;              switch ($attr_name) {
842                                                  $state = 0;                  case 'loop':
843                                          } else                      $output .= "{$section_props}['loop'] = is_array($attr_value) ? count($attr_value) : $attr_value;\n";
844                                                  $this->_syntax_error("'=' cannot be an attribute value");                      break;
845                                          break;  
846                          }                  case 'show':
847                  }                      if (is_bool($attr_value))
848                            $attr_value = $attr_value ? 'true' : 'false';
849                  $this->_parse_vars_props($attrs);                      $output .= "{$section_props}['$attr_name'] = $attr_value;\n";
850                        break;
851                  return $attrs;  
852          }                  default:
853                        $output .= "{$section_props}['$attr_name'] = $attr_value;\n";
854          function _preg_grep($pattern, $array)                      break;
855          {              }
856                  $result = array();          }
857    
858                  foreach ($array as $key => $entry) {          if (isset($attrs['loop'])) {
859                          if (preg_match($pattern, $entry))              $loop_check_code = "{$section_props}['loop'] > 0 && ";
860                                  $result[$key] = $entry;          } else {
861                  }              $output .= "{$section_props}['loop'] = 1;\n";
862            }
863                  return $result;  
864          }          if (isset($attrs['show'])) {
865                        $show_check_code = "{$section_props}['show'] && ";
866          function _parse_vars_props(&$tokens)          } else {
867          {              $output .= "{$section_props}['show'] = {$section_props}['loop'] > 0;\n";
868                  /* preg_grep() was fixed to return keys properly in 4.0.4 and later. To          }
869                     allow people to use older versions of PHP we emulate preg_grep() and  
870                     use the version check to see what function to call. */          $output .= "if ($loop_check_code $show_check_code true): ";
871                  if (strnatcmp(PHP_VERSION, '4.0.4') >= 0) {  
872                          $var_exprs = preg_grep('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:[^|]+)?)*$!', $tokens);          $output .= "
873                          $conf_var_exprs = preg_grep('!^#(\w+)#(?>\|@?\w+(:[^|]+)?)*$!', $tokens);              for ({$section_props}['index'] = 0;
874                          $sect_prop_exprs = preg_grep('!^%\w+\.\w+%(?>\|@?\w+(:[^|]+)?)*$!', $tokens);                   {$section_props}['index'] < {$section_props}['loop'];
875                  } else {                   {$section_props}['index']++):\n";
876                          $var_exprs = $this->_preg_grep('!^\$(\w+/)*\w+(?>\.\w+)*(?>\|@?\w+(:[^|]+)?)*$!', $tokens);          $output .= "{$section_props}['rownum'] = {$section_props}['index'] + 1;\n";
877                          $conf_var_exprs = $this->_preg_grep('!^#(\w+)#(?>\|@?\w+(:[^|]+)?)*$!', $tokens);  
878                          $sect_prop_exprs = $this->_preg_grep('!^%\w+\.\w+%(?>\|@?\w+(:[^|]+)?)*$!', $tokens);          $output .= "?>";
879                  }  
880            return $output;
881                  if (count($var_exprs)) {      }
882                          foreach ($var_exprs as $expr_index => $var_expr) {  
883                                  $tokens[$expr_index] = $this->_parse_var($var_expr);  
884                          }  /*======================================================================*\
885                  }      Function: _compile_if_tag
886                        Purpose:  Compile {if ...} tag
887                  if (count($conf_var_exprs)) {  \*======================================================================*/
888                          foreach ($conf_var_exprs as $expr_index => $var_expr) {      function _compile_if_tag($tag_args, $elseif = false)
889                                  $tokens[$expr_index] = $this->_parse_conf_var($var_expr);      {
890                          }          /* Tokenize args for 'if' tag. */
891                  }          preg_match_all('/(?:
892                             "[^"\\\\]*(?:\\\\.[^"\\\\]*)*"         | # match all double quoted strings allowed escaped double quotes
893                  if (count($sect_prop_exprs)) {                           \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'     | # match all single quoted strings allowed escaped single quotes
894                          foreach ($sect_prop_exprs as $expr_index => $section_prop_expr) {                           [()]                                   | # match parentheses
895                                  $tokens[$expr_index] = $this->_parse_section_prop($section_prop_expr);                           [^"\'\s()]+                              # match any other token that is not any of the above
896                          }                          )/x', $tag_args, $match);
897                  }          $tokens = $match[0];
898          }  
899            $this->_parse_vars_props($tokens);
900          function _parse_var($var_expr)  
901          {          $is_arg_stack = array();
902                  $modifiers = explode('|', substr($var_expr, 1));          
903            for ($i = 0; $i < count($tokens); $i++) {
904                  $sections = explode('/', array_shift($modifiers));              $token = &$tokens[$i];
905                  $props = explode('.', array_pop($sections));              switch ($token) {
906                  $var_name = array_shift($props);                  case 'eq':
907                        $token = '==';
908                  $output = "\$$var_name";                      break;
909    
910                  foreach ($sections as $section) {                  case 'ne':
911                          $output .= "[\$_sections['$section']['properties']['index']]";                  case 'neq':
912                  }                      $token = '!=';
913                  foreach ($props as $prop) {                      break;
914                          $output .= "['$prop']";  
915                  }                  case 'lt':
916                        $token = '<';
917                  $this->_parse_modifiers($output, $modifiers);                      break;
918    
919                  return $output;                  case 'le':
920          }                  case 'lte':
921                        $token = '<=';
922          function _parse_conf_var($conf_var_expr)                      break;
923          {  
924                  $modifiers = explode('|', $conf_var_expr);                  case 'gt':
925                        $token = '>';
926                  $var_name = substr(array_shift($modifiers), 1, -1);                      break;
927                    
928                  $output = "\$_config['$var_name']";                  case 'ge':
929                    case 'gte':
930                  $this->_parse_modifiers($output, $modifiers);                      $token = '>=';
931                        break;
932                  return $output;  
933          }                  case 'and':
934                        $token = '&&';
935          function _parse_section_prop($section_prop_expr)                      break;
936          {  
937                  $modifiers = explode('|', $section_prop_expr);                  case 'or':
938                        $token = '||';
939                  preg_match('!%(\w+)\.(\w+)%!', array_shift($modifiers), $match);                      break;
940                  $section_name = $match[1];  
941                  $prop_name = $match[2];                  case 'not':
942                        $token = '!';
943                  $output = "\$_sections['$section_name']['properties']['$prop_name']";                      break;
944    
945                  $this->_parse_modifiers($output, $modifiers);                  case 'mod':
946                        $token = '%';
947                  return $output;                      break;
948          }  
949                    case '(':
950          function _parse_modifiers(&$output, $modifiers)                      array_push($is_arg_stack, $i);
951          {                      break;
952                  foreach ($modifiers as $modifier) {  
953                          $modifier = explode(':', $modifier);                  case 'is':
954                          $modifier_name = array_shift($modifier);                      /* If last token was a ')', we operate on the parenthesized
955                           expression. The start of the expression is on the stack.
956                          if ($modifier_name{0} == '@') {                         Otherwise, we operate on the last encountered token. */
957                                  $map_array = 'false';                      if ($tokens[$i-1] == ')')
958                                  $modifier_name = substr($modifier_name, 1);                          $is_arg_start = array_pop($is_arg_stack);
959                          } else                      else
960                                  $map_array = 'true';                          $is_arg_start = $i-1;
961                        /* Construct the argument for 'is' expression, so it knows
962                          /*                         what to operate on. */
963                           * First we lookup the modifier function name in the registered                      $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start));
964                           * modifiers table.  
965                           */                      /* Pass all tokens from next one until the end to the
966                          $mod_func_name = $this->custom_mods[$modifier_name];                         'is' expression parsing function. The function will
967                           return modified tokens, where the first one is the result
968                          /*                         of the 'is' expression and the rest are the tokens it
969                           * If we don't find that modifier there, we assume it's just a PHP                         didn't touch. */
970                           * function name.                      $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));
971                           */  
972                          if (!isset($mod_func_name))                      /* Replace the old tokens with the new ones. */
973                                  $mod_func_name = $modifier_name;                      array_splice($tokens, $is_arg_start, count($tokens), $new_tokens);
974    
975                          $this->_parse_vars_props($modifier);                      /* Adjust argument start so that it won't change from the
976                           current position for the next iteration. */
977                          if (count($modifier) > 0)                      $i = $is_arg_start;
978                                  $modifier_args = ', '.implode(', ', $modifier);                      break;
979                          else              }
980                                  $modifier_args = '';          }
981    
982                          $output = "_smarty_mod_handler('$mod_func_name', $map_array, $output$modifier_args)";          if ($elseif)
983                  }              return '<?php elseif ('.implode(' ', $tokens).'): ?>';
984          }          else
985                        return '<?php if ('.implode(' ', $tokens).'): ?>';
986        }
987  /*======================================================================*\  
988          Function: _dequote      function _parse_is_expr($is_arg, $tokens)
989          Purpose:  Remove starting and ending quotes from the string      {
990  \*======================================================================*/          $expr_end = 0;
991          function _dequote($string)  
992          {          if (($first_token = array_shift($tokens)) == 'not') {
993                  if (($string{0} == "'" || $string{0} == '"') &&              $negate_expr = true;
994                          $string{strlen($string)-1} == $string{0})              $expr_type = array_shift($tokens);
995                          return substr($string, 1, -1);          } else
996          }              $expr_type = $first_token;
997    
998                    switch ($expr_type) {
999  /*======================================================================*\              case 'even':
1000          Function:       _read_file()                  if ($tokens[$expr_end] == 'by') {
1001          Purpose:        read in a file                      $expr_end++;
1002  \*======================================================================*/                      $expr_arg = $tokens[$expr_end++];
1003                        $expr = "!(($is_arg / $expr_arg) % $expr_arg)";
1004          function _read_file($filename)                  }
1005          {                  else
1006                  if(!($fd = fopen($filename, 'r'))) {                      $expr = "!($is_arg % 2)";
1007                          $this->_set_error_msg("problem reading '$filename.'");                  break;
1008                          return false;  
1009                  }              case 'odd':
1010                  $contents = fread($fd, filesize($filename));                  if ($tokens[$expr_end] == 'by') {
1011                  fclose($fd);                      $expr_end++;
1012                  return $contents;                      $expr_arg = $tokens[$expr_end++];
1013          }                      $expr = "(($is_arg / $expr_arg) % $expr_arg)";
1014                    }
1015  /*======================================================================*\                  else
1016          Function:       _write_file()                      $expr = "($is_arg % 2)";
1017          Purpose:        write out a file                  break;
1018  \*======================================================================*/  
1019                case 'div':
1020          function _write_file($filename,$contents)                  if ($tokens[$expr_end] == 'by') {
1021          {                      $expr_end++;
1022                  if(!($fd = fopen($filename, 'w'))) {                      $expr_arg = $tokens[$expr_end++];
1023                          $this->_set_error_msg("problem writing '$filename.'");                      $expr = "!($is_arg % $expr_arg)";
1024                          return false;                  } else {
1025                  }                      $this->_syntax_error("expecting 'by' after 'div'");
1026                  fwrite($fd, $contents);                  }
1027                  fclose($fd);                  break;
1028                  return true;  
1029          }              default:
1030                    $this->_syntax_error("unknown 'is' expression - '$expr_type'");
1031  /*======================================================================*\                  break;
1032          Function:       _set_error_msg()          }
1033          Purpose:        set the error message  
1034  \*======================================================================*/          if ($negate_expr) {
1035                $expr = "!($expr)";
1036          function _set_error_msg($error_msg)          }
1037          {  
1038                  $this->_error_msg="smarty error: $error_msg";          array_splice($tokens, 0, $expr_end, $expr);
1039                  return true;  
1040          }          return $tokens;
1041        }
1042  /*======================================================================*\  
1043          Function: _syntax_error  
1044          Purpose:  display Smarty syntax error  /*======================================================================*\
1045  \*======================================================================*/      Function: _parse_attrs
1046          function _syntax_error($error_msg, $error_type = E_USER_ERROR)      Purpose:  Parse attribute string
1047          {  \*======================================================================*/
1048                  trigger_error("Smarty: [in " . $this->_current_file . " line " .      function _parse_attrs($tag_args, $quote = true)
1049                                            $this->_current_line_no . "]: syntax error: $error_msg", $error_type);      {
1050          }          /* Tokenize tag attributes. */
1051            preg_match_all('/(?:"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"       |
1052                              \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'     | (?>[^"\'=\s]+)
1053                             )+ |
1054                             [=]
1055                            /x', $tag_args, $match);
1056            $tokens       = $match[0];
1057            $var_delims   = array('$', '#', '%');
1058    
1059            $attrs = array();
1060            /* Parse state:
1061                0 - expecting attribute name
1062                1 - expecting '='
1063                2 - expecting attribute value (not '=') */
1064            $state = 0;
1065    
1066            foreach ($tokens as $token) {
1067                switch ($state) {
1068                    case 0:
1069                        /* If the token is a valid identifier, we set attribute name
1070                           and go to state 1. */
1071                        if (preg_match('!^\w+$!', $token)) {
1072                            $attr_name = $token;
1073                            $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.1.1  
changed lines
  Added in v.1.5

  ViewVC Help
Powered by ViewVC 1.1.26