DOMLex.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. * Iterative function that tokenizes a node, putting it into an accumulator.
  64. * To iterate is human, to recurse divine - L. Peter Deutsch
  65. * @param $node DOMNode to be tokenized.
  66. * @param $tokens Array-list of already tokenized tokens.
  67. * @returns Tokens of node appended to previously passed tokens.
  68. */
  69. protected function tokenizeDOM($node, &$tokens) {
  70. $level = 0;
  71. $nodes = array($level => array($node));
  72. $closingNodes = array();
  73. do {
  74. while (!empty($nodes[$level])) {
  75. $node = array_shift($nodes[$level]); // FIFO
  76. $collect = $level > 0 ? true : false;
  77. $needEndingTag = $this->createStartNode($node, $tokens, $collect);
  78. if ($needEndingTag) {
  79. $closingNodes[$level][] = $node;
  80. }
  81. if ($node->childNodes && $node->childNodes->length) {
  82. $level++;
  83. $nodes[$level] = array();
  84. foreach ($node->childNodes as $childNode) {
  85. array_push($nodes[$level], $childNode);
  86. }
  87. }
  88. }
  89. $level--;
  90. if ($level && isset($closingNodes[$level])) {
  91. while($node = array_pop($closingNodes[$level])) {
  92. $this->createEndNode($node, $tokens);
  93. }
  94. }
  95. } while ($level > 0);
  96. }
  97. /**
  98. * @param $node DOMNode to be tokenized.
  99. * @param $tokens Array-list of already tokenized tokens.
  100. * @param $collect Says whether or start and close are collected, set to
  101. * false at first recursion because it's the implicit DIV
  102. * tag you're dealing with.
  103. * @returns bool if the token needs an endtoken
  104. */
  105. protected function createStartNode($node, &$tokens, $collect) {
  106. // intercept non element nodes. WE MUST catch all of them,
  107. // but we're not getting the character reference nodes because
  108. // those should have been preprocessed
  109. if ($node->nodeType === XML_TEXT_NODE) {
  110. $tokens[] = $this->factory->createText($node->data);
  111. return false;
  112. } elseif ($node->nodeType === XML_CDATA_SECTION_NODE) {
  113. // undo libxml's special treatment of <script> and <style> tags
  114. $last = end($tokens);
  115. $data = $node->data;
  116. // (note $node->tagname is already normalized)
  117. if ($last instanceof HTMLPurifier_Token_Start && ($last->name == 'script' || $last->name == 'style')) {
  118. $new_data = trim($data);
  119. if (substr($new_data, 0, 4) === '<!--') {
  120. $data = substr($new_data, 4);
  121. if (substr($data, -3) === '-->') {
  122. $data = substr($data, 0, -3);
  123. } else {
  124. // Highly suspicious! Not sure what to do...
  125. }
  126. }
  127. }
  128. $tokens[] = $this->factory->createText($this->parseData($data));
  129. return false;
  130. } elseif ($node->nodeType === XML_COMMENT_NODE) {
  131. // this is code is only invoked for comments in script/style in versions
  132. // of libxml pre-2.6.28 (regular comments, of course, are still
  133. // handled regularly)
  134. $tokens[] = $this->factory->createComment($node->data);
  135. return false;
  136. } elseif (
  137. // not-well tested: there may be other nodes we have to grab
  138. $node->nodeType !== XML_ELEMENT_NODE
  139. ) {
  140. return false;
  141. }
  142. $attr = $node->hasAttributes() ? $this->transformAttrToAssoc($node->attributes) : array();
  143. // We still have to make sure that the element actually IS empty
  144. if (!$node->childNodes->length) {
  145. if ($collect) {
  146. $tokens[] = $this->factory->createEmpty($node->tagName, $attr);
  147. }
  148. return false;
  149. } else {
  150. if ($collect) {
  151. $tokens[] = $this->factory->createStart(
  152. $tag_name = $node->tagName, // somehow, it get's dropped
  153. $attr
  154. );
  155. }
  156. return true;
  157. }
  158. }
  159. protected function createEndNode($node, &$tokens) {
  160. $tokens[] = $this->factory->createEnd($node->tagName);
  161. }
  162. /**
  163. * Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.
  164. *
  165. * @param $attribute_list DOMNamedNodeMap of DOMAttr objects.
  166. * @returns Associative array of attributes.
  167. */
  168. protected function transformAttrToAssoc($node_map) {
  169. // NamedNodeMap is documented very well, so we're using undocumented
  170. // features, namely, the fact that it implements Iterator and
  171. // has a ->length attribute
  172. if ($node_map->length === 0) return array();
  173. $array = array();
  174. foreach ($node_map as $attr) {
  175. $array[$attr->name] = $attr->value;
  176. }
  177. return $array;
  178. }
  179. /**
  180. * An error handler that mutes all errors
  181. */
  182. public function muteErrorHandler($errno, $errstr) {}
  183. /**
  184. * Callback function for undoing escaping of stray angled brackets
  185. * in comments
  186. */
  187. public function callbackUndoCommentSubst($matches) {
  188. return '<!--' . strtr($matches[1], array('&amp;'=>'&','&lt;'=>'<')) . $matches[2];
  189. }
  190. /**
  191. * Callback function that entity-izes ampersands in comments so that
  192. * callbackUndoCommentSubst doesn't clobber them
  193. */
  194. public function callbackArmorCommentEntities($matches) {
  195. return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];
  196. }
  197. /**
  198. * Wraps an HTML fragment in the necessary HTML
  199. */
  200. protected function wrapHTML($html, $config, $context) {
  201. $def = $config->getDefinition('HTML');
  202. $ret = '';
  203. if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {
  204. $ret .= '<!DOCTYPE html ';
  205. if (!empty($def->doctype->dtdPublic)) $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';
  206. if (!empty($def->doctype->dtdSystem)) $ret .= '"' . $def->doctype->dtdSystem . '" ';
  207. $ret .= '>';
  208. }
  209. $ret .= '<html><head>';
  210. $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  211. // No protection if $html contains a stray </div>!
  212. $ret .= '</head><body><div>'.$html.'</div></body></html>';
  213. return $ret;
  214. }
  215. }
  216. // vim: et sw=4 sts=4