Handle <ol><ol> properly by adding missing <li> tag.
[htmlpurifier.git] / library / HTMLPurifier / Strategy / MakeWellFormed.php
blob316b2386ac8cdfe05b6624bf90eaf485f0538183
1 <?php
3 /**
4 * Takes tokens makes them well-formed (balance end tags, etc.)
5 */
6 class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
9 /**
10 * Array stream of tokens being processed.
12 protected $tokens;
14 /**
15 * Current index in $tokens.
17 protected $t;
19 /**
20 * Current nesting of elements.
22 protected $stack;
24 /**
25 * Injectors active in this stream processing.
27 protected $injectors;
29 /**
30 * Current instance of HTMLPurifier_Config.
32 protected $config;
34 /**
35 * Current instance of HTMLPurifier_Context.
37 protected $context;
39 public function execute($tokens, $config, $context) {
41 $definition = $config->getHTMLDefinition();
43 // local variables
44 $generator = new HTMLPurifier_Generator($config, $context);
45 $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
46 $e = $context->get('ErrorCollector', true);
47 $t = false; // token index
48 $i = false; // injector index
49 $token = false; // the current token
50 $reprocess = false; // whether or not to reprocess the same token
51 $stack = array();
53 // member variables
54 $this->stack =& $stack;
55 $this->t =& $t;
56 $this->tokens =& $tokens;
57 $this->config = $config;
58 $this->context = $context;
60 // context variables
61 $context->register('CurrentNesting', $stack);
62 $context->register('InputIndex', $t);
63 $context->register('InputTokens', $tokens);
64 $context->register('CurrentToken', $token);
66 // -- begin INJECTOR --
68 $this->injectors = array();
70 $injectors = $config->getBatch('AutoFormat');
71 $def_injectors = $definition->info_injector;
72 $custom_injectors = $injectors['Custom'];
73 unset($injectors['Custom']); // special case
74 foreach ($injectors as $injector => $b) {
75 // XXX: Fix with a legitimate lookup table of enabled filters
76 if (strpos($injector, '.') !== false) continue;
77 $injector = "HTMLPurifier_Injector_$injector";
78 if (!$b) continue;
79 $this->injectors[] = new $injector;
81 foreach ($def_injectors as $injector) {
82 // assumed to be objects
83 $this->injectors[] = $injector;
85 foreach ($custom_injectors as $injector) {
86 if (!$injector) continue;
87 if (is_string($injector)) {
88 $injector = "HTMLPurifier_Injector_$injector";
89 $injector = new $injector;
91 $this->injectors[] = $injector;
94 // give the injectors references to the definition and context
95 // variables for performance reasons
96 foreach ($this->injectors as $ix => $injector) {
97 $error = $injector->prepare($config, $context);
98 if (!$error) continue;
99 array_splice($this->injectors, $ix, 1); // rm the injector
100 trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING);
103 // -- end INJECTOR --
105 // a note on punting:
106 // In order to reduce code duplication, whenever some code needs
107 // to make HTML changes in order to make things "correct", the
108 // new HTML gets sent through the purifier, regardless of its
109 // status. This means that if we add a start token, because it
110 // was totally necessary, we don't have to update nesting; we just
111 // punt ($reprocess = true; continue;) and it does that for us.
113 // isset is in loop because $tokens size changes during loop exec
114 for (
115 $t = 0;
116 $t == 0 || isset($tokens[$t - 1]);
117 // only increment if we don't need to reprocess
118 $reprocess ? $reprocess = false : $t++
121 // check for a rewind
122 if (is_int($i) && $i >= 0) {
123 // possibility: disable rewinding if the current token has a
124 // rewind set on it already. This would offer protection from
125 // infinite loop, but might hinder some advanced rewinding.
126 $rewind_to = $this->injectors[$i]->getRewind();
127 if (is_int($rewind_to) && $rewind_to < $t) {
128 if ($rewind_to < 0) $rewind_to = 0;
129 while ($t > $rewind_to) {
130 $t--;
131 $prev = $tokens[$t];
132 // indicate that other injectors should not process this token,
133 // but we need to reprocess it
134 unset($prev->skip[$i]);
135 $prev->rewind = $i;
136 if ($prev instanceof HTMLPurifier_Token_Start) array_pop($this->stack);
137 elseif ($prev instanceof HTMLPurifier_Token_End) $this->stack[] = $prev->start;
140 $i = false;
143 // handle case of document end
144 if (!isset($tokens[$t])) {
145 // kill processing if stack is empty
146 if (empty($this->stack)) break;
148 // peek
149 $top_nesting = array_pop($this->stack);
150 $this->stack[] = $top_nesting;
152 // send error
153 if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {
154 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);
157 // append, don't splice, since this is the end
158 $tokens[] = new HTMLPurifier_Token_End($top_nesting->name);
160 // punt!
161 $reprocess = true;
162 continue;
165 $token = $tokens[$t];
167 //echo '<br>'; printTokens($tokens, $t); printTokens($this->stack);
169 // quick-check: if it's not a tag, no need to process
170 if (empty($token->is_tag)) {
171 if ($token instanceof HTMLPurifier_Token_Text) {
172 foreach ($this->injectors as $i => $injector) {
173 if (isset($token->skip[$i])) continue;
174 if ($token->rewind !== null && $token->rewind !== $i) continue;
175 $injector->handleText($token);
176 $this->processToken($token, $i);
177 $reprocess = true;
178 break;
181 // another possibility is a comment
182 continue;
185 if (isset($definition->info[$token->name])) {
186 $type = $definition->info[$token->name]->child->type;
187 } else {
188 $type = false; // Type is unknown, treat accordingly
191 // quick tag checks: anything that's *not* an end tag
192 $ok = false;
193 if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {
194 // claims to be a start tag but is empty
195 $token = new HTMLPurifier_Token_Empty($token->name, $token->attr);
196 $ok = true;
197 } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) {
198 // claims to be empty but really is a start tag
199 $this->swap(new HTMLPurifier_Token_End($token->name));
200 $this->insertBefore(new HTMLPurifier_Token_Start($token->name, $token->attr));
201 // punt (since we had to modify the input stream in a non-trivial way)
202 $reprocess = true;
203 continue;
204 } elseif ($token instanceof HTMLPurifier_Token_Empty) {
205 // real empty token
206 $ok = true;
207 } elseif ($token instanceof HTMLPurifier_Token_Start) {
208 // start tag
210 // ...unless they also have to close their parent
211 if (!empty($this->stack)) {
213 $parent = array_pop($this->stack);
214 $this->stack[] = $parent;
216 if (isset($definition->info[$parent->name])) {
217 $elements = $definition->info[$parent->name]->child->getAllowedElements($config);
218 $autoclose = !isset($elements[$token->name]);
219 } else {
220 $autoclose = false;
223 if ($autoclose && $definition->info[$token->name]->wrap) {
224 // check if this is actually a wrap (mmm wraps!)
225 $wrapname = $definition->info[$token->name]->wrap;
226 $wrapdef = $definition->info[$wrapname];
227 $elements = $wrapdef->child->getAllowedElements($config);
228 if (isset($elements[$token->name])) {
229 $newtoken = new HTMLPurifier_Token_Start($wrapname);
230 $this->insertBefore($newtoken);
231 $reprocess = true;
232 continue;
236 $carryover = false;
237 if ($autoclose && $definition->info[$parent->name]->formatting) {
238 $carryover = true;
241 if ($autoclose) {
242 // errors need to be updated
243 $new_token = new HTMLPurifier_Token_End($parent->name);
244 $new_token->start = $parent;
245 if ($carryover) {
246 $element = clone $parent;
247 $element->armor['MakeWellFormed_TagClosedError'] = true;
248 $element->carryover = true;
249 $this->processToken(array($new_token, $token, $element));
250 } else {
251 $this->insertBefore($new_token);
253 if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) {
254 if (!$carryover) {
255 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);
256 } else {
257 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent);
260 $reprocess = true;
261 continue;
265 $ok = true;
268 if ($ok) {
269 foreach ($this->injectors as $i => $injector) {
270 if (isset($token->skip[$i])) continue;
271 if ($token->rewind !== null && $token->rewind !== $i) continue;
272 $injector->handleElement($token);
273 $this->processToken($token, $i);
274 $reprocess = true;
275 break;
277 if (!$reprocess) {
278 // ah, nothing interesting happened; do normal processing
279 $this->swap($token);
280 if ($token instanceof HTMLPurifier_Token_Start) {
281 $this->stack[] = $token;
282 } elseif ($token instanceof HTMLPurifier_Token_End) {
283 throw new HTMLPurifier_Exception('Improper handling of end tag in start code; possible error in MakeWellFormed');
286 continue;
289 // sanity check: we should be dealing with a closing tag
290 if (!$token instanceof HTMLPurifier_Token_End) {
291 throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');
294 // make sure that we have something open
295 if (empty($this->stack)) {
296 if ($escape_invalid_tags) {
297 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');
298 $this->swap(new HTMLPurifier_Token_Text(
299 $generator->generateFromToken($token)
301 } else {
302 $this->remove();
303 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');
305 $reprocess = true;
306 continue;
309 // first, check for the simplest case: everything closes neatly.
310 // Eventually, everything passes through here; if there are problems
311 // we modify the input stream accordingly and then punt, so that
312 // the tokens get processed again.
313 $current_parent = array_pop($this->stack);
314 if ($current_parent->name == $token->name) {
315 $token->start = $current_parent;
316 foreach ($this->injectors as $i => $injector) {
317 if (isset($token->skip[$i])) continue;
318 if ($token->rewind !== null && $token->rewind !== $i) continue;
319 $injector->handleEnd($token);
320 $this->processToken($token, $i);
321 $this->stack[] = $current_parent;
322 $reprocess = true;
323 break;
325 continue;
328 // okay, so we're trying to close the wrong tag
330 // undo the pop previous pop
331 $this->stack[] = $current_parent;
333 // scroll back the entire nest, trying to find our tag.
334 // (feature could be to specify how far you'd like to go)
335 $size = count($this->stack);
336 // -2 because -1 is the last element, but we already checked that
337 $skipped_tags = false;
338 for ($j = $size - 2; $j >= 0; $j--) {
339 if ($this->stack[$j]->name == $token->name) {
340 $skipped_tags = array_slice($this->stack, $j);
341 break;
345 // we didn't find the tag, so remove
346 if ($skipped_tags === false) {
347 if ($escape_invalid_tags) {
348 $this->swap(new HTMLPurifier_Token_Text(
349 $generator->generateFromToken($token)
351 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text');
352 } else {
353 $this->remove();
354 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');
356 $reprocess = true;
357 continue;
360 // do errors, in REVERSE $j order: a,b,c with </a></b></c>
361 $c = count($skipped_tags);
362 if ($e) {
363 for ($j = $c - 1; $j > 0; $j--) {
364 // notice we exclude $j == 0, i.e. the current ending tag, from
365 // the errors...
366 if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) {
367 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]);
372 // insert tags, in FORWARD $j order: c,b,a with </a></b></c>
373 $replace = array($token);
374 for ($j = 1; $j < $c; $j++) {
375 // ...as well as from the insertions
376 $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);
377 $new_token->start = $skipped_tags[$j];
378 array_unshift($replace, $new_token);
379 if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) {
380 $element = clone $skipped_tags[$j];
381 $element->carryover = true;
382 $element->armor['MakeWellFormed_TagClosedError'] = true;
383 $replace[] = $element;
386 $this->processToken($replace);
387 $reprocess = true;
388 continue;
391 $context->destroy('CurrentNesting');
392 $context->destroy('InputTokens');
393 $context->destroy('InputIndex');
394 $context->destroy('CurrentToken');
396 unset($this->injectors, $this->stack, $this->tokens, $this->t);
397 return $tokens;
401 * Processes arbitrary token values for complicated substitution patterns.
402 * In general:
404 * If $token is an array, it is a list of tokens to substitute for the
405 * current token. These tokens then get individually processed. If there
406 * is a leading integer in the list, that integer determines how many
407 * tokens from the stream should be removed.
409 * If $token is a regular token, it is swapped with the current token.
411 * If $token is false, the current token is deleted.
413 * If $token is an integer, that number of tokens (with the first token
414 * being the current one) will be deleted.
416 * @param $token Token substitution value
417 * @param $injector Injector that performed the substitution; default is if
418 * this is not an injector related operation.
420 protected function processToken($token, $injector = -1) {
422 // normalize forms of token
423 if (is_object($token)) $token = array(1, $token);
424 if (is_int($token)) $token = array($token);
425 if ($token === false) $token = array(1);
426 if (!is_array($token)) throw new HTMLPurifier_Exception('Invalid token type from injector');
427 if (!is_int($token[0])) array_unshift($token, 1);
428 if ($token[0] === 0) throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');
430 // $token is now an array with the following form:
431 // array(number nodes to delete, new node 1, new node 2, ...)
433 $delete = array_shift($token);
434 $old = array_splice($this->tokens, $this->t, $delete, $token);
436 if ($injector > -1) {
437 // determine appropriate skips
438 $oldskip = isset($old[0]) ? $old[0]->skip : array();
439 foreach ($token as $object) {
440 $object->skip = $oldskip;
441 $object->skip[$injector] = true;
448 * Inserts a token before the current token. Cursor now points to this token
450 private function insertBefore($token) {
451 array_splice($this->tokens, $this->t, 0, array($token));
455 * Removes current token. Cursor now points to new token occupying previously
456 * occupied space.
458 private function remove() {
459 array_splice($this->tokens, $this->t, 1);
463 * Swap current token with new token. Cursor points to new token (no change).
465 private function swap($token) {
466 $this->tokens[$this->t] = $token;
471 // vim: et sw=4 sts=4