1<?php 2 3/* 4 * This file is part of Twig. 5 * 6 * (c) Fabien Potencier 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Twig\TokenParser; 13 14use Twig\Error\SyntaxError; 15use Twig\Node\IncludeNode; 16use Twig\Node\Node; 17use Twig\Node\SandboxNode; 18use Twig\Node\TextNode; 19use Twig\Token; 20 21/** 22 * Marks a section of a template as untrusted code that must be evaluated in the sandbox mode. 23 * 24 * {% sandbox %} 25 * {% include 'user.html.twig' %} 26 * {% endsandbox %} 27 * 28 * @see https://twig.symfony.com/doc/api.html#sandbox-extension for details 29 * 30 * @internal 31 */ 32final class SandboxTokenParser extends AbstractTokenParser 33{ 34 public function parse(Token $token): Node 35 { 36 $stream = $this->parser->getStream(); 37 trigger_deprecation('twig/twig', '3.15', \sprintf('The "sandbox" tag is deprecated in "%s" at line %d.', $stream->getSourceContext()->getName(), $token->getLine())); 38 39 $stream->expect(Token::BLOCK_END_TYPE); 40 $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); 41 $stream->expect(Token::BLOCK_END_TYPE); 42 43 // in a sandbox tag, only include tags are allowed 44 if ($body instanceof IncludeNode) { 45 $body->setAttribute('sandboxed', true); 46 } else { 47 foreach ($body as $node) { 48 if ($node instanceof TextNode && ctype_space($node->getAttribute('data'))) { 49 continue; 50 } 51 52 if (!$node instanceof IncludeNode) { 53 throw new SyntaxError('Only "include" tags are allowed within a "sandbox" section.', $node->getTemplateLine(), $stream->getSourceContext()); 54 } 55 56 $node->setAttribute('sandboxed', true); 57 } 58 } 59 60 return new SandboxNode($body, $token->getLine()); 61 } 62 63 public function decideBlockEnd(Token $token): bool 64 { 65 return $token->test('endsandbox'); 66 } 67 68 public function getTag(): string 69 { 70 return 'sandbox'; 71 } 72} 73