Add vim modelines to all files.
[htmlpurifier.git] / library / HTMLPurifier / Strategy / MakeWellFormed.php
blobe04b826572de96a34a13d2dfc14fbcd29f26f3ee
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 $injector = "HTMLPurifier_Injector_$injector";
76 if (!$b) continue;
77 $this->injectors[] = new $injector;
79 foreach ($def_injectors as $injector) {
80 // assumed to be objects
81 $this->injectors[] = $injector;
83 foreach ($custom_injectors as $injector) {
84 if (is_string($injector)) {
85 $injector = "HTMLPurifier_Injector_$injector";
86 $injector = new $injector;
88 $this->injectors[] = $injector;
91 // give the injectors references to the definition and context
92 // variables for performance reasons
93 foreach ($this->injectors as $ix => $injector) {
94 $error = $injector->prepare($config, $context);
95 if (!$error) continue;
96 array_splice($this->injectors, $ix, 1); // rm the injector
97 trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING);
100 // -- end INJECTOR --
102 // a note on punting:
103 // In order to reduce code duplication, whenever some code needs
104 // to make HTML changes in order to make things "correct", the
105 // new HTML gets sent through the purifier, regardless of its
106 // status. This means that if we add a start token, because it
107 // was totally necessary, we don't have to update nesting; we just
108 // punt ($reprocess = true; continue;) and it does that for us.
110 // isset is in loop because $tokens size changes during loop exec
111 for (
112 $t = 0;
113 $t == 0 || isset($tokens[$t - 1]);
114 // only increment if we don't need to reprocess
115 $reprocess ? $reprocess = false : $t++
118 // check for a rewind
119 if (is_int($i) && $i >= 0) {
120 // possibility: disable rewinding if the current token has a
121 // rewind set on it already. This would offer protection from
122 // infinite loop, but might hinder some advanced rewinding.
123 $rewind_to = $this->injectors[$i]->getRewind();
124 if (is_int($rewind_to) && $rewind_to < $t) {
125 if ($rewind_to < 0) $rewind_to = 0;
126 while ($t > $rewind_to) {
127 $t--;
128 $prev = $tokens[$t];
129 // indicate that other injectors should not process this token,
130 // but we need to reprocess it
131 unset($prev->skip[$i]);
132 $prev->rewind = $i;
133 if ($prev instanceof HTMLPurifier_Token_Start) array_pop($this->stack);
134 elseif ($prev instanceof HTMLPurifier_Token_End) $this->stack[] = $prev->start;
137 $i = false;
140 // handle case of document end
141 if (!isset($tokens[$t])) {
142 // kill processing if stack is empty
143 if (empty($this->stack)) break;
145 // peek
146 $top_nesting = array_pop($this->stack);
147 $this->stack[] = $top_nesting;
149 // send error
150 if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {
151 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);
154 // append, don't splice, since this is the end
155 $tokens[] = new HTMLPurifier_Token_End($top_nesting->name);
157 // punt!
158 $reprocess = true;
159 continue;
162 // if all goes well, this token will be passed through unharmed
163 $token = $tokens[$t];
165 //echo '<hr>';
166 //printTokens($tokens, $t);
167 //var_dump($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->getNonAutoCloseElements($config);
218 $autoclose = !isset($elements[$token->name]);
219 } else {
220 $autoclose = false;
223 if ($autoclose) {
224 if ($e) $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);
225 // insert parent end tag before this tag
226 $new_token = new HTMLPurifier_Token_End($parent->name);
227 $new_token->start = $parent;
228 $this->insertBefore($new_token);
229 $reprocess = true;
230 continue;
234 $ok = true;
237 if ($ok) {
238 foreach ($this->injectors as $i => $injector) {
239 if (isset($token->skip[$i])) continue;
240 if ($token->rewind !== null && $token->rewind !== $i) continue;
241 $injector->handleElement($token);
242 $this->processToken($token, $i);
243 $reprocess = true;
244 break;
246 if (!$reprocess) {
247 // ah, nothing interesting happened; do normal processing
248 $this->swap($token);
249 if ($token instanceof HTMLPurifier_Token_Start) {
250 $this->stack[] = $token;
251 } elseif ($token instanceof HTMLPurifier_Token_End) {
252 throw new HTMLPurifier_Exception('Improper handling of end tag in start code; possible error in MakeWellFormed');
255 continue;
258 // sanity check: we should be dealing with a closing tag
259 if (!$token instanceof HTMLPurifier_Token_End) {
260 throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');
263 // make sure that we have something open
264 if (empty($this->stack)) {
265 if ($escape_invalid_tags) {
266 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');
267 $this->swap(new HTMLPurifier_Token_Text(
268 $generator->generateFromToken($token)
270 } else {
271 $this->remove();
272 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');
274 $reprocess = true;
275 continue;
278 // first, check for the simplest case: everything closes neatly.
279 // Eventually, everything passes through here; if there are problems
280 // we modify the input stream accordingly and then punt, so that
281 // the tokens get processed again.
282 $current_parent = array_pop($this->stack);
283 if ($current_parent->name == $token->name) {
284 $token->start = $current_parent;
285 foreach ($this->injectors as $i => $injector) {
286 if (isset($token->skip[$i])) continue;
287 if ($token->rewind !== null && $token->rewind !== $i) continue;
288 $injector->handleEnd($token);
289 $this->processToken($token, $i);
290 $this->stack[] = $current_parent;
291 $reprocess = true;
292 break;
294 continue;
297 // okay, so we're trying to close the wrong tag
299 // undo the pop previous pop
300 $this->stack[] = $current_parent;
302 // scroll back the entire nest, trying to find our tag.
303 // (feature could be to specify how far you'd like to go)
304 $size = count($this->stack);
305 // -2 because -1 is the last element, but we already checked that
306 $skipped_tags = false;
307 for ($j = $size - 2; $j >= 0; $j--) {
308 if ($this->stack[$j]->name == $token->name) {
309 $skipped_tags = array_slice($this->stack, $j);
310 break;
314 // we didn't find the tag, so remove
315 if ($skipped_tags === false) {
316 if ($escape_invalid_tags) {
317 $this->swap(new HTMLPurifier_Token_Text(
318 $generator->generateFromToken($token)
320 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text');
321 } else {
322 $this->remove();
323 if ($e) $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');
325 $reprocess = true;
326 continue;
329 // do errors, in REVERSE $j order: a,b,c with </a></b></c>
330 $c = count($skipped_tags);
331 if ($e) {
332 for ($j = $c - 1; $j > 0; $j--) {
333 // notice we exclude $j == 0, i.e. the current ending tag, from
334 // the errors...
335 if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) {
336 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]);
341 // insert tags, in FORWARD $j order: c,b,a with </a></b></c>
342 for ($j = 1; $j < $c; $j++) {
343 // ...as well as from the insertions
344 $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);
345 $new_token->start = $skipped_tags[$j];
346 $this->insertBefore($new_token);
348 $reprocess = true;
349 continue;
352 $context->destroy('CurrentNesting');
353 $context->destroy('InputTokens');
354 $context->destroy('InputIndex');
355 $context->destroy('CurrentToken');
357 unset($this->injectors, $this->stack, $this->tokens, $this->t);
358 return $tokens;
362 * Processes arbitrary token values for complicated substitution patterns.
363 * In general:
365 * If $token is an array, it is a list of tokens to substitute for the
366 * current token. These tokens then get individually processed. If there
367 * is a leading integer in the list, that integer determines how many
368 * tokens from the stream should be removed.
370 * If $token is a regular token, it is swapped with the current token.
372 * If $token is false, the current token is deleted.
374 * If $token is an integer, that number of tokens (with the first token
375 * being the current one) will be deleted.
377 * @param $token Token substitution value
378 * @param $injector Injector that performed the substitution; default is if
379 * this is not an injector related operation.
381 protected function processToken($token, $injector = -1) {
383 // normalize forms of token
384 if (is_object($token)) $token = array(1, $token);
385 if (is_int($token)) $token = array($token);
386 if ($token === false) $token = array(1);
387 if (!is_array($token)) throw new HTMLPurifier_Exception('Invalid token type from injector');
388 if (!is_int($token[0])) array_unshift($token, 1);
389 if ($token[0] === 0) throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');
391 // $token is now an array with the following form:
392 // array(number nodes to delete, new node 1, new node 2, ...)
394 $delete = array_shift($token);
395 $old = array_splice($this->tokens, $this->t, $delete, $token);
397 if ($injector > -1) {
398 // determine appropriate skips
399 $oldskip = isset($old[0]) ? $old[0]->skip : array();
400 foreach ($token as $object) {
401 $object->skip = $oldskip;
402 $object->skip[$injector] = true;
409 * Inserts a token before the current token. Cursor now points to this token
411 private function insertBefore($token) {
412 array_splice($this->tokens, $this->t, 0, array($token));
416 * Removes current token. Cursor now points to new token occupying previously
417 * occupied space.
419 private function remove() {
420 array_splice($this->tokens, $this->t, 1);
424 * Swap current token with new token. Cursor points to new token (no change).
426 private function swap($token) {
427 $this->tokens[$this->t] = $token;
432 // vim: et sw=4 sts=4