Use info_parent_def to get parent information, since it may not be present in info...
[htmlpurifier.git] / library / HTMLPurifier / Strategy / MakeWellFormed.php
blob53cd0db00583b4feacfad05d95d23830fb3b81f7
1 <?php
3 /**
4 * Takes tokens makes them well-formed (balance end tags, etc.)
6 * Specification of the armor attributes this strategy uses:
8 * - MakeWellFormed_TagClosedError: This armor field is used to
9 * suppress tag closed errors for certain tokens [TagClosedSuppress],
10 * in particular, if a tag was generated automatically by HTML
11 * Purifier, we may rely on our infrastructure to close it for us
12 * and shouldn't report an error to the user [TagClosedAuto].
14 class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
17 /**
18 * Array stream of tokens being processed.
20 protected $tokens;
22 /**
23 * Current index in $tokens.
25 protected $t;
27 /**
28 * Current nesting of elements.
30 protected $stack;
32 /**
33 * Injectors active in this stream processing.
35 protected $injectors;
37 /**
38 * Current instance of HTMLPurifier_Config.
40 protected $config;
42 /**
43 * Current instance of HTMLPurifier_Context.
45 protected $context;
47 public function execute($tokens, $config, $context) {
49 $definition = $config->getHTMLDefinition();
51 // local variables
52 $generator = new HTMLPurifier_Generator($config, $context);
53 $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
54 // used for autoclose early abortion
55 $global_parent_allowed_elements = $definition->info_parent_def->child->getAllowedElements($config);
56 $e = $context->get('ErrorCollector', true);
57 $t = false; // token index
58 $i = false; // injector index
59 $token = false; // the current token
60 $reprocess = false; // whether or not to reprocess the same token
61 $stack = array();
63 // member variables
64 $this->stack =& $stack;
65 $this->t =& $t;
66 $this->tokens =& $tokens;
67 $this->config = $config;
68 $this->context = $context;
70 // context variables
71 $context->register('CurrentNesting', $stack);
72 $context->register('InputIndex', $t);
73 $context->register('InputTokens', $tokens);
74 $context->register('CurrentToken', $token);
76 // -- begin INJECTOR --
78 $this->injectors = array();
80 $injectors = $config->getBatch('AutoFormat');
81 $def_injectors = $definition->info_injector;
82 $custom_injectors = $injectors['Custom'];
83 unset($injectors['Custom']); // special case
84 foreach ($injectors as $injector => $b) {
85 // XXX: Fix with a legitimate lookup table of enabled filters
86 if (strpos($injector, '.') !== false) continue;
87 $injector = "HTMLPurifier_Injector_$injector";
88 if (!$b) continue;
89 $this->injectors[] = new $injector;
91 foreach ($def_injectors as $injector) {
92 // assumed to be objects
93 $this->injectors[] = $injector;
95 foreach ($custom_injectors as $injector) {
96 if (!$injector) continue;
97 if (is_string($injector)) {
98 $injector = "HTMLPurifier_Injector_$injector";
99 $injector = new $injector;
101 $this->injectors[] = $injector;
104 // give the injectors references to the definition and context
105 // variables for performance reasons
106 foreach ($this->injectors as $ix => $injector) {
107 $error = $injector->prepare($config, $context);
108 if (!$error) continue;
109 array_splice($this->injectors, $ix, 1); // rm the injector
110 trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING);
113 // -- end INJECTOR --
115 // a note on reprocessing:
116 // In order to reduce code duplication, whenever some code needs
117 // to make HTML changes in order to make things "correct", the
118 // new HTML gets sent through the purifier, regardless of its
119 // status. This means that if we add a start token, because it
120 // was totally necessary, we don't have to update nesting; we just
121 // punt ($reprocess = true; continue;) and it does that for us.
123 // isset is in loop because $tokens size changes during loop exec
124 for (
125 $t = 0;
126 $t == 0 || isset($tokens[$t - 1]);
127 // only increment if we don't need to reprocess
128 $reprocess ? $reprocess = false : $t++
131 // check for a rewind
132 if (is_int($i) && $i >= 0) {
133 // possibility: disable rewinding if the current token has a
134 // rewind set on it already. This would offer protection from
135 // infinite loop, but might hinder some advanced rewinding.
136 $rewind_to = $this->injectors[$i]->getRewind();
137 if (is_int($rewind_to) && $rewind_to < $t) {
138 if ($rewind_to < 0) $rewind_to = 0;
139 while ($t > $rewind_to) {
140 $t--;
141 $prev = $tokens[$t];
142 // indicate that other injectors should not process this token,
143 // but we need to reprocess it
144 unset($prev->skip[$i]);
145 $prev->rewind = $i;
146 if ($prev instanceof HTMLPurifier_Token_Start) array_pop($this->stack);
147 elseif ($prev instanceof HTMLPurifier_Token_End) $this->stack[] = $prev->start;
150 $i = false;
153 // handle case of document end
154 if (!isset($tokens[$t])) {
155 // kill processing if stack is empty
156 if (empty($this->stack)) break;
158 // peek
159 $top_nesting = array_pop($this->stack);
160 $this->stack[] = $top_nesting;
162 // send error [TagClosedSuppress]
163 if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {
164 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);
167 // append, don't splice, since this is the end
168 $tokens[] = new HTMLPurifier_Token_End($top_nesting->name);
170 // punt!
171 $reprocess = true;
172 continue;
175 $token = $tokens[$t];
177 //echo '<br>'; printTokens($tokens, $t); printTokens($this->stack);
178 //flush();
180 // quick-check: if it's not a tag, no need to process
181 if (empty($token->is_tag)) {
182 if ($token instanceof HTMLPurifier_Token_Text) {
183 foreach ($this->injectors as $i => $injector) {
184 if (isset($token->skip[$i])) continue;
185 if ($token->rewind !== null && $token->rewind !== $i) continue;
186 $injector->handleText($token);
187 $this->processToken($token, $i);
188 $reprocess = true;
189 break;
192 // another possibility is a comment
193 continue;
196 if (isset($definition->info[$token->name])) {
197 $type = $definition->info[$token->name]->child->type;
198 } else {
199 $type = false; // Type is unknown, treat accordingly
202 // quick tag checks: anything that's *not* an end tag
203 $ok = false;
204 if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {
205 // claims to be a start tag but is empty
206 $token = new HTMLPurifier_Token_Empty($token->name, $token->attr, $token->line, $token->col, $token->armor);
207 $ok = true;
208 } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) {
209 // claims to be empty but really is a start tag
210 $this->swap(new HTMLPurifier_Token_End($token->name));
211 $this->insertBefore(new HTMLPurifier_Token_Start($token->name, $token->attr, $token->line, $token->col, $token->armor));
212 // punt (since we had to modify the input stream in a non-trivial way)
213 $reprocess = true;
214 continue;
215 } elseif ($token instanceof HTMLPurifier_Token_Empty) {
216 // real empty token
217 $ok = true;
218 } elseif ($token instanceof HTMLPurifier_Token_Start) {
219 // start tag
221 // ...unless they also have to close their parent
222 if (!empty($this->stack)) {
224 // Performance note: you might think that it's rather
225 // inefficient, recalculating the autoclose information
226 // for every tag that a token closes (since when we
227 // do an autoclose, we push a new token into the
228 // stream and then /process/ that, before
229 // re-processing this token.) But this is
230 // necessary, because an injector can make an
231 // arbitrary transformations to the autoclosing
232 // tokens we introduce, so things may have changed
233 // in the meantime. Also, doing the inefficient thing is
234 // "easy" to reason about (for certain perverse definitions
235 // of "easy")
237 $parent = array_pop($this->stack);
238 $this->stack[] = $parent;
240 $parent_def = null;
241 $parent_elements = null;
242 $autoclose = false;
243 if (isset($definition->info[$parent->name])) {
244 $parent_def = $definition->info[$parent->name];
245 $parent_elements = $parent_def->child->getAllowedElements($config);
246 $autoclose = !isset($parent_elements[$token->name]);
249 if ($autoclose && $definition->info[$token->name]->wrap) {
250 // Check if an element can be wrapped by another
251 // element to make it valid in a context (for
252 // example, <ul><ul> needs a <li> in between)
253 $wrapname = $definition->info[$token->name]->wrap;
254 $wrapdef = $definition->info[$wrapname];
255 $elements = $wrapdef->child->getAllowedElements($config);
256 if (isset($elements[$token->name]) && isset($parent_elements[$wrapname])) {
257 $newtoken = new HTMLPurifier_Token_Start($wrapname);
258 $this->insertBefore($newtoken);
259 $reprocess = true;
260 continue;
264 $carryover = false;
265 if ($autoclose && $parent_def->formatting) {
266 $carryover = true;
269 if ($autoclose) {
270 // check if this autoclose is doomed to fail
271 // (this rechecks $parent, which his harmless)
272 $autoclose_ok = isset($global_parent_allowed_elements[$token->name]);
273 if (!$autoclose_ok) {
274 foreach ($this->stack as $ancestor) {
275 $elements = $definition->info[$ancestor->name]->child->getAllowedElements($config);
276 if (isset($elements[$token->name])) {
277 $autoclose_ok = true;
278 break;
280 if ($definition->info[$token->name]->wrap) {
281 $wrapname = $definition->info[$token->name]->wrap;
282 $wrapdef = $definition->info[$wrapname];
283 $wrap_elements = $wrapdef->child->getAllowedElements($config);
284 if (isset($wrap_elements[$token->name]) && isset($elements[$wrapname])) {
285 $autoclose_ok = true;
286 break;
291 if ($autoclose_ok) {
292 // errors need to be updated
293 $new_token = new HTMLPurifier_Token_End($parent->name);
294 $new_token->start = $parent;
295 if ($carryover) {
296 $element = clone $parent;
297 // [TagClosedAuto]
298 $element->armor['MakeWellFormed_TagClosedError'] = true;
299 $element->carryover = true;
300 $this->processToken(array($new_token, $token, $element));
301 } else {
302 $this->insertBefore($new_token);
304 // [TagClosedSuppress]
305 if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) {
306 if (!$carryover) {
307 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);
308 } else {
309 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent);
312 } else {
313 $this->remove();
315 $reprocess = true;
316 continue;
320 $ok = true;
323 if ($ok) {
324 foreach ($this->injectors as $i => $injector) {
325 if (isset($token->skip[$i])) continue;
326 if ($token->rewind !== null && $token->rewind !== $i) continue;
327 $injector->handleElement($token);
328 $this->processToken($token, $i);
329 $reprocess = true;
330 break;
332 if (!$reprocess) {
333 // ah, nothing interesting happened; do normal processing
334 $this->swap($token);
335 if ($token instanceof HTMLPurifier_Token_Start) {
336 $this->stack[] = $token;
337 } elseif ($token instanceof HTMLPurifier_Token_End) {
338 throw new HTMLPurifier_Exception('Improper handling of end tag in start code; possible error in MakeWellFormed');
341 continue;
344 // sanity check: we should be dealing with a closing tag
345 if (!$token instanceof HTMLPurifier_Token_End) {
346 throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');
349 // make sure that we have something open
350 if (empty($this->stack)) {
351 if ($escape_invalid_tags) {
352 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');
353 $this->swap(new HTMLPurifier_Token_Text(
354 $generator->generateFromToken($token)
356 } else {
357 $this->remove();
358 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');
360 $reprocess = true;
361 continue;
364 // first, check for the simplest case: everything closes neatly.
365 // Eventually, everything passes through here; if there are problems
366 // we modify the input stream accordingly and then punt, so that
367 // the tokens get processed again.
368 $current_parent = array_pop($this->stack);
369 if ($current_parent->name == $token->name) {
370 $token->start = $current_parent;
371 foreach ($this->injectors as $i => $injector) {
372 if (isset($token->skip[$i])) continue;
373 if ($token->rewind !== null && $token->rewind !== $i) continue;
374 $injector->handleEnd($token);
375 $this->processToken($token, $i);
376 $this->stack[] = $current_parent;
377 $reprocess = true;
378 break;
380 continue;
383 // okay, so we're trying to close the wrong tag
385 // undo the pop previous pop
386 $this->stack[] = $current_parent;
388 // scroll back the entire nest, trying to find our tag.
389 // (feature could be to specify how far you'd like to go)
390 $size = count($this->stack);
391 // -2 because -1 is the last element, but we already checked that
392 $skipped_tags = false;
393 for ($j = $size - 2; $j >= 0; $j--) {
394 if ($this->stack[$j]->name == $token->name) {
395 $skipped_tags = array_slice($this->stack, $j);
396 break;
400 // we didn't find the tag, so remove
401 if ($skipped_tags === false) {
402 if ($escape_invalid_tags) {
403 $this->swap(new HTMLPurifier_Token_Text(
404 $generator->generateFromToken($token)
406 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text');
407 } else {
408 $this->remove();
409 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');
411 $reprocess = true;
412 continue;
415 // do errors, in REVERSE $j order: a,b,c with </a></b></c>
416 $c = count($skipped_tags);
417 if ($e) {
418 for ($j = $c - 1; $j > 0; $j--) {
419 // notice we exclude $j == 0, i.e. the current ending tag, from
420 // the errors... [TagClosedSuppress]
421 if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) {
422 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]);
427 // insert tags, in FORWARD $j order: c,b,a with </a></b></c>
428 $replace = array($token);
429 for ($j = 1; $j < $c; $j++) {
430 // ...as well as from the insertions
431 $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);
432 $new_token->start = $skipped_tags[$j];
433 array_unshift($replace, $new_token);
434 if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) {
435 // [TagClosedAuto]
436 $element = clone $skipped_tags[$j];
437 $element->carryover = true;
438 $element->armor['MakeWellFormed_TagClosedError'] = true;
439 $replace[] = $element;
442 $this->processToken($replace);
443 $reprocess = true;
444 continue;
447 $context->destroy('CurrentNesting');
448 $context->destroy('InputTokens');
449 $context->destroy('InputIndex');
450 $context->destroy('CurrentToken');
452 unset($this->injectors, $this->stack, $this->tokens, $this->t);
453 return $tokens;
457 * Processes arbitrary token values for complicated substitution patterns.
458 * In general:
460 * If $token is an array, it is a list of tokens to substitute for the
461 * current token. These tokens then get individually processed. If there
462 * is a leading integer in the list, that integer determines how many
463 * tokens from the stream should be removed.
465 * If $token is a regular token, it is swapped with the current token.
467 * If $token is false, the current token is deleted.
469 * If $token is an integer, that number of tokens (with the first token
470 * being the current one) will be deleted.
472 * @param $token Token substitution value
473 * @param $injector Injector that performed the substitution; default is if
474 * this is not an injector related operation.
476 protected function processToken($token, $injector = -1) {
478 // normalize forms of token
479 if (is_object($token)) $token = array(1, $token);
480 if (is_int($token)) $token = array($token);
481 if ($token === false) $token = array(1);
482 if (!is_array($token)) throw new HTMLPurifier_Exception('Invalid token type from injector');
483 if (!is_int($token[0])) array_unshift($token, 1);
484 if ($token[0] === 0) throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');
486 // $token is now an array with the following form:
487 // array(number nodes to delete, new node 1, new node 2, ...)
489 $delete = array_shift($token);
490 $old = array_splice($this->tokens, $this->t, $delete, $token);
492 if ($injector > -1) {
493 // determine appropriate skips
494 $oldskip = isset($old[0]) ? $old[0]->skip : array();
495 foreach ($token as $object) {
496 $object->skip = $oldskip;
497 $object->skip[$injector] = true;
504 * Inserts a token before the current token. Cursor now points to
505 * this token. You must reprocess after this.
507 private function insertBefore($token) {
508 array_splice($this->tokens, $this->t, 0, array($token));
512 * Removes current token. Cursor now points to new token occupying previously
513 * occupied space. You must reprocess after this.
515 private function remove() {
516 array_splice($this->tokens, $this->t, 1);
520 * Swap current token with new token. Cursor points to new token (no
521 * change). You must reprocess after this.
523 private function swap($token) {
524 $this->tokens[$this->t] = $token;
529 // vim: et sw=4 sts=4