Escaper.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. class Twig_Extension_Escaper extends Twig_Extension
  11. {
  12. protected $defaultStrategy;
  13. /**
  14. * Constructor.
  15. *
  16. * @param string|false|callable $defaultStrategy An escaping strategy
  17. *
  18. * @see setDefaultStrategy()
  19. */
  20. public function __construct($defaultStrategy = 'html')
  21. {
  22. $this->setDefaultStrategy($defaultStrategy);
  23. }
  24. public function getTokenParsers()
  25. {
  26. return array(new Twig_TokenParser_AutoEscape());
  27. }
  28. public function getNodeVisitors()
  29. {
  30. return array(new Twig_NodeVisitor_Escaper());
  31. }
  32. public function getFilters()
  33. {
  34. return array(
  35. new Twig_SimpleFilter('raw', 'twig_raw_filter', array('is_safe' => array('all'))),
  36. );
  37. }
  38. /**
  39. * Sets the default strategy to use when not defined by the user.
  40. *
  41. * The strategy can be a valid PHP callback that takes the template
  42. * "filename" as an argument and returns the strategy to use.
  43. *
  44. * @param string|false|callable $defaultStrategy An escaping strategy
  45. */
  46. public function setDefaultStrategy($defaultStrategy)
  47. {
  48. // for BC
  49. if (true === $defaultStrategy) {
  50. @trigger_error('Using "true" as the default strategy is deprecated since version 1.21. Use "html" instead.', E_USER_DEPRECATED);
  51. $defaultStrategy = 'html';
  52. }
  53. if ('filename' === $defaultStrategy) {
  54. $defaultStrategy = array('Twig_FileExtensionEscapingStrategy', 'guess');
  55. }
  56. $this->defaultStrategy = $defaultStrategy;
  57. }
  58. /**
  59. * Gets the default strategy to use when not defined by the user.
  60. *
  61. * @param string $filename The template "filename"
  62. *
  63. * @return string|false The default strategy to use for the template
  64. */
  65. public function getDefaultStrategy($filename)
  66. {
  67. // disable string callables to avoid calling a function named html or js,
  68. // or any other upcoming escaping strategy
  69. if (!is_string($this->defaultStrategy) && false !== $this->defaultStrategy) {
  70. return call_user_func($this->defaultStrategy, $filename);
  71. }
  72. return $this->defaultStrategy;
  73. }
  74. public function getName()
  75. {
  76. return 'escaper';
  77. }
  78. }
  79. /**
  80. * Marks a variable as being safe.
  81. *
  82. * @param string $string A PHP variable
  83. *
  84. * @return string
  85. */
  86. function twig_raw_filter($string)
  87. {
  88. return $string;
  89. }