DOMLex.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. <?php
  2. /**
  3. * Parser that uses PHP 5's DOM extension (part of the core).
  4. *
  5. * In PHP 5, the DOM XML extension was revamped into DOM and added to the core.
  6. * It gives us a forgiving HTML parser, which we use to transform the HTML
  7. * into a DOM, and then into the tokens. It is blazingly fast (for large
  8. * documents, it performs twenty times faster than
  9. * HTMLPurifier_Lexer_DirectLex,and is the default choice for PHP 5.
  10. *
  11. * @note Any empty elements will have empty tokens associated with them, even if
  12. * this is prohibited by the spec. This is cannot be fixed until the spec
  13. * comes into play.
  14. *
  15. * @note PHP's DOM extension does not actually parse any entities, we use
  16. * our own function to do that.
  17. *
  18. * @warning DOM tends to drop whitespace, which may wreak havoc on indenting.
  19. * If this is a huge problem, due to the fact that HTML is hand
  20. * edited and you are unable to get a parser cache that caches the
  21. * the output of HTML Purifier while keeping the original HTML lying
  22. * around, you may want to run Tidy on the resulting output or use
  23. * HTMLPurifier_DirectLex
  24. */
  25. class HTMLPurifier_Lexer_DOMLex extends HTMLPurifier_Lexer
  26. {
  27. private $factory;
  28. public function __construct() {
  29. // setup the factory
  30. parent::__construct();
  31. $this->factory = new HTMLPurifier_TokenFactory();
  32. }
  33. public function tokenizeHTML($html, $config, $context) {
  34. $html = $this->normalize($html, $config, $context);
  35. // attempt to armor stray angled brackets that cannot possibly
  36. // form tags and thus are probably being used as emoticons
  37. if ($config->get('Core.AggressivelyFixLt')) {
  38. $char = '[^a-z!\/]';
  39. $comment = "/<!--(.*?)(-->|\z)/is";
  40. $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html);
  41. do {
  42. $old = $html;
  43. $html = preg_replace("/<($char)/i", '&lt;\\1', $html);
  44. } while ($html !== $old);
  45. $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments
  46. }
  47. // preprocess html, essential for UTF-8
  48. $html = $this->wrapHTML($html, $config, $context);
  49. $doc = new DOMDocument();
  50. $doc->encoding = 'UTF-8'; // theoretically, the above has this covered
  51. set_error_handler(array($this, 'muteErrorHandler'));
  52. $doc->loadHTML($html);
  53. restore_error_handler();
  54. $tokens = array();
  55. $this->tokenizeDOM(
  56. $doc->getElementsByTagName('html')->item(0)-> // <html>
  57. getElementsByTagName('body')->item(0)-> // <body>
  58. getElementsByTagName('div')->item(0) // <div>
  59. , $tokens);
  60. return $tokens;
  61. }
  62. /**
  63. * Recursive function that tokenizes a node, putting it into an accumulator.
  64. *
  65. * @param $node DOMNode to be tokenized.
  66. * @param $tokens Array-list of already tokenized tokens.
  67. * @param $collect Says whether or start and close are collected, set to
  68. * false at first recursion because it's the implicit DIV
  69. * tag you're dealing with.
  70. * @returns Tokens of node appended to previously passed tokens.
  71. */
  72. protected function tokenizeDOM($node, &$tokens, $collect = false) {
  73. // intercept non element nodes. WE MUST catch all of them,
  74. // but we're not getting the character reference nodes because
  75. // those should have been preprocessed
  76. if ($node->nodeType === XML_TEXT_NODE) {
  77. $tokens[] = $this->factory->createText($node->data);
  78. return;
  79. } elseif ($node->nodeType === XML_CDATA_SECTION_NODE) {
  80. // undo libxml's special treatment of <script> and <style> tags
  81. $last = end($tokens);
  82. $data = $node->data;
  83. // (note $node->tagname is already normalized)
  84. if ($last instanceof HTMLPurifier_Token_Start && ($last->name == 'script' || $last->name == 'style')) {
  85. $new_data = trim($data);
  86. if (substr($new_data, 0, 4) === '<!--') {
  87. $data = substr($new_data, 4);
  88. if (substr($data, -3) === '-->') {
  89. $data = substr($data, 0, -3);
  90. } else {
  91. // Highly suspicious! Not sure what to do...
  92. }
  93. }
  94. }
  95. $tokens[] = $this->factory->createText($this->parseData($data));
  96. return;
  97. } elseif ($node->nodeType === XML_COMMENT_NODE) {
  98. // this is code is only invoked for comments in script/style in versions
  99. // of libxml pre-2.6.28 (regular comments, of course, are still
  100. // handled regularly)
  101. $tokens[] = $this->factory->createComment($node->data);
  102. return;
  103. } elseif (
  104. // not-well tested: there may be other nodes we have to grab
  105. $node->nodeType !== XML_ELEMENT_NODE
  106. ) {
  107. return;
  108. }
  109. $attr = $node->hasAttributes() ?
  110. $this->transformAttrToAssoc($node->attributes) :
  111. array();
  112. // We still have to make sure that the element actually IS empty
  113. if (!$node->childNodes->length) {
  114. if ($collect) {
  115. $tokens[] = $this->factory->createEmpty($node->tagName, $attr);
  116. }
  117. } else {
  118. if ($collect) { // don't wrap on first iteration
  119. $tokens[] = $this->factory->createStart(
  120. $tag_name = $node->tagName, // somehow, it get's dropped
  121. $attr
  122. );
  123. }
  124. foreach ($node->childNodes as $node) {
  125. // remember, it's an accumulator. Otherwise, we'd have
  126. // to use array_merge
  127. $this->tokenizeDOM($node, $tokens, true);
  128. }
  129. if ($collect) {
  130. $tokens[] = $this->factory->createEnd($tag_name);
  131. }
  132. }
  133. }
  134. /**
  135. * Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.
  136. *
  137. * @param $attribute_list DOMNamedNodeMap of DOMAttr objects.
  138. * @returns Associative array of attributes.
  139. */
  140. protected function transformAttrToAssoc($node_map) {
  141. // NamedNodeMap is documented very well, so we're using undocumented
  142. // features, namely, the fact that it implements Iterator and
  143. // has a ->length attribute
  144. if ($node_map->length === 0) return array();
  145. $array = array();
  146. foreach ($node_map as $attr) {
  147. $array[$attr->name] = $attr->value;
  148. }
  149. return $array;
  150. }
  151. /**
  152. * An error handler that mutes all errors
  153. */
  154. public function muteErrorHandler($errno, $errstr) {}
  155. /**
  156. * Callback function for undoing escaping of stray angled brackets
  157. * in comments
  158. */
  159. public function callbackUndoCommentSubst($matches) {
  160. return '<!--' . strtr($matches[1], array('&amp;'=>'&','&lt;'=>'<')) . $matches[2];
  161. }
  162. /**
  163. * Callback function that entity-izes ampersands in comments so that
  164. * callbackUndoCommentSubst doesn't clobber them
  165. */
  166. public function callbackArmorCommentEntities($matches) {
  167. return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];
  168. }
  169. /**
  170. * Wraps an HTML fragment in the necessary HTML
  171. */
  172. protected function wrapHTML($html, $config, $context) {
  173. $def = $config->getDefinition('HTML');
  174. $ret = '';
  175. if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {
  176. $ret .= '<!DOCTYPE html ';
  177. if (!empty($def->doctype->dtdPublic)) $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';
  178. if (!empty($def->doctype->dtdSystem)) $ret .= '"' . $def->doctype->dtdSystem . '" ';
  179. $ret .= '>';
  180. }
  181. $ret .= '<html><head>';
  182. $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  183. // No protection if $html contains a stray </div>!
  184. $ret .= '</head><body><div>'.$html.'</div></body></html>';
  185. return $ret;
  186. }
  187. }
  188. // vim: et sw=4 sts=4