Issues (4069)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

include/Smarty/Smarty_Compiler.class.php (15 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/**
4
 * Project:     Smarty: the PHP compiling template engine
5
 * File:        Smarty_Compiler.class.php
6
 *
7
 * This library is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU Lesser General Public
9
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
11
 *
12
 * This library is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 * Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library; if not, write to the Free Software
19
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
 *
21
 * @link http://smarty.php.net/
22
 * @author Monte Ohrt <monte at ohrt dot com>
23
 * @author Andrei Zmievski <[email protected]>
24
 * @version 2.6.29
25
 * @copyright 2001-2005 New Digital Group, Inc.
26
 * @package Smarty
27
 */
28
29
/* $Id$ */
30
31
/**
32
 * Template compiling class
33
 * @package Smarty
34
 */
35
class Smarty_Compiler extends Smarty {
36
37
    // internal vars
38
    /**#@+
39
     * @access private
40
     */
41
    var $_folded_blocks         =   array();    // keeps folded template blocks
42
    var $_current_file          =   null;       // the current template being compiled
43
    var $_current_line_no       =   1;          // line number for error messages
44
    var $_capture_stack         =   array();    // keeps track of nested capture buffers
45
    var $_plugin_info           =   array();    // keeps track of plugins to load
46
    var $_init_smarty_vars      =   false;
47
    var $_permitted_tokens      =   array('true','false','yes','no','on','off','null');
48
    var $_db_qstr_regexp        =   null;        // regexps are setup in the constructor
49
    var $_si_qstr_regexp        =   null;
50
    var $_qstr_regexp           =   null;
51
    var $_func_regexp           =   null;
52
    var $_reg_obj_regexp        =   null;
53
    var $_var_bracket_regexp    =   null;
54
    var $_num_const_regexp      =   null;
55
    var $_dvar_guts_regexp      =   null;
56
    var $_dvar_regexp           =   null;
57
    var $_cvar_regexp           =   null;
58
    var $_svar_regexp           =   null;
59
    var $_avar_regexp           =   null;
60
    var $_mod_regexp            =   null;
61
    var $_var_regexp            =   null;
62
    var $_parenth_param_regexp  =   null;
63
    var $_func_call_regexp      =   null;
64
    var $_obj_ext_regexp        =   null;
65
    var $_obj_start_regexp      =   null;
66
    var $_obj_params_regexp     =   null;
67
    var $_obj_call_regexp       =   null;
68
    var $_cacheable_state       =   0;
69
    var $_cache_attrs_count     =   0;
70
    var $_nocache_count         =   0;
71
    var $_cache_serial          =   null;
72
    var $_cache_include         =   null;
73
74
    var $_strip_depth           =   0;
75
    var $_additional_newline    =   "\n";
76
77
    /**#@-*/
78
    /**
79
     * The class constructor.
80
     */
81 10
    public function __construct()
82
    {
83
        // matches double quoted strings:
84
        // "foobar"
85
        // "foo\"bar"
86 10
        $this->_db_qstr_regexp = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
87
88
        // matches single quoted strings:
89
        // 'foobar'
90
        // 'foo\'bar'
91 10
        $this->_si_qstr_regexp = '\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'';
92
93
        // matches single or double quoted strings
94 10
        $this->_qstr_regexp = '(?:' . $this->_db_qstr_regexp . '|' . $this->_si_qstr_regexp . ')';
95
96
        // matches bracket portion of vars
97
        // [0]
98
        // [foo]
99
        // [$bar]
100 10
        $this->_var_bracket_regexp = '\[\$?[\w\.]+\]';
101
102
        // matches numerical constants
103
        // 30
104
        // -12
105
        // 13.22
106 10
        $this->_num_const_regexp = '(?:\-?\d+(?:\.\d+)?)';
107
108
        // matches $ vars (not objects):
109
        // $foo
110
        // $foo.bar
111
        // $foo.bar.foobar
112
        // $foo[0]
113
        // $foo[$bar]
114
        // $foo[5][blah]
115
        // $foo[5].bar[$foobar][4]
116 10
        $this->_dvar_math_regexp = '(?:[\+\*\/\%]|(?:-(?!>)))';
117 10
        $this->_dvar_math_var_regexp = '[\$\w\.\+\-\*\/\%\d\>\[\]]';
118 10
        $this->_dvar_guts_regexp = '\w+(?:' . $this->_var_bracket_regexp
119 10
                . ')*(?:\.\$?\w+(?:' . $this->_var_bracket_regexp . ')*)*(?:' . $this->_dvar_math_regexp . '(?:' . $this->_num_const_regexp . '|' . $this->_dvar_math_var_regexp . ')*)?';
120 10
        $this->_dvar_regexp = '\$' . $this->_dvar_guts_regexp;
121
122
        // matches config vars:
123
        // #foo#
124
        // #foobar123_foo#
125 10
        $this->_cvar_regexp = '\#\w+\#';
126
127
        // matches section vars:
128
        // %foo.bar%
129 10
        $this->_svar_regexp = '\%\w+\.\w+\%';
130
131
        // matches all valid variables (no quotes, no modifiers)
132 10
        $this->_avar_regexp = '(?:' . $this->_dvar_regexp . '|'
133 10
           . $this->_cvar_regexp . '|' . $this->_svar_regexp . ')';
134
135
        // matches valid variable syntax:
136
        // $foo
137
        // $foo
138
        // #foo#
139
        // #foo#
140
        // "text"
141
        // "text"
142 10
        $this->_var_regexp = '(?:' . $this->_avar_regexp . '|' . $this->_qstr_regexp . ')';
143
144
        // matches valid object call (one level of object nesting allowed in parameters):
145
        // $foo->bar
146
        // $foo->bar()
147
        // $foo->bar("text")
148
        // $foo->bar($foo, $bar, "text")
149
        // $foo->bar($foo, "foo")
150
        // $foo->bar->foo()
151
        // $foo->bar->foo->bar()
152
        // $foo->bar($foo->bar)
153
        // $foo->bar($foo->bar())
154
        // $foo->bar($foo->bar($blah,$foo,44,"foo",$foo[0].bar))
155 10
        $this->_obj_ext_regexp = '\->(?:\$?' . $this->_dvar_guts_regexp . ')';
156 10
        $this->_obj_restricted_param_regexp = '(?:'
157 10
                . '(?:' . $this->_var_regexp . '|' . $this->_num_const_regexp . ')(?:' . $this->_obj_ext_regexp . '(?:\((?:(?:' . $this->_var_regexp . '|' . $this->_num_const_regexp . ')'
158 10
                . '(?:\s*,\s*(?:' . $this->_var_regexp . '|' . $this->_num_const_regexp . '))*)?\))?)*)';
159 10
        $this->_obj_single_param_regexp = '(?:\w+|' . $this->_obj_restricted_param_regexp . '(?:\s*,\s*(?:(?:\w+|'
160 10
                . $this->_var_regexp . $this->_obj_restricted_param_regexp . ')))*)';
161 10
        $this->_obj_params_regexp = '\((?:' . $this->_obj_single_param_regexp
162 10
                . '(?:\s*,\s*' . $this->_obj_single_param_regexp . ')*)?\)';
163 10
        $this->_obj_start_regexp = '(?:' . $this->_dvar_regexp . '(?:' . $this->_obj_ext_regexp . ')+)';
164 10
        $this->_obj_call_regexp = '(?:' . $this->_obj_start_regexp . '(?:' . $this->_obj_params_regexp . ')?(?:' . $this->_dvar_math_regexp . '(?:' . $this->_num_const_regexp . '|' . $this->_dvar_math_var_regexp . ')*)?)';
165
        
166
        // matches valid modifier syntax:
167
        // |foo
168
        // |@foo
169
        // |foo:"bar"
170
        // |foo:$bar
171
        // |foo:"bar":$foobar
172
        // |foo|bar
173
        // |foo:$foo->bar
174 10
        $this->_mod_regexp = '(?:\|@?\w+(?::(?:\w+|' . $this->_num_const_regexp . '|'
175 10
           . $this->_obj_call_regexp . '|' . $this->_avar_regexp . '|' . $this->_qstr_regexp .'))*)';
176
177
        // matches valid function name:
178
        // foo123
179
        // _foo_bar
180 10
        $this->_func_regexp = '[a-zA-Z_]\w*';
181
182
        // matches valid registered object:
183
        // foo->bar
184 10
        $this->_reg_obj_regexp = '[a-zA-Z_]\w*->[a-zA-Z_]\w*';
185
186
        // matches valid parameter values:
187
        // true
188
        // $foo
189
        // $foo|bar
190
        // #foo#
191
        // #foo#|bar
192
        // "text"
193
        // "text"|bar
194
        // $foo->bar
195 10
        $this->_param_regexp = '(?:\s*(?:' . $this->_obj_call_regexp . '|'
196 10
           . $this->_var_regexp . '|' . $this->_num_const_regexp  . '|\w+)(?>' . $this->_mod_regexp . '*)\s*)';
197
198
        // matches valid parenthesised function parameters:
199
        //
200
        // "text"
201
        //    $foo, $bar, "text"
202
        // $foo|bar, "foo"|bar, $foo->bar($foo)|bar
203 10
        $this->_parenth_param_regexp = '(?:\((?:\w+|'
204 10
                . $this->_param_regexp . '(?:\s*,\s*(?:(?:\w+|'
205 10
                . $this->_param_regexp . ')))*)?\))';
206
207
        // matches valid function call:
208
        // foo()
209
        // foo_bar($foo)
210
        // _foo_bar($foo,"bar")
211
        // foo123($foo,$foo->bar(),"foo")
212 10
        $this->_func_call_regexp = '(?:' . $this->_func_regexp . '\s*(?:'
213 10
           . $this->_parenth_param_regexp . '))';
214 10
    }
215
216
    /**
217
     * compile a resource
218
     *
219
     * sets $compiled_content to the compiled source
220
     * @param string $resource_name
221
     * @param string $source_content
222
     * @param string $compiled_content
223
     * @return true
224
     */
225 10
    function _compile_file($resource_name, $source_content, &$compiled_content)
226
    {
227
228 10
        if ($this->security) {
229
            // do not allow php syntax to be executed unless specified
230
            if ($this->php_handling == SMARTY_PHP_ALLOW &&
231
                !$this->security_settings['PHP_HANDLING']) {
232
                $this->php_handling = SMARTY_PHP_PASSTHRU;
233
            }
234
        }
235
236 10
        $this->_load_filters();
237
238 10
        $this->_current_file = $resource_name;
239 10
        $this->_current_line_no = 1;
240 10
        $ldq = preg_quote($this->left_delimiter, '~');
241 10
        $rdq = preg_quote($this->right_delimiter, '~');
242
243
        // run template source through prefilter functions
244 10
        if (count($this->_plugins['prefilter']) > 0) {
245
            foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) {
246
                if ($prefilter === false) continue;
247
                if ($prefilter[3] || is_callable($prefilter[0])) {
248
                    $source_content = call_user_func_array($prefilter[0],
249
                                                            array($source_content, &$this));
250
                    $this->_plugins['prefilter'][$filter_name][3] = true;
251
                } else {
252
                    $this->_trigger_fatal_error("[plugin] prefilter '$filter_name' is not implemented");
253
                }
254
            }
255
        }
256
257
        /* fetch all special blocks */
258 10
        $search = "~{$ldq}\*(.*?)\*{$rdq}|{$ldq}\s*literal\s*{$rdq}(.*?){$ldq}\s*/literal\s*{$rdq}|{$ldq}\s*php\s*{$rdq}(.*?){$ldq}\s*/php\s*{$rdq}~s";
259
260 10
        preg_match_all($search, $source_content, $match,  PREG_SET_ORDER);
261 10
        $this->_folded_blocks = $match;
0 ignored issues
show
Documentation Bug introduced by
It seems like $match can be null. However, the property $_folded_blocks is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
262 10
        reset($this->_folded_blocks);
263
264
        /* replace special blocks by "{php}" */
265 10
        $source_content = preg_replace_callback($search, create_function ('$matches', "return '"
0 ignored issues
show
Security Best Practice introduced by
The use of create_function is highly discouraged, better use a closure.

create_function can pose a great security vulnerability as it is similar to eval, and could be used for arbitrary code execution. We highly recommend to use a closure instead.

// Instead of
$function = create_function('$a, $b', 'return $a + $b');

// Better use
$function = function($a, $b) { return $a + $b; }
Loading history...
266 10
                                       . $this->_quote_replace($this->left_delimiter) . 'php'
267 10
                                       . "' . str_repeat(\"\n\", substr_count('\$matches[1]', \"\n\")) .'"
268 10
                                       . $this->_quote_replace($this->right_delimiter)
269 10
                                       . "';")
270
                                       , $source_content);
271
272
        /* Gather all template tags. */
273 10
        preg_match_all("~{$ldq}\s*(.*?)\s*{$rdq}~s", $source_content, $_match);
274 10
        $template_tags = $_match[1];
275
        /* Split content by template tags to obtain non-template content. */
276 10
        $text_blocks = preg_split("~{$ldq}.*?{$rdq}~s", $source_content);
277
278
        /* loop through text blocks */
279 10
        for ($curr_tb = 0, $for_max = count($text_blocks); $curr_tb < $for_max; $curr_tb++) {
280
            /* match anything resembling php tags */
281 10
            if (preg_match_all('~(<\?(?:\w+|=)?|\?>|language\s*=\s*[\"\']?\s*php\s*[\"\']?)~is', $text_blocks[$curr_tb], $sp_match)) {
282
                /* replace tags with placeholders to prevent recursive replacements */
283
                $sp_match[1] = array_unique($sp_match[1]);
284
                usort($sp_match[1], '_smarty_sort_length');
285
                for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) {
286
                    $text_blocks[$curr_tb] = str_replace($sp_match[1][$curr_sp],'%%%SMARTYSP'.$curr_sp.'%%%',$text_blocks[$curr_tb]);
287
                }
288
                /* process each one */
289
                for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) {
290
                    if ($this->php_handling == SMARTY_PHP_PASSTHRU) {
291
                        /* echo php contents */
292
                        $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '<?php echo \''.str_replace("'", "\'", $sp_match[1][$curr_sp]).'\'; ?>'."\n", $text_blocks[$curr_tb]);
293
                    } else if ($this->php_handling == SMARTY_PHP_QUOTE) {
294
                        /* quote php tags */
295
                        $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', htmlspecialchars($sp_match[1][$curr_sp]), $text_blocks[$curr_tb]);
296
                    } else if ($this->php_handling == SMARTY_PHP_REMOVE) {
297
                        /* remove php tags */
298
                        $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '', $text_blocks[$curr_tb]);
299
                    } else {
300
                        /* SMARTY_PHP_ALLOW, but echo non php starting tags */
301
                        $sp_match[1][$curr_sp] = preg_replace('~(<\?(?!php|=|$))~i', '<?php echo \'\\1\'?>'."\n", $sp_match[1][$curr_sp]);
302
                        $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', $sp_match[1][$curr_sp], $text_blocks[$curr_tb]);
303
                    }
304
                }
305
            }
306
        }
307
        
308
        /* Compile the template tags into PHP code. */
309 10
        $compiled_tags = array();
310 10
        for ($i = 0, $for_max = count($template_tags); $i < $for_max; $i++) {
311 10
            $this->_current_line_no += substr_count($text_blocks[$i], "\n");
312 10
            $compiled_tags[] = $this->_compile_tag($template_tags[$i]);
313 10
            $this->_current_line_no += substr_count($template_tags[$i], "\n");
314
        }
315 10
        if (count($this->_tag_stack)>0) {
316
            list($_open_tag, $_line_no) = end($this->_tag_stack);
317
            $this->_syntax_error("unclosed tag \{$_open_tag} (opened line $_line_no).", E_USER_ERROR, __FILE__, __LINE__);
318
            return;
319
        }
320
321
        /* Reformat $text_blocks between 'strip' and '/strip' tags,
322
           removing spaces, tabs and newlines. */
323 10
        $strip = false;
324 10
        for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) {
325 10
            if ($compiled_tags[$i] == '{strip}') {
326 2
                $compiled_tags[$i] = '';
327 2
                $strip = true;
328
                /* remove leading whitespaces */
329 2
                $text_blocks[$i + 1] = ltrim($text_blocks[$i + 1]);
330
            }
331 10
            if ($strip) {
332
                /* strip all $text_blocks before the next '/strip' */
333 2
                for ($j = $i + 1; $j < $for_max; $j++) {
334
                    /* remove leading and trailing whitespaces of each line */
335 2
                    $text_blocks[$j] = preg_replace('![\t ]*[\r\n]+[\t ]*!', '', $text_blocks[$j]);
336 2
                    if ($compiled_tags[$j] == '{/strip}') {                       
337
                        /* remove trailing whitespaces from the last text_block */
338 2
                        $text_blocks[$j] = rtrim($text_blocks[$j]);
339
                    }
340 2
                    $text_blocks[$j] = "<?php echo '" . strtr($text_blocks[$j], array("'"=>"\'", "\\"=>"\\\\")) . "'; ?>";
341 2
                    if ($compiled_tags[$j] == '{/strip}') {
342 2
                        $compiled_tags[$j] = "\n"; /* slurped by php, but necessary
343
                                    if a newline is following the closing strip-tag */
344 2
                        $strip = false;
345 2
                        $i = $j;
346 2
                        break;
347
                    }
348
                }
349
            }
350
        }
351 10
        $compiled_content = '';
352
        
353 10
        $tag_guard = '%%%SMARTYOTG' . md5(uniqid(rand(), true)) . '%%%';
354
        
355
        /* Interleave the compiled contents and text blocks to get the final result. */
356 10
        for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) {
357 10
            if ($compiled_tags[$i] == '') {
358
                // tag result empty, remove first newline from following text block
359 8
                $text_blocks[$i+1] = preg_replace('~^(\r\n|\r|\n)~', '', $text_blocks[$i+1]);
360
            }
361
            // replace legit PHP tags with placeholder
362 10
            $text_blocks[$i] = str_replace('<?', $tag_guard, $text_blocks[$i]);
363 10
            $compiled_tags[$i] = str_replace('<?', $tag_guard, $compiled_tags[$i]);
364
            
365 10
            $compiled_content .= $text_blocks[$i] . $compiled_tags[$i];
366
        }
367 10
        $compiled_content .= str_replace('<?', $tag_guard, $text_blocks[$i]);
368
369
        // escape php tags created by interleaving
370 10
        $compiled_content = str_replace('<?', "<?php echo '<?' ?>\n", $compiled_content);
371 10
        $compiled_content = preg_replace("~(?<!')language\s*=\s*[\"\']?\s*php\s*[\"\']?~", "<?php echo 'language=php' ?>\n", $compiled_content);
372
373
        // recover legit tags
374 10
        $compiled_content = str_replace($tag_guard, '<?', $compiled_content); 
375
        
376
        // remove \n from the end of the file, if any
377 10
        if (strlen($compiled_content) && (substr($compiled_content, -1) == "\n") ) {
378 8
            $compiled_content = substr($compiled_content, 0, -1);
379
        }
380
381 10
        if (!empty($this->_cache_serial)) {
382
            $compiled_content = "<?php \$this->_cache_serials['".$this->_cache_include."'] = '".$this->_cache_serial."'; ?>" . $compiled_content;
383
        }
384
385
        // run compiled template through postfilter functions
386 10
        if (count($this->_plugins['postfilter']) > 0) {
387
            foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) {
388
                if ($postfilter === false) continue;
389
                if ($postfilter[3] || is_callable($postfilter[0])) {
390
                    $compiled_content = call_user_func_array($postfilter[0],
391
                                                              array($compiled_content, &$this));
392
                    $this->_plugins['postfilter'][$filter_name][3] = true;
393
                } else {
394
                    $this->_trigger_fatal_error("Smarty plugin error: postfilter '$filter_name' is not implemented");
395
                }
396
            }
397
        }
398
399
        // put header at the top of the compiled template
400 10
        $template_header = "<?php /* Smarty version ".$this->_version.", created on ".strftime("%Y-%m-%d %H:%M:%S")."\n";
401 10
        $template_header .= "         compiled from ".strtr(urlencode($resource_name), array('%2F'=>'/', '%3A'=>':'))." */ ?>\n";
402
403
        /* Emit code to load needed plugins. */
404 10
        $this->_plugins_code = '';
405 10
        if (count($this->_plugin_info)) {
406 9
            $_plugins_params = "array('plugins' => array(";
407 9
            foreach ($this->_plugin_info as $plugin_type => $plugins) {
408 9
                foreach ($plugins as $plugin_name => $plugin_info) {
409 9
                    $_plugins_params .= "array('$plugin_type', '$plugin_name', '" . strtr($plugin_info[0], array("'" => "\\'", "\\" => "\\\\")) . "', $plugin_info[1], ";
410 9
                    $_plugins_params .= $plugin_info[2] ? 'true),' : 'false),';
411
                }
412
            }
413 9
            $_plugins_params .= '))';
414 9
            $plugins_code = "<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');\nsmarty_core_load_plugins($_plugins_params, \$this); ?>\n";
415 9
            $template_header .= $plugins_code;
416 9
            $this->_plugin_info = array();
417 9
            $this->_plugins_code = $plugins_code;
418
        }
419
420 10
        if ($this->_init_smarty_vars) {
421
            $template_header .= "<?php require_once(SMARTY_CORE_DIR . 'core.assign_smarty_interface.php');\nsmarty_core_assign_smarty_interface(null, \$this); ?>\n";
422
            $this->_init_smarty_vars = false;
423
        }
424
425 10
        $compiled_content = $template_header . $compiled_content;
426 10
        return true;
427
    }
428
429
    /**
430
     * Compile a template tag
431
     *
432
     * @param string $template_tag
433
     * @return string
434
     */
435 10
    function _compile_tag($template_tag)
436
    {
437
        /* Matched comment. */
438 10
        if (substr($template_tag, 0, 1) == '*' && substr($template_tag, -1) == '*')
439
            return '';
440
        
441
        /* Split tag into two three parts: command, command modifiers and the arguments. */
442 10
        if(! preg_match('~^(?:(' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_var_regexp
443 10
                . '|\/?' . $this->_reg_obj_regexp . '|\/?' . $this->_func_regexp . ')(' . $this->_mod_regexp . '*))
444
                      (?:\s+(.*))?$
445 10
                    ~xs', $template_tag, $match)) {
446
            $this->_syntax_error("unrecognized tag: $template_tag", E_USER_ERROR, __FILE__, __LINE__);
447
        }
448
        
449 10
        $tag_command = $match[1];
450 10
        $tag_modifier = isset($match[2]) ? $match[2] : null;
451 10
        $tag_args = isset($match[3]) ? $match[3] : null;
452
453 10
        if (preg_match('~^' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '$~', $tag_command)) {
454
            /* tag name is a variable or object */
455 10
            $_return = $this->_parse_var_props($tag_command . $tag_modifier);
456 10
            return "<?php echo $_return; ?>" . $this->_additional_newline;
457
        }
458
459
        /* If the tag name is a registered object, we process it. */
460 10
        if (preg_match('~^\/?' . $this->_reg_obj_regexp . '$~', $tag_command)) {
461
            return $this->_compile_registered_object_tag($tag_command, $this->_parse_attrs($tag_args), $tag_modifier);
462
        }
463
464
        switch ($tag_command) {
465 10
            case 'include':
466 5
                return $this->_compile_include_tag($tag_args);
467
468 10
            case 'include_php':
469
                return $this->_compile_include_php_tag($tag_args);
470
471 10
            case 'if':
472 9
                $this->_push_tag('if');
473 9
                return $this->_compile_if_tag($tag_args);
474
475 10
            case 'else':
476 7
                list($_open_tag) = end($this->_tag_stack);
477 7
                if ($_open_tag != 'if' && $_open_tag != 'elseif')
478
                    $this->_syntax_error('unexpected {else}', E_USER_ERROR, __FILE__, __LINE__);
479
                else
480 7
                    $this->_push_tag('else');
481 7
                return '<?php else: ?>';
482
483 10
            case 'elseif':
484 6
                list($_open_tag) = end($this->_tag_stack);
485 6
                if ($_open_tag != 'if' && $_open_tag != 'elseif')
486
                    $this->_syntax_error('unexpected {elseif}', E_USER_ERROR, __FILE__, __LINE__);
487 6
                if ($_open_tag == 'if')
488 6
                    $this->_push_tag('elseif');
489 6
                return $this->_compile_if_tag($tag_args, true);
490
491 10
            case '/if':
492 9
                $this->_pop_tag('if');
493 9
                return '<?php endif; ?>';
494
495 10
            case 'capture':
496 6
                return $this->_compile_capture_tag(true, $tag_args);
497
498 10
            case '/capture':
499 6
                return $this->_compile_capture_tag(false);
500
501 10
            case 'ldelim':
502 6
                return $this->left_delimiter;
503
504 10
            case 'rdelim':
505 6
                return $this->right_delimiter;
506
507 10
            case 'section':
508
                $this->_push_tag('section');
509
                return $this->_compile_section_start($tag_args);
510
511 10
            case 'sectionelse':
512
                $this->_push_tag('sectionelse');
513
                return "<?php endfor; else: ?>";
514
                break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
515
516 10
            case '/section':
0 ignored issues
show
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
517
                $_open_tag = $this->_pop_tag('section');
518
                if ($_open_tag == 'sectionelse')
519
                    return "<?php endif; ?>";
520
                else
521
                    return "<?php endfor; endif; ?>";
522
523 10
            case 'foreach':
524 8
                $this->_push_tag('foreach');
525 8
                return $this->_compile_foreach_start($tag_args);
526
                break;
0 ignored issues
show
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
527
528 10
            case 'foreachelse':
529 4
                $this->_push_tag('foreachelse');
530 4
                return "<?php endforeach; else: ?>";
531
532 10
            case '/foreach':
533 8
                $_open_tag = $this->_pop_tag('foreach');
534 8
                if ($_open_tag == 'foreachelse')
535 4
                    return "<?php endif; unset(\$_from); ?>";
536
                else
537 7
                    return "<?php endforeach; endif; unset(\$_from); ?>";
538
                break;
0 ignored issues
show
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
539
540 10
            case 'strip':
541 10
            case '/strip':
542 2
                if (substr($tag_command, 0, 1)=='/') {
543 2
                    $this->_pop_tag('strip');
544 2
                    if (--$this->_strip_depth==0) { /* outermost closing {/strip} */
545 2
                        $this->_additional_newline = "\n";
546 2
                        return '{' . $tag_command . '}';
547
                    }
548
                } else {
549 2
                    $this->_push_tag('strip');
550 2
                    if ($this->_strip_depth++==0) { /* outermost opening {strip} */
551 2
                        $this->_additional_newline = "";
552 2
                        return '{' . $tag_command . '}';
553
                    }
554
                }
555
                return '';
556
557 10
            case 'php':
558
                /* handle folded tags replaced by {php} */
559 10
                list(, $block) = each($this->_folded_blocks);
560 10
                $this->_current_line_no += substr_count($block[0], "\n");
561
                /* the number of matched elements in the regexp in _compile_file()
562
                   determins the type of folded tag that was found */
563 10
                switch (count($block)) {
564 10
                    case 2: /* comment */
565 8
                        return '';
566
567 9
                    case 3: /* literal */
568 9
                        return "<?php echo '" . strtr($block[2], array("'"=>"\'", "\\"=>"\\\\")) . "'; ?>" . $this->_additional_newline;
569
570 1
                    case 4: /* php */
571 1
                        if ($this->security && !$this->security_settings['PHP_TAGS']) {
572
                            $this->_syntax_error("(secure mode) php tags not permitted", E_USER_WARNING, __FILE__, __LINE__);
573
                            return;
574
                        }
575 1
                        return '<?php ' . $block[3] .' ?>';
576
                }
577
                break;
578
579 9
            case 'insert':
580
                return $this->_compile_insert_tag($tag_args);
581
582
            default:
583 9
                if ($this->_compile_compiler_tag($tag_command, $tag_args, $output)) {
584 7
                    return $output;
585 9
                } else if ($this->_compile_block_tag($tag_command, $tag_args, $tag_modifier, $output)) {
586
                    return $output;
587 9
                } else if ($this->_compile_custom_tag($tag_command, $tag_args, $tag_modifier, $output)) {
588 9
                    return $output;                    
589
                } else {
590
                    $this->_syntax_error("unrecognized tag '$tag_command'", E_USER_ERROR, __FILE__, __LINE__);
591
                }
592
593
        }
594
    }
595
596
597
    /**
598
     * compile the custom compiler tag
599
     *
600
     * sets $output to the compiled custom compiler tag
601
     * @param string $tag_command
602
     * @param string $tag_args
603
     * @param string $output
604
     * @return boolean
605
     */
606 9
    function _compile_compiler_tag($tag_command, $tag_args, &$output)
607
    {
608 9
        $found = false;
609 9
        $have_function = true;
610
611
        /*
612
         * First we check if the compiler function has already been registered
613
         * or loaded from a plugin file.
614
         */
615 9
        if (isset($this->_plugins['compiler'][$tag_command])) {
616 7
            $found = true;
617 7
            $plugin_func = $this->_plugins['compiler'][$tag_command][0];
618 7
            if (!is_callable($plugin_func)) {
619
                $message = "compiler function '$tag_command' is not implemented";
620 7
                $have_function = false;
621
            }
622
        }
623
        /*
624
         * Otherwise we need to load plugin file and look for the function
625
         * inside it.
626
         */
627 9
        else if ($plugin_file = $this->_get_plugin_filepath('compiler', $tag_command)) {
628 7
            $found = true;
629
630 7
            include_once $plugin_file;
631
632 7
            $plugin_func = 'smarty_compiler_' . $tag_command;
633 7
            if (!is_callable($plugin_func)) {
634
                $message = "plugin function $plugin_func() not found in $plugin_file\n";
635
                $have_function = false;
636
            } else {
637 7
                $this->_plugins['compiler'][$tag_command] = array($plugin_func, null, null, null, true);
638
            }
639
        }
640
641
        /*
642
         * True return value means that we either found a plugin or a
643
         * dynamically registered function. False means that we didn't and the
644
         * compiler should now emit code to load custom function plugin for this
645
         * tag.
646
         */
647 9
        if ($found) {
648 7
            if ($have_function) {
649 7
                $output = call_user_func_array($plugin_func, array($tag_args, &$this));
650 7
                if($output != '') {
651 7
                $output = '<?php ' . $this->_push_cacheable_state('compiler', $tag_command)
652 7
                                   . $output
653 7
                                   . $this->_pop_cacheable_state('compiler', $tag_command) . ' ?>';
654
                }
655
            } else {
656
                $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);
657
            }
658 7
            return true;
659
        } else {
660 9
            return false;
661
        }
662
    }
663
664
665
    /**
666
     * compile block function tag
667
     *
668
     * sets $output to compiled block function tag
669
     * @param string $tag_command
670
     * @param string $tag_args
671
     * @param string $tag_modifier
672
     * @param string $output
673
     * @return boolean
674
     */
675 9
    function _compile_block_tag($tag_command, $tag_args, $tag_modifier, &$output)
676
    {
677 9
        if (substr($tag_command, 0, 1) == '/') {
678
            $start_tag = false;
679
            $tag_command = substr($tag_command, 1);
680
        } else
681 9
            $start_tag = true;
682
683 9
        $found = false;
684 9
        $have_function = true;
685
686
        /*
687
         * First we check if the block function has already been registered
688
         * or loaded from a plugin file.
689
         */
690 9
        if (isset($this->_plugins['block'][$tag_command])) {
691
            $found = true;
692
            $plugin_func = $this->_plugins['block'][$tag_command][0];
693
            if (!is_callable($plugin_func)) {
694
                $message = "block function '$tag_command' is not implemented";
695
                $have_function = false;
696
            }
697
        }
698
        /*
699
         * Otherwise we need to load plugin file and look for the function
700
         * inside it.
701
         */
702 9
        else if ($plugin_file = $this->_get_plugin_filepath('block', $tag_command)) {
703
            $found = true;
704
705
            include_once $plugin_file;
706
707
            $plugin_func = 'smarty_block_' . $tag_command;
708
            if (!function_exists($plugin_func)) {
709
                $message = "plugin function $plugin_func() not found in $plugin_file\n";
710
                $have_function = false;
711
            } else {
712
                $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true);
713
714
            }
715
        }
716
717 9
        if (!$found) {
718 9
            return false;
719
        } else if (!$have_function) {
720
            $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);
721
            return true;
722
        }
723
724
        /*
725
         * Even though we've located the plugin function, compilation
726
         * happens only once, so the plugin will still need to be loaded
727
         * at runtime for future requests.
728
         */
729
        $this->_add_plugin('block', $tag_command);
730
731
        if ($start_tag)
732
            $this->_push_tag($tag_command);
733
        else
734
            $this->_pop_tag($tag_command);
735
736
        if ($start_tag) {
737
            $output = '<?php ' . $this->_push_cacheable_state('block', $tag_command);
738
            $attrs = $this->_parse_attrs($tag_args);
739
            $_cache_attrs='';
740
            $arg_list = $this->_compile_arg_list('block', $tag_command, $attrs, $_cache_attrs);
741
            $output .= "$_cache_attrs\$this->_tag_stack[] = array('$tag_command', array(".implode(',', $arg_list).')); ';
742
            $output .= '$_block_repeat=true;' . $this->_compile_plugin_call('block', $tag_command).'($this->_tag_stack[count($this->_tag_stack)-1][1], null, $this, $_block_repeat);';
743
            $output .= 'while ($_block_repeat) { ob_start(); ?>';
744
        } else {
745
            $output = '<?php $_block_content = ob_get_contents(); ob_end_clean(); ';
746
            $_out_tag_text = $this->_compile_plugin_call('block', $tag_command).'($this->_tag_stack[count($this->_tag_stack)-1][1], $_block_content, $this, $_block_repeat)';
747
            if ($tag_modifier != '') {
748
                $this->_parse_modifiers($_out_tag_text, $tag_modifier);
749
            }
750
            $output .= '$_block_repeat=false;echo ' . $_out_tag_text . '; } ';
751
            $output .= " array_pop(\$this->_tag_stack); " . $this->_pop_cacheable_state('block', $tag_command) . '?>';
752
        }
753
754
        return true;
755
    }
756
757
758
    /**
759
     * compile custom function tag
760
     *
761
     * @param string $tag_command
762
     * @param string $tag_args
763
     * @param string $tag_modifier
764
     * @return string
765
     */
766 9
    function _compile_custom_tag($tag_command, $tag_args, $tag_modifier, &$output)
767
    {
768 9
        $found = false;
769 9
        $have_function = true;
770
771
        /*
772
         * First we check if the custom function has already been registered
773
         * or loaded from a plugin file.
774
         */
775 9
        if (isset($this->_plugins['function'][$tag_command])) {
776 8
            $found = true;
777 8
            $plugin_func = $this->_plugins['function'][$tag_command][0];
778 8
            if (!is_callable($plugin_func)) {
779
                $message = "custom function '$tag_command' is not implemented";
780 8
                $have_function = false;
781
            }
782
        }
783
        /*
784
         * Otherwise we need to load plugin file and look for the function
785
         * inside it.
786
         */
787 9
        else if ($plugin_file = $this->_get_plugin_filepath('function', $tag_command)) {
788 9
            $found = true;
789
790 9
            include_once $plugin_file;
791
792 9
            $plugin_func = 'smarty_function_' . $tag_command;
793 9
            if (!function_exists($plugin_func)) {
794
                $message = "plugin function $plugin_func() not found in $plugin_file\n";
795
                $have_function = false;
796
            } else {
797 9
                $this->_plugins['function'][$tag_command] = array($plugin_func, null, null, null, true);
798
799
            }
800
        }
801
802 9
        if (!$found) {
803
            return false;
804 9
        } else if (!$have_function) {
805
            $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__);
806
            return true;
807
        }
808
809
        /* declare plugin to be loaded on display of the template that
810
           we compile right now */
811 9
        $this->_add_plugin('function', $tag_command);
812
813 9
        $_cacheable_state = $this->_push_cacheable_state('function', $tag_command);
814 9
        $attrs = $this->_parse_attrs($tag_args);
815 9
        $_cache_attrs = '';
816 9
        $arg_list = $this->_compile_arg_list('function', $tag_command, $attrs, $_cache_attrs);
817
818 9
        $output = $this->_compile_plugin_call('function', $tag_command).'(array('.implode(',', $arg_list)."), \$this)";
819 9
        if($tag_modifier != '') {
820
            $this->_parse_modifiers($output, $tag_modifier);
821
        }
822
823 9
        if($output != '') {
824 9
            $output =  '<?php ' . $_cacheable_state . $_cache_attrs . 'echo ' . $output . ';'
825 9
                . $this->_pop_cacheable_state('function', $tag_command) . "?>" . $this->_additional_newline;
826
        }
827
828 9
        return true;
829
    }
830
831
    /**
832
     * compile a registered object tag
833
     *
834
     * @param string $tag_command
835
     * @param array $attrs
836
     * @param string $tag_modifier
837
     * @return string
838
     */
839
    function _compile_registered_object_tag($tag_command, $attrs, $tag_modifier)
840
    {
841
        if (substr($tag_command, 0, 1) == '/') {
842
            $start_tag = false;
843
            $tag_command = substr($tag_command, 1);
844
        } else {
845
            $start_tag = true;
846
        }
847
848
        list($object, $obj_comp) = explode('->', $tag_command);
849
850
        $arg_list = array();
851
        if(count($attrs)) {
852
            $_assign_var = false;
853
            foreach ($attrs as $arg_name => $arg_value) {
854
                if($arg_name == 'assign') {
855
                    $_assign_var = $arg_value;
856
                    unset($attrs['assign']);
857
                    continue;
858
                }
859
                if (is_bool($arg_value))
860
                    $arg_value = $arg_value ? 'true' : 'false';
861
                $arg_list[] = "'$arg_name' => $arg_value";
862
            }
863
        }
864
865
        if($this->_reg_objects[$object][2]) {
866
            // smarty object argument format
867
            $args = "array(".implode(',', (array)$arg_list)."), \$this";
868
        } else {
869
            // traditional argument format
870
            $args = implode(',', array_values($attrs));
871
            if (empty($args)) {
872
                $args = '';
873
            }
874
        }
875
876
        $prefix = '';
877
        $postfix = '';
878
        $newline = '';
879
        if(!is_object($this->_reg_objects[$object][0])) {
880
            $this->_trigger_fatal_error("registered '$object' is not an object" , $this->_current_file, $this->_current_line_no, __FILE__, __LINE__);
881
        } elseif(!empty($this->_reg_objects[$object][1]) && !in_array($obj_comp, $this->_reg_objects[$object][1])) {
882
            $this->_trigger_fatal_error("'$obj_comp' is not a registered component of object '$object'", $this->_current_file, $this->_current_line_no, __FILE__, __LINE__);
883
        } elseif(method_exists($this->_reg_objects[$object][0], $obj_comp)) {
884
            // method
885
            if(in_array($obj_comp, $this->_reg_objects[$object][3])) {
886
                // block method
887
                if ($start_tag) {
888
                    $prefix = "\$this->_tag_stack[] = array('$obj_comp', $args); ";
889
                    $prefix .= "\$_block_repeat=true; \$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], null, \$this, \$_block_repeat); ";
890
                    $prefix .= "while (\$_block_repeat) { ob_start();";
891
                    $return = null;
892
                    $postfix = '';
893
                } else {
894
                    $prefix = "\$_obj_block_content = ob_get_contents(); ob_end_clean(); \$_block_repeat=false;";
895
                    $return = "\$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], \$_obj_block_content, \$this, \$_block_repeat)";
896
                    $postfix = "} array_pop(\$this->_tag_stack);";
897
                }
898
            } else {
899
                // non-block method
900
                $return = "\$this->_reg_objects['$object'][0]->$obj_comp($args)";
901
            }
902
        } else {
903
            // property
904
            $return = "\$this->_reg_objects['$object'][0]->$obj_comp";
905
        }
906
907
        if($return != null) {
908
            if($tag_modifier != '') {
909
                $this->_parse_modifiers($return, $tag_modifier);
910
            }
911
912
            if(!empty($_assign_var)) {
913
                $output = "\$this->assign('" . $this->_dequote($_assign_var) ."',  $return);";
914
            } else {
915
                $output = 'echo ' . $return . ';';
916
                $newline = $this->_additional_newline;
917
            }
918
        } else {
919
            $output = '';
920
        }
921
922
        return '<?php ' . $prefix . $output . $postfix . "?>" . $newline;
923
    }
924
925
    /**
926
     * Compile {insert ...} tag
927
     *
928
     * @param string $tag_args
929
     * @return string
930
     */
931
    function _compile_insert_tag($tag_args)
932
    {
933
        $attrs = $this->_parse_attrs($tag_args);
934
        $name = $this->_dequote($attrs['name']);
935
936
        if (empty($name)) {
937
            return $this->_syntax_error("missing insert name", E_USER_ERROR, __FILE__, __LINE__);
938
        }
939
        
940
        if (!preg_match('~^\w+$~', $name)) {
941
            return $this->_syntax_error("'insert: 'name' must be an insert function name", E_USER_ERROR, __FILE__, __LINE__);
942
        }
943
944
        if (!empty($attrs['script'])) {
945
            $delayed_loading = true;
946
        } else {
947
            $delayed_loading = false;
948
        }
949
950
        foreach ($attrs as $arg_name => $arg_value) {
951
            if (is_bool($arg_value))
952
                $arg_value = $arg_value ? 'true' : 'false';
953
            $arg_list[] = "'$arg_name' => $arg_value";
954
        }
955
956
        $this->_add_plugin('insert', $name, $delayed_loading);
957
958
        $_params = "array('args' => array(".implode(', ', (array)$arg_list)."))";
959
960
        return "<?php require_once(SMARTY_CORE_DIR . 'core.run_insert_handler.php');\necho smarty_core_run_insert_handler($_params, \$this); ?>" . $this->_additional_newline;
961
    }
962
963
    /**
964
     * Compile {include ...} tag
965
     *
966
     * @param string $tag_args
967
     * @return string
968
     */
969 5
    function _compile_include_tag($tag_args)
970
    {
971 5
        $attrs = $this->_parse_attrs($tag_args);
972 5
        $arg_list = array();
973
974 5
        if (empty($attrs['file'])) {
975
            $this->_syntax_error("missing 'file' attribute in include tag", E_USER_ERROR, __FILE__, __LINE__);
976
        }
977
978 5
        $theme_template = 'false';
979 5
        foreach ($attrs as $arg_name => $arg_value) {
980 5
            if ($arg_name == 'file') {
981 5
                $include_file = $arg_value;
982 5
                continue;
983 1
            } else if ($arg_name == 'assign') {
984
                $assign_var = $arg_value;
985
                continue;
986 1
            } else if ($arg_name == 'theme_template') {
987 1
                $theme_template = $arg_value;
988 1
                continue;
989
            }
990
            if (is_bool($arg_value))
991
                $arg_value = $arg_value ? 'true' : 'false';
992
            $arg_list[] = "'$arg_name' => $arg_value";
993
        }
994
995 5
        if ( $theme_template == 'true' )
996 1
            $include_file = '"'.SugarThemeRegistry::current()->getTemplate(str_replace(array('"',"'"),'',$include_file)).'"';
997
998 5
        $output = '<?php ';
999
1000 5
        if (isset($assign_var)) {
1001
            $output .= "ob_start();\n";
1002
        }
1003
1004
        $output .=
1005 5
            "\$_smarty_tpl_vars = \$this->_tpl_vars;\n";
1006
1007
1008 5
        $_params = "array('smarty_include_tpl_file' => " . $include_file . ", 'smarty_include_vars' => array(".implode(',', (array)$arg_list)."))";
1009 5
        $output .= "\$this->_smarty_include($_params);\n" .
1010 5
        "\$this->_tpl_vars = \$_smarty_tpl_vars;\n" .
1011 5
        "unset(\$_smarty_tpl_vars);\n";
1012
1013 5
        if (isset($assign_var)) {
1014
            $output .= "\$this->assign(" . $assign_var . ", ob_get_contents()); ob_end_clean();\n";
1015
        }
1016
1017 5
        $output .= ' ?>';
1018
1019 5
        return $output;
1020
1021
    }
1022
1023
    /**
1024
     * Compile {include ...} tag
1025
     *
1026
     * @param string $tag_args
1027
     * @return string
1028
     */
1029
    function _compile_include_php_tag($tag_args)
1030
    {
1031
        $attrs = $this->_parse_attrs($tag_args);
1032
1033
        if (empty($attrs['file'])) {
1034
            $this->_syntax_error("missing 'file' attribute in include_php tag", E_USER_ERROR, __FILE__, __LINE__);
1035
        }
1036
1037
        $assign_var = (empty($attrs['assign'])) ? '' : $this->_dequote($attrs['assign']);
1038
        $once_var = (empty($attrs['once']) || $attrs['once']=='false') ? 'false' : 'true';
1039
1040
        $arg_list = array();
1041
        foreach($attrs as $arg_name => $arg_value) {
1042
            if($arg_name != 'file' AND $arg_name != 'once' AND $arg_name != 'assign') {
1043
                if(is_bool($arg_value))
1044
                    $arg_value = $arg_value ? 'true' : 'false';
1045
                $arg_list[] = "'$arg_name' => $arg_value";
1046
            }
1047
        }
1048
1049
        $_params = "array('smarty_file' => " . $attrs['file'] . ", 'smarty_assign' => '$assign_var', 'smarty_once' => $once_var, 'smarty_include_vars' => array(".implode(',', $arg_list)."))";
1050
1051
        return "<?php require_once(SMARTY_CORE_DIR . 'core.smarty_include_php.php');\nsmarty_core_smarty_include_php($_params, \$this); ?>" . $this->_additional_newline;
1052
    }
1053
1054
1055
    /**
1056
     * Compile {section ...} tag
1057
     *
1058
     * @param string $tag_args
1059
     * @return string
1060
     */
1061
    function _compile_section_start($tag_args)
1062
    {
1063
        $attrs = $this->_parse_attrs($tag_args);
1064
        $arg_list = array();
1065
1066
        $output = '<?php ';
1067
        $section_name = $attrs['name'];
1068
        if (empty($section_name)) {
1069
            $this->_syntax_error("missing section name", E_USER_ERROR, __FILE__, __LINE__);
1070
        }
1071
1072
        $output .= "unset(\$this->_sections[$section_name]);\n";
1073
        $section_props = "\$this->_sections[$section_name]";
1074
1075
        foreach ($attrs as $attr_name => $attr_value) {
1076
            switch ($attr_name) {
1077
                case 'loop':
1078
                    $output .= "{$section_props}['loop'] = is_array(\$_loop=$attr_value) ? count(\$_loop) : max(0, (int)\$_loop); unset(\$_loop);\n";
1079
                    break;
1080
1081
                case 'show':
1082
                    if (is_bool($attr_value))
1083
                        $show_attr_value = $attr_value ? 'true' : 'false';
1084
                    else
1085
                        $show_attr_value = "(bool)$attr_value";
1086
                    $output .= "{$section_props}['show'] = $show_attr_value;\n";
1087
                    break;
1088
1089
                case 'name':
1090
                    $output .= "{$section_props}['$attr_name'] = $attr_value;\n";
1091
                    break;
1092
1093
                case 'max':
1094
                case 'start':
1095
                    $output .= "{$section_props}['$attr_name'] = (int)$attr_value;\n";
1096
                    break;
1097
1098
                case 'step':
1099
                    $output .= "{$section_props}['$attr_name'] = ((int)$attr_value) == 0 ? 1 : (int)$attr_value;\n";
1100
                    break;
1101
1102
                default:
1103
                    $this->_syntax_error("unknown section attribute - '$attr_name'", E_USER_ERROR, __FILE__, __LINE__);
1104
                    break;
1105
            }
1106
        }
1107
1108
        if (!isset($attrs['show']))
1109
            $output .= "{$section_props}['show'] = true;\n";
1110
1111
        if (!isset($attrs['loop']))
1112
            $output .= "{$section_props}['loop'] = 1;\n";
1113
1114
        if (!isset($attrs['max']))
1115
            $output .= "{$section_props}['max'] = {$section_props}['loop'];\n";
1116
        else
1117
            $output .= "if ({$section_props}['max'] < 0)\n" .
1118
                       "    {$section_props}['max'] = {$section_props}['loop'];\n";
1119
1120
        if (!isset($attrs['step']))
1121
            $output .= "{$section_props}['step'] = 1;\n";
1122
1123
        if (!isset($attrs['start']))
1124
            $output .= "{$section_props}['start'] = {$section_props}['step'] > 0 ? 0 : {$section_props}['loop']-1;\n";
1125
        else {
1126
            $output .= "if ({$section_props}['start'] < 0)\n" .
1127
                       "    {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" .
1128
                       "else\n" .
1129
                       "    {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n";
1130
        }
1131
1132
        $output .= "if ({$section_props}['show']) {\n";
1133
        if (!isset($attrs['start']) && !isset($attrs['step']) && !isset($attrs['max'])) {
1134
            $output .= "    {$section_props}['total'] = {$section_props}['loop'];\n";
1135
        } else {
1136
            $output .= "    {$section_props}['total'] = min(ceil(({$section_props}['step'] > 0 ? {$section_props}['loop'] - {$section_props}['start'] : {$section_props}['start']+1)/abs({$section_props}['step'])), {$section_props}['max']);\n";
1137
        }
1138
        $output .= "    if ({$section_props}['total'] == 0)\n" .
1139
                   "        {$section_props}['show'] = false;\n" .
1140
                   "} else\n" .
1141
                   "    {$section_props}['total'] = 0;\n";
1142
1143
        $output .= "if ({$section_props}['show']):\n";
1144
        $output .= "
1145
            for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1;
1146
                 {$section_props}['iteration'] <= {$section_props}['total'];
1147
                 {$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n";
1148
        $output .= "{$section_props}['rownum'] = {$section_props}['iteration'];\n";
1149
        $output .= "{$section_props}['index_prev'] = {$section_props}['index'] - {$section_props}['step'];\n";
1150
        $output .= "{$section_props}['index_next'] = {$section_props}['index'] + {$section_props}['step'];\n";
1151
        $output .= "{$section_props}['first']      = ({$section_props}['iteration'] == 1);\n";
1152
        $output .= "{$section_props}['last']       = ({$section_props}['iteration'] == {$section_props}['total']);\n";
1153
1154
        $output .= "?>";
1155
1156
        return $output;
1157
    }
1158
1159
1160
    /**
1161
     * Compile {foreach ...} tag.
1162
     *
1163
     * @param string $tag_args
1164
     * @return string
1165
     */
1166 8
    function _compile_foreach_start($tag_args)
1167
    {
1168 8
        $attrs = $this->_parse_attrs($tag_args);
1169 8
        $arg_list = array();
1170
1171 8
        if (empty($attrs['from'])) {
1172
            return $this->_syntax_error("foreach: missing 'from' attribute", E_USER_ERROR, __FILE__, __LINE__);
1173
        }
1174 8
        $from = $attrs['from'];
1175
1176 8
        if (empty($attrs['item'])) {
1177
            return $this->_syntax_error("foreach: missing 'item' attribute", E_USER_ERROR, __FILE__, __LINE__);
1178
        }
1179 8
        $item = $this->_dequote($attrs['item']);
1180 8
        if (!preg_match('~^\w+$~', $item)) {
1181
            return $this->_syntax_error("foreach: 'item' must be a variable name (literal string)", E_USER_ERROR, __FILE__, __LINE__);
1182
        }
1183
1184 8
        if (isset($attrs['key'])) {
1185 7
            $key  = $this->_dequote($attrs['key']);
1186 7
            if (!preg_match('~^\w+$~', $key)) {
1187
                return $this->_syntax_error("foreach: 'key' must to be a variable name (literal string)", E_USER_ERROR, __FILE__, __LINE__);
1188
            }
1189 7
            $key_part = "\$this->_tpl_vars['$key'] => ";
1190
        } else {
1191 5
            $key = null;
1192 5
            $key_part = '';
1193
        }
1194
1195 8
        if (isset($attrs['name'])) {
1196 7
            $name = $attrs['name'];
1197
        } else {
1198 6
            $name = null;
1199
        }
1200
1201 8
        $output = '<?php ';
1202 8
        $output .= "\$_from = $from; if (!is_array(\$_from) && !is_object(\$_from)) { settype(\$_from, 'array'); }";
1203 8
        if (isset($name)) {
1204 7
            $foreach_props = "\$this->_foreach[$name]";
1205 7
            $output .= "{$foreach_props} = array('total' => count(\$_from), 'iteration' => 0);\n";
1206 7
            $output .= "if ({$foreach_props}['total'] > 0):\n";
1207 7
            $output .= "    foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n";
1208 7
            $output .= "        {$foreach_props}['iteration']++;\n";
1209
        } else {
1210 6
            $output .= "if (count(\$_from)):\n";
1211 6
            $output .= "    foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n";
1212
        }
1213 8
        $output .= '?>';
1214
1215 8
        return $output;
1216
    }
1217
1218
1219
    /**
1220
     * Compile {capture} .. {/capture} tags
1221
     *
1222
     * @param boolean $start true if this is the {capture} tag
1223
     * @param string $tag_args
1224
     * @return string
1225
     */
1226
1227 6
    function _compile_capture_tag($start, $tag_args = '')
1228
    {
1229 6
        $attrs = $this->_parse_attrs($tag_args);
1230
1231 6
        if ($start) {
1232 6
            $buffer = isset($attrs['name']) ? $attrs['name'] : "'default'";
1233 6
            $assign = isset($attrs['assign']) ? $attrs['assign'] : null;
1234 6
            $append = isset($attrs['append']) ? $attrs['append'] : null;
1235
            
1236 6
            $output = "<?php ob_start(); ?>";
1237 6
            $this->_capture_stack[] = array($buffer, $assign, $append);
1238
        } else {
1239 6
            list($buffer, $assign, $append) = array_pop($this->_capture_stack);
1240 6
            $output = "<?php \$this->_smarty_vars['capture'][$buffer] = ob_get_contents(); ";
1241 6
            if (isset($assign)) {
1242 6
                $output .= " \$this->assign($assign, ob_get_contents());";
1243
            }
1244 6
            if (isset($append)) {
1245
                $output .= " \$this->append($append, ob_get_contents());";
1246
            }
1247 6
            $output .= "ob_end_clean(); ?>";
1248
        }
1249
1250 6
        return $output;
1251
    }
1252
1253
    /**
1254
     * Compile {if ...} tag
1255
     *
1256
     * @param string $tag_args
1257
     * @param boolean $elseif if true, uses elseif instead of if
1258
     * @return string
1259
     */
1260 9
    function _compile_if_tag($tag_args, $elseif = false)
1261
    {
1262
1263
        /* Tokenize args for 'if' tag. */
1264 9
        preg_match_all('~(?>
1265 9
                ' . $this->_obj_call_regexp . '(?:' . $this->_mod_regexp . '*)? | # valid object call
1266 9
                ' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)?    | # var or quoted string
1267
                \-?0[xX][0-9a-fA-F]+|\-?\d+(?:\.\d+)?|\.\d+|!==|===|==|!=|<>|<<|>>|<=|>=|\&\&|\|\||\(|\)|,|\!|\^|=|\&|\~|<|>|\||\%|\+|\-|\/|\*|\@    | # valid non-word token
1268
                \b\w+\b                                                        | # valid word token
1269
                \S+                                                           # anything else
1270 9
                )~x', $tag_args, $match);
1271
1272 9
        $tokens = $match[0];
1273
1274 9
        if(empty($tokens)) {
1275
            $_error_msg = $elseif ? "'elseif'" : "'if'";
1276
            $_error_msg .= ' statement requires arguments'; 
1277
            $this->_syntax_error($_error_msg, E_USER_ERROR, __FILE__, __LINE__);
1278
        }
1279
            
1280
                
1281
        // make sure we have balanced parenthesis
1282 9
        $token_count = array_count_values($tokens);
1283 9
        if(isset($token_count['(']) && $token_count['('] != $token_count[')']) {
1284
            $this->_syntax_error("unbalanced parenthesis in if statement", E_USER_ERROR, __FILE__, __LINE__);
1285
        }
1286
1287 9
        $is_arg_stack = array();
1288
1289 9
        for ($i = 0; $i < count($tokens); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
1290
1291 9
            $token = &$tokens[$i];
1292
1293 9
            switch (strtolower($token)) {
1294 9
                case '!':
1295 9
                case '%':
1296 9
                case '!==':
1297 9
                case '==':
1298 9
                case '===':
1299 9
                case '>':
1300 9
                case '<':
1301 9
                case '!=':
1302 9
                case '<>':
1303 9
                case '<<':
1304 9
                case '>>':
1305 9
                case '<=':
1306 9
                case '>=':
1307 9
                case '&&':
1308 9
                case '||':
1309 9
                case '|':
1310 9
                case '^':
1311 9
                case '&':
1312 9
                case '~':
1313 9
                case ')':
1314 9
                case ',':
1315 9
                case '+':
1316 9
                case '-':
1317 9
                case '*':
1318 9
                case '/':
1319 9
                case '@':
1320 9
                    break;
1321
1322 9
                case 'eq':
1323 2
                    $token = '==';
1324 2
                    break;
1325
1326 9
                case 'ne':
1327 9
                case 'neq':
1328 1
                    $token = '!=';
1329 1
                    break;
1330
1331 9
                case 'lt':
1332
                    $token = '<';
1333
                    break;
1334
1335 9
                case 'le':
1336 9
                case 'lte':
1337
                    $token = '<=';
1338
                    break;
1339
1340 9
                case 'gt':
1341
                    $token = '>';
1342
                    break;
1343
1344 9
                case 'ge':
1345 9
                case 'gte':
1346
                    $token = '>=';
1347
                    break;
1348
1349 9
                case 'and':
1350
                    $token = '&&';
1351
                    break;
1352
1353 9
                case 'or':
1354
                    $token = '||';
1355
                    break;
1356
1357 9
                case 'not':
1358
                    $token = '!';
1359
                    break;
1360
1361 9
                case 'mod':
1362
                    $token = '%';
1363
                    break;
1364
1365 9
                case '(':
1366 7
                    array_push($is_arg_stack, $i);
1367 7
                    break;
1368
1369 9
                case 'is':
1370
                    /* If last token was a ')', we operate on the parenthesized
1371
                       expression. The start of the expression is on the stack.
1372
                       Otherwise, we operate on the last encountered token. */
1373 3
                    if ($tokens[$i-1] == ')') {
1374
                        $is_arg_start = array_pop($is_arg_stack);
1375
                        if ($is_arg_start != 0) {
1376
                            if (preg_match('~^' . $this->_func_regexp . '$~', $tokens[$is_arg_start-1])) {
1377
                                $is_arg_start--;
1378
                            } 
1379
                        } 
1380
                    } else
1381 3
                        $is_arg_start = $i-1;
1382
                    /* Construct the argument for 'is' expression, so it knows
1383
                       what to operate on. */
1384 3
                    $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start));
1385
1386
                    /* Pass all tokens from next one until the end to the
1387
                       'is' expression parsing function. The function will
1388
                       return modified tokens, where the first one is the result
1389
                       of the 'is' expression and the rest are the tokens it
1390
                       didn't touch. */
1391 3
                    $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));
1392
1393
                    /* Replace the old tokens with the new ones. */
1394 3
                    array_splice($tokens, $is_arg_start, count($tokens), $new_tokens);
1395
1396
                    /* Adjust argument start so that it won't change from the
1397
                       current position for the next iteration. */
1398 3
                    $i = $is_arg_start;
1399 3
                    break;
1400
1401
                default:
1402 9
                    if(preg_match('~^' . $this->_func_regexp . '$~', $token) ) {
1403
                            // function call
1404 7
                            if($this->security &&
1405 7
                               !in_array($token, $this->security_settings['IF_FUNCS'])) {
1406 7
                                $this->_syntax_error("(secure mode) '$token' not allowed in if statement", E_USER_ERROR, __FILE__, __LINE__);
1407
                            }
1408 9
                    } elseif(preg_match('~^' . $this->_var_regexp . '$~', $token) && (strpos('+-*/^%&|', substr($token, -1)) === false) && isset($tokens[$i+1]) && $tokens[$i+1] == '(') {
1409
                        // variable function call
1410
                        $this->_syntax_error("variable function call '$token' not allowed in if statement", E_USER_ERROR, __FILE__, __LINE__);                      
1411 9
                    } elseif(preg_match('~^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)$~', $token)) {
1412
                        // object or variable
1413 9
                        $token = $this->_parse_var_props($token);
1414 6
                    } elseif(is_numeric($token)) {
0 ignored issues
show
This elseif statement is empty, and could be removed.

This check looks for the bodies of elseif statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These elseif bodies can be removed. If you have an empty elseif but statements in the else branch, consider inverting the condition.

Loading history...
1415
                        // number, skip it
1416
                    } else {
1417
                        $this->_syntax_error("unidentified token '$token'", E_USER_ERROR, __FILE__, __LINE__);
1418
                    }
1419 9
                    break;
1420
            }
1421
        }
1422
1423 9
        if ($elseif)
1424 6
            return '<?php elseif ('.implode(' ', $tokens).'): ?>';
1425
        else
1426 9
            return '<?php if ('.implode(' ', $tokens).'): ?>';
1427
    }
1428
1429
1430 9
    function _compile_arg_list($type, $name, $attrs, &$cache_code) {
1431 9
        $arg_list = array();
1432
1433 9
        if (isset($type) && isset($name)
1434 9
            && isset($this->_plugins[$type])
1435 9
            && isset($this->_plugins[$type][$name])
1436 9
            && empty($this->_plugins[$type][$name][4])
1437 9
            && is_array($this->_plugins[$type][$name][5])
1438
            ) {
1439
            /* we have a list of parameters that should be cached */
1440
            $_cache_attrs = $this->_plugins[$type][$name][5];
1441
            $_count = $this->_cache_attrs_count++;
1442
            $cache_code = "\$_cache_attrs =& \$this->_smarty_cache_attrs('$this->_cache_serial','$_count');";
1443
1444
        } else {
1445
            /* no parameters are cached */
1446 9
            $_cache_attrs = null;
1447
        }
1448
1449 9
        foreach ($attrs as $arg_name => $arg_value) {
1450 9
            if (is_bool($arg_value))
1451
                $arg_value = $arg_value ? 'true' : 'false';
1452 9
            if (is_null($arg_value))
1453
                $arg_value = 'null';
1454 9
            if ($_cache_attrs && in_array($arg_name, $_cache_attrs)) {
1455
                $arg_list[] = "'$arg_name' => (\$this->_cache_including) ? \$_cache_attrs['$arg_name'] : (\$_cache_attrs['$arg_name']=$arg_value)";
1456
            } else {
1457 9
                $arg_list[] = "'$arg_name' => $arg_value";
1458
            }
1459
        }
1460 9
        return $arg_list;
1461
    }
1462
1463
    /**
1464
     * Parse is expression
1465
     *
1466
     * @param string $is_arg
1467
     * @param array $tokens
1468
     * @return array
1469
     */
1470 3
    function _parse_is_expr($is_arg, $tokens)
1471
    {
1472 3
        $expr_end = 0;
1473 3
        $negate_expr = false;
1474
1475 3
        if (($first_token = array_shift($tokens)) == 'not') {
1476
            $negate_expr = true;
1477
            $expr_type = array_shift($tokens);
1478
        } else
1479 3
            $expr_type = $first_token;
1480
1481
        switch ($expr_type) {
1482 3
            case 'even':
1483
                if (isset($tokens[$expr_end]) && $tokens[$expr_end] == 'by') {
1484
                    $expr_end++;
1485
                    $expr_arg = $tokens[$expr_end++];
1486
                    $expr = "!(1 & ($is_arg / " . $this->_parse_var_props($expr_arg) . "))";
1487
                } else
1488
                    $expr = "!(1 & $is_arg)";
1489
                break;
1490
1491 3
            case 'odd':
1492 3
                if (isset($tokens[$expr_end]) && $tokens[$expr_end] == 'by') {
1493
                    $expr_end++;
1494
                    $expr_arg = $tokens[$expr_end++];
1495
                    $expr = "(1 & ($is_arg / " . $this->_parse_var_props($expr_arg) . "))";
1496
                } else
1497 3
                    $expr = "(1 & $is_arg)";
1498 3
                break;
1499
1500
            case 'div':
1501
                if (@$tokens[$expr_end] == 'by') {
1502
                    $expr_end++;
1503
                    $expr_arg = $tokens[$expr_end++];
1504
                    $expr = "!($is_arg % " . $this->_parse_var_props($expr_arg) . ")";
1505
                } else {
1506
                    $this->_syntax_error("expecting 'by' after 'div'", E_USER_ERROR, __FILE__, __LINE__);
1507
                }
1508
                break;
1509
1510
            default:
1511
                $this->_syntax_error("unknown 'is' expression - '$expr_type'", E_USER_ERROR, __FILE__, __LINE__);
1512
                break;
1513
        }
1514
1515 3
        if ($negate_expr) {
1516
            $expr = "!($expr)";
1517
        }
1518
1519 3
        array_splice($tokens, 0, $expr_end, $expr);
1520
1521 3
        return $tokens;
1522
    }
1523
1524
1525
    /**
1526
     * Parse attribute string
1527
     *
1528
     * @param string $tag_args
1529
     * @return array
1530
     */
1531 9
    function _parse_attrs($tag_args)
1532
    {
1533
1534
        /* Tokenize tag attributes. */
1535 9
        preg_match_all('~(?:' . $this->_obj_call_regexp . '|' . $this->_qstr_regexp . ' | (?>[^"\'=\s]+)
1536
                         )+ |
1537
                         [=]
1538 9
                        ~x', $tag_args, $match);
1539 9
        $tokens       = $match[0];
1540
1541 9
        $attrs = array();
1542
        /* Parse state:
1543
            0 - expecting attribute name
1544
            1 - expecting '='
1545
            2 - expecting attribute value (not '=') */
1546 9
        $state = 0;
1547
1548 9
        foreach ($tokens as $token) {
1549
            switch ($state) {
1550 9
                case 0:
1551
                    /* If the token is a valid identifier, we set attribute name
1552
                       and go to state 1. */
1553 9
                    if (preg_match('~^\w+$~', $token)) {
1554 9
                        $attr_name = $token;
1555 9
                        $state = 1;
1556
                    } else
1557
                        $this->_syntax_error("invalid attribute name: '$token'", E_USER_ERROR, __FILE__, __LINE__);
1558 9
                    break;
1559
1560 9
                case 1:
1561
                    /* If the token is '=', then we go to state 2. */
1562 9
                    if ($token == '=') {
1563 9
                        $state = 2;
1564
                    } else
1565
                        $this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__, __LINE__);
1566 9
                    break;
1567
1568 9
                case 2:
1569
                    /* If token is not '=', we set the attribute value and go to
1570
                       state 0. */
1571 9
                    if ($token != '=') {
1572
                        /* We booleanize the token if it's a non-quoted possible
1573
                           boolean value. */
1574 9
                        if (preg_match('~^(on|yes|true)$~', $token)) {
1575 6
                            $token = 'true';
1576 9
                        } else if (preg_match('~^(off|no|false)$~', $token)) {
1577 6
                            $token = 'false';
1578 9
                        } else if ($token == 'null') {
1579
                            $token = 'null';
1580 9
                        } else if (preg_match('~^' . $this->_num_const_regexp . '|0[xX][0-9a-fA-F]+$~', $token)) {
0 ignored issues
show
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
1581
                            /* treat integer literally */
1582 9
                        } else if (!preg_match('~^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . ')*$~', $token)) {
1583
                            /* treat as a string, double-quote it escaping quotes */
1584 8
                            $token = '"'.addslashes($token).'"';
1585
                        }
1586
1587 9
                        $attrs[$attr_name] = $token;
1588 9
                        $state = 0;
1589
                    } else
1590
                        $this->_syntax_error("'=' cannot be an attribute value", E_USER_ERROR, __FILE__, __LINE__);
1591 9
                    break;
1592
            }
1593 9
            $last_token = $token;
1594
        }
1595
1596 9
        if($state != 0) {
1597
            if($state == 1) {
1598
                $this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__, __LINE__);
1599
            } else {
1600
                $this->_syntax_error("missing attribute value", E_USER_ERROR, __FILE__, __LINE__);
1601
            }
1602
        }
1603
1604 9
        $this->_parse_vars_props($attrs);
1605
1606 9
        return $attrs;
1607
    }
1608
1609
    /**
1610
     * compile multiple variables and section properties tokens into
1611
     * PHP code
1612
     *
1613
     * @param array $tokens
1614
     */
1615 9
    function _parse_vars_props(&$tokens)
1616
    {
1617 9
        foreach($tokens as $key => $val) {
1618 9
            $tokens[$key] = $this->_parse_var_props($val);
1619
        }
1620 9
    }
1621
1622
    /**
1623
     * compile single variable and section properties token into
1624
     * PHP code
1625
     *
1626
     * @param string $val
1627
     * @param string $tag_attrs
0 ignored issues
show
There is no parameter named $tag_attrs. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1628
     * @return string
1629
     */
1630 10
    function _parse_var_props($val)
1631
    {
1632 10
        $val = trim($val);
1633
1634 10
        if(preg_match('~^(' . $this->_obj_call_regexp . '|' . $this->_dvar_regexp . ')(' . $this->_mod_regexp . '*)$~', $val, $match)) {
1635
            // $ variable or object
1636 10
            $return = $this->_parse_var($match[1]);
1637 10
            $modifiers = $match[2];
1638 10
            if (!empty($this->default_modifiers) && !preg_match('~(^|\|)smarty:nodefaults($|\|)~',$modifiers)) {
1639
                $_default_mod_string = implode('|',(array)$this->default_modifiers);
1640
                $modifiers = empty($modifiers) ? $_default_mod_string : $_default_mod_string . '|' . $modifiers;
1641
            }
1642 10
            $this->_parse_modifiers($return, $modifiers);
1643 10
            return $return;
1644 9
        } elseif (preg_match('~^' . $this->_db_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) {
1645
                // double quoted text
1646 9
                preg_match('~^(' . $this->_db_qstr_regexp . ')('. $this->_mod_regexp . '*)$~', $val, $match);
1647 9
                $return = $this->_expand_quoted_text($match[1]);
1648 9
                if($match[2] != '') {
1649
                    $this->_parse_modifiers($return, $match[2]);
1650
                }
1651 9
                return $return;
1652
            }
1653 9
        elseif(preg_match('~^' . $this->_num_const_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) {
1654
                // numerical constant
1655 7
                preg_match('~^(' . $this->_num_const_regexp . ')('. $this->_mod_regexp . '*)$~', $val, $match);
1656 7
                if($match[2] != '') {
1657
                    $this->_parse_modifiers($match[1], $match[2]);
1658 7
                    return $match[1];
1659
                }
1660
            }
1661 9
        elseif(preg_match('~^' . $this->_si_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) {
1662
                // single quoted text
1663 9
                preg_match('~^(' . $this->_si_qstr_regexp . ')('. $this->_mod_regexp . '*)$~', $val, $match);
1664 9
                if($match[2] != '') {
1665
                    $this->_parse_modifiers($match[1], $match[2]);
1666 9
                    return $match[1];
1667
                }
1668
            }
1669 8
        elseif(preg_match('~^' . $this->_cvar_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) {
1670
                // config var
1671
                return $this->_parse_conf_var($val);
1672
            }
1673 8
        elseif(preg_match('~^' . $this->_svar_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) {
1674
                // section var
1675
                return $this->_parse_section_prop($val);
1676
            }
1677 8
        elseif(!in_array($val, $this->_permitted_tokens) && !is_numeric($val)) {
1678
            // literal string
1679 6
            return $this->_expand_quoted_text('"' . strtr($val, array('\\' => '\\\\', '"' => '\\"')) .'"');
1680
        }
1681 9
        return $val;
1682
    }
1683
1684
    /**
1685
     * expand quoted text with embedded variables
1686
     *
1687
     * @param string $var_expr
1688
     * @return string
1689
     */
1690 9
    function _expand_quoted_text($var_expr)
1691
    {
1692
        // if contains unescaped $, expand it
1693 9
        if(preg_match_all('~(?:\`(?<!\\\\)\$' . $this->_dvar_guts_regexp . '(?:' . $this->_obj_ext_regexp . ')*\`)|(?:(?<!\\\\)\$\w+(\[[a-zA-Z0-9]+\])*)~', $var_expr, $_match)) {
1694 6
            $_match = $_match[0];
1695 6
            $_replace = array();
1696 6
            foreach($_match as $_var) {
1697 6
                $_replace[$_var] = '".(' . $this->_parse_var(str_replace('`','',$_var)) . ')."';
1698
            }
1699 6
            $var_expr = strtr($var_expr, $_replace);
1700 6
            $_return = preg_replace('~\.""|(?<!\\\\)""\.~', '', $var_expr);
1701
        } else {
1702 9
            $_return = $var_expr;
1703
        }
1704
        // replace double quoted literal string with single quotes
1705 9
        $_return = preg_replace('~^"([\s\w]+)"$~',"'\\1'",$_return);
1706 9
        return $_return;
1707
    }
1708
1709
    /**
1710
     * parse variable expression into PHP code
1711
     *
1712
     * @param string $var_expr
1713
     * @param string $output
0 ignored issues
show
There is no parameter named $output. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1714
     * @return string
1715
     */
1716 10
    function _parse_var($var_expr)
1717
    {
1718 10
        $_has_math = false;
1719 10
        $_math_vars = preg_split('~('.$this->_dvar_math_regexp.'|'.$this->_qstr_regexp.')~', $var_expr, -1, PREG_SPLIT_DELIM_CAPTURE);
1720
1721 10
        if(count($_math_vars) > 1) {
1722 5
            $_first_var = "";
1723 5
            $_complete_var = "";
1724 5
            $_output = "";
1725
            // simple check if there is any math, to stop recursion (due to modifiers with "xx % yy" as parameter)
1726 5
            foreach($_math_vars as $_k => $_math_var) {
1727 5
                $_math_var = $_math_vars[$_k];
1728
1729 5
                if(!empty($_math_var) || is_numeric($_math_var)) {
1730
                    // hit a math operator, so process the stuff which came before it
1731 5
                    if(preg_match('~^' . $this->_dvar_math_regexp . '$~', $_math_var)) {
1732 4
                        $_has_math = true;
1733 4
                        if(!empty($_complete_var) || is_numeric($_complete_var)) {
1734 4
                            $_output .= $this->_parse_var($_complete_var);
1735
                        }
1736
1737
                        // just output the math operator to php
1738 4
                        $_output .= $_math_var;
1739
1740 4
                        if(empty($_first_var))
1741 4
                            $_first_var = $_complete_var;
1742
1743 4
                        $_complete_var = "";
1744
                    } else {
1745 5
                        $_complete_var .= $_math_var;
1746
                    }
1747
                }
1748
            }
1749 5
            if($_has_math) {
1750 4
                if(!empty($_complete_var) || is_numeric($_complete_var))
1751 4
                    $_output .= $this->_parse_var($_complete_var);
1752
1753
                // get the modifiers working (only the last var from math + modifier is left)
1754 4
                $var_expr = $_complete_var;
1755
            }
1756
        }
1757
1758
        // prevent cutting of first digit in the number (we _definitly_ got a number if the first char is a digit)
1759 10
        if(is_numeric(substr($var_expr, 0, 1)))
1760 4
            $_var_ref = $var_expr;
1761
        else
1762 10
            $_var_ref = substr($var_expr, 1);
1763
        
1764 10
        if(!$_has_math) {
1765
            
1766
            // get [foo] and .foo and ->foo and (...) pieces
1767 10
            preg_match_all('~(?:^\w+)|' . $this->_obj_params_regexp . '|(?:' . $this->_var_bracket_regexp . ')|->\$?\w+|\.\$?\w+|\S+~', $_var_ref, $match);
1768
                        
1769 10
            $_indexes = $match[0];
1770 10
            $_var_name = array_shift($_indexes);
1771
1772
            /* Handle $smarty.* variable references as a special case. */
1773 10
            if ($_var_name == 'smarty') {
1774
                /*
1775
                 * If the reference could be compiled, use the compiled output;
1776
                 * otherwise, fall back on the $smarty variable generated at
1777
                 * run-time.
1778
                 */
1779 8
                if (($smarty_ref = $this->_compile_smarty_ref($_indexes)) !== null) {
1780 8
                    $_output = $smarty_ref;
1781
                } else {
1782 3
                    $_var_name = substr(array_shift($_indexes), 1);
1783 8
                    $_output = "\$this->_smarty_vars['$_var_name']";
1784
                }
1785 10
            } elseif(is_numeric($_var_name) && is_numeric(substr($var_expr, 0, 1))) {
1786
                // because . is the operator for accessing arrays thru inidizes we need to put it together again for floating point numbers
1787 4
                if(count($_indexes) > 0)
1788
                {
1789
                    $_var_name .= implode("", $_indexes);
1790
                    $_indexes = array();
1791
                }
1792 4
                $_output = $_var_name;
1793
            } else {
1794 10
                $_output = "\$this->_tpl_vars['$_var_name']";
1795
            }
1796
1797 10
            foreach ($_indexes as $_index) {
0 ignored issues
show
The expression $_indexes of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1798 10
                if (substr($_index, 0, 1) == '[') {
1799 5
                    $_index = substr($_index, 1, -1);
1800 5
                    if (is_numeric($_index)) {
1801 3
                        $_output .= "[$_index]";
1802 5
                    } elseif (substr($_index, 0, 1) == '$') {
1803 5
                        if (strpos($_index, '.') !== false) {
1804 5
                            $_output .= '[' . $this->_parse_var($_index) . ']';
1805
                        } else {
1806 5
                            $_output .= "[\$this->_tpl_vars['" . substr($_index, 1) . "']]";
1807
                        }
1808
                    } else {
1809 1
                        $_var_parts = explode('.', $_index);
1810 1
                        $_var_section = $_var_parts[0];
1811 1
                        $_var_section_prop = isset($_var_parts[1]) ? $_var_parts[1] : 'index';
1812 5
                        $_output .= "[\$this->_sections['$_var_section']['$_var_section_prop']]";
1813
                    }
1814 10
                } else if (substr($_index, 0, 1) == '.') {
1815 10
                    if (substr($_index, 1, 1) == '$')
1816 4
                        $_output .= "[\$this->_tpl_vars['" . substr($_index, 2) . "']]";
1817
                    else
1818 10
                        $_output .= "['" . substr($_index, 1) . "']";
1819 2
                } else if (substr($_index,0,2) == '->') {
1820 2
                    if(substr($_index,2,2) == '__') {
1821
                        $this->_syntax_error('call to internal object members is not allowed', E_USER_ERROR, __FILE__, __LINE__);
1822 2
                    } elseif($this->security && substr($_index, 2, 1) == '_') {
1823
                        $this->_syntax_error('(secure) call to private object member is not allowed', E_USER_ERROR, __FILE__, __LINE__);
1824 2
                    } elseif (substr($_index, 2, 1) == '$') {
1825
                        if ($this->security) {
1826
                            $this->_syntax_error('(secure) call to dynamic object member is not allowed', E_USER_ERROR, __FILE__, __LINE__);
1827
                        } else {
1828
                            $_output .= '->{(($_var=$this->_tpl_vars[\''.substr($_index,3).'\']) && substr($_var,0,2)!=\'__\') ? $_var : $this->trigger_error("cannot access property \\"$_var\\"")}';
1829
                        }
1830
                    } else {
1831 2
                        $_output .= $_index;
1832
                    }
1833 2
                } elseif (substr($_index, 0, 1) == '(') {
1834 2
                    $_index = $this->_parse_parenth_args($_index);
1835 2
                    $_output .= $_index;
1836
                } else {
1837 10
                    $_output .= $_index;
1838
                }
1839
            }
1840
        }
1841
1842 10
        return $_output;
1843
    }
1844
1845
    /**
1846
     * parse arguments in function call parenthesis
1847
     *
1848
     * @param string $parenth_args
1849
     * @return string
1850
     */
1851 2
    function _parse_parenth_args($parenth_args)
1852
    {
1853 2
        preg_match_all('~' . $this->_param_regexp . '~',$parenth_args, $match);
1854 2
        $orig_vals = $match = $match[0];
1855 2
        $this->_parse_vars_props($match);
1856 2
        $replace = array();
1857 2
        for ($i = 0, $count = count($match); $i < $count; $i++) {
1858 2
            $replace[$orig_vals[$i]] = $match[$i];
1859
        }
1860 2
        return strtr($parenth_args, $replace);
1861
    }
1862
1863
    /**
1864
     * parse configuration variable expression into PHP code
1865
     *
1866
     * @param string $conf_var_expr
1867
     */
1868
    function _parse_conf_var($conf_var_expr)
1869
    {
1870
        $parts = explode('|', $conf_var_expr, 2);
1871
        $var_ref = $parts[0];
1872
        $modifiers = isset($parts[1]) ? $parts[1] : '';
1873
1874
        $var_name = substr($var_ref, 1, -1);
1875
1876
        $output = "\$this->_config[0]['vars']['$var_name']";
1877
1878
        $this->_parse_modifiers($output, $modifiers);
1879
1880
        return $output;
1881
    }
1882
1883
    /**
1884
     * parse section property expression into PHP code
1885
     *
1886
     * @param string $section_prop_expr
1887
     * @return string
1888
     */
1889
    function _parse_section_prop($section_prop_expr)
1890
    {
1891
        $parts = explode('|', $section_prop_expr, 2);
1892
        $var_ref = $parts[0];
1893
        $modifiers = isset($parts[1]) ? $parts[1] : '';
1894
1895
        preg_match('!%(\w+)\.(\w+)%!', $var_ref, $match);
1896
        $section_name = $match[1];
1897
        $prop_name = $match[2];
1898
1899
        $output = "\$this->_sections['$section_name']['$prop_name']";
1900
1901
        $this->_parse_modifiers($output, $modifiers);
1902
1903
        return $output;
1904
    }
1905
1906
1907
    /**
1908
     * parse modifier chain into PHP code
1909
     *
1910
     * sets $output to parsed modified chain
1911
     * @param string $output
1912
     * @param string $modifier_string
1913
     */
1914 10
    function _parse_modifiers(&$output, $modifier_string)
1915
    {
1916 10
        preg_match_all('~\|(@?\w+)((?>:(?:'. $this->_qstr_regexp . '|[^|]+))*)~', '|' . $modifier_string, $_match);
1917 10
        list(, $_modifiers, $modifier_arg_strings) = $_match;
1918
1919 10
        for ($_i = 0, $_for_max = count($_modifiers); $_i < $_for_max; $_i++) {
1920 8
            $_modifier_name = $_modifiers[$_i];
1921
1922 8
            if($_modifier_name == 'smarty') {
1923
                // skip smarty modifier
1924
                continue;
1925
            }
1926
1927 8
            preg_match_all('~:(' . $this->_qstr_regexp . '|[^:]+)~', $modifier_arg_strings[$_i], $_match);
1928 8
            $_modifier_args = $_match[1];
1929
1930 8
            if (substr($_modifier_name, 0, 1) == '@') {
1931 6
                $_map_array = false;
1932 6
                $_modifier_name = substr($_modifier_name, 1);
1933
            } else {
1934 7
                $_map_array = true;
1935
            }
1936
1937 8
            if (empty($this->_plugins['modifier'][$_modifier_name])
1938 8
                && !$this->_get_plugin_filepath('modifier', $_modifier_name)
1939 8
                && function_exists($_modifier_name)) {
1940 5
                if ($this->security && !in_array($_modifier_name, $this->security_settings['MODIFIER_FUNCS'])) {
1941
                    $this->_trigger_fatal_error("[plugin] (secure mode) modifier '$_modifier_name' is not allowed" , $this->_current_file, $this->_current_line_no, __FILE__, __LINE__);
1942
                } else {
1943 5
                    $this->_plugins['modifier'][$_modifier_name] = array($_modifier_name,  null, null, false);
1944
                }
1945
            }
1946 8
            $this->_add_plugin('modifier', $_modifier_name);
1947
1948 8
            $this->_parse_vars_props($_modifier_args);
1949
1950 8
            if($_modifier_name == 'default') {
1951
                // supress notifications of default modifier vars and args
1952 4
                if(substr($output, 0, 1) == '$') {
1953 4
                    $output = '@' . $output;
1954
                }
1955 4
                if(isset($_modifier_args[0]) && substr($_modifier_args[0], 0, 1) == '$') {
1956 3
                    $_modifier_args[0] = '@' . $_modifier_args[0];
1957
                }
1958
            }
1959 8
            if (count($_modifier_args) > 0)
1960 7
                $_modifier_args = ', '.implode(', ', $_modifier_args);
1961
            else
1962 7
                $_modifier_args = '';
1963
1964 8
            if ($_map_array) {
1965 7
                $output = "((is_array(\$_tmp=$output)) ? \$this->_run_mod_handler('$_modifier_name', true, \$_tmp$_modifier_args) : " . $this->_compile_plugin_call('modifier', $_modifier_name) . "(\$_tmp$_modifier_args))";
1966
1967
            } else {
1968
1969 6
                $output = $this->_compile_plugin_call('modifier', $_modifier_name)."($output$_modifier_args)";
1970
1971
            }
1972
        }
1973 10
    }
1974
1975
1976
    /**
1977
     * add plugin
1978
     *
1979
     * @param string $type
1980
     * @param string $name
1981
     * @param boolean? $delayed_loading
0 ignored issues
show
The doc-type boolean? could not be parsed: Unknown type name "boolean?" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1982
     */
1983 9
    function _add_plugin($type, $name, $delayed_loading = null)
1984
    {
1985 9
        if (!isset($this->_plugin_info[$type])) {
1986 9
            $this->_plugin_info[$type] = array();
1987
        }
1988 9
        if (!isset($this->_plugin_info[$type][$name])) {
1989 9
            $this->_plugin_info[$type][$name] = array($this->_current_file,
1990 9
                                                      $this->_current_line_no,
1991 9
                                                      $delayed_loading);
1992
        }
1993 9
    }
1994
1995
1996
    /**
1997
     * Compiles references of type $smarty.foo
1998
     *
1999
     * @param string $indexes
2000
     * @return string
2001
     */
2002 8
    function _compile_smarty_ref(&$indexes)
2003
    {
2004
        /* Extract the reference name. */
2005 8
        $_ref = substr($indexes[0], 1);
2006 8
        foreach($indexes as $_index_no=>$_index) {
0 ignored issues
show
The expression $indexes of type string is not traversable.
Loading history...
2007 8
            if (substr($_index, 0, 1) != '.' && $_index_no<2 || !preg_match('~^(\.|\[|->)~', $_index)) {
2008 8
                $this->_syntax_error('$smarty' . implode('', array_slice($indexes, 0, 2)) . ' is an invalid reference', E_USER_ERROR, __FILE__, __LINE__);
2009
            }
2010
        }
2011
2012
        switch ($_ref) {
2013 8
            case 'now':
2014
                $compiled_ref = 'time()';
2015
                $_max_index = 1;
2016
                break;
2017
2018 8
            case 'foreach':
2019 6
                array_shift($indexes);
2020 6
                $_var = $this->_parse_var_props(substr($indexes[0], 1));
2021 6
                $_propname = substr($indexes[1], 1);
2022 6
                $_max_index = 1;
2023
                switch ($_propname) {
2024 6
                    case 'index':
2025 2
                        array_shift($indexes);
2026 2
                        $compiled_ref = "(\$this->_foreach[$_var]['iteration']-1)";
2027 2
                        break;
2028
                        
2029 6
                    case 'first':
2030
                        array_shift($indexes);
2031
                        $compiled_ref = "(\$this->_foreach[$_var]['iteration'] <= 1)";
2032
                        break;
2033
2034 6
                    case 'last':
2035 1
                        array_shift($indexes);
2036 1
                        $compiled_ref = "(\$this->_foreach[$_var]['iteration'] == \$this->_foreach[$_var]['total'])";
2037 1
                        break;
2038
                        
2039 5
                    case 'show':
2040
                        array_shift($indexes);
2041
                        $compiled_ref = "(\$this->_foreach[$_var]['total'] > 0)";
2042
                        break;
2043
                        
2044
                    default:
2045 5
                        unset($_max_index);
2046 5
                        $compiled_ref = "\$this->_foreach[$_var]";
2047
                }
2048 6
                break;
2049
2050 5
            case 'section':
2051
                array_shift($indexes);
2052
                $_var = $this->_parse_var_props(substr($indexes[0], 1));
2053
                $compiled_ref = "\$this->_sections[$_var]";
2054
                break;
2055
2056 5
            case 'get':
2057
                if ($this->security && !$this->security_settings['ALLOW_SUPER_GLOBALS']) {
2058
                    $this->_syntax_error("(secure mode) super global access not permitted",
2059
                                         E_USER_WARNING, __FILE__, __LINE__);
2060
                    return;
2061
                }
2062
                $compiled_ref = "\$_GET";
2063
                break;
2064
2065 5
            case 'post':
2066
                if ($this->security && !$this->security_settings['ALLOW_SUPER_GLOBALS']) {
2067
                    $this->_syntax_error("(secure mode) super global access not permitted",
2068
                                         E_USER_WARNING, __FILE__, __LINE__);
2069
                    return;
2070
                }
2071
                $compiled_ref = "\$_POST";
2072
                break;
2073
2074 5
            case 'cookies':
2075 1
                if ($this->security && !$this->security_settings['ALLOW_SUPER_GLOBALS']) {
2076
                    $this->_syntax_error("(secure mode) super global access not permitted",
2077
                                         E_USER_WARNING, __FILE__, __LINE__);
2078
                    return;
2079
                }
2080 1
                $compiled_ref = "\$_COOKIE";
2081 1
                break;
2082
2083 5
            case 'env':
2084
                if ($this->security && !$this->security_settings['ALLOW_SUPER_GLOBALS']) {
2085
                    $this->_syntax_error("(secure mode) super global access not permitted",
2086
                                         E_USER_WARNING, __FILE__, __LINE__);
2087
                    return;
2088
                }
2089
                $compiled_ref = "\$_ENV";
2090
                break;
2091
2092 5
            case 'server':
2093
                if ($this->security && !$this->security_settings['ALLOW_SUPER_GLOBALS']) {
2094
                    $this->_syntax_error("(secure mode) super global access not permitted",
2095
                                         E_USER_WARNING, __FILE__, __LINE__);
2096
                    return;
2097
                }
2098
                $compiled_ref = "\$_SERVER";
2099
                break;
2100
2101 5
            case 'session':
2102
                if ($this->security && !$this->security_settings['ALLOW_SUPER_GLOBALS']) {
2103
                    $this->_syntax_error("(secure mode) super global access not permitted",
2104
                                         E_USER_WARNING, __FILE__, __LINE__);
2105
                    return;
2106
                }
2107
                $compiled_ref = "\$_SESSION";
2108
                break;
2109
2110
            /*
2111
             * These cases are handled either at run-time or elsewhere in the
2112
             * compiler.
2113
             */
2114 5
            case 'request':
2115 3
                if ($this->security && !$this->security_settings['ALLOW_SUPER_GLOBALS']) {
2116
                    $this->_syntax_error("(secure mode) super global access not permitted",
2117
                                         E_USER_WARNING, __FILE__, __LINE__);
2118
                    return;
2119
                }
2120 3
                if ($this->request_use_auto_globals) {
2121 3
                    $compiled_ref = "\$_REQUEST";
2122 3
                    break;
2123
                } else {
2124
                    $this->_init_smarty_vars = true;
2125
                }
2126
                return null;
2127
2128 4
            case 'capture':
2129 3
                return null;
2130
2131 1
            case 'template':
2132
                $compiled_ref = "'" . addslashes($this->_current_file) . "'";
2133
                $_max_index = 1;
2134
                break;
2135
2136 1
            case 'version':
2137
                $compiled_ref = "'$this->_version'";
2138
                $_max_index = 1;
2139
                break;
2140
2141 1
            case 'const':
2142 1
                if ($this->security && !$this->security_settings['ALLOW_CONSTANTS']) {
2143
                    $this->_syntax_error("(secure mode) constants not permitted",
2144
                                         E_USER_WARNING, __FILE__, __LINE__);
2145
                    return;
2146
                }
2147 1
                array_shift($indexes);
2148 1
                if (preg_match('!^\.\w+$!', $indexes[0])) {
2149 1
                    $compiled_ref = '@' . substr($indexes[0], 1);
2150
                } else {
2151
                    $_val = $this->_parse_var_props(substr($indexes[0], 1));
2152
                    $compiled_ref = '@constant(' . $_val . ')';
2153
                }
2154 1
                $_max_index = 1;
2155 1
                break;
2156
2157
            case 'config':
2158
                $compiled_ref = "\$this->_config[0]['vars']";
2159
                $_max_index = 3;
2160
                break;
2161
2162
            case 'ldelim':
2163
                $compiled_ref = "'$this->left_delimiter'";
2164
                break;
2165
2166
            case 'rdelim':
2167
                $compiled_ref = "'$this->right_delimiter'";
2168
                break;
2169
                
2170
            default:
2171
                $this->_syntax_error('$smarty.' . $_ref . ' is an unknown reference', E_USER_ERROR, __FILE__, __LINE__);
2172
                break;
2173
        }
2174
2175 8
        if (isset($_max_index) && count($indexes) > $_max_index) {
2176
            $this->_syntax_error('$smarty' . implode('', $indexes) .' is an invalid reference', E_USER_ERROR, __FILE__, __LINE__);
2177
        }
2178
2179 8
        array_shift($indexes);
2180 8
        return $compiled_ref;
2181
    }
2182
2183
    /**
2184
     * compiles call to plugin of type $type with name $name
2185
     * returns a string containing the function-name or method call
2186
     * without the paramter-list that would have follow to make the
2187
     * call valid php-syntax
2188
     *
2189
     * @param string $type
2190
     * @param string $name
2191
     * @return string
2192
     */
2193 9
    function _compile_plugin_call($type, $name) {
2194 9
        if (isset($this->_plugins[$type][$name])) {
2195
            /* plugin loaded */
2196 9
            if (is_array($this->_plugins[$type][$name][0])) {
2197
                return ((is_object($this->_plugins[$type][$name][0][0])) ?
2198
                        "\$this->_plugins['$type']['$name'][0][0]->"    /* method callback */
2199
                        : (string)($this->_plugins[$type][$name][0][0]).'::'    /* class callback */
2200
                       ). $this->_plugins[$type][$name][0][1];
2201
2202
            } else {
2203
                /* function callback */
2204 9
                return $this->_plugins[$type][$name][0];
2205
2206
            }
2207
        } else {
2208
            /* plugin not loaded -> auto-loadable-plugin */
2209 6
            return 'smarty_'.$type.'_'.$name;
2210
2211
        }
2212
    }
2213
2214
    /**
2215
     * load pre- and post-filters
2216
     */
2217 10
    function _load_filters()
2218
    {
2219 10
        if (count($this->_plugins['prefilter']) > 0) {
2220
            foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) {
2221
                if ($prefilter === false) {
2222
                    unset($this->_plugins['prefilter'][$filter_name]);
2223
                    $_params = array('plugins' => array(array('prefilter', $filter_name, null, null, false)));
2224
                    require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
2225
                    smarty_core_load_plugins($_params, $this);
2226
                }
2227
            }
2228
        }
2229 10
        if (count($this->_plugins['postfilter']) > 0) {
2230
            foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) {
2231
                if ($postfilter === false) {
2232
                    unset($this->_plugins['postfilter'][$filter_name]);
2233
                    $_params = array('plugins' => array(array('postfilter', $filter_name, null, null, false)));
2234
                    require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
2235
                    smarty_core_load_plugins($_params, $this);
2236
                }
2237
            }
2238
        }
2239 10
    }
2240
2241
2242
    /**
2243
     * Quote subpattern references
2244
     *
2245
     * @param string $string
2246
     * @return string
2247
     */
2248 10
    function _quote_replace($string)
2249
    {
2250 10
        return strtr($string, array('\\' => '\\\\', '$' => '\\$'));
2251
    }
2252
2253
    /**
2254
     * display Smarty syntax error
2255
     *
2256
     * @param string $error_msg
2257
     * @param integer $error_type
2258
     * @param string $file
2259
     * @param integer $line
2260
     */
2261
    function _syntax_error($error_msg, $error_type = E_USER_ERROR, $file=null, $line=null)
2262
    {
2263
        $this->_trigger_fatal_error("syntax error: $error_msg", $this->_current_file, $this->_current_line_no, $file, $line, $error_type);
2264
    }
2265
2266
2267
    /**
2268
     * check if the compilation changes from cacheable to
2269
     * non-cacheable state with the beginning of the current
2270
     * plugin. return php-code to reflect the transition.
2271
     * @return string
2272
     */
2273 9
    function _push_cacheable_state($type, $name) {
2274 9
        $_cacheable = !isset($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4];
2275 9
        if ($_cacheable
2276 9
            || 0<$this->_cacheable_state++) return '';
2277
        if (!isset($this->_cache_serial)) $this->_cache_serial = md5(uniqid('Smarty'));
2278
        $_ret = 'if ($this->caching && !$this->_cache_including): echo \'{nocache:'
2279
            . $this->_cache_serial . '#' . $this->_nocache_count
2280
            . '}\'; endif;';
2281
        return $_ret;
2282
    }
2283
2284
2285
    /**
2286
     * check if the compilation changes from non-cacheable to
2287
     * cacheable state with the end of the current plugin return
2288
     * php-code to reflect the transition.
2289
     * @return string
2290
     */
2291 9
    function _pop_cacheable_state($type, $name) {
2292 9
        $_cacheable = !isset($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4];
2293 9
        if ($_cacheable
2294 9
            || --$this->_cacheable_state>0) return '';
2295
        return 'if ($this->caching && !$this->_cache_including): echo \'{/nocache:'
2296
            . $this->_cache_serial . '#' . ($this->_nocache_count++)
2297
            . '}\'; endif;';
2298
    }
2299
2300
2301
    /**
2302
     * push opening tag-name, file-name and line-number on the tag-stack
2303
     * @param string the opening tag's name
2304
     */
2305 9
    function _push_tag($open_tag)
2306
    {
2307 9
        array_push($this->_tag_stack, array($open_tag, $this->_current_line_no));
2308 9
    }
2309
2310
    /**
2311
     * pop closing tag-name
2312
     * raise an error if this stack-top doesn't match with the closing tag
2313
     * @param string the closing tag's name
2314
     * @return string the opening tag's name
2315
     */
2316 9
    function _pop_tag($close_tag)
2317
    {
2318 9
        $message = '';
2319 9
        if (count($this->_tag_stack)>0) {
2320 9
            list($_open_tag, $_line_no) = array_pop($this->_tag_stack);
2321 9
            if ($close_tag == $_open_tag) {
2322 9
                return $_open_tag;
2323
            }
2324 8
            if ($close_tag == 'if' && ($_open_tag == 'else' || $_open_tag == 'elseif' )) {
2325 7
                return $this->_pop_tag($close_tag);
2326
            }
2327 4
            if ($close_tag == 'section' && $_open_tag == 'sectionelse') {
2328
                $this->_pop_tag($close_tag);
2329
                return $_open_tag;
2330
            }
2331 4
            if ($close_tag == 'foreach' && $_open_tag == 'foreachelse') {
2332 4
                $this->_pop_tag($close_tag);
2333 4
                return $_open_tag;
2334
            }
2335
            if ($_open_tag == 'else' || $_open_tag == 'elseif') {
2336
                $_open_tag = 'if';
2337
            } elseif ($_open_tag == 'sectionelse') {
2338
                $_open_tag = 'section';
2339
            } elseif ($_open_tag == 'foreachelse') {
2340
                $_open_tag = 'foreach';
2341
            }
2342
            $message = " expected {/$_open_tag} (opened line $_line_no).";
2343
        }
2344
        $this->_syntax_error("mismatched tag {/$close_tag}.$message",
2345
                             E_USER_ERROR, __FILE__, __LINE__);
2346
    }
2347
2348
}
2349
2350
/**
2351
 * compare to values by their string length
2352
 *
2353
 * @access private
2354
 * @param string $a
2355
 * @param string $b
2356
 * @return 0|-1|1
0 ignored issues
show
The doc-type 0|-1|1 could not be parsed: Unknown type name "0" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2357
 */
2358 1
function _smarty_sort_length($a, $b)
2359
{
2360
    if($a == $b)
2361
        return 0;
2362
2363
    if(strlen($a) == strlen($b))
2364
        return ($a > $b) ? -1 : 1;
2365
2366
    return (strlen($a) > strlen($b)) ? -1 : 1;
2367 1
}
2368
2369
2370
/* vim: set et: */
2371
2372
?>
2373