PK 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, ); } public function enterNode(Twig_NodeInterface $node, Twig_Environment $env) { return $node; } public function leaveNode(Twig_NodeInterface $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); } /** * {@inheritdoc} */ public function getPriority() { return 0; } } PK J|( ( lib/Twig/NodeVisitor/Sandbox.phpnu W+A */ class Twig_NodeVisitor_Sandbox implements Twig_NodeVisitorInterface { protected $inAModule = false; protected $tags; protected $filters; protected $functions; /** * Called before child nodes are visited. * * @param Twig_NodeInterface $node The node to visit * @param Twig_Environment $env The Twig environment instance * * @return Twig_NodeInterface The modified node */ public function enterNode(Twig_NodeInterface $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()) { $this->tags[] = $node->getNodeTag(); } // look for filters if ($node instanceof Twig_Node_Expression_Filter) { $this->filters[] = $node->getNode('filter')->getAttribute('value'); } // look for functions if ($node instanceof Twig_Node_Expression_Function) { $this->functions[] = $node->getAttribute('name'); } // wrap print to check __toString() calls if ($node instanceof Twig_Node_Print) { return new Twig_Node_SandboxedPrint($node->getNode('expr'), $node->getLine(), $node->getNodeTag()); } } return $node; } /** * Called after child nodes are visited. * * @param Twig_NodeInterface $node The node to visit * @param Twig_Environment $env The Twig environment instance * * @return Twig_NodeInterface The modified node */ public function leaveNode(Twig_NodeInterface $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Module) { $this->inAModule = false; return new Twig_Node_SandboxedModule($node, array_unique($this->filters), array_unique($this->tags), array_unique($this->functions)); } return $node; } /** * {@inheritdoc} */ public function getPriority() { return 0; } } PK JS$ lib/Twig/NodeVisitor/Escaper.phpnu W+A */ class Twig_NodeVisitor_Escaper implements Twig_NodeVisitorInterface { 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(); } /** * Called before child nodes are visited. * * @param Twig_NodeInterface $node The node to visit * @param Twig_Environment $env The Twig environment instance * * @return Twig_NodeInterface The modified node */ public function enterNode(Twig_NodeInterface $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Module) { if ($env->hasExtension('escaper') && $defaultStrategy = $env->getExtension('escaper')->getDefaultStrategy($node->getAttribute('filename'))) { $this->defaultStrategy = $defaultStrategy; } $this->safeVars = 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; } /** * Called after child nodes are visited. * * @param Twig_NodeInterface $node The node to visit * @param Twig_Environment $env The Twig environment instance * * @return Twig_NodeInterface The modified node */ public function leaveNode(Twig_NodeInterface $node, Twig_Environment $env) { if ($node instanceof Twig_Node_Module) { $this->defaultStrategy = false; $this->safeVars = 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->getLine() ); } 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->getLine(); $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); } /** * {@inheritdoc} */ public function getPriority() { return 0; } } PK Jl. . " lib/Twig/NodeVisitor/Optimizer.phpnu W+A */ class Twig_NodeVisitor_Optimizer implements Twig_NodeVisitorInterface { 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 $optimizers; protected $prependedNodes = array(); protected $inABody = false; /** * Constructor. * * @param integer $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; } /** * {@inheritdoc} */ public function enterNode(Twig_NodeInterface $node, Twig_Environment $env) { if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR & $this->optimizers)) { $this->enterOptimizeFor($node, $env); } if (!version_compare(phpversion(), '5.4.0RC1', '>=') && self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) && !$env->isStrictVariables() && !$env->hasExtension('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; } /** * {@inheritdoc} */ public function leaveNode(Twig_NodeInterface $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('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->getLine()); } $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->getLine()); } return $node; } /** * Optimizes print nodes. * * It replaces: * * * "echo $this->render(Parent)Block()" with "$this->display(Parent)Block()" * * @param Twig_NodeInterface $node A Node * @param Twig_Environment $env The current Twig environment */ protected function optimizePrintNode(Twig_NodeInterface $node, Twig_Environment $env) { if (!$node instanceof Twig_Node_Print) { return $node; } if ( $node->getNode('expr') instanceof Twig_Node_Expression_BlockReference || $node->getNode('expr') instanceof Twig_Node_Expression_Parent ) { $node->getNode('expr')->setAttribute('output', true); return $node->getNode('expr'); } return $node; } /** * Removes "raw" filters. * * @param Twig_NodeInterface $node A Node * @param Twig_Environment $env The current Twig environment */ 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. * * @param Twig_NodeInterface $node A Node * @param Twig_Environment $env The current Twig environment */ 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); } 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')) { $this->addLoopToCurrent(); } // 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(); } // 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. * * @param Twig_NodeInterface $node A Node * @param Twig_Environment $env The current Twig environment */ protected function leaveOptimizeFor(Twig_NodeInterface $node, Twig_Environment $env) { if ($node instanceof Twig_Node_For) { array_shift($this->loops); } } protected function addLoopToCurrent() { $this->loops[0]->setAttribute('with_loop', true); } protected function addLoopToAll() { foreach ($this->loops as $loop) { $loop->setAttribute('with_loop', true); } } /** * {@inheritdoc} */ public function getPriority() { return 255; } } PK JO^ lib/Twig/Autoloader.phpnu W+A */ class Twig_Autoloader { /** * Registers Twig_Autoloader as an SPL autoloader. * * @param Boolean $prepend Whether to prepend the autoloader or not. */ public static function register($prepend = false) { if (version_compare(phpversion(), '5.3.0', '>=')) { spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend); } else { spl_autoload_register(array(__CLASS__, 'autoload')); } } /** * 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 JhW- - 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(); /** * Constructor. * * @param Twig_Environment $env A Twig_Environment instance */ public function __construct(Twig_Environment $env) { $this->env = $env; } public function getEnvironment() { return $this->env; } public function getVarName() { return sprintf('__internal_%s', hash('sha256', uniqid(mt_rand(), true), false)); } public function getFilename() { return $this->stream->getFilename(); } /** * {@inheritdoc} */ public function parse(Twig_TokenStream $stream, $test = null, $dropNeedle = false) { // push all variables into the stack to keep the current state of the parser $vars = get_object_vars($this); unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser']); $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->getUnaryOperators(), $this->env->getBinaryOperators()); } $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) { if (null === $body = $this->filterBodyNodes($body)) { $body = new Twig_Node(); } } } catch (Twig_Error_Syntax $e) { if (!$e->getTemplateFile()) { $e->setTemplateFile($this->getFilename()); } 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, $this->getFilename()); $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->getFilename()); } 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) { $error = sprintf('Unexpected tag name "%s"', $token->getValue()); if (is_array($test) && isset($test[0]) && $test[0] instanceof Twig_TokenParserInterface) { $error .= sprintf(' (expecting closing tag for the "%s" tag defined near line %s)', $test[0]->getTag(), $lineno); } throw new Twig_Error_Syntax($error, $token->getLine(), $this->getFilename()); } $message = sprintf('Unknown tag name "%s"', $token->getValue()); if ($alternatives = $this->env->computeAlternatives($token->getValue(), array_keys($this->env->getTags()))) { $message = sprintf('%s. Did you mean "%s"', $message, implode('", "', $alternatives)); } throw new Twig_Error_Syntax($message, $token->getLine(), $this->getFilename()); } $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.', 0, $this->getFilename()); } } if (1 === count($rv)) { return $rv[0]; } return new Twig_Node($rv, array(), $lineno); } public function addHandler($name, $class) { $this->handlers[$name] = $class; } public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { $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->getLine()); } public function hasMacro($name) { return isset($this->macros[$name]); } public function setMacro($name, Twig_Node_Macro $node) { if (null === $this->reservedMacroNames) { $this->reservedMacroNames = array(); $r = new ReflectionClass($this->env->getBaseTemplateClass()); foreach ($r->getMethods() as $method) { $this->reservedMacroNames[] = $method->getName(); } } if (in_array($name, $this->reservedMacroNames)) { throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword', $name), $node->getLine(), $this->getFilename()); } $this->macros[$name] = $node; } 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); } /** * Gets the expression parser. * * @return Twig_ExpressionParser The expression parser */ public function getExpressionParser() { return $this->expressionParser; } public function getParent() { return $this->parent; } public function setParent($parent) { $this->parent = $parent; } /** * Gets the token stream. * * @return Twig_TokenStream The token stream */ public function getStream() { return $this->stream; } /** * Gets the current token. * * @return Twig_Token The current 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 have a body but a byte order mark (BOM) has been detected; it must be removed.', $node->getLine(), $this->getFilename()); } throw new Twig_Error_Syntax('A template that extends another one cannot have a body.', $node->getLine(), $this->getFilename()); } // 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 J^Ʀ\ ' 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 null|Twig_TokenParserInterface 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. * * @param Twig_ParserInterface $parser A Twig_ParserInterface interface */ public function setParser(Twig_ParserInterface $parser); /** * Gets the Twig_ParserInterface. * * @return null|Twig_ParserInterface A Twig_ParserInterface instance or null */ public function getParser(); } PK JT7^ lib/Twig/Node.phpnu W+A */ class Twig_Node implements Twig_NodeInterface { protected $nodes; protected $attributes; protected $lineno; protected $tag; /** * 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 integer $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) { $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 toXml($asDom = false) { $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 getLine() { return $this->lineno; } public function getNodeTag() { return $this->tag; } /** * Returns true if the attribute is defined. * * @param string The attribute name * * @return Boolean true if the attribute is defined, false otherwise */ public function hasAttribute($name) { return array_key_exists($name, $this->attributes); } /** * Gets an attribute. * * @param string The attribute name * * @return mixed The attribute value */ 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]; } /** * Sets an attribute. * * @param string The attribute name * @param mixed The attribute value */ public function setAttribute($name, $value) { $this->attributes[$name] = $value; } /** * Removes an attribute. * * @param string The attribute name */ public function removeAttribute($name) { unset($this->attributes[$name]); } /** * Returns true if the node with the given identifier exists. * * @param string The node name * * @return Boolean true if the node with the given name exists, false otherwise */ public function hasNode($name) { return array_key_exists($name, $this->nodes); } /** * Gets a node by name. * * @param string The node name * * @return Twig_Node A Twig_Node instance */ 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]; } /** * Sets a node. * * @param string The node name * @param Twig_Node A Twig_Node instance */ public function setNode($name, $node = null) { $this->nodes[$name] = $node; } /** * Removes a node by name. * * @param string The node name */ public function removeNode($name) { unset($this->nodes[$name]); } public function count() { return count($this->nodes); } public function getIterator() { return new ArrayIterator($this->nodes); } } PK 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 JSN N 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 J8 lib/Twig/TokenParser/Import.phpnu W+A * {% import 'forms.html' as forms %} * */ class Twig_TokenParser_Import extends Twig_TokenParser { /** * Parses a token and returns a node. * * @param Twig_Token $token A Twig_Token instance * * @return Twig_NodeInterface A Twig_NodeInterface instance */ 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()); } /** * Gets the tag name associated with this token parser. * * @return string The tag name */ public function getTag() { return 'import'; } } PK JV lib/Twig/TokenParser/For.phpnu W+A *
* {{ post.published_at|date("m/d/Y") }} ** * @param Twig_Environment $env A Twig_Environment instance * @param DateTime|DateInterval|string $date A date * @param string $format A format * @param DateTimeZone|string $timezone A timezone * * @return string The formatted date */ function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $timezone = null) { if (null === $format) { $formats = $env->getExtension('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 A Twig_Environment instance * @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); $date->modify($modifier); return $date; } /** * Converts an input to a DateTime instance. * *
* {% if date(user.created_at) < date('+2days') %} * {# do something #} * {% endif %} ** * @param Twig_Environment $env A Twig_Environment instance * @param DateTime|string $date A date * @param DateTimeZone|string $timezone A timezone * * @return DateTime A DateTime instance */ function twig_date_converter(Twig_Environment $env, $date = null, $timezone = null) { // determine the timezone if (!$timezone) { $defaultTimezone = $env->getExtension('core')->getTimezone(); } elseif (!$timezone instanceof DateTimeZone) { $defaultTimezone = new DateTimeZone($timezone); } else { $defaultTimezone = $timezone; } // immutable dates if ($date instanceof DateTimeImmutable) { return false !== $timezone ? $date->setTimezone($defaultTimezone) : $date; } if ($date instanceof DateTime || $date instanceof DateTimeInterface) { $date = clone $date; if (false !== $timezone) { $date->setTimezone($defaultTimezone); } return $date; } $asString = (string) $date; if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) { $date = '@'.$date; } $date = new DateTime($date, $defaultTimezone); if (false !== $timezone) { $date->setTimezone($defaultTimezone); } return $date; } /** * Rounds a number. * * @param integer|float $value The value to round * @param integer|float $precision The rounding precision * @param string $method The method to use for rounding * * @return integer|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 A Twig_Environment instance * @param mixed $number A float/int/string of the number to format * @param integer $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('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 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 * @param Boolean $raw true to use rawurlencode() instead of urlencode * * @return string The URL encoded value */ function twig_urlencode_filter($url, $raw = false) { if (is_array($url)) { return http_build_query($url, '', '&'); } if ($raw) { return rawurlencode($url); } return urlencode($url); } if (version_compare(PHP_VERSION, '5.3.0', '<')) { /** * JSON encodes a variable. * * @param mixed $value The value to encode. * @param integer $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 integer $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 $arr1 An array * @param array $arr2 An array * * @return array The merged array */ function twig_array_merge($arr1, $arr2) { if (!is_array($arr1) || !is_array($arr2)) { throw new Twig_Error_Runtime('The merge filter only works with arrays or hashes.'); } return array_merge($arr1, $arr2); } /** * Slices a variable. * * @param Twig_Environment $env A Twig_Environment instance * @param mixed $item A variable * @param integer $start Start of the slice * @param integer $length Size of the slice * @param Boolean $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) { $item = iterator_to_array($item, false); } 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 mb_substr($item, $start, null === $length ? mb_strlen($item, $charset) - $start : $length, $charset); } return null === $length ? substr($item, $start) : substr($item, $start, $length); } /** * Returns the first element of the item. * * @param Twig_Environment $env A Twig_Environment instance * @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 A Twig_Environment instance * @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 string $value A string * @param string $delimiter The delimiter * @param integer $limit The limit * * @return array The split string as an array */ function twig_split_filter($value, $delimiter, $limit = null) { if (empty($delimiter)) { return str_split($value, null === $limit ? 1 : $limit); } return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit); } // 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. 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 (is_object($array) && $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 A Twig_Environment instance * @param array|Traversable|string $item An array, a Traversable instance, or a string * @param Boolean $preserveKeys Whether to preserve key or not * * @return mixed The reversed input */ function twig_reverse_filter(Twig_Environment $env, $item, $preserveKeys = false) { if (is_object($item) && $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 $array An array */ function twig_sort_filter($array) { asort($array); return $array; } /* used internally */ function twig_in_filter($value, $compare) { if (is_array($compare)) { return in_array($value, $compare, is_object($value)); } elseif (is_string($compare)) { if (!strlen($value)) { return empty($compare); } return false !== strpos($compare, (string) $value); } elseif ($compare instanceof Traversable) { return in_array($value, iterator_to_array($compare, false), is_object($value)); } return false; } /** * Escapes a string. * * @param Twig_Environment $env A Twig_Environment instance * @param string $string The value to be escaped * @param string $strategy The escaping strategy * @param string $charset The charset * @param Boolean $autoescape Whether the function is called by the auto-escaping feature (true) or by the developer (false) */ 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; } else { 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 ('hiphop' === substr(PHP_VERSION, -6)) { $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) ? false : true)) { 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) ? false : true)) { 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) ? false : true)) { 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': // hackish test to avoid version_compare that is much slower, this works unless PHP releases a 5.10.* // at that point however PHP 5.2.* support can be removed if (PHP_VERSION < '5.3.0') { return str_replace('%7E', '~', rawurlencode($string)); } return rawurlencode($string); default: static $escapers; if (null === $escapers) { $escapers = $env->getExtension('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)); } } /* used internally */ 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 A Twig_Environment instance * @param mixed $thing A variable * * @return integer 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 A Twig_Environment instance * @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 A Twig_Environment instance * @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 A Twig_Environment instance * @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 A Twig_Environment instance * @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 A Twig_Environment instance * @param mixed $thing A variable * * @return integer 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 A Twig_Environment instance * @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 A Twig_Environment instance * @param string $string A string * * @return string The capitalized string */ function twig_capitalize_string_filter(Twig_Environment $env, $string) { return ucfirst(strtolower($string)); } } /* used internally */ 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 Boolean 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 Boolean true if the value is traversable */ function twig_test_iterable($value) { return $value instanceof Traversable || is_array($value); } /** * Renders a template. * * @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 Boolean $with_context Whether to pass the current context variables or not * @param Boolean $ignore_missing Whether to ignore missing templates or not * @param Boolean $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('sandbox')) { $sandbox = $env->getExtension('sandbox'); if (!$alreadySandboxed = $sandbox->isSandboxed()) { $sandbox->enableSandbox(); } } try { return $env->resolveTemplate($template)->render($variables); } catch (Twig_Error_Loader $e) { if (!$ignoreMissing) { throw $e; } } if ($isSandboxed && !$alreadySandboxed) { $sandbox->disableSandbox(); } } /** * Returns a template content without rendering it. * * @param string $name The template name * * @return string The template source */ function twig_source(Twig_Environment $env, $name) { return $env->getLoader()->getSource($name); } /** * 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); } /** * Batches item. * * @param array $items An array of items * @param integer $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) { $last = count($result) - 1; if ($fillCount = $size - count($result[$last])) { $result[$last] = array_merge( $result[$last], array_fill(0, $fillCount, $fill) ); } } return $result; } PK JrI lib/Twig/Extension/Debug.phpnu W+A $isDumpOutputHtmlSafe ? array('html') : array(), 'needs_context' => true, 'needs_environment' => true)), ); } /** * Returns the name of the extension. * * @return string The extension name */ 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 JNR0 0 lib/Twig/Extension/Staging.phpnu W+A */ 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) { $this->functions[$name] = $function; } /** * {@inheritdoc} */ public function getFunctions() { return $this->functions; } public function addFilter($name, $filter) { $this->filters[$name] = $filter; } /** * {@inheritdoc} */ public function getFilters() { return $this->filters; } public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { $this->visitors[] = $visitor; } /** * {@inheritdoc} */ public function getNodeVisitors() { return $this->visitors; } public function addTokenParser(Twig_TokenParserInterface $parser) { $this->tokenParsers[] = $parser; } /** * {@inheritdoc} */ public function getTokenParsers() { return $this->tokenParsers; } public function addGlobal($name, $value) { $this->globals[$name] = $value; } /** * {@inheritdoc} */ public function getGlobals() { return $this->globals; } public function addTest($name, $test) { $this->tests[$name] = $test; } /** * {@inheritdoc} */ public function getTests() { return $this->tests; } /** * {@inheritdoc} */ public function getName() { return 'staging'; } } PK J