RemoveSpansWithoutAttributes.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Injector that removes spans with no attributes
  4. */
  5. class HTMLPurifier_Injector_RemoveSpansWithoutAttributes extends HTMLPurifier_Injector
  6. {
  7. /**
  8. * @type string
  9. */
  10. public $name = 'RemoveSpansWithoutAttributes';
  11. /**
  12. * @type array
  13. */
  14. public $needed = array('span');
  15. /**
  16. * @type HTMLPurifier_AttrValidator
  17. */
  18. private $attrValidator;
  19. /**
  20. * Used by AttrValidator.
  21. * @type HTMLPurifier_Config
  22. */
  23. private $config;
  24. /**
  25. * @type HTMLPurifier_Context
  26. */
  27. private $context;
  28. /**
  29. * @type SplObjectStorage
  30. */
  31. private $markForDeletion;
  32. public function __construct()
  33. {
  34. $this->markForDeletion = new SplObjectStorage();
  35. }
  36. public function prepare($config, $context)
  37. {
  38. $this->attrValidator = new HTMLPurifier_AttrValidator();
  39. $this->config = $config;
  40. $this->context = $context;
  41. return parent::prepare($config, $context);
  42. }
  43. /**
  44. * @param HTMLPurifier_Token $token
  45. */
  46. public function handleElement(&$token)
  47. {
  48. if ($token->name !== 'span' || !$token instanceof HTMLPurifier_Token_Start) {
  49. return;
  50. }
  51. // We need to validate the attributes now since this doesn't normally
  52. // happen until after MakeWellFormed. If all the attributes are removed
  53. // the span needs to be removed too.
  54. $this->attrValidator->validateToken($token, $this->config, $this->context);
  55. $token->armor['ValidateAttributes'] = true;
  56. if (!empty($token->attr)) {
  57. return;
  58. }
  59. $nesting = 0;
  60. while ($this->forwardUntilEndToken($i, $current, $nesting)) {
  61. }
  62. if ($current instanceof HTMLPurifier_Token_End && $current->name === 'span') {
  63. // Mark closing span tag for deletion
  64. $this->markForDeletion->attach($current);
  65. // Delete open span tag
  66. $token = false;
  67. }
  68. }
  69. /**
  70. * @param HTMLPurifier_Token $token
  71. */
  72. public function handleEnd(&$token)
  73. {
  74. if ($this->markForDeletion->contains($token)) {
  75. $this->markForDeletion->detach($token);
  76. $token = false;
  77. }
  78. }
  79. }
  80. // vim: et sw=4 sts=4