Updated Drupal to 8.6. This goes with the following updates because it's possible...
[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 https://secure.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 https://secure.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 \x 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     /*
1156      * A few characters have short escape sequences in JSON and JavaScript.
1157      * Escape sequences supported only by JavaScript, not JSON, are ommitted.
1158      * \" is also supported but omitted, because the resulting string is not HTML safe.
1159      */
1160     static $shortMap = array(
1161         '\\' => '\\\\',
1162         '/' => '\\/',
1163         "\x08" => '\b',
1164         "\x0C" => '\f',
1165         "\x0A" => '\n',
1166         "\x0D" => '\r',
1167         "\x09" => '\t',
1168     );
1169
1170     if (isset($shortMap[$char])) {
1171         return $shortMap[$char];
1172     }
1173
1174     // \uHHHH
1175     $char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8');
1176     $char = strtoupper(bin2hex($char));
1177
1178     if (4 >= strlen($char)) {
1179         return sprintf('\u%04s', $char);
1180     }
1181
1182     return sprintf('\u%04s\u%04s', substr($char, 0, -4), substr($char, -4));
1183 }
1184
1185 function _twig_escape_css_callback($matches)
1186 {
1187     $char = $matches[0];
1188
1189     // \xHH
1190     if (!isset($char[1])) {
1191         $hex = ltrim(strtoupper(bin2hex($char)), '0');
1192         if (0 === strlen($hex)) {
1193             $hex = '0';
1194         }
1195
1196         return '\\'.$hex.' ';
1197     }
1198
1199     // \uHHHH
1200     $char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8');
1201
1202     return '\\'.ltrim(strtoupper(bin2hex($char)), '0').' ';
1203 }
1204
1205 /**
1206  * This function is adapted from code coming from Zend Framework.
1207  *
1208  * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (https://www.zend.com)
1209  * @license   https://framework.zend.com/license/new-bsd New BSD License
1210  */
1211 function _twig_escape_html_attr_callback($matches)
1212 {
1213     /*
1214      * While HTML supports far more named entities, the lowest common denominator
1215      * has become HTML5's XML Serialisation which is restricted to the those named
1216      * entities that XML supports. Using HTML entities would result in this error:
1217      *     XML Parsing Error: undefined entity
1218      */
1219     static $entityMap = array(
1220         34 => 'quot', /* quotation mark */
1221         38 => 'amp',  /* ampersand */
1222         60 => 'lt',   /* less-than sign */
1223         62 => 'gt',   /* greater-than sign */
1224     );
1225
1226     $chr = $matches[0];
1227     $ord = ord($chr);
1228
1229     /*
1230      * The following replaces characters undefined in HTML with the
1231      * hex entity for the Unicode replacement character.
1232      */
1233     if (($ord <= 0x1f && "\t" != $chr && "\n" != $chr && "\r" != $chr) || ($ord >= 0x7f && $ord <= 0x9f)) {
1234         return '&#xFFFD;';
1235     }
1236
1237     /*
1238      * Check if the current character to escape has a name entity we should
1239      * replace it with while grabbing the hex value of the character.
1240      */
1241     if (1 == strlen($chr)) {
1242         $hex = strtoupper(substr('00'.bin2hex($chr), -2));
1243     } else {
1244         $chr = twig_convert_encoding($chr, 'UTF-16BE', 'UTF-8');
1245         $hex = strtoupper(substr('0000'.bin2hex($chr), -4));
1246     }
1247
1248     $int = hexdec($hex);
1249     if (array_key_exists($int, $entityMap)) {
1250         return sprintf('&%s;', $entityMap[$int]);
1251     }
1252
1253     /*
1254      * Per OWASP recommendations, we'll use hex entities for any other
1255      * characters where a named entity does not exist.
1256      */
1257     return sprintf('&#x%s;', $hex);
1258 }
1259
1260 // add multibyte extensions if possible
1261 if (function_exists('mb_get_info')) {
1262     /**
1263      * Returns the length of a variable.
1264      *
1265      * @param Twig_Environment $env
1266      * @param mixed            $thing A variable
1267      *
1268      * @return int The length of the value
1269      */
1270     function twig_length_filter(Twig_Environment $env, $thing)
1271     {
1272         if (null === $thing) {
1273             return 0;
1274         }
1275
1276         if (is_scalar($thing)) {
1277             return mb_strlen($thing, $env->getCharset());
1278         }
1279
1280         if ($thing instanceof \SimpleXMLElement) {
1281             return count($thing);
1282         }
1283
1284         if (is_object($thing) && method_exists($thing, '__toString') && !$thing instanceof \Countable) {
1285             return mb_strlen((string) $thing, $env->getCharset());
1286         }
1287
1288         if ($thing instanceof \Countable || is_array($thing)) {
1289             return count($thing);
1290         }
1291
1292         if ($thing instanceof \IteratorAggregate) {
1293             return iterator_count($thing);
1294         }
1295
1296         return 1;
1297     }
1298
1299     /**
1300      * Converts a string to uppercase.
1301      *
1302      * @param Twig_Environment $env
1303      * @param string           $string A string
1304      *
1305      * @return string The uppercased string
1306      */
1307     function twig_upper_filter(Twig_Environment $env, $string)
1308     {
1309         if (null !== $charset = $env->getCharset()) {
1310             return mb_strtoupper($string, $charset);
1311         }
1312
1313         return strtoupper($string);
1314     }
1315
1316     /**
1317      * Converts a string to lowercase.
1318      *
1319      * @param Twig_Environment $env
1320      * @param string           $string A string
1321      *
1322      * @return string The lowercased string
1323      */
1324     function twig_lower_filter(Twig_Environment $env, $string)
1325     {
1326         if (null !== $charset = $env->getCharset()) {
1327             return mb_strtolower($string, $charset);
1328         }
1329
1330         return strtolower($string);
1331     }
1332
1333     /**
1334      * Returns a titlecased string.
1335      *
1336      * @param Twig_Environment $env
1337      * @param string           $string A string
1338      *
1339      * @return string The titlecased string
1340      */
1341     function twig_title_string_filter(Twig_Environment $env, $string)
1342     {
1343         if (null !== $charset = $env->getCharset()) {
1344             return mb_convert_case($string, MB_CASE_TITLE, $charset);
1345         }
1346
1347         return ucwords(strtolower($string));
1348     }
1349
1350     /**
1351      * Returns a capitalized string.
1352      *
1353      * @param Twig_Environment $env
1354      * @param string           $string A string
1355      *
1356      * @return string The capitalized string
1357      */
1358     function twig_capitalize_string_filter(Twig_Environment $env, $string)
1359     {
1360         if (null !== $charset = $env->getCharset()) {
1361             return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).mb_strtolower(mb_substr($string, 1, mb_strlen($string, $charset), $charset), $charset);
1362         }
1363
1364         return ucfirst(strtolower($string));
1365     }
1366 }
1367 // and byte fallback
1368 else {
1369     /**
1370      * Returns the length of a variable.
1371      *
1372      * @param Twig_Environment $env
1373      * @param mixed            $thing A variable
1374      *
1375      * @return int The length of the value
1376      */
1377     function twig_length_filter(Twig_Environment $env, $thing)
1378     {
1379         if (null === $thing) {
1380             return 0;
1381         }
1382
1383         if (is_scalar($thing)) {
1384             return strlen($thing);
1385         }
1386
1387         if ($thing instanceof \SimpleXMLElement) {
1388             return count($thing);
1389         }
1390
1391         if (is_object($thing) && method_exists($thing, '__toString') && !$thing instanceof \Countable) {
1392             return strlen((string) $thing);
1393         }
1394
1395         if ($thing instanceof \Countable || is_array($thing)) {
1396             return count($thing);
1397         }
1398
1399         if ($thing instanceof \IteratorAggregate) {
1400             return iterator_count($thing);
1401         }
1402
1403         return 1;
1404     }
1405
1406     /**
1407      * Returns a titlecased string.
1408      *
1409      * @param Twig_Environment $env
1410      * @param string           $string A string
1411      *
1412      * @return string The titlecased string
1413      */
1414     function twig_title_string_filter(Twig_Environment $env, $string)
1415     {
1416         return ucwords(strtolower($string));
1417     }
1418
1419     /**
1420      * Returns a capitalized string.
1421      *
1422      * @param Twig_Environment $env
1423      * @param string           $string A string
1424      *
1425      * @return string The capitalized string
1426      */
1427     function twig_capitalize_string_filter(Twig_Environment $env, $string)
1428     {
1429         return ucfirst(strtolower($string));
1430     }
1431 }
1432
1433 /**
1434  * @internal
1435  */
1436 function twig_ensure_traversable($seq)
1437 {
1438     if ($seq instanceof Traversable || is_array($seq)) {
1439         return $seq;
1440     }
1441
1442     return array();
1443 }
1444
1445 /**
1446  * Checks if a variable is empty.
1447  *
1448  * <pre>
1449  * {# evaluates to true if the foo variable is null, false, or the empty string #}
1450  * {% if foo is empty %}
1451  *     {# ... #}
1452  * {% endif %}
1453  * </pre>
1454  *
1455  * @param mixed $value A variable
1456  *
1457  * @return bool true if the value is empty, false otherwise
1458  */
1459 function twig_test_empty($value)
1460 {
1461     if ($value instanceof Countable) {
1462         return 0 == count($value);
1463     }
1464
1465     if (is_object($value) && method_exists($value, '__toString')) {
1466         return '' === (string) $value;
1467     }
1468
1469     return '' === $value || false === $value || null === $value || array() === $value;
1470 }
1471
1472 /**
1473  * Checks if a variable is traversable.
1474  *
1475  * <pre>
1476  * {# evaluates to true if the foo variable is an array or a traversable object #}
1477  * {% if foo is iterable %}
1478  *     {# ... #}
1479  * {% endif %}
1480  * </pre>
1481  *
1482  * @param mixed $value A variable
1483  *
1484  * @return bool true if the value is traversable
1485  */
1486 function twig_test_iterable($value)
1487 {
1488     return $value instanceof Traversable || is_array($value);
1489 }
1490
1491 /**
1492  * Renders a template.
1493  *
1494  * @param Twig_Environment $env
1495  * @param array            $context
1496  * @param string|array     $template      The template to render or an array of templates to try consecutively
1497  * @param array            $variables     The variables to pass to the template
1498  * @param bool             $withContext
1499  * @param bool             $ignoreMissing Whether to ignore missing templates or not
1500  * @param bool             $sandboxed     Whether to sandbox the template or not
1501  *
1502  * @return string The rendered template
1503  */
1504 function twig_include(Twig_Environment $env, $context, $template, $variables = array(), $withContext = true, $ignoreMissing = false, $sandboxed = false)
1505 {
1506     $alreadySandboxed = false;
1507     $sandbox = null;
1508     if ($withContext) {
1509         $variables = array_merge($context, $variables);
1510     }
1511
1512     if ($isSandboxed = $sandboxed && $env->hasExtension('Twig_Extension_Sandbox')) {
1513         $sandbox = $env->getExtension('Twig_Extension_Sandbox');
1514         if (!$alreadySandboxed = $sandbox->isSandboxed()) {
1515             $sandbox->enableSandbox();
1516         }
1517     }
1518
1519     $result = null;
1520     try {
1521         $result = $env->resolveTemplate($template)->render($variables);
1522     } catch (Twig_Error_Loader $e) {
1523         if (!$ignoreMissing) {
1524             if ($isSandboxed && !$alreadySandboxed) {
1525                 $sandbox->disableSandbox();
1526             }
1527
1528             throw $e;
1529         }
1530     } catch (Throwable $e) {
1531         if ($isSandboxed && !$alreadySandboxed) {
1532             $sandbox->disableSandbox();
1533         }
1534
1535         throw $e;
1536     } catch (Exception $e) {
1537         if ($isSandboxed && !$alreadySandboxed) {
1538             $sandbox->disableSandbox();
1539         }
1540
1541         throw $e;
1542     }
1543
1544     if ($isSandboxed && !$alreadySandboxed) {
1545         $sandbox->disableSandbox();
1546     }
1547
1548     return $result;
1549 }
1550
1551 /**
1552  * Returns a template content without rendering it.
1553  *
1554  * @param Twig_Environment $env
1555  * @param string           $name          The template name
1556  * @param bool             $ignoreMissing Whether to ignore missing templates or not
1557  *
1558  * @return string The template source
1559  */
1560 function twig_source(Twig_Environment $env, $name, $ignoreMissing = false)
1561 {
1562     $loader = $env->getLoader();
1563     try {
1564         if (!$loader instanceof Twig_SourceContextLoaderInterface) {
1565             return $loader->getSource($name);
1566         } else {
1567             return $loader->getSourceContext($name)->getCode();
1568         }
1569     } catch (Twig_Error_Loader $e) {
1570         if (!$ignoreMissing) {
1571             throw $e;
1572         }
1573     }
1574 }
1575
1576 /**
1577  * Provides the ability to get constants from instances as well as class/global constants.
1578  *
1579  * @param string      $constant The name of the constant
1580  * @param null|object $object   The object to get the constant from
1581  *
1582  * @return string
1583  */
1584 function twig_constant($constant, $object = null)
1585 {
1586     if (null !== $object) {
1587         $constant = get_class($object).'::'.$constant;
1588     }
1589
1590     return constant($constant);
1591 }
1592
1593 /**
1594  * Checks if a constant exists.
1595  *
1596  * @param string      $constant The name of the constant
1597  * @param null|object $object   The object to get the constant from
1598  *
1599  * @return bool
1600  */
1601 function twig_constant_is_defined($constant, $object = null)
1602 {
1603     if (null !== $object) {
1604         $constant = get_class($object).'::'.$constant;
1605     }
1606
1607     return defined($constant);
1608 }
1609
1610 /**
1611  * Batches item.
1612  *
1613  * @param array $items An array of items
1614  * @param int   $size  The size of the batch
1615  * @param mixed $fill  A value used to fill missing items
1616  *
1617  * @return array
1618  */
1619 function twig_array_batch($items, $size, $fill = null)
1620 {
1621     if ($items instanceof Traversable) {
1622         $items = iterator_to_array($items, false);
1623     }
1624
1625     $size = ceil($size);
1626
1627     $result = array_chunk($items, $size, true);
1628
1629     if (null !== $fill && !empty($result)) {
1630         $last = count($result) - 1;
1631         if ($fillCount = $size - count($result[$last])) {
1632             $result[$last] = array_merge(
1633                 $result[$last],
1634                 array_fill(0, $fillCount, $fill)
1635             );
1636         }
1637     }
1638
1639     return $result;
1640 }
1641
1642 class_alias('Twig_Extension_Core', 'Twig\Extension\CoreExtension', false);