Announce PHP 7 support.
[htmlpurifier.git] / library / HTMLPurifier / Injector / RemoveEmpty.php
blob01353ff1d5037950f8dc6e162696de4709853745
1 <?php
3 class HTMLPurifier_Injector_RemoveEmpty extends HTMLPurifier_Injector
5 /**
6 * @type HTMLPurifier_Context
7 */
8 private $context;
10 /**
11 * @type HTMLPurifier_Config
13 private $config;
15 /**
16 * @type HTMLPurifier_AttrValidator
18 private $attrValidator;
20 /**
21 * @type bool
23 private $removeNbsp;
25 /**
26 * @type bool
28 private $removeNbspExceptions;
30 /**
31 * Cached contents of %AutoFormat.RemoveEmpty.Predicate
32 * @type array
34 private $exclude;
36 /**
37 * @param HTMLPurifier_Config $config
38 * @param HTMLPurifier_Context $context
39 * @return void
41 public function prepare($config, $context)
43 parent::prepare($config, $context);
44 $this->config = $config;
45 $this->context = $context;
46 $this->removeNbsp = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp');
47 $this->removeNbspExceptions = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions');
48 $this->exclude = $config->get('AutoFormat.RemoveEmpty.Predicate');
49 $this->attrValidator = new HTMLPurifier_AttrValidator();
52 /**
53 * @param HTMLPurifier_Token $token
55 public function handleElement(&$token)
57 if (!$token instanceof HTMLPurifier_Token_Start) {
58 return;
60 $next = false;
61 $deleted = 1; // the current tag
62 for ($i = count($this->inputZipper->back) - 1; $i >= 0; $i--, $deleted++) {
63 $next = $this->inputZipper->back[$i];
64 if ($next instanceof HTMLPurifier_Token_Text) {
65 if ($next->is_whitespace) {
66 continue;
68 if ($this->removeNbsp && !isset($this->removeNbspExceptions[$token->name])) {
69 $plain = str_replace("\xC2\xA0", "", $next->data);
70 $isWsOrNbsp = $plain === '' || ctype_space($plain);
71 if ($isWsOrNbsp) {
72 continue;
76 break;
78 if (!$next || ($next instanceof HTMLPurifier_Token_End && $next->name == $token->name)) {
79 $this->attrValidator->validateToken($token, $this->config, $this->context);
80 $token->armor['ValidateAttributes'] = true;
81 if (isset($this->exclude[$token->name])) {
82 $r = true;
83 foreach ($this->exclude[$token->name] as $elem) {
84 if (!isset($token->attr[$elem])) $r = false;
86 if ($r) return;
88 if (isset($token->attr['id']) || isset($token->attr['name'])) {
89 return;
91 $token = $deleted + 1;
92 for ($b = 0, $c = count($this->inputZipper->front); $b < $c; $b++) {
93 $prev = $this->inputZipper->front[$b];
94 if ($prev instanceof HTMLPurifier_Token_Text && $prev->is_whitespace) {
95 continue;
97 break;
99 // This is safe because we removed the token that triggered this.
100 $this->rewindOffset($b+$deleted);
101 return;
106 // vim: et sw=4 sts=4