RemoveEmpty.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. class HTMLPurifier_Injector_RemoveEmpty extends HTMLPurifier_Injector
  3. {
  4. private $context, $config, $attrValidator, $removeNbsp, $removeNbspExceptions;
  5. public function prepare($config, $context) {
  6. parent::prepare($config, $context);
  7. $this->config = $config;
  8. $this->context = $context;
  9. $this->removeNbsp = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp');
  10. $this->removeNbspExceptions = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions');
  11. $this->attrValidator = new HTMLPurifier_AttrValidator();
  12. }
  13. public function handleElement(&$token) {
  14. if (!$token instanceof HTMLPurifier_Token_Start) return;
  15. $next = false;
  16. for ($i = $this->inputIndex + 1, $c = count($this->inputTokens); $i < $c; $i++) {
  17. $next = $this->inputTokens[$i];
  18. if ($next instanceof HTMLPurifier_Token_Text) {
  19. if ($next->is_whitespace) continue;
  20. if ($this->removeNbsp && !isset($this->removeNbspExceptions[$token->name])) {
  21. $plain = str_replace("\xC2\xA0", "", $next->data);
  22. $isWsOrNbsp = $plain === '' || ctype_space($plain);
  23. if ($isWsOrNbsp) continue;
  24. }
  25. }
  26. break;
  27. }
  28. if (!$next || ($next instanceof HTMLPurifier_Token_End && $next->name == $token->name)) {
  29. if ($token->name == 'colgroup') return;
  30. $this->attrValidator->validateToken($token, $this->config, $this->context);
  31. $token->armor['ValidateAttributes'] = true;
  32. if (isset($token->attr['id']) || isset($token->attr['name'])) return;
  33. $token = $i - $this->inputIndex + 1;
  34. for ($b = $this->inputIndex - 1; $b > 0; $b--) {
  35. $prev = $this->inputTokens[$b];
  36. if ($prev instanceof HTMLPurifier_Token_Text && $prev->is_whitespace) continue;
  37. break;
  38. }
  39. // This is safe because we removed the token that triggered this.
  40. $this->rewind($b - 1);
  41. return;
  42. }
  43. }
  44. }
  45. // vim: et sw=4 sts=4