File indexing completed on 2024-12-22 05:36:20
0001 <?php 0002 0003 /** 0004 * Takes tokens makes them well-formed (balance end tags, etc.) 0005 * 0006 * Specification of the armor attributes this strategy uses: 0007 * 0008 * - MakeWellFormed_TagClosedError: This armor field is used to 0009 * suppress tag closed errors for certain tokens [TagClosedSuppress], 0010 * in particular, if a tag was generated automatically by HTML 0011 * Purifier, we may rely on our infrastructure to close it for us 0012 * and shouldn't report an error to the user [TagClosedAuto]. 0013 */ 0014 class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy 0015 { 0016 0017 /** 0018 * Array stream of tokens being processed. 0019 * @type HTMLPurifier_Token[] 0020 */ 0021 protected $tokens; 0022 0023 /** 0024 * Current token. 0025 * @type HTMLPurifier_Token 0026 */ 0027 protected $token; 0028 0029 /** 0030 * Zipper managing the true state. 0031 * @type HTMLPurifier_Zipper 0032 */ 0033 protected $zipper; 0034 0035 /** 0036 * Current nesting of elements. 0037 * @type array 0038 */ 0039 protected $stack; 0040 0041 /** 0042 * Injectors active in this stream processing. 0043 * @type HTMLPurifier_Injector[] 0044 */ 0045 protected $injectors; 0046 0047 /** 0048 * Current instance of HTMLPurifier_Config. 0049 * @type HTMLPurifier_Config 0050 */ 0051 protected $config; 0052 0053 /** 0054 * Current instance of HTMLPurifier_Context. 0055 * @type HTMLPurifier_Context 0056 */ 0057 protected $context; 0058 0059 /** 0060 * @param HTMLPurifier_Token[] $tokens 0061 * @param HTMLPurifier_Config $config 0062 * @param HTMLPurifier_Context $context 0063 * @return HTMLPurifier_Token[] 0064 * @throws HTMLPurifier_Exception 0065 */ 0066 public function execute($tokens, $config, $context) 0067 { 0068 $definition = $config->getHTMLDefinition(); 0069 0070 // local variables 0071 $generator = new HTMLPurifier_Generator($config, $context); 0072 $escape_invalid_tags = $config->get('Core.EscapeInvalidTags'); 0073 // used for autoclose early abortion 0074 $global_parent_allowed_elements = $definition->info_parent_def->child->getAllowedElements($config); 0075 $e = $context->get('ErrorCollector', true); 0076 $i = false; // injector index 0077 list($zipper, $token) = HTMLPurifier_Zipper::fromArray($tokens); 0078 if ($token === NULL) { 0079 return array(); 0080 } 0081 $reprocess = false; // whether or not to reprocess the same token 0082 $stack = array(); 0083 0084 // member variables 0085 $this->stack =& $stack; 0086 $this->tokens =& $tokens; 0087 $this->token =& $token; 0088 $this->zipper =& $zipper; 0089 $this->config = $config; 0090 $this->context = $context; 0091 0092 // context variables 0093 $context->register('CurrentNesting', $stack); 0094 $context->register('InputZipper', $zipper); 0095 $context->register('CurrentToken', $token); 0096 0097 // -- begin INJECTOR -- 0098 0099 $this->injectors = array(); 0100 0101 $injectors = $config->getBatch('AutoFormat'); 0102 $def_injectors = $definition->info_injector; 0103 $custom_injectors = $injectors['Custom']; 0104 unset($injectors['Custom']); // special case 0105 foreach ($injectors as $injector => $b) { 0106 // XXX: Fix with a legitimate lookup table of enabled filters 0107 if (strpos($injector, '.') !== false) { 0108 continue; 0109 } 0110 $injector = "HTMLPurifier_Injector_$injector"; 0111 if (!$b) { 0112 continue; 0113 } 0114 $this->injectors[] = new $injector; 0115 } 0116 foreach ($def_injectors as $injector) { 0117 // assumed to be objects 0118 $this->injectors[] = $injector; 0119 } 0120 foreach ($custom_injectors as $injector) { 0121 if (!$injector) { 0122 continue; 0123 } 0124 if (is_string($injector)) { 0125 $injector = "HTMLPurifier_Injector_$injector"; 0126 $injector = new $injector; 0127 } 0128 $this->injectors[] = $injector; 0129 } 0130 0131 // give the injectors references to the definition and context 0132 // variables for performance reasons 0133 foreach ($this->injectors as $ix => $injector) { 0134 $error = $injector->prepare($config, $context); 0135 if (!$error) { 0136 continue; 0137 } 0138 array_splice($this->injectors, $ix, 1); // rm the injector 0139 trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING); 0140 } 0141 0142 // -- end INJECTOR -- 0143 0144 // a note on reprocessing: 0145 // In order to reduce code duplication, whenever some code needs 0146 // to make HTML changes in order to make things "correct", the 0147 // new HTML gets sent through the purifier, regardless of its 0148 // status. This means that if we add a start token, because it 0149 // was totally necessary, we don't have to update nesting; we just 0150 // punt ($reprocess = true; continue;) and it does that for us. 0151 0152 // isset is in loop because $tokens size changes during loop exec 0153 for (;; 0154 // only increment if we don't need to reprocess 0155 $reprocess ? $reprocess = false : $token = $zipper->next($token)) { 0156 0157 // check for a rewind 0158 if (is_int($i)) { 0159 // possibility: disable rewinding if the current token has a 0160 // rewind set on it already. This would offer protection from 0161 // infinite loop, but might hinder some advanced rewinding. 0162 $rewind_offset = $this->injectors[$i]->getRewindOffset(); 0163 if (is_int($rewind_offset)) { 0164 for ($j = 0; $j < $rewind_offset; $j++) { 0165 if (empty($zipper->front)) break; 0166 $token = $zipper->prev($token); 0167 // indicate that other injectors should not process this token, 0168 // but we need to reprocess it. See Note [Injector skips] 0169 unset($token->skip[$i]); 0170 $token->rewind = $i; 0171 if ($token instanceof HTMLPurifier_Token_Start) { 0172 array_pop($this->stack); 0173 } elseif ($token instanceof HTMLPurifier_Token_End) { 0174 $this->stack[] = $token->start; 0175 } 0176 } 0177 } 0178 $i = false; 0179 } 0180 0181 // handle case of document end 0182 if ($token === NULL) { 0183 // kill processing if stack is empty 0184 if (empty($this->stack)) { 0185 break; 0186 } 0187 0188 // peek 0189 $top_nesting = array_pop($this->stack); 0190 $this->stack[] = $top_nesting; 0191 0192 // send error [TagClosedSuppress] 0193 if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) { 0194 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting); 0195 } 0196 0197 // append, don't splice, since this is the end 0198 $token = new HTMLPurifier_Token_End($top_nesting->name); 0199 0200 // punt! 0201 $reprocess = true; 0202 continue; 0203 } 0204 0205 //echo '<br>'; printZipper($zipper, $token);//printTokens($this->stack); 0206 //flush(); 0207 0208 // quick-check: if it's not a tag, no need to process 0209 if (empty($token->is_tag)) { 0210 if ($token instanceof HTMLPurifier_Token_Text) { 0211 foreach ($this->injectors as $i => $injector) { 0212 if (isset($token->skip[$i])) { 0213 // See Note [Injector skips] 0214 continue; 0215 } 0216 if ($token->rewind !== null && $token->rewind !== $i) { 0217 continue; 0218 } 0219 // XXX fuckup 0220 $r = $token; 0221 $injector->handleText($r); 0222 $token = $this->processToken($r, $i); 0223 $reprocess = true; 0224 break; 0225 } 0226 } 0227 // another possibility is a comment 0228 continue; 0229 } 0230 0231 if (isset($definition->info[$token->name])) { 0232 $type = $definition->info[$token->name]->child->type; 0233 } else { 0234 $type = false; // Type is unknown, treat accordingly 0235 } 0236 0237 // quick tag checks: anything that's *not* an end tag 0238 $ok = false; 0239 if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) { 0240 // claims to be a start tag but is empty 0241 $token = new HTMLPurifier_Token_Empty( 0242 $token->name, 0243 $token->attr, 0244 $token->line, 0245 $token->col, 0246 $token->armor 0247 ); 0248 $ok = true; 0249 } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) { 0250 // claims to be empty but really is a start tag 0251 // NB: this assignment is required 0252 $old_token = $token; 0253 $token = new HTMLPurifier_Token_End($token->name); 0254 $token = $this->insertBefore( 0255 new HTMLPurifier_Token_Start($old_token->name, $old_token->attr, $old_token->line, $old_token->col, $old_token->armor) 0256 ); 0257 // punt (since we had to modify the input stream in a non-trivial way) 0258 $reprocess = true; 0259 continue; 0260 } elseif ($token instanceof HTMLPurifier_Token_Empty) { 0261 // real empty token 0262 $ok = true; 0263 } elseif ($token instanceof HTMLPurifier_Token_Start) { 0264 // start tag 0265 0266 // ...unless they also have to close their parent 0267 if (!empty($this->stack)) { 0268 0269 // Performance note: you might think that it's rather 0270 // inefficient, recalculating the autoclose information 0271 // for every tag that a token closes (since when we 0272 // do an autoclose, we push a new token into the 0273 // stream and then /process/ that, before 0274 // re-processing this token.) But this is 0275 // necessary, because an injector can make an 0276 // arbitrary transformations to the autoclosing 0277 // tokens we introduce, so things may have changed 0278 // in the meantime. Also, doing the inefficient thing is 0279 // "easy" to reason about (for certain perverse definitions 0280 // of "easy") 0281 0282 $parent = array_pop($this->stack); 0283 $this->stack[] = $parent; 0284 0285 $parent_def = null; 0286 $parent_elements = null; 0287 $autoclose = false; 0288 if (isset($definition->info[$parent->name])) { 0289 $parent_def = $definition->info[$parent->name]; 0290 $parent_elements = $parent_def->child->getAllowedElements($config); 0291 $autoclose = !isset($parent_elements[$token->name]); 0292 } 0293 0294 if ($autoclose && $definition->info[$token->name]->wrap) { 0295 // Check if an element can be wrapped by another 0296 // element to make it valid in a context (for 0297 // example, <ul><ul> needs a <li> in between) 0298 $wrapname = $definition->info[$token->name]->wrap; 0299 $wrapdef = $definition->info[$wrapname]; 0300 $elements = $wrapdef->child->getAllowedElements($config); 0301 if (isset($elements[$token->name]) && isset($parent_elements[$wrapname])) { 0302 $newtoken = new HTMLPurifier_Token_Start($wrapname); 0303 $token = $this->insertBefore($newtoken); 0304 $reprocess = true; 0305 continue; 0306 } 0307 } 0308 0309 $carryover = false; 0310 if ($autoclose && $parent_def->formatting) { 0311 $carryover = true; 0312 } 0313 0314 if ($autoclose) { 0315 // check if this autoclose is doomed to fail 0316 // (this rechecks $parent, which his harmless) 0317 $autoclose_ok = isset($global_parent_allowed_elements[$token->name]); 0318 if (!$autoclose_ok) { 0319 foreach ($this->stack as $ancestor) { 0320 $elements = $definition->info[$ancestor->name]->child->getAllowedElements($config); 0321 if (isset($elements[$token->name])) { 0322 $autoclose_ok = true; 0323 break; 0324 } 0325 if ($definition->info[$token->name]->wrap) { 0326 $wrapname = $definition->info[$token->name]->wrap; 0327 $wrapdef = $definition->info[$wrapname]; 0328 $wrap_elements = $wrapdef->child->getAllowedElements($config); 0329 if (isset($wrap_elements[$token->name]) && isset($elements[$wrapname])) { 0330 $autoclose_ok = true; 0331 break; 0332 } 0333 } 0334 } 0335 } 0336 if ($autoclose_ok) { 0337 // errors need to be updated 0338 $new_token = new HTMLPurifier_Token_End($parent->name); 0339 $new_token->start = $parent; 0340 // [TagClosedSuppress] 0341 if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) { 0342 if (!$carryover) { 0343 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent); 0344 } else { 0345 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent); 0346 } 0347 } 0348 if ($carryover) { 0349 $element = clone $parent; 0350 // [TagClosedAuto] 0351 $element->armor['MakeWellFormed_TagClosedError'] = true; 0352 $element->carryover = true; 0353 $token = $this->processToken(array($new_token, $token, $element)); 0354 } else { 0355 $token = $this->insertBefore($new_token); 0356 } 0357 } else { 0358 $token = $this->remove(); 0359 } 0360 $reprocess = true; 0361 continue; 0362 } 0363 0364 } 0365 $ok = true; 0366 } 0367 0368 if ($ok) { 0369 foreach ($this->injectors as $i => $injector) { 0370 if (isset($token->skip[$i])) { 0371 // See Note [Injector skips] 0372 continue; 0373 } 0374 if ($token->rewind !== null && $token->rewind !== $i) { 0375 continue; 0376 } 0377 $r = $token; 0378 $injector->handleElement($r); 0379 $token = $this->processToken($r, $i); 0380 $reprocess = true; 0381 break; 0382 } 0383 if (!$reprocess) { 0384 // ah, nothing interesting happened; do normal processing 0385 if ($token instanceof HTMLPurifier_Token_Start) { 0386 $this->stack[] = $token; 0387 } elseif ($token instanceof HTMLPurifier_Token_End) { 0388 throw new HTMLPurifier_Exception( 0389 'Improper handling of end tag in start code; possible error in MakeWellFormed' 0390 ); 0391 } 0392 } 0393 continue; 0394 } 0395 0396 // sanity check: we should be dealing with a closing tag 0397 if (!$token instanceof HTMLPurifier_Token_End) { 0398 throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier'); 0399 } 0400 0401 // make sure that we have something open 0402 if (empty($this->stack)) { 0403 if ($escape_invalid_tags) { 0404 if ($e) { 0405 $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text'); 0406 } 0407 $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token)); 0408 } else { 0409 if ($e) { 0410 $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed'); 0411 } 0412 $token = $this->remove(); 0413 } 0414 $reprocess = true; 0415 continue; 0416 } 0417 0418 // first, check for the simplest case: everything closes neatly. 0419 // Eventually, everything passes through here; if there are problems 0420 // we modify the input stream accordingly and then punt, so that 0421 // the tokens get processed again. 0422 $current_parent = array_pop($this->stack); 0423 if ($current_parent->name == $token->name) { 0424 $token->start = $current_parent; 0425 foreach ($this->injectors as $i => $injector) { 0426 if (isset($token->skip[$i])) { 0427 // See Note [Injector skips] 0428 continue; 0429 } 0430 if ($token->rewind !== null && $token->rewind !== $i) { 0431 continue; 0432 } 0433 $r = $token; 0434 $injector->handleEnd($r); 0435 $token = $this->processToken($r, $i); 0436 $this->stack[] = $current_parent; 0437 $reprocess = true; 0438 break; 0439 } 0440 continue; 0441 } 0442 0443 // okay, so we're trying to close the wrong tag 0444 0445 // undo the pop previous pop 0446 $this->stack[] = $current_parent; 0447 0448 // scroll back the entire nest, trying to find our tag. 0449 // (feature could be to specify how far you'd like to go) 0450 $size = count($this->stack); 0451 // -2 because -1 is the last element, but we already checked that 0452 $skipped_tags = false; 0453 for ($j = $size - 2; $j >= 0; $j--) { 0454 if ($this->stack[$j]->name == $token->name) { 0455 $skipped_tags = array_slice($this->stack, $j); 0456 break; 0457 } 0458 } 0459 0460 // we didn't find the tag, so remove 0461 if ($skipped_tags === false) { 0462 if ($escape_invalid_tags) { 0463 if ($e) { 0464 $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text'); 0465 } 0466 $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token)); 0467 } else { 0468 if ($e) { 0469 $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed'); 0470 } 0471 $token = $this->remove(); 0472 } 0473 $reprocess = true; 0474 continue; 0475 } 0476 0477 // do errors, in REVERSE $j order: a,b,c with </a></b></c> 0478 $c = count($skipped_tags); 0479 if ($e) { 0480 for ($j = $c - 1; $j > 0; $j--) { 0481 // notice we exclude $j == 0, i.e. the current ending tag, from 0482 // the errors... [TagClosedSuppress] 0483 if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) { 0484 $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]); 0485 } 0486 } 0487 } 0488 0489 // insert tags, in FORWARD $j order: c,b,a with </a></b></c> 0490 $replace = array($token); 0491 for ($j = 1; $j < $c; $j++) { 0492 // ...as well as from the insertions 0493 $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name); 0494 $new_token->start = $skipped_tags[$j]; 0495 array_unshift($replace, $new_token); 0496 if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) { 0497 // [TagClosedAuto] 0498 $element = clone $skipped_tags[$j]; 0499 $element->carryover = true; 0500 $element->armor['MakeWellFormed_TagClosedError'] = true; 0501 $replace[] = $element; 0502 } 0503 } 0504 $token = $this->processToken($replace); 0505 $reprocess = true; 0506 continue; 0507 } 0508 0509 $context->destroy('CurrentToken'); 0510 $context->destroy('CurrentNesting'); 0511 $context->destroy('InputZipper'); 0512 0513 unset($this->injectors, $this->stack, $this->tokens); 0514 return $zipper->toArray($token); 0515 } 0516 0517 /** 0518 * Processes arbitrary token values for complicated substitution patterns. 0519 * In general: 0520 * 0521 * If $token is an array, it is a list of tokens to substitute for the 0522 * current token. These tokens then get individually processed. If there 0523 * is a leading integer in the list, that integer determines how many 0524 * tokens from the stream should be removed. 0525 * 0526 * If $token is a regular token, it is swapped with the current token. 0527 * 0528 * If $token is false, the current token is deleted. 0529 * 0530 * If $token is an integer, that number of tokens (with the first token 0531 * being the current one) will be deleted. 0532 * 0533 * @param HTMLPurifier_Token|array|int|bool $token Token substitution value 0534 * @param HTMLPurifier_Injector|int $injector Injector that performed the substitution; default is if 0535 * this is not an injector related operation. 0536 * @throws HTMLPurifier_Exception 0537 */ 0538 protected function processToken($token, $injector = -1) 0539 { 0540 // Zend OpCache miscompiles $token = array($token), so 0541 // avoid this pattern. See: https://github.com/ezyang/htmlpurifier/issues/108 0542 0543 // normalize forms of token 0544 if (is_object($token)) { 0545 $tmp = $token; 0546 $token = array(1, $tmp); 0547 } 0548 if (is_int($token)) { 0549 $tmp = $token; 0550 $token = array($tmp); 0551 } 0552 if ($token === false) { 0553 $token = array(1); 0554 } 0555 if (!is_array($token)) { 0556 throw new HTMLPurifier_Exception('Invalid token type from injector'); 0557 } 0558 if (!is_int($token[0])) { 0559 array_unshift($token, 1); 0560 } 0561 if ($token[0] === 0) { 0562 throw new HTMLPurifier_Exception('Deleting zero tokens is not valid'); 0563 } 0564 0565 // $token is now an array with the following form: 0566 // array(number nodes to delete, new node 1, new node 2, ...) 0567 0568 $delete = array_shift($token); 0569 list($old, $r) = $this->zipper->splice($this->token, $delete, $token); 0570 0571 if ($injector > -1) { 0572 // See Note [Injector skips] 0573 // Determine appropriate skips. Here's what the code does: 0574 // *If* we deleted one or more tokens, copy the skips 0575 // of those tokens into the skips of the new tokens (in $token). 0576 // Also, mark the newly inserted tokens as having come from 0577 // $injector. 0578 $oldskip = isset($old[0]) ? $old[0]->skip : array(); 0579 foreach ($token as $object) { 0580 $object->skip = $oldskip; 0581 $object->skip[$injector] = true; 0582 } 0583 } 0584 0585 return $r; 0586 0587 } 0588 0589 /** 0590 * Inserts a token before the current token. Cursor now points to 0591 * this token. You must reprocess after this. 0592 * @param HTMLPurifier_Token $token 0593 */ 0594 private function insertBefore($token) 0595 { 0596 // NB not $this->zipper->insertBefore(), due to positioning 0597 // differences 0598 $splice = $this->zipper->splice($this->token, 0, array($token)); 0599 0600 return $splice[1]; 0601 } 0602 0603 /** 0604 * Removes current token. Cursor now points to new token occupying previously 0605 * occupied space. You must reprocess after this. 0606 */ 0607 private function remove() 0608 { 0609 return $this->zipper->delete(); 0610 } 0611 } 0612 0613 // Note [Injector skips] 0614 // ~~~~~~~~~~~~~~~~~~~~~ 0615 // When I originally designed this class, the idea behind the 'skip' 0616 // property of HTMLPurifier_Token was to help avoid infinite loops 0617 // in injector processing. For example, suppose you wrote an injector 0618 // that bolded swear words. Naively, you might write it so that 0619 // whenever you saw ****, you replaced it with <strong>****</strong>. 0620 // 0621 // When this happens, we will reprocess all of the tokens with the 0622 // other injectors. Now there is an opportunity for infinite loop: 0623 // if we rerun the swear-word injector on these tokens, we might 0624 // see **** and then reprocess again to get 0625 // <strong><strong>****</strong></strong> ad infinitum. 0626 // 0627 // Thus, the idea of a skip is that once we process a token with 0628 // an injector, we mark all of those tokens as having "come from" 0629 // the injector, and we never run the injector again on these 0630 // tokens. 0631 // 0632 // There were two more complications, however: 0633 // 0634 // - With HTMLPurifier_Injector_RemoveEmpty, we noticed that if 0635 // you had <b><i></i></b>, after you removed the <i></i>, you 0636 // really would like this injector to go back and reprocess 0637 // the <b> tag, discovering that it is now empty and can be 0638 // removed. So we reintroduced the possibility of infinite looping 0639 // by adding a "rewind" function, which let you go back to an 0640 // earlier point in the token stream and reprocess it with injectors. 0641 // Needless to say, we need to UN-skip the token so it gets 0642 // reprocessed. 0643 // 0644 // - Suppose that you successfuly process a token, replace it with 0645 // one with your skip mark, but now another injector wants to 0646 // process the skipped token with another token. Should you continue 0647 // to skip that new token, or reprocess it? If you reprocess, 0648 // you can end up with an infinite loop where one injector converts 0649 // <a> to <b>, and then another injector converts it back. So 0650 // we inherit the skips, but for some reason, I thought that we 0651 // should inherit the skip from the first token of the token 0652 // that we deleted. Why? Well, it seems to work OK. 0653 // 0654 // If I were to redesign this functionality, I would absolutely not 0655 // go about doing it this way: the semantics are just not very well 0656 // defined, and in any case you probably wanted to operate on trees, 0657 // not token streams. 0658 0659 // vim: et sw=4 sts=4