PK S JΘ! % lib/Twig/NodeVisitor/SafeAnalysis.phpnu W+A safeVars = $safeVars; } public function getSafe(Twig_NodeInterface $node) { $hash = spl_object_hash($node); if (!isset($this->data[$hash])) { return; } foreach ($this->data[$hash] as $bucket) { if ($bucket['key'] !== $node) { continue; } if (in_array('html_attr', $bucket['value'])) { $bucket['value'][] = 'html'; } return $bucket['value']; } } protected function setSafe(Twig_NodeInterface $node, array $safe) { $hash = spl_object_hash($node); if (isset($this->data[$hash])) { foreach ($this->data[$hash] as &$bucket) { if ($bucket['key'] === $node) { $bucket['value'] = $safe; return; } } } $this->data[$hash][] = array( 'key' => $node, 'value' => $safe, ); } protected function doEnterNode(Twig_Node $node, Twig_Environment $env) { return $node; } protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Expression_Constant) { // constants are marked safe for all $this->setSafe($node, array('all')); } elseif ($node instanceof Twig_Node_Expression_BlockReference) { // blocks are safe by definition $this->setSafe($node, array('all')); } elseif ($node instanceof Twig_Node_Expression_Parent) { // parent block is safe by definition $this->setSafe($node, array('all')); } elseif ($node instanceof Twig_Node_Expression_Conditional) { // intersect safeness of both operands $safe = $this->intersectSafe($this->getSafe($node->getNode('expr2')), $this->getSafe($node->getNode('expr3'))); $this->setSafe($node, $safe); } elseif ($node instanceof Twig_Node_Expression_Filter) { // filter expression is safe when the filter is safe $name = $node->getNode('filter')->getAttribute('value'); $args = $node->getNode('arguments'); if (false !== $filter = $env->getFilter($name)) { $safe = $filter->getSafe($args); if (null === $safe) { $safe = $this->intersectSafe($this->getSafe($node->getNode('node')), $filter->getPreservesSafety()); } $this->setSafe($node, $safe); } else { $this->setSafe($node, array()); } } elseif ($node instanceof Twig_Node_Expression_Function) { // function expression is safe when the function is safe $name = $node->getAttribute('name'); $args = $node->getNode('arguments'); $function = $env->getFunction($name); if (false !== $function) { $this->setSafe($node, $function->getSafe($args)); } else { $this->setSafe($node, array()); } } elseif ($node instanceof Twig_Node_Expression_MethodCall) { if ($node->getAttribute('safe')) { $this->setSafe($node, array('all')); } else { $this->setSafe($node, array()); } } elseif ($node instanceof Twig_Node_Expression_GetAttr && $node->getNode('node') instanceof Twig_Node_Expression_Name) { $name = $node->getNode('node')->getAttribute('name'); // attributes on template instances are safe if ('_self' == $name || in_array($name, $this->safeVars)) { $this->setSafe($node, array('all')); } else { $this->setSafe($node, array()); } } else { $this->setSafe($node, array()); } return $node; } protected function intersectSafe(array $a = null, array $b = null) { if (null === $a || null === $b) { return array(); } if (in_array('all', $a)) { return $b; } if (in_array('all', $b)) { return $a; } return array_intersect($a, $b); } public function getPriority() { return 0; } } PK S J9 lib/Twig/NodeVisitor/Sandbox.phpnu W+A */ class Twig_NodeVisitor_Sandbox extends Twig_BaseNodeVisitor { protected $inAModule = false; protected $tags; protected $filters; protected $functions; protected function doEnterNode(Twig_Node $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Module) { $this->inAModule = true; $this->tags = array(); $this->filters = array(); $this->functions = array(); return $node; } elseif ($this->inAModule) { // look for tags if ($node->getNodeTag() && !isset($this->tags[$node->getNodeTag()])) { $this->tags[$node->getNodeTag()] = $node; } // look for filters if ($node instanceof Twig_Node_Expression_Filter && !isset($this->filters[$node->getNode('filter')->getAttribute('value')])) { $this->filters[$node->getNode('filter')->getAttribute('value')] = $node; } // look for functions if ($node instanceof Twig_Node_Expression_Function && !isset($this->functions[$node->getAttribute('name')])) { $this->functions[$node->getAttribute('name')] = $node; } // wrap print to check __toString() calls if ($node instanceof Twig_Node_Print) { return new Twig_Node_SandboxedPrint($node->getNode('expr'), $node->getTemplateLine(), $node->getNodeTag()); } } return $node; } protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Module) { $this->inAModule = false; $node->setNode('display_start', new Twig_Node(array(new Twig_Node_CheckSecurity($this->filters, $this->tags, $this->functions), $node->getNode('display_start')))); } return $node; } public function getPriority() { return 0; } } PK S JD D lib/Twig/NodeVisitor/Escaper.phpnu W+A */ class Twig_NodeVisitor_Escaper extends Twig_BaseNodeVisitor { protected $statusStack = array(); protected $blocks = array(); protected $safeAnalysis; protected $traverser; protected $defaultStrategy = false; protected $safeVars = array(); public function __construct() { $this->safeAnalysis = new Twig_NodeVisitor_SafeAnalysis(); } protected function doEnterNode(Twig_Node $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Module) { if ($env->hasExtension('Twig_Extension_Escaper') && $defaultStrategy = $env->getExtension('Twig_Extension_Escaper')->getDefaultStrategy($node->getTemplateName())) { $this->defaultStrategy = $defaultStrategy; } $this->safeVars = array(); $this->blocks = array(); } elseif ($node instanceof Twig_Node_AutoEscape) { $this->statusStack[] = $node->getAttribute('value'); } elseif ($node instanceof Twig_Node_Block) { $this->statusStack[] = isset($this->blocks[$node->getAttribute('name')]) ? $this->blocks[$node->getAttribute('name')] : $this->needEscaping($env); } elseif ($node instanceof Twig_Node_Import) { $this->safeVars[] = $node->getNode('var')->getAttribute('name'); } return $node; } protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Module) { $this->defaultStrategy = false; $this->safeVars = array(); $this->blocks = array(); } elseif ($node instanceof Twig_Node_Expression_Filter) { return $this->preEscapeFilterNode($node, $env); } elseif ($node instanceof Twig_Node_Print) { return $this->escapePrintNode($node, $env, $this->needEscaping($env)); } if ($node instanceof Twig_Node_AutoEscape || $node instanceof Twig_Node_Block) { array_pop($this->statusStack); } elseif ($node instanceof Twig_Node_BlockReference) { $this->blocks[$node->getAttribute('name')] = $this->needEscaping($env); } return $node; } protected function escapePrintNode(Twig_Node_Print $node, Twig_Environment $env, $type) { if (false === $type) { return $node; } $expression = $node->getNode('expr'); if ($this->isSafeFor($type, $expression, $env)) { return $node; } $class = get_class($node); return new $class( $this->getEscaperFilter($type, $expression), $node->getTemplateLine() ); } protected function preEscapeFilterNode(Twig_Node_Expression_Filter $filter, Twig_Environment $env) { $name = $filter->getNode('filter')->getAttribute('value'); $type = $env->getFilter($name)->getPreEscape(); if (null === $type) { return $filter; } $node = $filter->getNode('node'); if ($this->isSafeFor($type, $node, $env)) { return $filter; } $filter->setNode('node', $this->getEscaperFilter($type, $node)); return $filter; } protected function isSafeFor($type, Twig_NodeInterface $expression, $env) { $safe = $this->safeAnalysis->getSafe($expression); if (null === $safe) { if (null === $this->traverser) { $this->traverser = new Twig_NodeTraverser($env, array($this->safeAnalysis)); } $this->safeAnalysis->setSafeVars($this->safeVars); $this->traverser->traverse($expression); $safe = $this->safeAnalysis->getSafe($expression); } return in_array($type, $safe) || in_array('all', $safe); } protected function needEscaping(Twig_Environment $env) { if (count($this->statusStack)) { return $this->statusStack[count($this->statusStack) - 1]; } return $this->defaultStrategy ? $this->defaultStrategy : false; } protected function getEscaperFilter($type, Twig_NodeInterface $node) { $line = $node->getTemplateLine(); $name = new Twig_Node_Expression_Constant('escape', $line); $args = new Twig_Node(array(new Twig_Node_Expression_Constant((string) $type, $line), new Twig_Node_Expression_Constant(null, $line), new Twig_Node_Expression_Constant(true, $line))); return new Twig_Node_Expression_Filter($node, $name, $args, $line); } public function getPriority() { return 0; } } PK S J"'! '! " lib/Twig/NodeVisitor/Optimizer.phpnu W+A */ class Twig_NodeVisitor_Optimizer extends Twig_BaseNodeVisitor { const OPTIMIZE_ALL = -1; const OPTIMIZE_NONE = 0; const OPTIMIZE_FOR = 2; const OPTIMIZE_RAW_FILTER = 4; const OPTIMIZE_VAR_ACCESS = 8; protected $loops = array(); protected $loopsTargets = array(); protected $optimizers; protected $prependedNodes = array(); protected $inABody = false; /** * @param int $optimizers The optimizer mode */ public function __construct($optimizers = -1) { if (!is_int($optimizers) || $optimizers > (self::OPTIMIZE_FOR | self::OPTIMIZE_RAW_FILTER | self::OPTIMIZE_VAR_ACCESS)) { throw new InvalidArgumentException(sprintf('Optimizer mode "%s" is not valid.', $optimizers)); } $this->optimizers = $optimizers; } protected function doEnterNode(Twig_Node $node, Twig_Environment $env) { if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR & $this->optimizers)) { $this->enterOptimizeFor($node, $env); } if (PHP_VERSION_ID < 50400 && self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) && !$env->isStrictVariables() && !$env->hasExtension('Twig_Extension_Sandbox')) { if ($this->inABody) { if (!$node instanceof Twig_Node_Expression) { if (get_class($node) !== 'Twig_Node') { array_unshift($this->prependedNodes, array()); } } else { $node = $this->optimizeVariables($node, $env); } } elseif ($node instanceof Twig_Node_Body) { $this->inABody = true; } } return $node; } protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) { $expression = $node instanceof Twig_Node_Expression; if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR & $this->optimizers)) { $this->leaveOptimizeFor($node, $env); } if (self::OPTIMIZE_RAW_FILTER === (self::OPTIMIZE_RAW_FILTER & $this->optimizers)) { $node = $this->optimizeRawFilter($node, $env); } $node = $this->optimizePrintNode($node, $env); if (self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) && !$env->isStrictVariables() && !$env->hasExtension('Twig_Extension_Sandbox')) { if ($node instanceof Twig_Node_Body) { $this->inABody = false; } elseif ($this->inABody) { if (!$expression && get_class($node) !== 'Twig_Node' && $prependedNodes = array_shift($this->prependedNodes)) { $nodes = array(); foreach (array_unique($prependedNodes) as $name) { $nodes[] = new Twig_Node_SetTemp($name, $node->getTemplateLine()); } $nodes[] = $node; $node = new Twig_Node($nodes); } } } return $node; } protected function optimizeVariables(Twig_NodeInterface $node, Twig_Environment $env) { if ('Twig_Node_Expression_Name' === get_class($node) && $node->isSimple()) { $this->prependedNodes[0][] = $node->getAttribute('name'); return new Twig_Node_Expression_TempName($node->getAttribute('name'), $node->getTemplateLine()); } return $node; } /** * Optimizes print nodes. * * It replaces: * * * "echo $this->render(Parent)Block()" with "$this->display(Parent)Block()" * * @return Twig_NodeInterface */ protected function optimizePrintNode(Twig_NodeInterface $node, Twig_Environment $env) { if (!$node instanceof Twig_Node_Print) { return $node; } $exprNode = $node->getNode('expr'); if ( $exprNode instanceof Twig_Node_Expression_BlockReference || $exprNode instanceof Twig_Node_Expression_Parent ) { $exprNode->setAttribute('output', true); return $exprNode; } return $node; } /** * Removes "raw" filters. * * @return Twig_NodeInterface */ protected function optimizeRawFilter(Twig_NodeInterface $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Expression_Filter && 'raw' == $node->getNode('filter')->getAttribute('value')) { return $node->getNode('node'); } return $node; } /** * Optimizes "for" tag by removing the "loop" variable creation whenever possible. */ protected function enterOptimizeFor(Twig_NodeInterface $node, Twig_Environment $env) { if ($node instanceof Twig_Node_For) { // disable the loop variable by default $node->setAttribute('with_loop', false); array_unshift($this->loops, $node); array_unshift($this->loopsTargets, $node->getNode('value_target')->getAttribute('name')); array_unshift($this->loopsTargets, $node->getNode('key_target')->getAttribute('name')); } elseif (!$this->loops) { // we are outside a loop return; } // when do we need to add the loop variable back? // the loop variable is referenced for the current loop elseif ($node instanceof Twig_Node_Expression_Name && 'loop' === $node->getAttribute('name')) { $node->setAttribute('always_defined', true); $this->addLoopToCurrent(); } // optimize access to loop targets elseif ($node instanceof Twig_Node_Expression_Name && in_array($node->getAttribute('name'), $this->loopsTargets)) { $node->setAttribute('always_defined', true); } // block reference elseif ($node instanceof Twig_Node_BlockReference || $node instanceof Twig_Node_Expression_BlockReference) { $this->addLoopToCurrent(); } // include without the only attribute elseif ($node instanceof Twig_Node_Include && !$node->getAttribute('only')) { $this->addLoopToAll(); } // include function without the with_context=false parameter elseif ($node instanceof Twig_Node_Expression_Function && 'include' === $node->getAttribute('name') && (!$node->getNode('arguments')->hasNode('with_context') || false !== $node->getNode('arguments')->getNode('with_context')->getAttribute('value') ) ) { $this->addLoopToAll(); } // the loop variable is referenced via an attribute elseif ($node instanceof Twig_Node_Expression_GetAttr && (!$node->getNode('attribute') instanceof Twig_Node_Expression_Constant || 'parent' === $node->getNode('attribute')->getAttribute('value') ) && (true === $this->loops[0]->getAttribute('with_loop') || ($node->getNode('node') instanceof Twig_Node_Expression_Name && 'loop' === $node->getNode('node')->getAttribute('name') ) ) ) { $this->addLoopToAll(); } } /** * Optimizes "for" tag by removing the "loop" variable creation whenever possible. */ protected function leaveOptimizeFor(Twig_NodeInterface $node, Twig_Environment $env) { if ($node instanceof Twig_Node_For) { array_shift($this->loops); array_shift($this->loopsTargets); array_shift($this->loopsTargets); } } protected function addLoopToCurrent() { $this->loops[0]->setAttribute('with_loop', true); } protected function addLoopToAll() { foreach ($this->loops as $loop) { $loop->setAttribute('with_loop', true); } } public function getPriority() { return 255; } } PK S J# lib/Twig/Autoloader.phpnu W+A * * @deprecated since 1.21 and will be removed in 2.0. Use Composer instead. 2.0. */ class Twig_Autoloader { /** * Registers Twig_Autoloader as an SPL autoloader. * * @param bool $prepend whether to prepend the autoloader or not */ public static function register($prepend = false) { @trigger_error('Using Twig_Autoloader is deprecated since version 1.21. Use Composer instead.', E_USER_DEPRECATED); if (PHP_VERSION_ID < 50300) { spl_autoload_register(array(__CLASS__, 'autoload')); } else { spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend); } } /** * Handles autoloading of classes. * * @param string $class a class name */ public static function autoload($class) { if (0 !== strpos($class, 'Twig')) { return; } if (is_file($file = dirname(__FILE__).'/../'.str_replace(array('_', "\0"), array('/', ''), $class).'.php')) { require $file; } } } PK S Jbr2 r2 lib/Twig/Parser.phpnu W+A */ class Twig_Parser implements Twig_ParserInterface { protected $stack = array(); protected $stream; protected $parent; protected $handlers; protected $visitors; protected $expressionParser; protected $blocks; protected $blockStack; protected $macros; protected $env; protected $reservedMacroNames; protected $importedSymbols; protected $traits; protected $embeddedTemplates = array(); public function __construct(Twig_Environment $env) { $this->env = $env; } /** * @deprecated since 1.27 (to be removed in 2.0) */ public function getEnvironment() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED); return $this->env; } public function getVarName() { return sprintf('__internal_%s', hash('sha256', uniqid(mt_rand(), true), false)); } /** * @deprecated since 1.27 (to be removed in 2.0). Use $parser->getStream()->getSourceContext()->getPath() instead. */ public function getFilename() { @trigger_error(sprintf('The "%s" method is deprecated since version 1.27 and will be removed in 2.0. Use $parser->getStream()->getSourceContext()->getPath() instead.', __METHOD__), E_USER_DEPRECATED); return $this->stream->getSourceContext()->getName(); } public function parse(Twig_TokenStream $stream, $test = null, $dropNeedle = false) { // push all variables into the stack to keep the current state of the parser // using get_object_vars() instead of foreach would lead to https://bugs.php.net/71336 // This hack can be removed when min version if PHP 7.0 $vars = array(); foreach ($this as $k => $v) { $vars[$k] = $v; } unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames']); $this->stack[] = $vars; // tag handlers if (null === $this->handlers) { $this->handlers = $this->env->getTokenParsers(); $this->handlers->setParser($this); } // node visitors if (null === $this->visitors) { $this->visitors = $this->env->getNodeVisitors(); } if (null === $this->expressionParser) { $this->expressionParser = new Twig_ExpressionParser($this, $this->env); } $this->stream = $stream; $this->parent = null; $this->blocks = array(); $this->macros = array(); $this->traits = array(); $this->blockStack = array(); $this->importedSymbols = array(array()); $this->embeddedTemplates = array(); try { $body = $this->subparse($test, $dropNeedle); if (null !== $this->parent && null === $body = $this->filterBodyNodes($body)) { $body = new Twig_Node(); } } catch (Twig_Error_Syntax $e) { if (!$e->getSourceContext()) { $e->setSourceContext($this->stream->getSourceContext()); } if (!$e->getTemplateLine()) { $e->setTemplateLine($this->stream->getCurrent()->getLine()); } throw $e; } $node = new Twig_Node_Module(new Twig_Node_Body(array($body)), $this->parent, new Twig_Node($this->blocks), new Twig_Node($this->macros), new Twig_Node($this->traits), $this->embeddedTemplates, $stream->getSourceContext()); $traverser = new Twig_NodeTraverser($this->env, $this->visitors); $node = $traverser->traverse($node); // restore previous stack so previous parse() call can resume working foreach (array_pop($this->stack) as $key => $val) { $this->$key = $val; } return $node; } public function subparse($test, $dropNeedle = false) { $lineno = $this->getCurrentToken()->getLine(); $rv = array(); while (!$this->stream->isEOF()) { switch ($this->getCurrentToken()->getType()) { case Twig_Token::TEXT_TYPE: $token = $this->stream->next(); $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine()); break; case Twig_Token::VAR_START_TYPE: $token = $this->stream->next(); $expr = $this->expressionParser->parseExpression(); $this->stream->expect(Twig_Token::VAR_END_TYPE); $rv[] = new Twig_Node_Print($expr, $token->getLine()); break; case Twig_Token::BLOCK_START_TYPE: $this->stream->next(); $token = $this->getCurrentToken(); if ($token->getType() !== Twig_Token::NAME_TYPE) { throw new Twig_Error_Syntax('A block must start with a tag name.', $token->getLine(), $this->stream->getSourceContext()); } if (null !== $test && call_user_func($test, $token)) { if ($dropNeedle) { $this->stream->next(); } if (1 === count($rv)) { return $rv[0]; } return new Twig_Node($rv, array(), $lineno); } $subparser = $this->handlers->getTokenParser($token->getValue()); if (null === $subparser) { if (null !== $test) { $e = new Twig_Error_Syntax(sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->stream->getSourceContext()); if (is_array($test) && isset($test[0]) && $test[0] instanceof Twig_TokenParserInterface) { $e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $test[0]->getTag(), $lineno)); } } else { $e = new Twig_Error_Syntax(sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->stream->getSourceContext()); $e->addSuggestions($token->getValue(), array_keys($this->env->getTags())); } throw $e; } $this->stream->next(); $node = $subparser->parse($token); if (null !== $node) { $rv[] = $node; } break; default: throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', $this->getCurrentToken()->getLine(), $this->stream->getSourceContext()); } } if (1 === count($rv)) { return $rv[0]; } return new Twig_Node($rv, array(), $lineno); } /** * @deprecated since 1.27 (to be removed in 2.0) */ public function addHandler($name, $class) { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED); $this->handlers[$name] = $class; } /** * @deprecated since 1.27 (to be removed in 2.0) */ public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED); $this->visitors[] = $visitor; } public function getBlockStack() { return $this->blockStack; } public function peekBlockStack() { return $this->blockStack[count($this->blockStack) - 1]; } public function popBlockStack() { array_pop($this->blockStack); } public function pushBlockStack($name) { $this->blockStack[] = $name; } public function hasBlock($name) { return isset($this->blocks[$name]); } public function getBlock($name) { return $this->blocks[$name]; } public function setBlock($name, Twig_Node_Block $value) { $this->blocks[$name] = new Twig_Node_Body(array($value), array(), $value->getTemplateLine()); } public function hasMacro($name) { return isset($this->macros[$name]); } public function setMacro($name, Twig_Node_Macro $node) { if ($this->isReservedMacroName($name)) { throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword.', $name), $node->getTemplateLine(), $this->stream->getSourceContext()); } $this->macros[$name] = $node; } public function isReservedMacroName($name) { if (null === $this->reservedMacroNames) { $this->reservedMacroNames = array(); $r = new ReflectionClass($this->env->getBaseTemplateClass()); foreach ($r->getMethods() as $method) { $methodName = strtolower($method->getName()); if ('get' === substr($methodName, 0, 3) && isset($methodName[3])) { $this->reservedMacroNames[] = substr($methodName, 3); } } } return in_array(strtolower($name), $this->reservedMacroNames); } public function addTrait($trait) { $this->traits[] = $trait; } public function hasTraits() { return count($this->traits) > 0; } public function embedTemplate(Twig_Node_Module $template) { $template->setIndex(mt_rand()); $this->embeddedTemplates[] = $template; } public function addImportedSymbol($type, $alias, $name = null, Twig_Node_Expression $node = null) { $this->importedSymbols[0][$type][$alias] = array('name' => $name, 'node' => $node); } public function getImportedSymbol($type, $alias) { foreach ($this->importedSymbols as $functions) { if (isset($functions[$type][$alias])) { return $functions[$type][$alias]; } } } public function isMainScope() { return 1 === count($this->importedSymbols); } public function pushLocalScope() { array_unshift($this->importedSymbols, array()); } public function popLocalScope() { array_shift($this->importedSymbols); } /** * @return Twig_ExpressionParser */ public function getExpressionParser() { return $this->expressionParser; } public function getParent() { return $this->parent; } public function setParent($parent) { $this->parent = $parent; } /** * @return Twig_TokenStream */ public function getStream() { return $this->stream; } /** * @return Twig_Token */ public function getCurrentToken() { return $this->stream->getCurrent(); } protected function filterBodyNodes(Twig_NodeInterface $node) { // check that the body does not contain non-empty output nodes if ( ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data'))) || (!$node instanceof Twig_Node_Text && !$node instanceof Twig_Node_BlockReference && $node instanceof Twig_NodeOutputInterface) ) { if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) { throw new Twig_Error_Syntax('A template that extends another one cannot start with a byte order mark (BOM); it must be removed.', $node->getTemplateLine(), $this->stream->getSourceContext()); } throw new Twig_Error_Syntax('A template that extends another one cannot include contents outside Twig blocks. Did you forget to put the contents inside a {% block %} tag?', $node->getTemplateLine(), $this->stream->getSourceContext()); } // bypass "set" nodes as they "capture" the output if ($node instanceof Twig_Node_Set) { return $node; } if ($node instanceof Twig_NodeOutputInterface) { return; } foreach ($node as $k => $n) { if (null !== $n && null === $this->filterBodyNodes($n)) { $node->removeNode($k); } } return $node; } } PK S JLa0G ' lib/Twig/TokenParserBrokerInterface.phpnu W+A * * @deprecated since 1.12 (to be removed in 2.0) */ interface Twig_TokenParserBrokerInterface { /** * Gets a TokenParser suitable for a tag. * * @param string $tag A tag name * * @return Twig_TokenParserInterface|null A Twig_TokenParserInterface or null if no suitable TokenParser was found */ public function getTokenParser($tag); /** * Calls Twig_TokenParserInterface::setParser on all parsers the implementation knows of. */ public function setParser(Twig_ParserInterface $parser); /** * Gets the Twig_ParserInterface. * * @return null|Twig_ParserInterface A Twig_ParserInterface instance or null */ public function getParser(); } PK S JL` lib/Twig/Node.phpnu W+A */ class Twig_Node implements Twig_NodeInterface { protected $nodes; protected $attributes; protected $lineno; protected $tag; private $name; /** * Constructor. * * The nodes are automatically made available as properties ($this->node). * The attributes are automatically made available as array items ($this['name']). * * @param array $nodes An array of named nodes * @param array $attributes An array of attributes (should not be nodes) * @param int $lineno The line number * @param string $tag The tag name associated with the Node */ public function __construct(array $nodes = array(), array $attributes = array(), $lineno = 0, $tag = null) { foreach ($nodes as $name => $node) { if (!$node instanceof Twig_NodeInterface) { @trigger_error(sprintf('Using "%s" for the value of node "%s" of "%s" is deprecated since version 1.25 and will be removed in 2.0.', is_object($node) ? get_class($node) : null === $node ? 'null' : gettype($node), $name, get_class($this)), E_USER_DEPRECATED); } } $this->nodes = $nodes; $this->attributes = $attributes; $this->lineno = $lineno; $this->tag = $tag; } public function __toString() { $attributes = array(); foreach ($this->attributes as $name => $value) { $attributes[] = sprintf('%s: %s', $name, str_replace("\n", '', var_export($value, true))); } $repr = array(get_class($this).'('.implode(', ', $attributes)); if (count($this->nodes)) { foreach ($this->nodes as $name => $node) { $len = strlen($name) + 4; $noderepr = array(); foreach (explode("\n", (string) $node) as $line) { $noderepr[] = str_repeat(' ', $len).$line; } $repr[] = sprintf(' %s: %s', $name, ltrim(implode("\n", $noderepr))); } $repr[] = ')'; } else { $repr[0] .= ')'; } return implode("\n", $repr); } /** * @deprecated since 1.16.1 (to be removed in 2.0) */ public function toXml($asDom = false) { @trigger_error(sprintf('%s is deprecated since version 1.16.1 and will be removed in 2.0.', __METHOD__), E_USER_DEPRECATED); $dom = new DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $dom->appendChild($xml = $dom->createElement('twig')); $xml->appendChild($node = $dom->createElement('node')); $node->setAttribute('class', get_class($this)); foreach ($this->attributes as $name => $value) { $node->appendChild($attribute = $dom->createElement('attribute')); $attribute->setAttribute('name', $name); $attribute->appendChild($dom->createTextNode($value)); } foreach ($this->nodes as $name => $n) { if (null === $n) { continue; } $child = $n->toXml(true)->getElementsByTagName('node')->item(0); $child = $dom->importNode($child, true); $child->setAttribute('name', $name); $node->appendChild($child); } return $asDom ? $dom : $dom->saveXML(); } public function compile(Twig_Compiler $compiler) { foreach ($this->nodes as $node) { $node->compile($compiler); } } public function getTemplateLine() { return $this->lineno; } /** * @deprecated since 1.27 (to be removed in 2.0) */ public function getLine() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getTemplateLine() instead.', E_USER_DEPRECATED); return $this->lineno; } public function getNodeTag() { return $this->tag; } /** * @return bool */ public function hasAttribute($name) { return array_key_exists($name, $this->attributes); } /** * @return mixed */ public function getAttribute($name) { if (!array_key_exists($name, $this->attributes)) { throw new LogicException(sprintf('Attribute "%s" does not exist for Node "%s".', $name, get_class($this))); } return $this->attributes[$name]; } /** * @param string $name * @param mixed $value */ public function setAttribute($name, $value) { $this->attributes[$name] = $value; } public function removeAttribute($name) { unset($this->attributes[$name]); } /** * @return bool */ public function hasNode($name) { return array_key_exists($name, $this->nodes); } /** * @return Twig_Node */ public function getNode($name) { if (!array_key_exists($name, $this->nodes)) { throw new LogicException(sprintf('Node "%s" does not exist for Node "%s".', $name, get_class($this))); } return $this->nodes[$name]; } public function setNode($name, $node = null) { if (!$node instanceof Twig_NodeInterface) { @trigger_error(sprintf('Using "%s" for the value of node "%s" of "%s" is deprecated since version 1.25 and will be removed in 2.0.', is_object($node) ? get_class($node) : null === $node ? 'null' : gettype($node), $name, get_class($this)), E_USER_DEPRECATED); } $this->nodes[$name] = $node; } public function removeNode($name) { unset($this->nodes[$name]); } public function count() { return count($this->nodes); } public function getIterator() { return new ArrayIterator($this->nodes); } public function setTemplateName($name) { $this->name = $name; foreach ($this->nodes as $node) { if (null !== $node) { $node->setTemplateName($name); } } } public function getTemplateName() { return $this->name; } /** * @deprecated since 1.27 (to be removed in 2.0) */ public function setFilename($name) { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use setTemplateName() instead.', E_USER_DEPRECATED); $this->setTemplateName($name); } /** * @deprecated since 1.27 (to be removed in 2.0) */ public function getFilename() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getTemplateName() instead.', E_USER_DEPRECATED); return $this->name; } } PK S JE lib/Twig/Markup.phpnu W+A */ class Twig_Markup implements Countable { protected $content; protected $charset; public function __construct($content, $charset) { $this->content = (string) $content; $this->charset = $charset; } public function __toString() { return $this->content; } public function count() { return function_exists('mb_get_info') ? mb_strlen($this->content, $this->charset) : strlen($this->content); } } PK S Jew-lQ Q lib/Twig/FilterInterface.phpnu W+A * * @deprecated since 1.12 (to be removed in 2.0) */ interface Twig_FilterInterface { /** * Compiles a filter. * * @return string The PHP code for the filter */ public function compile(); public function needsEnvironment(); public function needsContext(); public function getSafe(Twig_Node $filterArgs); public function getPreservesSafety(); public function getPreEscape(); public function setArguments($arguments); public function getArguments(); } PK S J1m#/ lib/Twig/Source.phpnu W+A */ class Twig_Source { private $code; private $name; private $path; /** * @param string $code The template source code * @param string $name The template logical name * @param string $path The filesystem path of the template if any */ public function __construct($code, $name, $path = '') { $this->code = $code; $this->name = $name; $this->path = $path; } public function getCode() { return $this->code; } public function getName() { return $this->name; } public function getPath() { return $this->path; } } PK S JSf lib/Twig/TokenParser/Import.phpnu W+A * {% import 'forms.html' as forms %} * * * @final */ class Twig_TokenParser_Import extends Twig_TokenParser { public function parse(Twig_Token $token) { $macro = $this->parser->getExpressionParser()->parseExpression(); $this->parser->getStream()->expect('as'); $var = new Twig_Node_Expression_AssignName($this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue(), $token->getLine()); $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); $this->parser->addImportedSymbol('template', $var->getAttribute('name')); return new Twig_Node_Import($macro, $var, $token->getLine(), $this->getTag()); } public function getTag() { return 'import'; } } PK S J; lib/Twig/TokenParser/For.phpnu W+A *
* {{ post.published_at|date("m/d/Y") }} ** * @param Twig_Environment $env * @param DateTime|DateTimeInterface|DateInterval|string $date A date * @param string|null $format The target format, null to use the default * @param DateTimeZone|string|null|false $timezone The target timezone, null to use the default, false to leave unchanged * * @return string The formatted date */ function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $timezone = null) { if (null === $format) { $formats = $env->getExtension('Twig_Extension_Core')->getDateFormat(); $format = $date instanceof DateInterval ? $formats[1] : $formats[0]; } if ($date instanceof DateInterval) { return $date->format($format); } return twig_date_converter($env, $date, $timezone)->format($format); } /** * Returns a new date object modified. * *
* {{ post.published_at|date_modify("-1day")|date("m/d/Y") }} ** * @param Twig_Environment $env * @param DateTime|string $date A date * @param string $modifier A modifier string * * @return DateTime A new date object */ function twig_date_modify_filter(Twig_Environment $env, $date, $modifier) { $date = twig_date_converter($env, $date, false); $resultDate = $date->modify($modifier); // This is a hack to ensure PHP 5.2 support and support for DateTimeImmutable // DateTime::modify does not return the modified DateTime object < 5.3.0 // and DateTimeImmutable does not modify $date. return null === $resultDate ? $date : $resultDate; } /** * Converts an input to a DateTime instance. * *
* {% if date(user.created_at) < date('+2days') %} * {# do something #} * {% endif %} ** * @param Twig_Environment $env * @param DateTime|DateTimeInterface|string|null $date A date * @param DateTimeZone|string|null|false $timezone The target timezone, null to use the default, false to leave unchanged * * @return DateTime A DateTime instance */ function twig_date_converter(Twig_Environment $env, $date = null, $timezone = null) { // determine the timezone if (false !== $timezone) { if (null === $timezone) { $timezone = $env->getExtension('Twig_Extension_Core')->getTimezone(); } elseif (!$timezone instanceof DateTimeZone) { $timezone = new DateTimeZone($timezone); } } // immutable dates if ($date instanceof DateTimeImmutable) { return false !== $timezone ? $date->setTimezone($timezone) : $date; } if ($date instanceof DateTime || $date instanceof DateTimeInterface) { $date = clone $date; if (false !== $timezone) { $date->setTimezone($timezone); } return $date; } if (null === $date || 'now' === $date) { return new DateTime($date, false !== $timezone ? $timezone : $env->getExtension('Twig_Extension_Core')->getTimezone()); } $asString = (string) $date; if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) { $date = new DateTime('@'.$date); } else { $date = new DateTime($date, $env->getExtension('Twig_Extension_Core')->getTimezone()); } if (false !== $timezone) { $date->setTimezone($timezone); } return $date; } /** * Replaces strings within a string. * * @param string $str String to replace in * @param array|Traversable $from Replace values * @param string|null $to Replace to, deprecated (@see http://php.net/manual/en/function.strtr.php) * * @return string */ function twig_replace_filter($str, $from, $to = null) { if ($from instanceof Traversable) { $from = iterator_to_array($from); } elseif (is_string($from) && is_string($to)) { @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); return strtr($str, $from, $to); } elseif (!is_array($from)) { 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))); } return strtr($str, $from); } /** * Rounds a number. * * @param int|float $value The value to round * @param int|float $precision The rounding precision * @param string $method The method to use for rounding * * @return int|float The rounded number */ function twig_round($value, $precision = 0, $method = 'common') { if ('common' == $method) { return round($value, $precision); } if ('ceil' != $method && 'floor' != $method) { throw new Twig_Error_Runtime('The round filter only supports the "common", "ceil", and "floor" methods.'); } return $method($value * pow(10, $precision)) / pow(10, $precision); } /** * Number format filter. * * All of the formatting options can be left null, in that case the defaults will * be used. Supplying any of the parameters will override the defaults set in the * environment object. * * @param Twig_Environment $env * @param mixed $number A float/int/string of the number to format * @param int $decimal the number of decimal points to display * @param string $decimalPoint the character(s) to use for the decimal point * @param string $thousandSep the character(s) to use for the thousands separator * * @return string The formatted number */ function twig_number_format_filter(Twig_Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null) { $defaults = $env->getExtension('Twig_Extension_Core')->getNumberFormat(); if (null === $decimal) { $decimal = $defaults[0]; } if (null === $decimalPoint) { $decimalPoint = $defaults[1]; } if (null === $thousandSep) { $thousandSep = $defaults[2]; } return number_format((float) $number, $decimal, $decimalPoint, $thousandSep); } /** * URL encodes (RFC 3986) a string as a path segment or an array as a query string. * * @param string|array $url A URL or an array of query parameters * * @return string The URL encoded value */ function twig_urlencode_filter($url) { if (is_array($url)) { if (defined('PHP_QUERY_RFC3986')) { return http_build_query($url, '', '&', PHP_QUERY_RFC3986); } return http_build_query($url, '', '&'); } return rawurlencode($url); } if (PHP_VERSION_ID < 50300) { /** * JSON encodes a variable. * * @param mixed $value the value to encode * @param int $options Not used on PHP 5.2.x * * @return mixed The JSON encoded value */ function twig_jsonencode_filter($value, $options = 0) { if ($value instanceof Twig_Markup) { $value = (string) $value; } elseif (is_array($value)) { array_walk_recursive($value, '_twig_markup2string'); } return json_encode($value); } } else { /** * JSON encodes a variable. * * @param mixed $value the value to encode * @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 * * @return mixed The JSON encoded value */ function twig_jsonencode_filter($value, $options = 0) { if ($value instanceof Twig_Markup) { $value = (string) $value; } elseif (is_array($value)) { array_walk_recursive($value, '_twig_markup2string'); } return json_encode($value, $options); } } function _twig_markup2string(&$value) { if ($value instanceof Twig_Markup) { $value = (string) $value; } } /** * Merges an array with another one. * *
* {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %} * * {% set items = items|merge({ 'peugeot': 'car' }) %} * * {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #} ** * @param array|Traversable $arr1 An array * @param array|Traversable $arr2 An array * * @return array The merged array */ function twig_array_merge($arr1, $arr2) { if ($arr1 instanceof Traversable) { $arr1 = iterator_to_array($arr1); } elseif (!is_array($arr1)) { throw new Twig_Error_Runtime(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as first argument.', gettype($arr1))); } if ($arr2 instanceof Traversable) { $arr2 = iterator_to_array($arr2); } elseif (!is_array($arr2)) { throw new Twig_Error_Runtime(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as second argument.', gettype($arr2))); } return array_merge($arr1, $arr2); } /** * Slices a variable. * * @param Twig_Environment $env * @param mixed $item A variable * @param int $start Start of the slice * @param int $length Size of the slice * @param bool $preserveKeys Whether to preserve key or not (when the input is an array) * * @return mixed The sliced variable */ function twig_slice(Twig_Environment $env, $item, $start, $length = null, $preserveKeys = false) { if ($item instanceof Traversable) { if ($item instanceof IteratorAggregate) { $item = $item->getIterator(); } if ($start >= 0 && $length >= 0 && $item instanceof Iterator) { try { return iterator_to_array(new LimitIterator($item, $start, $length === null ? -1 : $length), $preserveKeys); } catch (OutOfBoundsException $exception) { return array(); } } $item = iterator_to_array($item, $preserveKeys); } if (is_array($item)) { return array_slice($item, $start, $length, $preserveKeys); } $item = (string) $item; if (function_exists('mb_get_info') && null !== $charset = $env->getCharset()) { return (string) mb_substr($item, $start, null === $length ? mb_strlen($item, $charset) - $start : $length, $charset); } return (string) (null === $length ? substr($item, $start) : substr($item, $start, $length)); } /** * Returns the first element of the item. * * @param Twig_Environment $env * @param mixed $item A variable * * @return mixed The first element of the item */ function twig_first(Twig_Environment $env, $item) { $elements = twig_slice($env, $item, 0, 1, false); return is_string($elements) ? $elements : current($elements); } /** * Returns the last element of the item. * * @param Twig_Environment $env * @param mixed $item A variable * * @return mixed The last element of the item */ function twig_last(Twig_Environment $env, $item) { $elements = twig_slice($env, $item, -1, 1, false); return is_string($elements) ? $elements : current($elements); } /** * Joins the values to a string. * * The separator between elements is an empty string per default, you can define it with the optional parameter. * *
* {{ [1, 2, 3]|join('|') }} * {# returns 1|2|3 #} * * {{ [1, 2, 3]|join }} * {# returns 123 #} ** * @param array $value An array * @param string $glue The separator * * @return string The concatenated string */ function twig_join_filter($value, $glue = '') { if ($value instanceof Traversable) { $value = iterator_to_array($value, false); } return implode($glue, (array) $value); } /** * Splits the string into an array. * *
* {{ "one,two,three"|split(',') }} * {# returns [one, two, three] #} * * {{ "one,two,three,four,five"|split(',', 3) }} * {# returns [one, two, "three,four,five"] #} * * {{ "123"|split('') }} * {# returns [1, 2, 3] #} * * {{ "aabbcc"|split('', 2) }} * {# returns [aa, bb, cc] #} ** * @param Twig_Environment $env * @param string $value A string * @param string $delimiter The delimiter * @param int $limit The limit * * @return array The split string as an array */ function twig_split_filter(Twig_Environment $env, $value, $delimiter, $limit = null) { if (!empty($delimiter)) { return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit); } if (!function_exists('mb_get_info') || null === $charset = $env->getCharset()) { return str_split($value, null === $limit ? 1 : $limit); } if ($limit <= 1) { return preg_split('/(? * {% for key in array|keys %} * {# ... #} * {% endfor %} * * * @param array $array An array * * @return array The keys */ function twig_get_array_keys_filter($array) { if ($array instanceof Traversable) { return array_keys(iterator_to_array($array)); } if (!is_array($array)) { return array(); } return array_keys($array); } /** * Reverses a variable. * * @param Twig_Environment $env * @param array|Traversable|string $item An array, a Traversable instance, or a string * @param bool $preserveKeys Whether to preserve key or not * * @return mixed The reversed input */ function twig_reverse_filter(Twig_Environment $env, $item, $preserveKeys = false) { if ($item instanceof Traversable) { return array_reverse(iterator_to_array($item), $preserveKeys); } if (is_array($item)) { return array_reverse($item, $preserveKeys); } if (null !== $charset = $env->getCharset()) { $string = (string) $item; if ('UTF-8' !== $charset) { $item = twig_convert_encoding($string, 'UTF-8', $charset); } preg_match_all('/./us', $item, $matches); $string = implode('', array_reverse($matches[0])); if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, $charset, 'UTF-8'); } return $string; } return strrev((string) $item); } /** * Sorts an array. * * @param array|Traversable $array * * @return array */ function twig_sort_filter($array) { if ($array instanceof Traversable) { $array = iterator_to_array($array); } elseif (!is_array($array)) { throw new Twig_Error_Runtime(sprintf('The sort filter only works with arrays or "Traversable", got "%s".', gettype($array))); } asort($array); return $array; } /** * @internal */ function twig_in_filter($value, $compare) { if (is_array($compare)) { return in_array($value, $compare, is_object($value) || is_resource($value)); } elseif (is_string($compare) && (is_string($value) || is_int($value) || is_float($value))) { return '' === $value || false !== strpos($compare, (string) $value); } elseif ($compare instanceof Traversable) { return in_array($value, iterator_to_array($compare, false), is_object($value) || is_resource($value)); } return false; } /** * Escapes a string. * * @param Twig_Environment $env * @param mixed $string The value to be escaped * @param string $strategy The escaping strategy * @param string $charset The charset * @param bool $autoescape Whether the function is called by the auto-escaping feature (true) or by the developer (false) * * @return string */ function twig_escape_filter(Twig_Environment $env, $string, $strategy = 'html', $charset = null, $autoescape = false) { if ($autoescape && $string instanceof Twig_Markup) { return $string; } if (!is_string($string)) { if (is_object($string) && method_exists($string, '__toString')) { $string = (string) $string; } elseif (in_array($strategy, array('html', 'js', 'css', 'html_attr', 'url'))) { return $string; } } if (null === $charset) { $charset = $env->getCharset(); } switch ($strategy) { case 'html': // see http://php.net/htmlspecialchars // Using a static variable to avoid initializing the array // each time the function is called. Moving the declaration on the // top of the function slow downs other escaping strategies. static $htmlspecialcharsCharsets; if (null === $htmlspecialcharsCharsets) { if (defined('HHVM_VERSION')) { $htmlspecialcharsCharsets = array('utf-8' => true, 'UTF-8' => true); } else { $htmlspecialcharsCharsets = array( 'ISO-8859-1' => true, 'ISO8859-1' => true, 'ISO-8859-15' => true, 'ISO8859-15' => true, 'utf-8' => true, 'UTF-8' => true, 'CP866' => true, 'IBM866' => true, '866' => true, 'CP1251' => true, 'WINDOWS-1251' => true, 'WIN-1251' => true, '1251' => true, 'CP1252' => true, 'WINDOWS-1252' => true, '1252' => true, 'KOI8-R' => true, 'KOI8-RU' => true, 'KOI8R' => true, 'BIG5' => true, '950' => true, 'GB2312' => true, '936' => true, 'BIG5-HKSCS' => true, 'SHIFT_JIS' => true, 'SJIS' => true, '932' => true, 'EUC-JP' => true, 'EUCJP' => true, 'ISO8859-5' => true, 'ISO-8859-5' => true, 'MACROMAN' => true, ); } } if (isset($htmlspecialcharsCharsets[$charset])) { return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset); } if (isset($htmlspecialcharsCharsets[strtoupper($charset)])) { // cache the lowercase variant for future iterations $htmlspecialcharsCharsets[$charset] = true; return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset); } $string = twig_convert_encoding($string, 'UTF-8', $charset); $string = htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); return twig_convert_encoding($string, $charset, 'UTF-8'); case 'js': // escape all non-alphanumeric characters // into their \xHH or \uHHHH representations if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, 'UTF-8', $charset); } if (0 == strlen($string) ? false : 1 !== preg_match('/^./su', $string)) { throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.'); } $string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', '_twig_escape_js_callback', $string); if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, $charset, 'UTF-8'); } return $string; case 'css': if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, 'UTF-8', $charset); } if (0 == strlen($string) ? false : 1 !== preg_match('/^./su', $string)) { throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.'); } $string = preg_replace_callback('#[^a-zA-Z0-9]#Su', '_twig_escape_css_callback', $string); if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, $charset, 'UTF-8'); } return $string; case 'html_attr': if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, 'UTF-8', $charset); } if (0 == strlen($string) ? false : 1 !== preg_match('/^./su', $string)) { throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.'); } $string = preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su', '_twig_escape_html_attr_callback', $string); if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, $charset, 'UTF-8'); } return $string; case 'url': if (PHP_VERSION_ID < 50300) { return str_replace('%7E', '~', rawurlencode($string)); } return rawurlencode($string); default: static $escapers; if (null === $escapers) { $escapers = $env->getExtension('Twig_Extension_Core')->getEscapers(); } if (isset($escapers[$strategy])) { return call_user_func($escapers[$strategy], $env, $string, $charset); } $validStrategies = implode(', ', array_merge(array('html', 'js', 'url', 'css', 'html_attr'), array_keys($escapers))); throw new Twig_Error_Runtime(sprintf('Invalid escaping strategy "%s" (valid ones: %s).', $strategy, $validStrategies)); } } /** * @internal */ function twig_escape_filter_is_safe(Twig_Node $filterArgs) { foreach ($filterArgs as $arg) { if ($arg instanceof Twig_Node_Expression_Constant) { return array($arg->getAttribute('value')); } return array(); } return array('html'); } if (function_exists('mb_convert_encoding')) { function twig_convert_encoding($string, $to, $from) { return mb_convert_encoding($string, $to, $from); } } elseif (function_exists('iconv')) { function twig_convert_encoding($string, $to, $from) { return iconv($from, $to, $string); } } else { function twig_convert_encoding($string, $to, $from) { throw new Twig_Error_Runtime('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).'); } } function _twig_escape_js_callback($matches) { $char = $matches[0]; // \xHH if (!isset($char[1])) { return '\\x'.strtoupper(substr('00'.bin2hex($char), -2)); } // \uHHHH $char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8'); return '\\u'.strtoupper(substr('0000'.bin2hex($char), -4)); } function _twig_escape_css_callback($matches) { $char = $matches[0]; // \xHH if (!isset($char[1])) { $hex = ltrim(strtoupper(bin2hex($char)), '0'); if (0 === strlen($hex)) { $hex = '0'; } return '\\'.$hex.' '; } // \uHHHH $char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8'); return '\\'.ltrim(strtoupper(bin2hex($char)), '0').' '; } /** * This function is adapted from code coming from Zend Framework. * * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ function _twig_escape_html_attr_callback($matches) { /* * While HTML supports far more named entities, the lowest common denominator * has become HTML5's XML Serialisation which is restricted to the those named * entities that XML supports. Using HTML entities would result in this error: * XML Parsing Error: undefined entity */ static $entityMap = array( 34 => 'quot', /* quotation mark */ 38 => 'amp', /* ampersand */ 60 => 'lt', /* less-than sign */ 62 => 'gt', /* greater-than sign */ ); $chr = $matches[0]; $ord = ord($chr); /* * The following replaces characters undefined in HTML with the * hex entity for the Unicode replacement character. */ if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r") || ($ord >= 0x7f && $ord <= 0x9f)) { return '�'; } /* * Check if the current character to escape has a name entity we should * replace it with while grabbing the hex value of the character. */ if (strlen($chr) == 1) { $hex = strtoupper(substr('00'.bin2hex($chr), -2)); } else { $chr = twig_convert_encoding($chr, 'UTF-16BE', 'UTF-8'); $hex = strtoupper(substr('0000'.bin2hex($chr), -4)); } $int = hexdec($hex); if (array_key_exists($int, $entityMap)) { return sprintf('&%s;', $entityMap[$int]); } /* * Per OWASP recommendations, we'll use hex entities for any other * characters where a named entity does not exist. */ return sprintf('%s;', $hex); } // add multibyte extensions if possible if (function_exists('mb_get_info')) { /** * Returns the length of a variable. * * @param Twig_Environment $env * @param mixed $thing A variable * * @return int The length of the value */ function twig_length_filter(Twig_Environment $env, $thing) { return is_scalar($thing) ? mb_strlen($thing, $env->getCharset()) : count($thing); } /** * Converts a string to uppercase. * * @param Twig_Environment $env * @param string $string A string * * @return string The uppercased string */ function twig_upper_filter(Twig_Environment $env, $string) { if (null !== $charset = $env->getCharset()) { return mb_strtoupper($string, $charset); } return strtoupper($string); } /** * Converts a string to lowercase. * * @param Twig_Environment $env * @param string $string A string * * @return string The lowercased string */ function twig_lower_filter(Twig_Environment $env, $string) { if (null !== $charset = $env->getCharset()) { return mb_strtolower($string, $charset); } return strtolower($string); } /** * Returns a titlecased string. * * @param Twig_Environment $env * @param string $string A string * * @return string The titlecased string */ function twig_title_string_filter(Twig_Environment $env, $string) { if (null !== $charset = $env->getCharset()) { return mb_convert_case($string, MB_CASE_TITLE, $charset); } return ucwords(strtolower($string)); } /** * Returns a capitalized string. * * @param Twig_Environment $env * @param string $string A string * * @return string The capitalized string */ function twig_capitalize_string_filter(Twig_Environment $env, $string) { if (null !== $charset = $env->getCharset()) { return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).mb_strtolower(mb_substr($string, 1, mb_strlen($string, $charset), $charset), $charset); } return ucfirst(strtolower($string)); } } // and byte fallback else { /** * Returns the length of a variable. * * @param Twig_Environment $env * @param mixed $thing A variable * * @return int The length of the value */ function twig_length_filter(Twig_Environment $env, $thing) { return is_scalar($thing) ? strlen($thing) : count($thing); } /** * Returns a titlecased string. * * @param Twig_Environment $env * @param string $string A string * * @return string The titlecased string */ function twig_title_string_filter(Twig_Environment $env, $string) { return ucwords(strtolower($string)); } /** * Returns a capitalized string. * * @param Twig_Environment $env * @param string $string A string * * @return string The capitalized string */ function twig_capitalize_string_filter(Twig_Environment $env, $string) { return ucfirst(strtolower($string)); } } /** * @internal */ function twig_ensure_traversable($seq) { if ($seq instanceof Traversable || is_array($seq)) { return $seq; } return array(); } /** * Checks if a variable is empty. * *
* {# evaluates to true if the foo variable is null, false, or the empty string #} * {% if foo is empty %} * {# ... #} * {% endif %} ** * @param mixed $value A variable * * @return bool true if the value is empty, false otherwise */ function twig_test_empty($value) { if ($value instanceof Countable) { return 0 == count($value); } return '' === $value || false === $value || null === $value || array() === $value; } /** * Checks if a variable is traversable. * *
* {# evaluates to true if the foo variable is an array or a traversable object #} * {% if foo is traversable %} * {# ... #} * {% endif %} ** * @param mixed $value A variable * * @return bool true if the value is traversable */ function twig_test_iterable($value) { return $value instanceof Traversable || is_array($value); } /** * Renders a template. * * @param Twig_Environment $env * @param array $context * @param string|array $template The template to render or an array of templates to try consecutively * @param array $variables The variables to pass to the template * @param bool $withContext * @param bool $ignoreMissing Whether to ignore missing templates or not * @param bool $sandboxed Whether to sandbox the template or not * * @return string The rendered template */ function twig_include(Twig_Environment $env, $context, $template, $variables = array(), $withContext = true, $ignoreMissing = false, $sandboxed = false) { $alreadySandboxed = false; $sandbox = null; if ($withContext) { $variables = array_merge($context, $variables); } if ($isSandboxed = $sandboxed && $env->hasExtension('Twig_Extension_Sandbox')) { $sandbox = $env->getExtension('Twig_Extension_Sandbox'); if (!$alreadySandboxed = $sandbox->isSandboxed()) { $sandbox->enableSandbox(); } } $result = null; try { $result = $env->resolveTemplate($template)->render($variables); } catch (Twig_Error_Loader $e) { if (!$ignoreMissing) { if ($isSandboxed && !$alreadySandboxed) { $sandbox->disableSandbox(); } throw $e; } } catch (Throwable $e) { if ($isSandboxed && !$alreadySandboxed) { $sandbox->disableSandbox(); } throw $e; } catch (Exception $e) { if ($isSandboxed && !$alreadySandboxed) { $sandbox->disableSandbox(); } throw $e; } if ($isSandboxed && !$alreadySandboxed) { $sandbox->disableSandbox(); } return $result; } /** * Returns a template content without rendering it. * * @param Twig_Environment $env * @param string $name The template name * @param bool $ignoreMissing Whether to ignore missing templates or not * * @return string The template source */ function twig_source(Twig_Environment $env, $name, $ignoreMissing = false) { $loader = $env->getLoader(); try { if (!$loader instanceof Twig_SourceContextLoaderInterface) { return $loader->getSource($name); } else { return $loader->getSourceContext($name)->getCode(); } } catch (Twig_Error_Loader $e) { if (!$ignoreMissing) { throw $e; } } } /** * Provides the ability to get constants from instances as well as class/global constants. * * @param string $constant The name of the constant * @param null|object $object The object to get the constant from * * @return string */ function twig_constant($constant, $object = null) { if (null !== $object) { $constant = get_class($object).'::'.$constant; } return constant($constant); } /** * Checks if a constant exists. * * @param string $constant The name of the constant * @param null|object $object The object to get the constant from * * @return bool */ function twig_constant_is_defined($constant, $object = null) { if (null !== $object) { $constant = get_class($object).'::'.$constant; } return defined($constant); } /** * Batches item. * * @param array $items An array of items * @param int $size The size of the batch * @param mixed $fill A value used to fill missing items * * @return array */ function twig_array_batch($items, $size, $fill = null) { if ($items instanceof Traversable) { $items = iterator_to_array($items, false); } $size = ceil($size); $result = array_chunk($items, $size, true); if (null !== $fill && !empty($result)) { $last = count($result) - 1; if ($fillCount = $size - count($result[$last])) { $result[$last] = array_merge( $result[$last], array_fill(0, $fillCount, $fill) ); } } return $result; } PK S J庾 lib/Twig/Extension/Debug.phpnu W+A $isDumpOutputHtmlSafe ? array('html') : array(), 'needs_context' => true, 'needs_environment' => true)), ); } public function getName() { return 'debug'; } } function twig_var_dump(Twig_Environment $env, $context) { if (!$env->isDebug()) { return; } ob_start(); $count = func_num_args(); if (2 === $count) { $vars = array(); foreach ($context as $key => $value) { if (!$value instanceof Twig_Template) { $vars[$key] = $value; } } var_dump($vars); } else { for ($i = 2; $i < $count; ++$i) { var_dump(func_get_arg($i)); } } return ob_get_clean(); } PK S JHb~ lib/Twig/Extension/Profiler.phpnu W+A actives[] = $profile; } public function enter(Twig_Profiler_Profile $profile) { $this->actives[0]->addProfile($profile); array_unshift($this->actives, $profile); } public function leave(Twig_Profiler_Profile $profile) { $profile->leave(); array_shift($this->actives); if (1 === count($this->actives)) { $this->actives[0]->leave(); } } public function getNodeVisitors() { return array(new Twig_Profiler_NodeVisitor_Profiler(get_class($this))); } public function getName() { return 'profiler'; } } PK S Jyl4 4 lib/Twig/Extension/Staging.phpnu W+A * * @internal */ class Twig_Extension_Staging extends Twig_Extension { protected $functions = array(); protected $filters = array(); protected $visitors = array(); protected $tokenParsers = array(); protected $globals = array(); protected $tests = array(); public function addFunction($name, $function) { if (isset($this->functions[$name])) { @trigger_error(sprintf('Overriding function "%s" that is already registered is deprecated since version 1.30 and won\'t be possible anymore in 2.0.', $name), E_USER_DEPRECATED); } $this->functions[$name] = $function; } public function getFunctions() { return $this->functions; } public function addFilter($name, $filter) { if (isset($this->filters[$name])) { @trigger_error(sprintf('Overriding filter "%s" that is already registered is deprecated since version 1.30 and won\'t be possible anymore in 2.0.', $name), E_USER_DEPRECATED); } $this->filters[$name] = $filter; } public function getFilters() { return $this->filters; } public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { $this->visitors[] = $visitor; } public function getNodeVisitors() { return $this->visitors; } public function addTokenParser(Twig_TokenParserInterface $parser) { if (isset($this->tokenParsers[$parser->getTag()])) { @trigger_error(sprintf('Overriding tag "%s" that is already registered is deprecated since version 1.30 and won\'t be possible anymore in 2.0.', $parser->getTag()), E_USER_DEPRECATED); } $this->tokenParsers[$parser->getTag()] = $parser; } public function getTokenParsers() { return $this->tokenParsers; } public function addGlobal($name, $value) { $this->globals[$name] = $value; } public function getGlobals() { return $this->globals; } public function addTest($name, $test) { if (isset($this->tests[$name])) { @trigger_error(sprintf('Overriding test "%s" that is already registered is deprecated since version 1.30 and won\'t be possible anymore in 2.0.', $name), E_USER_DEPRECATED); } $this->tests[$name] = $test; } public function getTests() { return $this->tests; } public function getName() { return 'staging'; } } PK S J Ҩ lib/Twig/Extension/Sandbox.phpnu W+A policy = $policy; $this->sandboxedGlobally = $sandboxed; } public function getTokenParsers() { return array(new Twig_TokenParser_Sandbox()); } public function getNodeVisitors() { return array(new Twig_NodeVisitor_Sandbox()); } public function enableSandbox() { $this->sandboxed = true; } public function disableSandbox() { $this->sandboxed = false; } public function isSandboxed() { return $this->sandboxedGlobally || $this->sandboxed; } public function isSandboxedGlobally() { return $this->sandboxedGlobally; } public function setSecurityPolicy(Twig_Sandbox_SecurityPolicyInterface $policy) { $this->policy = $policy; } public function getSecurityPolicy() { return $this->policy; } public function checkSecurity($tags, $filters, $functions) { if ($this->isSandboxed()) { $this->policy->checkSecurity($tags, $filters, $functions); } } public function checkMethodAllowed($obj, $method) { if ($this->isSandboxed()) { $this->policy->checkMethodAllowed($obj, $method); } } public function checkPropertyAllowed($obj, $method) { if ($this->isSandboxed()) { $this->policy->checkPropertyAllowed($obj, $method); } } public function ensureToStringAllowed($obj) { if ($this->isSandboxed() && is_object($obj)) { $this->policy->checkMethodAllowed($obj, '__toString'); } return $obj; } public function getName() { return 'sandbox'; } } PK S JМ`. . lib/Twig/Extension/Escaper.phpnu W+A setDefaultStrategy($defaultStrategy); } public function getTokenParsers() { return array(new Twig_TokenParser_AutoEscape()); } public function getNodeVisitors() { return array(new Twig_NodeVisitor_Escaper()); } public function getFilters() { return array( new Twig_SimpleFilter('raw', 'twig_raw_filter', array('is_safe' => array('all'))), ); } /** * Sets the default strategy to use when not defined by the user. * * The strategy can be a valid PHP callback that takes the template * name as an argument and returns the strategy to use. * * @param string|false|callable $defaultStrategy An escaping strategy */ public function setDefaultStrategy($defaultStrategy) { // for BC if (true === $defaultStrategy) { @trigger_error('Using "true" as the default strategy is deprecated since version 1.21. Use "html" instead.', E_USER_DEPRECATED); $defaultStrategy = 'html'; } if ('filename' === $defaultStrategy) { @trigger_error('Using "filename" as the default strategy is deprecated since version 1.27. Use "name" instead.', E_USER_DEPRECATED); $defaultStrategy = 'name'; } if ('name' === $defaultStrategy) { $defaultStrategy = array('Twig_FileExtensionEscapingStrategy', 'guess'); } $this->defaultStrategy = $defaultStrategy; } /** * Gets the default strategy to use when not defined by the user. * * @param string $name The template name * * @return string|false The default strategy to use for the template */ public function getDefaultStrategy($name) { // disable string callables to avoid calling a function named html or js, // or any other upcoming escaping strategy if (!is_string($this->defaultStrategy) && false !== $this->defaultStrategy) { return call_user_func($this->defaultStrategy, $name); } return $this->defaultStrategy; } public function getName() { return 'escaper'; } } /** * Marks a variable as being safe. * * @param string $string A PHP variable * * @return string */ function twig_raw_filter($string) { return $string; } PK S J,a a lib/Twig/Extension/Optimizer.phpnu W+A optimizers = $optimizers; } public function getNodeVisitors() { return array(new Twig_NodeVisitor_Optimizer($this->optimizers)); } public function getName() { return 'optimizer'; } } PK S J %] ' lib/Twig/Extension/GlobalsInterface.phpnu W+A */ interface Twig_Extension_GlobalsInterface { } PK S J0LT # lib/Twig/Extension/StringLoader.phpnu W+A true)), ); } public function getName() { return 'string_loader'; } } /** * Loads a template from a string. * *
* {{ include(template_from_string("Hello {{ name }}")) }} ** * @param Twig_Environment $env A Twig_Environment instance * @param string $template A template as a string or object implementing __toString() * * @return Twig_Template */ function twig_template_from_string(Twig_Environment $env, $template) { return $env->createTemplate((string) $template); } PK S J@ + lib/Twig/Extension/InitRuntimeInterface.phpnu W+A */ interface Twig_Extension_InitRuntimeInterface { } PK S Jx# # lib/Twig/TokenParserBroker.phpnu W+A * * @deprecated since 1.12 (to be removed in 2.0) */ class Twig_TokenParserBroker implements Twig_TokenParserBrokerInterface { protected $parser; protected $parsers = array(); protected $brokers = array(); /** * @param array|Traversable $parsers A Traversable of Twig_TokenParserInterface instances * @param array|Traversable $brokers A Traversable of Twig_TokenParserBrokerInterface instances * @param bool $triggerDeprecationError */ public function __construct($parsers = array(), $brokers = array(), $triggerDeprecationError = true) { if ($triggerDeprecationError) { @trigger_error('The '.__CLASS__.' class is deprecated since version 1.12 and will be removed in 2.0.', E_USER_DEPRECATED); } foreach ($parsers as $parser) { if (!$parser instanceof Twig_TokenParserInterface) { throw new LogicException('$parsers must a an array of Twig_TokenParserInterface.'); } $this->parsers[$parser->getTag()] = $parser; } foreach ($brokers as $broker) { if (!$broker instanceof Twig_TokenParserBrokerInterface) { throw new LogicException('$brokers must a an array of Twig_TokenParserBrokerInterface.'); } $this->brokers[] = $broker; } } public function addTokenParser(Twig_TokenParserInterface $parser) { $this->parsers[$parser->getTag()] = $parser; } public function removeTokenParser(Twig_TokenParserInterface $parser) { $name = $parser->getTag(); if (isset($this->parsers[$name]) && $parser === $this->parsers[$name]) { unset($this->parsers[$name]); } } public function addTokenParserBroker(Twig_TokenParserBroker $broker) { $this->brokers[] = $broker; } public function removeTokenParserBroker(Twig_TokenParserBroker $broker) { if (false !== $pos = array_search($broker, $this->brokers)) { unset($this->brokers[$pos]); } } /** * Gets a suitable TokenParser for a tag. * * First looks in parsers, then in brokers. * * @param string $tag A tag name * * @return null|Twig_TokenParserInterface A Twig_TokenParserInterface or null if no suitable TokenParser was found */ public function getTokenParser($tag) { if (isset($this->parsers[$tag])) { return $this->parsers[$tag]; } $broker = end($this->brokers); while (false !== $broker) { $parser = $broker->getTokenParser($tag); if (null !== $parser) { return $parser; } $broker = prev($this->brokers); } } public function getParsers() { return $this->parsers; } public function getParser() { return $this->parser; } public function setParser(Twig_ParserInterface $parser) { $this->parser = $parser; foreach ($this->parsers as $tokenParser) { $tokenParser->setParser($parser); } foreach ($this->brokers as $broker) { $broker->setParser($parser); } } } PK S J