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\Extension { 13use Twig\NodeVisitor\EscaperNodeVisitor; 14use Twig\TokenParser\AutoEscapeTokenParser; 15use Twig\TwigFilter; 16 17/** 18 * @final 19 */ 20class EscaperExtension extends AbstractExtension 21{ 22 protected $defaultStrategy; 23 24 /** 25 * @param string|false|callable $defaultStrategy An escaping strategy 26 * 27 * @see setDefaultStrategy() 28 */ 29 public function __construct($defaultStrategy = 'html') 30 { 31 $this->setDefaultStrategy($defaultStrategy); 32 } 33 34 public function getTokenParsers() 35 { 36 return [new AutoEscapeTokenParser()]; 37 } 38 39 public function getNodeVisitors() 40 { 41 return [new EscaperNodeVisitor()]; 42 } 43 44 public function getFilters() 45 { 46 return [ 47 new TwigFilter('raw', 'twig_raw_filter', ['is_safe' => ['all']]), 48 ]; 49 } 50 51 /** 52 * Sets the default strategy to use when not defined by the user. 53 * 54 * The strategy can be a valid PHP callback that takes the template 55 * name as an argument and returns the strategy to use. 56 * 57 * @param string|false|callable $defaultStrategy An escaping strategy 58 */ 59 public function setDefaultStrategy($defaultStrategy) 60 { 61 // for BC 62 if (true === $defaultStrategy) { 63 @trigger_error('Using "true" as the default strategy is deprecated since version 1.21. Use "html" instead.', E_USER_DEPRECATED); 64 65 $defaultStrategy = 'html'; 66 } 67 68 if ('filename' === $defaultStrategy) { 69 @trigger_error('Using "filename" as the default strategy is deprecated since version 1.27. Use "name" instead.', E_USER_DEPRECATED); 70 71 $defaultStrategy = 'name'; 72 } 73 74 if ('name' === $defaultStrategy) { 75 $defaultStrategy = ['\Twig\FileExtensionEscapingStrategy', 'guess']; 76 } 77 78 $this->defaultStrategy = $defaultStrategy; 79 } 80 81 /** 82 * Gets the default strategy to use when not defined by the user. 83 * 84 * @param string $name The template name 85 * 86 * @return string|false The default strategy to use for the template 87 */ 88 public function getDefaultStrategy($name) 89 { 90 // disable string callables to avoid calling a function named html or js, 91 // or any other upcoming escaping strategy 92 if (!\is_string($this->defaultStrategy) && false !== $this->defaultStrategy) { 93 return \call_user_func($this->defaultStrategy, $name); 94 } 95 96 return $this->defaultStrategy; 97 } 98 99 public function getName() 100 { 101 return 'escaper'; 102 } 103} 104 105class_alias('Twig\Extension\EscaperExtension', 'Twig_Extension_Escaper'); 106} 107 108namespace { 109/** 110 * Marks a variable as being safe. 111 * 112 * @param string $string A PHP variable 113 * 114 * @return string 115 */ 116function twig_raw_filter($string) 117{ 118 return $string; 119} 120} 121