Test Failed
Pull Request — 1.2 (#90)
by
unknown
04:55
created
lib/Dwoo/Compiler.php 1 patch
Indentation   +3356 added lines, -3356 removed lines patch added patch discarded remove patch
@@ -19,3360 +19,3360 @@
 block discarded – undo
19 19
  */
20 20
 class Dwoo_Compiler implements Dwoo_ICompiler
21 21
 {
22
-    /**
23
-     * constant that represents a php opening tag.
24
-     *
25
-     * use it in case it needs to be adjusted
26
-     *
27
-     * @var string
28
-     */
29
-    const PHP_OPEN = '<?php ';
30
-
31
-    /**
32
-     * constant that represents a php closing tag.
33
-     *
34
-     * use it in case it needs to be adjusted
35
-     *
36
-     * @var string
37
-     */
38
-    const PHP_CLOSE = '?>';
39
-
40
-    /**
41
-     * boolean flag to enable or disable debugging output.
42
-     *
43
-     * @var bool
44
-     */
45
-    public $debug = false;
46
-
47
-    /**
48
-     * left script delimiter.
49
-     *
50
-     * @var string
51
-     */
52
-    protected $ld = '{';
53
-
54
-    /**
55
-     * left script delimiter with escaped regex meta characters.
56
-     *
57
-     * @var string
58
-     */
59
-    protected $ldr = '\\{';
60
-
61
-    /**
62
-     * right script delimiter.
63
-     *
64
-     * @var string
65
-     */
66
-    protected $rd = '}';
67
-
68
-    /**
69
-     * right script delimiter with escaped regex meta characters.
70
-     *
71
-     * @var string
72
-     */
73
-    protected $rdr = '\\}';
74
-
75
-    /**
76
-     * defines whether the nested comments should be parsed as nested or not.
77
-     *
78
-     * defaults to false (classic block comment parsing as in all languages)
79
-     *
80
-     * @var bool
81
-     */
82
-    protected $allowNestedComments = false;
83
-
84
-    /**
85
-     * defines whether opening and closing tags can contain spaces before valid data or not.
86
-     *
87
-     * turn to true if you want to be sloppy with the syntax, but when set to false it allows
88
-     * to skip javascript and css tags as long as they are in the form "{ something", which is
89
-     * nice. default is false.
90
-     *
91
-     * @var bool
92
-     */
93
-    protected $allowLooseOpenings = false;
94
-
95
-    /**
96
-     * defines whether the compiler will automatically html-escape variables or not.
97
-     *
98
-     * default is false
99
-     *
100
-     * @var bool
101
-     */
102
-    protected $autoEscape = false;
103
-
104
-    /**
105
-     * security policy object.
106
-     *
107
-     * @var Dwoo_Security_Policy
108
-     */
109
-    protected $securityPolicy;
110
-
111
-    /**
112
-     * stores the custom plugins registered with this compiler.
113
-     *
114
-     * @var array
115
-     */
116
-    protected $customPlugins = array();
117
-
118
-    /**
119
-     * stores the template plugins registered with this compiler.
120
-     *
121
-     * @var array
122
-     */
123
-    protected $templatePlugins = array();
124
-
125
-    /**
126
-     * stores the pre- and post-processors callbacks.
127
-     *
128
-     * @var array
129
-     */
130
-    protected $processors = array('pre' => array(), 'post' => array());
131
-
132
-    /**
133
-     * stores a list of plugins that are used in the currently compiled
134
-     * template, and that are not compilable. these plugins will be loaded
135
-     * during the template's runtime if required.
136
-     *
137
-     * it is a 1D array formatted as key:pluginName value:pluginType
138
-     *
139
-     * @var array
140
-     */
141
-    protected $usedPlugins;
142
-
143
-    /**
144
-     * stores the template undergoing compilation.
145
-     *
146
-     * @var string
147
-     */
148
-    protected $template;
149
-
150
-    /**
151
-     * stores the current pointer position inside the template.
152
-     *
153
-     * @var int
154
-     */
155
-    protected $pointer;
156
-
157
-    /**
158
-     * stores the current line count inside the template for debugging purposes.
159
-     *
160
-     * @var int
161
-     */
162
-    protected $line;
163
-
164
-    /**
165
-     * stores the current template source while compiling it.
166
-     *
167
-     * @var string
168
-     */
169
-    protected $templateSource;
170
-
171
-    /**
172
-     * stores the data within which the scope moves.
173
-     *
174
-     * @var array
175
-     */
176
-    protected $data;
177
-
178
-    /**
179
-     * variable scope of the compiler, set to null if
180
-     * it can not be resolved to a static string (i.e. if some
181
-     * plugin defines a new scope based on a variable array key).
182
-     *
183
-     * @var mixed
184
-     */
185
-    protected $scope;
186
-
187
-    /**
188
-     * variable scope tree, that allows to rebuild the current
189
-     * scope if required, i.e. when going to a parent level.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $scopeTree;
194
-
195
-    /**
196
-     * block plugins stack, accessible through some methods.
197
-     *
198
-     * @see findBlock
199
-     * @see getCurrentBlock
200
-     * @see addBlock
201
-     * @see addCustomBlock
202
-     * @see injectBlock
203
-     * @see removeBlock
204
-     * @see removeTopBlock
205
-     *
206
-     * @var array
207
-     */
208
-    protected $stack = array();
209
-
210
-    /**
211
-     * current block at the top of the block plugins stack,
212
-     * accessible through getCurrentBlock.
213
-     *
214
-     * @see getCurrentBlock
215
-     *
216
-     * @var Dwoo_Block_Plugin
217
-     */
218
-    protected $curBlock;
219
-
220
-    /**
221
-     * current dwoo object that uses this compiler, or null.
222
-     *
223
-     * @var Dwoo
224
-     */
225
-    protected $dwoo;
226
-
227
-    /**
228
-     * holds an instance of this class, used by getInstance when you don't
229
-     * provide a custom compiler in order to save resources.
230
-     *
231
-     * @var Dwoo_Compiler
232
-     */
233
-    protected static $instance;
234
-
235
-    /**
236
-     * token types.
237
-     *
238
-     * @var int
239
-     */
240
-    const T_UNQUOTED_STRING = 1;
241
-    const T_NUMERIC = 2;
242
-    const T_NULL = 4;
243
-    const T_BOOL = 8;
244
-    const T_MATH = 16;
245
-    const T_BREAKCHAR = 32;
246
-
247
-    /**
248
-     * constructor.
249
-     *
250
-     * saves the created instance so that child templates get the same one
251
-     */
252
-    public function __construct()
253
-    {
254
-        self::$instance = $this;
255
-    }
256
-
257
-    /**
258
-     * sets the delimiters to use in the templates.
259
-     *
260
-     * delimiters can be multi-character strings but should not be one of those as they will
261
-     * make it very hard to work with templates or might even break the compiler entirely : "\", "$", "|", ":" and finally "#" only if you intend to use config-vars with the #var# syntax.
262
-     *
263
-     * @param string $left  left delimiter
264
-     * @param string $right right delimiter
265
-     */
266
-    public function setDelimiters($left, $right)
267
-    {
268
-        $this->ld = $left;
269
-        $this->rd = $right;
270
-        $this->ldr = preg_quote($left, '/');
271
-        $this->rdr = preg_quote($right, '/');
272
-    }
273
-
274
-    /**
275
-     * returns the left and right template delimiters.
276
-     *
277
-     * @return array containing the left and the right delimiters
278
-     */
279
-    public function getDelimiters()
280
-    {
281
-        return array($this->ld, $this->rd);
282
-    }
283
-
284
-    /**
285
-     * sets the way to handle nested comments, if set to true
286
-     * {* foo {* some other *} comment *} will be stripped correctly.
287
-     *
288
-     * if false it will remove {* foo {* some other *} and leave "comment *}" alone,
289
-     * this is the default behavior
290
-     *
291
-     * @param bool $allow allow nested comments or not, defaults to true (but the default internal value is false)
292
-     */
293
-    public function setNestedCommentsHandling($allow = true)
294
-    {
295
-        $this->allowNestedComments = (bool) $allow;
296
-    }
297
-
298
-    /**
299
-     * returns the nested comments handling setting.
300
-     *
301
-     * @see setNestedCommentsHandling
302
-     *
303
-     * @return bool true if nested comments are allowed
304
-     */
305
-    public function getNestedCommentsHandling()
306
-    {
307
-        return $this->allowNestedComments;
308
-    }
309
-
310
-    /**
311
-     * sets the tag openings handling strictness, if set to true, template tags can
312
-     * contain spaces before the first function/string/variable such as { $foo} is valid.
313
-     *
314
-     * if set to false (default setting), { $foo} is invalid but that is however a good thing
315
-     * as it allows css (i.e. #foo { color:red; }) to be parsed silently without triggering
316
-     * an error, same goes for javascript.
317
-     *
318
-     * @param bool $allow true to allow loose handling, false to restore default setting
319
-     */
320
-    public function setLooseOpeningHandling($allow = false)
321
-    {
322
-        $this->allowLooseOpenings = (bool) $allow;
323
-    }
324
-
325
-    /**
326
-     * returns the tag openings handling strictness setting.
327
-     *
328
-     * @see setLooseOpeningHandling
329
-     *
330
-     * @return bool true if loose tags are allowed
331
-     */
332
-    public function getLooseOpeningHandling()
333
-    {
334
-        return $this->allowLooseOpenings;
335
-    }
336
-
337
-    /**
338
-     * changes the auto escape setting.
339
-     *
340
-     * if enabled, the compiler will automatically html-escape variables,
341
-     * unless they are passed through the safe function such as {$var|safe}
342
-     * or {safe $var}
343
-     *
344
-     * default setting is disabled/false
345
-     *
346
-     * @param bool $enabled set to true to enable, false to disable
347
-     */
348
-    public function setAutoEscape($enabled)
349
-    {
350
-        $this->autoEscape = (bool) $enabled;
351
-    }
352
-
353
-    /**
354
-     * returns the auto escape setting.
355
-     *
356
-     * default setting is disabled/false
357
-     *
358
-     * @return bool
359
-     */
360
-    public function getAutoEscape()
361
-    {
362
-        return $this->autoEscape;
363
-    }
364
-
365
-    /**
366
-     * adds a preprocessor to the compiler, it will be called
367
-     * before the template is compiled.
368
-     *
369
-     * @param mixed $callback either a valid callback to the preprocessor or a simple name if the autoload is set to true
370
-     * @param bool  $autoload if set to true, the preprocessor is auto-loaded from one of the plugin directories, else you must provide a valid callback
371
-     */
372
-    public function addPreProcessor($callback, $autoload = false)
373
-    {
374
-        if ($autoload) {
375
-            $name = str_replace('Dwoo_Processor_', '', $callback);
376
-            $class = 'Dwoo_Processor_'.$name;
377
-
378
-            if (class_exists($class)) {
379
-                $callback = array(new $class($this), 'process');
380
-            } elseif (function_exists($class)) {
381
-                $callback = $class;
382
-            } else {
383
-                $callback = array('autoload' => true, 'class' => $class, 'name' => $name);
384
-            }
385
-
386
-            $this->processors['pre'][] = $callback;
387
-        } else {
388
-            $this->processors['pre'][] = $callback;
389
-        }
390
-    }
391
-
392
-    /**
393
-     * removes a preprocessor from the compiler.
394
-     *
395
-     * @param mixed $callback either a valid callback to the preprocessor or a simple name if it was autoloaded
396
-     */
397
-    public function removePreProcessor($callback)
398
-    {
399
-        if (($index = array_search($callback, $this->processors['pre'], true)) !== false) {
400
-            unset($this->processors['pre'][$index]);
401
-        } elseif (($index = array_search('Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback), $this->processors['pre'], true)) !== false) {
402
-            unset($this->processors['pre'][$index]);
403
-        } else {
404
-            $class = 'Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback);
405
-            foreach ($this->processors['pre'] as $index => $proc) {
406
-                if (is_array($proc) && ($proc[0] instanceof $class) || (isset($proc['class']) && $proc['class'] == $class)) {
407
-                    unset($this->processors['pre'][$index]);
408
-                    break;
409
-                }
410
-            }
411
-        }
412
-    }
413
-
414
-    /**
415
-     * adds a postprocessor to the compiler, it will be called
416
-     * before the template is compiled.
417
-     *
418
-     * @param mixed $callback either a valid callback to the postprocessor or a simple name if the autoload is set to true
419
-     * @param bool  $autoload if set to true, the postprocessor is auto-loaded from one of the plugin directories, else you must provide a valid callback
420
-     */
421
-    public function addPostProcessor($callback, $autoload = false)
422
-    {
423
-        if ($autoload) {
424
-            $name = str_replace('Dwoo_Processor_', '', $callback);
425
-            $class = 'Dwoo_Processor_'.$name;
426
-
427
-            if (class_exists($class)) {
428
-                $callback = array(new $class($this), 'process');
429
-            } elseif (function_exists($class)) {
430
-                $callback = $class;
431
-            } else {
432
-                $callback = array('autoload' => true, 'class' => $class, 'name' => $name);
433
-            }
434
-
435
-            $this->processors['post'][] = $callback;
436
-        } else {
437
-            $this->processors['post'][] = $callback;
438
-        }
439
-    }
440
-
441
-    /**
442
-     * removes a postprocessor from the compiler.
443
-     *
444
-     * @param mixed $callback either a valid callback to the postprocessor or a simple name if it was autoloaded
445
-     */
446
-    public function removePostProcessor($callback)
447
-    {
448
-        if (($index = array_search($callback, $this->processors['post'], true)) !== false) {
449
-            unset($this->processors['post'][$index]);
450
-        } elseif (($index = array_search('Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback), $this->processors['post'], true)) !== false) {
451
-            unset($this->processors['post'][$index]);
452
-        } else {
453
-            $class = 'Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback);
454
-            foreach ($this->processors['post'] as $index => $proc) {
455
-                if (is_array($proc) && ($proc[0] instanceof $class) || (isset($proc['class']) && $proc['class'] == $class)) {
456
-                    unset($this->processors['post'][$index]);
457
-                    break;
458
-                }
459
-            }
460
-        }
461
-    }
462
-
463
-    /**
464
-     * internal function to autoload processors at runtime if required.
465
-     *
466
-     * @param string $class the class/function name
467
-     * @param string $name  the plugin name (without Dwoo_Plugin_ prefix)
468
-     *
469
-     * @return array|string
470
-     *
471
-     * @throws Dwoo_Exception
472
-     */
473
-    protected function loadProcessor($class, $name)
474
-    {
475
-        if (!class_exists($class) && !function_exists($class)) {
476
-            try {
477
-                $this->dwoo->getLoader()->loadPlugin($name);
478
-            } catch (Dwoo_Exception $e) {
479
-                throw new Dwoo_Exception('Processor '.$name.' could not be found in your plugin directories, please ensure it is in a file named '.$name.'.php in the plugin directory');
480
-            }
481
-        }
482
-
483
-        if (class_exists($class)) {
484
-            return array(new $class($this), 'process');
485
-        }
486
-
487
-        if (function_exists($class)) {
488
-            return $class;
489
-        }
490
-
491
-        throw new Dwoo_Exception('Wrong processor name, when using autoload the processor must be in one of your plugin dir as "name.php" containg a class or function named "Dwoo_Processor_name"');
492
-    }
493
-
494
-    /**
495
-     * adds an used plugin, this is reserved for use by the {template} plugin.
496
-     *
497
-     * this is required so that plugin loading bubbles up from loaded
498
-     * template files to the current one
499
-     *
500
-     * @private
501
-     *
502
-     * @param string $name function name
503
-     * @param int    $type plugin type (Dwoo_Core::*_PLUGIN)
504
-     */
505
-    public function addUsedPlugin($name, $type)
506
-    {
507
-        $this->usedPlugins[$name] = $type;
508
-    }
509
-
510
-    /**
511
-     * returns all the plugins this template uses.
512
-     *
513
-     * @private
514
-     *
515
-     * @return array the list of used plugins in the parsed template
516
-     */
517
-    public function getUsedPlugins()
518
-    {
519
-        return $this->usedPlugins;
520
-    }
521
-
522
-    /**
523
-     * adds a template plugin, this is reserved for use by the {template} plugin.
524
-     *
525
-     * this is required because the template functions are not declared yet
526
-     * during compilation, so we must have a way of validating their argument
527
-     * signature without using the reflection api
528
-     *
529
-     * @private
530
-     *
531
-     * @param string $name   function name
532
-     * @param array  $params parameter array to help validate the function call
533
-     * @param string $uuid   unique id of the function
534
-     * @param string $body   function php code
535
-     */
536
-    public function addTemplatePlugin($name, array $params, $uuid, $body = null)
537
-    {
538
-        $this->templatePlugins[$name] = array('params' => $params, 'body' => $body, 'uuid' => $uuid);
539
-    }
540
-
541
-    /**
542
-     * returns all the parsed sub-templates.
543
-     *
544
-     * @private
545
-     *
546
-     * @return array the parsed sub-templates
547
-     */
548
-    public function getTemplatePlugins()
549
-    {
550
-        return $this->templatePlugins;
551
-    }
552
-
553
-    /**
554
-     * marks a template plugin as being called, which means its source must be included in the compiled template.
555
-     *
556
-     * @param string $name function name
557
-     */
558
-    public function useTemplatePlugin($name)
559
-    {
560
-        $this->templatePlugins[$name]['called'] = true;
561
-    }
562
-
563
-    /**
564
-     * adds the custom plugins loaded into Dwoo to the compiler so it can load them.
565
-     *
566
-     * @see Dwoo_Core::addPlugin
567
-     *
568
-     * @param array $customPlugins an array of custom plugins
569
-     */
570
-    public function setCustomPlugins(array $customPlugins)
571
-    {
572
-        $this->customPlugins = $customPlugins;
573
-    }
574
-
575
-    /**
576
-     * sets the security policy object to enforce some php security settings.
577
-     *
578
-     * use this if untrusted persons can modify templates,
579
-     * set it on the Dwoo object as it will be passed onto the compiler automatically
580
-     *
581
-     * @param Dwoo_Security_Policy $policy the security policy object
582
-     */
583
-    public function setSecurityPolicy(Dwoo_Security_Policy $policy = null)
584
-    {
585
-        $this->securityPolicy = $policy;
586
-    }
587
-
588
-    /**
589
-     * returns the current security policy object or null by default.
590
-     *
591
-     * @return Dwoo_Security_Policy|null the security policy object if any
592
-     */
593
-    public function getSecurityPolicy()
594
-    {
595
-        return $this->securityPolicy;
596
-    }
597
-
598
-    /**
599
-     * sets the pointer position.
600
-     *
601
-     * @param int  $position the new pointer position
602
-     * @param bool $isOffset if set to true, the position acts as an offset and not an absolute position
603
-     */
604
-    public function setPointer($position, $isOffset = false)
605
-    {
606
-        if ($isOffset) {
607
-            $this->pointer += $position;
608
-        } else {
609
-            $this->pointer = $position;
610
-        }
611
-    }
612
-
613
-    /**
614
-     * returns the current pointer position, only available during compilation of a template.
615
-     *
616
-     * @return int
617
-     */
618
-    public function getPointer()
619
-    {
620
-        return $this->pointer;
621
-    }
622
-
623
-    /**
624
-     * sets the line number.
625
-     *
626
-     * @param int  $number   the new line number
627
-     * @param bool $isOffset if set to true, the position acts as an offset and not an absolute position
628
-     */
629
-    public function setLine($number, $isOffset = false)
630
-    {
631
-        if ($isOffset) {
632
-            $this->line += $number;
633
-        } else {
634
-            $this->line = $number;
635
-        }
636
-    }
637
-
638
-    /**
639
-     * returns the current line number, only available during compilation of a template.
640
-     *
641
-     * @return int
642
-     */
643
-    public function getLine()
644
-    {
645
-        return $this->line;
646
-    }
647
-
648
-    /**
649
-     * returns the dwoo object that initiated this template compilation, only available during compilation of a template.
650
-     *
651
-     * @return Dwoo
652
-     */
653
-    public function getDwoo()
654
-    {
655
-        return $this->dwoo;
656
-    }
657
-
658
-    /**
659
-     * overwrites the template that is being compiled.
660
-     *
661
-     * @param string $newSource   the template source that must replace the current one
662
-     * @param bool   $fromPointer if set to true, only the source from the current pointer position is replaced
663
-     *
664
-     * @return string the template or partial template
665
-     */
666
-    public function setTemplateSource($newSource, $fromPointer = false)
667
-    {
668
-        if ($fromPointer === true) {
669
-            $this->templateSource = substr($this->templateSource, 0, $this->pointer).$newSource;
670
-        } else {
671
-            $this->templateSource = $newSource;
672
-        }
673
-    }
674
-
675
-    /**
676
-     * returns the template that is being compiled.
677
-     *
678
-     * @param mixed $fromPointer if set to true, only the source from the current pointer
679
-     *                           position is returned, if a number is given it overrides the current pointer
680
-     *
681
-     * @return string the template or partial template
682
-     */
683
-    public function getTemplateSource($fromPointer = false)
684
-    {
685
-        if ($fromPointer === true) {
686
-            return substr($this->templateSource, $this->pointer);
687
-        } elseif (is_numeric($fromPointer)) {
688
-            return substr($this->templateSource, $fromPointer);
689
-        } else {
690
-            return $this->templateSource;
691
-        }
692
-    }
693
-
694
-    /**
695
-     * resets the compilation pointer, effectively restarting the compilation process.
696
-     *
697
-     * this is useful if a plugin modifies the template source since it might need to be recompiled
698
-     */
699
-    public function recompile()
700
-    {
701
-        $this->setPointer(0);
702
-    }
703
-
704
-    /**
705
-     * compiles the provided string down to php code.
706
-     *
707
-     * @param Dwoo_Core      $dwoo
708
-     * @param Dwoo_ITemplate $template the template to compile
709
-     *
710
-     * @return string a compiled php string
711
-     *
712
-     * @throws Dwoo_Compilation_Exception
713
-     */
714
-    public function compile(Dwoo_Core $dwoo, Dwoo_ITemplate $template)
715
-    {
716
-        // init vars
717
-        $tpl = $template->getSource();
718
-        $ptr = 0;
719
-        $this->dwoo = $dwoo;
720
-        $this->template = $template;
721
-        $this->templateSource = &$tpl;
722
-        $this->pointer = &$ptr;
723
-
724
-        while (true) {
725
-            // if pointer is at the beginning, reset everything, that allows a plugin to externally reset the compiler if everything must be reparsed
726
-            if ($ptr === 0) {
727
-                // resets variables
728
-                $this->usedPlugins = array();
729
-                $this->data = array();
730
-                $this->scope = &$this->data;
731
-                $this->scopeTree = array();
732
-                $this->stack = array();
733
-                $this->line = 1;
734
-                $this->templatePlugins = array();
735
-                // add top level block
736
-                $compiled = $this->addBlock('topLevelBlock', array(), 0);
737
-                $this->stack[0]['buffer'] = '';
738
-
739
-                if ($this->debug) {
740
-                    echo "\n";
741
-                    echo 'COMPILER INIT'."\n";
742
-                }
743
-
744
-                if ($this->debug) {
745
-                    echo 'PROCESSING PREPROCESSORS ('.count($this->processors['pre']).')'."\n";
746
-                }
747
-
748
-                // runs preprocessors
749
-                foreach ($this->processors['pre'] as $preProc) {
750
-                    if (is_array($preProc) && isset($preProc['autoload'])) {
751
-                        $preProc = $this->loadProcessor($preProc['class'], $preProc['name']);
752
-                    }
753
-                    if (is_array($preProc) && $preProc[0] instanceof Dwoo_Processor) {
754
-                        $tpl = call_user_func($preProc, $tpl);
755
-                    } else {
756
-                        $tpl = call_user_func($preProc, $this, $tpl);
757
-                    }
758
-                }
759
-                unset($preProc);
760
-
761
-                // show template source if debug
762
-                if ($this->debug) {
763
-                    echo '<pre>'.print_r(htmlentities($tpl), true).'</pre>'."\n";
764
-                }
765
-
766
-                // strips php tags if required by the security policy
767
-                if ($this->securityPolicy !== null) {
768
-                    $search = array('{<\?php.*?\?>}');
769
-                    if (ini_get('short_open_tags')) {
770
-                        $search = array('{<\?.*?\?>}', '{<%.*?%>}');
771
-                    }
772
-                    switch ($this->securityPolicy->getPhpHandling()) {
773
-
774
-                    case Dwoo_Security_Policy::PHP_ALLOW:
775
-                        break;
776
-                    case Dwoo_Security_Policy::PHP_ENCODE:
777
-                        $tpl = preg_replace_callback($search, array($this, 'phpTagEncodingHelper'), $tpl);
778
-                        break;
779
-                    case Dwoo_Security_Policy::PHP_REMOVE:
780
-                        $tpl = preg_replace($search, '', $tpl);
781
-
782
-                    }
783
-                }
784
-            }
785
-
786
-            $pos = strpos($tpl, $this->ld, $ptr);
787
-
788
-            if ($pos === false) {
789
-                $this->push(substr($tpl, $ptr), 0);
790
-                break;
791
-            } elseif (substr($tpl, $pos - 1, 1) === '\\' && substr($tpl, $pos - 2, 1) !== '\\') {
792
-                $this->push(substr($tpl, $ptr, $pos - $ptr - 1).$this->ld);
793
-                $ptr = $pos + strlen($this->ld);
794
-            } elseif (preg_match('/^'.$this->ldr.($this->allowLooseOpenings ? '\s*' : '').'literal'.($this->allowLooseOpenings ? '\s*' : '').$this->rdr.'/s', substr($tpl, $pos), $litOpen)) {
795
-                if (!preg_match('/'.$this->ldr.($this->allowLooseOpenings ? '\s*' : '').'\/literal'.($this->allowLooseOpenings ? '\s*' : '').$this->rdr.'/s', $tpl, $litClose, PREG_OFFSET_CAPTURE, $pos)) {
796
-                    throw new Dwoo_Compilation_Exception($this, 'The {literal} blocks must be closed explicitly with {/literal}');
797
-                }
798
-                $endpos = $litClose[0][1];
799
-                $this->push(substr($tpl, $ptr, $pos - $ptr).substr($tpl, $pos + strlen($litOpen[0]), $endpos - $pos - strlen($litOpen[0])));
800
-                $ptr = $endpos + strlen($litClose[0][0]);
801
-            } else {
802
-                if (substr($tpl, $pos - 2, 1) === '\\' && substr($tpl, $pos - 1, 1) === '\\') {
803
-                    $this->push(substr($tpl, $ptr, $pos - $ptr - 1));
804
-                    $ptr = $pos;
805
-                }
806
-
807
-                $this->push(substr($tpl, $ptr, $pos - $ptr));
808
-                $ptr = $pos;
809
-
810
-                $pos += strlen($this->ld);
811
-                if ($this->allowLooseOpenings) {
812
-                    while (substr($tpl, $pos, 1) === ' ') {
813
-                        $pos += 1;
814
-                    }
815
-                } else {
816
-                    if (substr($tpl, $pos, 1) === ' ' || substr($tpl, $pos, 1) === "\r" || substr($tpl, $pos, 1) === "\n" || substr($tpl, $pos, 1) === "\t") {
817
-                        $ptr = $pos;
818
-                        $this->push($this->ld);
819
-                        continue;
820
-                    }
821
-                }
822
-
823
-                // check that there is an end tag present
824
-                if (strpos($tpl, $this->rd, $pos) === false) {
825
-                    throw new Dwoo_Compilation_Exception($this, 'A template tag was not closed, started with "'.substr($tpl, $ptr, 30).'"');
826
-                }
827
-
828
-                $ptr += strlen($this->ld);
829
-                $subptr = $ptr;
830
-
831
-                while (true) {
832
-                    $parsed = $this->parse($tpl, $subptr, null, false, 'root', $subptr);
833
-
834
-                    // reload loop if the compiler was reset
835
-                    if ($ptr === 0) {
836
-                        continue 2;
837
-                    }
838
-
839
-                    $len = $subptr - $ptr;
840
-                    $this->push($parsed, substr_count(substr($tpl, $ptr, $len), "\n"));
841
-                    $ptr += $len;
842
-
843
-                    if ($parsed === false) {
844
-                        break;
845
-                    }
846
-                }
847
-            }
848
-        }
849
-
850
-        $compiled .= $this->removeBlock('topLevelBlock');
851
-
852
-        if ($this->debug) {
853
-            echo 'PROCESSING POSTPROCESSORS'."\n";
854
-        }
855
-
856
-        foreach ($this->processors['post'] as $postProc) {
857
-            if (is_array($postProc) && isset($postProc['autoload'])) {
858
-                $postProc = $this->loadProcessor($postProc['class'], $postProc['name']);
859
-            }
860
-            if (is_array($postProc) && $postProc[0] instanceof Dwoo_Processor) {
861
-                $compiled = call_user_func($postProc, $compiled);
862
-            } else {
863
-                $compiled = call_user_func($postProc, $this, $compiled);
864
-            }
865
-        }
866
-        unset($postProc);
867
-
868
-        if ($this->debug) {
869
-            echo 'COMPILATION COMPLETE : MEM USAGE : '.memory_get_usage()."\n";
870
-        }
871
-
872
-        $output = "<?php\n/* template head */\n";
873
-
874
-        // build plugin preloader
875
-        foreach ($this->usedPlugins as $plugin => $type) {
876
-            if ($type & Dwoo_Core::CUSTOM_PLUGIN) {
877
-                continue;
878
-            }
879
-
880
-            switch ($type) {
881
-
882
-            case Dwoo_Core::BLOCK_PLUGIN:
883
-            case Dwoo_Core::CLASS_PLUGIN:
884
-                $output .= "if (class_exists('Dwoo_Plugin_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
885
-                break;
886
-            case Dwoo_Core::FUNC_PLUGIN:
887
-                $output .= "if (function_exists('Dwoo_Plugin_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
888
-                break;
889
-            case Dwoo_Core::SMARTY_MODIFIER:
890
-                $output .= "if (function_exists('smarty_modifier_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
891
-                break;
892
-            case Dwoo_Core::SMARTY_FUNCTION:
893
-                $output .= "if (function_exists('smarty_function_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
894
-                break;
895
-            case Dwoo_Core::SMARTY_BLOCK:
896
-                $output .= "if (function_exists('smarty_block_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
897
-                break;
898
-            case Dwoo_Core::PROXY_PLUGIN:
899
-                $output .= $this->getDwoo()->getPluginProxy()->getPreloader($plugin);
900
-                break;
901
-            default:
902
-                throw new Dwoo_Compilation_Exception($this, 'Type error for '.$plugin.' with type'.$type);
903
-
904
-            }
905
-        }
906
-
907
-        foreach ($this->templatePlugins as $function => $attr) {
908
-            if (isset($attr['called']) && $attr['called'] === true && !isset($attr['checked'])) {
909
-                $this->resolveSubTemplateDependencies($function);
910
-            }
911
-        }
912
-        foreach ($this->templatePlugins as $function) {
913
-            if (isset($function['called']) && $function['called'] === true) {
914
-                $output .= $function['body'].PHP_EOL;
915
-            }
916
-        }
917
-
918
-        $output .= $compiled."\n?>";
919
-
920
-        $output = preg_replace('/(?<!;|\}|\*\/|\n|\{)(\s*'.preg_quote(self::PHP_CLOSE, '/').preg_quote(self::PHP_OPEN, '/').')/', ";\n", $output);
921
-        $output = str_replace(self::PHP_CLOSE.self::PHP_OPEN, "\n", $output);
922
-
923
-        // handle <?xml tag at the beginning
924
-        $output = preg_replace('#(/\* template body \*/ \?>\s*)<\?xml#is', '$1<?php echo \'<?xml\'; ?>', $output);
925
-
926
-        // add another line break after PHP closing tags that have a line break following,
927
-        // as we do not know whether it's intended, and PHP will strip it otherwise
928
-        $output = preg_replace('/(?<!"|<\?xml)\s*\?>\n/', '$0'."\n", $output);
929
-
930
-        if ($this->debug) {
931
-            echo '============================================================================================='."\n";
932
-            $lines = preg_split('{\r\n|\n|<br />}', $output);
933
-            array_shift($lines);
934
-            foreach ($lines as $i => $line) {
935
-                echo($i + 1).'. '.$line."\r\n";
936
-            }
937
-            echo '============================================================================================='."\n";
938
-        }
939
-
940
-        $this->template = $this->dwoo = null;
941
-        $tpl = null;
942
-
943
-        return $output;
944
-    }
945
-
946
-    /**
947
-     * checks what sub-templates are used in every sub-template so that we're sure they are all compiled.
948
-     *
949
-     * @param string $function the sub-template name
950
-     */
951
-    protected function resolveSubTemplateDependencies($function)
952
-    {
953
-        if ($this->debug) {
954
-            echo 'Compiler::'.__FUNCTION__."\n";
955
-        }
956
-
957
-        $body = $this->templatePlugins[$function]['body'];
958
-        foreach ($this->templatePlugins as $func => $attr) {
959
-            if ($func !== $function && !isset($attr['called']) && strpos($body, 'Dwoo_Plugin_'.$func) !== false) {
960
-                $this->templatePlugins[$func]['called'] = true;
961
-                $this->resolveSubTemplateDependencies($func);
962
-            }
963
-        }
964
-        $this->templatePlugins[$function]['checked'] = true;
965
-    }
966
-
967
-    /**
968
-     * adds compiled content to the current block.
969
-     *
970
-     * @param string $content   the content to push
971
-     * @param int    $lineCount newlines count in content, optional
972
-     *
973
-     * @throws Dwoo_Compilation_Exception
974
-     */
975
-    public function push($content, $lineCount = null)
976
-    {
977
-        if ($lineCount === null) {
978
-            $lineCount = substr_count($content, "\n");
979
-        }
980
-
981
-        if ($this->curBlock['buffer'] === null && count($this->stack) > 1) {
982
-            // buffer is not initialized yet (the block has just been created)
983
-            $this->stack[count($this->stack) - 2]['buffer'] .= (string) $content;
984
-            $this->curBlock['buffer'] = '';
985
-        } else {
986
-            if (!isset($this->curBlock['buffer'])) {
987
-                throw new Dwoo_Compilation_Exception($this, 'The template has been closed too early, you probably have an extra block-closing tag somewhere');
988
-            }
989
-            // append current content to current block's buffer
990
-            $this->curBlock['buffer'] .= (string) $content;
991
-        }
992
-        $this->line += $lineCount;
993
-    }
994
-
995
-    /**
996
-     * sets the scope.
997
-     *
998
-     * set to null if the scope becomes "unstable" (i.e. too variable or unknown) so that
999
-     * variables are compiled in a more evaluative way than just $this->scope['key']
1000
-     *
1001
-     * @param mixed $scope    a string i.e. "level1.level2" or an array i.e. array("level1", "level2")
1002
-     * @param bool  $absolute if true, the scope is set from the top level scope and not from the current scope
1003
-     *
1004
-     * @return array the current scope tree
1005
-     */
1006
-    public function setScope($scope, $absolute = false)
1007
-    {
1008
-        $old = $this->scopeTree;
1009
-
1010
-        if ($scope === null) {
1011
-            unset($this->scope);
1012
-            $this->scope = null;
1013
-        }
1014
-
1015
-        if (is_array($scope) === false) {
1016
-            $scope = explode('.', $scope);
1017
-        }
1018
-
1019
-        if ($absolute === true) {
1020
-            $this->scope = &$this->data;
1021
-            $this->scopeTree = array();
1022
-        }
1023
-
1024
-        while (($bit = array_shift($scope)) !== null) {
1025
-            if ($bit === '_parent' || $bit === '_') {
1026
-                array_pop($this->scopeTree);
1027
-                reset($this->scopeTree);
1028
-                $this->scope = &$this->data;
1029
-                $cnt = count($this->scopeTree);
1030
-                for ($i = 0; $i < $cnt; ++$i) {
1031
-                    $this->scope = &$this->scope[$this->scopeTree[$i]];
1032
-                }
1033
-            } elseif ($bit === '_root' || $bit === '__') {
1034
-                $this->scope = &$this->data;
1035
-                $this->scopeTree = array();
1036
-            } elseif (isset($this->scope[$bit])) {
1037
-                $this->scope = &$this->scope[$bit];
1038
-                $this->scopeTree[] = $bit;
1039
-            } else {
1040
-                $this->scope[$bit] = array();
1041
-                $this->scope = &$this->scope[$bit];
1042
-                $this->scopeTree[] = $bit;
1043
-            }
1044
-        }
1045
-
1046
-        return $old;
1047
-    }
1048
-
1049
-    /**
1050
-     * adds a block to the top of the block stack.
1051
-     *
1052
-     * @param string $type      block type (name)
1053
-     * @param array  $params    the parameters array
1054
-     * @param int    $paramtype the parameters type (see mapParams), 0, 1 or 2
1055
-     *
1056
-     * @return string the preProcessing() method's output
1057
-     */
1058
-    public function addBlock($type, array $params, $paramtype)
1059
-    {
1060
-        if ($this->debug) {
1061
-            echo 'Compiler::'.__FUNCTION__."\n";
1062
-        }
1063
-
1064
-        $class = 'Dwoo_Plugin_'.$type;
1065
-        if (class_exists($class) === false) {
1066
-            $this->dwoo->getLoader()->loadPlugin($type);
1067
-        }
1068
-        $params = $this->mapParams($params, array($class, 'init'), $paramtype);
1069
-
1070
-        $this->stack[] = array('type' => $type, 'params' => $params, 'custom' => false, 'class' => $class, 'buffer' => null);
1071
-        $this->curBlock = &$this->stack[count($this->stack) - 1];
1072
-
1073
-        return call_user_func(array($class, 'preProcessing'), $this, $params, '', '', $type);
1074
-    }
1075
-
1076
-    /**
1077
-     * adds a custom block to the top of the block stack.
1078
-     *
1079
-     * @param string $type      block type (name)
1080
-     * @param array  $params    the parameters array
1081
-     * @param int    $paramtype the parameters type (see mapParams), 0, 1 or 2
1082
-     *
1083
-     * @return string the preProcessing() method's output
1084
-     */
1085
-    public function addCustomBlock($type, array $params, $paramtype)
1086
-    {
1087
-        $callback = $this->customPlugins[$type]['callback'];
1088
-        if (is_array($callback)) {
1089
-            $class = is_object($callback[0]) ? get_class($callback[0]) : $callback[0];
1090
-        } else {
1091
-            $class = $callback;
1092
-        }
1093
-
1094
-        $params = $this->mapParams($params, array($class, 'init'), $paramtype);
1095
-
1096
-        $this->stack[] = array('type' => $type, 'params' => $params, 'custom' => true, 'class' => $class, 'buffer' => null);
1097
-        $this->curBlock = &$this->stack[count($this->stack) - 1];
1098
-
1099
-        return call_user_func(array($class, 'preProcessing'), $this, $params, '', '', $type);
1100
-    }
1101
-
1102
-    /**
1103
-     * injects a block at the top of the plugin stack without calling its preProcessing method.
1104
-     *
1105
-     * used by {else} blocks to re-add themselves after having closed everything up to their parent
1106
-     *
1107
-     * @param string $type   block type (name)
1108
-     * @param array  $params parameters array
1109
-     */
1110
-    public function injectBlock($type, array $params)
1111
-    {
1112
-        if ($this->debug) {
1113
-            echo 'Compiler::'.__FUNCTION__."\n";
1114
-        }
1115
-
1116
-        $class = 'Dwoo_Plugin_'.$type;
1117
-        if (class_exists($class) === false) {
1118
-            $this->dwoo->getLoader()->loadPlugin($type);
1119
-        }
1120
-        $this->stack[] = array('type' => $type, 'params' => $params, 'custom' => false, 'class' => $class, 'buffer' => null);
1121
-        $this->curBlock = &$this->stack[count($this->stack) - 1];
1122
-    }
1123
-
1124
-    /**
1125
-     * removes the closest-to-top block of the given type and all other
1126
-     * blocks encountered while going down the block stack.
1127
-     *
1128
-     * @param string $type block type (name)
1129
-     *
1130
-     * @return string the output of all postProcessing() method's return values of the closed blocks
1131
-     *
1132
-     * @throws Dwoo_Compilation_Exception
1133
-     */
1134
-    public function removeBlock($type)
1135
-    {
1136
-        if ($this->debug) {
1137
-            echo 'Compiler::'.__FUNCTION__."\n";
1138
-        }
1139
-
1140
-        $output = '';
1141
-
1142
-        $pluginType = $this->getPluginType($type);
1143
-        if ($pluginType & Dwoo_Core::SMARTY_BLOCK) {
1144
-            $type = 'smartyinterface';
1145
-        }
1146
-        while (true) {
1147
-            while ($top = array_pop($this->stack)) {
1148
-                if ($top['custom']) {
1149
-                    $class = $top['class'];
1150
-                } else {
1151
-                    $class = 'Dwoo_Plugin_'.$top['type'];
1152
-                }
1153
-                if (count($this->stack)) {
1154
-                    $this->curBlock = &$this->stack[count($this->stack) - 1];
1155
-                    $this->push(call_user_func(array($class, 'postProcessing'), $this, $top['params'], '', '', $top['buffer']), 0);
1156
-                } else {
1157
-                    $null = null;
1158
-                    $this->curBlock = &$null;
1159
-                    $output = call_user_func(array($class, 'postProcessing'), $this, $top['params'], '', '', $top['buffer']);
1160
-                }
1161
-
1162
-                if ($top['type'] === $type) {
1163
-                    break 2;
1164
-                }
1165
-            }
1166
-
1167
-            throw new Dwoo_Compilation_Exception($this, 'Syntax malformation, a block of type "'.$type.'" was closed but was not opened');
1168
-            break;
1169
-        }
1170
-
1171
-        return $output;
1172
-    }
1173
-
1174
-    /**
1175
-     * returns a reference to the first block of the given type encountered and
1176
-     * optionally closes all blocks until it finds it
1177
-     * this is mainly used by {else} plugins to close everything that was opened
1178
-     * between their parent and themselves.
1179
-     *
1180
-     * @param string $type       the block type (name)
1181
-     * @param bool   $closeAlong whether to close all blocks encountered while going down the block stack or not
1182
-     *
1183
-     * @return mixed &array the array is as such: array('type'=>pluginName, 'params'=>parameter array,
1184
-     *               'custom'=>bool defining whether it's a custom plugin or not, for internal use)
1185
-     *
1186
-     * @throws Dwoo_Compilation_Exception
1187
-     */
1188
-    public function &findBlock($type, $closeAlong = false)
1189
-    {
1190
-        if ($closeAlong === true) {
1191
-            while ($b = end($this->stack)) {
1192
-                if ($b['type'] === $type) {
1193
-                    return $this->stack[key($this->stack)];
1194
-                }
1195
-                $this->push($this->removeTopBlock(), 0);
1196
-            }
1197
-        } else {
1198
-            end($this->stack);
1199
-            while ($b = current($this->stack)) {
1200
-                if ($b['type'] === $type) {
1201
-                    return $this->stack[key($this->stack)];
1202
-                }
1203
-                prev($this->stack);
1204
-            }
1205
-        }
1206
-
1207
-        throw new Dwoo_Compilation_Exception($this, 'A parent block of type "'.$type.'" is required and can not be found');
1208
-    }
1209
-
1210
-    /**
1211
-     * returns a reference to the current block array.
1212
-     *
1213
-     * @return &array the array is as such: array('type'=>pluginName, 'params'=>parameter array,
1214
-     *                'custom'=>bool defining whether it's a custom plugin or not, for internal use)
1215
-     */
1216
-    public function &getCurrentBlock()
1217
-    {
1218
-        return $this->curBlock;
1219
-    }
1220
-
1221
-    /**
1222
-     * removes the block at the top of the stack and calls its postProcessing() method.
1223
-     *
1224
-     * @return string the postProcessing() method's output
1225
-     *
1226
-     * @throws Dwoo_Compilation_Exception
1227
-     */
1228
-    public function removeTopBlock()
1229
-    {
1230
-        if ($this->debug) {
1231
-            echo 'Compiler::'.__FUNCTION__."\n";
1232
-        }
1233
-
1234
-        $o = array_pop($this->stack);
1235
-        if ($o === null) {
1236
-            throw new Dwoo_Compilation_Exception($this, 'Syntax malformation, a block of unknown type was closed but was not opened.');
1237
-        }
1238
-        if ($o['custom']) {
1239
-            $class = $o['class'];
1240
-        } else {
1241
-            $class = 'Dwoo_Plugin_'.$o['type'];
1242
-        }
1243
-
1244
-        $this->curBlock = &$this->stack[count($this->stack) - 1];
1245
-
1246
-        return call_user_func(array($class, 'postProcessing'), $this, $o['params'], '', '', $o['buffer']);
1247
-    }
1248
-
1249
-    /**
1250
-     * returns the compiled parameters (for example a variable's compiled parameter will be "$this->scope['key']") out of the given parameter array.
1251
-     *
1252
-     * @param array $params parameter array
1253
-     *
1254
-     * @return array filtered parameters
1255
-     */
1256
-    public function getCompiledParams(array $params)
1257
-    {
1258
-        foreach ($params as $k => $p) {
1259
-            if (is_array($p)) {
1260
-                $params[$k] = $p[0];
1261
-            }
1262
-        }
1263
-
1264
-        return $params;
1265
-    }
1266
-
1267
-    /**
1268
-     * returns the real parameters (for example a variable's real parameter will be its key, etc) out of the given parameter array.
1269
-     *
1270
-     * @param array $params parameter array
1271
-     *
1272
-     * @return array filtered parameters
1273
-     */
1274
-    public function getRealParams(array $params)
1275
-    {
1276
-        foreach ($params as $k => $p) {
1277
-            if (is_array($p)) {
1278
-                $params[$k] = $p[1];
1279
-            }
1280
-        }
1281
-
1282
-        return $params;
1283
-    }
1284
-
1285
-    /**
1286
-     * returns the token of each parameter out of the given parameter array.
1287
-     *
1288
-     * @param array $params parameter array
1289
-     *
1290
-     * @return array tokens
1291
-     */
1292
-    public function getParamTokens(array $params)
1293
-    {
1294
-        foreach ($params as $k => $p) {
1295
-            if (is_array($p)) {
1296
-                $params[$k] = isset($p[2]) ? $p[2] : 0;
1297
-            }
1298
-        }
1299
-
1300
-        return $params;
1301
-    }
1302
-
1303
-    /**
1304
-     * entry point of the parser, it redirects calls to other parse* functions.
1305
-     *
1306
-     * @param string $in            the string within which we must parse something
1307
-     * @param int    $from          the starting offset of the parsed area
1308
-     * @param int    $to            the ending offset of the parsed area
1309
-     * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
1310
-     * @param string $curBlock      the current parser-block being processed
1311
-     * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
1312
-     *
1313
-     * @return string parsed values
1314
-     *
1315
-     * @throws Dwoo_Compilation_Exception
1316
-     */
1317
-    protected function parse($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
1318
-    {
1319
-        if ($this->debug) {
1320
-            echo 'Compiler::'.__FUNCTION__."\n";
1321
-        }
1322
-
1323
-        if ($to === null) {
1324
-            $to = strlen($in);
1325
-        }
1326
-        $first = substr($in, $from, 1);
1327
-
1328
-        if ($first === false) {
1329
-            throw new Dwoo_Compilation_Exception($this, 'Unexpected EOF, a template tag was not closed');
1330
-        }
1331
-
1332
-        while ($first === ' ' || $first === "\n" || $first === "\t" || $first === "\r") {
1333
-            if ($curBlock === 'root' && substr($in, $from, strlen($this->rd)) === $this->rd) {
1334
-                // end template tag
1335
-                $pointer += strlen($this->rd);
1336
-                if ($this->debug) {
1337
-                    echo 'TEMPLATE PARSING ENDED'."\n";
1338
-                }
1339
-
1340
-                return false;
1341
-            }
1342
-            ++$from;
1343
-            if ($pointer !== null) {
1344
-                ++$pointer;
1345
-            }
1346
-            if ($from >= $to) {
1347
-                if (is_array($parsingParams)) {
1348
-                    return $parsingParams;
1349
-                } else {
1350
-                    return '';
1351
-                }
1352
-            }
1353
-            $first = $in[$from];
1354
-        }
1355
-
1356
-        $substr = substr($in, $from, $to - $from);
1357
-
1358
-        if ($this->debug) {
1359
-            echo 'PARSE CALL : PARSING "<b>'.htmlentities(substr($in, $from, min($to - $from, 50))).(($to - $from) > 50 ? '...' : '').'</b>" @ '.$from.':'.$to.' in '.$curBlock.' : pointer='.$pointer."\n";
1360
-        }
1361
-        $parsed = '';
1362
-
1363
-        if ($curBlock === 'root' && $first === '*') {
1364
-            $src = $this->getTemplateSource();
1365
-            $startpos = $this->getPointer() - strlen($this->ld);
1366
-            if (substr($src, $startpos, strlen($this->ld)) === $this->ld) {
1367
-                if ($startpos > 0) {
1368
-                    do {
1369
-                        $char = substr($src, --$startpos, 1);
1370
-                        if ($char == "\n") {
1371
-                            ++$startpos;
1372
-                            $whitespaceStart = true;
1373
-                            break;
1374
-                        }
1375
-                    } while ($startpos > 0 && ($char == ' ' || $char == "\t"));
1376
-                }
1377
-
1378
-                if (!isset($whitespaceStart)) {
1379
-                    $startpos = $this->getPointer();
1380
-                } else {
1381
-                    $pointer -= $this->getPointer() - $startpos;
1382
-                }
1383
-
1384
-                if ($this->allowNestedComments && strpos($src, $this->ld.'*', $this->getPointer()) !== false) {
1385
-                    $comOpen = $this->ld.'*';
1386
-                    $comClose = '*'.$this->rd;
1387
-                    $level = 1;
1388
-                    $ptr = $this->getPointer();
1389
-
1390
-                    while ($level > 0 && $ptr < strlen($src)) {
1391
-                        $open = strpos($src, $comOpen, $ptr);
1392
-                        $close = strpos($src, $comClose, $ptr);
1393
-
1394
-                        if ($open !== false && $close !== false) {
1395
-                            if ($open < $close) {
1396
-                                $ptr = $open + strlen($comOpen);
1397
-                                ++$level;
1398
-                            } else {
1399
-                                $ptr = $close + strlen($comClose);
1400
-                                --$level;
1401
-                            }
1402
-                        } elseif ($open !== false) {
1403
-                            $ptr = $open + strlen($comOpen);
1404
-                            ++$level;
1405
-                        } elseif ($close !== false) {
1406
-                            $ptr = $close + strlen($comClose);
1407
-                            --$level;
1408
-                        } else {
1409
-                            $ptr = strlen($src);
1410
-                        }
1411
-                    }
1412
-                    $endpos = $ptr - strlen('*'.$this->rd);
1413
-                } else {
1414
-                    $endpos = strpos($src, '*'.$this->rd, $startpos);
1415
-                    if ($endpos == false) {
1416
-                        throw new Dwoo_Compilation_Exception($this, 'Un-ended comment');
1417
-                    }
1418
-                }
1419
-                $pointer += $endpos - $startpos + strlen('*'.$this->rd);
1420
-                if (isset($whitespaceStart) && preg_match('#^[\t ]*\r?\n#', substr($src, $endpos + strlen('*'.$this->rd)), $m)) {
1421
-                    $pointer += strlen($m[0]);
1422
-                    $this->curBlock['buffer'] = substr($this->curBlock['buffer'], 0, strlen($this->curBlock['buffer']) - ($this->getPointer() - $startpos - strlen($this->ld)));
1423
-                }
1424
-
1425
-                return false;
1426
-            }
1427
-        }
1428
-
1429
-        if ($first === '$') {
1430
-            // var
1431
-            $out = $this->parseVar($in, $from, $to, $parsingParams, $curBlock, $pointer);
1432
-            $parsed = 'var';
1433
-        } elseif ($first === '%' && preg_match('#^%[a-z_]#i', $substr)) {
1434
-            // const
1435
-            $out = $this->parseConst($in, $from, $to, $parsingParams, $curBlock, $pointer);
1436
-        } elseif (($first === '"' || $first === "'") && !(is_array($parsingParams) && preg_match('#^([\'"])[a-z0-9_]+\1\s*=>?(?:\s+|[^=])#i', $substr))) {
1437
-            // string
1438
-            $out = $this->parseString($in, $from, $to, $parsingParams, $curBlock, $pointer);
1439
-        } elseif (preg_match('/^\\\\?[a-z_](?:\\\\?[a-z0-9_]+)*(?:::[a-z_][a-z0-9_]*)?('.(is_array($parsingParams) || $curBlock != 'root' ? '' : '\s+[^(]|').'\s*\(|\s*'.$this->rdr.'|\s*;)/i', $substr)) {
1440
-            // func
1441
-            $out = $this->parseFunction($in, $from, $to, $parsingParams, $curBlock, $pointer);
1442
-            $parsed = 'func';
1443
-        } elseif ($first === ';') {
1444
-            // instruction end
1445
-            if ($this->debug) {
1446
-                echo 'END OF INSTRUCTION'."\n";
1447
-            }
1448
-            if ($pointer !== null) {
1449
-                ++$pointer;
1450
-            }
1451
-
1452
-            return $this->parse($in, $from + 1, $to, false, 'root', $pointer);
1453
-        } elseif ($curBlock === 'root' && preg_match('#^/([a-z_][a-z0-9_]*)?#i', $substr, $match)) {
1454
-            // close block
1455
-            if (!empty($match[1]) && $match[1] == 'else') {
1456
-                throw new Dwoo_Compilation_Exception($this, 'Else blocks must not be closed explicitly, they are automatically closed when their parent block is closed');
1457
-            }
1458
-            if (!empty($match[1]) && $match[1] == 'elseif') {
1459
-                throw new Dwoo_Compilation_Exception($this, 'Elseif blocks must not be closed explicitly, they are automatically closed when their parent block is closed or a new else/elseif block is declared after them');
1460
-            }
1461
-            if ($pointer !== null) {
1462
-                $pointer += strlen($match[0]);
1463
-            }
1464
-            if (empty($match[1])) {
1465
-                if ($this->curBlock['type'] == 'else' || $this->curBlock['type'] == 'elseif') {
1466
-                    $pointer -= strlen($match[0]);
1467
-                }
1468
-                if ($this->debug) {
1469
-                    echo 'TOP BLOCK CLOSED'."\n";
1470
-                }
1471
-
1472
-                return $this->removeTopBlock();
1473
-            } else {
1474
-                if ($this->debug) {
1475
-                    echo 'BLOCK OF TYPE '.$match[1].' CLOSED'."\n";
1476
-                }
1477
-
1478
-                return $this->removeBlock($match[1]);
1479
-            }
1480
-        } elseif ($curBlock === 'root' && substr($substr, 0, strlen($this->rd)) === $this->rd) {
1481
-            // end template tag
1482
-            if ($this->debug) {
1483
-                echo 'TAG PARSING ENDED'."\n";
1484
-            }
1485
-            $pointer += strlen($this->rd);
1486
-
1487
-            return false;
1488
-        } elseif (is_array($parsingParams) && preg_match('#^(([\'"]?)[a-z0-9_]+\2\s*='.($curBlock === 'array' ? '>?' : '').')(?:\s+|[^=]).*#i', $substr, $match)) {
1489
-            // named parameter
1490
-            if ($this->debug) {
1491
-                echo 'NAMED PARAM FOUND'."\n";
1492
-            }
1493
-            $len = strlen($match[1]);
1494
-            while (substr($in, $from + $len, 1) === ' ') {
1495
-                ++$len;
1496
-            }
1497
-            if ($pointer !== null) {
1498
-                $pointer += $len;
1499
-            }
1500
-
1501
-            $output = array(trim($match[1], " \t\r\n=>'\""), $this->parse($in, $from + $len, $to, false, 'namedparam', $pointer));
1502
-
1503
-            $parsingParams[] = $output;
1504
-
1505
-            return $parsingParams;
1506
-        } elseif (preg_match('#^(\\\\?[a-z_](?:\\\\?[a-z0-9_]+)*::\$[a-z0-9_]+)#i', $substr, $match)) {
1507
-            // static member access
1508
-            $parsed = 'var';
1509
-            if (is_array($parsingParams)) {
1510
-                $parsingParams[] = array($match[1], $match[1]);
1511
-                $out = $parsingParams;
1512
-            } else {
1513
-                $out = $match[1];
1514
-            }
1515
-            $pointer += strlen($match[1]);
1516
-        } elseif ($substr !== '' && (is_array($parsingParams) || $curBlock === 'namedparam' || $curBlock === 'condition' || $curBlock === 'expression')) {
1517
-            // unquoted string, bool or number
1518
-            $out = $this->parseOthers($in, $from, $to, $parsingParams, $curBlock, $pointer);
1519
-        } else {
1520
-            // parse error
1521
-            throw new Dwoo_Compilation_Exception($this, 'Parse error in "'.substr($in, $from, $to - $from).'"');
1522
-        }
1523
-
1524
-        if (empty($out)) {
1525
-            return '';
1526
-        }
1527
-
1528
-        $substr = substr($in, $pointer, $to - $pointer);
1529
-
1530
-        // var parsed, check if any var-extension applies
1531
-        if ($parsed === 'var') {
1532
-            if (preg_match('#^\s*([/%+*-])\s*([a-z0-9]|\$)#i', $substr, $match)) {
1533
-                if ($this->debug) {
1534
-                    echo 'PARSING POST-VAR EXPRESSION '.$substr."\n";
1535
-                }
1536
-                // parse expressions
1537
-                $pointer += strlen($match[0]) - 1;
1538
-                if (is_array($parsingParams)) {
1539
-                    if ($match[2] == '$') {
1540
-                        $expr = $this->parseVar($in, $pointer, $to, array(), $curBlock, $pointer);
1541
-                    } else {
1542
-                        $expr = $this->parse($in, $pointer, $to, array(), 'expression', $pointer);
1543
-                    }
1544
-                    $out[count($out) - 1][0] .= $match[1].$expr[0][0];
1545
-                    $out[count($out) - 1][1] .= $match[1].$expr[0][1];
1546
-                } else {
1547
-                    if ($match[2] == '$') {
1548
-                        $expr = $this->parseVar($in, $pointer, $to, false, $curBlock, $pointer);
1549
-                    } else {
1550
-                        $expr = $this->parse($in, $pointer, $to, false, 'expression', $pointer);
1551
-                    }
1552
-                    if (is_array($out) && is_array($expr)) {
1553
-                        $out[0] .= $match[1].$expr[0];
1554
-                        $out[1] .= $match[1].$expr[1];
1555
-                    } elseif (is_array($out)) {
1556
-                        $out[0] .= $match[1].$expr;
1557
-                        $out[1] .= $match[1].$expr;
1558
-                    } elseif (is_array($expr)) {
1559
-                        $out .= $match[1].$expr[0];
1560
-                    } else {
1561
-                        $out .= $match[1].$expr;
1562
-                    }
1563
-                }
1564
-            } elseif ($curBlock === 'root' && preg_match('#^(\s*(?:[+/*%-.]=|=|\+\+|--)\s*)(.*)#s', $substr, $match)) {
1565
-                if ($this->debug) {
1566
-                    echo 'PARSING POST-VAR ASSIGNMENT '.$substr."\n";
1567
-                }
1568
-                // parse assignment
1569
-                $value = $match[2];
1570
-                $operator = trim($match[1]);
1571
-                if (substr($value, 0, 1) == '=') {
1572
-                    throw new Dwoo_Compilation_Exception($this, 'Unexpected "=" in <em>'.$substr.'</em>');
1573
-                }
1574
-
1575
-                if ($pointer !== null) {
1576
-                    $pointer += strlen($match[1]);
1577
-                }
1578
-
1579
-                if ($operator !== '++' && $operator !== '--') {
1580
-                    $parts = array();
1581
-                    $ptr = 0;
1582
-                    $parts = $this->parse($value, 0, strlen($value), $parts, 'condition', $ptr);
1583
-                    $pointer += $ptr;
1584
-
1585
-                    // load if plugin
1586
-                    try {
1587
-                        $this->getPluginType('if');
1588
-                    } catch (Dwoo_Exception $e) {
1589
-                        throw new Dwoo_Compilation_Exception($this, 'Assignments require the "if" plugin to be accessible');
1590
-                    }
1591
-
1592
-                    $parts = $this->mapParams($parts, array('Dwoo_Plugin_if', 'init'), 1);
1593
-                    $tokens = $this->getParamTokens($parts);
1594
-                    $parts = $this->getCompiledParams($parts);
1595
-
1596
-                    $value = Dwoo_Plugin_if::replaceKeywords($parts['*'], $tokens['*'], $this);
1597
-                    $echo = '';
1598
-                } else {
1599
-                    $value = array();
1600
-                    $echo = 'echo ';
1601
-                }
1602
-
1603
-                if ($this->autoEscape) {
1604
-                    $out = preg_replace('#\(is_string\(\$tmp=(.+?)\) \? htmlspecialchars\(\$tmp, ENT_QUOTES, \$this->charset\) : \$tmp\)#', '$1', $out);
1605
-                }
1606
-                $out = self::PHP_OPEN.$echo.$out.$operator.implode(' ', $value).self::PHP_CLOSE;
1607
-            } elseif ($curBlock === 'array' && is_array($parsingParams) && preg_match('#^(\s*=>?\s*)#', $substr, $match)) {
1608
-                // parse namedparam with var as name (only for array)
1609
-                if ($this->debug) {
1610
-                    echo 'VARIABLE NAMED PARAM (FOR ARRAY) FOUND'."\n";
1611
-                }
1612
-                $len = strlen($match[1]);
1613
-                $var = $out[count($out) - 1];
1614
-                $pointer += $len;
1615
-
1616
-                $output = array($var[0], $this->parse($substr, $len, null, false, 'namedparam', $pointer));
1617
-
1618
-                $parsingParams[] = $output;
1619
-
1620
-                return $parsingParams;
1621
-            }
1622
-        }
1623
-
1624
-        if ($curBlock !== 'modifier' && ($parsed === 'func' || $parsed === 'var') && preg_match('#^(\|@?[a-z0-9_]+(:.*)?)+#i', $substr, $match)) {
1625
-            // parse modifier on funcs or vars
1626
-            $srcPointer = $pointer;
1627
-            if (is_array($parsingParams)) {
1628
-                $tmp = $this->replaceModifiers(array(null, null, $out[count($out) - 1][0], $match[0]), $curBlock, $pointer);
1629
-                $out[count($out) - 1][0] = $tmp;
1630
-                $out[count($out) - 1][1] .= substr($substr, $srcPointer, $srcPointer - $pointer);
1631
-            } else {
1632
-                $out = $this->replaceModifiers(array(null, null, $out, $match[0]), $curBlock, $pointer);
1633
-            }
1634
-        }
1635
-
1636
-        // func parsed, check if any func-extension applies
1637
-        if ($parsed === 'func' && preg_match('#^->[a-z0-9_]+(\s*\(.+|->[a-z_].*)?#is', $substr, $match)) {
1638
-            // parse method call or property read
1639
-            $ptr = 0;
1640
-
1641
-            if (is_array($parsingParams)) {
1642
-                $output = $this->parseMethodCall($out[count($out) - 1][1], $match[0], $curBlock, $ptr);
1643
-
1644
-                $out[count($out) - 1][0] = $output;
1645
-                $out[count($out) - 1][1] .= substr($match[0], 0, $ptr);
1646
-            } else {
1647
-                $out = $this->parseMethodCall($out, $match[0], $curBlock, $ptr);
1648
-            }
1649
-
1650
-            $pointer += $ptr;
1651
-        }
1652
-
1653
-        if ($curBlock === 'root' && substr($out, 0, strlen(self::PHP_OPEN)) !== self::PHP_OPEN) {
1654
-            return self::PHP_OPEN.'echo '.$out.';'.self::PHP_CLOSE;
1655
-        } else {
1656
-            return $out;
1657
-        }
1658
-    }
1659
-
1660
-    /**
1661
-     * parses a function call.
1662
-     *
1663
-     * @param string $in            the string within which we must parse something
1664
-     * @param int    $from          the starting offset of the parsed area
1665
-     * @param int    $to            the ending offset of the parsed area
1666
-     * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
1667
-     * @param string $curBlock      the current parser-block being processed
1668
-     * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
1669
-     *
1670
-     * @return string parsed values
1671
-     *
1672
-     * @throws Dwoo_Compilation_Exception
1673
-     * @throws Dwoo_Exception
1674
-     * @throws Dwoo_Security_Exception
1675
-     */
1676
-    protected function parseFunction($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
1677
-    {
1678
-        $cmdstr = substr($in, $from, $to - $from);
1679
-        preg_match('/^(\\\\?[a-z_](?:\\\\?[a-z0-9_]+)*(?:::[a-z_][a-z0-9_]*)?)(\s*'.$this->rdr.'|\s*;)?/i', $cmdstr, $match);
1680
-
1681
-        if (empty($match[1])) {
1682
-            throw new Dwoo_Compilation_Exception($this, 'Parse error, invalid function name : '.substr($cmdstr, 0, 15));
1683
-        }
1684
-
1685
-        $func = $match[1];
1686
-
1687
-        if (!empty($match[2])) {
1688
-            $cmdstr = $match[1];
1689
-        }
1690
-
1691
-        if ($this->debug) {
1692
-            echo 'FUNC FOUND ('.$func.')'."\n";
1693
-        }
1694
-
1695
-        $paramsep = '';
1696
-
1697
-        if (is_array($parsingParams) || $curBlock != 'root') {
1698
-            $paramspos = strpos($cmdstr, '(');
1699
-            $paramsep = ')';
1700
-        } elseif (preg_match_all('#^\s*[\\\\:a-z0-9_]+(\s*\(|\s+[^(])#i', $cmdstr, $match, PREG_OFFSET_CAPTURE)) {
1701
-            $paramspos = $match[1][0][1];
1702
-            $paramsep = substr($match[1][0][0], -1) === '(' ? ')' : '';
1703
-            if ($paramsep === ')') {
1704
-                $paramspos += strlen($match[1][0][0]) - 1;
1705
-                if (substr($cmdstr, 0, 2) === 'if' || substr($cmdstr, 0, 6) === 'elseif') {
1706
-                    $paramsep = '';
1707
-                    if (strlen($match[1][0][0]) > 1) {
1708
-                        --$paramspos;
1709
-                    }
1710
-                }
1711
-            }
1712
-        } else {
1713
-            $paramspos = false;
1714
-        }
1715
-
1716
-        $state = 0;
1717
-
1718
-        if ($paramspos === false) {
1719
-            $params = array();
1720
-
1721
-            if ($curBlock !== 'root') {
1722
-                return $this->parseOthers($in, $from, $to, $parsingParams, $curBlock, $pointer);
1723
-            }
1724
-        } else {
1725
-            if ($curBlock === 'condition') {
1726
-                // load if plugin
1727
-                $this->getPluginType('if');
1728
-
1729
-                if (Dwoo_Plugin_if::replaceKeywords(array($func), array(self::T_UNQUOTED_STRING), $this) !== array($func)) {
1730
-                    return $this->parseOthers($in, $from, $to, $parsingParams, $curBlock, $pointer);
1731
-                }
1732
-            }
1733
-            $whitespace = strlen(substr($cmdstr, strlen($func), $paramspos - strlen($func)));
1734
-            $paramstr = substr($cmdstr, $paramspos + 1);
1735
-            if (substr($paramstr, -1, 1) === $paramsep) {
1736
-                $paramstr = substr($paramstr, 0, -1);
1737
-            }
1738
-
1739
-            if (strlen($paramstr) === 0) {
1740
-                $params = array();
1741
-                $paramstr = '';
1742
-            } else {
1743
-                $ptr = 0;
1744
-                $params = array();
1745
-                if ($func === 'empty') {
1746
-                    $params = $this->parseVar($paramstr, $ptr, strlen($paramstr), $params, 'root', $ptr);
1747
-                } else {
1748
-                    while ($ptr < strlen($paramstr)) {
1749
-                        while (true) {
1750
-                            if ($ptr >= strlen($paramstr)) {
1751
-                                break 2;
1752
-                            }
1753
-
1754
-                            if ($func !== 'if' && $func !== 'elseif' && $paramstr[$ptr] === ')') {
1755
-                                if ($this->debug) {
1756
-                                    echo 'PARAM PARSING ENDED, ")" FOUND, POINTER AT '.$ptr."\n";
1757
-                                }
1758
-                                break 2;
1759
-                            } elseif ($paramstr[$ptr] === ';') {
1760
-                                ++$ptr;
1761
-                                if ($this->debug) {
1762
-                                    echo 'PARAM PARSING ENDED, ";" FOUND, POINTER AT '.$ptr."\n";
1763
-                                }
1764
-                                break 2;
1765
-                            } elseif ($func !== 'if' && $func !== 'elseif' && $paramstr[$ptr] === '/') {
1766
-                                if ($this->debug) {
1767
-                                    echo 'PARAM PARSING ENDED, "/" FOUND, POINTER AT '.$ptr."\n";
1768
-                                }
1769
-                                break 2;
1770
-                            } elseif (substr($paramstr, $ptr, strlen($this->rd)) === $this->rd) {
1771
-                                if ($this->debug) {
1772
-                                    echo 'PARAM PARSING ENDED, RIGHT DELIMITER FOUND, POINTER AT '.$ptr."\n";
1773
-                                }
1774
-                                break 2;
1775
-                            }
1776
-
1777
-                            if ($paramstr[$ptr] === ' ' || $paramstr[$ptr] === ',' || $paramstr[$ptr] === "\r" || $paramstr[$ptr] === "\n" || $paramstr[$ptr] === "\t") {
1778
-                                ++$ptr;
1779
-                            } else {
1780
-                                break;
1781
-                            }
1782
-                        }
1783
-
1784
-                        if ($this->debug) {
1785
-                            echo 'FUNC START PARAM PARSING WITH POINTER AT '.$ptr."\n";
1786
-                        }
1787
-
1788
-                        if ($func === 'if' || $func === 'elseif' || $func === 'tif') {
1789
-                            $params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'condition', $ptr);
1790
-                        } elseif ($func === 'array') {
1791
-                            $params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'array', $ptr);
1792
-                        } else {
1793
-                            $params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'function', $ptr);
1794
-                        }
1795
-
1796
-                        if ($this->debug) {
1797
-                            echo 'PARAM PARSED, POINTER AT '.$ptr.' ('.substr($paramstr, $ptr - 1, 3).')'."\n";
1798
-                        }
1799
-                    }
1800
-                }
1801
-                $paramstr = substr($paramstr, 0, $ptr);
1802
-                $state = 0;
1803
-                foreach ($params as $k => $p) {
1804
-                    if (is_array($p) && is_array($p[1])) {
1805
-                        $state |= 2;
1806
-                    } else {
1807
-                        if (($state & 2) && preg_match('#^(["\'])(.+?)\1$#', $p[0], $m) && $func !== 'array') {
1808
-                            $params[$k] = array($m[2], array('true', 'true'));
1809
-                        } else {
1810
-                            if ($state & 2 && $func !== 'array') {
1811
-                                throw new Dwoo_Compilation_Exception($this, 'You can not use an unnamed parameter after a named one');
1812
-                            }
1813
-                            $state |= 1;
1814
-                        }
1815
-                    }
1816
-                }
1817
-            }
1818
-        }
1819
-
1820
-        if ($pointer !== null) {
1821
-            $pointer += (isset($paramstr) ? strlen($paramstr) : 0) + (')' === $paramsep ? 2 : ($paramspos === false ? 0 : 1)) + strlen($func) + (isset($whitespace) ? $whitespace : 0);
1822
-            if ($this->debug) {
1823
-                echo 'FUNC ADDS '.((isset($paramstr) ? strlen($paramstr) : 0) + (')' === $paramsep ? 2 : ($paramspos === false ? 0 : 1)) + strlen($func)).' TO POINTER'."\n";
1824
-            }
1825
-        }
1826
-
1827
-        if ($curBlock === 'method' || $func === 'do' || strstr($func, '::') !== false) {
1828
-            // handle static method calls with security policy
1829
-            if (strstr($func, '::') !== false && $this->securityPolicy !== null && $this->securityPolicy->isMethodAllowed(explode('::', strtolower($func))) !== true) {
1830
-                throw new Dwoo_Security_Exception('Call to a disallowed php function : '.$func);
1831
-            }
1832
-            $pluginType = Dwoo_Core::NATIVE_PLUGIN;
1833
-        } else {
1834
-            $pluginType = $this->getPluginType($func);
1835
-        }
1836
-
1837
-        // blocks
1838
-        if ($pluginType & Dwoo_Core::BLOCK_PLUGIN) {
1839
-            if ($curBlock !== 'root' || is_array($parsingParams)) {
1840
-                throw new Dwoo_Compilation_Exception($this, 'Block plugins can not be used as other plugin\'s arguments');
1841
-            }
1842
-            if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1843
-                return $this->addCustomBlock($func, $params, $state);
1844
-            } else {
1845
-                return $this->addBlock($func, $params, $state);
1846
-            }
1847
-        } elseif ($pluginType & Dwoo_Core::SMARTY_BLOCK) {
1848
-            if ($curBlock !== 'root' || is_array($parsingParams)) {
1849
-                throw new Dwoo_Compilation_Exception($this, 'Block plugins can not be used as other plugin\'s arguments');
1850
-            }
1851
-
1852
-            if ($state & 2) {
1853
-                array_unshift($params, array('__functype', array($pluginType, $pluginType)));
1854
-                array_unshift($params, array('__funcname', array($func, $func)));
1855
-            } else {
1856
-                array_unshift($params, array($pluginType, $pluginType));
1857
-                array_unshift($params, array($func, $func));
1858
-            }
1859
-
1860
-            return $this->addBlock('smartyinterface', $params, $state);
1861
-        }
1862
-
1863
-        // funcs
1864
-        if ($pluginType & Dwoo_Core::NATIVE_PLUGIN || $pluginType & Dwoo_Core::SMARTY_FUNCTION || $pluginType & Dwoo_Core::SMARTY_BLOCK) {
1865
-            $params = $this->mapParams($params, null, $state);
1866
-        } elseif ($pluginType & Dwoo_Core::CLASS_PLUGIN) {
1867
-            if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1868
-                $params = $this->mapParams($params, array($this->customPlugins[$func]['class'], $this->customPlugins[$func]['function']), $state);
1869
-            } else {
1870
-                $params = $this->mapParams($params, array('Dwoo_Plugin_'.$func, ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) ? 'compile' : 'process'), $state);
1871
-            }
1872
-        } elseif ($pluginType & Dwoo_Core::FUNC_PLUGIN) {
1873
-            if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1874
-                $params = $this->mapParams($params, $this->customPlugins[$func]['callback'], $state);
1875
-            } else {
1876
-                $params = $this->mapParams($params, 'Dwoo_Plugin_'.$func.(($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) ? '_compile' : ''), $state);
1877
-            }
1878
-        } elseif ($pluginType & Dwoo_Core::SMARTY_MODIFIER) {
1879
-            $output = 'smarty_modifier_'.$func.'('.implode(', ', $params).')';
1880
-        } elseif ($pluginType & Dwoo_Core::PROXY_PLUGIN) {
1881
-            $params = $this->mapParams($params, $this->getDwoo()->getPluginProxy()->getCallback($func), $state);
1882
-        } elseif ($pluginType & Dwoo_Core::TEMPLATE_PLUGIN) {
1883
-            // transforms the parameter array from (x=>array('paramname'=>array(values))) to (paramname=>array(values))
1884
-            $map = array();
1885
-            foreach ($this->templatePlugins[$func]['params'] as $param => $defValue) {
1886
-                if ($param == 'rest') {
1887
-                    $param = '*';
1888
-                }
1889
-                $hasDefault = $defValue !== null;
1890
-                if ($defValue === 'null') {
1891
-                    $defValue = null;
1892
-                } elseif ($defValue === 'false') {
1893
-                    $defValue = false;
1894
-                } elseif ($defValue === 'true') {
1895
-                    $defValue = true;
1896
-                } elseif (preg_match('#^([\'"]).*?\1$#', $defValue)) {
1897
-                    $defValue = substr($defValue, 1, -1);
1898
-                }
1899
-                $map[] = array($param, $hasDefault, $defValue);
1900
-            }
1901
-
1902
-            $params = $this->mapParams($params, null, $state, $map);
1903
-        }
1904
-
1905
-        // only keep php-syntax-safe values for non-block plugins
1906
-        $tokens = array();
1907
-        foreach ($params as $k => $p) {
1908
-            $tokens[$k] = isset($p[2]) ? $p[2] : 0;
1909
-            $params[$k] = $p[0];
1910
-        }
1911
-        if ($pluginType & Dwoo_Core::NATIVE_PLUGIN) {
1912
-            if ($func === 'do') {
1913
-                if (isset($params['*'])) {
1914
-                    $output = implode(';', $params['*']).';';
1915
-                } else {
1916
-                    $output = '';
1917
-                }
1918
-
1919
-                if (is_array($parsingParams) || $curBlock !== 'root') {
1920
-                    throw new Dwoo_Compilation_Exception($this, 'Do can not be used inside another function or block');
1921
-                } else {
1922
-                    return self::PHP_OPEN.$output.self::PHP_CLOSE;
1923
-                }
1924
-            } else {
1925
-                if (isset($params['*'])) {
1926
-                    $output = $func.'('.implode(', ', $params['*']).')';
1927
-                } else {
1928
-                    $output = $func.'()';
1929
-                }
1930
-            }
1931
-        } elseif ($pluginType & Dwoo_Core::FUNC_PLUGIN) {
1932
-            if ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) {
1933
-                if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1934
-                    $funcCompiler = $this->customPlugins[$func]['callback'];
1935
-                } else {
1936
-                    $funcCompiler = 'Dwoo_Plugin_'.$func.'_compile';
1937
-                }
1938
-                array_unshift($params, $this);
1939
-                if ($func === 'tif') {
1940
-                    $params[] = $tokens;
1941
-                }
1942
-                $output = call_user_func_array($funcCompiler, $params);
1943
-            } else {
1944
-                if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1945
-                    $callback = $this->customPlugins[$func]['callback'];
1946
-                    if ($callback instanceof \Closure) {
1947
-                        array_unshift($params, $this->getDwoo());
1948
-                        $output = call_user_func_array($callback, $params);
1949
-                    } else {
1950
-                        array_unshift($params, '$this');
1951
-                        $params = self::implode_r($params);
1952
-                        $output = 'call_user_func(\''.$callback.'\', '.$params.')';
1953
-                    }
1954
-                } else {
1955
-                    array_unshift($params, '$this');
1956
-                    $params = self::implode_r($params);
1957
-                    $output = 'Dwoo_Plugin_'.$func.'('.$params.')';
1958
-                }
1959
-            }
1960
-        } elseif ($pluginType & Dwoo_Core::CLASS_PLUGIN) {
1961
-            if ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) {
1962
-                if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1963
-                    $callback = $this->customPlugins[$func]['callback'];
1964
-                    if (!is_array($callback)) {
1965
-                        if (!method_exists($callback, 'compile')) {
1966
-                            throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "compile" method to be compilable, or you should provide a full callback to the method to use');
1967
-                        }
1968
-                        if (($ref = new ReflectionMethod($callback, 'compile')) && $ref->isStatic()) {
1969
-                            $funcCompiler = array($callback, 'compile');
1970
-                        } else {
1971
-                            $funcCompiler = array(new $callback(), 'compile');
1972
-                        }
1973
-                    } else {
1974
-                        $funcCompiler = $callback;
1975
-                    }
1976
-                } else {
1977
-                    $funcCompiler = array('Dwoo_Plugin_'.$func, 'compile');
1978
-                    array_unshift($params, $this);
1979
-                }
1980
-                $output = call_user_func_array($funcCompiler, $params);
1981
-            } else {
1982
-                $params = self::implode_r($params);
1983
-                if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1984
-                    $callback = $this->customPlugins[$func]['callback'];
1985
-                    if (!is_array($callback)) {
1986
-                        if (!method_exists($callback, 'process')) {
1987
-                            throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "process" method to be usable, or you should provide a full callback to the method to use');
1988
-                        }
1989
-                        if (($ref = new ReflectionMethod($callback, 'process')) && $ref->isStatic()) {
1990
-                            $output = 'call_user_func(array(\''.$callback.'\', \'process\'), '.$params.')';
1991
-                        } else {
1992
-                            $output = 'call_user_func(array($this->getObjectPlugin(\''.$callback.'\'), \'process\'), '.$params.')';
1993
-                        }
1994
-                    } elseif (is_object($callback[0])) {
1995
-                        $output = 'call_user_func(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), '.$params.')';
1996
-                    } elseif (($ref = new ReflectionMethod($callback[0], $callback[1])) && $ref->isStatic()) {
1997
-                        $output = 'call_user_func(array(\''.$callback[0].'\', \''.$callback[1].'\'), '.$params.')';
1998
-                    } else {
1999
-                        $output = 'call_user_func(array($this->getObjectPlugin(\''.$callback[0].'\'), \''.$callback[1].'\'), '.$params.')';
2000
-                    }
2001
-                    if (empty($params)) {
2002
-                        $output = substr($output, 0, -3).')';
2003
-                    }
2004
-                } else {
2005
-                    $output = '$this->classCall(\''.$func.'\', array('.$params.'))';
2006
-                }
2007
-            }
2008
-        } elseif ($pluginType & Dwoo_Core::PROXY_PLUGIN) {
2009
-            $output = call_user_func(array($this->dwoo->getPluginProxy(), 'getCode'), $func, $params);
2010
-        } elseif ($pluginType & Dwoo_Core::SMARTY_FUNCTION) {
2011
-            if (isset($params['*'])) {
2012
-                $params = self::implode_r($params['*'], true);
2013
-            } else {
2014
-                $params = '';
2015
-            }
2016
-
2017
-            if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
2018
-                $callback = $this->customPlugins[$func]['callback'];
2019
-                if (is_array($callback)) {
2020
-                    if (is_object($callback[0])) {
2021
-                        $output = 'call_user_func_array(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array(array('.$params.'), $this))';
2022
-                    } else {
2023
-                        $output = 'call_user_func_array(array(\''.$callback[0].'\', \''.$callback[1].'\'), array(array('.$params.'), $this))';
2024
-                    }
2025
-                } else {
2026
-                    $output = $callback.'(array('.$params.'), $this)';
2027
-                }
2028
-            } else {
2029
-                $output = 'smarty_function_'.$func.'(array('.$params.'), $this)';
2030
-            }
2031
-        } elseif ($pluginType & Dwoo_Core::TEMPLATE_PLUGIN) {
2032
-            array_unshift($params, '$this');
2033
-            $params = self::implode_r($params);
2034
-            $output = 'Dwoo_Plugin_'.$func.'('.$params.')';
2035
-            $this->templatePlugins[$func]['called'] = true;
2036
-        }
2037
-
2038
-        if (is_array($parsingParams)) {
2039
-            $parsingParams[] = array($output, $output);
2040
-
2041
-            return $parsingParams;
2042
-        } elseif ($curBlock === 'namedparam') {
2043
-            return array($output, $output);
2044
-        } else {
2045
-            return $output;
2046
-        }
2047
-    }
2048
-
2049
-    /**
2050
-     * parses a string.
2051
-     *
2052
-     * @param string $in            the string within which we must parse something
2053
-     * @param int    $from          the starting offset of the parsed area
2054
-     * @param int    $to            the ending offset of the parsed area
2055
-     * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
2056
-     * @param string $curBlock      the current parser-block being processed
2057
-     * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
2058
-     *
2059
-     * @return string parsed values
2060
-     *
2061
-     * @throws Dwoo_Compilation_Exception
2062
-     */
2063
-    protected function parseString($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
2064
-    {
2065
-        $substr = substr($in, $from, $to - $from);
2066
-        $first = $substr[0];
2067
-
2068
-        if ($this->debug) {
2069
-            echo 'STRING FOUND (in '.htmlentities(substr($in, $from, min($to - $from, 50))).(($to - $from) > 50 ? '...' : '').')'."\n";
2070
-        }
2071
-        $strend = false;
2072
-        $o = $from + 1;
2073
-        while ($strend === false) {
2074
-            $strend = strpos($in, $first, $o);
2075
-            if ($strend === false) {
2076
-                throw new Dwoo_Compilation_Exception($this, 'Unfinished string, started with '.substr($in, $from, $to - $from));
2077
-            }
2078
-            if (substr($in, $strend - 1, 1) === '\\') {
2079
-                $o = $strend + 1;
2080
-                $strend = false;
2081
-            }
2082
-        }
2083
-        if ($this->debug) {
2084
-            echo 'STRING DELIMITED: '.substr($in, $from, $strend + 1 - $from)."\n";
2085
-        }
2086
-
2087
-        $srcOutput = substr($in, $from, $strend + 1 - $from);
2088
-
2089
-        if ($pointer !== null) {
2090
-            $pointer += strlen($srcOutput);
2091
-        }
2092
-
2093
-        $output = $this->replaceStringVars($srcOutput, $first);
2094
-
2095
-        // handle modifiers
2096
-        if ($curBlock !== 'modifier' && preg_match('#^((?:\|(?:@?[a-z0-9_]+(?::.*)*))+)#i', substr($substr, $strend + 1 - $from), $match)) {
2097
-            $modstr = $match[1];
2098
-
2099
-            if ($curBlock === 'root' && substr($modstr, -1) === '}') {
2100
-                $modstr = substr($modstr, 0, -1);
2101
-            }
2102
-            $modstr = str_replace('\\'.$first, $first, $modstr);
2103
-            $ptr = 0;
2104
-            $output = $this->replaceModifiers(array(null, null, $output, $modstr), 'string', $ptr);
2105
-
2106
-            $strend += $ptr;
2107
-            if ($pointer !== null) {
2108
-                $pointer += $ptr;
2109
-            }
2110
-            $srcOutput .= substr($substr, $strend + 1 - $from, $ptr);
2111
-        }
2112
-
2113
-        if (is_array($parsingParams)) {
2114
-            $parsingParams[] = array($output, substr($srcOutput, 1, -1));
2115
-
2116
-            return $parsingParams;
2117
-        } elseif ($curBlock === 'namedparam') {
2118
-            return array($output, substr($srcOutput, 1, -1));
2119
-        } else {
2120
-            return $output;
2121
-        }
2122
-    }
2123
-
2124
-    /**
2125
-     * parses a constant.
2126
-     *
2127
-     * @param string $in            the string within which we must parse something
2128
-     * @param int    $from          the starting offset of the parsed area
2129
-     * @param int    $to            the ending offset of the parsed area
2130
-     * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
2131
-     * @param string $curBlock      the current parser-block being processed
2132
-     * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
2133
-     *
2134
-     * @return string parsed values
2135
-     *
2136
-     * @throws Dwoo_Compilation_Exception
2137
-     */
2138
-    protected function parseConst($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
2139
-    {
2140
-        $substr = substr($in, $from, $to - $from);
2141
-
2142
-        if ($this->debug) {
2143
-            echo 'CONST FOUND : '.$substr."\n";
2144
-        }
2145
-
2146
-        if (!preg_match('#^%([\\\\a-z0-9_:]+)#i', $substr, $m)) {
2147
-            throw new Dwoo_Compilation_Exception($this, 'Invalid constant');
2148
-        }
2149
-
2150
-        if ($pointer !== null) {
2151
-            $pointer += strlen($m[0]);
2152
-        }
2153
-
2154
-        $output = $this->parseConstKey($m[1], $curBlock);
2155
-
2156
-        if (is_array($parsingParams)) {
2157
-            $parsingParams[] = array($output, $m[1]);
2158
-
2159
-            return $parsingParams;
2160
-        } elseif ($curBlock === 'namedparam') {
2161
-            return array($output, $m[1]);
2162
-        } else {
2163
-            return $output;
2164
-        }
2165
-    }
2166
-
2167
-    /**
2168
-     * parses a constant.
2169
-     *
2170
-     * @param string $key      the constant to parse
2171
-     * @param string $curBlock the current parser-block being processed
2172
-     *
2173
-     * @return string parsed constant
2174
-     */
2175
-    protected function parseConstKey($key, $curBlock)
2176
-    {
2177
-        if ($this->securityPolicy !== null && $this->securityPolicy->getConstantHandling() === Dwoo_Security_Policy::CONST_DISALLOW) {
2178
-            return 'null';
2179
-        }
2180
-
2181
-        if ($curBlock !== 'root') {
2182
-            $output = '(defined("'.$key.'") ? '.$key.' : null)';
2183
-        } else {
2184
-            $output = $key;
2185
-        }
2186
-
2187
-        return $output;
2188
-    }
2189
-
2190
-    /**
2191
-     * parses a variable.
2192
-     *
2193
-     * @param string $in            the string within which we must parse something
2194
-     * @param int    $from          the starting offset of the parsed area
2195
-     * @param int    $to            the ending offset of the parsed area
2196
-     * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
2197
-     * @param string $curBlock      the current parser-block being processed
2198
-     * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
2199
-     *
2200
-     * @return string parsed values
2201
-     *
2202
-     * @throws Dwoo_Compilation_Exception
2203
-     */
2204
-    protected function parseVar($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
2205
-    {
2206
-        $substr = substr($in, $from, $to - $from);
2207
-
2208
-        if (preg_match('#(\$?\.?[a-z0-9_:]*(?:(?:(?:\.|->)(?:[a-z0-9_:]+|(?R))|\[(?:[a-z0-9_:]+|(?R)|(["\'])[^\2]*?\2)\]))*)'. // var key
2209
-            ($curBlock === 'root' || $curBlock === 'function' || $curBlock === 'namedparam' || $curBlock === 'condition' || $curBlock === 'variable' || $curBlock === 'expression' || $curBlock === 'delimited_string' ? '(\(.*)?' : '()'). // method call
2210
-            ($curBlock === 'root' || $curBlock === 'function' || $curBlock === 'namedparam' || $curBlock === 'condition' || $curBlock === 'variable' || $curBlock === 'delimited_string' ? '((?:(?:[+/*%=-])(?:(?<!=)=?-?[$%][a-z0-9.[\]>_:-]+(?:\([^)]*\))?|(?<!=)=?-?[0-9.,]*|[+-]))*)' : '()'). // simple math expressions
2211
-            ($curBlock !== 'modifier' ? '((?:\|(?:@?[a-z0-9_]+(?:(?::("|\').*?\5|:[^`]*))*))+)?' : '(())'). // modifiers
2212
-            '#i', $substr, $match)) {
2213
-            $key = substr($match[1], 1);
2214
-
2215
-            $matchedLength = strlen($match[0]);
2216
-            $hasModifiers = !empty($match[5]);
2217
-            $hasExpression = !empty($match[4]);
2218
-            $hasMethodCall = !empty($match[3]);
2219
-
2220
-            if (substr($key, -1) == '.') {
2221
-                $key = substr($key, 0, -1);
2222
-                --$matchedLength;
2223
-            }
2224
-
2225
-            if ($hasMethodCall) {
2226
-                $matchedLength -= strlen($match[3]) + strlen(substr($match[1], strrpos($match[1], '->')));
2227
-                $key = substr($match[1], 1, strrpos($match[1], '->') - 1);
2228
-                $methodCall = substr($match[1], strrpos($match[1], '->')).$match[3];
2229
-            }
2230
-
2231
-            if ($hasModifiers) {
2232
-                $matchedLength -= strlen($match[5]);
2233
-            }
2234
-
2235
-            if ($pointer !== null) {
2236
-                $pointer += $matchedLength;
2237
-            }
2238
-
2239
-            // replace useless brackets by dot accessed vars and strip enclosing quotes if present
2240
-            $key = preg_replace('#\[(["\']?)([^$%\[.>-]+)\1\]#', '.$2', $key);
2241
-
2242
-            if ($this->debug) {
2243
-                if ($hasMethodCall) {
2244
-                    echo 'METHOD CALL FOUND : $'.$key.substr($methodCall, 0, 30)."\n";
2245
-                } else {
2246
-                    echo 'VAR FOUND : $'.$key."\n";
2247
-                }
2248
-            }
2249
-
2250
-            $key = str_replace('"', '\\"', $key);
2251
-
2252
-            $cnt = substr_count($key, '$');
2253
-            if ($cnt > 0) {
2254
-                $uid = 0;
2255
-                $parsed = array($uid => '');
2256
-                $current = &$parsed;
2257
-                $curTxt = &$parsed[$uid++];
2258
-                $tree = array();
2259
-                $chars = str_split($key, 1);
2260
-                $inSplittedVar = false;
2261
-                $bracketCount = 0;
2262
-
2263
-                while (($char = array_shift($chars)) !== null) {
2264
-                    if ($char === '[') {
2265
-                        if (count($tree) > 0) {
2266
-                            ++$bracketCount;
2267
-                        } else {
2268
-                            $tree[] = &$current;
2269
-                            $current[$uid] = array($uid + 1 => '');
2270
-                            $current = &$current[$uid++];
2271
-                            $curTxt = &$current[$uid++];
2272
-                            continue;
2273
-                        }
2274
-                    } elseif ($char === ']') {
2275
-                        if ($bracketCount > 0) {
2276
-                            --$bracketCount;
2277
-                        } else {
2278
-                            $current = &$tree[count($tree) - 1];
2279
-                            array_pop($tree);
2280
-                            if (current($chars) !== '[' && current($chars) !== false && current($chars) !== ']') {
2281
-                                $current[$uid] = '';
2282
-                                $curTxt = &$current[$uid++];
2283
-                            }
2284
-                            continue;
2285
-                        }
2286
-                    } elseif ($char === '$') {
2287
-                        if (count($tree) == 0) {
2288
-                            $curTxt = &$current[$uid++];
2289
-                            $inSplittedVar = true;
2290
-                        }
2291
-                    } elseif (($char === '.' || $char === '-') && count($tree) == 0 && $inSplittedVar) {
2292
-                        $curTxt = &$current[$uid++];
2293
-                        $inSplittedVar = false;
2294
-                    }
2295
-
2296
-                    $curTxt .= $char;
2297
-                }
2298
-                unset($uid, $current, $curTxt, $tree, $chars);
2299
-
2300
-                if ($this->debug) {
2301
-                    echo 'RECURSIVE VAR REPLACEMENT : '.$key."\n";
2302
-                }
2303
-
2304
-                $key = $this->flattenVarTree($parsed);
2305
-
2306
-                if ($this->debug) {
2307
-                    echo 'RECURSIVE VAR REPLACEMENT DONE : '.$key."\n";
2308
-                }
2309
-
2310
-                $output = preg_replace('#(^""\.|""\.|\.""$|(\()""\.|\.""(\)))#', '$2$3', '$this->readVar("'.$key.'")');
2311
-            } else {
2312
-                $output = $this->parseVarKey($key, $hasModifiers ? 'modifier' : $curBlock);
2313
-            }
2314
-
2315
-            // methods
2316
-            if ($hasMethodCall) {
2317
-                $ptr = 0;
2318
-
2319
-                $output = $this->parseMethodCall($output, $methodCall, $curBlock, $ptr);
2320
-
2321
-                if ($pointer !== null) {
2322
-                    $pointer += $ptr;
2323
-                }
2324
-                $matchedLength += $ptr;
2325
-            }
2326
-
2327
-            if ($hasExpression) {
2328
-                // expressions
2329
-                preg_match_all('#(?:([+/*%=-])(=?-?[%$][a-z0-9.[\]>_:-]+(?:\([^)]*\))?|=?-?[0-9.,]+|\1))#i', $match[4], $expMatch);
2330
-
2331
-                foreach ($expMatch[1] as $k => $operator) {
2332
-                    if (substr($expMatch[2][$k], 0, 1) === '=') {
2333
-                        $assign = true;
2334
-                        if ($operator === '=') {
2335
-                            throw new Dwoo_Compilation_Exception($this, 'Invalid expression <em>'.$substr.'</em>, can not use "==" in expressions');
2336
-                        }
2337
-                        if ($curBlock !== 'root') {
2338
-                            throw new Dwoo_Compilation_Exception($this, 'Invalid expression <em>'.$substr.'</em>, assignments can only be used in top level expressions like {$foo+=3} or {$foo="bar"}');
2339
-                        }
2340
-                        $operator .= '=';
2341
-                        $expMatch[2][$k] = substr($expMatch[2][$k], 1);
2342
-                    }
2343
-
2344
-                    if (substr($expMatch[2][$k], 0, 1) === '-' && strlen($expMatch[2][$k]) > 1) {
2345
-                        $operator .= '-';
2346
-                        $expMatch[2][$k] = substr($expMatch[2][$k], 1);
2347
-                    }
2348
-                    if (($operator === '+' || $operator === '-') && $expMatch[2][$k] === $operator) {
2349
-                        $output = '('.$output.$operator.$operator.')';
2350
-                        break;
2351
-                    } elseif (substr($expMatch[2][$k], 0, 1) === '$') {
2352
-                        $output = '('.$output.' '.$operator.' '.$this->parseVar($expMatch[2][$k], 0, strlen($expMatch[2][$k]), false, 'expression').')';
2353
-                    } elseif (substr($expMatch[2][$k], 0, 1) === '%') {
2354
-                        $output = '('.$output.' '.$operator.' '.$this->parseConst($expMatch[2][$k], 0, strlen($expMatch[2][$k]), false, 'expression').')';
2355
-                    } elseif (!empty($expMatch[2][$k])) {
2356
-                        $output = '('.$output.' '.$operator.' '.str_replace(',', '.', $expMatch[2][$k]).')';
2357
-                    } else {
2358
-                        throw new Dwoo_Compilation_Exception($this, 'Unfinished expression <em>'.$substr.'</em>, missing var or number after math operator');
2359
-                    }
2360
-                }
2361
-            }
2362
-
2363
-            if ($this->autoEscape === true && $curBlock !== 'condition') {
2364
-                $output = '(is_string($tmp='.$output.') ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp)';
2365
-            }
2366
-
2367
-            // handle modifiers
2368
-            if ($curBlock !== 'modifier' && $hasModifiers) {
2369
-                $ptr = 0;
2370
-                $output = $this->replaceModifiers(array(null, null, $output, $match[5]), 'var', $ptr);
2371
-                if ($pointer !== null) {
2372
-                    $pointer += $ptr;
2373
-                }
2374
-                $matchedLength += $ptr;
2375
-            }
2376
-
2377
-            if (is_array($parsingParams)) {
2378
-                $parsingParams[] = array($output, $key);
2379
-
2380
-                return $parsingParams;
2381
-            } elseif ($curBlock === 'namedparam') {
2382
-                return array($output, $key);
2383
-            } elseif ($curBlock === 'string' || $curBlock === 'delimited_string') {
2384
-                return array($matchedLength, $output);
2385
-            } elseif ($curBlock === 'expression' || $curBlock === 'variable') {
2386
-                return $output;
2387
-            } elseif (isset($assign)) {
2388
-                return self::PHP_OPEN.$output.';'.self::PHP_CLOSE;
2389
-            } else {
2390
-                return $output;
2391
-            }
2392
-        } else {
2393
-            if ($curBlock === 'string' || $curBlock === 'delimited_string') {
2394
-                return array(0, '');
2395
-            } else {
2396
-                throw new Dwoo_Compilation_Exception($this, 'Invalid variable name <em>'.$substr.'</em>');
2397
-            }
2398
-        }
2399
-    }
2400
-
2401
-    /**
2402
-     * parses any number of chained method calls/property reads.
2403
-     *
2404
-     * @param string $output     the variable or whatever upon which the method are called
2405
-     * @param string $methodCall method call source, starting at "->"
2406
-     * @param string $curBlock   the current parser-block being processed
2407
-     * @param int    $pointer    a reference to a pointer that will be increased by the amount of characters parsed
2408
-     *
2409
-     * @return string parsed call(s)/read(s)
2410
-     */
2411
-    protected function parseMethodCall($output, $methodCall, $curBlock, &$pointer)
2412
-    {
2413
-        $ptr = 0;
2414
-        $len = strlen($methodCall);
2415
-
2416
-        while ($ptr < $len) {
2417
-            if (strpos($methodCall, '->', $ptr) === $ptr) {
2418
-                $ptr += 2;
2419
-            }
2420
-
2421
-            if (in_array($methodCall[$ptr], array(';', ',', '/', ' ', "\t", "\r", "\n", ')', '+', '*', '%', '=', '-', '|')) || substr($methodCall, $ptr, strlen($this->rd)) === $this->rd) {
2422
-                // break char found
2423
-                break;
2424
-            }
2425
-
2426
-            if (!preg_match('/^([a-z0-9_]+)(\(.*?\))?/i', substr($methodCall, $ptr), $methMatch)) {
2427
-                break;
2428
-            }
2429
-
2430
-            if (empty($methMatch[2])) {
2431
-                // property
2432
-                if ($curBlock === 'root') {
2433
-                    $output .= '->'.$methMatch[1];
2434
-                } else {
2435
-                    $output = '(($tmp = '.$output.') ? $tmp->'.$methMatch[1].' : null)';
2436
-                }
2437
-                $ptr += strlen($methMatch[1]);
2438
-            } else {
2439
-                // method
2440
-                if (substr($methMatch[2], 0, 2) === '()') {
2441
-                    $parsedCall = $methMatch[1].'()';
2442
-                    $ptr += strlen($methMatch[1]) + 2;
2443
-                } else {
2444
-                    $parsedCall = $this->parseFunction($methodCall, $ptr, strlen($methodCall), false, 'method', $ptr);
2445
-                }
2446
-                if ($this->securityPolicy !== null) {
2447
-                    $argPos = strpos($parsedCall, '(');
2448
-                    $method = strtolower(substr($parsedCall, 0, $argPos));
2449
-                    $args = substr($parsedCall, $argPos);
2450
-                    if ($curBlock === 'root') {
2451
-                        $output = '$this->getSecurityPolicy()->callMethod($this, '.$output.', '.var_export($method, true).', array'.$args.')';
2452
-                    } else {
2453
-                        $output = '(($tmp = '.$output.') ? $this->getSecurityPolicy()->callMethod($this, $tmp, '.var_export($method, true).', array'.$args.') : null)';
2454
-                    }
2455
-                } else {
2456
-                    if ($curBlock === 'root') {
2457
-                        $output .= '->'.$parsedCall;
2458
-                    } else {
2459
-                        $output = '(($tmp = '.$output.') ? $tmp->'.$parsedCall.' : null)';
2460
-                    }
2461
-                }
2462
-            }
2463
-        }
2464
-
2465
-        $pointer += $ptr;
2466
-
2467
-        return $output;
2468
-    }
2469
-
2470
-    /**
2471
-     * parses a constant variable (a variable that doesn't contain another variable) and preprocesses it to save runtime processing time.
2472
-     *
2473
-     * @param string $key      the variable to parse
2474
-     * @param string $curBlock the current parser-block being processed
2475
-     *
2476
-     * @return string parsed variable
2477
-     */
2478
-    protected function parseVarKey($key, $curBlock)
2479
-    {
2480
-        if ($key === '') {
2481
-            return '$this->scope';
2482
-        }
2483
-        if (substr($key, 0, 1) === '.') {
2484
-            $key = 'dwoo'.$key;
2485
-        }
2486
-        if (preg_match('#dwoo\.(get|post|server|cookies|session|env|request)((?:\.[a-z0-9_-]+)+)#i', $key, $m)) {
2487
-            $global = strtoupper($m[1]);
2488
-            if ($global === 'COOKIES') {
2489
-                $global = 'COOKIE';
2490
-            }
2491
-            $key = '$_'.$global;
2492
-            foreach (explode('.', ltrim($m[2], '.')) as $part) {
2493
-                $key .= '['.var_export($part, true).']';
2494
-            }
2495
-            if ($curBlock === 'root') {
2496
-                $output = $key;
2497
-            } else {
2498
-                $output = '(isset('.$key.')?'.$key.':null)';
2499
-            }
2500
-        } elseif (preg_match('#dwoo\.const\.([a-z0-9_:]+)#i', $key, $m)) {
2501
-            return $this->parseConstKey($m[1], $curBlock);
2502
-        } elseif ($this->scope !== null) {
2503
-            if (strstr($key, '.') === false && strstr($key, '[') === false && strstr($key, '->') === false) {
2504
-                if ($key === 'dwoo') {
2505
-                    $output = '$this->globals';
2506
-                } elseif ($key === '_root' || $key === '__') {
2507
-                    $output = '$this->data';
2508
-                } elseif ($key === '_parent' || $key === '_') {
2509
-                    $output = '$this->readParentVar(1)';
2510
-                } elseif ($key === '_key') {
2511
-                    $output = '$tmp_key';
2512
-                } else {
2513
-                    if ($curBlock === 'root') {
2514
-                        $output = '$this->scope["'.$key.'"]';
2515
-                    } else {
2516
-                        $output = '(isset($this->scope["'.$key.'"]) ? $this->scope["'.$key.'"] : null)';
2517
-                    }
2518
-                }
2519
-            } else {
2520
-                preg_match_all('#(\[|->|\.)?((?:[a-z0-9_]|-(?!>))+|(\\\?[\'"])[^\3]*?\3)\]?#i', $key, $m);
2521
-
2522
-                $i = $m[2][0];
2523
-                if ($i === '_parent' || $i === '_') {
2524
-                    $parentCnt = 0;
2525
-
2526
-                    while (true) {
2527
-                        ++$parentCnt;
2528
-                        array_shift($m[2]);
2529
-                        array_shift($m[1]);
2530
-                        if (current($m[2]) === '_parent') {
2531
-                            continue;
2532
-                        }
2533
-                        break;
2534
-                    }
2535
-
2536
-                    $output = '$this->readParentVar('.$parentCnt.')';
2537
-                } else {
2538
-                    if ($i === 'dwoo') {
2539
-                        $output = '$this->globals';
2540
-                        array_shift($m[2]);
2541
-                        array_shift($m[1]);
2542
-                    } elseif ($i === '_root' || $i === '__') {
2543
-                        $output = '$this->data';
2544
-                        array_shift($m[2]);
2545
-                        array_shift($m[1]);
2546
-                    } elseif ($i === '_key') {
2547
-                        $output = '$tmp_key';
2548
-                    } else {
2549
-                        $output = '$this->scope';
2550
-                    }
2551
-
2552
-                    while (count($m[1]) && $m[1][0] !== '->') {
2553
-                        $m[2][0] = preg_replace('/(^\\\([\'"])|\\\([\'"])$)/x', '$2$3', $m[2][0]);
2554
-                        if (substr($m[2][0], 0, 1) == '"' || substr($m[2][0], 0, 1) == "'") {
2555
-                            $output .= '['.$m[2][0].']';
2556
-                        } else {
2557
-                            $output .= '["'.$m[2][0].'"]';
2558
-                        }
2559
-                        array_shift($m[2]);
2560
-                        array_shift($m[1]);
2561
-                    }
2562
-
2563
-                    if ($curBlock !== 'root') {
2564
-                        $output = '(isset('.$output.') ? '.$output.':null)';
2565
-                    }
2566
-                }
2567
-
2568
-                if (count($m[2])) {
2569
-                    unset($m[0]);
2570
-                    $output = '$this->readVarInto('.str_replace("\n", '', var_export($m, true)).', '.$output.', '.($curBlock == 'root' ? 'false' : 'true').')';
2571
-                }
2572
-            }
2573
-        } else {
2574
-            preg_match_all('#(\[|->|\.)?((?:[a-z0-9_]|-(?!>))+)\]?#i', $key, $m);
2575
-            unset($m[0]);
2576
-            $output = '$this->readVar('.str_replace("\n", '', var_export($m, true)).')';
2577
-        }
2578
-
2579
-        return $output;
2580
-    }
2581
-
2582
-    /**
2583
-     * flattens a variable tree, this helps in parsing very complex variables such as $var.foo[$foo.bar->baz].baz,
2584
-     * it computes the contents of the brackets first and works out from there.
2585
-     *
2586
-     * @param array $tree     the variable tree parsed by he parseVar() method that must be flattened
2587
-     * @param bool  $recursed leave that to false by default, it is only for internal use
2588
-     *
2589
-     * @return string flattened tree
2590
-     */
2591
-    protected function flattenVarTree(array $tree, $recursed = false)
2592
-    {
2593
-        $out = $recursed ? '".$this->readVarInto(' : '';
2594
-        foreach ($tree as $bit) {
2595
-            if (is_array($bit)) {
2596
-                $out .= '.'.$this->flattenVarTree($bit, false);
2597
-            } else {
2598
-                $key = str_replace('"', '\\"', $bit);
2599
-
2600
-                if (substr($key, 0, 1) === '$') {
2601
-                    $out .= '".'.$this->parseVar($key, 0, strlen($key), false, 'variable').'."';
2602
-                } else {
2603
-                    $cnt = substr_count($key, '$');
2604
-
2605
-                    if ($this->debug) {
2606
-                        echo 'PARSING SUBVARS IN : '.$key."\n";
2607
-                    }
2608
-                    if ($cnt > 0) {
2609
-                        while (--$cnt >= 0) {
2610
-                            if (isset($last)) {
2611
-                                $last = strrpos($key, '$', -(strlen($key) - $last + 1));
2612
-                            } else {
2613
-                                $last = strrpos($key, '$');
2614
-                            }
2615
-                            preg_match('#\$[a-z0-9_]+((?:(?:\.|->)(?:[a-z0-9_]+|(?R))|\[(?:[a-z0-9_]+|(?R))\]))*'.
2616
-                                      '((?:(?:[+/*%-])(?:\$[a-z0-9.[\]>_:-]+(?:\([^)]*\))?|[0-9.,]*))*)#i', substr($key, $last), $submatch);
2617
-
2618
-                            $len = strlen($submatch[0]);
2619
-                            $key = substr_replace(
2620
-                                $key,
2621
-                                preg_replace_callback(
2622
-                                    '#(\$[a-z0-9_]+((?:(?:\.|->)(?:[a-z0-9_]+|(?R))|\[(?:[a-z0-9_]+|(?R))\]))*)'.
2623
-                                    '((?:(?:[+/*%-])(?:\$[a-z0-9.[\]>_:-]+(?:\([^)]*\))?|[0-9.,]*))*)#i',
2624
-                                    array($this, 'replaceVarKeyHelper'), substr($key, $last, $len)
2625
-                                ),
2626
-                                $last,
2627
-                                $len
2628
-                            );
2629
-                            if ($this->debug) {
2630
-                                echo 'RECURSIVE VAR REPLACEMENT DONE : '.$key."\n";
2631
-                            }
2632
-                        }
2633
-                        unset($last);
2634
-
2635
-                        $out .= $key;
2636
-                    } else {
2637
-                        $out .= $key;
2638
-                    }
2639
-                }
2640
-            }
2641
-        }
2642
-        $out .= $recursed ? ', true)."' : '';
2643
-
2644
-        return $out;
2645
-    }
2646
-
2647
-    /**
2648
-     * helper function that parses a variable.
2649
-     *
2650
-     * @param array $match the matched variable, array(1=>"string match")
2651
-     *
2652
-     * @return string parsed variable
2653
-     */
2654
-    protected function replaceVarKeyHelper($match)
2655
-    {
2656
-        return '".'.$this->parseVar($match[0], 0, strlen($match[0]), false, 'variable').'."';
2657
-    }
2658
-
2659
-    /**
2660
-     * parses various constants, operators or non-quoted strings.
2661
-     *
2662
-     * @param string $in            the string within which we must parse something
2663
-     * @param int    $from          the starting offset of the parsed area
2664
-     * @param int    $to            the ending offset of the parsed area
2665
-     * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
2666
-     * @param string $curBlock      the current parser-block being processed
2667
-     * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
2668
-     *
2669
-     * @return string parsed values
2670
-     *
2671
-     * @throws Exception
2672
-     */
2673
-    protected function parseOthers($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
2674
-    {
2675
-        $first = $in[$from];
2676
-        $substr = substr($in, $from, $to - $from);
2677
-
2678
-        $end = strlen($substr);
2679
-
2680
-        if ($curBlock === 'condition') {
2681
-            $breakChars = array('(', ')', ' ', '||', '&&', '|', '&', '>=', '<=', '===', '==', '=', '!==', '!=', '<<', '<', '>>', '>', '^', '~', ',', '+', '-', '*', '/', '%', '!', '?', ':', $this->rd, ';');
2682
-        } elseif ($curBlock === 'modifier') {
2683
-            $breakChars = array(' ', ',', ')', ':', '|', "\r", "\n", "\t", ';', $this->rd);
2684
-        } elseif ($curBlock === 'expression') {
2685
-            $breakChars = array('/', '%', '+', '-', '*', ' ', ',', ')', "\r", "\n", "\t", ';', $this->rd);
2686
-        } else {
2687
-            $breakChars = array(' ', ',', ')', "\r", "\n", "\t", ';', $this->rd);
2688
-        }
2689
-
2690
-        $breaker = false;
2691
-        while (list($k, $char) = each($breakChars)) {
2692
-            $test = strpos($substr, $char);
2693
-            if ($test !== false && $test < $end) {
2694
-                $end = $test;
2695
-                $breaker = $k;
2696
-            }
2697
-        }
2698
-
2699
-        if ($curBlock === 'condition') {
2700
-            if ($end === 0 && $breaker !== false) {
2701
-                $end = strlen($breakChars[$breaker]);
2702
-            }
2703
-        }
2704
-
2705
-        if ($end !== false) {
2706
-            $substr = substr($substr, 0, $end);
2707
-        }
2708
-
2709
-        if ($pointer !== null) {
2710
-            $pointer += strlen($substr);
2711
-        }
2712
-
2713
-        $src = $substr;
2714
-        $substr = trim($substr);
2715
-
2716
-        if (strtolower($substr) === 'false' || strtolower($substr) === 'no' || strtolower($substr) === 'off') {
2717
-            if ($this->debug) {
2718
-                echo 'BOOLEAN(FALSE) PARSED'."\n";
2719
-            }
2720
-            $substr = 'false';
2721
-            $type = self::T_BOOL;
2722
-        } elseif (strtolower($substr) === 'true' || strtolower($substr) === 'yes' || strtolower($substr) === 'on') {
2723
-            if ($this->debug) {
2724
-                echo 'BOOLEAN(TRUE) PARSED'."\n";
2725
-            }
2726
-            $substr = 'true';
2727
-            $type = self::T_BOOL;
2728
-        } elseif ($substr === 'null' || $substr === 'NULL') {
2729
-            if ($this->debug) {
2730
-                echo 'NULL PARSED'."\n";
2731
-            }
2732
-            $substr = 'null';
2733
-            $type = self::T_NULL;
2734
-        } elseif (is_numeric($substr)) {
2735
-            $substr = (float) $substr;
2736
-            if ((int) $substr == $substr) {
2737
-                $substr = (int) $substr;
2738
-            }
2739
-            $type = self::T_NUMERIC;
2740
-            if ($this->debug) {
2741
-                echo 'NUMBER ('.$substr.') PARSED'."\n";
2742
-            }
2743
-        } elseif (preg_match('{^-?(\d+|\d*(\.\d+))\s*([/*%+-]\s*-?(\d+|\d*(\.\d+)))+$}', $substr)) {
2744
-            if ($this->debug) {
2745
-                echo 'SIMPLE MATH PARSED . "\n"';
2746
-            }
2747
-            $type = self::T_MATH;
2748
-            $substr = '('.$substr.')';
2749
-        } elseif ($curBlock === 'condition' && array_search($substr, $breakChars, true) !== false) {
2750
-            if ($this->debug) {
2751
-                echo 'BREAKCHAR ('.$substr.') PARSED'."\n";
2752
-            }
2753
-            $type = self::T_BREAKCHAR;
2754
-            //$substr = '"'.$substr.'"';
2755
-        } else {
2756
-            $substr = $this->replaceStringVars('\''.str_replace('\'', '\\\'', $substr).'\'', '\'', $curBlock);
2757
-            $type = self::T_UNQUOTED_STRING;
2758
-            if ($this->debug) {
2759
-                echo 'BLABBER ('.$substr.') CASTED AS STRING'."\n";
2760
-            }
2761
-        }
2762
-
2763
-        if (is_array($parsingParams)) {
2764
-            $parsingParams[] = array($substr, $src, $type);
2765
-
2766
-            return $parsingParams;
2767
-        } elseif ($curBlock === 'namedparam') {
2768
-            return array($substr, $src, $type);
2769
-        } elseif ($curBlock === 'expression') {
2770
-            return $substr;
2771
-        } else {
2772
-            throw new Exception('Something went wrong');
2773
-        }
2774
-    }
2775
-
2776
-    /**
2777
-     * replaces variables within a parsed string.
2778
-     *
2779
-     * @param string $string   the parsed string
2780
-     * @param string $first    the first character parsed in the string, which is the string delimiter (' or ")
2781
-     * @param string $curBlock the current parser-block being processed
2782
-     *
2783
-     * @return string the original string with variables replaced
2784
-     */
2785
-    protected function replaceStringVars($string, $first, $curBlock = '')
2786
-    {
2787
-        $pos = 0;
2788
-        if ($this->debug) {
2789
-            echo 'STRING VAR REPLACEMENT : '.$string."\n";
2790
-        }
2791
-        // replace vars
2792
-        while (($pos = strpos($string, '$', $pos)) !== false) {
2793
-            $prev = substr($string, $pos - 1, 1);
2794
-            if ($prev === '\\') {
2795
-                ++$pos;
2796
-                continue;
2797
-            }
2798
-
2799
-            $var = $this->parse($string, $pos, null, false, ($curBlock === 'modifier' ? 'modifier' : ($prev === '`' ? 'delimited_string' : 'string')));
2800
-            $len = $var[0];
2801
-            $var = $this->parse(str_replace('\\'.$first, $first, $string), $pos, null, false, ($curBlock === 'modifier' ? 'modifier' : ($prev === '`' ? 'delimited_string' : 'string')));
2802
-
2803
-            if ($prev === '`' && substr($string, $pos + $len, 1) === '`') {
2804
-                $string = substr_replace($string, $first.'.'.$var[1].'.'.$first, $pos - 1, $len + 2);
2805
-            } else {
2806
-                $string = substr_replace($string, $first.'.'.$var[1].'.'.$first, $pos, $len);
2807
-            }
2808
-            $pos += strlen($var[1]) + 2;
2809
-            if ($this->debug) {
2810
-                echo 'STRING VAR REPLACEMENT DONE : '.$string."\n";
2811
-            }
2812
-        }
2813
-
2814
-        // handle modifiers
2815
-        // TODO Obsolete?
2816
-        $string = preg_replace_callback('#("|\')\.(.+?)\.\1((?:\|(?:@?[a-z0-9_]+(?:(?::("|\').+?\4|:[^`]*))*))+)#i', array($this, 'replaceModifiers'), $string);
2817
-
2818
-        // replace escaped dollar operators by unescaped ones if required
2819
-        if ($first === "'") {
2820
-            $string = str_replace('\\$', '$', $string);
2821
-        }
2822
-
2823
-        return $string;
2824
-    }
2825
-
2826
-    /**
2827
-     * replaces the modifiers applied to a string or a variable.
2828
-     *
2829
-     * @param array  $m        the regex matches that must be array(1=>"double or single quotes enclosing a string, when applicable", 2=>"the string or var", 3=>"the modifiers matched")
2830
-     * @param string $curBlock the current parser-block being processed
2831
-     * @param null   $pointer
2832
-     *
2833
-     * @return string the input enclosed with various function calls according to the modifiers found
2834
-     *
2835
-     * @throws Dwoo_Compilation_Exception
2836
-     * @throws Dwoo_Exception
2837
-     */
2838
-    protected function replaceModifiers(array $m, $curBlock = null, &$pointer = null)
2839
-    {
2840
-        if ($this->debug) {
2841
-            echo 'PARSING MODIFIERS : '.$m[3]."\n";
2842
-        }
2843
-
2844
-        if ($pointer !== null) {
2845
-            $pointer += strlen($m[3]);
2846
-        }
2847
-        // remove first pipe
2848
-        $cmdstrsrc = substr($m[3], 1);
2849
-        // remove last quote if present
2850
-        if (substr($cmdstrsrc, -1, 1) === $m[1]) {
2851
-            $cmdstrsrc = substr($cmdstrsrc, 0, -1);
2852
-            $add = $m[1];
2853
-        }
2854
-
2855
-        $output = $m[2];
2856
-
2857
-        $continue = true;
2858
-        while (strlen($cmdstrsrc) > 0 && $continue) {
2859
-            if ($cmdstrsrc[0] === '|') {
2860
-                $cmdstrsrc = substr($cmdstrsrc, 1);
2861
-                continue;
2862
-            }
2863
-            if ($cmdstrsrc[0] === ' ' || $cmdstrsrc[0] === ';' || substr($cmdstrsrc, 0, strlen($this->rd)) === $this->rd) {
2864
-                if ($this->debug) {
2865
-                    echo 'MODIFIER PARSING ENDED, RIGHT DELIMITER or ";" FOUND'."\n";
2866
-                }
2867
-                $continue = false;
2868
-                if ($pointer !== null) {
2869
-                    $pointer -= strlen($cmdstrsrc);
2870
-                }
2871
-                break;
2872
-            }
2873
-            $cmdstr = $cmdstrsrc;
2874
-            $paramsep = ':';
2875
-            if (!preg_match('/^(@{0,2}[a-z_][a-z0-9_]*)(:)?/i', $cmdstr, $match)) {
2876
-                throw new Dwoo_Compilation_Exception($this, 'Invalid modifier name, started with : '.substr($cmdstr, 0, 10));
2877
-            }
2878
-            $paramspos = !empty($match[2]) ? strlen($match[1]) : false;
2879
-            $func = $match[1];
2880
-
2881
-            $state = 0;
2882
-            if ($paramspos === false) {
2883
-                $cmdstrsrc = substr($cmdstrsrc, strlen($func));
2884
-                $params = array();
2885
-                if ($this->debug) {
2886
-                    echo 'MODIFIER ('.$func.') CALLED WITH NO PARAMS'."\n";
2887
-                }
2888
-            } else {
2889
-                $paramstr = substr($cmdstr, $paramspos + 1);
2890
-                if (substr($paramstr, -1, 1) === $paramsep) {
2891
-                    $paramstr = substr($paramstr, 0, -1);
2892
-                }
2893
-
2894
-                $ptr = 0;
2895
-                $params = array();
2896
-                while ($ptr < strlen($paramstr)) {
2897
-                    if ($this->debug) {
2898
-                        echo 'MODIFIER ('.$func.') START PARAM PARSING WITH POINTER AT '.$ptr."\n";
2899
-                    }
2900
-                    if ($this->debug) {
2901
-                        echo $paramstr.'--'.$ptr.'--'.strlen($paramstr).'--modifier'."\n";
2902
-                    }
2903
-                    $params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'modifier', $ptr);
2904
-                    if ($this->debug) {
2905
-                        echo 'PARAM PARSED, POINTER AT '.$ptr."\n";
2906
-                    }
2907
-
2908
-                    if ($ptr >= strlen($paramstr)) {
2909
-                        if ($this->debug) {
2910
-                            echo 'PARAM PARSING ENDED, PARAM STRING CONSUMED'."\n";
2911
-                        }
2912
-                        break;
2913
-                    }
2914
-
2915
-                    if ($paramstr[$ptr] === ' ' || $paramstr[$ptr] === '|' || $paramstr[$ptr] === ';' || substr($paramstr, $ptr, strlen($this->rd)) === $this->rd) {
2916
-                        if ($this->debug) {
2917
-                            echo 'PARAM PARSING ENDED, " ", "|", RIGHT DELIMITER or ";" FOUND, POINTER AT '.$ptr."\n";
2918
-                        }
2919
-                        if ($paramstr[$ptr] !== '|') {
2920
-                            $continue = false;
2921
-                            if ($pointer !== null) {
2922
-                                $pointer -= strlen($paramstr) - $ptr;
2923
-                            }
2924
-                        }
2925
-                        ++$ptr;
2926
-                        break;
2927
-                    }
2928
-                    if ($ptr < strlen($paramstr) && $paramstr[$ptr] === ':') {
2929
-                        ++$ptr;
2930
-                    }
2931
-                }
2932
-                $cmdstrsrc = substr($cmdstrsrc, strlen($func) + 1 + $ptr);
2933
-                $paramstr = substr($paramstr, 0, $ptr);
2934
-                foreach ($params as $k => $p) {
2935
-                    if (is_array($p) && is_array($p[1])) {
2936
-                        $state |= 2;
2937
-                    } else {
2938
-                        if (($state & 2) && preg_match('#^(["\'])(.+?)\1$#', $p[0], $m)) {
2939
-                            $params[$k] = array($m[2], array('true', 'true'));
2940
-                        } else {
2941
-                            if ($state & 2) {
2942
-                                throw new Dwoo_Compilation_Exception($this, 'You can not use an unnamed parameter after a named one');
2943
-                            }
2944
-                            $state |= 1;
2945
-                        }
2946
-                    }
2947
-                }
2948
-            }
2949
-
2950
-            // check if we must use array_map with this plugin or not
2951
-            $mapped = false;
2952
-            if (substr($func, 0, 1) === '@') {
2953
-                $func = substr($func, 1);
2954
-                $mapped = true;
2955
-            }
2956
-
2957
-            $pluginType = $this->getPluginType($func);
2958
-
2959
-            if ($state & 2) {
2960
-                array_unshift($params, array('value', is_array($output) ? $output : array($output, $output)));
2961
-            } else {
2962
-                array_unshift($params, is_array($output) ? $output : array($output, $output));
2963
-            }
2964
-
2965
-            if ($pluginType & Dwoo_Core::NATIVE_PLUGIN) {
2966
-                $params = $this->mapParams($params, null, $state);
2967
-
2968
-                $params = $params['*'][0];
2969
-
2970
-                $params = self::implode_r($params);
2971
-
2972
-                if ($mapped) {
2973
-                    $output = '$this->arrayMap(\''.$func.'\', array('.$params.'))';
2974
-                } else {
2975
-                    $output = $func.'('.$params.')';
2976
-                }
2977
-            } elseif ($pluginType & Dwoo_Core::PROXY_PLUGIN) {
2978
-                $params = $this->mapParams($params, $this->getDwoo()->getPluginProxy()->getCallback($func), $state);
2979
-                foreach ($params as &$p) {
2980
-                    $p = $p[0];
2981
-                }
2982
-                $output = call_user_func(array($this->dwoo->getPluginProxy(), 'getCode'), $func, $params);
2983
-            } elseif ($pluginType & Dwoo_Core::SMARTY_MODIFIER) {
2984
-                $params = $this->mapParams($params, null, $state);
2985
-                $params = $params['*'][0];
2986
-
2987
-                $params = self::implode_r($params);
2988
-
2989
-                if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
2990
-                    $callback = $this->customPlugins[$func]['callback'];
2991
-                    if (is_array($callback)) {
2992
-                        if (is_object($callback[0])) {
2993
-                            $output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array('.$params.'))';
2994
-                        } else {
2995
-                            $output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array(\''.$callback[0].'\', \''.$callback[1].'\'), array('.$params.'))';
2996
-                        }
2997
-                    } elseif ($mapped) {
2998
-                        $output = '$this->arrayMap(\''.$callback.'\', array('.$params.'))';
2999
-                    } else {
3000
-                        $output = $callback.'('.$params.')';
3001
-                    }
3002
-                } elseif ($mapped) {
3003
-                    $output = '$this->arrayMap(\'smarty_modifier_'.$func.'\', array('.$params.'))';
3004
-                } else {
3005
-                    $output = 'smarty_modifier_'.$func.'('.$params.')';
3006
-                }
3007
-            } else {
3008
-                if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
3009
-                    $callback = $this->customPlugins[$func]['callback'];
3010
-                    $pluginName = $callback;
3011
-                } else {
3012
-                    $pluginName = 'Dwoo_Plugin_'.$func;
3013
-
3014
-                    if ($pluginType & Dwoo_Core::CLASS_PLUGIN) {
3015
-                        $callback = array($pluginName, ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) ? 'compile' : 'process');
3016
-                    } else {
3017
-                        $callback = $pluginName.(($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) ? '_compile' : '');
3018
-                    }
3019
-                }
3020
-
3021
-                $params = $this->mapParams($params, $callback, $state);
3022
-
3023
-                foreach ($params as &$p) {
3024
-                    $p = $p[0];
3025
-                }
3026
-
3027
-                if ($pluginType & Dwoo_Core::FUNC_PLUGIN) {
3028
-                    if ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) {
3029
-                        if ($mapped) {
3030
-                            throw new Dwoo_Compilation_Exception($this, 'The @ operator can not be used on compiled plugins.');
3031
-                        }
3032
-                        if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
3033
-                            $funcCompiler = $this->customPlugins[$func]['callback'];
3034
-                        } else {
3035
-                            $funcCompiler = 'Dwoo_Plugin_'.$func.'_compile';
3036
-                        }
3037
-                        array_unshift($params, $this);
3038
-                        $output = call_user_func_array($funcCompiler, $params);
3039
-                    } else {
3040
-                        array_unshift($params, '$this');
3041
-
3042
-                        $params = self::implode_r($params);
3043
-                        if ($mapped) {
3044
-                            $output = '$this->arrayMap(\''.$pluginName.'\', array('.$params.'))';
3045
-                        } else {
3046
-                            $output = $pluginName.'('.$params.')';
3047
-                        }
3048
-                    }
3049
-                } else {
3050
-                    if ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) {
3051
-                        if ($mapped) {
3052
-                            throw new Dwoo_Compilation_Exception($this, 'The @ operator can not be used on compiled plugins.');
3053
-                        }
3054
-                        if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
3055
-                            $callback = $this->customPlugins[$func]['callback'];
3056
-                            if (!is_array($callback)) {
3057
-                                if (!method_exists($callback, 'compile')) {
3058
-                                    throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "compile" method to be compilable, or you should provide a full callback to the method to use');
3059
-                                }
3060
-                                if (($ref = new ReflectionMethod($callback, 'compile')) && $ref->isStatic()) {
3061
-                                    $funcCompiler = array($callback, 'compile');
3062
-                                } else {
3063
-                                    $funcCompiler = array(new $callback(), 'compile');
3064
-                                }
3065
-                            } else {
3066
-                                $funcCompiler = $callback;
3067
-                            }
3068
-                        } else {
3069
-                            $funcCompiler = array('Dwoo_Plugin_'.$func, 'compile');
3070
-                            array_unshift($params, $this);
3071
-                        }
3072
-                        $output = call_user_func_array($funcCompiler, $params);
3073
-                    } else {
3074
-                        $params = self::implode_r($params);
3075
-
3076
-                        if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
3077
-                            if (is_object($callback[0])) {
3078
-                                $output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array('.$params.'))';
3079
-                            } else {
3080
-                                $output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array(\''.$callback[0].'\', \''.$callback[1].'\'), array('.$params.'))';
3081
-                            }
3082
-                        } elseif ($mapped) {
3083
-                            $output = '$this->arrayMap(array($this->getObjectPlugin(\'Dwoo_Plugin_'.$func.'\'), \'process\'), array('.$params.'))';
3084
-                        } else {
3085
-                            $output = '$this->classCall(\''.$func.'\', array('.$params.'))';
3086
-                        }
3087
-                    }
3088
-                }
3089
-            }
3090
-        }
3091
-
3092
-        if ($curBlock === 'namedparam') {
3093
-            return array($output, $output);
3094
-        } elseif ($curBlock === 'var' || $m[1] === null) {
3095
-            return $output;
3096
-        } elseif ($curBlock === 'string' || $curBlock === 'root') {
3097
-            return $m[1].'.'.$output.'.'.$m[1].(isset($add) ? $add : null);
3098
-        }
3099
-
3100
-        return '';
3101
-    }
3102
-
3103
-    /**
3104
-     * recursively implodes an array in a similar manner as var_export() does but with some tweaks
3105
-     * to handle pre-compiled values and the fact that we do not need to enclose everything with
3106
-     * "array" and do not require top-level keys to be displayed.
3107
-     *
3108
-     * @param array $params        the array to implode
3109
-     * @param bool  $recursiveCall if set to true, the function outputs key names for the top level
3110
-     *
3111
-     * @return string the imploded array
3112
-     */
3113
-    public static function implode_r(array $params, $recursiveCall = false)
3114
-    {
3115
-        $out = '';
3116
-        foreach ($params as $k => $p) {
3117
-            if (is_array($p)) {
3118
-                $out2 = 'array(';
3119
-                foreach ($p as $k2 => $v) {
3120
-                    $out2 .= var_export($k2, true).' => '.(is_array($v) ? 'array('.self::implode_r($v, true).')' : $v).', ';
3121
-                }
3122
-                $p = rtrim($out2, ', ').')';
3123
-            }
3124
-            if ($recursiveCall) {
3125
-                $out .= var_export($k, true).' => '.$p.', ';
3126
-            } else {
3127
-                $out .= $p.', ';
3128
-            }
3129
-        }
3130
-
3131
-        return rtrim($out, ', ');
3132
-    }
3133
-
3134
-    /**
3135
-     * returns the plugin type of a plugin and adds it to the used plugins array if required.
3136
-     *
3137
-     * @param string $name plugin name, as found in the template
3138
-     *
3139
-     * @return int type as a multi bit flag composed of the Dwoo plugin types constants
3140
-     *
3141
-     * @throws Dwoo_Exception
3142
-     * @throws Dwoo_Security_Exception
3143
-     * @throws Exception
3144
-     */
3145
-    protected function getPluginType($name)
3146
-    {
3147
-        $pluginType = -1;
3148
-
3149
-        if (($this->securityPolicy === null && (function_exists($name) || strtolower($name) === 'isset' || strtolower($name) === 'empty')) ||
3150
-            ($this->securityPolicy !== null && array_key_exists(strtolower($name), $this->securityPolicy->getAllowedPhpFunctions()) !== false)) {
3151
-            $phpFunc = true;
3152
-        } elseif ($this->securityPolicy !== null && function_exists($name) && array_key_exists(strtolower($name), $this->securityPolicy->getAllowedPhpFunctions()) === false) {
3153
-            throw new Dwoo_Security_Exception('Call to a disallowed php function : '.$name);
3154
-        }
3155
-
3156
-        while ($pluginType <= 0) {
3157
-            if (isset($this->templatePlugins[$name])) {
3158
-                $pluginType = Dwoo_Core::TEMPLATE_PLUGIN | Dwoo_Core::COMPILABLE_PLUGIN;
3159
-            } elseif (isset($this->customPlugins[$name])) {
3160
-                $pluginType = $this->customPlugins[$name]['type'] | Dwoo_Core::CUSTOM_PLUGIN;
3161
-            } elseif (class_exists('Dwoo_Plugin_'.$name) !== false) {
3162
-                if (is_subclass_of('Dwoo_Plugin_'.$name, 'Dwoo_Block_Plugin')) {
3163
-                    $pluginType = Dwoo_Core::BLOCK_PLUGIN;
3164
-                } else {
3165
-                    $pluginType = Dwoo_Core::CLASS_PLUGIN;
3166
-                }
3167
-                $interfaces = class_implements('Dwoo_Plugin_'.$name);
3168
-                if (in_array('Dwoo_ICompilable', $interfaces) !== false || in_array('Dwoo_ICompilable_Block', $interfaces) !== false) {
3169
-                    $pluginType |= Dwoo_Core::COMPILABLE_PLUGIN;
3170
-                }
3171
-            } elseif (function_exists('Dwoo_Plugin_'.$name) !== false) {
3172
-                $pluginType = Dwoo_Core::FUNC_PLUGIN;
3173
-            } elseif (function_exists('Dwoo_Plugin_'.$name.'_compile')) {
3174
-                $pluginType = Dwoo_Core::FUNC_PLUGIN | Dwoo_Core::COMPILABLE_PLUGIN;
3175
-            } elseif (function_exists('smarty_modifier_'.$name) !== false) {
3176
-                $pluginType = Dwoo_Core::SMARTY_MODIFIER;
3177
-            } elseif (function_exists('smarty_function_'.$name) !== false) {
3178
-                $pluginType = Dwoo_Core::SMARTY_FUNCTION;
3179
-            } elseif (function_exists('smarty_block_'.$name) !== false) {
3180
-                $pluginType = Dwoo_Core::SMARTY_BLOCK;
3181
-            } else {
3182
-                if ($pluginType === -1) {
3183
-                    try {
3184
-                        $this->dwoo->getLoader()->loadPlugin($name, isset($phpFunc) === false);
3185
-                    } catch (Exception $e) {
3186
-                        if (isset($phpFunc)) {
3187
-                            $pluginType = Dwoo_Core::NATIVE_PLUGIN;
3188
-                        } elseif (is_object($this->dwoo->getPluginProxy()) && $this->dwoo->getPluginProxy()->handles($name)) {
3189
-                            $pluginType = Dwoo_Core::PROXY_PLUGIN;
3190
-                            break;
3191
-                        } else {
3192
-                            throw $e;
3193
-                        }
3194
-                    }
3195
-                } else {
3196
-                    throw new Dwoo_Exception('Plugin "'.$name.'" could not be found');
3197
-                }
3198
-                ++$pluginType;
3199
-            }
3200
-        }
3201
-
3202
-        if (($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) === 0 && ($pluginType & Dwoo_Core::NATIVE_PLUGIN) === 0 && ($pluginType & Dwoo_Core::PROXY_PLUGIN) === 0) {
3203
-            $this->addUsedPlugin($name, $pluginType);
3204
-        }
3205
-
3206
-        return $pluginType;
3207
-    }
3208
-
3209
-    /**
3210
-     * allows a plugin to load another one at compile time, this will also mark
3211
-     * it as used by this template so it will be loaded at runtime (which can be
3212
-     * useful for compiled plugins that rely on another plugin when their compiled
3213
-     * code runs).
3214
-     *
3215
-     * @param string $name the plugin name
3216
-     */
3217
-    public function loadPlugin($name)
3218
-    {
3219
-        $this->getPluginType($name);
3220
-    }
3221
-
3222
-    /**
3223
-     * runs htmlentities over the matched <?php ?> blocks when the security policy enforces that.
3224
-     *
3225
-     * @param array $match matched php block
3226
-     *
3227
-     * @return string the htmlentities-converted string
3228
-     */
3229
-    protected function phpTagEncodingHelper($match)
3230
-    {
3231
-        return htmlspecialchars($match[0]);
3232
-    }
3233
-
3234
-    /**
3235
-     * maps the parameters received from the template onto the parameters required by the given callback.
3236
-     *
3237
-     * @param array    $params   the array of parameters
3238
-     * @param callback $callback the function or method to reflect on to find out the required parameters
3239
-     * @param int      $callType the type of call in the template, 0 = no params, 1 = php-style call, 2 = named parameters call
3240
-     * @param array    $map      the parameter map to use, if not provided it will be built from the callback
3241
-     *
3242
-     * @return array parameters sorted in the correct order with missing optional parameters filled
3243
-     *
3244
-     * @throws Dwoo_Compilation_Exception
3245
-     */
3246
-    protected function mapParams(array $params, $callback, $callType = 2, $map = null)
3247
-    {
3248
-        if (!$map) {
3249
-            $map = $this->getParamMap($callback);
3250
-        }
3251
-
3252
-        $paramlist = array();
3253
-
3254
-        // transforms the parameter array from (x=>array('paramname'=>array(values))) to (paramname=>array(values))
3255
-        $ps = array();
3256
-        foreach ($params as $p) {
3257
-            if (is_array($p[1])) {
3258
-                $ps[$p[0]] = $p[1];
3259
-            } else {
3260
-                $ps[] = $p;
3261
-            }
3262
-        }
3263
-
3264
-        // loops over the param map and assigns values from the template or default value for unset optional params
3265
-        while (list($k, $v) = each($map)) {
3266
-            if ($v[0] === '*') {
3267
-                // "rest" array parameter, fill every remaining params in it and then break
3268
-                if (count($ps) === 0) {
3269
-                    if ($v[1] === false) {
3270
-                        throw new Dwoo_Compilation_Exception($this, 'Rest argument missing for '.str_replace(array('Dwoo_Plugin_', '_compile'), '', (is_array($callback) ? $callback[0] : $callback)));
3271
-                    } else {
3272
-                        break;
3273
-                    }
3274
-                }
3275
-                $tmp = array();
3276
-                $tmp2 = array();
3277
-                $tmp3 = array();
3278
-                foreach ($ps as $i => $p) {
3279
-                    $tmp[$i] = $p[0];
3280
-                    $tmp2[$i] = $p[1];
3281
-                    $tmp3[$i] = isset($p[2]) ? $p[2] : 0;
3282
-                    unset($ps[$i]);
3283
-                }
3284
-                $paramlist[$v[0]] = array($tmp, $tmp2, $tmp3);
3285
-                unset($tmp, $tmp2, $i, $p);
3286
-                break;
3287
-            } elseif (isset($ps[$v[0]])) {
3288
-                // parameter is defined as named param
3289
-                $paramlist[$v[0]] = $ps[$v[0]];
3290
-                unset($ps[$v[0]]);
3291
-            } elseif (isset($ps[$k])) {
3292
-                // parameter is defined as ordered param
3293
-                $paramlist[$v[0]] = $ps[$k];
3294
-                unset($ps[$k]);
3295
-            } elseif ($v[1] === false) {
3296
-                // parameter is not defined and not optional, throw error
3297
-                if (is_array($callback)) {
3298
-                    if (is_object($callback[0])) {
3299
-                        $name = get_class($callback[0]).'::'.$callback[1];
3300
-                    } else {
3301
-                        $name = $callback[0];
3302
-                    }
3303
-                } else {
3304
-                    $name = $callback;
3305
-                }
3306
-
3307
-                throw new Dwoo_Compilation_Exception($this, 'Argument '.$k.'/'.$v[0].' missing for '.str_replace(array('Dwoo_Plugin_', '_compile'), '', $name));
3308
-            } elseif ($v[2] === null) {
3309
-                // enforce lowercased null if default value is null (php outputs NULL with var export)
3310
-                $paramlist[$v[0]] = array('null', null, self::T_NULL);
3311
-            } else {
3312
-                // outputs default value with var_export
3313
-                $paramlist[$v[0]] = array(var_export($v[2], true), $v[2]);
3314
-            }
3315
-        }
3316
-
3317
-        if (count($ps)) {
3318
-            foreach ($ps as $i => $p) {
3319
-                array_push($paramlist, $p);
3320
-            }
3321
-        }
3322
-
3323
-        return $paramlist;
3324
-    }
3325
-
3326
-    /**
3327
-     * returns the parameter map of the given callback, it filters out entries typed as Dwoo and Dwoo_Compiler and turns the rest parameter into a "*".
3328
-     *
3329
-     * @param callback $callback the function/method to reflect on
3330
-     *
3331
-     * @return array processed parameter map
3332
-     */
3333
-    protected function getParamMap($callback)
3334
-    {
3335
-        if (is_null($callback)) {
3336
-            return array(array('*', true));
3337
-        }
3338
-        if (is_array($callback)) {
3339
-            $ref = new ReflectionMethod($callback[0], $callback[1]);
3340
-        } else {
3341
-            $ref = new ReflectionFunction($callback);
3342
-        }
3343
-
3344
-        $out = array();
3345
-        foreach ($ref->getParameters() as $param) {
3346
-            if (($class = $param->getClass()) !== null && ($class->name === 'Dwoo' || $class->name === 'Dwoo_Core')) {
3347
-                continue;
3348
-            }
3349
-            if (($class = $param->getClass()) !== null && $class->name === 'Dwoo_Compiler') {
3350
-                continue;
3351
-            }
3352
-            if ($param->getName() === 'rest' && $param->isArray() === true) {
3353
-                $out[] = array('*', $param->isOptional(), null);
3354
-                continue;
3355
-            }
3356
-            $out[] = array($param->getName(), $param->isOptional(), $param->isOptional() ? $param->getDefaultValue() : null);
3357
-        }
3358
-
3359
-        return $out;
3360
-    }
3361
-
3362
-    /**
3363
-     * returns a default instance of this compiler, used by default by all Dwoo templates that do not have a
3364
-     * specific compiler assigned and when you do not override the default compiler factory function.
3365
-     *
3366
-     * @see Dwoo_Core::setDefaultCompilerFactory()
3367
-     *
3368
-     * @return Dwoo_Compiler
3369
-     */
3370
-    public static function compilerFactory()
3371
-    {
3372
-        if (self::$instance === null) {
3373
-            new self();
3374
-        }
3375
-
3376
-        return self::$instance;
3377
-    }
22
+	/**
23
+	 * constant that represents a php opening tag.
24
+	 *
25
+	 * use it in case it needs to be adjusted
26
+	 *
27
+	 * @var string
28
+	 */
29
+	const PHP_OPEN = '<?php ';
30
+
31
+	/**
32
+	 * constant that represents a php closing tag.
33
+	 *
34
+	 * use it in case it needs to be adjusted
35
+	 *
36
+	 * @var string
37
+	 */
38
+	const PHP_CLOSE = '?>';
39
+
40
+	/**
41
+	 * boolean flag to enable or disable debugging output.
42
+	 *
43
+	 * @var bool
44
+	 */
45
+	public $debug = false;
46
+
47
+	/**
48
+	 * left script delimiter.
49
+	 *
50
+	 * @var string
51
+	 */
52
+	protected $ld = '{';
53
+
54
+	/**
55
+	 * left script delimiter with escaped regex meta characters.
56
+	 *
57
+	 * @var string
58
+	 */
59
+	protected $ldr = '\\{';
60
+
61
+	/**
62
+	 * right script delimiter.
63
+	 *
64
+	 * @var string
65
+	 */
66
+	protected $rd = '}';
67
+
68
+	/**
69
+	 * right script delimiter with escaped regex meta characters.
70
+	 *
71
+	 * @var string
72
+	 */
73
+	protected $rdr = '\\}';
74
+
75
+	/**
76
+	 * defines whether the nested comments should be parsed as nested or not.
77
+	 *
78
+	 * defaults to false (classic block comment parsing as in all languages)
79
+	 *
80
+	 * @var bool
81
+	 */
82
+	protected $allowNestedComments = false;
83
+
84
+	/**
85
+	 * defines whether opening and closing tags can contain spaces before valid data or not.
86
+	 *
87
+	 * turn to true if you want to be sloppy with the syntax, but when set to false it allows
88
+	 * to skip javascript and css tags as long as they are in the form "{ something", which is
89
+	 * nice. default is false.
90
+	 *
91
+	 * @var bool
92
+	 */
93
+	protected $allowLooseOpenings = false;
94
+
95
+	/**
96
+	 * defines whether the compiler will automatically html-escape variables or not.
97
+	 *
98
+	 * default is false
99
+	 *
100
+	 * @var bool
101
+	 */
102
+	protected $autoEscape = false;
103
+
104
+	/**
105
+	 * security policy object.
106
+	 *
107
+	 * @var Dwoo_Security_Policy
108
+	 */
109
+	protected $securityPolicy;
110
+
111
+	/**
112
+	 * stores the custom plugins registered with this compiler.
113
+	 *
114
+	 * @var array
115
+	 */
116
+	protected $customPlugins = array();
117
+
118
+	/**
119
+	 * stores the template plugins registered with this compiler.
120
+	 *
121
+	 * @var array
122
+	 */
123
+	protected $templatePlugins = array();
124
+
125
+	/**
126
+	 * stores the pre- and post-processors callbacks.
127
+	 *
128
+	 * @var array
129
+	 */
130
+	protected $processors = array('pre' => array(), 'post' => array());
131
+
132
+	/**
133
+	 * stores a list of plugins that are used in the currently compiled
134
+	 * template, and that are not compilable. these plugins will be loaded
135
+	 * during the template's runtime if required.
136
+	 *
137
+	 * it is a 1D array formatted as key:pluginName value:pluginType
138
+	 *
139
+	 * @var array
140
+	 */
141
+	protected $usedPlugins;
142
+
143
+	/**
144
+	 * stores the template undergoing compilation.
145
+	 *
146
+	 * @var string
147
+	 */
148
+	protected $template;
149
+
150
+	/**
151
+	 * stores the current pointer position inside the template.
152
+	 *
153
+	 * @var int
154
+	 */
155
+	protected $pointer;
156
+
157
+	/**
158
+	 * stores the current line count inside the template for debugging purposes.
159
+	 *
160
+	 * @var int
161
+	 */
162
+	protected $line;
163
+
164
+	/**
165
+	 * stores the current template source while compiling it.
166
+	 *
167
+	 * @var string
168
+	 */
169
+	protected $templateSource;
170
+
171
+	/**
172
+	 * stores the data within which the scope moves.
173
+	 *
174
+	 * @var array
175
+	 */
176
+	protected $data;
177
+
178
+	/**
179
+	 * variable scope of the compiler, set to null if
180
+	 * it can not be resolved to a static string (i.e. if some
181
+	 * plugin defines a new scope based on a variable array key).
182
+	 *
183
+	 * @var mixed
184
+	 */
185
+	protected $scope;
186
+
187
+	/**
188
+	 * variable scope tree, that allows to rebuild the current
189
+	 * scope if required, i.e. when going to a parent level.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $scopeTree;
194
+
195
+	/**
196
+	 * block plugins stack, accessible through some methods.
197
+	 *
198
+	 * @see findBlock
199
+	 * @see getCurrentBlock
200
+	 * @see addBlock
201
+	 * @see addCustomBlock
202
+	 * @see injectBlock
203
+	 * @see removeBlock
204
+	 * @see removeTopBlock
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $stack = array();
209
+
210
+	/**
211
+	 * current block at the top of the block plugins stack,
212
+	 * accessible through getCurrentBlock.
213
+	 *
214
+	 * @see getCurrentBlock
215
+	 *
216
+	 * @var Dwoo_Block_Plugin
217
+	 */
218
+	protected $curBlock;
219
+
220
+	/**
221
+	 * current dwoo object that uses this compiler, or null.
222
+	 *
223
+	 * @var Dwoo
224
+	 */
225
+	protected $dwoo;
226
+
227
+	/**
228
+	 * holds an instance of this class, used by getInstance when you don't
229
+	 * provide a custom compiler in order to save resources.
230
+	 *
231
+	 * @var Dwoo_Compiler
232
+	 */
233
+	protected static $instance;
234
+
235
+	/**
236
+	 * token types.
237
+	 *
238
+	 * @var int
239
+	 */
240
+	const T_UNQUOTED_STRING = 1;
241
+	const T_NUMERIC = 2;
242
+	const T_NULL = 4;
243
+	const T_BOOL = 8;
244
+	const T_MATH = 16;
245
+	const T_BREAKCHAR = 32;
246
+
247
+	/**
248
+	 * constructor.
249
+	 *
250
+	 * saves the created instance so that child templates get the same one
251
+	 */
252
+	public function __construct()
253
+	{
254
+		self::$instance = $this;
255
+	}
256
+
257
+	/**
258
+	 * sets the delimiters to use in the templates.
259
+	 *
260
+	 * delimiters can be multi-character strings but should not be one of those as they will
261
+	 * make it very hard to work with templates or might even break the compiler entirely : "\", "$", "|", ":" and finally "#" only if you intend to use config-vars with the #var# syntax.
262
+	 *
263
+	 * @param string $left  left delimiter
264
+	 * @param string $right right delimiter
265
+	 */
266
+	public function setDelimiters($left, $right)
267
+	{
268
+		$this->ld = $left;
269
+		$this->rd = $right;
270
+		$this->ldr = preg_quote($left, '/');
271
+		$this->rdr = preg_quote($right, '/');
272
+	}
273
+
274
+	/**
275
+	 * returns the left and right template delimiters.
276
+	 *
277
+	 * @return array containing the left and the right delimiters
278
+	 */
279
+	public function getDelimiters()
280
+	{
281
+		return array($this->ld, $this->rd);
282
+	}
283
+
284
+	/**
285
+	 * sets the way to handle nested comments, if set to true
286
+	 * {* foo {* some other *} comment *} will be stripped correctly.
287
+	 *
288
+	 * if false it will remove {* foo {* some other *} and leave "comment *}" alone,
289
+	 * this is the default behavior
290
+	 *
291
+	 * @param bool $allow allow nested comments or not, defaults to true (but the default internal value is false)
292
+	 */
293
+	public function setNestedCommentsHandling($allow = true)
294
+	{
295
+		$this->allowNestedComments = (bool) $allow;
296
+	}
297
+
298
+	/**
299
+	 * returns the nested comments handling setting.
300
+	 *
301
+	 * @see setNestedCommentsHandling
302
+	 *
303
+	 * @return bool true if nested comments are allowed
304
+	 */
305
+	public function getNestedCommentsHandling()
306
+	{
307
+		return $this->allowNestedComments;
308
+	}
309
+
310
+	/**
311
+	 * sets the tag openings handling strictness, if set to true, template tags can
312
+	 * contain spaces before the first function/string/variable such as { $foo} is valid.
313
+	 *
314
+	 * if set to false (default setting), { $foo} is invalid but that is however a good thing
315
+	 * as it allows css (i.e. #foo { color:red; }) to be parsed silently without triggering
316
+	 * an error, same goes for javascript.
317
+	 *
318
+	 * @param bool $allow true to allow loose handling, false to restore default setting
319
+	 */
320
+	public function setLooseOpeningHandling($allow = false)
321
+	{
322
+		$this->allowLooseOpenings = (bool) $allow;
323
+	}
324
+
325
+	/**
326
+	 * returns the tag openings handling strictness setting.
327
+	 *
328
+	 * @see setLooseOpeningHandling
329
+	 *
330
+	 * @return bool true if loose tags are allowed
331
+	 */
332
+	public function getLooseOpeningHandling()
333
+	{
334
+		return $this->allowLooseOpenings;
335
+	}
336
+
337
+	/**
338
+	 * changes the auto escape setting.
339
+	 *
340
+	 * if enabled, the compiler will automatically html-escape variables,
341
+	 * unless they are passed through the safe function such as {$var|safe}
342
+	 * or {safe $var}
343
+	 *
344
+	 * default setting is disabled/false
345
+	 *
346
+	 * @param bool $enabled set to true to enable, false to disable
347
+	 */
348
+	public function setAutoEscape($enabled)
349
+	{
350
+		$this->autoEscape = (bool) $enabled;
351
+	}
352
+
353
+	/**
354
+	 * returns the auto escape setting.
355
+	 *
356
+	 * default setting is disabled/false
357
+	 *
358
+	 * @return bool
359
+	 */
360
+	public function getAutoEscape()
361
+	{
362
+		return $this->autoEscape;
363
+	}
364
+
365
+	/**
366
+	 * adds a preprocessor to the compiler, it will be called
367
+	 * before the template is compiled.
368
+	 *
369
+	 * @param mixed $callback either a valid callback to the preprocessor or a simple name if the autoload is set to true
370
+	 * @param bool  $autoload if set to true, the preprocessor is auto-loaded from one of the plugin directories, else you must provide a valid callback
371
+	 */
372
+	public function addPreProcessor($callback, $autoload = false)
373
+	{
374
+		if ($autoload) {
375
+			$name = str_replace('Dwoo_Processor_', '', $callback);
376
+			$class = 'Dwoo_Processor_'.$name;
377
+
378
+			if (class_exists($class)) {
379
+				$callback = array(new $class($this), 'process');
380
+			} elseif (function_exists($class)) {
381
+				$callback = $class;
382
+			} else {
383
+				$callback = array('autoload' => true, 'class' => $class, 'name' => $name);
384
+			}
385
+
386
+			$this->processors['pre'][] = $callback;
387
+		} else {
388
+			$this->processors['pre'][] = $callback;
389
+		}
390
+	}
391
+
392
+	/**
393
+	 * removes a preprocessor from the compiler.
394
+	 *
395
+	 * @param mixed $callback either a valid callback to the preprocessor or a simple name if it was autoloaded
396
+	 */
397
+	public function removePreProcessor($callback)
398
+	{
399
+		if (($index = array_search($callback, $this->processors['pre'], true)) !== false) {
400
+			unset($this->processors['pre'][$index]);
401
+		} elseif (($index = array_search('Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback), $this->processors['pre'], true)) !== false) {
402
+			unset($this->processors['pre'][$index]);
403
+		} else {
404
+			$class = 'Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback);
405
+			foreach ($this->processors['pre'] as $index => $proc) {
406
+				if (is_array($proc) && ($proc[0] instanceof $class) || (isset($proc['class']) && $proc['class'] == $class)) {
407
+					unset($this->processors['pre'][$index]);
408
+					break;
409
+				}
410
+			}
411
+		}
412
+	}
413
+
414
+	/**
415
+	 * adds a postprocessor to the compiler, it will be called
416
+	 * before the template is compiled.
417
+	 *
418
+	 * @param mixed $callback either a valid callback to the postprocessor or a simple name if the autoload is set to true
419
+	 * @param bool  $autoload if set to true, the postprocessor is auto-loaded from one of the plugin directories, else you must provide a valid callback
420
+	 */
421
+	public function addPostProcessor($callback, $autoload = false)
422
+	{
423
+		if ($autoload) {
424
+			$name = str_replace('Dwoo_Processor_', '', $callback);
425
+			$class = 'Dwoo_Processor_'.$name;
426
+
427
+			if (class_exists($class)) {
428
+				$callback = array(new $class($this), 'process');
429
+			} elseif (function_exists($class)) {
430
+				$callback = $class;
431
+			} else {
432
+				$callback = array('autoload' => true, 'class' => $class, 'name' => $name);
433
+			}
434
+
435
+			$this->processors['post'][] = $callback;
436
+		} else {
437
+			$this->processors['post'][] = $callback;
438
+		}
439
+	}
440
+
441
+	/**
442
+	 * removes a postprocessor from the compiler.
443
+	 *
444
+	 * @param mixed $callback either a valid callback to the postprocessor or a simple name if it was autoloaded
445
+	 */
446
+	public function removePostProcessor($callback)
447
+	{
448
+		if (($index = array_search($callback, $this->processors['post'], true)) !== false) {
449
+			unset($this->processors['post'][$index]);
450
+		} elseif (($index = array_search('Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback), $this->processors['post'], true)) !== false) {
451
+			unset($this->processors['post'][$index]);
452
+		} else {
453
+			$class = 'Dwoo_Processor_'.str_replace('Dwoo_Processor_', '', $callback);
454
+			foreach ($this->processors['post'] as $index => $proc) {
455
+				if (is_array($proc) && ($proc[0] instanceof $class) || (isset($proc['class']) && $proc['class'] == $class)) {
456
+					unset($this->processors['post'][$index]);
457
+					break;
458
+				}
459
+			}
460
+		}
461
+	}
462
+
463
+	/**
464
+	 * internal function to autoload processors at runtime if required.
465
+	 *
466
+	 * @param string $class the class/function name
467
+	 * @param string $name  the plugin name (without Dwoo_Plugin_ prefix)
468
+	 *
469
+	 * @return array|string
470
+	 *
471
+	 * @throws Dwoo_Exception
472
+	 */
473
+	protected function loadProcessor($class, $name)
474
+	{
475
+		if (!class_exists($class) && !function_exists($class)) {
476
+			try {
477
+				$this->dwoo->getLoader()->loadPlugin($name);
478
+			} catch (Dwoo_Exception $e) {
479
+				throw new Dwoo_Exception('Processor '.$name.' could not be found in your plugin directories, please ensure it is in a file named '.$name.'.php in the plugin directory');
480
+			}
481
+		}
482
+
483
+		if (class_exists($class)) {
484
+			return array(new $class($this), 'process');
485
+		}
486
+
487
+		if (function_exists($class)) {
488
+			return $class;
489
+		}
490
+
491
+		throw new Dwoo_Exception('Wrong processor name, when using autoload the processor must be in one of your plugin dir as "name.php" containg a class or function named "Dwoo_Processor_name"');
492
+	}
493
+
494
+	/**
495
+	 * adds an used plugin, this is reserved for use by the {template} plugin.
496
+	 *
497
+	 * this is required so that plugin loading bubbles up from loaded
498
+	 * template files to the current one
499
+	 *
500
+	 * @private
501
+	 *
502
+	 * @param string $name function name
503
+	 * @param int    $type plugin type (Dwoo_Core::*_PLUGIN)
504
+	 */
505
+	public function addUsedPlugin($name, $type)
506
+	{
507
+		$this->usedPlugins[$name] = $type;
508
+	}
509
+
510
+	/**
511
+	 * returns all the plugins this template uses.
512
+	 *
513
+	 * @private
514
+	 *
515
+	 * @return array the list of used plugins in the parsed template
516
+	 */
517
+	public function getUsedPlugins()
518
+	{
519
+		return $this->usedPlugins;
520
+	}
521
+
522
+	/**
523
+	 * adds a template plugin, this is reserved for use by the {template} plugin.
524
+	 *
525
+	 * this is required because the template functions are not declared yet
526
+	 * during compilation, so we must have a way of validating their argument
527
+	 * signature without using the reflection api
528
+	 *
529
+	 * @private
530
+	 *
531
+	 * @param string $name   function name
532
+	 * @param array  $params parameter array to help validate the function call
533
+	 * @param string $uuid   unique id of the function
534
+	 * @param string $body   function php code
535
+	 */
536
+	public function addTemplatePlugin($name, array $params, $uuid, $body = null)
537
+	{
538
+		$this->templatePlugins[$name] = array('params' => $params, 'body' => $body, 'uuid' => $uuid);
539
+	}
540
+
541
+	/**
542
+	 * returns all the parsed sub-templates.
543
+	 *
544
+	 * @private
545
+	 *
546
+	 * @return array the parsed sub-templates
547
+	 */
548
+	public function getTemplatePlugins()
549
+	{
550
+		return $this->templatePlugins;
551
+	}
552
+
553
+	/**
554
+	 * marks a template plugin as being called, which means its source must be included in the compiled template.
555
+	 *
556
+	 * @param string $name function name
557
+	 */
558
+	public function useTemplatePlugin($name)
559
+	{
560
+		$this->templatePlugins[$name]['called'] = true;
561
+	}
562
+
563
+	/**
564
+	 * adds the custom plugins loaded into Dwoo to the compiler so it can load them.
565
+	 *
566
+	 * @see Dwoo_Core::addPlugin
567
+	 *
568
+	 * @param array $customPlugins an array of custom plugins
569
+	 */
570
+	public function setCustomPlugins(array $customPlugins)
571
+	{
572
+		$this->customPlugins = $customPlugins;
573
+	}
574
+
575
+	/**
576
+	 * sets the security policy object to enforce some php security settings.
577
+	 *
578
+	 * use this if untrusted persons can modify templates,
579
+	 * set it on the Dwoo object as it will be passed onto the compiler automatically
580
+	 *
581
+	 * @param Dwoo_Security_Policy $policy the security policy object
582
+	 */
583
+	public function setSecurityPolicy(Dwoo_Security_Policy $policy = null)
584
+	{
585
+		$this->securityPolicy = $policy;
586
+	}
587
+
588
+	/**
589
+	 * returns the current security policy object or null by default.
590
+	 *
591
+	 * @return Dwoo_Security_Policy|null the security policy object if any
592
+	 */
593
+	public function getSecurityPolicy()
594
+	{
595
+		return $this->securityPolicy;
596
+	}
597
+
598
+	/**
599
+	 * sets the pointer position.
600
+	 *
601
+	 * @param int  $position the new pointer position
602
+	 * @param bool $isOffset if set to true, the position acts as an offset and not an absolute position
603
+	 */
604
+	public function setPointer($position, $isOffset = false)
605
+	{
606
+		if ($isOffset) {
607
+			$this->pointer += $position;
608
+		} else {
609
+			$this->pointer = $position;
610
+		}
611
+	}
612
+
613
+	/**
614
+	 * returns the current pointer position, only available during compilation of a template.
615
+	 *
616
+	 * @return int
617
+	 */
618
+	public function getPointer()
619
+	{
620
+		return $this->pointer;
621
+	}
622
+
623
+	/**
624
+	 * sets the line number.
625
+	 *
626
+	 * @param int  $number   the new line number
627
+	 * @param bool $isOffset if set to true, the position acts as an offset and not an absolute position
628
+	 */
629
+	public function setLine($number, $isOffset = false)
630
+	{
631
+		if ($isOffset) {
632
+			$this->line += $number;
633
+		} else {
634
+			$this->line = $number;
635
+		}
636
+	}
637
+
638
+	/**
639
+	 * returns the current line number, only available during compilation of a template.
640
+	 *
641
+	 * @return int
642
+	 */
643
+	public function getLine()
644
+	{
645
+		return $this->line;
646
+	}
647
+
648
+	/**
649
+	 * returns the dwoo object that initiated this template compilation, only available during compilation of a template.
650
+	 *
651
+	 * @return Dwoo
652
+	 */
653
+	public function getDwoo()
654
+	{
655
+		return $this->dwoo;
656
+	}
657
+
658
+	/**
659
+	 * overwrites the template that is being compiled.
660
+	 *
661
+	 * @param string $newSource   the template source that must replace the current one
662
+	 * @param bool   $fromPointer if set to true, only the source from the current pointer position is replaced
663
+	 *
664
+	 * @return string the template or partial template
665
+	 */
666
+	public function setTemplateSource($newSource, $fromPointer = false)
667
+	{
668
+		if ($fromPointer === true) {
669
+			$this->templateSource = substr($this->templateSource, 0, $this->pointer).$newSource;
670
+		} else {
671
+			$this->templateSource = $newSource;
672
+		}
673
+	}
674
+
675
+	/**
676
+	 * returns the template that is being compiled.
677
+	 *
678
+	 * @param mixed $fromPointer if set to true, only the source from the current pointer
679
+	 *                           position is returned, if a number is given it overrides the current pointer
680
+	 *
681
+	 * @return string the template or partial template
682
+	 */
683
+	public function getTemplateSource($fromPointer = false)
684
+	{
685
+		if ($fromPointer === true) {
686
+			return substr($this->templateSource, $this->pointer);
687
+		} elseif (is_numeric($fromPointer)) {
688
+			return substr($this->templateSource, $fromPointer);
689
+		} else {
690
+			return $this->templateSource;
691
+		}
692
+	}
693
+
694
+	/**
695
+	 * resets the compilation pointer, effectively restarting the compilation process.
696
+	 *
697
+	 * this is useful if a plugin modifies the template source since it might need to be recompiled
698
+	 */
699
+	public function recompile()
700
+	{
701
+		$this->setPointer(0);
702
+	}
703
+
704
+	/**
705
+	 * compiles the provided string down to php code.
706
+	 *
707
+	 * @param Dwoo_Core      $dwoo
708
+	 * @param Dwoo_ITemplate $template the template to compile
709
+	 *
710
+	 * @return string a compiled php string
711
+	 *
712
+	 * @throws Dwoo_Compilation_Exception
713
+	 */
714
+	public function compile(Dwoo_Core $dwoo, Dwoo_ITemplate $template)
715
+	{
716
+		// init vars
717
+		$tpl = $template->getSource();
718
+		$ptr = 0;
719
+		$this->dwoo = $dwoo;
720
+		$this->template = $template;
721
+		$this->templateSource = &$tpl;
722
+		$this->pointer = &$ptr;
723
+
724
+		while (true) {
725
+			// if pointer is at the beginning, reset everything, that allows a plugin to externally reset the compiler if everything must be reparsed
726
+			if ($ptr === 0) {
727
+				// resets variables
728
+				$this->usedPlugins = array();
729
+				$this->data = array();
730
+				$this->scope = &$this->data;
731
+				$this->scopeTree = array();
732
+				$this->stack = array();
733
+				$this->line = 1;
734
+				$this->templatePlugins = array();
735
+				// add top level block
736
+				$compiled = $this->addBlock('topLevelBlock', array(), 0);
737
+				$this->stack[0]['buffer'] = '';
738
+
739
+				if ($this->debug) {
740
+					echo "\n";
741
+					echo 'COMPILER INIT'."\n";
742
+				}
743
+
744
+				if ($this->debug) {
745
+					echo 'PROCESSING PREPROCESSORS ('.count($this->processors['pre']).')'."\n";
746
+				}
747
+
748
+				// runs preprocessors
749
+				foreach ($this->processors['pre'] as $preProc) {
750
+					if (is_array($preProc) && isset($preProc['autoload'])) {
751
+						$preProc = $this->loadProcessor($preProc['class'], $preProc['name']);
752
+					}
753
+					if (is_array($preProc) && $preProc[0] instanceof Dwoo_Processor) {
754
+						$tpl = call_user_func($preProc, $tpl);
755
+					} else {
756
+						$tpl = call_user_func($preProc, $this, $tpl);
757
+					}
758
+				}
759
+				unset($preProc);
760
+
761
+				// show template source if debug
762
+				if ($this->debug) {
763
+					echo '<pre>'.print_r(htmlentities($tpl), true).'</pre>'."\n";
764
+				}
765
+
766
+				// strips php tags if required by the security policy
767
+				if ($this->securityPolicy !== null) {
768
+					$search = array('{<\?php.*?\?>}');
769
+					if (ini_get('short_open_tags')) {
770
+						$search = array('{<\?.*?\?>}', '{<%.*?%>}');
771
+					}
772
+					switch ($this->securityPolicy->getPhpHandling()) {
773
+
774
+					case Dwoo_Security_Policy::PHP_ALLOW:
775
+						break;
776
+					case Dwoo_Security_Policy::PHP_ENCODE:
777
+						$tpl = preg_replace_callback($search, array($this, 'phpTagEncodingHelper'), $tpl);
778
+						break;
779
+					case Dwoo_Security_Policy::PHP_REMOVE:
780
+						$tpl = preg_replace($search, '', $tpl);
781
+
782
+					}
783
+				}
784
+			}
785
+
786
+			$pos = strpos($tpl, $this->ld, $ptr);
787
+
788
+			if ($pos === false) {
789
+				$this->push(substr($tpl, $ptr), 0);
790
+				break;
791
+			} elseif (substr($tpl, $pos - 1, 1) === '\\' && substr($tpl, $pos - 2, 1) !== '\\') {
792
+				$this->push(substr($tpl, $ptr, $pos - $ptr - 1).$this->ld);
793
+				$ptr = $pos + strlen($this->ld);
794
+			} elseif (preg_match('/^'.$this->ldr.($this->allowLooseOpenings ? '\s*' : '').'literal'.($this->allowLooseOpenings ? '\s*' : '').$this->rdr.'/s', substr($tpl, $pos), $litOpen)) {
795
+				if (!preg_match('/'.$this->ldr.($this->allowLooseOpenings ? '\s*' : '').'\/literal'.($this->allowLooseOpenings ? '\s*' : '').$this->rdr.'/s', $tpl, $litClose, PREG_OFFSET_CAPTURE, $pos)) {
796
+					throw new Dwoo_Compilation_Exception($this, 'The {literal} blocks must be closed explicitly with {/literal}');
797
+				}
798
+				$endpos = $litClose[0][1];
799
+				$this->push(substr($tpl, $ptr, $pos - $ptr).substr($tpl, $pos + strlen($litOpen[0]), $endpos - $pos - strlen($litOpen[0])));
800
+				$ptr = $endpos + strlen($litClose[0][0]);
801
+			} else {
802
+				if (substr($tpl, $pos - 2, 1) === '\\' && substr($tpl, $pos - 1, 1) === '\\') {
803
+					$this->push(substr($tpl, $ptr, $pos - $ptr - 1));
804
+					$ptr = $pos;
805
+				}
806
+
807
+				$this->push(substr($tpl, $ptr, $pos - $ptr));
808
+				$ptr = $pos;
809
+
810
+				$pos += strlen($this->ld);
811
+				if ($this->allowLooseOpenings) {
812
+					while (substr($tpl, $pos, 1) === ' ') {
813
+						$pos += 1;
814
+					}
815
+				} else {
816
+					if (substr($tpl, $pos, 1) === ' ' || substr($tpl, $pos, 1) === "\r" || substr($tpl, $pos, 1) === "\n" || substr($tpl, $pos, 1) === "\t") {
817
+						$ptr = $pos;
818
+						$this->push($this->ld);
819
+						continue;
820
+					}
821
+				}
822
+
823
+				// check that there is an end tag present
824
+				if (strpos($tpl, $this->rd, $pos) === false) {
825
+					throw new Dwoo_Compilation_Exception($this, 'A template tag was not closed, started with "'.substr($tpl, $ptr, 30).'"');
826
+				}
827
+
828
+				$ptr += strlen($this->ld);
829
+				$subptr = $ptr;
830
+
831
+				while (true) {
832
+					$parsed = $this->parse($tpl, $subptr, null, false, 'root', $subptr);
833
+
834
+					// reload loop if the compiler was reset
835
+					if ($ptr === 0) {
836
+						continue 2;
837
+					}
838
+
839
+					$len = $subptr - $ptr;
840
+					$this->push($parsed, substr_count(substr($tpl, $ptr, $len), "\n"));
841
+					$ptr += $len;
842
+
843
+					if ($parsed === false) {
844
+						break;
845
+					}
846
+				}
847
+			}
848
+		}
849
+
850
+		$compiled .= $this->removeBlock('topLevelBlock');
851
+
852
+		if ($this->debug) {
853
+			echo 'PROCESSING POSTPROCESSORS'."\n";
854
+		}
855
+
856
+		foreach ($this->processors['post'] as $postProc) {
857
+			if (is_array($postProc) && isset($postProc['autoload'])) {
858
+				$postProc = $this->loadProcessor($postProc['class'], $postProc['name']);
859
+			}
860
+			if (is_array($postProc) && $postProc[0] instanceof Dwoo_Processor) {
861
+				$compiled = call_user_func($postProc, $compiled);
862
+			} else {
863
+				$compiled = call_user_func($postProc, $this, $compiled);
864
+			}
865
+		}
866
+		unset($postProc);
867
+
868
+		if ($this->debug) {
869
+			echo 'COMPILATION COMPLETE : MEM USAGE : '.memory_get_usage()."\n";
870
+		}
871
+
872
+		$output = "<?php\n/* template head */\n";
873
+
874
+		// build plugin preloader
875
+		foreach ($this->usedPlugins as $plugin => $type) {
876
+			if ($type & Dwoo_Core::CUSTOM_PLUGIN) {
877
+				continue;
878
+			}
879
+
880
+			switch ($type) {
881
+
882
+			case Dwoo_Core::BLOCK_PLUGIN:
883
+			case Dwoo_Core::CLASS_PLUGIN:
884
+				$output .= "if (class_exists('Dwoo_Plugin_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
885
+				break;
886
+			case Dwoo_Core::FUNC_PLUGIN:
887
+				$output .= "if (function_exists('Dwoo_Plugin_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
888
+				break;
889
+			case Dwoo_Core::SMARTY_MODIFIER:
890
+				$output .= "if (function_exists('smarty_modifier_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
891
+				break;
892
+			case Dwoo_Core::SMARTY_FUNCTION:
893
+				$output .= "if (function_exists('smarty_function_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
894
+				break;
895
+			case Dwoo_Core::SMARTY_BLOCK:
896
+				$output .= "if (function_exists('smarty_block_$plugin')===false)\n\t\$this->getLoader()->loadPlugin('$plugin');\n";
897
+				break;
898
+			case Dwoo_Core::PROXY_PLUGIN:
899
+				$output .= $this->getDwoo()->getPluginProxy()->getPreloader($plugin);
900
+				break;
901
+			default:
902
+				throw new Dwoo_Compilation_Exception($this, 'Type error for '.$plugin.' with type'.$type);
903
+
904
+			}
905
+		}
906
+
907
+		foreach ($this->templatePlugins as $function => $attr) {
908
+			if (isset($attr['called']) && $attr['called'] === true && !isset($attr['checked'])) {
909
+				$this->resolveSubTemplateDependencies($function);
910
+			}
911
+		}
912
+		foreach ($this->templatePlugins as $function) {
913
+			if (isset($function['called']) && $function['called'] === true) {
914
+				$output .= $function['body'].PHP_EOL;
915
+			}
916
+		}
917
+
918
+		$output .= $compiled."\n?>";
919
+
920
+		$output = preg_replace('/(?<!;|\}|\*\/|\n|\{)(\s*'.preg_quote(self::PHP_CLOSE, '/').preg_quote(self::PHP_OPEN, '/').')/', ";\n", $output);
921
+		$output = str_replace(self::PHP_CLOSE.self::PHP_OPEN, "\n", $output);
922
+
923
+		// handle <?xml tag at the beginning
924
+		$output = preg_replace('#(/\* template body \*/ \?>\s*)<\?xml#is', '$1<?php echo \'<?xml\'; ?>', $output);
925
+
926
+		// add another line break after PHP closing tags that have a line break following,
927
+		// as we do not know whether it's intended, and PHP will strip it otherwise
928
+		$output = preg_replace('/(?<!"|<\?xml)\s*\?>\n/', '$0'."\n", $output);
929
+
930
+		if ($this->debug) {
931
+			echo '============================================================================================='."\n";
932
+			$lines = preg_split('{\r\n|\n|<br />}', $output);
933
+			array_shift($lines);
934
+			foreach ($lines as $i => $line) {
935
+				echo($i + 1).'. '.$line."\r\n";
936
+			}
937
+			echo '============================================================================================='."\n";
938
+		}
939
+
940
+		$this->template = $this->dwoo = null;
941
+		$tpl = null;
942
+
943
+		return $output;
944
+	}
945
+
946
+	/**
947
+	 * checks what sub-templates are used in every sub-template so that we're sure they are all compiled.
948
+	 *
949
+	 * @param string $function the sub-template name
950
+	 */
951
+	protected function resolveSubTemplateDependencies($function)
952
+	{
953
+		if ($this->debug) {
954
+			echo 'Compiler::'.__FUNCTION__."\n";
955
+		}
956
+
957
+		$body = $this->templatePlugins[$function]['body'];
958
+		foreach ($this->templatePlugins as $func => $attr) {
959
+			if ($func !== $function && !isset($attr['called']) && strpos($body, 'Dwoo_Plugin_'.$func) !== false) {
960
+				$this->templatePlugins[$func]['called'] = true;
961
+				$this->resolveSubTemplateDependencies($func);
962
+			}
963
+		}
964
+		$this->templatePlugins[$function]['checked'] = true;
965
+	}
966
+
967
+	/**
968
+	 * adds compiled content to the current block.
969
+	 *
970
+	 * @param string $content   the content to push
971
+	 * @param int    $lineCount newlines count in content, optional
972
+	 *
973
+	 * @throws Dwoo_Compilation_Exception
974
+	 */
975
+	public function push($content, $lineCount = null)
976
+	{
977
+		if ($lineCount === null) {
978
+			$lineCount = substr_count($content, "\n");
979
+		}
980
+
981
+		if ($this->curBlock['buffer'] === null && count($this->stack) > 1) {
982
+			// buffer is not initialized yet (the block has just been created)
983
+			$this->stack[count($this->stack) - 2]['buffer'] .= (string) $content;
984
+			$this->curBlock['buffer'] = '';
985
+		} else {
986
+			if (!isset($this->curBlock['buffer'])) {
987
+				throw new Dwoo_Compilation_Exception($this, 'The template has been closed too early, you probably have an extra block-closing tag somewhere');
988
+			}
989
+			// append current content to current block's buffer
990
+			$this->curBlock['buffer'] .= (string) $content;
991
+		}
992
+		$this->line += $lineCount;
993
+	}
994
+
995
+	/**
996
+	 * sets the scope.
997
+	 *
998
+	 * set to null if the scope becomes "unstable" (i.e. too variable or unknown) so that
999
+	 * variables are compiled in a more evaluative way than just $this->scope['key']
1000
+	 *
1001
+	 * @param mixed $scope    a string i.e. "level1.level2" or an array i.e. array("level1", "level2")
1002
+	 * @param bool  $absolute if true, the scope is set from the top level scope and not from the current scope
1003
+	 *
1004
+	 * @return array the current scope tree
1005
+	 */
1006
+	public function setScope($scope, $absolute = false)
1007
+	{
1008
+		$old = $this->scopeTree;
1009
+
1010
+		if ($scope === null) {
1011
+			unset($this->scope);
1012
+			$this->scope = null;
1013
+		}
1014
+
1015
+		if (is_array($scope) === false) {
1016
+			$scope = explode('.', $scope);
1017
+		}
1018
+
1019
+		if ($absolute === true) {
1020
+			$this->scope = &$this->data;
1021
+			$this->scopeTree = array();
1022
+		}
1023
+
1024
+		while (($bit = array_shift($scope)) !== null) {
1025
+			if ($bit === '_parent' || $bit === '_') {
1026
+				array_pop($this->scopeTree);
1027
+				reset($this->scopeTree);
1028
+				$this->scope = &$this->data;
1029
+				$cnt = count($this->scopeTree);
1030
+				for ($i = 0; $i < $cnt; ++$i) {
1031
+					$this->scope = &$this->scope[$this->scopeTree[$i]];
1032
+				}
1033
+			} elseif ($bit === '_root' || $bit === '__') {
1034
+				$this->scope = &$this->data;
1035
+				$this->scopeTree = array();
1036
+			} elseif (isset($this->scope[$bit])) {
1037
+				$this->scope = &$this->scope[$bit];
1038
+				$this->scopeTree[] = $bit;
1039
+			} else {
1040
+				$this->scope[$bit] = array();
1041
+				$this->scope = &$this->scope[$bit];
1042
+				$this->scopeTree[] = $bit;
1043
+			}
1044
+		}
1045
+
1046
+		return $old;
1047
+	}
1048
+
1049
+	/**
1050
+	 * adds a block to the top of the block stack.
1051
+	 *
1052
+	 * @param string $type      block type (name)
1053
+	 * @param array  $params    the parameters array
1054
+	 * @param int    $paramtype the parameters type (see mapParams), 0, 1 or 2
1055
+	 *
1056
+	 * @return string the preProcessing() method's output
1057
+	 */
1058
+	public function addBlock($type, array $params, $paramtype)
1059
+	{
1060
+		if ($this->debug) {
1061
+			echo 'Compiler::'.__FUNCTION__."\n";
1062
+		}
1063
+
1064
+		$class = 'Dwoo_Plugin_'.$type;
1065
+		if (class_exists($class) === false) {
1066
+			$this->dwoo->getLoader()->loadPlugin($type);
1067
+		}
1068
+		$params = $this->mapParams($params, array($class, 'init'), $paramtype);
1069
+
1070
+		$this->stack[] = array('type' => $type, 'params' => $params, 'custom' => false, 'class' => $class, 'buffer' => null);
1071
+		$this->curBlock = &$this->stack[count($this->stack) - 1];
1072
+
1073
+		return call_user_func(array($class, 'preProcessing'), $this, $params, '', '', $type);
1074
+	}
1075
+
1076
+	/**
1077
+	 * adds a custom block to the top of the block stack.
1078
+	 *
1079
+	 * @param string $type      block type (name)
1080
+	 * @param array  $params    the parameters array
1081
+	 * @param int    $paramtype the parameters type (see mapParams), 0, 1 or 2
1082
+	 *
1083
+	 * @return string the preProcessing() method's output
1084
+	 */
1085
+	public function addCustomBlock($type, array $params, $paramtype)
1086
+	{
1087
+		$callback = $this->customPlugins[$type]['callback'];
1088
+		if (is_array($callback)) {
1089
+			$class = is_object($callback[0]) ? get_class($callback[0]) : $callback[0];
1090
+		} else {
1091
+			$class = $callback;
1092
+		}
1093
+
1094
+		$params = $this->mapParams($params, array($class, 'init'), $paramtype);
1095
+
1096
+		$this->stack[] = array('type' => $type, 'params' => $params, 'custom' => true, 'class' => $class, 'buffer' => null);
1097
+		$this->curBlock = &$this->stack[count($this->stack) - 1];
1098
+
1099
+		return call_user_func(array($class, 'preProcessing'), $this, $params, '', '', $type);
1100
+	}
1101
+
1102
+	/**
1103
+	 * injects a block at the top of the plugin stack without calling its preProcessing method.
1104
+	 *
1105
+	 * used by {else} blocks to re-add themselves after having closed everything up to their parent
1106
+	 *
1107
+	 * @param string $type   block type (name)
1108
+	 * @param array  $params parameters array
1109
+	 */
1110
+	public function injectBlock($type, array $params)
1111
+	{
1112
+		if ($this->debug) {
1113
+			echo 'Compiler::'.__FUNCTION__."\n";
1114
+		}
1115
+
1116
+		$class = 'Dwoo_Plugin_'.$type;
1117
+		if (class_exists($class) === false) {
1118
+			$this->dwoo->getLoader()->loadPlugin($type);
1119
+		}
1120
+		$this->stack[] = array('type' => $type, 'params' => $params, 'custom' => false, 'class' => $class, 'buffer' => null);
1121
+		$this->curBlock = &$this->stack[count($this->stack) - 1];
1122
+	}
1123
+
1124
+	/**
1125
+	 * removes the closest-to-top block of the given type and all other
1126
+	 * blocks encountered while going down the block stack.
1127
+	 *
1128
+	 * @param string $type block type (name)
1129
+	 *
1130
+	 * @return string the output of all postProcessing() method's return values of the closed blocks
1131
+	 *
1132
+	 * @throws Dwoo_Compilation_Exception
1133
+	 */
1134
+	public function removeBlock($type)
1135
+	{
1136
+		if ($this->debug) {
1137
+			echo 'Compiler::'.__FUNCTION__."\n";
1138
+		}
1139
+
1140
+		$output = '';
1141
+
1142
+		$pluginType = $this->getPluginType($type);
1143
+		if ($pluginType & Dwoo_Core::SMARTY_BLOCK) {
1144
+			$type = 'smartyinterface';
1145
+		}
1146
+		while (true) {
1147
+			while ($top = array_pop($this->stack)) {
1148
+				if ($top['custom']) {
1149
+					$class = $top['class'];
1150
+				} else {
1151
+					$class = 'Dwoo_Plugin_'.$top['type'];
1152
+				}
1153
+				if (count($this->stack)) {
1154
+					$this->curBlock = &$this->stack[count($this->stack) - 1];
1155
+					$this->push(call_user_func(array($class, 'postProcessing'), $this, $top['params'], '', '', $top['buffer']), 0);
1156
+				} else {
1157
+					$null = null;
1158
+					$this->curBlock = &$null;
1159
+					$output = call_user_func(array($class, 'postProcessing'), $this, $top['params'], '', '', $top['buffer']);
1160
+				}
1161
+
1162
+				if ($top['type'] === $type) {
1163
+					break 2;
1164
+				}
1165
+			}
1166
+
1167
+			throw new Dwoo_Compilation_Exception($this, 'Syntax malformation, a block of type "'.$type.'" was closed but was not opened');
1168
+			break;
1169
+		}
1170
+
1171
+		return $output;
1172
+	}
1173
+
1174
+	/**
1175
+	 * returns a reference to the first block of the given type encountered and
1176
+	 * optionally closes all blocks until it finds it
1177
+	 * this is mainly used by {else} plugins to close everything that was opened
1178
+	 * between their parent and themselves.
1179
+	 *
1180
+	 * @param string $type       the block type (name)
1181
+	 * @param bool   $closeAlong whether to close all blocks encountered while going down the block stack or not
1182
+	 *
1183
+	 * @return mixed &array the array is as such: array('type'=>pluginName, 'params'=>parameter array,
1184
+	 *               'custom'=>bool defining whether it's a custom plugin or not, for internal use)
1185
+	 *
1186
+	 * @throws Dwoo_Compilation_Exception
1187
+	 */
1188
+	public function &findBlock($type, $closeAlong = false)
1189
+	{
1190
+		if ($closeAlong === true) {
1191
+			while ($b = end($this->stack)) {
1192
+				if ($b['type'] === $type) {
1193
+					return $this->stack[key($this->stack)];
1194
+				}
1195
+				$this->push($this->removeTopBlock(), 0);
1196
+			}
1197
+		} else {
1198
+			end($this->stack);
1199
+			while ($b = current($this->stack)) {
1200
+				if ($b['type'] === $type) {
1201
+					return $this->stack[key($this->stack)];
1202
+				}
1203
+				prev($this->stack);
1204
+			}
1205
+		}
1206
+
1207
+		throw new Dwoo_Compilation_Exception($this, 'A parent block of type "'.$type.'" is required and can not be found');
1208
+	}
1209
+
1210
+	/**
1211
+	 * returns a reference to the current block array.
1212
+	 *
1213
+	 * @return &array the array is as such: array('type'=>pluginName, 'params'=>parameter array,
1214
+	 *                'custom'=>bool defining whether it's a custom plugin or not, for internal use)
1215
+	 */
1216
+	public function &getCurrentBlock()
1217
+	{
1218
+		return $this->curBlock;
1219
+	}
1220
+
1221
+	/**
1222
+	 * removes the block at the top of the stack and calls its postProcessing() method.
1223
+	 *
1224
+	 * @return string the postProcessing() method's output
1225
+	 *
1226
+	 * @throws Dwoo_Compilation_Exception
1227
+	 */
1228
+	public function removeTopBlock()
1229
+	{
1230
+		if ($this->debug) {
1231
+			echo 'Compiler::'.__FUNCTION__."\n";
1232
+		}
1233
+
1234
+		$o = array_pop($this->stack);
1235
+		if ($o === null) {
1236
+			throw new Dwoo_Compilation_Exception($this, 'Syntax malformation, a block of unknown type was closed but was not opened.');
1237
+		}
1238
+		if ($o['custom']) {
1239
+			$class = $o['class'];
1240
+		} else {
1241
+			$class = 'Dwoo_Plugin_'.$o['type'];
1242
+		}
1243
+
1244
+		$this->curBlock = &$this->stack[count($this->stack) - 1];
1245
+
1246
+		return call_user_func(array($class, 'postProcessing'), $this, $o['params'], '', '', $o['buffer']);
1247
+	}
1248
+
1249
+	/**
1250
+	 * returns the compiled parameters (for example a variable's compiled parameter will be "$this->scope['key']") out of the given parameter array.
1251
+	 *
1252
+	 * @param array $params parameter array
1253
+	 *
1254
+	 * @return array filtered parameters
1255
+	 */
1256
+	public function getCompiledParams(array $params)
1257
+	{
1258
+		foreach ($params as $k => $p) {
1259
+			if (is_array($p)) {
1260
+				$params[$k] = $p[0];
1261
+			}
1262
+		}
1263
+
1264
+		return $params;
1265
+	}
1266
+
1267
+	/**
1268
+	 * returns the real parameters (for example a variable's real parameter will be its key, etc) out of the given parameter array.
1269
+	 *
1270
+	 * @param array $params parameter array
1271
+	 *
1272
+	 * @return array filtered parameters
1273
+	 */
1274
+	public function getRealParams(array $params)
1275
+	{
1276
+		foreach ($params as $k => $p) {
1277
+			if (is_array($p)) {
1278
+				$params[$k] = $p[1];
1279
+			}
1280
+		}
1281
+
1282
+		return $params;
1283
+	}
1284
+
1285
+	/**
1286
+	 * returns the token of each parameter out of the given parameter array.
1287
+	 *
1288
+	 * @param array $params parameter array
1289
+	 *
1290
+	 * @return array tokens
1291
+	 */
1292
+	public function getParamTokens(array $params)
1293
+	{
1294
+		foreach ($params as $k => $p) {
1295
+			if (is_array($p)) {
1296
+				$params[$k] = isset($p[2]) ? $p[2] : 0;
1297
+			}
1298
+		}
1299
+
1300
+		return $params;
1301
+	}
1302
+
1303
+	/**
1304
+	 * entry point of the parser, it redirects calls to other parse* functions.
1305
+	 *
1306
+	 * @param string $in            the string within which we must parse something
1307
+	 * @param int    $from          the starting offset of the parsed area
1308
+	 * @param int    $to            the ending offset of the parsed area
1309
+	 * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
1310
+	 * @param string $curBlock      the current parser-block being processed
1311
+	 * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
1312
+	 *
1313
+	 * @return string parsed values
1314
+	 *
1315
+	 * @throws Dwoo_Compilation_Exception
1316
+	 */
1317
+	protected function parse($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
1318
+	{
1319
+		if ($this->debug) {
1320
+			echo 'Compiler::'.__FUNCTION__."\n";
1321
+		}
1322
+
1323
+		if ($to === null) {
1324
+			$to = strlen($in);
1325
+		}
1326
+		$first = substr($in, $from, 1);
1327
+
1328
+		if ($first === false) {
1329
+			throw new Dwoo_Compilation_Exception($this, 'Unexpected EOF, a template tag was not closed');
1330
+		}
1331
+
1332
+		while ($first === ' ' || $first === "\n" || $first === "\t" || $first === "\r") {
1333
+			if ($curBlock === 'root' && substr($in, $from, strlen($this->rd)) === $this->rd) {
1334
+				// end template tag
1335
+				$pointer += strlen($this->rd);
1336
+				if ($this->debug) {
1337
+					echo 'TEMPLATE PARSING ENDED'."\n";
1338
+				}
1339
+
1340
+				return false;
1341
+			}
1342
+			++$from;
1343
+			if ($pointer !== null) {
1344
+				++$pointer;
1345
+			}
1346
+			if ($from >= $to) {
1347
+				if (is_array($parsingParams)) {
1348
+					return $parsingParams;
1349
+				} else {
1350
+					return '';
1351
+				}
1352
+			}
1353
+			$first = $in[$from];
1354
+		}
1355
+
1356
+		$substr = substr($in, $from, $to - $from);
1357
+
1358
+		if ($this->debug) {
1359
+			echo 'PARSE CALL : PARSING "<b>'.htmlentities(substr($in, $from, min($to - $from, 50))).(($to - $from) > 50 ? '...' : '').'</b>" @ '.$from.':'.$to.' in '.$curBlock.' : pointer='.$pointer."\n";
1360
+		}
1361
+		$parsed = '';
1362
+
1363
+		if ($curBlock === 'root' && $first === '*') {
1364
+			$src = $this->getTemplateSource();
1365
+			$startpos = $this->getPointer() - strlen($this->ld);
1366
+			if (substr($src, $startpos, strlen($this->ld)) === $this->ld) {
1367
+				if ($startpos > 0) {
1368
+					do {
1369
+						$char = substr($src, --$startpos, 1);
1370
+						if ($char == "\n") {
1371
+							++$startpos;
1372
+							$whitespaceStart = true;
1373
+							break;
1374
+						}
1375
+					} while ($startpos > 0 && ($char == ' ' || $char == "\t"));
1376
+				}
1377
+
1378
+				if (!isset($whitespaceStart)) {
1379
+					$startpos = $this->getPointer();
1380
+				} else {
1381
+					$pointer -= $this->getPointer() - $startpos;
1382
+				}
1383
+
1384
+				if ($this->allowNestedComments && strpos($src, $this->ld.'*', $this->getPointer()) !== false) {
1385
+					$comOpen = $this->ld.'*';
1386
+					$comClose = '*'.$this->rd;
1387
+					$level = 1;
1388
+					$ptr = $this->getPointer();
1389
+
1390
+					while ($level > 0 && $ptr < strlen($src)) {
1391
+						$open = strpos($src, $comOpen, $ptr);
1392
+						$close = strpos($src, $comClose, $ptr);
1393
+
1394
+						if ($open !== false && $close !== false) {
1395
+							if ($open < $close) {
1396
+								$ptr = $open + strlen($comOpen);
1397
+								++$level;
1398
+							} else {
1399
+								$ptr = $close + strlen($comClose);
1400
+								--$level;
1401
+							}
1402
+						} elseif ($open !== false) {
1403
+							$ptr = $open + strlen($comOpen);
1404
+							++$level;
1405
+						} elseif ($close !== false) {
1406
+							$ptr = $close + strlen($comClose);
1407
+							--$level;
1408
+						} else {
1409
+							$ptr = strlen($src);
1410
+						}
1411
+					}
1412
+					$endpos = $ptr - strlen('*'.$this->rd);
1413
+				} else {
1414
+					$endpos = strpos($src, '*'.$this->rd, $startpos);
1415
+					if ($endpos == false) {
1416
+						throw new Dwoo_Compilation_Exception($this, 'Un-ended comment');
1417
+					}
1418
+				}
1419
+				$pointer += $endpos - $startpos + strlen('*'.$this->rd);
1420
+				if (isset($whitespaceStart) && preg_match('#^[\t ]*\r?\n#', substr($src, $endpos + strlen('*'.$this->rd)), $m)) {
1421
+					$pointer += strlen($m[0]);
1422
+					$this->curBlock['buffer'] = substr($this->curBlock['buffer'], 0, strlen($this->curBlock['buffer']) - ($this->getPointer() - $startpos - strlen($this->ld)));
1423
+				}
1424
+
1425
+				return false;
1426
+			}
1427
+		}
1428
+
1429
+		if ($first === '$') {
1430
+			// var
1431
+			$out = $this->parseVar($in, $from, $to, $parsingParams, $curBlock, $pointer);
1432
+			$parsed = 'var';
1433
+		} elseif ($first === '%' && preg_match('#^%[a-z_]#i', $substr)) {
1434
+			// const
1435
+			$out = $this->parseConst($in, $from, $to, $parsingParams, $curBlock, $pointer);
1436
+		} elseif (($first === '"' || $first === "'") && !(is_array($parsingParams) && preg_match('#^([\'"])[a-z0-9_]+\1\s*=>?(?:\s+|[^=])#i', $substr))) {
1437
+			// string
1438
+			$out = $this->parseString($in, $from, $to, $parsingParams, $curBlock, $pointer);
1439
+		} elseif (preg_match('/^\\\\?[a-z_](?:\\\\?[a-z0-9_]+)*(?:::[a-z_][a-z0-9_]*)?('.(is_array($parsingParams) || $curBlock != 'root' ? '' : '\s+[^(]|').'\s*\(|\s*'.$this->rdr.'|\s*;)/i', $substr)) {
1440
+			// func
1441
+			$out = $this->parseFunction($in, $from, $to, $parsingParams, $curBlock, $pointer);
1442
+			$parsed = 'func';
1443
+		} elseif ($first === ';') {
1444
+			// instruction end
1445
+			if ($this->debug) {
1446
+				echo 'END OF INSTRUCTION'."\n";
1447
+			}
1448
+			if ($pointer !== null) {
1449
+				++$pointer;
1450
+			}
1451
+
1452
+			return $this->parse($in, $from + 1, $to, false, 'root', $pointer);
1453
+		} elseif ($curBlock === 'root' && preg_match('#^/([a-z_][a-z0-9_]*)?#i', $substr, $match)) {
1454
+			// close block
1455
+			if (!empty($match[1]) && $match[1] == 'else') {
1456
+				throw new Dwoo_Compilation_Exception($this, 'Else blocks must not be closed explicitly, they are automatically closed when their parent block is closed');
1457
+			}
1458
+			if (!empty($match[1]) && $match[1] == 'elseif') {
1459
+				throw new Dwoo_Compilation_Exception($this, 'Elseif blocks must not be closed explicitly, they are automatically closed when their parent block is closed or a new else/elseif block is declared after them');
1460
+			}
1461
+			if ($pointer !== null) {
1462
+				$pointer += strlen($match[0]);
1463
+			}
1464
+			if (empty($match[1])) {
1465
+				if ($this->curBlock['type'] == 'else' || $this->curBlock['type'] == 'elseif') {
1466
+					$pointer -= strlen($match[0]);
1467
+				}
1468
+				if ($this->debug) {
1469
+					echo 'TOP BLOCK CLOSED'."\n";
1470
+				}
1471
+
1472
+				return $this->removeTopBlock();
1473
+			} else {
1474
+				if ($this->debug) {
1475
+					echo 'BLOCK OF TYPE '.$match[1].' CLOSED'."\n";
1476
+				}
1477
+
1478
+				return $this->removeBlock($match[1]);
1479
+			}
1480
+		} elseif ($curBlock === 'root' && substr($substr, 0, strlen($this->rd)) === $this->rd) {
1481
+			// end template tag
1482
+			if ($this->debug) {
1483
+				echo 'TAG PARSING ENDED'."\n";
1484
+			}
1485
+			$pointer += strlen($this->rd);
1486
+
1487
+			return false;
1488
+		} elseif (is_array($parsingParams) && preg_match('#^(([\'"]?)[a-z0-9_]+\2\s*='.($curBlock === 'array' ? '>?' : '').')(?:\s+|[^=]).*#i', $substr, $match)) {
1489
+			// named parameter
1490
+			if ($this->debug) {
1491
+				echo 'NAMED PARAM FOUND'."\n";
1492
+			}
1493
+			$len = strlen($match[1]);
1494
+			while (substr($in, $from + $len, 1) === ' ') {
1495
+				++$len;
1496
+			}
1497
+			if ($pointer !== null) {
1498
+				$pointer += $len;
1499
+			}
1500
+
1501
+			$output = array(trim($match[1], " \t\r\n=>'\""), $this->parse($in, $from + $len, $to, false, 'namedparam', $pointer));
1502
+
1503
+			$parsingParams[] = $output;
1504
+
1505
+			return $parsingParams;
1506
+		} elseif (preg_match('#^(\\\\?[a-z_](?:\\\\?[a-z0-9_]+)*::\$[a-z0-9_]+)#i', $substr, $match)) {
1507
+			// static member access
1508
+			$parsed = 'var';
1509
+			if (is_array($parsingParams)) {
1510
+				$parsingParams[] = array($match[1], $match[1]);
1511
+				$out = $parsingParams;
1512
+			} else {
1513
+				$out = $match[1];
1514
+			}
1515
+			$pointer += strlen($match[1]);
1516
+		} elseif ($substr !== '' && (is_array($parsingParams) || $curBlock === 'namedparam' || $curBlock === 'condition' || $curBlock === 'expression')) {
1517
+			// unquoted string, bool or number
1518
+			$out = $this->parseOthers($in, $from, $to, $parsingParams, $curBlock, $pointer);
1519
+		} else {
1520
+			// parse error
1521
+			throw new Dwoo_Compilation_Exception($this, 'Parse error in "'.substr($in, $from, $to - $from).'"');
1522
+		}
1523
+
1524
+		if (empty($out)) {
1525
+			return '';
1526
+		}
1527
+
1528
+		$substr = substr($in, $pointer, $to - $pointer);
1529
+
1530
+		// var parsed, check if any var-extension applies
1531
+		if ($parsed === 'var') {
1532
+			if (preg_match('#^\s*([/%+*-])\s*([a-z0-9]|\$)#i', $substr, $match)) {
1533
+				if ($this->debug) {
1534
+					echo 'PARSING POST-VAR EXPRESSION '.$substr."\n";
1535
+				}
1536
+				// parse expressions
1537
+				$pointer += strlen($match[0]) - 1;
1538
+				if (is_array($parsingParams)) {
1539
+					if ($match[2] == '$') {
1540
+						$expr = $this->parseVar($in, $pointer, $to, array(), $curBlock, $pointer);
1541
+					} else {
1542
+						$expr = $this->parse($in, $pointer, $to, array(), 'expression', $pointer);
1543
+					}
1544
+					$out[count($out) - 1][0] .= $match[1].$expr[0][0];
1545
+					$out[count($out) - 1][1] .= $match[1].$expr[0][1];
1546
+				} else {
1547
+					if ($match[2] == '$') {
1548
+						$expr = $this->parseVar($in, $pointer, $to, false, $curBlock, $pointer);
1549
+					} else {
1550
+						$expr = $this->parse($in, $pointer, $to, false, 'expression', $pointer);
1551
+					}
1552
+					if (is_array($out) && is_array($expr)) {
1553
+						$out[0] .= $match[1].$expr[0];
1554
+						$out[1] .= $match[1].$expr[1];
1555
+					} elseif (is_array($out)) {
1556
+						$out[0] .= $match[1].$expr;
1557
+						$out[1] .= $match[1].$expr;
1558
+					} elseif (is_array($expr)) {
1559
+						$out .= $match[1].$expr[0];
1560
+					} else {
1561
+						$out .= $match[1].$expr;
1562
+					}
1563
+				}
1564
+			} elseif ($curBlock === 'root' && preg_match('#^(\s*(?:[+/*%-.]=|=|\+\+|--)\s*)(.*)#s', $substr, $match)) {
1565
+				if ($this->debug) {
1566
+					echo 'PARSING POST-VAR ASSIGNMENT '.$substr."\n";
1567
+				}
1568
+				// parse assignment
1569
+				$value = $match[2];
1570
+				$operator = trim($match[1]);
1571
+				if (substr($value, 0, 1) == '=') {
1572
+					throw new Dwoo_Compilation_Exception($this, 'Unexpected "=" in <em>'.$substr.'</em>');
1573
+				}
1574
+
1575
+				if ($pointer !== null) {
1576
+					$pointer += strlen($match[1]);
1577
+				}
1578
+
1579
+				if ($operator !== '++' && $operator !== '--') {
1580
+					$parts = array();
1581
+					$ptr = 0;
1582
+					$parts = $this->parse($value, 0, strlen($value), $parts, 'condition', $ptr);
1583
+					$pointer += $ptr;
1584
+
1585
+					// load if plugin
1586
+					try {
1587
+						$this->getPluginType('if');
1588
+					} catch (Dwoo_Exception $e) {
1589
+						throw new Dwoo_Compilation_Exception($this, 'Assignments require the "if" plugin to be accessible');
1590
+					}
1591
+
1592
+					$parts = $this->mapParams($parts, array('Dwoo_Plugin_if', 'init'), 1);
1593
+					$tokens = $this->getParamTokens($parts);
1594
+					$parts = $this->getCompiledParams($parts);
1595
+
1596
+					$value = Dwoo_Plugin_if::replaceKeywords($parts['*'], $tokens['*'], $this);
1597
+					$echo = '';
1598
+				} else {
1599
+					$value = array();
1600
+					$echo = 'echo ';
1601
+				}
1602
+
1603
+				if ($this->autoEscape) {
1604
+					$out = preg_replace('#\(is_string\(\$tmp=(.+?)\) \? htmlspecialchars\(\$tmp, ENT_QUOTES, \$this->charset\) : \$tmp\)#', '$1', $out);
1605
+				}
1606
+				$out = self::PHP_OPEN.$echo.$out.$operator.implode(' ', $value).self::PHP_CLOSE;
1607
+			} elseif ($curBlock === 'array' && is_array($parsingParams) && preg_match('#^(\s*=>?\s*)#', $substr, $match)) {
1608
+				// parse namedparam with var as name (only for array)
1609
+				if ($this->debug) {
1610
+					echo 'VARIABLE NAMED PARAM (FOR ARRAY) FOUND'."\n";
1611
+				}
1612
+				$len = strlen($match[1]);
1613
+				$var = $out[count($out) - 1];
1614
+				$pointer += $len;
1615
+
1616
+				$output = array($var[0], $this->parse($substr, $len, null, false, 'namedparam', $pointer));
1617
+
1618
+				$parsingParams[] = $output;
1619
+
1620
+				return $parsingParams;
1621
+			}
1622
+		}
1623
+
1624
+		if ($curBlock !== 'modifier' && ($parsed === 'func' || $parsed === 'var') && preg_match('#^(\|@?[a-z0-9_]+(:.*)?)+#i', $substr, $match)) {
1625
+			// parse modifier on funcs or vars
1626
+			$srcPointer = $pointer;
1627
+			if (is_array($parsingParams)) {
1628
+				$tmp = $this->replaceModifiers(array(null, null, $out[count($out) - 1][0], $match[0]), $curBlock, $pointer);
1629
+				$out[count($out) - 1][0] = $tmp;
1630
+				$out[count($out) - 1][1] .= substr($substr, $srcPointer, $srcPointer - $pointer);
1631
+			} else {
1632
+				$out = $this->replaceModifiers(array(null, null, $out, $match[0]), $curBlock, $pointer);
1633
+			}
1634
+		}
1635
+
1636
+		// func parsed, check if any func-extension applies
1637
+		if ($parsed === 'func' && preg_match('#^->[a-z0-9_]+(\s*\(.+|->[a-z_].*)?#is', $substr, $match)) {
1638
+			// parse method call or property read
1639
+			$ptr = 0;
1640
+
1641
+			if (is_array($parsingParams)) {
1642
+				$output = $this->parseMethodCall($out[count($out) - 1][1], $match[0], $curBlock, $ptr);
1643
+
1644
+				$out[count($out) - 1][0] = $output;
1645
+				$out[count($out) - 1][1] .= substr($match[0], 0, $ptr);
1646
+			} else {
1647
+				$out = $this->parseMethodCall($out, $match[0], $curBlock, $ptr);
1648
+			}
1649
+
1650
+			$pointer += $ptr;
1651
+		}
1652
+
1653
+		if ($curBlock === 'root' && substr($out, 0, strlen(self::PHP_OPEN)) !== self::PHP_OPEN) {
1654
+			return self::PHP_OPEN.'echo '.$out.';'.self::PHP_CLOSE;
1655
+		} else {
1656
+			return $out;
1657
+		}
1658
+	}
1659
+
1660
+	/**
1661
+	 * parses a function call.
1662
+	 *
1663
+	 * @param string $in            the string within which we must parse something
1664
+	 * @param int    $from          the starting offset of the parsed area
1665
+	 * @param int    $to            the ending offset of the parsed area
1666
+	 * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
1667
+	 * @param string $curBlock      the current parser-block being processed
1668
+	 * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
1669
+	 *
1670
+	 * @return string parsed values
1671
+	 *
1672
+	 * @throws Dwoo_Compilation_Exception
1673
+	 * @throws Dwoo_Exception
1674
+	 * @throws Dwoo_Security_Exception
1675
+	 */
1676
+	protected function parseFunction($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
1677
+	{
1678
+		$cmdstr = substr($in, $from, $to - $from);
1679
+		preg_match('/^(\\\\?[a-z_](?:\\\\?[a-z0-9_]+)*(?:::[a-z_][a-z0-9_]*)?)(\s*'.$this->rdr.'|\s*;)?/i', $cmdstr, $match);
1680
+
1681
+		if (empty($match[1])) {
1682
+			throw new Dwoo_Compilation_Exception($this, 'Parse error, invalid function name : '.substr($cmdstr, 0, 15));
1683
+		}
1684
+
1685
+		$func = $match[1];
1686
+
1687
+		if (!empty($match[2])) {
1688
+			$cmdstr = $match[1];
1689
+		}
1690
+
1691
+		if ($this->debug) {
1692
+			echo 'FUNC FOUND ('.$func.')'."\n";
1693
+		}
1694
+
1695
+		$paramsep = '';
1696
+
1697
+		if (is_array($parsingParams) || $curBlock != 'root') {
1698
+			$paramspos = strpos($cmdstr, '(');
1699
+			$paramsep = ')';
1700
+		} elseif (preg_match_all('#^\s*[\\\\:a-z0-9_]+(\s*\(|\s+[^(])#i', $cmdstr, $match, PREG_OFFSET_CAPTURE)) {
1701
+			$paramspos = $match[1][0][1];
1702
+			$paramsep = substr($match[1][0][0], -1) === '(' ? ')' : '';
1703
+			if ($paramsep === ')') {
1704
+				$paramspos += strlen($match[1][0][0]) - 1;
1705
+				if (substr($cmdstr, 0, 2) === 'if' || substr($cmdstr, 0, 6) === 'elseif') {
1706
+					$paramsep = '';
1707
+					if (strlen($match[1][0][0]) > 1) {
1708
+						--$paramspos;
1709
+					}
1710
+				}
1711
+			}
1712
+		} else {
1713
+			$paramspos = false;
1714
+		}
1715
+
1716
+		$state = 0;
1717
+
1718
+		if ($paramspos === false) {
1719
+			$params = array();
1720
+
1721
+			if ($curBlock !== 'root') {
1722
+				return $this->parseOthers($in, $from, $to, $parsingParams, $curBlock, $pointer);
1723
+			}
1724
+		} else {
1725
+			if ($curBlock === 'condition') {
1726
+				// load if plugin
1727
+				$this->getPluginType('if');
1728
+
1729
+				if (Dwoo_Plugin_if::replaceKeywords(array($func), array(self::T_UNQUOTED_STRING), $this) !== array($func)) {
1730
+					return $this->parseOthers($in, $from, $to, $parsingParams, $curBlock, $pointer);
1731
+				}
1732
+			}
1733
+			$whitespace = strlen(substr($cmdstr, strlen($func), $paramspos - strlen($func)));
1734
+			$paramstr = substr($cmdstr, $paramspos + 1);
1735
+			if (substr($paramstr, -1, 1) === $paramsep) {
1736
+				$paramstr = substr($paramstr, 0, -1);
1737
+			}
1738
+
1739
+			if (strlen($paramstr) === 0) {
1740
+				$params = array();
1741
+				$paramstr = '';
1742
+			} else {
1743
+				$ptr = 0;
1744
+				$params = array();
1745
+				if ($func === 'empty') {
1746
+					$params = $this->parseVar($paramstr, $ptr, strlen($paramstr), $params, 'root', $ptr);
1747
+				} else {
1748
+					while ($ptr < strlen($paramstr)) {
1749
+						while (true) {
1750
+							if ($ptr >= strlen($paramstr)) {
1751
+								break 2;
1752
+							}
1753
+
1754
+							if ($func !== 'if' && $func !== 'elseif' && $paramstr[$ptr] === ')') {
1755
+								if ($this->debug) {
1756
+									echo 'PARAM PARSING ENDED, ")" FOUND, POINTER AT '.$ptr."\n";
1757
+								}
1758
+								break 2;
1759
+							} elseif ($paramstr[$ptr] === ';') {
1760
+								++$ptr;
1761
+								if ($this->debug) {
1762
+									echo 'PARAM PARSING ENDED, ";" FOUND, POINTER AT '.$ptr."\n";
1763
+								}
1764
+								break 2;
1765
+							} elseif ($func !== 'if' && $func !== 'elseif' && $paramstr[$ptr] === '/') {
1766
+								if ($this->debug) {
1767
+									echo 'PARAM PARSING ENDED, "/" FOUND, POINTER AT '.$ptr."\n";
1768
+								}
1769
+								break 2;
1770
+							} elseif (substr($paramstr, $ptr, strlen($this->rd)) === $this->rd) {
1771
+								if ($this->debug) {
1772
+									echo 'PARAM PARSING ENDED, RIGHT DELIMITER FOUND, POINTER AT '.$ptr."\n";
1773
+								}
1774
+								break 2;
1775
+							}
1776
+
1777
+							if ($paramstr[$ptr] === ' ' || $paramstr[$ptr] === ',' || $paramstr[$ptr] === "\r" || $paramstr[$ptr] === "\n" || $paramstr[$ptr] === "\t") {
1778
+								++$ptr;
1779
+							} else {
1780
+								break;
1781
+							}
1782
+						}
1783
+
1784
+						if ($this->debug) {
1785
+							echo 'FUNC START PARAM PARSING WITH POINTER AT '.$ptr."\n";
1786
+						}
1787
+
1788
+						if ($func === 'if' || $func === 'elseif' || $func === 'tif') {
1789
+							$params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'condition', $ptr);
1790
+						} elseif ($func === 'array') {
1791
+							$params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'array', $ptr);
1792
+						} else {
1793
+							$params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'function', $ptr);
1794
+						}
1795
+
1796
+						if ($this->debug) {
1797
+							echo 'PARAM PARSED, POINTER AT '.$ptr.' ('.substr($paramstr, $ptr - 1, 3).')'."\n";
1798
+						}
1799
+					}
1800
+				}
1801
+				$paramstr = substr($paramstr, 0, $ptr);
1802
+				$state = 0;
1803
+				foreach ($params as $k => $p) {
1804
+					if (is_array($p) && is_array($p[1])) {
1805
+						$state |= 2;
1806
+					} else {
1807
+						if (($state & 2) && preg_match('#^(["\'])(.+?)\1$#', $p[0], $m) && $func !== 'array') {
1808
+							$params[$k] = array($m[2], array('true', 'true'));
1809
+						} else {
1810
+							if ($state & 2 && $func !== 'array') {
1811
+								throw new Dwoo_Compilation_Exception($this, 'You can not use an unnamed parameter after a named one');
1812
+							}
1813
+							$state |= 1;
1814
+						}
1815
+					}
1816
+				}
1817
+			}
1818
+		}
1819
+
1820
+		if ($pointer !== null) {
1821
+			$pointer += (isset($paramstr) ? strlen($paramstr) : 0) + (')' === $paramsep ? 2 : ($paramspos === false ? 0 : 1)) + strlen($func) + (isset($whitespace) ? $whitespace : 0);
1822
+			if ($this->debug) {
1823
+				echo 'FUNC ADDS '.((isset($paramstr) ? strlen($paramstr) : 0) + (')' === $paramsep ? 2 : ($paramspos === false ? 0 : 1)) + strlen($func)).' TO POINTER'."\n";
1824
+			}
1825
+		}
1826
+
1827
+		if ($curBlock === 'method' || $func === 'do' || strstr($func, '::') !== false) {
1828
+			// handle static method calls with security policy
1829
+			if (strstr($func, '::') !== false && $this->securityPolicy !== null && $this->securityPolicy->isMethodAllowed(explode('::', strtolower($func))) !== true) {
1830
+				throw new Dwoo_Security_Exception('Call to a disallowed php function : '.$func);
1831
+			}
1832
+			$pluginType = Dwoo_Core::NATIVE_PLUGIN;
1833
+		} else {
1834
+			$pluginType = $this->getPluginType($func);
1835
+		}
1836
+
1837
+		// blocks
1838
+		if ($pluginType & Dwoo_Core::BLOCK_PLUGIN) {
1839
+			if ($curBlock !== 'root' || is_array($parsingParams)) {
1840
+				throw new Dwoo_Compilation_Exception($this, 'Block plugins can not be used as other plugin\'s arguments');
1841
+			}
1842
+			if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1843
+				return $this->addCustomBlock($func, $params, $state);
1844
+			} else {
1845
+				return $this->addBlock($func, $params, $state);
1846
+			}
1847
+		} elseif ($pluginType & Dwoo_Core::SMARTY_BLOCK) {
1848
+			if ($curBlock !== 'root' || is_array($parsingParams)) {
1849
+				throw new Dwoo_Compilation_Exception($this, 'Block plugins can not be used as other plugin\'s arguments');
1850
+			}
1851
+
1852
+			if ($state & 2) {
1853
+				array_unshift($params, array('__functype', array($pluginType, $pluginType)));
1854
+				array_unshift($params, array('__funcname', array($func, $func)));
1855
+			} else {
1856
+				array_unshift($params, array($pluginType, $pluginType));
1857
+				array_unshift($params, array($func, $func));
1858
+			}
1859
+
1860
+			return $this->addBlock('smartyinterface', $params, $state);
1861
+		}
1862
+
1863
+		// funcs
1864
+		if ($pluginType & Dwoo_Core::NATIVE_PLUGIN || $pluginType & Dwoo_Core::SMARTY_FUNCTION || $pluginType & Dwoo_Core::SMARTY_BLOCK) {
1865
+			$params = $this->mapParams($params, null, $state);
1866
+		} elseif ($pluginType & Dwoo_Core::CLASS_PLUGIN) {
1867
+			if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1868
+				$params = $this->mapParams($params, array($this->customPlugins[$func]['class'], $this->customPlugins[$func]['function']), $state);
1869
+			} else {
1870
+				$params = $this->mapParams($params, array('Dwoo_Plugin_'.$func, ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) ? 'compile' : 'process'), $state);
1871
+			}
1872
+		} elseif ($pluginType & Dwoo_Core::FUNC_PLUGIN) {
1873
+			if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1874
+				$params = $this->mapParams($params, $this->customPlugins[$func]['callback'], $state);
1875
+			} else {
1876
+				$params = $this->mapParams($params, 'Dwoo_Plugin_'.$func.(($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) ? '_compile' : ''), $state);
1877
+			}
1878
+		} elseif ($pluginType & Dwoo_Core::SMARTY_MODIFIER) {
1879
+			$output = 'smarty_modifier_'.$func.'('.implode(', ', $params).')';
1880
+		} elseif ($pluginType & Dwoo_Core::PROXY_PLUGIN) {
1881
+			$params = $this->mapParams($params, $this->getDwoo()->getPluginProxy()->getCallback($func), $state);
1882
+		} elseif ($pluginType & Dwoo_Core::TEMPLATE_PLUGIN) {
1883
+			// transforms the parameter array from (x=>array('paramname'=>array(values))) to (paramname=>array(values))
1884
+			$map = array();
1885
+			foreach ($this->templatePlugins[$func]['params'] as $param => $defValue) {
1886
+				if ($param == 'rest') {
1887
+					$param = '*';
1888
+				}
1889
+				$hasDefault = $defValue !== null;
1890
+				if ($defValue === 'null') {
1891
+					$defValue = null;
1892
+				} elseif ($defValue === 'false') {
1893
+					$defValue = false;
1894
+				} elseif ($defValue === 'true') {
1895
+					$defValue = true;
1896
+				} elseif (preg_match('#^([\'"]).*?\1$#', $defValue)) {
1897
+					$defValue = substr($defValue, 1, -1);
1898
+				}
1899
+				$map[] = array($param, $hasDefault, $defValue);
1900
+			}
1901
+
1902
+			$params = $this->mapParams($params, null, $state, $map);
1903
+		}
1904
+
1905
+		// only keep php-syntax-safe values for non-block plugins
1906
+		$tokens = array();
1907
+		foreach ($params as $k => $p) {
1908
+			$tokens[$k] = isset($p[2]) ? $p[2] : 0;
1909
+			$params[$k] = $p[0];
1910
+		}
1911
+		if ($pluginType & Dwoo_Core::NATIVE_PLUGIN) {
1912
+			if ($func === 'do') {
1913
+				if (isset($params['*'])) {
1914
+					$output = implode(';', $params['*']).';';
1915
+				} else {
1916
+					$output = '';
1917
+				}
1918
+
1919
+				if (is_array($parsingParams) || $curBlock !== 'root') {
1920
+					throw new Dwoo_Compilation_Exception($this, 'Do can not be used inside another function or block');
1921
+				} else {
1922
+					return self::PHP_OPEN.$output.self::PHP_CLOSE;
1923
+				}
1924
+			} else {
1925
+				if (isset($params['*'])) {
1926
+					$output = $func.'('.implode(', ', $params['*']).')';
1927
+				} else {
1928
+					$output = $func.'()';
1929
+				}
1930
+			}
1931
+		} elseif ($pluginType & Dwoo_Core::FUNC_PLUGIN) {
1932
+			if ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) {
1933
+				if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1934
+					$funcCompiler = $this->customPlugins[$func]['callback'];
1935
+				} else {
1936
+					$funcCompiler = 'Dwoo_Plugin_'.$func.'_compile';
1937
+				}
1938
+				array_unshift($params, $this);
1939
+				if ($func === 'tif') {
1940
+					$params[] = $tokens;
1941
+				}
1942
+				$output = call_user_func_array($funcCompiler, $params);
1943
+			} else {
1944
+				if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1945
+					$callback = $this->customPlugins[$func]['callback'];
1946
+					if ($callback instanceof \Closure) {
1947
+						array_unshift($params, $this->getDwoo());
1948
+						$output = call_user_func_array($callback, $params);
1949
+					} else {
1950
+						array_unshift($params, '$this');
1951
+						$params = self::implode_r($params);
1952
+						$output = 'call_user_func(\''.$callback.'\', '.$params.')';
1953
+					}
1954
+				} else {
1955
+					array_unshift($params, '$this');
1956
+					$params = self::implode_r($params);
1957
+					$output = 'Dwoo_Plugin_'.$func.'('.$params.')';
1958
+				}
1959
+			}
1960
+		} elseif ($pluginType & Dwoo_Core::CLASS_PLUGIN) {
1961
+			if ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) {
1962
+				if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1963
+					$callback = $this->customPlugins[$func]['callback'];
1964
+					if (!is_array($callback)) {
1965
+						if (!method_exists($callback, 'compile')) {
1966
+							throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "compile" method to be compilable, or you should provide a full callback to the method to use');
1967
+						}
1968
+						if (($ref = new ReflectionMethod($callback, 'compile')) && $ref->isStatic()) {
1969
+							$funcCompiler = array($callback, 'compile');
1970
+						} else {
1971
+							$funcCompiler = array(new $callback(), 'compile');
1972
+						}
1973
+					} else {
1974
+						$funcCompiler = $callback;
1975
+					}
1976
+				} else {
1977
+					$funcCompiler = array('Dwoo_Plugin_'.$func, 'compile');
1978
+					array_unshift($params, $this);
1979
+				}
1980
+				$output = call_user_func_array($funcCompiler, $params);
1981
+			} else {
1982
+				$params = self::implode_r($params);
1983
+				if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
1984
+					$callback = $this->customPlugins[$func]['callback'];
1985
+					if (!is_array($callback)) {
1986
+						if (!method_exists($callback, 'process')) {
1987
+							throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "process" method to be usable, or you should provide a full callback to the method to use');
1988
+						}
1989
+						if (($ref = new ReflectionMethod($callback, 'process')) && $ref->isStatic()) {
1990
+							$output = 'call_user_func(array(\''.$callback.'\', \'process\'), '.$params.')';
1991
+						} else {
1992
+							$output = 'call_user_func(array($this->getObjectPlugin(\''.$callback.'\'), \'process\'), '.$params.')';
1993
+						}
1994
+					} elseif (is_object($callback[0])) {
1995
+						$output = 'call_user_func(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), '.$params.')';
1996
+					} elseif (($ref = new ReflectionMethod($callback[0], $callback[1])) && $ref->isStatic()) {
1997
+						$output = 'call_user_func(array(\''.$callback[0].'\', \''.$callback[1].'\'), '.$params.')';
1998
+					} else {
1999
+						$output = 'call_user_func(array($this->getObjectPlugin(\''.$callback[0].'\'), \''.$callback[1].'\'), '.$params.')';
2000
+					}
2001
+					if (empty($params)) {
2002
+						$output = substr($output, 0, -3).')';
2003
+					}
2004
+				} else {
2005
+					$output = '$this->classCall(\''.$func.'\', array('.$params.'))';
2006
+				}
2007
+			}
2008
+		} elseif ($pluginType & Dwoo_Core::PROXY_PLUGIN) {
2009
+			$output = call_user_func(array($this->dwoo->getPluginProxy(), 'getCode'), $func, $params);
2010
+		} elseif ($pluginType & Dwoo_Core::SMARTY_FUNCTION) {
2011
+			if (isset($params['*'])) {
2012
+				$params = self::implode_r($params['*'], true);
2013
+			} else {
2014
+				$params = '';
2015
+			}
2016
+
2017
+			if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
2018
+				$callback = $this->customPlugins[$func]['callback'];
2019
+				if (is_array($callback)) {
2020
+					if (is_object($callback[0])) {
2021
+						$output = 'call_user_func_array(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array(array('.$params.'), $this))';
2022
+					} else {
2023
+						$output = 'call_user_func_array(array(\''.$callback[0].'\', \''.$callback[1].'\'), array(array('.$params.'), $this))';
2024
+					}
2025
+				} else {
2026
+					$output = $callback.'(array('.$params.'), $this)';
2027
+				}
2028
+			} else {
2029
+				$output = 'smarty_function_'.$func.'(array('.$params.'), $this)';
2030
+			}
2031
+		} elseif ($pluginType & Dwoo_Core::TEMPLATE_PLUGIN) {
2032
+			array_unshift($params, '$this');
2033
+			$params = self::implode_r($params);
2034
+			$output = 'Dwoo_Plugin_'.$func.'('.$params.')';
2035
+			$this->templatePlugins[$func]['called'] = true;
2036
+		}
2037
+
2038
+		if (is_array($parsingParams)) {
2039
+			$parsingParams[] = array($output, $output);
2040
+
2041
+			return $parsingParams;
2042
+		} elseif ($curBlock === 'namedparam') {
2043
+			return array($output, $output);
2044
+		} else {
2045
+			return $output;
2046
+		}
2047
+	}
2048
+
2049
+	/**
2050
+	 * parses a string.
2051
+	 *
2052
+	 * @param string $in            the string within which we must parse something
2053
+	 * @param int    $from          the starting offset of the parsed area
2054
+	 * @param int    $to            the ending offset of the parsed area
2055
+	 * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
2056
+	 * @param string $curBlock      the current parser-block being processed
2057
+	 * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
2058
+	 *
2059
+	 * @return string parsed values
2060
+	 *
2061
+	 * @throws Dwoo_Compilation_Exception
2062
+	 */
2063
+	protected function parseString($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
2064
+	{
2065
+		$substr = substr($in, $from, $to - $from);
2066
+		$first = $substr[0];
2067
+
2068
+		if ($this->debug) {
2069
+			echo 'STRING FOUND (in '.htmlentities(substr($in, $from, min($to - $from, 50))).(($to - $from) > 50 ? '...' : '').')'."\n";
2070
+		}
2071
+		$strend = false;
2072
+		$o = $from + 1;
2073
+		while ($strend === false) {
2074
+			$strend = strpos($in, $first, $o);
2075
+			if ($strend === false) {
2076
+				throw new Dwoo_Compilation_Exception($this, 'Unfinished string, started with '.substr($in, $from, $to - $from));
2077
+			}
2078
+			if (substr($in, $strend - 1, 1) === '\\') {
2079
+				$o = $strend + 1;
2080
+				$strend = false;
2081
+			}
2082
+		}
2083
+		if ($this->debug) {
2084
+			echo 'STRING DELIMITED: '.substr($in, $from, $strend + 1 - $from)."\n";
2085
+		}
2086
+
2087
+		$srcOutput = substr($in, $from, $strend + 1 - $from);
2088
+
2089
+		if ($pointer !== null) {
2090
+			$pointer += strlen($srcOutput);
2091
+		}
2092
+
2093
+		$output = $this->replaceStringVars($srcOutput, $first);
2094
+
2095
+		// handle modifiers
2096
+		if ($curBlock !== 'modifier' && preg_match('#^((?:\|(?:@?[a-z0-9_]+(?::.*)*))+)#i', substr($substr, $strend + 1 - $from), $match)) {
2097
+			$modstr = $match[1];
2098
+
2099
+			if ($curBlock === 'root' && substr($modstr, -1) === '}') {
2100
+				$modstr = substr($modstr, 0, -1);
2101
+			}
2102
+			$modstr = str_replace('\\'.$first, $first, $modstr);
2103
+			$ptr = 0;
2104
+			$output = $this->replaceModifiers(array(null, null, $output, $modstr), 'string', $ptr);
2105
+
2106
+			$strend += $ptr;
2107
+			if ($pointer !== null) {
2108
+				$pointer += $ptr;
2109
+			}
2110
+			$srcOutput .= substr($substr, $strend + 1 - $from, $ptr);
2111
+		}
2112
+
2113
+		if (is_array($parsingParams)) {
2114
+			$parsingParams[] = array($output, substr($srcOutput, 1, -1));
2115
+
2116
+			return $parsingParams;
2117
+		} elseif ($curBlock === 'namedparam') {
2118
+			return array($output, substr($srcOutput, 1, -1));
2119
+		} else {
2120
+			return $output;
2121
+		}
2122
+	}
2123
+
2124
+	/**
2125
+	 * parses a constant.
2126
+	 *
2127
+	 * @param string $in            the string within which we must parse something
2128
+	 * @param int    $from          the starting offset of the parsed area
2129
+	 * @param int    $to            the ending offset of the parsed area
2130
+	 * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
2131
+	 * @param string $curBlock      the current parser-block being processed
2132
+	 * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
2133
+	 *
2134
+	 * @return string parsed values
2135
+	 *
2136
+	 * @throws Dwoo_Compilation_Exception
2137
+	 */
2138
+	protected function parseConst($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
2139
+	{
2140
+		$substr = substr($in, $from, $to - $from);
2141
+
2142
+		if ($this->debug) {
2143
+			echo 'CONST FOUND : '.$substr."\n";
2144
+		}
2145
+
2146
+		if (!preg_match('#^%([\\\\a-z0-9_:]+)#i', $substr, $m)) {
2147
+			throw new Dwoo_Compilation_Exception($this, 'Invalid constant');
2148
+		}
2149
+
2150
+		if ($pointer !== null) {
2151
+			$pointer += strlen($m[0]);
2152
+		}
2153
+
2154
+		$output = $this->parseConstKey($m[1], $curBlock);
2155
+
2156
+		if (is_array($parsingParams)) {
2157
+			$parsingParams[] = array($output, $m[1]);
2158
+
2159
+			return $parsingParams;
2160
+		} elseif ($curBlock === 'namedparam') {
2161
+			return array($output, $m[1]);
2162
+		} else {
2163
+			return $output;
2164
+		}
2165
+	}
2166
+
2167
+	/**
2168
+	 * parses a constant.
2169
+	 *
2170
+	 * @param string $key      the constant to parse
2171
+	 * @param string $curBlock the current parser-block being processed
2172
+	 *
2173
+	 * @return string parsed constant
2174
+	 */
2175
+	protected function parseConstKey($key, $curBlock)
2176
+	{
2177
+		if ($this->securityPolicy !== null && $this->securityPolicy->getConstantHandling() === Dwoo_Security_Policy::CONST_DISALLOW) {
2178
+			return 'null';
2179
+		}
2180
+
2181
+		if ($curBlock !== 'root') {
2182
+			$output = '(defined("'.$key.'") ? '.$key.' : null)';
2183
+		} else {
2184
+			$output = $key;
2185
+		}
2186
+
2187
+		return $output;
2188
+	}
2189
+
2190
+	/**
2191
+	 * parses a variable.
2192
+	 *
2193
+	 * @param string $in            the string within which we must parse something
2194
+	 * @param int    $from          the starting offset of the parsed area
2195
+	 * @param int    $to            the ending offset of the parsed area
2196
+	 * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
2197
+	 * @param string $curBlock      the current parser-block being processed
2198
+	 * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
2199
+	 *
2200
+	 * @return string parsed values
2201
+	 *
2202
+	 * @throws Dwoo_Compilation_Exception
2203
+	 */
2204
+	protected function parseVar($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
2205
+	{
2206
+		$substr = substr($in, $from, $to - $from);
2207
+
2208
+		if (preg_match('#(\$?\.?[a-z0-9_:]*(?:(?:(?:\.|->)(?:[a-z0-9_:]+|(?R))|\[(?:[a-z0-9_:]+|(?R)|(["\'])[^\2]*?\2)\]))*)'. // var key
2209
+			($curBlock === 'root' || $curBlock === 'function' || $curBlock === 'namedparam' || $curBlock === 'condition' || $curBlock === 'variable' || $curBlock === 'expression' || $curBlock === 'delimited_string' ? '(\(.*)?' : '()'). // method call
2210
+			($curBlock === 'root' || $curBlock === 'function' || $curBlock === 'namedparam' || $curBlock === 'condition' || $curBlock === 'variable' || $curBlock === 'delimited_string' ? '((?:(?:[+/*%=-])(?:(?<!=)=?-?[$%][a-z0-9.[\]>_:-]+(?:\([^)]*\))?|(?<!=)=?-?[0-9.,]*|[+-]))*)' : '()'). // simple math expressions
2211
+			($curBlock !== 'modifier' ? '((?:\|(?:@?[a-z0-9_]+(?:(?::("|\').*?\5|:[^`]*))*))+)?' : '(())'). // modifiers
2212
+			'#i', $substr, $match)) {
2213
+			$key = substr($match[1], 1);
2214
+
2215
+			$matchedLength = strlen($match[0]);
2216
+			$hasModifiers = !empty($match[5]);
2217
+			$hasExpression = !empty($match[4]);
2218
+			$hasMethodCall = !empty($match[3]);
2219
+
2220
+			if (substr($key, -1) == '.') {
2221
+				$key = substr($key, 0, -1);
2222
+				--$matchedLength;
2223
+			}
2224
+
2225
+			if ($hasMethodCall) {
2226
+				$matchedLength -= strlen($match[3]) + strlen(substr($match[1], strrpos($match[1], '->')));
2227
+				$key = substr($match[1], 1, strrpos($match[1], '->') - 1);
2228
+				$methodCall = substr($match[1], strrpos($match[1], '->')).$match[3];
2229
+			}
2230
+
2231
+			if ($hasModifiers) {
2232
+				$matchedLength -= strlen($match[5]);
2233
+			}
2234
+
2235
+			if ($pointer !== null) {
2236
+				$pointer += $matchedLength;
2237
+			}
2238
+
2239
+			// replace useless brackets by dot accessed vars and strip enclosing quotes if present
2240
+			$key = preg_replace('#\[(["\']?)([^$%\[.>-]+)\1\]#', '.$2', $key);
2241
+
2242
+			if ($this->debug) {
2243
+				if ($hasMethodCall) {
2244
+					echo 'METHOD CALL FOUND : $'.$key.substr($methodCall, 0, 30)."\n";
2245
+				} else {
2246
+					echo 'VAR FOUND : $'.$key."\n";
2247
+				}
2248
+			}
2249
+
2250
+			$key = str_replace('"', '\\"', $key);
2251
+
2252
+			$cnt = substr_count($key, '$');
2253
+			if ($cnt > 0) {
2254
+				$uid = 0;
2255
+				$parsed = array($uid => '');
2256
+				$current = &$parsed;
2257
+				$curTxt = &$parsed[$uid++];
2258
+				$tree = array();
2259
+				$chars = str_split($key, 1);
2260
+				$inSplittedVar = false;
2261
+				$bracketCount = 0;
2262
+
2263
+				while (($char = array_shift($chars)) !== null) {
2264
+					if ($char === '[') {
2265
+						if (count($tree) > 0) {
2266
+							++$bracketCount;
2267
+						} else {
2268
+							$tree[] = &$current;
2269
+							$current[$uid] = array($uid + 1 => '');
2270
+							$current = &$current[$uid++];
2271
+							$curTxt = &$current[$uid++];
2272
+							continue;
2273
+						}
2274
+					} elseif ($char === ']') {
2275
+						if ($bracketCount > 0) {
2276
+							--$bracketCount;
2277
+						} else {
2278
+							$current = &$tree[count($tree) - 1];
2279
+							array_pop($tree);
2280
+							if (current($chars) !== '[' && current($chars) !== false && current($chars) !== ']') {
2281
+								$current[$uid] = '';
2282
+								$curTxt = &$current[$uid++];
2283
+							}
2284
+							continue;
2285
+						}
2286
+					} elseif ($char === '$') {
2287
+						if (count($tree) == 0) {
2288
+							$curTxt = &$current[$uid++];
2289
+							$inSplittedVar = true;
2290
+						}
2291
+					} elseif (($char === '.' || $char === '-') && count($tree) == 0 && $inSplittedVar) {
2292
+						$curTxt = &$current[$uid++];
2293
+						$inSplittedVar = false;
2294
+					}
2295
+
2296
+					$curTxt .= $char;
2297
+				}
2298
+				unset($uid, $current, $curTxt, $tree, $chars);
2299
+
2300
+				if ($this->debug) {
2301
+					echo 'RECURSIVE VAR REPLACEMENT : '.$key."\n";
2302
+				}
2303
+
2304
+				$key = $this->flattenVarTree($parsed);
2305
+
2306
+				if ($this->debug) {
2307
+					echo 'RECURSIVE VAR REPLACEMENT DONE : '.$key."\n";
2308
+				}
2309
+
2310
+				$output = preg_replace('#(^""\.|""\.|\.""$|(\()""\.|\.""(\)))#', '$2$3', '$this->readVar("'.$key.'")');
2311
+			} else {
2312
+				$output = $this->parseVarKey($key, $hasModifiers ? 'modifier' : $curBlock);
2313
+			}
2314
+
2315
+			// methods
2316
+			if ($hasMethodCall) {
2317
+				$ptr = 0;
2318
+
2319
+				$output = $this->parseMethodCall($output, $methodCall, $curBlock, $ptr);
2320
+
2321
+				if ($pointer !== null) {
2322
+					$pointer += $ptr;
2323
+				}
2324
+				$matchedLength += $ptr;
2325
+			}
2326
+
2327
+			if ($hasExpression) {
2328
+				// expressions
2329
+				preg_match_all('#(?:([+/*%=-])(=?-?[%$][a-z0-9.[\]>_:-]+(?:\([^)]*\))?|=?-?[0-9.,]+|\1))#i', $match[4], $expMatch);
2330
+
2331
+				foreach ($expMatch[1] as $k => $operator) {
2332
+					if (substr($expMatch[2][$k], 0, 1) === '=') {
2333
+						$assign = true;
2334
+						if ($operator === '=') {
2335
+							throw new Dwoo_Compilation_Exception($this, 'Invalid expression <em>'.$substr.'</em>, can not use "==" in expressions');
2336
+						}
2337
+						if ($curBlock !== 'root') {
2338
+							throw new Dwoo_Compilation_Exception($this, 'Invalid expression <em>'.$substr.'</em>, assignments can only be used in top level expressions like {$foo+=3} or {$foo="bar"}');
2339
+						}
2340
+						$operator .= '=';
2341
+						$expMatch[2][$k] = substr($expMatch[2][$k], 1);
2342
+					}
2343
+
2344
+					if (substr($expMatch[2][$k], 0, 1) === '-' && strlen($expMatch[2][$k]) > 1) {
2345
+						$operator .= '-';
2346
+						$expMatch[2][$k] = substr($expMatch[2][$k], 1);
2347
+					}
2348
+					if (($operator === '+' || $operator === '-') && $expMatch[2][$k] === $operator) {
2349
+						$output = '('.$output.$operator.$operator.')';
2350
+						break;
2351
+					} elseif (substr($expMatch[2][$k], 0, 1) === '$') {
2352
+						$output = '('.$output.' '.$operator.' '.$this->parseVar($expMatch[2][$k], 0, strlen($expMatch[2][$k]), false, 'expression').')';
2353
+					} elseif (substr($expMatch[2][$k], 0, 1) === '%') {
2354
+						$output = '('.$output.' '.$operator.' '.$this->parseConst($expMatch[2][$k], 0, strlen($expMatch[2][$k]), false, 'expression').')';
2355
+					} elseif (!empty($expMatch[2][$k])) {
2356
+						$output = '('.$output.' '.$operator.' '.str_replace(',', '.', $expMatch[2][$k]).')';
2357
+					} else {
2358
+						throw new Dwoo_Compilation_Exception($this, 'Unfinished expression <em>'.$substr.'</em>, missing var or number after math operator');
2359
+					}
2360
+				}
2361
+			}
2362
+
2363
+			if ($this->autoEscape === true && $curBlock !== 'condition') {
2364
+				$output = '(is_string($tmp='.$output.') ? htmlspecialchars($tmp, ENT_QUOTES, $this->charset) : $tmp)';
2365
+			}
2366
+
2367
+			// handle modifiers
2368
+			if ($curBlock !== 'modifier' && $hasModifiers) {
2369
+				$ptr = 0;
2370
+				$output = $this->replaceModifiers(array(null, null, $output, $match[5]), 'var', $ptr);
2371
+				if ($pointer !== null) {
2372
+					$pointer += $ptr;
2373
+				}
2374
+				$matchedLength += $ptr;
2375
+			}
2376
+
2377
+			if (is_array($parsingParams)) {
2378
+				$parsingParams[] = array($output, $key);
2379
+
2380
+				return $parsingParams;
2381
+			} elseif ($curBlock === 'namedparam') {
2382
+				return array($output, $key);
2383
+			} elseif ($curBlock === 'string' || $curBlock === 'delimited_string') {
2384
+				return array($matchedLength, $output);
2385
+			} elseif ($curBlock === 'expression' || $curBlock === 'variable') {
2386
+				return $output;
2387
+			} elseif (isset($assign)) {
2388
+				return self::PHP_OPEN.$output.';'.self::PHP_CLOSE;
2389
+			} else {
2390
+				return $output;
2391
+			}
2392
+		} else {
2393
+			if ($curBlock === 'string' || $curBlock === 'delimited_string') {
2394
+				return array(0, '');
2395
+			} else {
2396
+				throw new Dwoo_Compilation_Exception($this, 'Invalid variable name <em>'.$substr.'</em>');
2397
+			}
2398
+		}
2399
+	}
2400
+
2401
+	/**
2402
+	 * parses any number of chained method calls/property reads.
2403
+	 *
2404
+	 * @param string $output     the variable or whatever upon which the method are called
2405
+	 * @param string $methodCall method call source, starting at "->"
2406
+	 * @param string $curBlock   the current parser-block being processed
2407
+	 * @param int    $pointer    a reference to a pointer that will be increased by the amount of characters parsed
2408
+	 *
2409
+	 * @return string parsed call(s)/read(s)
2410
+	 */
2411
+	protected function parseMethodCall($output, $methodCall, $curBlock, &$pointer)
2412
+	{
2413
+		$ptr = 0;
2414
+		$len = strlen($methodCall);
2415
+
2416
+		while ($ptr < $len) {
2417
+			if (strpos($methodCall, '->', $ptr) === $ptr) {
2418
+				$ptr += 2;
2419
+			}
2420
+
2421
+			if (in_array($methodCall[$ptr], array(';', ',', '/', ' ', "\t", "\r", "\n", ')', '+', '*', '%', '=', '-', '|')) || substr($methodCall, $ptr, strlen($this->rd)) === $this->rd) {
2422
+				// break char found
2423
+				break;
2424
+			}
2425
+
2426
+			if (!preg_match('/^([a-z0-9_]+)(\(.*?\))?/i', substr($methodCall, $ptr), $methMatch)) {
2427
+				break;
2428
+			}
2429
+
2430
+			if (empty($methMatch[2])) {
2431
+				// property
2432
+				if ($curBlock === 'root') {
2433
+					$output .= '->'.$methMatch[1];
2434
+				} else {
2435
+					$output = '(($tmp = '.$output.') ? $tmp->'.$methMatch[1].' : null)';
2436
+				}
2437
+				$ptr += strlen($methMatch[1]);
2438
+			} else {
2439
+				// method
2440
+				if (substr($methMatch[2], 0, 2) === '()') {
2441
+					$parsedCall = $methMatch[1].'()';
2442
+					$ptr += strlen($methMatch[1]) + 2;
2443
+				} else {
2444
+					$parsedCall = $this->parseFunction($methodCall, $ptr, strlen($methodCall), false, 'method', $ptr);
2445
+				}
2446
+				if ($this->securityPolicy !== null) {
2447
+					$argPos = strpos($parsedCall, '(');
2448
+					$method = strtolower(substr($parsedCall, 0, $argPos));
2449
+					$args = substr($parsedCall, $argPos);
2450
+					if ($curBlock === 'root') {
2451
+						$output = '$this->getSecurityPolicy()->callMethod($this, '.$output.', '.var_export($method, true).', array'.$args.')';
2452
+					} else {
2453
+						$output = '(($tmp = '.$output.') ? $this->getSecurityPolicy()->callMethod($this, $tmp, '.var_export($method, true).', array'.$args.') : null)';
2454
+					}
2455
+				} else {
2456
+					if ($curBlock === 'root') {
2457
+						$output .= '->'.$parsedCall;
2458
+					} else {
2459
+						$output = '(($tmp = '.$output.') ? $tmp->'.$parsedCall.' : null)';
2460
+					}
2461
+				}
2462
+			}
2463
+		}
2464
+
2465
+		$pointer += $ptr;
2466
+
2467
+		return $output;
2468
+	}
2469
+
2470
+	/**
2471
+	 * parses a constant variable (a variable that doesn't contain another variable) and preprocesses it to save runtime processing time.
2472
+	 *
2473
+	 * @param string $key      the variable to parse
2474
+	 * @param string $curBlock the current parser-block being processed
2475
+	 *
2476
+	 * @return string parsed variable
2477
+	 */
2478
+	protected function parseVarKey($key, $curBlock)
2479
+	{
2480
+		if ($key === '') {
2481
+			return '$this->scope';
2482
+		}
2483
+		if (substr($key, 0, 1) === '.') {
2484
+			$key = 'dwoo'.$key;
2485
+		}
2486
+		if (preg_match('#dwoo\.(get|post|server|cookies|session|env|request)((?:\.[a-z0-9_-]+)+)#i', $key, $m)) {
2487
+			$global = strtoupper($m[1]);
2488
+			if ($global === 'COOKIES') {
2489
+				$global = 'COOKIE';
2490
+			}
2491
+			$key = '$_'.$global;
2492
+			foreach (explode('.', ltrim($m[2], '.')) as $part) {
2493
+				$key .= '['.var_export($part, true).']';
2494
+			}
2495
+			if ($curBlock === 'root') {
2496
+				$output = $key;
2497
+			} else {
2498
+				$output = '(isset('.$key.')?'.$key.':null)';
2499
+			}
2500
+		} elseif (preg_match('#dwoo\.const\.([a-z0-9_:]+)#i', $key, $m)) {
2501
+			return $this->parseConstKey($m[1], $curBlock);
2502
+		} elseif ($this->scope !== null) {
2503
+			if (strstr($key, '.') === false && strstr($key, '[') === false && strstr($key, '->') === false) {
2504
+				if ($key === 'dwoo') {
2505
+					$output = '$this->globals';
2506
+				} elseif ($key === '_root' || $key === '__') {
2507
+					$output = '$this->data';
2508
+				} elseif ($key === '_parent' || $key === '_') {
2509
+					$output = '$this->readParentVar(1)';
2510
+				} elseif ($key === '_key') {
2511
+					$output = '$tmp_key';
2512
+				} else {
2513
+					if ($curBlock === 'root') {
2514
+						$output = '$this->scope["'.$key.'"]';
2515
+					} else {
2516
+						$output = '(isset($this->scope["'.$key.'"]) ? $this->scope["'.$key.'"] : null)';
2517
+					}
2518
+				}
2519
+			} else {
2520
+				preg_match_all('#(\[|->|\.)?((?:[a-z0-9_]|-(?!>))+|(\\\?[\'"])[^\3]*?\3)\]?#i', $key, $m);
2521
+
2522
+				$i = $m[2][0];
2523
+				if ($i === '_parent' || $i === '_') {
2524
+					$parentCnt = 0;
2525
+
2526
+					while (true) {
2527
+						++$parentCnt;
2528
+						array_shift($m[2]);
2529
+						array_shift($m[1]);
2530
+						if (current($m[2]) === '_parent') {
2531
+							continue;
2532
+						}
2533
+						break;
2534
+					}
2535
+
2536
+					$output = '$this->readParentVar('.$parentCnt.')';
2537
+				} else {
2538
+					if ($i === 'dwoo') {
2539
+						$output = '$this->globals';
2540
+						array_shift($m[2]);
2541
+						array_shift($m[1]);
2542
+					} elseif ($i === '_root' || $i === '__') {
2543
+						$output = '$this->data';
2544
+						array_shift($m[2]);
2545
+						array_shift($m[1]);
2546
+					} elseif ($i === '_key') {
2547
+						$output = '$tmp_key';
2548
+					} else {
2549
+						$output = '$this->scope';
2550
+					}
2551
+
2552
+					while (count($m[1]) && $m[1][0] !== '->') {
2553
+						$m[2][0] = preg_replace('/(^\\\([\'"])|\\\([\'"])$)/x', '$2$3', $m[2][0]);
2554
+						if (substr($m[2][0], 0, 1) == '"' || substr($m[2][0], 0, 1) == "'") {
2555
+							$output .= '['.$m[2][0].']';
2556
+						} else {
2557
+							$output .= '["'.$m[2][0].'"]';
2558
+						}
2559
+						array_shift($m[2]);
2560
+						array_shift($m[1]);
2561
+					}
2562
+
2563
+					if ($curBlock !== 'root') {
2564
+						$output = '(isset('.$output.') ? '.$output.':null)';
2565
+					}
2566
+				}
2567
+
2568
+				if (count($m[2])) {
2569
+					unset($m[0]);
2570
+					$output = '$this->readVarInto('.str_replace("\n", '', var_export($m, true)).', '.$output.', '.($curBlock == 'root' ? 'false' : 'true').')';
2571
+				}
2572
+			}
2573
+		} else {
2574
+			preg_match_all('#(\[|->|\.)?((?:[a-z0-9_]|-(?!>))+)\]?#i', $key, $m);
2575
+			unset($m[0]);
2576
+			$output = '$this->readVar('.str_replace("\n", '', var_export($m, true)).')';
2577
+		}
2578
+
2579
+		return $output;
2580
+	}
2581
+
2582
+	/**
2583
+	 * flattens a variable tree, this helps in parsing very complex variables such as $var.foo[$foo.bar->baz].baz,
2584
+	 * it computes the contents of the brackets first and works out from there.
2585
+	 *
2586
+	 * @param array $tree     the variable tree parsed by he parseVar() method that must be flattened
2587
+	 * @param bool  $recursed leave that to false by default, it is only for internal use
2588
+	 *
2589
+	 * @return string flattened tree
2590
+	 */
2591
+	protected function flattenVarTree(array $tree, $recursed = false)
2592
+	{
2593
+		$out = $recursed ? '".$this->readVarInto(' : '';
2594
+		foreach ($tree as $bit) {
2595
+			if (is_array($bit)) {
2596
+				$out .= '.'.$this->flattenVarTree($bit, false);
2597
+			} else {
2598
+				$key = str_replace('"', '\\"', $bit);
2599
+
2600
+				if (substr($key, 0, 1) === '$') {
2601
+					$out .= '".'.$this->parseVar($key, 0, strlen($key), false, 'variable').'."';
2602
+				} else {
2603
+					$cnt = substr_count($key, '$');
2604
+
2605
+					if ($this->debug) {
2606
+						echo 'PARSING SUBVARS IN : '.$key."\n";
2607
+					}
2608
+					if ($cnt > 0) {
2609
+						while (--$cnt >= 0) {
2610
+							if (isset($last)) {
2611
+								$last = strrpos($key, '$', -(strlen($key) - $last + 1));
2612
+							} else {
2613
+								$last = strrpos($key, '$');
2614
+							}
2615
+							preg_match('#\$[a-z0-9_]+((?:(?:\.|->)(?:[a-z0-9_]+|(?R))|\[(?:[a-z0-9_]+|(?R))\]))*'.
2616
+									  '((?:(?:[+/*%-])(?:\$[a-z0-9.[\]>_:-]+(?:\([^)]*\))?|[0-9.,]*))*)#i', substr($key, $last), $submatch);
2617
+
2618
+							$len = strlen($submatch[0]);
2619
+							$key = substr_replace(
2620
+								$key,
2621
+								preg_replace_callback(
2622
+									'#(\$[a-z0-9_]+((?:(?:\.|->)(?:[a-z0-9_]+|(?R))|\[(?:[a-z0-9_]+|(?R))\]))*)'.
2623
+									'((?:(?:[+/*%-])(?:\$[a-z0-9.[\]>_:-]+(?:\([^)]*\))?|[0-9.,]*))*)#i',
2624
+									array($this, 'replaceVarKeyHelper'), substr($key, $last, $len)
2625
+								),
2626
+								$last,
2627
+								$len
2628
+							);
2629
+							if ($this->debug) {
2630
+								echo 'RECURSIVE VAR REPLACEMENT DONE : '.$key."\n";
2631
+							}
2632
+						}
2633
+						unset($last);
2634
+
2635
+						$out .= $key;
2636
+					} else {
2637
+						$out .= $key;
2638
+					}
2639
+				}
2640
+			}
2641
+		}
2642
+		$out .= $recursed ? ', true)."' : '';
2643
+
2644
+		return $out;
2645
+	}
2646
+
2647
+	/**
2648
+	 * helper function that parses a variable.
2649
+	 *
2650
+	 * @param array $match the matched variable, array(1=>"string match")
2651
+	 *
2652
+	 * @return string parsed variable
2653
+	 */
2654
+	protected function replaceVarKeyHelper($match)
2655
+	{
2656
+		return '".'.$this->parseVar($match[0], 0, strlen($match[0]), false, 'variable').'."';
2657
+	}
2658
+
2659
+	/**
2660
+	 * parses various constants, operators or non-quoted strings.
2661
+	 *
2662
+	 * @param string $in            the string within which we must parse something
2663
+	 * @param int    $from          the starting offset of the parsed area
2664
+	 * @param int    $to            the ending offset of the parsed area
2665
+	 * @param mixed  $parsingParams must be an array if we are parsing a function or modifier's parameters, or false by default
2666
+	 * @param string $curBlock      the current parser-block being processed
2667
+	 * @param mixed  $pointer       a reference to a pointer that will be increased by the amount of characters parsed, or null by default
2668
+	 *
2669
+	 * @return string parsed values
2670
+	 *
2671
+	 * @throws Exception
2672
+	 */
2673
+	protected function parseOthers($in, $from, $to, $parsingParams = false, $curBlock = '', &$pointer = null)
2674
+	{
2675
+		$first = $in[$from];
2676
+		$substr = substr($in, $from, $to - $from);
2677
+
2678
+		$end = strlen($substr);
2679
+
2680
+		if ($curBlock === 'condition') {
2681
+			$breakChars = array('(', ')', ' ', '||', '&&', '|', '&', '>=', '<=', '===', '==', '=', '!==', '!=', '<<', '<', '>>', '>', '^', '~', ',', '+', '-', '*', '/', '%', '!', '?', ':', $this->rd, ';');
2682
+		} elseif ($curBlock === 'modifier') {
2683
+			$breakChars = array(' ', ',', ')', ':', '|', "\r", "\n", "\t", ';', $this->rd);
2684
+		} elseif ($curBlock === 'expression') {
2685
+			$breakChars = array('/', '%', '+', '-', '*', ' ', ',', ')', "\r", "\n", "\t", ';', $this->rd);
2686
+		} else {
2687
+			$breakChars = array(' ', ',', ')', "\r", "\n", "\t", ';', $this->rd);
2688
+		}
2689
+
2690
+		$breaker = false;
2691
+		while (list($k, $char) = each($breakChars)) {
2692
+			$test = strpos($substr, $char);
2693
+			if ($test !== false && $test < $end) {
2694
+				$end = $test;
2695
+				$breaker = $k;
2696
+			}
2697
+		}
2698
+
2699
+		if ($curBlock === 'condition') {
2700
+			if ($end === 0 && $breaker !== false) {
2701
+				$end = strlen($breakChars[$breaker]);
2702
+			}
2703
+		}
2704
+
2705
+		if ($end !== false) {
2706
+			$substr = substr($substr, 0, $end);
2707
+		}
2708
+
2709
+		if ($pointer !== null) {
2710
+			$pointer += strlen($substr);
2711
+		}
2712
+
2713
+		$src = $substr;
2714
+		$substr = trim($substr);
2715
+
2716
+		if (strtolower($substr) === 'false' || strtolower($substr) === 'no' || strtolower($substr) === 'off') {
2717
+			if ($this->debug) {
2718
+				echo 'BOOLEAN(FALSE) PARSED'."\n";
2719
+			}
2720
+			$substr = 'false';
2721
+			$type = self::T_BOOL;
2722
+		} elseif (strtolower($substr) === 'true' || strtolower($substr) === 'yes' || strtolower($substr) === 'on') {
2723
+			if ($this->debug) {
2724
+				echo 'BOOLEAN(TRUE) PARSED'."\n";
2725
+			}
2726
+			$substr = 'true';
2727
+			$type = self::T_BOOL;
2728
+		} elseif ($substr === 'null' || $substr === 'NULL') {
2729
+			if ($this->debug) {
2730
+				echo 'NULL PARSED'."\n";
2731
+			}
2732
+			$substr = 'null';
2733
+			$type = self::T_NULL;
2734
+		} elseif (is_numeric($substr)) {
2735
+			$substr = (float) $substr;
2736
+			if ((int) $substr == $substr) {
2737
+				$substr = (int) $substr;
2738
+			}
2739
+			$type = self::T_NUMERIC;
2740
+			if ($this->debug) {
2741
+				echo 'NUMBER ('.$substr.') PARSED'."\n";
2742
+			}
2743
+		} elseif (preg_match('{^-?(\d+|\d*(\.\d+))\s*([/*%+-]\s*-?(\d+|\d*(\.\d+)))+$}', $substr)) {
2744
+			if ($this->debug) {
2745
+				echo 'SIMPLE MATH PARSED . "\n"';
2746
+			}
2747
+			$type = self::T_MATH;
2748
+			$substr = '('.$substr.')';
2749
+		} elseif ($curBlock === 'condition' && array_search($substr, $breakChars, true) !== false) {
2750
+			if ($this->debug) {
2751
+				echo 'BREAKCHAR ('.$substr.') PARSED'."\n";
2752
+			}
2753
+			$type = self::T_BREAKCHAR;
2754
+			//$substr = '"'.$substr.'"';
2755
+		} else {
2756
+			$substr = $this->replaceStringVars('\''.str_replace('\'', '\\\'', $substr).'\'', '\'', $curBlock);
2757
+			$type = self::T_UNQUOTED_STRING;
2758
+			if ($this->debug) {
2759
+				echo 'BLABBER ('.$substr.') CASTED AS STRING'."\n";
2760
+			}
2761
+		}
2762
+
2763
+		if (is_array($parsingParams)) {
2764
+			$parsingParams[] = array($substr, $src, $type);
2765
+
2766
+			return $parsingParams;
2767
+		} elseif ($curBlock === 'namedparam') {
2768
+			return array($substr, $src, $type);
2769
+		} elseif ($curBlock === 'expression') {
2770
+			return $substr;
2771
+		} else {
2772
+			throw new Exception('Something went wrong');
2773
+		}
2774
+	}
2775
+
2776
+	/**
2777
+	 * replaces variables within a parsed string.
2778
+	 *
2779
+	 * @param string $string   the parsed string
2780
+	 * @param string $first    the first character parsed in the string, which is the string delimiter (' or ")
2781
+	 * @param string $curBlock the current parser-block being processed
2782
+	 *
2783
+	 * @return string the original string with variables replaced
2784
+	 */
2785
+	protected function replaceStringVars($string, $first, $curBlock = '')
2786
+	{
2787
+		$pos = 0;
2788
+		if ($this->debug) {
2789
+			echo 'STRING VAR REPLACEMENT : '.$string."\n";
2790
+		}
2791
+		// replace vars
2792
+		while (($pos = strpos($string, '$', $pos)) !== false) {
2793
+			$prev = substr($string, $pos - 1, 1);
2794
+			if ($prev === '\\') {
2795
+				++$pos;
2796
+				continue;
2797
+			}
2798
+
2799
+			$var = $this->parse($string, $pos, null, false, ($curBlock === 'modifier' ? 'modifier' : ($prev === '`' ? 'delimited_string' : 'string')));
2800
+			$len = $var[0];
2801
+			$var = $this->parse(str_replace('\\'.$first, $first, $string), $pos, null, false, ($curBlock === 'modifier' ? 'modifier' : ($prev === '`' ? 'delimited_string' : 'string')));
2802
+
2803
+			if ($prev === '`' && substr($string, $pos + $len, 1) === '`') {
2804
+				$string = substr_replace($string, $first.'.'.$var[1].'.'.$first, $pos - 1, $len + 2);
2805
+			} else {
2806
+				$string = substr_replace($string, $first.'.'.$var[1].'.'.$first, $pos, $len);
2807
+			}
2808
+			$pos += strlen($var[1]) + 2;
2809
+			if ($this->debug) {
2810
+				echo 'STRING VAR REPLACEMENT DONE : '.$string."\n";
2811
+			}
2812
+		}
2813
+
2814
+		// handle modifiers
2815
+		// TODO Obsolete?
2816
+		$string = preg_replace_callback('#("|\')\.(.+?)\.\1((?:\|(?:@?[a-z0-9_]+(?:(?::("|\').+?\4|:[^`]*))*))+)#i', array($this, 'replaceModifiers'), $string);
2817
+
2818
+		// replace escaped dollar operators by unescaped ones if required
2819
+		if ($first === "'") {
2820
+			$string = str_replace('\\$', '$', $string);
2821
+		}
2822
+
2823
+		return $string;
2824
+	}
2825
+
2826
+	/**
2827
+	 * replaces the modifiers applied to a string or a variable.
2828
+	 *
2829
+	 * @param array  $m        the regex matches that must be array(1=>"double or single quotes enclosing a string, when applicable", 2=>"the string or var", 3=>"the modifiers matched")
2830
+	 * @param string $curBlock the current parser-block being processed
2831
+	 * @param null   $pointer
2832
+	 *
2833
+	 * @return string the input enclosed with various function calls according to the modifiers found
2834
+	 *
2835
+	 * @throws Dwoo_Compilation_Exception
2836
+	 * @throws Dwoo_Exception
2837
+	 */
2838
+	protected function replaceModifiers(array $m, $curBlock = null, &$pointer = null)
2839
+	{
2840
+		if ($this->debug) {
2841
+			echo 'PARSING MODIFIERS : '.$m[3]."\n";
2842
+		}
2843
+
2844
+		if ($pointer !== null) {
2845
+			$pointer += strlen($m[3]);
2846
+		}
2847
+		// remove first pipe
2848
+		$cmdstrsrc = substr($m[3], 1);
2849
+		// remove last quote if present
2850
+		if (substr($cmdstrsrc, -1, 1) === $m[1]) {
2851
+			$cmdstrsrc = substr($cmdstrsrc, 0, -1);
2852
+			$add = $m[1];
2853
+		}
2854
+
2855
+		$output = $m[2];
2856
+
2857
+		$continue = true;
2858
+		while (strlen($cmdstrsrc) > 0 && $continue) {
2859
+			if ($cmdstrsrc[0] === '|') {
2860
+				$cmdstrsrc = substr($cmdstrsrc, 1);
2861
+				continue;
2862
+			}
2863
+			if ($cmdstrsrc[0] === ' ' || $cmdstrsrc[0] === ';' || substr($cmdstrsrc, 0, strlen($this->rd)) === $this->rd) {
2864
+				if ($this->debug) {
2865
+					echo 'MODIFIER PARSING ENDED, RIGHT DELIMITER or ";" FOUND'."\n";
2866
+				}
2867
+				$continue = false;
2868
+				if ($pointer !== null) {
2869
+					$pointer -= strlen($cmdstrsrc);
2870
+				}
2871
+				break;
2872
+			}
2873
+			$cmdstr = $cmdstrsrc;
2874
+			$paramsep = ':';
2875
+			if (!preg_match('/^(@{0,2}[a-z_][a-z0-9_]*)(:)?/i', $cmdstr, $match)) {
2876
+				throw new Dwoo_Compilation_Exception($this, 'Invalid modifier name, started with : '.substr($cmdstr, 0, 10));
2877
+			}
2878
+			$paramspos = !empty($match[2]) ? strlen($match[1]) : false;
2879
+			$func = $match[1];
2880
+
2881
+			$state = 0;
2882
+			if ($paramspos === false) {
2883
+				$cmdstrsrc = substr($cmdstrsrc, strlen($func));
2884
+				$params = array();
2885
+				if ($this->debug) {
2886
+					echo 'MODIFIER ('.$func.') CALLED WITH NO PARAMS'."\n";
2887
+				}
2888
+			} else {
2889
+				$paramstr = substr($cmdstr, $paramspos + 1);
2890
+				if (substr($paramstr, -1, 1) === $paramsep) {
2891
+					$paramstr = substr($paramstr, 0, -1);
2892
+				}
2893
+
2894
+				$ptr = 0;
2895
+				$params = array();
2896
+				while ($ptr < strlen($paramstr)) {
2897
+					if ($this->debug) {
2898
+						echo 'MODIFIER ('.$func.') START PARAM PARSING WITH POINTER AT '.$ptr."\n";
2899
+					}
2900
+					if ($this->debug) {
2901
+						echo $paramstr.'--'.$ptr.'--'.strlen($paramstr).'--modifier'."\n";
2902
+					}
2903
+					$params = $this->parse($paramstr, $ptr, strlen($paramstr), $params, 'modifier', $ptr);
2904
+					if ($this->debug) {
2905
+						echo 'PARAM PARSED, POINTER AT '.$ptr."\n";
2906
+					}
2907
+
2908
+					if ($ptr >= strlen($paramstr)) {
2909
+						if ($this->debug) {
2910
+							echo 'PARAM PARSING ENDED, PARAM STRING CONSUMED'."\n";
2911
+						}
2912
+						break;
2913
+					}
2914
+
2915
+					if ($paramstr[$ptr] === ' ' || $paramstr[$ptr] === '|' || $paramstr[$ptr] === ';' || substr($paramstr, $ptr, strlen($this->rd)) === $this->rd) {
2916
+						if ($this->debug) {
2917
+							echo 'PARAM PARSING ENDED, " ", "|", RIGHT DELIMITER or ";" FOUND, POINTER AT '.$ptr."\n";
2918
+						}
2919
+						if ($paramstr[$ptr] !== '|') {
2920
+							$continue = false;
2921
+							if ($pointer !== null) {
2922
+								$pointer -= strlen($paramstr) - $ptr;
2923
+							}
2924
+						}
2925
+						++$ptr;
2926
+						break;
2927
+					}
2928
+					if ($ptr < strlen($paramstr) && $paramstr[$ptr] === ':') {
2929
+						++$ptr;
2930
+					}
2931
+				}
2932
+				$cmdstrsrc = substr($cmdstrsrc, strlen($func) + 1 + $ptr);
2933
+				$paramstr = substr($paramstr, 0, $ptr);
2934
+				foreach ($params as $k => $p) {
2935
+					if (is_array($p) && is_array($p[1])) {
2936
+						$state |= 2;
2937
+					} else {
2938
+						if (($state & 2) && preg_match('#^(["\'])(.+?)\1$#', $p[0], $m)) {
2939
+							$params[$k] = array($m[2], array('true', 'true'));
2940
+						} else {
2941
+							if ($state & 2) {
2942
+								throw new Dwoo_Compilation_Exception($this, 'You can not use an unnamed parameter after a named one');
2943
+							}
2944
+							$state |= 1;
2945
+						}
2946
+					}
2947
+				}
2948
+			}
2949
+
2950
+			// check if we must use array_map with this plugin or not
2951
+			$mapped = false;
2952
+			if (substr($func, 0, 1) === '@') {
2953
+				$func = substr($func, 1);
2954
+				$mapped = true;
2955
+			}
2956
+
2957
+			$pluginType = $this->getPluginType($func);
2958
+
2959
+			if ($state & 2) {
2960
+				array_unshift($params, array('value', is_array($output) ? $output : array($output, $output)));
2961
+			} else {
2962
+				array_unshift($params, is_array($output) ? $output : array($output, $output));
2963
+			}
2964
+
2965
+			if ($pluginType & Dwoo_Core::NATIVE_PLUGIN) {
2966
+				$params = $this->mapParams($params, null, $state);
2967
+
2968
+				$params = $params['*'][0];
2969
+
2970
+				$params = self::implode_r($params);
2971
+
2972
+				if ($mapped) {
2973
+					$output = '$this->arrayMap(\''.$func.'\', array('.$params.'))';
2974
+				} else {
2975
+					$output = $func.'('.$params.')';
2976
+				}
2977
+			} elseif ($pluginType & Dwoo_Core::PROXY_PLUGIN) {
2978
+				$params = $this->mapParams($params, $this->getDwoo()->getPluginProxy()->getCallback($func), $state);
2979
+				foreach ($params as &$p) {
2980
+					$p = $p[0];
2981
+				}
2982
+				$output = call_user_func(array($this->dwoo->getPluginProxy(), 'getCode'), $func, $params);
2983
+			} elseif ($pluginType & Dwoo_Core::SMARTY_MODIFIER) {
2984
+				$params = $this->mapParams($params, null, $state);
2985
+				$params = $params['*'][0];
2986
+
2987
+				$params = self::implode_r($params);
2988
+
2989
+				if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
2990
+					$callback = $this->customPlugins[$func]['callback'];
2991
+					if (is_array($callback)) {
2992
+						if (is_object($callback[0])) {
2993
+							$output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array('.$params.'))';
2994
+						} else {
2995
+							$output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array(\''.$callback[0].'\', \''.$callback[1].'\'), array('.$params.'))';
2996
+						}
2997
+					} elseif ($mapped) {
2998
+						$output = '$this->arrayMap(\''.$callback.'\', array('.$params.'))';
2999
+					} else {
3000
+						$output = $callback.'('.$params.')';
3001
+					}
3002
+				} elseif ($mapped) {
3003
+					$output = '$this->arrayMap(\'smarty_modifier_'.$func.'\', array('.$params.'))';
3004
+				} else {
3005
+					$output = 'smarty_modifier_'.$func.'('.$params.')';
3006
+				}
3007
+			} else {
3008
+				if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
3009
+					$callback = $this->customPlugins[$func]['callback'];
3010
+					$pluginName = $callback;
3011
+				} else {
3012
+					$pluginName = 'Dwoo_Plugin_'.$func;
3013
+
3014
+					if ($pluginType & Dwoo_Core::CLASS_PLUGIN) {
3015
+						$callback = array($pluginName, ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) ? 'compile' : 'process');
3016
+					} else {
3017
+						$callback = $pluginName.(($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) ? '_compile' : '');
3018
+					}
3019
+				}
3020
+
3021
+				$params = $this->mapParams($params, $callback, $state);
3022
+
3023
+				foreach ($params as &$p) {
3024
+					$p = $p[0];
3025
+				}
3026
+
3027
+				if ($pluginType & Dwoo_Core::FUNC_PLUGIN) {
3028
+					if ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) {
3029
+						if ($mapped) {
3030
+							throw new Dwoo_Compilation_Exception($this, 'The @ operator can not be used on compiled plugins.');
3031
+						}
3032
+						if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
3033
+							$funcCompiler = $this->customPlugins[$func]['callback'];
3034
+						} else {
3035
+							$funcCompiler = 'Dwoo_Plugin_'.$func.'_compile';
3036
+						}
3037
+						array_unshift($params, $this);
3038
+						$output = call_user_func_array($funcCompiler, $params);
3039
+					} else {
3040
+						array_unshift($params, '$this');
3041
+
3042
+						$params = self::implode_r($params);
3043
+						if ($mapped) {
3044
+							$output = '$this->arrayMap(\''.$pluginName.'\', array('.$params.'))';
3045
+						} else {
3046
+							$output = $pluginName.'('.$params.')';
3047
+						}
3048
+					}
3049
+				} else {
3050
+					if ($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) {
3051
+						if ($mapped) {
3052
+							throw new Dwoo_Compilation_Exception($this, 'The @ operator can not be used on compiled plugins.');
3053
+						}
3054
+						if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
3055
+							$callback = $this->customPlugins[$func]['callback'];
3056
+							if (!is_array($callback)) {
3057
+								if (!method_exists($callback, 'compile')) {
3058
+									throw new Dwoo_Exception('Custom plugin '.$func.' must implement the "compile" method to be compilable, or you should provide a full callback to the method to use');
3059
+								}
3060
+								if (($ref = new ReflectionMethod($callback, 'compile')) && $ref->isStatic()) {
3061
+									$funcCompiler = array($callback, 'compile');
3062
+								} else {
3063
+									$funcCompiler = array(new $callback(), 'compile');
3064
+								}
3065
+							} else {
3066
+								$funcCompiler = $callback;
3067
+							}
3068
+						} else {
3069
+							$funcCompiler = array('Dwoo_Plugin_'.$func, 'compile');
3070
+							array_unshift($params, $this);
3071
+						}
3072
+						$output = call_user_func_array($funcCompiler, $params);
3073
+					} else {
3074
+						$params = self::implode_r($params);
3075
+
3076
+						if ($pluginType & Dwoo_Core::CUSTOM_PLUGIN) {
3077
+							if (is_object($callback[0])) {
3078
+								$output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array($this->plugins[\''.$func.'\'][\'callback\'][0], \''.$callback[1].'\'), array('.$params.'))';
3079
+							} else {
3080
+								$output = ($mapped ? '$this->arrayMap' : 'call_user_func_array').'(array(\''.$callback[0].'\', \''.$callback[1].'\'), array('.$params.'))';
3081
+							}
3082
+						} elseif ($mapped) {
3083
+							$output = '$this->arrayMap(array($this->getObjectPlugin(\'Dwoo_Plugin_'.$func.'\'), \'process\'), array('.$params.'))';
3084
+						} else {
3085
+							$output = '$this->classCall(\''.$func.'\', array('.$params.'))';
3086
+						}
3087
+					}
3088
+				}
3089
+			}
3090
+		}
3091
+
3092
+		if ($curBlock === 'namedparam') {
3093
+			return array($output, $output);
3094
+		} elseif ($curBlock === 'var' || $m[1] === null) {
3095
+			return $output;
3096
+		} elseif ($curBlock === 'string' || $curBlock === 'root') {
3097
+			return $m[1].'.'.$output.'.'.$m[1].(isset($add) ? $add : null);
3098
+		}
3099
+
3100
+		return '';
3101
+	}
3102
+
3103
+	/**
3104
+	 * recursively implodes an array in a similar manner as var_export() does but with some tweaks
3105
+	 * to handle pre-compiled values and the fact that we do not need to enclose everything with
3106
+	 * "array" and do not require top-level keys to be displayed.
3107
+	 *
3108
+	 * @param array $params        the array to implode
3109
+	 * @param bool  $recursiveCall if set to true, the function outputs key names for the top level
3110
+	 *
3111
+	 * @return string the imploded array
3112
+	 */
3113
+	public static function implode_r(array $params, $recursiveCall = false)
3114
+	{
3115
+		$out = '';
3116
+		foreach ($params as $k => $p) {
3117
+			if (is_array($p)) {
3118
+				$out2 = 'array(';
3119
+				foreach ($p as $k2 => $v) {
3120
+					$out2 .= var_export($k2, true).' => '.(is_array($v) ? 'array('.self::implode_r($v, true).')' : $v).', ';
3121
+				}
3122
+				$p = rtrim($out2, ', ').')';
3123
+			}
3124
+			if ($recursiveCall) {
3125
+				$out .= var_export($k, true).' => '.$p.', ';
3126
+			} else {
3127
+				$out .= $p.', ';
3128
+			}
3129
+		}
3130
+
3131
+		return rtrim($out, ', ');
3132
+	}
3133
+
3134
+	/**
3135
+	 * returns the plugin type of a plugin and adds it to the used plugins array if required.
3136
+	 *
3137
+	 * @param string $name plugin name, as found in the template
3138
+	 *
3139
+	 * @return int type as a multi bit flag composed of the Dwoo plugin types constants
3140
+	 *
3141
+	 * @throws Dwoo_Exception
3142
+	 * @throws Dwoo_Security_Exception
3143
+	 * @throws Exception
3144
+	 */
3145
+	protected function getPluginType($name)
3146
+	{
3147
+		$pluginType = -1;
3148
+
3149
+		if (($this->securityPolicy === null && (function_exists($name) || strtolower($name) === 'isset' || strtolower($name) === 'empty')) ||
3150
+			($this->securityPolicy !== null && array_key_exists(strtolower($name), $this->securityPolicy->getAllowedPhpFunctions()) !== false)) {
3151
+			$phpFunc = true;
3152
+		} elseif ($this->securityPolicy !== null && function_exists($name) && array_key_exists(strtolower($name), $this->securityPolicy->getAllowedPhpFunctions()) === false) {
3153
+			throw new Dwoo_Security_Exception('Call to a disallowed php function : '.$name);
3154
+		}
3155
+
3156
+		while ($pluginType <= 0) {
3157
+			if (isset($this->templatePlugins[$name])) {
3158
+				$pluginType = Dwoo_Core::TEMPLATE_PLUGIN | Dwoo_Core::COMPILABLE_PLUGIN;
3159
+			} elseif (isset($this->customPlugins[$name])) {
3160
+				$pluginType = $this->customPlugins[$name]['type'] | Dwoo_Core::CUSTOM_PLUGIN;
3161
+			} elseif (class_exists('Dwoo_Plugin_'.$name) !== false) {
3162
+				if (is_subclass_of('Dwoo_Plugin_'.$name, 'Dwoo_Block_Plugin')) {
3163
+					$pluginType = Dwoo_Core::BLOCK_PLUGIN;
3164
+				} else {
3165
+					$pluginType = Dwoo_Core::CLASS_PLUGIN;
3166
+				}
3167
+				$interfaces = class_implements('Dwoo_Plugin_'.$name);
3168
+				if (in_array('Dwoo_ICompilable', $interfaces) !== false || in_array('Dwoo_ICompilable_Block', $interfaces) !== false) {
3169
+					$pluginType |= Dwoo_Core::COMPILABLE_PLUGIN;
3170
+				}
3171
+			} elseif (function_exists('Dwoo_Plugin_'.$name) !== false) {
3172
+				$pluginType = Dwoo_Core::FUNC_PLUGIN;
3173
+			} elseif (function_exists('Dwoo_Plugin_'.$name.'_compile')) {
3174
+				$pluginType = Dwoo_Core::FUNC_PLUGIN | Dwoo_Core::COMPILABLE_PLUGIN;
3175
+			} elseif (function_exists('smarty_modifier_'.$name) !== false) {
3176
+				$pluginType = Dwoo_Core::SMARTY_MODIFIER;
3177
+			} elseif (function_exists('smarty_function_'.$name) !== false) {
3178
+				$pluginType = Dwoo_Core::SMARTY_FUNCTION;
3179
+			} elseif (function_exists('smarty_block_'.$name) !== false) {
3180
+				$pluginType = Dwoo_Core::SMARTY_BLOCK;
3181
+			} else {
3182
+				if ($pluginType === -1) {
3183
+					try {
3184
+						$this->dwoo->getLoader()->loadPlugin($name, isset($phpFunc) === false);
3185
+					} catch (Exception $e) {
3186
+						if (isset($phpFunc)) {
3187
+							$pluginType = Dwoo_Core::NATIVE_PLUGIN;
3188
+						} elseif (is_object($this->dwoo->getPluginProxy()) && $this->dwoo->getPluginProxy()->handles($name)) {
3189
+							$pluginType = Dwoo_Core::PROXY_PLUGIN;
3190
+							break;
3191
+						} else {
3192
+							throw $e;
3193
+						}
3194
+					}
3195
+				} else {
3196
+					throw new Dwoo_Exception('Plugin "'.$name.'" could not be found');
3197
+				}
3198
+				++$pluginType;
3199
+			}
3200
+		}
3201
+
3202
+		if (($pluginType & Dwoo_Core::COMPILABLE_PLUGIN) === 0 && ($pluginType & Dwoo_Core::NATIVE_PLUGIN) === 0 && ($pluginType & Dwoo_Core::PROXY_PLUGIN) === 0) {
3203
+			$this->addUsedPlugin($name, $pluginType);
3204
+		}
3205
+
3206
+		return $pluginType;
3207
+	}
3208
+
3209
+	/**
3210
+	 * allows a plugin to load another one at compile time, this will also mark
3211
+	 * it as used by this template so it will be loaded at runtime (which can be
3212
+	 * useful for compiled plugins that rely on another plugin when their compiled
3213
+	 * code runs).
3214
+	 *
3215
+	 * @param string $name the plugin name
3216
+	 */
3217
+	public function loadPlugin($name)
3218
+	{
3219
+		$this->getPluginType($name);
3220
+	}
3221
+
3222
+	/**
3223
+	 * runs htmlentities over the matched <?php ?> blocks when the security policy enforces that.
3224
+	 *
3225
+	 * @param array $match matched php block
3226
+	 *
3227
+	 * @return string the htmlentities-converted string
3228
+	 */
3229
+	protected function phpTagEncodingHelper($match)
3230
+	{
3231
+		return htmlspecialchars($match[0]);
3232
+	}
3233
+
3234
+	/**
3235
+	 * maps the parameters received from the template onto the parameters required by the given callback.
3236
+	 *
3237
+	 * @param array    $params   the array of parameters
3238
+	 * @param callback $callback the function or method to reflect on to find out the required parameters
3239
+	 * @param int      $callType the type of call in the template, 0 = no params, 1 = php-style call, 2 = named parameters call
3240
+	 * @param array    $map      the parameter map to use, if not provided it will be built from the callback
3241
+	 *
3242
+	 * @return array parameters sorted in the correct order with missing optional parameters filled
3243
+	 *
3244
+	 * @throws Dwoo_Compilation_Exception
3245
+	 */
3246
+	protected function mapParams(array $params, $callback, $callType = 2, $map = null)
3247
+	{
3248
+		if (!$map) {
3249
+			$map = $this->getParamMap($callback);
3250
+		}
3251
+
3252
+		$paramlist = array();
3253
+
3254
+		// transforms the parameter array from (x=>array('paramname'=>array(values))) to (paramname=>array(values))
3255
+		$ps = array();
3256
+		foreach ($params as $p) {
3257
+			if (is_array($p[1])) {
3258
+				$ps[$p[0]] = $p[1];
3259
+			} else {
3260
+				$ps[] = $p;
3261
+			}
3262
+		}
3263
+
3264
+		// loops over the param map and assigns values from the template or default value for unset optional params
3265
+		while (list($k, $v) = each($map)) {
3266
+			if ($v[0] === '*') {
3267
+				// "rest" array parameter, fill every remaining params in it and then break
3268
+				if (count($ps) === 0) {
3269
+					if ($v[1] === false) {
3270
+						throw new Dwoo_Compilation_Exception($this, 'Rest argument missing for '.str_replace(array('Dwoo_Plugin_', '_compile'), '', (is_array($callback) ? $callback[0] : $callback)));
3271
+					} else {
3272
+						break;
3273
+					}
3274
+				}
3275
+				$tmp = array();
3276
+				$tmp2 = array();
3277
+				$tmp3 = array();
3278
+				foreach ($ps as $i => $p) {
3279
+					$tmp[$i] = $p[0];
3280
+					$tmp2[$i] = $p[1];
3281
+					$tmp3[$i] = isset($p[2]) ? $p[2] : 0;
3282
+					unset($ps[$i]);
3283
+				}
3284
+				$paramlist[$v[0]] = array($tmp, $tmp2, $tmp3);
3285
+				unset($tmp, $tmp2, $i, $p);
3286
+				break;
3287
+			} elseif (isset($ps[$v[0]])) {
3288
+				// parameter is defined as named param
3289
+				$paramlist[$v[0]] = $ps[$v[0]];
3290
+				unset($ps[$v[0]]);
3291
+			} elseif (isset($ps[$k])) {
3292
+				// parameter is defined as ordered param
3293
+				$paramlist[$v[0]] = $ps[$k];
3294
+				unset($ps[$k]);
3295
+			} elseif ($v[1] === false) {
3296
+				// parameter is not defined and not optional, throw error
3297
+				if (is_array($callback)) {
3298
+					if (is_object($callback[0])) {
3299
+						$name = get_class($callback[0]).'::'.$callback[1];
3300
+					} else {
3301
+						$name = $callback[0];
3302
+					}
3303
+				} else {
3304
+					$name = $callback;
3305
+				}
3306
+
3307
+				throw new Dwoo_Compilation_Exception($this, 'Argument '.$k.'/'.$v[0].' missing for '.str_replace(array('Dwoo_Plugin_', '_compile'), '', $name));
3308
+			} elseif ($v[2] === null) {
3309
+				// enforce lowercased null if default value is null (php outputs NULL with var export)
3310
+				$paramlist[$v[0]] = array('null', null, self::T_NULL);
3311
+			} else {
3312
+				// outputs default value with var_export
3313
+				$paramlist[$v[0]] = array(var_export($v[2], true), $v[2]);
3314
+			}
3315
+		}
3316
+
3317
+		if (count($ps)) {
3318
+			foreach ($ps as $i => $p) {
3319
+				array_push($paramlist, $p);
3320
+			}
3321
+		}
3322
+
3323
+		return $paramlist;
3324
+	}
3325
+
3326
+	/**
3327
+	 * returns the parameter map of the given callback, it filters out entries typed as Dwoo and Dwoo_Compiler and turns the rest parameter into a "*".
3328
+	 *
3329
+	 * @param callback $callback the function/method to reflect on
3330
+	 *
3331
+	 * @return array processed parameter map
3332
+	 */
3333
+	protected function getParamMap($callback)
3334
+	{
3335
+		if (is_null($callback)) {
3336
+			return array(array('*', true));
3337
+		}
3338
+		if (is_array($callback)) {
3339
+			$ref = new ReflectionMethod($callback[0], $callback[1]);
3340
+		} else {
3341
+			$ref = new ReflectionFunction($callback);
3342
+		}
3343
+
3344
+		$out = array();
3345
+		foreach ($ref->getParameters() as $param) {
3346
+			if (($class = $param->getClass()) !== null && ($class->name === 'Dwoo' || $class->name === 'Dwoo_Core')) {
3347
+				continue;
3348
+			}
3349
+			if (($class = $param->getClass()) !== null && $class->name === 'Dwoo_Compiler') {
3350
+				continue;
3351
+			}
3352
+			if ($param->getName() === 'rest' && $param->isArray() === true) {
3353
+				$out[] = array('*', $param->isOptional(), null);
3354
+				continue;
3355
+			}
3356
+			$out[] = array($param->getName(), $param->isOptional(), $param->isOptional() ? $param->getDefaultValue() : null);
3357
+		}
3358
+
3359
+		return $out;
3360
+	}
3361
+
3362
+	/**
3363
+	 * returns a default instance of this compiler, used by default by all Dwoo templates that do not have a
3364
+	 * specific compiler assigned and when you do not override the default compiler factory function.
3365
+	 *
3366
+	 * @see Dwoo_Core::setDefaultCompilerFactory()
3367
+	 *
3368
+	 * @return Dwoo_Compiler
3369
+	 */
3370
+	public static function compilerFactory()
3371
+	{
3372
+		if (self::$instance === null) {
3373
+			new self();
3374
+		}
3375
+
3376
+		return self::$instance;
3377
+	}
3378 3378
 }
Please login to merge, or discard this patch.
lib/plugins/builtin/blocks/template.php 1 patch
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -22,72 +22,72 @@
 block discarded – undo
22 22
  */
23 23
 class Dwoo_Plugin_template extends Dwoo_Block_Plugin implements Dwoo_ICompilable_Block
24 24
 {
25
-    public function init($name, array $rest = array())
26
-    {
27
-    }
25
+	public function init($name, array $rest = array())
26
+	{
27
+	}
28 28
 
29
-    public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type)
30
-    {
31
-        $params = $compiler->getCompiledParams($params);
32
-        $parsedParams = array();
33
-        if (!isset($params['*'])) {
34
-            $params['*'] = array();
35
-        }
36
-        foreach ($params['*'] as $param => $defValue) {
37
-            if (is_numeric($param)) {
38
-                $param = $defValue;
39
-                $defValue = null;
40
-            }
41
-            $param = trim($param, '\'"');
42
-            if (!preg_match('#^[a-z0-9_]+$#i', $param)) {
43
-                throw new Dwoo_Compilation_Exception($compiler, 'Function : parameter names must contain only A-Z, 0-9 or _');
44
-            }
45
-            $parsedParams[$param] = $defValue;
46
-        }
47
-        $params['name'] = substr($params['name'], 1, -1);
48
-        $params['*'] = $parsedParams;
49
-        $params['uuid'] = uniqid();
50
-        $compiler->addTemplatePlugin($params['name'], $parsedParams, $params['uuid']);
51
-        $currentBlock = &$compiler->getCurrentBlock();
52
-        $currentBlock['params'] = $params;
29
+	public static function preProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $type)
30
+	{
31
+		$params = $compiler->getCompiledParams($params);
32
+		$parsedParams = array();
33
+		if (!isset($params['*'])) {
34
+			$params['*'] = array();
35
+		}
36
+		foreach ($params['*'] as $param => $defValue) {
37
+			if (is_numeric($param)) {
38
+				$param = $defValue;
39
+				$defValue = null;
40
+			}
41
+			$param = trim($param, '\'"');
42
+			if (!preg_match('#^[a-z0-9_]+$#i', $param)) {
43
+				throw new Dwoo_Compilation_Exception($compiler, 'Function : parameter names must contain only A-Z, 0-9 or _');
44
+			}
45
+			$parsedParams[$param] = $defValue;
46
+		}
47
+		$params['name'] = substr($params['name'], 1, -1);
48
+		$params['*'] = $parsedParams;
49
+		$params['uuid'] = uniqid();
50
+		$compiler->addTemplatePlugin($params['name'], $parsedParams, $params['uuid']);
51
+		$currentBlock = &$compiler->getCurrentBlock();
52
+		$currentBlock['params'] = $params;
53 53
 
54
-        return '';
55
-    }
54
+		return '';
55
+	}
56 56
 
57
-    public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content)
58
-    {
59
-        $paramstr = 'Dwoo_Core $dwoo';
60
-        $init = 'static $_callCnt = 0;'."\n".
61
-        '$dwoo->scope[\' '.$params['uuid'].'\'.$_callCnt] = array();'."\n".
62
-        '$_scope = $dwoo->setScope(array(\' '.$params['uuid'].'\'.($_callCnt++)));'."\n";
63
-        $cleanup = '/* -- template end output */ $dwoo->setScope($_scope, true);';
64
-        foreach ($params['*'] as $param => $defValue) {
65
-            if ($defValue === null) {
66
-                $paramstr .= ', $'.$param;
67
-            } else {
68
-                $paramstr .= ', $'.$param.' = '.$defValue;
69
-            }
70
-            $init .= '$dwoo->scope[\''.$param.'\'] = $'.$param.";\n";
71
-        }
72
-        $init .= '/* -- template start output */';
57
+	public static function postProcessing(Dwoo_Compiler $compiler, array $params, $prepend, $append, $content)
58
+	{
59
+		$paramstr = 'Dwoo_Core $dwoo';
60
+		$init = 'static $_callCnt = 0;'."\n".
61
+		'$dwoo->scope[\' '.$params['uuid'].'\'.$_callCnt] = array();'."\n".
62
+		'$_scope = $dwoo->setScope(array(\' '.$params['uuid'].'\'.($_callCnt++)));'."\n";
63
+		$cleanup = '/* -- template end output */ $dwoo->setScope($_scope, true);';
64
+		foreach ($params['*'] as $param => $defValue) {
65
+			if ($defValue === null) {
66
+				$paramstr .= ', $'.$param;
67
+			} else {
68
+				$paramstr .= ', $'.$param.' = '.$defValue;
69
+			}
70
+			$init .= '$dwoo->scope[\''.$param.'\'] = $'.$param.";\n";
71
+		}
72
+		$init .= '/* -- template start output */';
73 73
 
74
-        $funcName = 'Dwoo_Plugin_'.$params['name'];
74
+		$funcName = 'Dwoo_Plugin_'.$params['name'];
75 75
 
76
-        $search = array(
77
-            '$this->charset',
78
-            '$this->',
79
-            '$this,',
80
-        );
81
-        $replacement = array(
82
-            '$dwoo->getCharset()',
83
-            '$dwoo->',
84
-            '$dwoo,',
85
-        );
86
-        $content = str_replace($search, $replacement, $content);
76
+		$search = array(
77
+			'$this->charset',
78
+			'$this->',
79
+			'$this,',
80
+		);
81
+		$replacement = array(
82
+			'$dwoo->getCharset()',
83
+			'$dwoo->',
84
+			'$dwoo,',
85
+		);
86
+		$content = str_replace($search, $replacement, $content);
87 87
 
88
-        $body = 'if (!function_exists(\''.$funcName."')) {\nfunction ".$funcName.'('.$paramstr.') {'."\n$init".Dwoo_Compiler::PHP_CLOSE.
89
-            $prepend.$content.$append.
90
-            Dwoo_Compiler::PHP_OPEN.$cleanup."\n}\n}";
91
-        $compiler->addTemplatePlugin($params['name'], $params['*'], $params['uuid'], $body);
92
-    }
88
+		$body = 'if (!function_exists(\''.$funcName."')) {\nfunction ".$funcName.'('.$paramstr.') {'."\n$init".Dwoo_Compiler::PHP_CLOSE.
89
+			$prepend.$content.$append.
90
+			Dwoo_Compiler::PHP_OPEN.$cleanup."\n}\n}";
91
+		$compiler->addTemplatePlugin($params['name'], $params['*'], $params['uuid'], $body);
92
+	}
93 93
 }
Please login to merge, or discard this patch.