PK e!dL [T\ % lib/Twig/NodeVisitor/SafeAnalysis.phpnu W+A safeVars = $safeVars; } public function getSafe(Twig_Node $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']; } } private function setSafe(Twig_Node $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'); if (in_array($name, $this->safeVars)) { $this->setSafe($node, array('all')); } else { $this->setSafe($node, array()); } } else { $this->setSafe($node, array()); } return $node; } private 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; } } class_alias('Twig_NodeVisitor_SafeAnalysis', 'Twig\NodeVisitor\SafeAnalysisNodeVisitor', false); PK e!dLs!}. . lib/Twig/NodeVisitor/Sandbox.phpnu W+A */ final class Twig_NodeVisitor_Sandbox extends Twig_BaseNodeVisitor { private $inAModule = false; private $tags; private $filters; private $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; } } class_alias('Twig_NodeVisitor_Sandbox', 'Twig\NodeVisitor\SandboxNodeVisitor', false); PK e!dLbh h lib/Twig/NodeVisitor/Escaper.phpnu W+A */ final class Twig_NodeVisitor_Escaper extends Twig_BaseNodeVisitor { private $statusStack = array(); private $blocks = array(); private $safeAnalysis; private $traverser; private $defaultStrategy = false; private $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; } private 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() ); } private 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; } private function isSafeFor($type, Twig_Node $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); } private function needEscaping(Twig_Environment $env) { if (count($this->statusStack)) { return $this->statusStack[count($this->statusStack) - 1]; } return $this->defaultStrategy ? $this->defaultStrategy : false; } private function getEscaperFilter($type, Twig_Node $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; } } class_alias('Twig_NodeVisitor_Escaper', 'Twig\NodeVisitor\EscaperNodeVisitor', false); PK e!dLkeEG " lib/Twig/NodeVisitor/Optimizer.phpnu W+A */ final class Twig_NodeVisitor_Optimizer extends Twig_BaseNodeVisitor { const OPTIMIZE_ALL = -1; const OPTIMIZE_NONE = 0; const OPTIMIZE_FOR = 2; const OPTIMIZE_RAW_FILTER = 4; // obsolete, does not do anything const OPTIMIZE_VAR_ACCESS = 8; private $loops = array(); private $loopsTargets = array(); private $optimizers; /** * @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); } return $node; } protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) { 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); return $node; } /** * Optimizes print nodes. * * It replaces: * * * "echo $this->render(Parent)Block()" with "$this->display(Parent)Block()" * * @return Twig_Node */ private function optimizePrintNode(Twig_Node $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_Node */ private function optimizeRawFilter(Twig_Node $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. */ private function enterOptimizeFor(Twig_Node $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. */ private function leaveOptimizeFor(Twig_Node $node, Twig_Environment $env) { if ($node instanceof Twig_Node_For) { array_shift($this->loops); array_shift($this->loopsTargets); array_shift($this->loopsTargets); } } private function addLoopToCurrent() { $this->loops[0]->setAttribute('with_loop', true); } private function addLoopToAll() { foreach ($this->loops as $loop) { $loop->setAttribute('with_loop', true); } } public function getPriority() { return 255; } } class_alias('Twig_NodeVisitor_Optimizer', 'Twig\NodeVisitor\OptimizerNodeVisitor', false); PK e!dLqD 4 4 lib/Twig/ExtensionSet.phpnu W+A * * @internal */ final class Twig_ExtensionSet { private $extensions; private $initialized = false; private $runtimeInitialized = false; private $staging; private $parsers; private $visitors; private $filters; private $tests; private $functions; private $unaryOperators; private $binaryOperators; private $globals; private $functionCallbacks = array(); private $filterCallbacks = array(); private $lastModified = 0; public function __construct() { $this->staging = new Twig_Extension_Staging(); } /** * Initializes the runtime environment. */ public function initRuntime(Twig_Environment $env) { if ($this->runtimeInitialized) { return; } $this->runtimeInitialized = true; foreach ($this->extensions as $extension) { if ($extension instanceof Twig_Extension_InitRuntimeInterface) { $extension->initRuntime($env); } } } /** * Returns true if the given extension is registered. * * @param string $class The extension class name * * @return bool Whether the extension is registered or not */ public function hasExtension($class) { $class = ltrim($class, '\\'); if (!isset($this->extensions[$class]) && class_exists($class, false)) { // For BC/FC with namespaced aliases $class = (new ReflectionClass($class))->name; } return isset($this->extensions[$class]); } /** * Gets an extension by class name. * * @param string $class The extension class name * * @return Twig_ExtensionInterface A Twig_ExtensionInterface instance */ public function getExtension($class) { $class = ltrim($class, '\\'); if (!isset($this->extensions[$class]) && class_exists($class, false)) { // For BC/FC with namespaced aliases $class = (new ReflectionClass($class))->name; } if (!isset($this->extensions[$class])) { throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $class)); } return $this->extensions[$class]; } /** * Registers an array of extensions. * * @param array $extensions An array of extensions */ public function setExtensions(array $extensions) { foreach ($extensions as $extension) { $this->addExtension($extension); } } /** * Returns all registered extensions. * * @return array An array of extensions */ public function getExtensions() { return $this->extensions; } public function getSignature() { return json_encode(array_keys($this->extensions)); } public function isInitialized() { return $this->initialized || $this->runtimeInitialized; } public function getLastModified() { if (0 !== $this->lastModified) { return $this->lastModified; } foreach ($this->extensions as $extension) { $r = new ReflectionObject($extension); if (file_exists($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $this->lastModified) { $this->lastModified = $extensionTime; } } return $this->lastModified; } /** * Registers an extension. * * @param Twig_ExtensionInterface $extension A Twig_ExtensionInterface instance */ public function addExtension(Twig_ExtensionInterface $extension) { $class = get_class($extension); if ($this->initialized) { throw new LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $class)); } if (isset($this->extensions[$class])) { throw new LogicException(sprintf('Unable to register extension "%s" as it is already registered.', $class)); } $this->extensions[$class] = $extension; } public function addFunction(Twig_Function $function) { if ($this->initialized) { throw new LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $function->getName())); } $this->staging->addFunction($function); } public function getFunctions() { if (!$this->initialized) { $this->initExtensions(); } return $this->functions; } /** * Get a function by name. * * @param string $name function name * * @return Twig_Function|false A Twig_Function instance or false if the function does not exist */ public function getFunction($name) { if (!$this->initialized) { $this->initExtensions(); } if (isset($this->functions[$name])) { return $this->functions[$name]; } foreach ($this->functions as $pattern => $function) { $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count); if ($count && preg_match('#^'.$pattern.'$#', $name, $matches)) { array_shift($matches); $function->setArguments($matches); return $function; } } foreach ($this->functionCallbacks as $callback) { if (false !== $function = $callback($name)) { return $function; } } return false; } public function registerUndefinedFunctionCallback(callable $callable) { $this->functionCallbacks[] = $callable; } public function addFilter(Twig_Filter $filter) { if ($this->initialized) { throw new LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $filter->getName())); } $this->staging->addFilter($filter); } public function getFilters() { if (!$this->initialized) { $this->initExtensions(); } return $this->filters; } /** * Get a filter by name. * * Subclasses may override this method and load filters differently; * so no list of filters is available. * * @param string $name The filter name * * @return Twig_Filter|false A Twig_Filter instance or false if the filter does not exist */ public function getFilter($name) { if (!$this->initialized) { $this->initExtensions(); } if (isset($this->filters[$name])) { return $this->filters[$name]; } foreach ($this->filters as $pattern => $filter) { $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count); if ($count && preg_match('#^'.$pattern.'$#', $name, $matches)) { array_shift($matches); $filter->setArguments($matches); return $filter; } } foreach ($this->filterCallbacks as $callback) { if (false !== $filter = $callback($name)) { return $filter; } } return false; } public function registerUndefinedFilterCallback(callable $callable) { $this->filterCallbacks[] = $callable; } public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { if ($this->initialized) { throw new LogicException('Unable to add a node visitor as extensions have already been initialized.'); } $this->staging->addNodeVisitor($visitor); } public function getNodeVisitors() { if (!$this->initialized) { $this->initExtensions(); } return $this->visitors; } public function addTokenParser(Twig_TokenParserInterface $parser) { if ($this->initialized) { throw new LogicException('Unable to add a token parser as extensions have already been initialized.'); } $this->staging->addTokenParser($parser); } public function getTokenParsers() { if (!$this->initialized) { $this->initExtensions(); } return $this->parsers; } public function getGlobals() { if (null !== $this->globals) { return $this->globals; } $globals = array(); foreach ($this->extensions as $extension) { if (!$extension instanceof Twig_Extension_GlobalsInterface) { continue; } $extGlobals = $extension->getGlobals(); if (!is_array($extGlobals)) { throw new UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', get_class($extension))); } $globals = array_merge($globals, $extGlobals); } if ($this->initialized) { $this->globals = $globals; } return $globals; } public function addTest(Twig_Test $test) { if ($this->initialized) { throw new LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $test->getName())); } $this->staging->addTest($test); } public function getTests() { if (!$this->initialized) { $this->initExtensions(); } return $this->tests; } /** * Gets a test by name. * * @param string $name The test name * * @return Twig_Test|false A Twig_Test instance or false if the test does not exist */ public function getTest($name) { if (!$this->initialized) { $this->initExtensions(); } if (isset($this->tests[$name])) { return $this->tests[$name]; } return false; } /** * Gets the registered unary Operators. * * @return array An array of unary operators */ public function getUnaryOperators() { if (!$this->initialized) { $this->initExtensions(); } return $this->unaryOperators; } /** * Gets the registered binary Operators. * * @return array An array of binary operators */ public function getBinaryOperators() { if (!$this->initialized) { $this->initExtensions(); } return $this->binaryOperators; } private function initExtensions() { $this->parsers = array(); $this->filters = array(); $this->functions = array(); $this->tests = array(); $this->visitors = array(); $this->unaryOperators = array(); $this->binaryOperators = array(); foreach ($this->extensions as $extension) { $this->initExtension($extension); } $this->initExtension($this->staging); // Done at the end only, so that an exception during initialization does not mark the environment as initialized when catching the exception $this->initialized = true; } private function initExtension(Twig_ExtensionInterface $extension) { // filters foreach ($extension->getFilters() as $filter) { $this->filters[$filter->getName()] = $filter; } // functions foreach ($extension->getFunctions() as $function) { $this->functions[$function->getName()] = $function; } // tests foreach ($extension->getTests() as $test) { $this->tests[$test->getName()] = $test; } // token parsers foreach ($extension->getTokenParsers() as $parser) { if (!$parser instanceof Twig_TokenParserInterface) { throw new LogicException('getTokenParsers() must return an array of Twig_TokenParserInterface.'); } $this->parsers[] = $parser; } // node visitors foreach ($extension->getNodeVisitors() as $visitor) { $this->visitors[] = $visitor; } // operators if ($operators = $extension->getOperators()) { if (!is_array($operators)) { throw new InvalidArgumentException(sprintf('"%s::getOperators()" must return an array with operators, got "%s".', get_class($extension), is_object($operators) ? get_class($operators) : gettype($operators).(is_resource($operators) ? '' : '#'.$operators))); } if (2 !== count($operators)) { throw new InvalidArgumentException(sprintf('"%s::getOperators()" must return an array of 2 elements, got %d.', get_class($extension), count($operators))); } $this->unaryOperators = array_merge($this->unaryOperators, $operators[0]); $this->binaryOperators = array_merge($this->binaryOperators, $operators[1]); } } } class_alias('Twig_ExtensionSet', 'Twig\ExtensionSet', false); PK e!dLm<~) ) lib/Twig/Parser.phpnu W+A */ class Twig_Parser { private $stack = array(); private $stream; private $parent; private $handlers; private $visitors; private $expressionParser; private $blocks; private $blockStack; private $macros; private $env; private $importedSymbols; private $traits; private $embeddedTemplates = array(); private $varNameSalt = 0; public function __construct(Twig_Environment $env) { $this->env = $env; } public function getVarName() { return sprintf('__internal_%s', hash('sha256', __METHOD__.$this->varNameSalt++)); } public function parse(Twig_TokenStream $stream, $test = null, $dropNeedle = false) { $vars = get_object_vars($this); unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames']); $this->stack[] = $vars; // tag handlers if (null === $this->handlers) { $this->handlers = array(); foreach ($this->env->getTokenParsers() as $handler) { $handler->setParser($this); $this->handlers[$handler->getTag()] = $handler; } } // 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(); $this->varNameSalt = 0; 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 (Twig_Token::NAME_TYPE !== $token->getType()) { throw new Twig_Error_Syntax('A block must start with a tag name.', $token->getLine(), $this->stream->getSourceContext()); } if (null !== $test && $test($token)) { if ($dropNeedle) { $this->stream->next(); } if (1 === count($rv)) { return $rv[0]; } return new Twig_Node($rv, array(), $lineno); } if (!isset($this->handlers[$token->getValue()])) { 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(); $subparser = $this->handlers[$token->getValue()]; $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); } 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) { $this->macros[$name] = $node; } public function isReservedMacroName($name) { return false; } 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(); } private function filterBodyNodes(Twig_Node $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 content outside Twig blocks. Did you forget to put the content inside a {% block %} tag?', $node->getTemplateLine(), $this->stream->getSourceContext()); } // bypass nodes that will "capture" the output if ($node instanceof Twig_NodeCaptureInterface) { 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; } } class_alias('Twig_Parser', 'Twig\Parser', false); class_exists('Twig_Node'); class_exists('Twig_TokenStream'); PK e!dLW lib/Twig/Node.phpnu W+A */ class Twig_Node implements Countable, IteratorAggregate { 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 self) { throw new InvalidArgumentException(sprintf('Using "%s" for the value of node "%s" of "%s" is not supported. You must pass a Twig_Node instance.', is_object($node) ? get_class($node) : null === $node ? 'null' : gettype($node), $name, get_class($this))); } } $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); } public function compile(Twig_Compiler $compiler) { foreach ($this->nodes as $node) { $node->compile($compiler); } } public function getTemplateLine() { 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 isset($this->nodes[$name]); } /** * @return Twig_Node */ public function getNode($name) { if (!isset($this->nodes[$name])) { throw new LogicException(sprintf('Node "%s" does not exist for Node "%s".', $name, get_class($this))); } return $this->nodes[$name]; } public function setNode($name, self $node) { $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) { $node->setTemplateName($name); } } public function getTemplateName() { return $this->name; } } class_alias('Twig_Node', 'Twig\Node\Node', false); class_exists('Twig_Compiler'); PK e!dLN N lib/Twig/Markup.phpnu W+A */ class Twig_Markup implements Countable, JsonSerializable { private $content; private $charset; public function __construct($content, $charset) { $this->content = (string) $content; $this->charset = $charset; } public function __toString() { return $this->content; } public function count() { return mb_strlen($this->content, $this->charset); } public function jsonSerialize() { return $this->content; } } class_alias('Twig_Markup', 'Twig\Markup', false); PK e!dL.f lib/Twig/Source.phpnu W+A */ final 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; } } class_alias('Twig_Source', 'Twig\Source', false); PK e!dL9e3 3 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'; } } class_alias('Twig_TokenParser_Import', 'Twig\TokenParser\ImportTokenParser', false); PK e!dLLTc lib/Twig/TokenParser/For.phpnu W+A *
* {{ post.published_at|date("m/d/Y") }} ** * @param Twig_Environment $env * @param 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 DateTimeInterface|string $date A date * @param string $modifier A modifier string * * @return DateTimeInterface A new date object */ function twig_date_modify_filter(Twig_Environment $env, $date, $modifier) { $date = twig_date_converter($env, $date, false); return $date->modify($modifier); } /** * Converts an input to a DateTime instance. * *
* {% if date(user.created_at) < date('+2days') %} * {# do something #} * {% endif %} ** * @param Twig_Environment $env * @param DateTimeInterface|string|null $date A date or null to use the current time * @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 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 * * @return string */ function twig_replace_filter($str, $from) { if ($from instanceof Traversable) { $from = iterator_to_array($from); } 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)) { return http_build_query($url, '', '&', PHP_QUERY_RFC3986); } return rawurlencode($url); } /** * 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) { while ($item instanceof IteratorAggregate) { $item = $item->getIterator(); } if ($start >= 0 && $length >= 0 && $item instanceof Iterator) { try { return iterator_to_array(new LimitIterator($item, $start, null === $length ? -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; return (string) mb_substr($item, $start, $length, $env->getCharset()); } /** * 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 ($limit <= 1) { return preg_split('/(?getCharset()); if ($length < $limit) { return array($value); } $r = array(); for ($i = 0; $i < $length; $i += $limit) { $r[] = mb_substr($value, $i, $limit, $env->getCharset()); } return $r; } // The '_default' filter is used internally to avoid using the ternary operator // which costs a lot for big contexts (before PHP 5.4). So, on average, // a function call is cheaper. /** * @internal */ function _twig_default_filter($value, $default = '') { if (twig_test_empty($value)) { return $default; } return $value; } /** * Returns the keys for the given array. * * It is useful when you want to iterate over the keys of an array: * *
* {% 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) { while ($array instanceof IteratorAggregate) { $array = $array->getIterator(); } if ($array instanceof Iterator) { $keys = array(); $array->rewind(); while ($array->valid()) { $keys[] = $array->key(); $array->next(); } return $keys; } $keys = array(); foreach ($array as $key => $item) { $keys[] = $key; } return $keys; } 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); } $string = (string) $item; $charset = $env->getCharset(); if ('UTF-8' !== $charset) { $item = iconv($charset, 'UTF-8', $string); } preg_match_all('/./us', $item, $matches); $string = implode('', array_reverse($matches[0])); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; } /** * 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) { if (is_object($value) || is_resource($value)) { foreach ($compare as $item) { if ($item === $value) { return true; } } } else { foreach ($compare as $item) { if ($item == $value) { return true; } } } return false; } return false; } /** * Returns a trimmed string. * * @return string * * @throws Twig_Error_Runtime When an invalid trimming side is used (not a string or not 'left', 'right', or 'both') */ function twig_trim_filter($string, $characterMask = null, $side = 'both') { if (null === $characterMask) { $characterMask = " \t\n\r\0\x0B"; } switch ($side) { case 'both': return trim($string, $characterMask); case 'left': return ltrim($string, $characterMask); case 'right': return rtrim($string, $characterMask); default: throw new Twig_Error_Runtime('Trimming side must be "left", "right" or "both".'); } } /** * 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 = 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 = iconv($charset, 'UTF-8', $string); $string = htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); return iconv('UTF-8', $charset, $string); case 'js': // escape all non-alphanumeric characters // into their \xHH or \uHHHH representations if ('UTF-8' !== $charset) { $string = iconv($charset, 'UTF-8', $string); } 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', function ($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'); $char = strtoupper(bin2hex($char)); if (4 >= strlen($char)) { return sprintf('\u%04s', $char); } return sprintf('\u%04s\u%04s', substr($char, 0, -4), substr($char, -4)); }, $string); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; case 'css': if ('UTF-8' !== $charset) { $string = iconv($charset, 'UTF-8', $string); } 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', function ($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').' '; }, $string); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; case 'html_attr': if ('UTF-8' !== $charset) { $string = iconv($charset, 'UTF-8', $string); } 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', function ($matches) { /** * 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 */ /* * 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 && "\t" != $chr && "\n" != $chr && "\r" != $chr) || ($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 (1 == strlen($chr)) { $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); }, $string); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; case 'url': return rawurlencode($string); default: static $escapers; if (null === $escapers) { $escapers = $env->getExtension('Twig_Extension_Core')->getEscapers(); } if (isset($escapers[$strategy])) { return $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'); } function twig_convert_encoding($string, $to, $from) { return iconv($from, $to, $string); } /** * Returns the length of a variable. * * @param Twig_Environment $env A Twig_Environment instance * @param mixed $thing A variable * * @return int The length of the value */ function twig_length_filter(Twig_Environment $env, $thing) { if (null === $thing) { return 0; } if (is_scalar($thing)) { return mb_strlen($thing, $env->getCharset()); } if (method_exists($thing, '__toString') && !$thing instanceof \Countable) { return mb_strlen((string) $thing, $env->getCharset()); } if ($thing instanceof \Countable || is_array($thing)) { return count($thing); } if ($thing instanceof \IteratorAggregate) { return iterator_count($thing); } return 1; } /** * 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) { return mb_strtoupper($string, $env->getCharset()); } /** * 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) { return mb_strtolower($string, $env->getCharset()); } /** * 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) { $charset = $env->getCharset(); return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).mb_strtolower(mb_substr($string, 1, null, $charset), $charset); } /** * @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); } if (is_object($value) && method_exists($value, '__toString')) { return '' === (string) $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 iterable %} * {# ... #} * {% 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; } 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 { 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; } /** * Returns the attribute value for a given array/object. * * @param mixed $object The object or array from where to get the item * @param mixed $item The item to get from the array or object * @param array $arguments An array of arguments to pass if the item is an object method * @param string $type The type of attribute (@see Twig_Template constants) * @param bool $isDefinedTest Whether this is only a defined check * @param bool $ignoreStrictCheck Whether to ignore the strict attribute check or not * * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true * * @throws Twig_Error_Runtime if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false * * @internal */ function twig_get_attribute(Twig_Environment $env, Twig_Source $source, $object, $item, array $arguments = array(), $type = /* Twig_Template::ANY_CALL */ 'any', $isDefinedTest = false, $ignoreStrictCheck = false, $sandboxed = false) { // array if (/* Twig_Template::METHOD_CALL */ 'method' !== $type) { $arrayItem = is_bool($item) || is_float($item) ? (int) $item : $item; if ((is_array($object) && (isset($object[$arrayItem]) || array_key_exists($arrayItem, $object))) || ($object instanceof ArrayAccess && isset($object[$arrayItem])) ) { if ($isDefinedTest) { return true; } return $object[$arrayItem]; } if (/* Twig_Template::ARRAY_CALL */ 'array' === $type || !is_object($object)) { if ($isDefinedTest) { return false; } if ($ignoreStrictCheck || !$env->isStrictVariables()) { return; } if ($object instanceof ArrayAccess) { $message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.', $arrayItem, get_class($object)); } elseif (is_object($object)) { $message = sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.', $item, get_class($object)); } elseif (is_array($object)) { if (empty($object)) { $message = sprintf('Key "%s" does not exist as the array is empty.', $arrayItem); } else { $message = sprintf('Key "%s" for array with keys "%s" does not exist.', $arrayItem, implode(', ', array_keys($object))); } } elseif (/* Twig_Template::ARRAY_CALL */ 'array' === $type) { if (null === $object) { $message = sprintf('Impossible to access a key ("%s") on a null variable.', $item); } else { $message = sprintf('Impossible to access a key ("%s") on a %s variable ("%s").', $item, gettype($object), $object); } } elseif (null === $object) { $message = sprintf('Impossible to access an attribute ("%s") on a null variable.', $item); } else { $message = sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s").', $item, gettype($object), $object); } throw new Twig_Error_Runtime($message, -1, $source); } } if (!is_object($object)) { if ($isDefinedTest) { return false; } if ($ignoreStrictCheck || !$env->isStrictVariables()) { return; } if (null === $object) { $message = sprintf('Impossible to invoke a method ("%s") on a null variable.', $item); } elseif (is_array($object)) { $message = sprintf('Impossible to invoke a method ("%s") on an array.', $item); } else { $message = sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s").', $item, gettype($object), $object); } throw new Twig_Error_Runtime($message, -1, $source); } if ($object instanceof Twig_Template) { throw new Twig_Error_Runtime('Accessing Twig_Template attributes is forbidden.'); } // object property if (/* Twig_Template::METHOD_CALL */ 'method' !== $type) { if (isset($object->$item) || array_key_exists((string) $item, $object)) { if ($isDefinedTest) { return true; } if ($sandboxed) { $env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object, $item); } return $object->$item; } } static $cache = array(); $class = get_class($object); // object method // precedence: getXxx() > isXxx() > hasXxx() if (!isset($cache[$class])) { $methods = get_class_methods($object); sort($methods); $lcMethods = array_map('strtolower', $methods); $classCache = array(); foreach ($methods as $i => $method) { $classCache[$method] = $method; $classCache[$lcName = $lcMethods[$i]] = $method; if ('g' === $lcName[0] && 0 === strpos($lcName, 'get')) { $name = substr($method, 3); $lcName = substr($lcName, 3); } elseif ('i' === $lcName[0] && 0 === strpos($lcName, 'is')) { $name = substr($method, 2); $lcName = substr($lcName, 2); } elseif ('h' === $lcName[0] && 0 === strpos($lcName, 'has')) { $name = substr($method, 3); $lcName = substr($lcName, 3); if (in_array('is'.$lcName, $lcMethods)) { continue; } } else { continue; } // skip get() and is() methods (in which case, $name is empty) if ($name) { if (!isset($classCache[$name])) { $classCache[$name] = $method; } if (!isset($classCache[$lcName])) { $classCache[$lcName] = $method; } } } $cache[$class] = $classCache; } $call = false; if (isset($cache[$class][$item])) { $method = $cache[$class][$item]; } elseif (isset($cache[$class][$lcItem = strtolower($item)])) { $method = $cache[$class][$lcItem]; } elseif (isset($cache[$class]['__call'])) { $method = $item; $call = true; } else { if ($isDefinedTest) { return false; } if ($ignoreStrictCheck || !$env->isStrictVariables()) { return; } throw new Twig_Error_Runtime(sprintf('Neither the property "%1$s" nor one of the methods "%1$s()", "get%1$s()"/"is%1$s()"/"has%1$s()" or "__call()" exist and have public access in class "%2$s".', $item, $class), -1, $source); } if ($isDefinedTest) { return true; } if ($sandboxed) { $env->getExtension('Twig_Extension_Sandbox')->checkMethodAllowed($object, $method); } // Some objects throw exceptions when they have __call, and the method we try // to call is not supported. If ignoreStrictCheck is true, we should return null. try { $ret = $object->$method(...$arguments); } catch (BadMethodCallException $e) { if ($call && ($ignoreStrictCheck || !$env->isStrictVariables())) { return; } throw $e; } return $ret; } class_alias('Twig_Extension_Core', 'Twig\Extension\CoreExtension', false); PK e!dL6Y lib/Twig/Extension/Debug.phpnu W+A $isDumpOutputHtmlSafe ? array('html') : array(), 'needs_context' => true, 'needs_environment' => true)), ); } } function twig_var_dump(Twig_Environment $env, $context, ...$vars) { if (!$env->isDebug()) { return; } ob_start(); if (!$vars) { $vars = array(); foreach ($context as $key => $value) { if (!$value instanceof Twig_Template) { $vars[$key] = $value; } } var_dump($vars); } else { var_dump(...$vars); } return ob_get_clean(); } class_alias('Twig_Extension_Debug', 'Twig\Extension\DebugExtension', false); PK e!dL_ ! ! 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))); } } class_alias('Twig_Extension_Profiler', 'Twig\Extension\ProfilerExtension', false); class_exists('Twig_Profiler_Profile'); PK e!dLT8(( ( lib/Twig/Extension/Staging.phpnu W+A * * @internal */ final class Twig_Extension_Staging extends Twig_Extension { private $functions = array(); private $filters = array(); private $visitors = array(); private $tokenParsers = array(); private $tests = array(); public function addFunction(Twig_Function $function) { if (isset($this->functions[$function->getName()])) { throw new LogicException(sprintf('Function "%s" is already registered.', $function->getName())); } $this->functions[$function->getName()] = $function; } public function getFunctions() { return $this->functions; } public function addFilter(Twig_Filter $filter) { if (isset($this->filters[$filter->getName()])) { throw new LogicException(sprintf('Filter "%s" is already registered.', $filter->getName())); } $this->filters[$filter->getName()] = $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()])) { throw new LogicException(sprintf('Tag "%s" is already registered.', $parser->getTag())); } $this->tokenParsers[$parser->getTag()] = $parser; } public function getTokenParsers() { return $this->tokenParsers; } public function addTest(Twig_Test $test) { if (isset($this->tests[$test->getName()])) { throw new LogicException(sprintf('Test "%s" is already registered.', $test->getTag())); } $this->tests[$test->getName()] = $test; } public function getTests() { return $this->tests; } } class_alias('Twig_Extension_Staging', 'Twig\Extension\StagingExtension', false); PK e!dL[ hy y 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; } } class_alias('Twig_Extension_Sandbox', 'Twig\Extension\SandboxExtension', false); PK e!dL-4 4 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_Filter('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) { 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; } } /** * Marks a variable as being safe. * * @param string $string A PHP variable * * @return string */ function twig_raw_filter($string) { return $string; } class_alias('Twig_Extension_Escaper', 'Twig\Extension\EscaperExtension', false); PK e!dL`] ] lib/Twig/Extension/Optimizer.phpnu W+A optimizers = $optimizers; } public function getNodeVisitors() { return array(new Twig_NodeVisitor_Optimizer($this->optimizers)); } } class_alias('Twig_Extension_Optimizer', 'Twig\Extension\OptimizerExtension', false); PK e!dL"L ' lib/Twig/Extension/GlobalsInterface.phpnu W+A */ interface Twig_Extension_GlobalsInterface { /** * Returns a list of global variables to add to the existing list. * * @return array An array of global variables */ public function getGlobals(); } class_alias('Twig_Extension_GlobalsInterface', 'Twig\Extension\GlobalsInterface', false); PK e!dLo # lib/Twig/Extension/StringLoader.phpnu W+A true)), ); } } /** * 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); } class_alias('Twig_Extension_StringLoader', 'Twig\Extension\StringLoaderExtension', false); PK e!dLhY + lib/Twig/Extension/InitRuntimeInterface.phpnu W+A */ interface Twig_Extension_InitRuntimeInterface { /** * Initializes the runtime environment. * * This is where you can load some file that contains filter functions for instance. * * @param Twig_Environment $environment The current Twig_Environment instance */ public function initRuntime(Twig_Environment $environment); } class_alias('Twig_Extension_InitRuntimeInterface', 'Twig\Extension\InitRuntimeInterface', false); PK e!dLzw # lib/Twig/ContainerRuntimeLoader.phpnu W+A * @author Robin Chalas