Security update to Drupal 8.4.6
[yaffs-website] / vendor / twig / twig / lib / Twig / Extension / Core.php
1 <?php
2
3 if (!defined('ENT_SUBSTITUTE')) {
4     define('ENT_SUBSTITUTE', 8);
5 }
6
7 /*
8  * This file is part of Twig.
9  *
10  * (c) Fabien Potencier
11  *
12  * For the full copyright and license information, please view the LICENSE
13  * file that was distributed with this source code.
14  */
15
16 /**
17  * @final
18  */
19 class Twig_Extension_Core extends Twig_Extension
20 {
21     protected $dateFormats = array('F j, Y H:i', '%d days');
22     protected $numberFormat = array(0, '.', ',');
23     protected $timezone = null;
24     protected $escapers = array();
25
26     /**
27      * Defines a new escaper to be used via the escape filter.
28      *
29      * @param string   $strategy The strategy name that should be used as a strategy in the escape call
30      * @param callable $callable A valid PHP callable
31      */
32     public function setEscaper($strategy, $callable)
33     {
34         $this->escapers[$strategy] = $callable;
35     }
36
37     /**
38      * Gets all defined escapers.
39      *
40      * @return array An array of escapers
41      */
42     public function getEscapers()
43     {
44         return $this->escapers;
45     }
46
47     /**
48      * Sets the default format to be used by the date filter.
49      *
50      * @param string $format             The default date format string
51      * @param string $dateIntervalFormat The default date interval format string
52      */
53     public function setDateFormat($format = null, $dateIntervalFormat = null)
54     {
55         if (null !== $format) {
56             $this->dateFormats[0] = $format;
57         }
58
59         if (null !== $dateIntervalFormat) {
60             $this->dateFormats[1] = $dateIntervalFormat;
61         }
62     }
63
64     /**
65      * Gets the default format to be used by the date filter.
66      *
67      * @return array The default date format string and the default date interval format string
68      */
69     public function getDateFormat()
70     {
71         return $this->dateFormats;
72     }
73
74     /**
75      * Sets the default timezone to be used by the date filter.
76      *
77      * @param DateTimeZone|string $timezone The default timezone string or a DateTimeZone object
78      */
79     public function setTimezone($timezone)
80     {
81         $this->timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
82     }
83
84     /**
85      * Gets the default timezone to be used by the date filter.
86      *
87      * @return DateTimeZone The default timezone currently in use
88      */
89     public function getTimezone()
90     {
91         if (null === $this->timezone) {
92             $this->timezone = new DateTimeZone(date_default_timezone_get());
93         }
94
95         return $this->timezone;
96     }
97
98     /**
99      * Sets the default format to be used by the number_format filter.
100      *
101      * @param int    $decimal      the number of decimal places to use
102      * @param string $decimalPoint the character(s) to use for the decimal point
103      * @param string $thousandSep  the character(s) to use for the thousands separator
104      */
105     public function setNumberFormat($decimal, $decimalPoint, $thousandSep)
106     {
107         $this->numberFormat = array($decimal, $decimalPoint, $thousandSep);
108     }
109
110     /**
111      * Get the default format used by the number_format filter.
112      *
113      * @return array The arguments for number_format()
114      */
115     public function getNumberFormat()
116     {
117         return $this->numberFormat;
118     }
119
120     public function getTokenParsers()
121     {
122         return array(
123             new Twig_TokenParser_For(),
124             new Twig_TokenParser_If(),
125             new Twig_TokenParser_Extends(),
126             new Twig_TokenParser_Include(),
127             new Twig_TokenParser_Block(),
128             new Twig_TokenParser_Use(),
129             new Twig_TokenParser_Filter(),
130             new Twig_TokenParser_Macro(),
131             new Twig_TokenParser_Import(),
132             new Twig_TokenParser_From(),
133             new Twig_TokenParser_Set(),
134             new Twig_TokenParser_Spaceless(),
135             new Twig_TokenParser_Flush(),
136             new Twig_TokenParser_Do(),
137             new Twig_TokenParser_Embed(),
138             new Twig_TokenParser_With(),
139         );
140     }
141
142     public function getFilters()
143     {
144         $filters = array(
145             // formatting filters
146             new Twig_SimpleFilter('date', 'twig_date_format_filter', array('needs_environment' => true)),
147             new Twig_SimpleFilter('date_modify', 'twig_date_modify_filter', array('needs_environment' => true)),
148             new Twig_SimpleFilter('format', 'sprintf'),
149             new Twig_SimpleFilter('replace', 'twig_replace_filter'),
150             new Twig_SimpleFilter('number_format', 'twig_number_format_filter', array('needs_environment' => true)),
151             new Twig_SimpleFilter('abs', 'abs'),
152             new Twig_SimpleFilter('round', 'twig_round'),
153
154             // encoding
155             new Twig_SimpleFilter('url_encode', 'twig_urlencode_filter'),
156             new Twig_SimpleFilter('json_encode', 'twig_jsonencode_filter'),
157             new Twig_SimpleFilter('convert_encoding', 'twig_convert_encoding'),
158
159             // string filters
160             new Twig_SimpleFilter('title', 'twig_title_string_filter', array('needs_environment' => true)),
161             new Twig_SimpleFilter('capitalize', 'twig_capitalize_string_filter', array('needs_environment' => true)),
162             new Twig_SimpleFilter('upper', 'strtoupper'),
163             new Twig_SimpleFilter('lower', 'strtolower'),
164             new Twig_SimpleFilter('striptags', 'strip_tags'),
165             new Twig_SimpleFilter('trim', 'twig_trim_filter'),
166             new Twig_SimpleFilter('nl2br', 'nl2br', array('pre_escape' => 'html', 'is_safe' => array('html'))),
167
168             // array helpers
169             new Twig_SimpleFilter('join', 'twig_join_filter'),
170             new Twig_SimpleFilter('split', 'twig_split_filter', array('needs_environment' => true)),
171             new Twig_SimpleFilter('sort', 'twig_sort_filter'),
172             new Twig_SimpleFilter('merge', 'twig_array_merge'),
173             new Twig_SimpleFilter('batch', 'twig_array_batch'),
174
175             // string/array filters
176             new Twig_SimpleFilter('reverse', 'twig_reverse_filter', array('needs_environment' => true)),
177             new Twig_SimpleFilter('length', 'twig_length_filter', array('needs_environment' => true)),
178             new Twig_SimpleFilter('slice', 'twig_slice', array('needs_environment' => true)),
179             new Twig_SimpleFilter('first', 'twig_first', array('needs_environment' => true)),
180             new Twig_SimpleFilter('last', 'twig_last', array('needs_environment' => true)),
181
182             // iteration and runtime
183             new Twig_SimpleFilter('default', '_twig_default_filter', array('node_class' => 'Twig_Node_Expression_Filter_Default')),
184             new Twig_SimpleFilter('keys', 'twig_get_array_keys_filter'),
185
186             // escaping
187             new Twig_SimpleFilter('escape', 'twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe')),
188             new Twig_SimpleFilter('e', 'twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe')),
189         );
190
191         if (function_exists('mb_get_info')) {
192             $filters[] = new Twig_SimpleFilter('upper', 'twig_upper_filter', array('needs_environment' => true));
193             $filters[] = new Twig_SimpleFilter('lower', 'twig_lower_filter', array('needs_environment' => true));
194         }
195
196         return $filters;
197     }
198
199     public function getFunctions()
200     {
201         return array(
202             new Twig_SimpleFunction('max', 'max'),
203             new Twig_SimpleFunction('min', 'min'),
204             new Twig_SimpleFunction('range', 'range'),
205             new Twig_SimpleFunction('constant', 'twig_constant'),
206             new Twig_SimpleFunction('cycle', 'twig_cycle'),
207             new Twig_SimpleFunction('random', 'twig_random', array('needs_environment' => true)),
208             new Twig_SimpleFunction('date', 'twig_date_converter', array('needs_environment' => true)),
209             new Twig_SimpleFunction('include', 'twig_include', array('needs_environment' => true, 'needs_context' => true, 'is_safe' => array('all'))),
210             new Twig_SimpleFunction('source', 'twig_source', array('needs_environment' => true, 'is_safe' => array('all'))),
211         );
212     }
213
214     public function getTests()
215     {
216         return array(
217             new Twig_SimpleTest('even', null, array('node_class' => 'Twig_Node_Expression_Test_Even')),
218             new Twig_SimpleTest('odd', null, array('node_class' => 'Twig_Node_Expression_Test_Odd')),
219             new Twig_SimpleTest('defined', null, array('node_class' => 'Twig_Node_Expression_Test_Defined')),
220             new Twig_SimpleTest('sameas', null, array('node_class' => 'Twig_Node_Expression_Test_Sameas', 'deprecated' => '1.21', 'alternative' => 'same as')),
221             new Twig_SimpleTest('same as', null, array('node_class' => 'Twig_Node_Expression_Test_Sameas')),
222             new Twig_SimpleTest('none', null, array('node_class' => 'Twig_Node_Expression_Test_Null')),
223             new Twig_SimpleTest('null', null, array('node_class' => 'Twig_Node_Expression_Test_Null')),
224             new Twig_SimpleTest('divisibleby', null, array('node_class' => 'Twig_Node_Expression_Test_Divisibleby', 'deprecated' => '1.21', 'alternative' => 'divisible by')),
225             new Twig_SimpleTest('divisible by', null, array('node_class' => 'Twig_Node_Expression_Test_Divisibleby')),
226             new Twig_SimpleTest('constant', null, array('node_class' => 'Twig_Node_Expression_Test_Constant')),
227             new Twig_SimpleTest('empty', 'twig_test_empty'),
228             new Twig_SimpleTest('iterable', 'twig_test_iterable'),
229         );
230     }
231
232     public function getOperators()
233     {
234         return array(
235             array(
236                 'not' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'),
237                 '-' => array('precedence' => 500, 'class' => 'Twig_Node_Expression_Unary_Neg'),
238                 '+' => array('precedence' => 500, 'class' => 'Twig_Node_Expression_Unary_Pos'),
239             ),
240             array(
241                 'or' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
242                 'and' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
243                 'b-or' => array('precedence' => 16, 'class' => 'Twig_Node_Expression_Binary_BitwiseOr', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
244                 'b-xor' => array('precedence' => 17, 'class' => 'Twig_Node_Expression_Binary_BitwiseXor', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
245                 'b-and' => array('precedence' => 18, 'class' => 'Twig_Node_Expression_Binary_BitwiseAnd', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
246                 '==' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Equal', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
247                 '!=' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_NotEqual', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
248                 '<' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Less', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
249                 '>' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Greater', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
250                 '>=' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_GreaterEqual', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
251                 '<=' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_LessEqual', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
252                 'not in' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_NotIn', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
253                 'in' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_In', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
254                 'matches' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Matches', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
255                 'starts with' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_StartsWith', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
256                 'ends with' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_EndsWith', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
257                 '..' => array('precedence' => 25, 'class' => 'Twig_Node_Expression_Binary_Range', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
258                 '+' => array('precedence' => 30, 'class' => 'Twig_Node_Expression_Binary_Add', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
259                 '-' => array('precedence' => 30, 'class' => 'Twig_Node_Expression_Binary_Sub', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
260                 '~' => array('precedence' => 40, 'class' => 'Twig_Node_Expression_Binary_Concat', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
261                 '*' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Mul', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
262                 '/' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Div', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
263                 '//' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_FloorDiv', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
264                 '%' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Mod', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
265                 'is' => array('precedence' => 100, 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
266                 'is not' => array('precedence' => 100, 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
267                 '**' => array('precedence' => 200, 'class' => 'Twig_Node_Expression_Binary_Power', 'associativity' => Twig_ExpressionParser::OPERATOR_RIGHT),
268                 '??' => array('precedence' => 300, 'class' => 'Twig_Node_Expression_NullCoalesce', 'associativity' => Twig_ExpressionParser::OPERATOR_RIGHT),
269             ),
270         );
271     }
272
273     public function getName()
274     {
275         return 'core';
276     }
277 }
278
279 /**
280  * Cycles over a value.
281  *
282  * @param ArrayAccess|array $values
283  * @param int               $position The cycle position
284  *
285  * @return string The next value in the cycle
286  */
287 function twig_cycle($values, $position)
288 {
289     if (!is_array($values) && !$values instanceof ArrayAccess) {
290         return $values;
291     }
292
293     return $values[$position % count($values)];
294 }
295
296 /**
297  * Returns a random value depending on the supplied parameter type:
298  * - a random item from a Traversable or array
299  * - a random character from a string
300  * - a random integer between 0 and the integer parameter.
301  *
302  * @param Twig_Environment                   $env
303  * @param Traversable|array|int|float|string $values The values to pick a random item from
304  *
305  * @throws Twig_Error_Runtime when $values is an empty array (does not apply to an empty string which is returned as is)
306  *
307  * @return mixed A random value from the given sequence
308  */
309 function twig_random(Twig_Environment $env, $values = null)
310 {
311     if (null === $values) {
312         return mt_rand();
313     }
314
315     if (is_int($values) || is_float($values)) {
316         return $values < 0 ? mt_rand($values, 0) : mt_rand(0, $values);
317     }
318
319     if ($values instanceof Traversable) {
320         $values = iterator_to_array($values);
321     } elseif (is_string($values)) {
322         if ('' === $values) {
323             return '';
324         }
325         if (null !== $charset = $env->getCharset()) {
326             if ('UTF-8' !== $charset) {
327                 $values = twig_convert_encoding($values, 'UTF-8', $charset);
328             }
329
330             // unicode version of str_split()
331             // split at all positions, but not after the start and not before the end
332             $values = preg_split('/(?<!^)(?!$)/u', $values);
333
334             if ('UTF-8' !== $charset) {
335                 foreach ($values as $i => $value) {
336                     $values[$i] = twig_convert_encoding($value, $charset, 'UTF-8');
337                 }
338             }
339         } else {
340             return $values[mt_rand(0, strlen($values) - 1)];
341         }
342     }
343
344     if (!is_array($values)) {
345         return $values;
346     }
347
348     if (0 === count($values)) {
349         throw new Twig_Error_Runtime('The random function cannot pick from an empty array.');
350     }
351
352     return $values[array_rand($values, 1)];
353 }
354
355 /**
356  * Converts a date to the given format.
357  *
358  * <pre>
359  *   {{ post.published_at|date("m/d/Y") }}
360  * </pre>
361  *
362  * @param Twig_Environment                               $env
363  * @param DateTime|DateTimeInterface|DateInterval|string $date     A date
364  * @param string|null                                    $format   The target format, null to use the default
365  * @param DateTimeZone|string|null|false                 $timezone The target timezone, null to use the default, false to leave unchanged
366  *
367  * @return string The formatted date
368  */
369 function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $timezone = null)
370 {
371     if (null === $format) {
372         $formats = $env->getExtension('Twig_Extension_Core')->getDateFormat();
373         $format = $date instanceof DateInterval ? $formats[1] : $formats[0];
374     }
375
376     if ($date instanceof DateInterval) {
377         return $date->format($format);
378     }
379
380     return twig_date_converter($env, $date, $timezone)->format($format);
381 }
382
383 /**
384  * Returns a new date object modified.
385  *
386  * <pre>
387  *   {{ post.published_at|date_modify("-1day")|date("m/d/Y") }}
388  * </pre>
389  *
390  * @param Twig_Environment $env
391  * @param DateTime|string  $date     A date
392  * @param string           $modifier A modifier string
393  *
394  * @return DateTime A new date object
395  */
396 function twig_date_modify_filter(Twig_Environment $env, $date, $modifier)
397 {
398     $date = twig_date_converter($env, $date, false);
399     $resultDate = $date->modify($modifier);
400
401     // This is a hack to ensure PHP 5.2 support and support for DateTimeImmutable
402     // DateTime::modify does not return the modified DateTime object < 5.3.0
403     // and DateTimeImmutable does not modify $date.
404     return null === $resultDate ? $date : $resultDate;
405 }
406
407 /**
408  * Converts an input to a DateTime instance.
409  *
410  * <pre>
411  *    {% if date(user.created_at) < date('+2days') %}
412  *      {# do something #}
413  *    {% endif %}
414  * </pre>
415  *
416  * @param Twig_Environment                       $env
417  * @param DateTime|DateTimeInterface|string|null $date     A date
418  * @param DateTimeZone|string|null|false         $timezone The target timezone, null to use the default, false to leave unchanged
419  *
420  * @return DateTime A DateTime instance
421  */
422 function twig_date_converter(Twig_Environment $env, $date = null, $timezone = null)
423 {
424     // determine the timezone
425     if (false !== $timezone) {
426         if (null === $timezone) {
427             $timezone = $env->getExtension('Twig_Extension_Core')->getTimezone();
428         } elseif (!$timezone instanceof DateTimeZone) {
429             $timezone = new DateTimeZone($timezone);
430         }
431     }
432
433     // immutable dates
434     if ($date instanceof DateTimeImmutable) {
435         return false !== $timezone ? $date->setTimezone($timezone) : $date;
436     }
437
438     if ($date instanceof DateTime || $date instanceof DateTimeInterface) {
439         $date = clone $date;
440         if (false !== $timezone) {
441             $date->setTimezone($timezone);
442         }
443
444         return $date;
445     }
446
447     if (null === $date || 'now' === $date) {
448         return new DateTime($date, false !== $timezone ? $timezone : $env->getExtension('Twig_Extension_Core')->getTimezone());
449     }
450
451     $asString = (string) $date;
452     if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) {
453         $date = new DateTime('@'.$date);
454     } else {
455         $date = new DateTime($date, $env->getExtension('Twig_Extension_Core')->getTimezone());
456     }
457
458     if (false !== $timezone) {
459         $date->setTimezone($timezone);
460     }
461
462     return $date;
463 }
464
465 /**
466  * Replaces strings within a string.
467  *
468  * @param string            $str  String to replace in
469  * @param array|Traversable $from Replace values
470  * @param string|null       $to   Replace to, deprecated (@see http://php.net/manual/en/function.strtr.php)
471  *
472  * @return string
473  */
474 function twig_replace_filter($str, $from, $to = null)
475 {
476     if ($from instanceof Traversable) {
477         $from = iterator_to_array($from);
478     } elseif (is_string($from) && is_string($to)) {
479         @trigger_error('Using "replace" with character by character replacement is deprecated since version 1.22 and will be removed in Twig 2.0', E_USER_DEPRECATED);
480
481         return strtr($str, $from, $to);
482     } elseif (!is_array($from)) {
483         throw new Twig_Error_Runtime(sprintf('The "replace" filter expects an array or "Traversable" as replace values, got "%s".', is_object($from) ? get_class($from) : gettype($from)));
484     }
485
486     return strtr($str, $from);
487 }
488
489 /**
490  * Rounds a number.
491  *
492  * @param int|float $value     The value to round
493  * @param int|float $precision The rounding precision
494  * @param string    $method    The method to use for rounding
495  *
496  * @return int|float The rounded number
497  */
498 function twig_round($value, $precision = 0, $method = 'common')
499 {
500     if ('common' == $method) {
501         return round($value, $precision);
502     }
503
504     if ('ceil' != $method && 'floor' != $method) {
505         throw new Twig_Error_Runtime('The round filter only supports the "common", "ceil", and "floor" methods.');
506     }
507
508     return $method($value * pow(10, $precision)) / pow(10, $precision);
509 }
510
511 /**
512  * Number format filter.
513  *
514  * All of the formatting options can be left null, in that case the defaults will
515  * be used.  Supplying any of the parameters will override the defaults set in the
516  * environment object.
517  *
518  * @param Twig_Environment $env
519  * @param mixed            $number       A float/int/string of the number to format
520  * @param int              $decimal      the number of decimal points to display
521  * @param string           $decimalPoint the character(s) to use for the decimal point
522  * @param string           $thousandSep  the character(s) to use for the thousands separator
523  *
524  * @return string The formatted number
525  */
526 function twig_number_format_filter(Twig_Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null)
527 {
528     $defaults = $env->getExtension('Twig_Extension_Core')->getNumberFormat();
529     if (null === $decimal) {
530         $decimal = $defaults[0];
531     }
532
533     if (null === $decimalPoint) {
534         $decimalPoint = $defaults[1];
535     }
536
537     if (null === $thousandSep) {
538         $thousandSep = $defaults[2];
539     }
540
541     return number_format((float) $number, $decimal, $decimalPoint, $thousandSep);
542 }
543
544 /**
545  * URL encodes (RFC 3986) a string as a path segment or an array as a query string.
546  *
547  * @param string|array $url A URL or an array of query parameters
548  *
549  * @return string The URL encoded value
550  */
551 function twig_urlencode_filter($url)
552 {
553     if (is_array($url)) {
554         if (defined('PHP_QUERY_RFC3986')) {
555             return http_build_query($url, '', '&', PHP_QUERY_RFC3986);
556         }
557
558         return http_build_query($url, '', '&');
559     }
560
561     return rawurlencode($url);
562 }
563
564 if (PHP_VERSION_ID < 50300) {
565     /**
566      * JSON encodes a variable.
567      *
568      * @param mixed $value   the value to encode
569      * @param int   $options Not used on PHP 5.2.x
570      *
571      * @return mixed The JSON encoded value
572      */
573     function twig_jsonencode_filter($value, $options = 0)
574     {
575         if ($value instanceof Twig_Markup) {
576             $value = (string) $value;
577         } elseif (is_array($value)) {
578             array_walk_recursive($value, '_twig_markup2string');
579         }
580
581         return json_encode($value);
582     }
583 } else {
584     /**
585      * JSON encodes a variable.
586      *
587      * @param mixed $value   the value to encode
588      * @param int   $options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
589      *
590      * @return mixed The JSON encoded value
591      */
592     function twig_jsonencode_filter($value, $options = 0)
593     {
594         if ($value instanceof Twig_Markup) {
595             $value = (string) $value;
596         } elseif (is_array($value)) {
597             array_walk_recursive($value, '_twig_markup2string');
598         }
599
600         return json_encode($value, $options);
601     }
602 }
603
604 function _twig_markup2string(&$value)
605 {
606     if ($value instanceof Twig_Markup) {
607         $value = (string) $value;
608     }
609 }
610
611 /**
612  * Merges an array with another one.
613  *
614  * <pre>
615  *  {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
616  *
617  *  {% set items = items|merge({ 'peugeot': 'car' }) %}
618  *
619  *  {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #}
620  * </pre>
621  *
622  * @param array|Traversable $arr1 An array
623  * @param array|Traversable $arr2 An array
624  *
625  * @return array The merged array
626  */
627 function twig_array_merge($arr1, $arr2)
628 {
629     if ($arr1 instanceof Traversable) {
630         $arr1 = iterator_to_array($arr1);
631     } elseif (!is_array($arr1)) {
632         throw new Twig_Error_Runtime(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as first argument.', gettype($arr1)));
633     }
634
635     if ($arr2 instanceof Traversable) {
636         $arr2 = iterator_to_array($arr2);
637     } elseif (!is_array($arr2)) {
638         throw new Twig_Error_Runtime(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as second argument.', gettype($arr2)));
639     }
640
641     return array_merge($arr1, $arr2);
642 }
643
644 /**
645  * Slices a variable.
646  *
647  * @param Twig_Environment $env
648  * @param mixed            $item         A variable
649  * @param int              $start        Start of the slice
650  * @param int              $length       Size of the slice
651  * @param bool             $preserveKeys Whether to preserve key or not (when the input is an array)
652  *
653  * @return mixed The sliced variable
654  */
655 function twig_slice(Twig_Environment $env, $item, $start, $length = null, $preserveKeys = false)
656 {
657     if ($item instanceof Traversable) {
658         while ($item instanceof IteratorAggregate) {
659             $item = $item->getIterator();
660         }
661
662         if ($start >= 0 && $length >= 0 && $item instanceof Iterator) {
663             try {
664                 return iterator_to_array(new LimitIterator($item, $start, null === $length ? -1 : $length), $preserveKeys);
665             } catch (OutOfBoundsException $exception) {
666                 return array();
667             }
668         }
669
670         $item = iterator_to_array($item, $preserveKeys);
671     }
672
673     if (is_array($item)) {
674         return array_slice($item, $start, $length, $preserveKeys);
675     }
676
677     $item = (string) $item;
678
679     if (function_exists('mb_get_info') && null !== $charset = $env->getCharset()) {
680         return (string) mb_substr($item, $start, null === $length ? mb_strlen($item, $charset) - $start : $length, $charset);
681     }
682
683     return (string) (null === $length ? substr($item, $start) : substr($item, $start, $length));
684 }
685
686 /**
687  * Returns the first element of the item.
688  *
689  * @param Twig_Environment $env
690  * @param mixed            $item A variable
691  *
692  * @return mixed The first element of the item
693  */
694 function twig_first(Twig_Environment $env, $item)
695 {
696     $elements = twig_slice($env, $item, 0, 1, false);
697
698     return is_string($elements) ? $elements : current($elements);
699 }
700
701 /**
702  * Returns the last element of the item.
703  *
704  * @param Twig_Environment $env
705  * @param mixed            $item A variable
706  *
707  * @return mixed The last element of the item
708  */
709 function twig_last(Twig_Environment $env, $item)
710 {
711     $elements = twig_slice($env, $item, -1, 1, false);
712
713     return is_string($elements) ? $elements : current($elements);
714 }
715
716 /**
717  * Joins the values to a string.
718  *
719  * The separator between elements is an empty string per default, you can define it with the optional parameter.
720  *
721  * <pre>
722  *  {{ [1, 2, 3]|join('|') }}
723  *  {# returns 1|2|3 #}
724  *
725  *  {{ [1, 2, 3]|join }}
726  *  {# returns 123 #}
727  * </pre>
728  *
729  * @param array  $value An array
730  * @param string $glue  The separator
731  *
732  * @return string The concatenated string
733  */
734 function twig_join_filter($value, $glue = '')
735 {
736     if ($value instanceof Traversable) {
737         $value = iterator_to_array($value, false);
738     }
739
740     return implode($glue, (array) $value);
741 }
742
743 /**
744  * Splits the string into an array.
745  *
746  * <pre>
747  *  {{ "one,two,three"|split(',') }}
748  *  {# returns [one, two, three] #}
749  *
750  *  {{ "one,two,three,four,five"|split(',', 3) }}
751  *  {# returns [one, two, "three,four,five"] #}
752  *
753  *  {{ "123"|split('') }}
754  *  {# returns [1, 2, 3] #}
755  *
756  *  {{ "aabbcc"|split('', 2) }}
757  *  {# returns [aa, bb, cc] #}
758  * </pre>
759  *
760  * @param Twig_Environment $env
761  * @param string           $value     A string
762  * @param string           $delimiter The delimiter
763  * @param int              $limit     The limit
764  *
765  * @return array The split string as an array
766  */
767 function twig_split_filter(Twig_Environment $env, $value, $delimiter, $limit = null)
768 {
769     if (!empty($delimiter)) {
770         return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit);
771     }
772
773     if (!function_exists('mb_get_info') || null === $charset = $env->getCharset()) {
774         return str_split($value, null === $limit ? 1 : $limit);
775     }
776
777     if ($limit <= 1) {
778         return preg_split('/(?<!^)(?!$)/u', $value);
779     }
780
781     $length = mb_strlen($value, $charset);
782     if ($length < $limit) {
783         return array($value);
784     }
785
786     $r = array();
787     for ($i = 0; $i < $length; $i += $limit) {
788         $r[] = mb_substr($value, $i, $limit, $charset);
789     }
790
791     return $r;
792 }
793
794 // The '_default' filter is used internally to avoid using the ternary operator
795 // which costs a lot for big contexts (before PHP 5.4). So, on average,
796 // a function call is cheaper.
797 /**
798  * @internal
799  */
800 function _twig_default_filter($value, $default = '')
801 {
802     if (twig_test_empty($value)) {
803         return $default;
804     }
805
806     return $value;
807 }
808
809 /**
810  * Returns the keys for the given array.
811  *
812  * It is useful when you want to iterate over the keys of an array:
813  *
814  * <pre>
815  *  {% for key in array|keys %}
816  *      {# ... #}
817  *  {% endfor %}
818  * </pre>
819  *
820  * @param array $array An array
821  *
822  * @return array The keys
823  */
824 function twig_get_array_keys_filter($array)
825 {
826     if ($array instanceof Traversable) {
827         while ($array instanceof IteratorAggregate) {
828             $array = $array->getIterator();
829         }
830
831         if ($array instanceof Iterator) {
832             $keys = array();
833             $array->rewind();
834             while ($array->valid()) {
835                 $keys[] = $array->key();
836                 $array->next();
837             }
838
839             return $keys;
840         }
841
842         $keys = array();
843         foreach ($array as $key => $item) {
844             $keys[] = $key;
845         }
846
847         return $keys;
848     }
849
850     if (!is_array($array)) {
851         return array();
852     }
853
854     return array_keys($array);
855 }
856
857 /**
858  * Reverses a variable.
859  *
860  * @param Twig_Environment         $env
861  * @param array|Traversable|string $item         An array, a Traversable instance, or a string
862  * @param bool                     $preserveKeys Whether to preserve key or not
863  *
864  * @return mixed The reversed input
865  */
866 function twig_reverse_filter(Twig_Environment $env, $item, $preserveKeys = false)
867 {
868     if ($item instanceof Traversable) {
869         return array_reverse(iterator_to_array($item), $preserveKeys);
870     }
871
872     if (is_array($item)) {
873         return array_reverse($item, $preserveKeys);
874     }
875
876     if (null !== $charset = $env->getCharset()) {
877         $string = (string) $item;
878
879         if ('UTF-8' !== $charset) {
880             $item = twig_convert_encoding($string, 'UTF-8', $charset);
881         }
882
883         preg_match_all('/./us', $item, $matches);
884
885         $string = implode('', array_reverse($matches[0]));
886
887         if ('UTF-8' !== $charset) {
888             $string = twig_convert_encoding($string, $charset, 'UTF-8');
889         }
890
891         return $string;
892     }
893
894     return strrev((string) $item);
895 }
896
897 /**
898  * Sorts an array.
899  *
900  * @param array|Traversable $array
901  *
902  * @return array
903  */
904 function twig_sort_filter($array)
905 {
906     if ($array instanceof Traversable) {
907         $array = iterator_to_array($array);
908     } elseif (!is_array($array)) {
909         throw new Twig_Error_Runtime(sprintf('The sort filter only works with arrays or "Traversable", got "%s".', gettype($array)));
910     }
911
912     asort($array);
913
914     return $array;
915 }
916
917 /**
918  * @internal
919  */
920 function twig_in_filter($value, $compare)
921 {
922     if (is_array($compare)) {
923         return in_array($value, $compare, is_object($value) || is_resource($value));
924     } elseif (is_string($compare) && (is_string($value) || is_int($value) || is_float($value))) {
925         return '' === $value || false !== strpos($compare, (string) $value);
926     } elseif ($compare instanceof Traversable) {
927         if (is_object($value) || is_resource($value)) {
928             foreach ($compare as $item) {
929                 if ($item === $value) {
930                     return true;
931                 }
932             }
933         } else {
934             foreach ($compare as $item) {
935                 if ($item == $value) {
936                     return true;
937                 }
938             }
939         }
940
941         return false;
942     }
943
944     return false;
945 }
946
947 /**
948  * Returns a trimmed string.
949  *
950  * @return string
951  *
952  * @throws Twig_Error_Runtime When an invalid trimming side is used (not a string or not 'left', 'right', or 'both')
953  */
954 function twig_trim_filter($string, $characterMask = null, $side = 'both')
955 {
956     if (null === $characterMask) {
957         $characterMask = " \t\n\r\0\x0B";
958     }
959
960     switch ($side) {
961         case 'both':
962             return trim($string, $characterMask);
963         case 'left':
964             return ltrim($string, $characterMask);
965         case 'right':
966             return rtrim($string, $characterMask);
967         default:
968             throw new Twig_Error_Runtime('Trimming side must be "left", "right" or "both".');
969     }
970 }
971
972 /**
973  * Escapes a string.
974  *
975  * @param Twig_Environment $env
976  * @param mixed            $string     The value to be escaped
977  * @param string           $strategy   The escaping strategy
978  * @param string           $charset    The charset
979  * @param bool             $autoescape Whether the function is called by the auto-escaping feature (true) or by the developer (false)
980  *
981  * @return string
982  */
983 function twig_escape_filter(Twig_Environment $env, $string, $strategy = 'html', $charset = null, $autoescape = false)
984 {
985     if ($autoescape && $string instanceof Twig_Markup) {
986         return $string;
987     }
988
989     if (!is_string($string)) {
990         if (is_object($string) && method_exists($string, '__toString')) {
991             $string = (string) $string;
992         } elseif (in_array($strategy, array('html', 'js', 'css', 'html_attr', 'url'))) {
993             return $string;
994         }
995     }
996
997     if (null === $charset) {
998         $charset = $env->getCharset();
999     }
1000
1001     switch ($strategy) {
1002         case 'html':
1003             // see http://php.net/htmlspecialchars
1004
1005             // Using a static variable to avoid initializing the array
1006             // each time the function is called. Moving the declaration on the
1007             // top of the function slow downs other escaping strategies.
1008             static $htmlspecialcharsCharsets = array(
1009                 'ISO-8859-1' => true, 'ISO8859-1' => true,
1010                 'ISO-8859-15' => true, 'ISO8859-15' => true,
1011                 'utf-8' => true, 'UTF-8' => true,
1012                 'CP866' => true, 'IBM866' => true, '866' => true,
1013                 'CP1251' => true, 'WINDOWS-1251' => true, 'WIN-1251' => true,
1014                 '1251' => true,
1015                 'CP1252' => true, 'WINDOWS-1252' => true, '1252' => true,
1016                 'KOI8-R' => true, 'KOI8-RU' => true, 'KOI8R' => true,
1017                 'BIG5' => true, '950' => true,
1018                 'GB2312' => true, '936' => true,
1019                 'BIG5-HKSCS' => true,
1020                 'SHIFT_JIS' => true, 'SJIS' => true, '932' => true,
1021                 'EUC-JP' => true, 'EUCJP' => true,
1022                 'ISO8859-5' => true, 'ISO-8859-5' => true, 'MACROMAN' => true,
1023             );
1024
1025             if (isset($htmlspecialcharsCharsets[$charset])) {
1026                 return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
1027             }
1028
1029             if (isset($htmlspecialcharsCharsets[strtoupper($charset)])) {
1030                 // cache the lowercase variant for future iterations
1031                 $htmlspecialcharsCharsets[$charset] = true;
1032
1033                 return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
1034             }
1035
1036             $string = twig_convert_encoding($string, 'UTF-8', $charset);
1037             $string = htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
1038
1039             return twig_convert_encoding($string, $charset, 'UTF-8');
1040
1041         case 'js':
1042             // escape all non-alphanumeric characters
1043             // into their \xHH or \uHHHH representations
1044             if ('UTF-8' !== $charset) {
1045                 $string = twig_convert_encoding($string, 'UTF-8', $charset);
1046             }
1047
1048             if (0 == strlen($string) ? false : 1 !== preg_match('/^./su', $string)) {
1049                 throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
1050             }
1051
1052             $string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', '_twig_escape_js_callback', $string);
1053
1054             if ('UTF-8' !== $charset) {
1055                 $string = twig_convert_encoding($string, $charset, 'UTF-8');
1056             }
1057
1058             return $string;
1059
1060         case 'css':
1061             if ('UTF-8' !== $charset) {
1062                 $string = twig_convert_encoding($string, 'UTF-8', $charset);
1063             }
1064
1065             if (0 == strlen($string) ? false : 1 !== preg_match('/^./su', $string)) {
1066                 throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
1067             }
1068
1069             $string = preg_replace_callback('#[^a-zA-Z0-9]#Su', '_twig_escape_css_callback', $string);
1070
1071             if ('UTF-8' !== $charset) {
1072                 $string = twig_convert_encoding($string, $charset, 'UTF-8');
1073             }
1074
1075             return $string;
1076
1077         case 'html_attr':
1078             if ('UTF-8' !== $charset) {
1079                 $string = twig_convert_encoding($string, 'UTF-8', $charset);
1080             }
1081
1082             if (0 == strlen($string) ? false : 1 !== preg_match('/^./su', $string)) {
1083                 throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
1084             }
1085
1086             $string = preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su', '_twig_escape_html_attr_callback', $string);
1087
1088             if ('UTF-8' !== $charset) {
1089                 $string = twig_convert_encoding($string, $charset, 'UTF-8');
1090             }
1091
1092             return $string;
1093
1094         case 'url':
1095             if (PHP_VERSION_ID < 50300) {
1096                 return str_replace('%7E', '~', rawurlencode($string));
1097             }
1098
1099             return rawurlencode($string);
1100
1101         default:
1102             static $escapers;
1103
1104             if (null === $escapers) {
1105                 $escapers = $env->getExtension('Twig_Extension_Core')->getEscapers();
1106             }
1107
1108             if (isset($escapers[$strategy])) {
1109                 return call_user_func($escapers[$strategy], $env, $string, $charset);
1110             }
1111
1112             $validStrategies = implode(', ', array_merge(array('html', 'js', 'url', 'css', 'html_attr'), array_keys($escapers)));
1113
1114             throw new Twig_Error_Runtime(sprintf('Invalid escaping strategy "%s" (valid ones: %s).', $strategy, $validStrategies));
1115     }
1116 }
1117
1118 /**
1119  * @internal
1120  */
1121 function twig_escape_filter_is_safe(Twig_Node $filterArgs)
1122 {
1123     foreach ($filterArgs as $arg) {
1124         if ($arg instanceof Twig_Node_Expression_Constant) {
1125             return array($arg->getAttribute('value'));
1126         }
1127
1128         return array();
1129     }
1130
1131     return array('html');
1132 }
1133
1134 if (function_exists('mb_convert_encoding')) {
1135     function twig_convert_encoding($string, $to, $from)
1136     {
1137         return mb_convert_encoding($string, $to, $from);
1138     }
1139 } elseif (function_exists('iconv')) {
1140     function twig_convert_encoding($string, $to, $from)
1141     {
1142         return iconv($from, $to, $string);
1143     }
1144 } else {
1145     function twig_convert_encoding($string, $to, $from)
1146     {
1147         throw new Twig_Error_Runtime('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).');
1148     }
1149 }
1150
1151 function _twig_escape_js_callback($matches)
1152 {
1153     $char = $matches[0];
1154
1155     // \xHH
1156     if (!isset($char[1])) {
1157         return '\\x'.strtoupper(substr('00'.bin2hex($char), -2));
1158     }
1159
1160     // \uHHHH
1161     $char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8');
1162     $char = strtoupper(bin2hex($char));
1163
1164     if (4 >= strlen($char)) {
1165         return sprintf('\u%04s', $char);
1166     }
1167
1168     return sprintf('\u%04s\u%04s', substr($char, 0, -4), substr($char, -4));
1169 }
1170
1171 function _twig_escape_css_callback($matches)
1172 {
1173     $char = $matches[0];
1174
1175     // \xHH
1176     if (!isset($char[1])) {
1177         $hex = ltrim(strtoupper(bin2hex($char)), '0');
1178         if (0 === strlen($hex)) {
1179             $hex = '0';
1180         }
1181
1182         return '\\'.$hex.' ';
1183     }
1184
1185     // \uHHHH
1186     $char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8');
1187
1188     return '\\'.ltrim(strtoupper(bin2hex($char)), '0').' ';
1189 }
1190
1191 /**
1192  * This function is adapted from code coming from Zend Framework.
1193  *
1194  * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
1195  * @license   http://framework.zend.com/license/new-bsd New BSD License
1196  */
1197 function _twig_escape_html_attr_callback($matches)
1198 {
1199     /*
1200      * While HTML supports far more named entities, the lowest common denominator
1201      * has become HTML5's XML Serialisation which is restricted to the those named
1202      * entities that XML supports. Using HTML entities would result in this error:
1203      *     XML Parsing Error: undefined entity
1204      */
1205     static $entityMap = array(
1206         34 => 'quot', /* quotation mark */
1207         38 => 'amp',  /* ampersand */
1208         60 => 'lt',   /* less-than sign */
1209         62 => 'gt',   /* greater-than sign */
1210     );
1211
1212     $chr = $matches[0];
1213     $ord = ord($chr);
1214
1215     /*
1216      * The following replaces characters undefined in HTML with the
1217      * hex entity for the Unicode replacement character.
1218      */
1219     if (($ord <= 0x1f && "\t" != $chr && "\n" != $chr && "\r" != $chr) || ($ord >= 0x7f && $ord <= 0x9f)) {
1220         return '&#xFFFD;';
1221     }
1222
1223     /*
1224      * Check if the current character to escape has a name entity we should
1225      * replace it with while grabbing the hex value of the character.
1226      */
1227     if (1 == strlen($chr)) {
1228         $hex = strtoupper(substr('00'.bin2hex($chr), -2));
1229     } else {
1230         $chr = twig_convert_encoding($chr, 'UTF-16BE', 'UTF-8');
1231         $hex = strtoupper(substr('0000'.bin2hex($chr), -4));
1232     }
1233
1234     $int = hexdec($hex);
1235     if (array_key_exists($int, $entityMap)) {
1236         return sprintf('&%s;', $entityMap[$int]);
1237     }
1238
1239     /*
1240      * Per OWASP recommendations, we'll use hex entities for any other
1241      * characters where a named entity does not exist.
1242      */
1243     return sprintf('&#x%s;', $hex);
1244 }
1245
1246 // add multibyte extensions if possible
1247 if (function_exists('mb_get_info')) {
1248     /**
1249      * Returns the length of a variable.
1250      *
1251      * @param Twig_Environment $env
1252      * @param mixed            $thing A variable
1253      *
1254      * @return int The length of the value
1255      */
1256     function twig_length_filter(Twig_Environment $env, $thing)
1257     {
1258         if (null === $thing) {
1259             return 0;
1260         }
1261
1262         if (is_scalar($thing)) {
1263             return mb_strlen($thing, $env->getCharset());
1264         }
1265
1266         if ($thing instanceof \SimpleXMLElement) {
1267             return count($thing);
1268         }
1269
1270         if (is_object($thing) && method_exists($thing, '__toString') && !$thing instanceof \Countable) {
1271             return mb_strlen((string) $thing, $env->getCharset());
1272         }
1273
1274         if ($thing instanceof \Countable || is_array($thing)) {
1275             return count($thing);
1276         }
1277
1278         if ($thing instanceof \IteratorAggregate) {
1279             return iterator_count($thing);
1280         }
1281
1282         return 1;
1283     }
1284
1285     /**
1286      * Converts a string to uppercase.
1287      *
1288      * @param Twig_Environment $env
1289      * @param string           $string A string
1290      *
1291      * @return string The uppercased string
1292      */
1293     function twig_upper_filter(Twig_Environment $env, $string)
1294     {
1295         if (null !== $charset = $env->getCharset()) {
1296             return mb_strtoupper($string, $charset);
1297         }
1298
1299         return strtoupper($string);
1300     }
1301
1302     /**
1303      * Converts a string to lowercase.
1304      *
1305      * @param Twig_Environment $env
1306      * @param string           $string A string
1307      *
1308      * @return string The lowercased string
1309      */
1310     function twig_lower_filter(Twig_Environment $env, $string)
1311     {
1312         if (null !== $charset = $env->getCharset()) {
1313             return mb_strtolower($string, $charset);
1314         }
1315
1316         return strtolower($string);
1317     }
1318
1319     /**
1320      * Returns a titlecased string.
1321      *
1322      * @param Twig_Environment $env
1323      * @param string           $string A string
1324      *
1325      * @return string The titlecased string
1326      */
1327     function twig_title_string_filter(Twig_Environment $env, $string)
1328     {
1329         if (null !== $charset = $env->getCharset()) {
1330             return mb_convert_case($string, MB_CASE_TITLE, $charset);
1331         }
1332
1333         return ucwords(strtolower($string));
1334     }
1335
1336     /**
1337      * Returns a capitalized string.
1338      *
1339      * @param Twig_Environment $env
1340      * @param string           $string A string
1341      *
1342      * @return string The capitalized string
1343      */
1344     function twig_capitalize_string_filter(Twig_Environment $env, $string)
1345     {
1346         if (null !== $charset = $env->getCharset()) {
1347             return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).mb_strtolower(mb_substr($string, 1, mb_strlen($string, $charset), $charset), $charset);
1348         }
1349
1350         return ucfirst(strtolower($string));
1351     }
1352 }
1353 // and byte fallback
1354 else {
1355     /**
1356      * Returns the length of a variable.
1357      *
1358      * @param Twig_Environment $env
1359      * @param mixed            $thing A variable
1360      *
1361      * @return int The length of the value
1362      */
1363     function twig_length_filter(Twig_Environment $env, $thing)
1364     {
1365         if (null === $thing) {
1366             return 0;
1367         }
1368
1369         if (is_scalar($thing)) {
1370             return strlen($thing);
1371         }
1372
1373         if ($thing instanceof \SimpleXMLElement) {
1374             return count($thing);
1375         }
1376
1377         if (is_object($thing) && method_exists($thing, '__toString') && !$thing instanceof \Countable) {
1378             return strlen((string) $thing);
1379         }
1380
1381         if ($thing instanceof \Countable || is_array($thing)) {
1382             return count($thing);
1383         }
1384
1385         if ($thing instanceof \IteratorAggregate) {
1386             return iterator_count($thing);
1387         }
1388
1389         return 1;
1390     }
1391
1392     /**
1393      * Returns a titlecased string.
1394      *
1395      * @param Twig_Environment $env
1396      * @param string           $string A string
1397      *
1398      * @return string The titlecased string
1399      */
1400     function twig_title_string_filter(Twig_Environment $env, $string)
1401     {
1402         return ucwords(strtolower($string));
1403     }
1404
1405     /**
1406      * Returns a capitalized string.
1407      *
1408      * @param Twig_Environment $env
1409      * @param string           $string A string
1410      *
1411      * @return string The capitalized string
1412      */
1413     function twig_capitalize_string_filter(Twig_Environment $env, $string)
1414     {
1415         return ucfirst(strtolower($string));
1416     }
1417 }
1418
1419 /**
1420  * @internal
1421  */
1422 function twig_ensure_traversable($seq)
1423 {
1424     if ($seq instanceof Traversable || is_array($seq)) {
1425         return $seq;
1426     }
1427
1428     return array();
1429 }
1430
1431 /**
1432  * Checks if a variable is empty.
1433  *
1434  * <pre>
1435  * {# evaluates to true if the foo variable is null, false, or the empty string #}
1436  * {% if foo is empty %}
1437  *     {# ... #}
1438  * {% endif %}
1439  * </pre>
1440  *
1441  * @param mixed $value A variable
1442  *
1443  * @return bool true if the value is empty, false otherwise
1444  */
1445 function twig_test_empty($value)
1446 {
1447     if ($value instanceof Countable) {
1448         return 0 == count($value);
1449     }
1450
1451     if (is_object($value) && method_exists($value, '__toString')) {
1452         return '' === (string) $value;
1453     }
1454
1455     return '' === $value || false === $value || null === $value || array() === $value;
1456 }
1457
1458 /**
1459  * Checks if a variable is traversable.
1460  *
1461  * <pre>
1462  * {# evaluates to true if the foo variable is an array or a traversable object #}
1463  * {% if foo is iterable %}
1464  *     {# ... #}
1465  * {% endif %}
1466  * </pre>
1467  *
1468  * @param mixed $value A variable
1469  *
1470  * @return bool true if the value is traversable
1471  */
1472 function twig_test_iterable($value)
1473 {
1474     return $value instanceof Traversable || is_array($value);
1475 }
1476
1477 /**
1478  * Renders a template.
1479  *
1480  * @param Twig_Environment $env
1481  * @param array            $context
1482  * @param string|array     $template      The template to render or an array of templates to try consecutively
1483  * @param array            $variables     The variables to pass to the template
1484  * @param bool             $withContext
1485  * @param bool             $ignoreMissing Whether to ignore missing templates or not
1486  * @param bool             $sandboxed     Whether to sandbox the template or not
1487  *
1488  * @return string The rendered template
1489  */
1490 function twig_include(Twig_Environment $env, $context, $template, $variables = array(), $withContext = true, $ignoreMissing = false, $sandboxed = false)
1491 {
1492     $alreadySandboxed = false;
1493     $sandbox = null;
1494     if ($withContext) {
1495         $variables = array_merge($context, $variables);
1496     }
1497
1498     if ($isSandboxed = $sandboxed && $env->hasExtension('Twig_Extension_Sandbox')) {
1499         $sandbox = $env->getExtension('Twig_Extension_Sandbox');
1500         if (!$alreadySandboxed = $sandbox->isSandboxed()) {
1501             $sandbox->enableSandbox();
1502         }
1503     }
1504
1505     $result = null;
1506     try {
1507         $result = $env->resolveTemplate($template)->render($variables);
1508     } catch (Twig_Error_Loader $e) {
1509         if (!$ignoreMissing) {
1510             if ($isSandboxed && !$alreadySandboxed) {
1511                 $sandbox->disableSandbox();
1512             }
1513
1514             throw $e;
1515         }
1516     } catch (Throwable $e) {
1517         if ($isSandboxed && !$alreadySandboxed) {
1518             $sandbox->disableSandbox();
1519         }
1520
1521         throw $e;
1522     } catch (Exception $e) {
1523         if ($isSandboxed && !$alreadySandboxed) {
1524             $sandbox->disableSandbox();
1525         }
1526
1527         throw $e;
1528     }
1529
1530     if ($isSandboxed && !$alreadySandboxed) {
1531         $sandbox->disableSandbox();
1532     }
1533
1534     return $result;
1535 }
1536
1537 /**
1538  * Returns a template content without rendering it.
1539  *
1540  * @param Twig_Environment $env
1541  * @param string           $name          The template name
1542  * @param bool             $ignoreMissing Whether to ignore missing templates or not
1543  *
1544  * @return string The template source
1545  */
1546 function twig_source(Twig_Environment $env, $name, $ignoreMissing = false)
1547 {
1548     $loader = $env->getLoader();
1549     try {
1550         if (!$loader instanceof Twig_SourceContextLoaderInterface) {
1551             return $loader->getSource($name);
1552         } else {
1553             return $loader->getSourceContext($name)->getCode();
1554         }
1555     } catch (Twig_Error_Loader $e) {
1556         if (!$ignoreMissing) {
1557             throw $e;
1558         }
1559     }
1560 }
1561
1562 /**
1563  * Provides the ability to get constants from instances as well as class/global constants.
1564  *
1565  * @param string      $constant The name of the constant
1566  * @param null|object $object   The object to get the constant from
1567  *
1568  * @return string
1569  */
1570 function twig_constant($constant, $object = null)
1571 {
1572     if (null !== $object) {
1573         $constant = get_class($object).'::'.$constant;
1574     }
1575
1576     return constant($constant);
1577 }
1578
1579 /**
1580  * Checks if a constant exists.
1581  *
1582  * @param string      $constant The name of the constant
1583  * @param null|object $object   The object to get the constant from
1584  *
1585  * @return bool
1586  */
1587 function twig_constant_is_defined($constant, $object = null)
1588 {
1589     if (null !== $object) {
1590         $constant = get_class($object).'::'.$constant;
1591     }
1592
1593     return defined($constant);
1594 }
1595
1596 /**
1597  * Batches item.
1598  *
1599  * @param array $items An array of items
1600  * @param int   $size  The size of the batch
1601  * @param mixed $fill  A value used to fill missing items
1602  *
1603  * @return array
1604  */
1605 function twig_array_batch($items, $size, $fill = null)
1606 {
1607     if ($items instanceof Traversable) {
1608         $items = iterator_to_array($items, false);
1609     }
1610
1611     $size = ceil($size);
1612
1613     $result = array_chunk($items, $size, true);
1614
1615     if (null !== $fill && !empty($result)) {
1616         $last = count($result) - 1;
1617         if ($fillCount = $size - count($result[$last])) {
1618             $result[$last] = array_merge(
1619                 $result[$last],
1620                 array_fill(0, $fillCount, $fill)
1621             );
1622         }
1623     }
1624
1625     return $result;
1626 }
1627
1628 class_alias('Twig_Extension_Core', 'Twig\Extension\CoreExtension', false);