Issues (1369)

classes/template_compile.php (19 issues)

1
<?php
2
/**
3
*
4
* @package phpBB3
5
* @version $Id$
6
* @copyright (c) 2005 phpBB Group, sections (c) 2001 ispi of Lincoln Inc
7
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
8
*
9
* Modified by Gorlum to work within http://supernova.ws
10
*
11
*/
12
13
/**
14
* @ignore
15
*/
16
if (!defined('INSIDE'))
17
{
18
  exit;
19
}
20
21
/**
22
* Extension of template class - Functions needed for compiling templates only.
23
*
24
* psoTFX, phpBB Development Team - Completion of file caching, decompilation
25
* routines and implementation of conditionals/keywords and associated changes
26
*
27
* The interface was inspired by PHPLib templates,  and the template file (formats are
28
* quite similar)
29
*
30
* The keyword/conditional implementation is currently based on sections of code from
31
* the Smarty templating engine (c) 2001 ispi of Lincoln, Inc. which is released
32
* (on its own and in whole) under the LGPL. Section 3 of the LGPL states that any code
33
* derived from an LGPL application may be relicenced under the GPL, this applies
34
* to this source
35
*
36
* DEFINE directive inspired by a request by Cyberalien
37
*
38
* @package phpBB3
39
*/
40
class template_compile
41
{
42
  var $template;
43
44
  // Various storage arrays
45
  var $block_names = array();
46
  var $block_else_level = array();
47
48
  /**
49
   * template_compile constructor.
50
   *
51
   * @param template $template
52
   */
53
  public function __construct($template) {
54
    $this->template = $template;
55
  }
56
57
  /**
58
  * Load template source from file
59
  * @access private
60
  */
61
  function _tpl_load_file($handle, $store_in_db = false)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
62
  {
63
    // Try and open template for read
64
    if (!file_exists($this->template->files[$handle]))
65
    {
66
      if (!file_exists($this->template->files_inherit[$handle]))
67
      {
68
//        pdump($handle);
69
////        global $debug;
70
//        var_dump((debug_backtrace()));
71
//        die();
72
73
        SN::$gc->debug->warning("template->_tpl_load_file(): File {$this->template->files[$handle]} does not exist or is empty");
74
75
        return;
76
        trigger_error("template->_tpl_load_file(): File {$this->template->files[$handle]} does not exist or is empty", E_USER_ERROR);
0 ignored issues
show
trigger_error('template-...s empty', E_USER_ERROR) is not 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...
77
      }
78
      else
79
      {
80
        $this->template->files[$handle] = $this->template->files_inherit[$handle];
81
      }
82
    }
83
84
    $html = $this->minify(@file_get_contents($this->template->files[$handle]));
85
86
    $this->template->compiled_code[$handle] = $this->compile(trim($html));
0 ignored issues
show
It seems like $html can also be of type false; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

86
    $this->template->compiled_code[$handle] = $this->compile(trim(/** @scrutinizer ignore-type */ $html));
Loading history...
87
88
    // Actually compile the code now.
89
    $this->compile_write($handle, $this->template->compiled_code[$handle]);
90
91
    // Store in database if required...
92
    if ($store_in_db)
93
    {
94
//      global $db, $user;
95
//
96
//      $sql_ary = array(
97
//        'template_id'     => $this->template->files_template[$handle],
98
//        'template_filename'   => $this->template->filename[$handle],
99
//        'template_included'   => '',
100
//        'template_mtime'    => time(),
101
//        'template_data'     => trim(@file_get_contents($this->template->files[$handle])),
102
//      );
103
//
104
//      $sql = 'INSERT INTO ' . STYLES_TEMPLATE_DATA_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
105
//      $db->sql_query($sql);
106
    }
107
  }
108
109
  /**
110
  * Remove any PHP tags that do not belong, these regular expressions are derived from
111
  * the ones that exist in zend_language_scanner.l
112
  * @access private
113
  */
114
  function remove_php_tags(&$code)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
115
  {
116
    // This matches the information gathered from the internal PHP lexer
117
    $match = array(
118
      '#<([\?%])=?.*?\1>#s',
119
      '#<script\s+language\s*=\s*(["\']?)php\1\s*>.*?</script\s*>#s',
120
      '#<\?php(?:\r\n?|[ \n\t]).*?\?>#s'
121
    );
122
123
    $code = preg_replace($match, '', $code);
124
  }
125
126
  /**
127
  * The all seeing all doing compile method. Parts are inspired by or directly from Smarty
128
  * @access private
129
  */
130
  function compile($code, $no_echo = false, $echo_var = '')
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
131
  {
132
    if ($echo_var)
133
    {
134
      global $$echo_var;
135
    }
136
137
    // Remove any "loose" php ... we want to give admins the ability
138
    // to switch on/off PHP for a given template. Allowing unchecked
139
    // php is a no-no. There is a potential issue here in that non-php
140
    // content may be removed ... however designers should use entities
141
    // if they wish to display < and >
142
    $this->remove_php_tags($code);
143
144
    // Pull out all block/statement level elements and separate plain text
145
    preg_match_all('#<!-- PHP -->(.*?)<!-- ENDPHP -->#s', $code, $matches);
146
    $php_blocks = $matches[1];
147
    $code = preg_replace('#<!-- PHP -->.*?<!-- ENDPHP -->#s', '<!-- PHP -->', $code);
148
149
    preg_match_all('#<!-- INCLUDE (\{\$?[A-Z0-9\-_]+\}|[a-zA-Z0-9\_\-\+\./]+) -->#', $code, $matches);
150
    $include_blocks = $matches[1];
151
    if($include_blocks)
152
    {
153
      foreach($include_blocks as &$included_file)
154
      {
155
        $included_file .= '.tpl.html';
156
      }
157
    }
158
    $code = preg_replace('#<!-- INCLUDE (?:\{\$?[A-Z0-9\-_]+\}|[a-zA-Z0-9\_\-\+\./]+) -->#', '<!-- INCLUDE -->', $code);
159
160
    preg_match_all('#<!-- INCLUDEPHP ([a-zA-Z0-9\_\-\+\./]+) -->#', $code, $matches);
161
    $includephp_blocks = $matches[1];
162
    $code = preg_replace('#<!-- INCLUDEPHP [a-zA-Z0-9\_\-\+\./]+ -->#', '<!-- INCLUDEPHP -->', $code);
163
164
    preg_match_all('#<!-- ([^<].*?) (.*?)? ?-->#', $code, $blocks, PREG_SET_ORDER);
165
166
    $text_blocks = preg_split('#<!-- [^<].*? (?:.*?)? ?-->#', $code);
167
168
    for ($i = 0, $j = sizeof($text_blocks); $i < $j; $i++)
169
    {
170
      $this->compile_var_tags($text_blocks[$i]);
171
    }
172
    $compile_blocks = array();
173
174
    for ($curr_tb = 0, $tb_size = sizeof($blocks); $curr_tb < $tb_size; $curr_tb++)
175
    {
176
      $block_val = &$blocks[$curr_tb];
177
178
      switch ($block_val[1])
179
      {
180
        case 'BEGIN':
181
          $this->block_else_level[] = false;
182
          $compile_blocks[] = '<?php ' . $this->compile_tag_block($block_val[2]) . ' ?>';
183
        break;
184
185
        case 'BEGINELSE':
186
          $this->block_else_level[sizeof($this->block_else_level) - 1] = true;
187
          $compile_blocks[] = '<?php }} else { ?>';
188
        break;
189
190
        case 'END':
191
          array_pop($this->block_names);
192
          $compile_blocks[] = '<?php ' . ((array_pop($this->block_else_level)) ? '}' : '}}') . ' ?>';
193
        break;
194
195
        case 'IF':
196
          $compile_blocks[] = '<?php ' . $this->compile_tag_if($block_val[2], false) . ' ?>';
197
        break;
198
199
        case 'ELSE':
200
          $compile_blocks[] = '<?php } else { ?>';
201
        break;
202
203
        case 'ELSEIF':
204
          $compile_blocks[] = '<?php ' . $this->compile_tag_if($block_val[2], true) . ' ?>';
205
        break;
206
207
        case 'ENDIF':
208
          $compile_blocks[] = '<?php } ?>';
209
        break;
210
211
        case 'DEFINE':
212
          $compile_blocks[] = '<?php ' . $this->compile_tag_define($block_val[2], true) . ' ?>';
213
        break;
214
215
        case 'UNDEFINE':
216
          $compile_blocks[] = '<?php ' . $this->compile_tag_define($block_val[2], false) . ' ?>';
217
        break;
218
219
        case 'INCLUDE':
220
          $temp = array_shift($include_blocks);
221
222
          // Dynamic includes
223
          // Cheap match rather than a full blown regexp, we already know
224
          // the format of the input so just use string manipulation.
225
          if ($temp[0] == '{')
226
          {
227
            $file = false;
228
229
            if ($temp[1] == '$')
230
            {
231
              $var = substr($temp, 2, -1);
232
              //$file = $this->template->_tpldata['DEFINE']['.'][$var];
233
              $temp = "\$this->_tpldata['DEFINE']['.']['$var']";
234
            }
235
            else
236
            {
237
              $var = substr($temp, 1, -1);
238
              //$file = $this->template->_rootref[$var];
239
              $temp = "\$this->_rootref['$var']";
240
            }
241
          }
242
          else
243
          {
244
            $file = $temp;
245
          }
246
247
          $compile_blocks[] = '<?php ' . $this->compile_tag_include($temp) . ' ?>';
248
249
          // No point in checking variable includes
250
          if ($file)
251
          {
252
            $this->template->_tpl_include($file, false);
253
          }
254
        break;
255
256
        case 'INCLUDEPHP':
257
          $compile_blocks[] = (SN::$config->tpl_allow_php) ? '<?php ' . $this->compile_tag_include_php(array_shift($includephp_blocks)) . ' ?>' : '';
258
        break;
259
260
        case 'PHP':
261
          $compile_blocks[] = (SN::$config->tpl_allow_php) ? '<?php ' . array_shift($php_blocks) . ' ?>' : '';
262
        break;
263
264
        default:
265
          $this->compile_var_tags($block_val[0]);
266
          $trim_check = trim($block_val[0]);
267
          $compile_blocks[] = (!$no_echo) ? ((!empty($trim_check)) ? $block_val[0] : '') : ((!empty($trim_check)) ? $block_val[0] : '');
268
        break;
269
      }
270
    }
271
272
    $template_php = '';
273
    for ($i = 0, $size = sizeof($text_blocks); $i < $size; $i++)
274
    {
275
      $trim_check_text = trim($text_blocks[$i]);
276
      $template_php .= (!$no_echo) ? (($trim_check_text != '') ? $text_blocks[$i] : '') . ((isset($compile_blocks[$i])) ? $compile_blocks[$i] : '') : (($trim_check_text != '') ? $text_blocks[$i] : '') . ((isset($compile_blocks[$i])) ? $compile_blocks[$i] : '');
277
    }
278
279
    // Remove unused opening/closing tags
280
    $template_php = str_replace(' ?><?php ', ' ', $template_php);
281
282
    // Now add a newline after each php closing tag which already has a newline
283
    // PHP itself strips a newline if a closing tag is used (this is documented behaviour) and it is mostly not intended by style authors to remove newlines
284
    $template_php = preg_replace('#\?\>([\r\n])#', '?>\1\1', $template_php);
285
286
    // There will be a number of occasions where we switch into and out of
287
    // PHP mode instantaneously. Rather than "burden" the parser with this
288
    // we'll strip out such occurences, minimising such switching
289
    if ($no_echo)
290
    {
291
      return "\$$echo_var .= '" . $template_php . "'";
292
    }
293
294
    return $template_php;
295
  }
296
297
  /**
298
  * Compile variables
299
  * @access private
300
  */
301
  function compile_var_tags(&$text_blocks)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
302
  {
303
    // including $lang variable
304
    // global $lang, $config; // NOT NEDEED - $lang now is global!
305
306
    // change template varrefs into PHP varrefs
307
    $varrefs = array();
308
309
    // This one will handle varrefs WITH namespaces
310
    preg_match_all('#\{((?:[a-z0-9\-_]+\.)+)(\$)?([A-Z0-9\-_]+)(?:(\|.+?)*)?\}#', $text_blocks, $varrefs, PREG_SET_ORDER);
311
312
    foreach ($varrefs as $var_val)
313
    {
314
      $namespace = $var_val[1];
315
      $varname = $var_val[3];
316
      $new = $this->generate_block_varref($namespace, $varname, $var_val[2]);
317
318
      if(!empty($var_val[4])) {
319
        $new = \Ptl\PtlVariableDecorator::decorate($var_val[0], $new, $this->template);
320
      }
321
322
      $new = "<?php echo $new; ?>";
323
324
      $text_blocks = str_replace($var_val[0], $new, $text_blocks);
325
    }
326
327
    // This will handle the remaining root-level varrefs
328
329
    // Prefix R_ means "render this block again". Only one level of rendering supported to avoid circular references
330
    if (strpos($text_blocks, '{R_') !== false) {
331
      $text_blocks = preg_replace(/** @lang RegExp */'#\{R_([a-zA-Z0-9\-_\.\$\[\]]+)\}#', /** @lang PHP */'<?php $this->reRender(\'\\1\'); ?>', $text_blocks);
332
    }
333
334
    // transform vars prefixed by I_ into skin-specific images with context
335
    if (strpos($text_blocks, '{I_') !== false && is_callable(array('SkinV2', 'image_url'))) {
336
      $text_blocks = preg_replace(/** @lang RegExp */'#\{I_(.+?)\}#', /** @lang PHP */'<?php echo SkinV2::image_url(\'\\1\', $this); ?>', $text_blocks);
337
    }
338
339
    // transform vars prefixed by C_ into global config value
340
    if (strpos($text_blocks, '{C_') !== false)
341
    {
342
      $text_blocks = preg_replace(/** @lang RegExp */'#\{C_([a-zA-Z0-9\-_]+)\[([a-zA-Z0-9\-_]*?)\]\}#', /** @lang PHP */'<?php echo ((isset($this->_rootref[\'C_\\1\'][\'\\2\'])) ? $this->_rootref[\'C_\\1\'][\'\\2\'] : ((isset(SN::$config[\'\\1\'][\'\\2\'])) ? SN::$config[\'\\1\'][\'\\2\'] : \'{ \\1[\\2] }\')); ?>', $text_blocks);
343
      $text_blocks = preg_replace(/** @lang RegExp */'#\{C_([a-zA-Z0-9\-_]+)\}#', /** @lang PHP */'<?php echo ((isset($this->_rootref[\'C_\\1\'])) ? $this->_rootref[\'C_\\1\'] : ((isset(SN::$config[\'\\1\'])) ? SN::$config[\'\\1\'] : \'{ C_\\1 }\')); ?>', $text_blocks);
344
    }
345
    // transform vars prefixed by D_ into global defined constant
346
    if (strpos($text_blocks, '{D_') !== false)
347
    {
348
      $text_blocks = preg_replace(/** @lang RegExp */'#\{D_([a-zA-Z0-9\-_]+)\}#', /** @lang PHP */'<?php echo ((isset($this->_rootref[\'D_\\1\'])) ? $this->_rootref[\'D_\\1\'] : ((defined(\'\\1\')) ? \\1 : \'{ D_\\1 }\')); ?>', $text_blocks);
349
    }
350
    // transform vars prefixed by L_ into their language variable pendant if nothing is set within the tpldata array
351
    if (strpos($text_blocks, '{L_') !== false)
352
    {
353
      $text_blocks = preg_replace(/** @lang RegExp */'#\{L_([a-zA-Z0-9\-_]+)\[D_([a-zA-Z0-9\-_]*?)\]\}#', /** @lang PHP */'<?php echo ((isset($this->_rootref[\'L_\\1\'][\\2])) ? $this->_rootref[\'L_\\1\'][\\2] : ((isset(SN::$lang[\'\\1\'][\\2])) ? SN::$lang[\'\\1\'][\\2] : \'{ \\1[\\2] }\')); ?>', $text_blocks);
354
      $text_blocks = preg_replace(/** @lang RegExp */'#\{L_([a-zA-Z0-9\-_]+)\[([a-zA-Z0-9\-_]*?)\]\}#', /** @lang PHP */'<?php echo ((isset($this->_rootref[\'L_\\1\'][\'\\2\'])) ? $this->_rootref[\'L_\\1\'][\'\\2\'] : ((isset(SN::$lang[\'\\1\'][\'\\2\'])) ? SN::$lang[\'\\1\'][\'\\2\'] : \'{ \\1[\\2] }\')); ?>', $text_blocks);
355
      $text_blocks = preg_replace(/** @lang RegExp */'#\{L_([a-zA-Z0-9\-_]+)\}#', /** @lang PHP */'<?php echo ((isset($this->_rootref[\'L_\\1\'])) ? $this->_rootref[\'L_\\1\'] : ((isset(SN::$lang[\'\\1\'])) ? SN::$lang[\'\\1\'] : \'{ L_\\1 }\')); ?>', $text_blocks);
356
    }
357
358
    // Handle addslashed language variables prefixed with LA_
359
    // If a template variable already exist, it will be used in favor of it...
360
    if (strpos($text_blocks, '{LA_') !== false)
361
    {
362
      $text_blocks = preg_replace(/** @lang RegExp */'#\{LA_([a-zA-Z0-9\-_]+)\}#', /** @lang PHP */'<?php echo ((isset($this->_rootref[\'LA_\\1\'])) ? $this->_rootref[\'LA_\\1\'] : ((isset($this->_rootref[\'L_\\1\'])) ? addslashes($this->_rootref[\'L_\\1\']) : ((isset(SN::$lang[\'\\1\'])) ? addslashes(SN::$lang[\'\\1\']) : \'{ LA_\\1 }\'))); ?>', $text_blocks);
363
    }
364
365
    // Handle remaining varrefs
366
    $text_blocks = preg_replace(/** @lang RegExp */'#\{([a-zA-Z0-9\-_]+)\}#', /** @lang PHP */'<?php echo (isset($this->_rootref[\'\\1\'])) ? $this->_rootref[\'\\1\'] : \'\'; ?>', $text_blocks);
367
    $text_blocks = preg_replace(/** @lang RegExp */'#\{\$([a-zA-Z0-9\-_]+)\}#', /** @lang PHP */'<?php echo (isset($this->_tpldata[\'DEFINE\'][\'.\'][\'\\1\'])) ? $this->_tpldata[\'DEFINE\'][\'.\'][\'\\1\'] : \'\'; ?>', $text_blocks);
368
369
    return;
370
  }
371
372
  /**
373
  * Compile blocks
374
  * @access private
375
  */
376
  function compile_tag_block($tag_args)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
377
  {
378
    $no_nesting = false;
379
380
    // Is the designer wanting to call another loop in a loop?
381
    if (strpos($tag_args, '!') === 0)
382
    {
383
      // Count the number if ! occurrences (not allowed in vars)
384
      $no_nesting = substr_count($tag_args, '!');
385
      $tag_args = substr($tag_args, $no_nesting);
386
    }
387
388
    // Allow for control of looping (indexes start from zero):
389
    // foo(2)    : Will start the loop on the 3rd entry
390
    // foo(-2)   : Will start the loop two entries from the end
391
    // foo(3,4)  : Will start the loop on the fourth entry and end it on the fifth
392
    // foo(3,-4) : Will start the loop on the fourth entry and end it four from last
393
    if (preg_match('#^([^()]*)\(([\-\d]+)(?:,([\-\d]+))?\)$#', $tag_args, $match))
394
    {
395
      $tag_args = $match[1];
396
397
      if ($match[2] < 0)
398
      {
399
        $loop_start = '($_' . $tag_args . '_count ' . $match[2] . ' < 0 ? 0 : $_' . $tag_args . '_count ' . $match[2] . ')';
400
      }
401
      else
402
      {
403
        $loop_start = '($_' . $tag_args . '_count < ' . $match[2] . ' ? $_' . $tag_args . '_count : ' . $match[2] . ')';
404
      }
405
406
      if (strlen($match[3]) < 1 || $match[3] == -1)
407
      {
408
        $loop_end = '$_' . $tag_args . '_count';
409
      }
410
      else if ($match[3] >= 0)
411
      {
412
        $loop_end = '(' . ($match[3] + 1) . ' > $_' . $tag_args . '_count ? $_' . $tag_args . '_count : ' . ($match[3] + 1) . ')';
413
      }
414
      else //if ($match[3] < -1)
415
      {
416
        $loop_end = '$_' . $tag_args . '_count' . ($match[3] + 1);
417
      }
418
    }
419
    else
420
    {
421
      $loop_start = 0;
422
      $loop_end = '$_' . $tag_args . '_count';
423
    }
424
425
    $tag_template_php = '';
426
    array_push($this->block_names, $tag_args);
427
428
    if ($no_nesting !== false)
429
    {
430
      // We need to implode $no_nesting times from the end...
431
      $block = array_slice($this->block_names, -$no_nesting);
432
    }
433
    else
434
    {
435
      $block = $this->block_names;
436
    }
437
438
    if (sizeof($block) < 2)
439
    {
440
      // Block is not nested.
441
      $tag_template_php = '$_' . $tag_args . "_count = (isset(\$this->_tpldata['$tag_args'])) ? sizeof(\$this->_tpldata['$tag_args']) : 0;";
442
      $varref = "\$this->_tpldata['$tag_args']";
443
    }
444
    else
445
    {
446
      // This block is nested.
447
      // Generate a namespace string for this block.
448
      $namespace = implode('.', $block);
449
450
      // Get a reference to the data array for this block that depends on the
451
      // current indices of all parent blocks.
452
      $varref = $this->generate_block_data_ref($namespace, false);
453
454
      // Create the for loop code to iterate over this block.
455
      $tag_template_php = '$_' . $tag_args . '_count = (isset(' . $varref . ')) ? sizeof(' . $varref . ') : 0;';
456
    }
457
458
    $tag_template_php .= 'if ($_' . $tag_args . '_count) {';
459
460
    /**
461
    * The following uses foreach for iteration instead of a for loop, foreach is faster but requires PHP to make a copy of the contents of the array which uses more memory
462
    * <code>
463
    * if (!$offset)
464
    * {
465
    *   $tag_template_php .= 'foreach (' . $varref . ' as $_' . $tag_args . '_i => $_' . $tag_args . '_val){';
466
    * }
467
    * </code>
468
    */
469
470
    $tag_template_php .= 'for ($_' . $tag_args . '_i = ' . $loop_start . '; $_' . $tag_args . '_i < ' . $loop_end . '; ++$_' . $tag_args . '_i){';
471
//    $tag_template_php .= '$this->_block_counter["'. $tag_args . '"] = $_' . $tag_args . '_i;';
472
    $tag_template_php .= '$_'. $tag_args . '_val = &' . $varref . '[$_'. $tag_args. '_i];';
473
    $tag_template_php .= '$this->_block_value["'. $tag_args . '"] = &' . $varref . '[$_'. $tag_args. '_i];';
474
475
    return $tag_template_php;
476
  }
477
478
  /**
479
  * Compile IF tags - much of this is from Smarty with
480
  * some adaptions for our block level methods
481
  * @access private
482
  */
483
  function compile_tag_if($tag_args, $elseif)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
484
  {
485
    // Tokenize args for 'if' tag.
486
    preg_match_all('/(?:
487
      "[^"\\\\]*(?:\\\\.[^"\\\\]*)*"         |
488
      \'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'     |
489
      [(),]                                  |
490
      [^\s(),]+)/x', $tag_args, $match);
491
492
    $tokens = $match[0];
493
    $is_arg_stack = array();
494
495
    for ($i = 0, $size = sizeof($tokens); $i < $size; $i++)
496
    {
497
      $token = &$tokens[$i];
498
499
      switch ($token)
500
      {
501
        case '!==':
502
        case '===':
503
        case '<<':
504
        case '>>':
505
        case '|':
506
        case '^':
507
        case '&':
508
        case '~':
509
        case ')':
510
        case ',':
511
        case '+':
512
        case '-':
513
        case '*':
514
        case '/':
515
        case '@':
516
        break;
517
518
        case '==':
519
        case 'eq':
520
          $token = '==';
521
        break;
522
523
        case '!=':
524
        case '<>':
525
        case 'ne':
526
        case 'neq':
527
          $token = '!=';
528
        break;
529
530
        case '<':
531
        case 'lt':
532
          $token = '<';
533
        break;
534
535
        case '<=':
536
        case 'le':
537
        case 'lte':
538
          $token = '<=';
539
        break;
540
541
        case '>':
542
        case 'gt':
543
          $token = '>';
544
        break;
545
546
        case '>=':
547
        case 'ge':
548
        case 'gte':
549
          $token = '>=';
550
        break;
551
552
        case '&&':
553
        case 'and':
554
          $token = '&&';
555
        break;
556
557
        case '||':
558
        case 'or':
559
          $token = '||';
560
        break;
561
562
        case '!':
563
        case 'not':
564
          $token = '!';
565
        break;
566
567
        case '%':
568
        case 'mod':
569
          $token = '%';
570
        break;
571
572
        case '(':
573
          array_push($is_arg_stack, $i);
574
        break;
575
576
        case 'is':
577
          $is_arg_start = ($tokens[$i-1] == ')') ? array_pop($is_arg_stack) : $i-1;
578
          $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start));
579
580
          $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1));
581
582
          array_splice($tokens, $is_arg_start, sizeof($tokens), $new_tokens);
583
584
          $i = $is_arg_start;
585
586
        // no break
587
588
        default:
589
          if (preg_match('#^((?:[a-z0-9\-_]+\.)+)?(\$)?(?=[A-Za-z])([A-Za-z0-9\-_]+)#s', $token, $varrefs))
590
          {
591
            $token = (!empty($varrefs[1])) ? $this->generate_block_data_ref(substr($varrefs[1], 0, -1), true, $varrefs[2]) . '[\'' . $varrefs[3] . '\']' : (($varrefs[2]) ? '$this->_tpldata[\'DEFINE\'][\'.\'][\'' . $varrefs[3] . '\']' : '$this->_rootref[\'' . $varrefs[3] . '\']');
592
          }
593
          else if (preg_match('#^\.((?:[a-z0-9\-_]+\.?)+)$#s', $token, $varrefs))
594
          {
595
            // Allow checking if loops are set with .loopname
596
            // It is also possible to check the loop count by doing <!-- IF .loopname > 1 --> for example
597
            $blocks = explode('.', $varrefs[1]);
598
599
            // If the block is nested, we have a reference that we can grab.
600
            // If the block is not nested, we just go and grab the block from _tpldata
601
            if (sizeof($blocks) > 1)
602
            {
603
              $block = array_pop($blocks);
604
              $namespace = implode('.', $blocks);
605
              $varref = $this->generate_block_data_ref($namespace, true);
606
607
              // Add the block reference for the last child.
608
              $varref .= "['" . $block . "']";
609
            }
610
            else
611
            {
612
              $varref = '$this->_tpldata';
613
614
              // Add the block reference for the last child.
615
              $varref .= "['" . $blocks[0] . "']";
616
            }
617
            $token = "(empty($varref) ? 0 : sizeof($varref))";
618
          }
619
          else if (!empty($token))
620
          {
621
            $token = '(' . $token . ')';
622
          }
623
624
        break;
625
      }
626
    }
627
628
    // If there are no valid tokens left or only control/compare characters left, we do skip this statement
629
    if (!sizeof($tokens) || str_replace(array(' ', '=', '!', '<', '>', '&', '|', '%', '(', ')'), '', implode('', $tokens)) == '')
630
    {
631
      $tokens = array('false');
632
    }
633
    return (($elseif) ? '} else if (' : 'if (') . (implode(' ', $tokens) . ') { ');
634
  }
635
636
  /**
637
  * Compile DEFINE tags
638
  * @access private
639
  */
640
  function compile_tag_define($tag_args, $op)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
641
  {
642
    preg_match('#^((?:[a-z0-9\-_]+\.)+)?\$(?=[A-Z])([A-Z0-9_\-]*)(?: = (\'?)([^\']*)(\'?))?$#', $tag_args, $match);
643
644
    if (empty($match[2]) || (!isset($match[4]) && $op))
645
    {
646
      return '';
647
    }
648
649
    if (!$op)
650
    {
651
      return 'unset(' . (($match[1]) ? $this->generate_block_data_ref(substr($match[1], 0, -1), true, true) . '[\'' . $match[2] . '\']' : '$this->_tpldata[\'DEFINE\'][\'.\'][\'' . $match[2] . '\']') . ');';
652
    }
653
654
    // Are we a string?
655
    if ($match[3] && $match[5])
656
    {
657
      $match[4] = str_replace(array('\\\'', '\\\\', '\''), array('\'', '\\', '\\\''), $match[4]);
658
659
      // Compile reference, we allow template variables in defines...
660
      $match[4] = $this->compile($match[4]);
661
662
      // Now replace the php code
663
      $match[4] = "'" . str_replace(array('<?php echo ', '; ?>'), array("' . ", " . '"), $match[4]) . "'";
664
    }
665
    else
666
    {
667
      preg_match('#true|false|\.#i', $match[4], $type);
668
669
      switch (strtolower($type[0]))
670
      {
671
        case 'true':
672
        case 'false':
673
          $match[4] = strtoupper($match[4]);
674
        break;
675
676
        case '.':
677
          $match[4] = doubleval($match[4]);
678
        break;
679
680
        default:
681
          $match[4] = intval($match[4]);
682
        break;
683
      }
684
    }
685
686
    return (($match[1]) ? $this->generate_block_data_ref(substr($match[1], 0, -1), true, true) . '[\'' . $match[2] . '\']' : '$this->_tpldata[\'DEFINE\'][\'.\'][\'' . $match[2] . '\']') . ' = ' . $match[4] . ';';
687
  }
688
689
  /**
690
  * Compile INCLUDE tag
691
  * @access private
692
  */
693
  function compile_tag_include($tag_args)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
694
  {
695
    // Process dynamic includes
696
    if ($tag_args[0] == '$')
697
    {
698
      return "if (isset($tag_args)) { \$this->_tpl_include($tag_args); }";
699
    }
700
701
    return "\$this->_tpl_include('$tag_args');";
702
  }
703
704
  /**
705
  * Compile INCLUDE_PHP tag
706
  * @access private
707
  */
708
  function compile_tag_include_php($tag_args)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
709
  {
710
    return "\$this->_php_include('$tag_args');";
711
  }
712
713
  /**
714
  * parse expression
715
  * This is from Smarty
716
  * @access private
717
  */
718
  function _parse_is_expr($is_arg, $tokens)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
719
  {
720
    $expr_end = 0;
721
    $negate_expr = false;
722
723
    if (($first_token = array_shift($tokens)) == 'not')
724
    {
725
      $negate_expr = true;
726
      $expr_type = array_shift($tokens);
727
    }
728
    else
729
    {
730
      $expr_type = $first_token;
731
    }
732
733
    switch ($expr_type)
734
    {
735
      case 'even':
736
        if (@$tokens[$expr_end] == 'by')
737
        {
738
          $expr_end++;
739
          $expr_arg = $tokens[$expr_end++];
740
          $expr = "!(($is_arg / $expr_arg) % $expr_arg)";
741
        }
742
        else
743
        {
744
          $expr = "!($is_arg & 1)";
745
        }
746
      break;
747
748
      case 'odd':
749
        if (@$tokens[$expr_end] == 'by')
750
        {
751
          $expr_end++;
752
          $expr_arg = $tokens[$expr_end++];
753
          $expr = "(($is_arg / $expr_arg) % $expr_arg)";
754
        }
755
        else
756
        {
757
          $expr = "($is_arg & 1)";
758
        }
759
      break;
760
761
      case 'div':
762
        if (@$tokens[$expr_end] == 'by')
763
        {
764
          $expr_end++;
765
          $expr_arg = $tokens[$expr_end++];
766
          $expr = "!($is_arg % $expr_arg)";
767
        }
768
      break;
769
    }
770
771
    if ($negate_expr)
772
    {
773
      $expr = "!($expr)";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $expr does not seem to be defined for all execution paths leading up to this point.
Loading history...
774
    }
775
776
    array_splice($tokens, 0, $expr_end, $expr);
777
778
    return $tokens;
779
  }
780
781
  /**
782
   * Generates a reference to the given variable inside the given (possibly nested)
783
   * block namespace. This is a string of the form:
784
   * ' . $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['varname'] . '
785
   * It's ready to be inserted into an "echo" line in one of the templates.
786
   * NOTE: expects a trailing "." on the namespace.
787
   *
788
   * @param string $namespace
789
   * @param string $varname
790
   * @param bool   $defop
791
   *
792
   * @return string
793
   */
794
  private function generate_block_varref($namespace, $varname, $defop = false)
795
  {
796
    // Strip the trailing period.
797
    $namespace = substr($namespace, 0, -1);
798
799
    // Get a reference to the data block for this namespace.
800
    $varref = $this->generate_block_data_ref($namespace, true, $defop);
801
    // Prepend the necessary code to stick this in an echo line.
802
803
    // Append the variable reference.
804
    $varref .= "['$varname']";
805
806
    return $varref;
807
  }
808
809
  /**
810
  * Generates a reference to the array of data values for the given
811
  * (possibly nested) block namespace. This is a string of the form:
812
  * $this->_tpldata['parent'][$_parent_i]['$child1'][$_child1_i]['$child2'][$_child2_i]...['$childN']
813
  *
814
  * If $include_last_iterator is true, then [$_childN_i] will be appended to the form shown above.
815
  * NOTE: does not expect a trailing "." on the blockname.
816
  * @access private
817
  */
818
  function generate_block_data_ref($blockname, $include_last_iterator, $defop = false)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
819
  {
820
    // Get an array of the blocks involved.
821
    $blocks = explode('.', $blockname);
822
    $blockcount = sizeof($blocks) - 1;
823
824
    // DEFINE is not an element of any referenced variable, we must use _tpldata to access it
825
    if ($defop)
826
    {
827
      $varref = '$this->_tpldata[\'DEFINE\']';
828
      // Build up the string with everything but the last child.
829
      for ($i = 0; $i < $blockcount; $i++)
830
      {
831
        $varref .= "['" . $blocks[$i] . "'][\$_" . $blocks[$i] . '_i]';
832
      }
833
      // Add the block reference for the last child.
834
      $varref .= "['" . $blocks[$blockcount] . "']";
835
      // Add the iterator for the last child if requried.
836
      if ($include_last_iterator)
837
      {
838
        $varref .= '[$_' . $blocks[$blockcount] . '_i]';
839
      }
840
      return $varref;
841
    }
842
    else if ($include_last_iterator)
843
    {
844
      return '$_'. $blocks[$blockcount] . '_val';
845
    }
846
    else
847
    {
848
      return '$_'. $blocks[$blockcount - 1] . '_val[\''. $blocks[$blockcount]. '\']';
849
    }
850
  }
851
852
  /**
853
  * Write compiled file to cache directory
854
  * @access private
855
  */
856
  function compile_write($handle, $data)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
857
  {
858
    $filename = $this->template->cachepath . str_replace('/', '.', $this->template->filename[$handle]) . DOT_PHP_EX;
859
860
    $data = "<?php if (!defined('INSIDE')) exit;" . ((strpos($data, '<?php') === 0) ? substr($data, 5) : ' ?>' . $data);
861
862
    if ($fp = @fopen($filename, 'wb'))
863
    {
864
      @flock($fp, LOCK_EX);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for flock(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

864
      /** @scrutinizer ignore-unhandled */ @flock($fp, LOCK_EX);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
865
      @fwrite ($fp, $data);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for fwrite(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

865
      /** @scrutinizer ignore-unhandled */ @fwrite ($fp, $data);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
866
      @flock($fp, LOCK_UN);
867
      @fclose($fp);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for fclose(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

867
      /** @scrutinizer ignore-unhandled */ @fclose($fp);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
868
869
      //phpbb_chmod($filename, CHMOD_READ | CHMOD_WRITE);
870
      chmod($filename, 0710);
871
    }
872
873
    return;
874
  }
875
876
  // Gorlum's minifier BOF
877
  /**
878
  * Minifies template w/i PHP code by removing extra spaces
879
  * @access private
880
  */
881
  function minify($html)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
882
  {
883
    if(!SN::$config->tpl_minifier)
884
    {
885
      return $html;
886
    }
887
888
    // TODO: Match <code> and <pre> too - in separate arrays
889
    preg_match_all('/(<script[^>]*?>.*?<\/script>)/si', $html, $pre);
890
    $html = preg_replace('/(<script[^>]*?>.*?<\/script>)/si', '#pre#', $html);
891
    //$html = preg_replace('#<!-[^\[].+->#', '', $html);
892
    //$html = preg_replace('/[\r\n\t]+/', ' ', $html);
893
    $html = preg_replace('/>[\s]*</', '><', $html); // Strip spacechars between tags
894
    $html = preg_replace('/[\s]+/', ' ', $html); // Replace several spacechars with one space
895
    if(!empty($pre[0]))
896
    {
897
      foreach($pre[0] as $tag)
898
      {
899
        $tag = preg_replace('/^\ *\/\/[^\<]*?$/m', ' ', $tag); // Strips comments - except those that contains HTML comment inside
900
        $tag = preg_replace('/[\ \t]{2,}/', ' ', $tag); // Replace several spaces by one
901
        $tag = preg_replace('/\s{2,}/', "\r\n", $tag); // Replace several linefeeds by one
902
        $html = preg_replace('/#pre#/', $tag, $html,1);
903
      }
904
    }
905
906
    return $html;
907
  }
908
  // Gorlum's minifier EOF
909
910
}
911