vendor/twig/twig/lib/Twig/Extension/Core.php line 1521

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