DOMLex.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. /**
  28. * @type HTMLPurifier_TokenFactory
  29. */
  30. private $factory;
  31. public function __construct()
  32. {
  33. // setup the factory
  34. parent::__construct();
  35. $this->factory = new HTMLPurifier_TokenFactory();
  36. }
  37. /**
  38. * @param string $html
  39. * @param HTMLPurifier_Config $config
  40. * @param HTMLPurifier_Context $context
  41. * @return HTMLPurifier_Token[]
  42. */
  43. public function tokenizeHTML($html, $config, $context)
  44. {
  45. $html = $this->normalize($html, $config, $context);
  46. // attempt to armor stray angled brackets that cannot possibly
  47. // form tags and thus are probably being used as emoticons
  48. if ($config->get('Core.AggressivelyFixLt')) {
  49. $char = '[^a-z!\/]';
  50. $comment = "/<!--(.*?)(-->|\z)/is";
  51. $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html);
  52. do {
  53. $old = $html;
  54. $html = preg_replace("/<($char)/i", '&lt;\\1', $html);
  55. } while ($html !== $old);
  56. $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments
  57. }
  58. // preprocess html, essential for UTF-8
  59. $html = $this->wrapHTML($html, $config, $context);
  60. $doc = new DOMDocument();
  61. $doc->encoding = 'UTF-8'; // theoretically, the above has this covered
  62. $options = 0;
  63. if ($config->get('Core.AllowParseManyTags') && defined('LIBXML_PARSEHUGE')) {
  64. $options |= LIBXML_PARSEHUGE;
  65. }
  66. set_error_handler(array($this, 'muteErrorHandler'));
  67. // loadHTML() fails on PHP 5.3 when second parameter is given
  68. if ($options) {
  69. $doc->loadHTML($html, $options);
  70. } else {
  71. $doc->loadHTML($html);
  72. }
  73. restore_error_handler();
  74. $body = $doc->getElementsByTagName('html')->item(0)-> // <html>
  75. getElementsByTagName('body')->item(0); // <body>
  76. $div = $body->getElementsByTagName('div')->item(0); // <div>
  77. $tokens = array();
  78. $this->tokenizeDOM($div, $tokens, $config);
  79. // If the div has a sibling, that means we tripped across
  80. // a premature </div> tag. So remove the div we parsed,
  81. // and then tokenize the rest of body. We can't tokenize
  82. // the sibling directly as we'll lose the tags in that case.
  83. if ($div->nextSibling) {
  84. $body->removeChild($div);
  85. $this->tokenizeDOM($body, $tokens, $config);
  86. }
  87. return $tokens;
  88. }
  89. /**
  90. * Iterative function that tokenizes a node, putting it into an accumulator.
  91. * To iterate is human, to recurse divine - L. Peter Deutsch
  92. * @param DOMNode $node DOMNode to be tokenized.
  93. * @param HTMLPurifier_Token[] $tokens Array-list of already tokenized tokens.
  94. */
  95. protected function tokenizeDOM($node, &$tokens, $config)
  96. {
  97. $level = 0;
  98. $nodes = array($level => new HTMLPurifier_Queue(array($node)));
  99. $closingNodes = array();
  100. do {
  101. while (!$nodes[$level]->isEmpty()) {
  102. $node = $nodes[$level]->shift(); // FIFO
  103. $collect = $level > 0 ? true : false;
  104. $needEndingTag = $this->createStartNode($node, $tokens, $collect, $config);
  105. if ($needEndingTag) {
  106. $closingNodes[$level][] = $node;
  107. }
  108. if ($node->childNodes && $node->childNodes->length) {
  109. $level++;
  110. $nodes[$level] = new HTMLPurifier_Queue();
  111. foreach ($node->childNodes as $childNode) {
  112. $nodes[$level]->push($childNode);
  113. }
  114. }
  115. }
  116. $level--;
  117. if ($level && isset($closingNodes[$level])) {
  118. while ($node = array_pop($closingNodes[$level])) {
  119. $this->createEndNode($node, $tokens);
  120. }
  121. }
  122. } while ($level > 0);
  123. }
  124. /**
  125. * Portably retrieve the tag name of a node; deals with older versions
  126. * of libxml like 2.7.6
  127. * @param DOMNode $node
  128. */
  129. protected function getTagName($node)
  130. {
  131. if (isset($node->tagName)) {
  132. return $node->tagName;
  133. } else if (isset($node->nodeName)) {
  134. return $node->nodeName;
  135. } else if (isset($node->localName)) {
  136. return $node->localName;
  137. }
  138. return null;
  139. }
  140. /**
  141. * Portably retrieve the data of a node; deals with older versions
  142. * of libxml like 2.7.6
  143. * @param DOMNode $node
  144. */
  145. protected function getData($node)
  146. {
  147. if (isset($node->data)) {
  148. return $node->data;
  149. } else if (isset($node->nodeValue)) {
  150. return $node->nodeValue;
  151. } else if (isset($node->textContent)) {
  152. return $node->textContent;
  153. }
  154. return null;
  155. }
  156. /**
  157. * @param DOMNode $node DOMNode to be tokenized.
  158. * @param HTMLPurifier_Token[] $tokens Array-list of already tokenized tokens.
  159. * @param bool $collect Says whether or start and close are collected, set to
  160. * false at first recursion because it's the implicit DIV
  161. * tag you're dealing with.
  162. * @return bool if the token needs an endtoken
  163. * @todo data and tagName properties don't seem to exist in DOMNode?
  164. */
  165. protected function createStartNode($node, &$tokens, $collect, $config)
  166. {
  167. // intercept non element nodes. WE MUST catch all of them,
  168. // but we're not getting the character reference nodes because
  169. // those should have been preprocessed
  170. if ($node->nodeType === XML_TEXT_NODE) {
  171. $data = $this->getData($node); // Handle variable data property
  172. if ($data !== null) {
  173. $tokens[] = $this->factory->createText($data);
  174. }
  175. return false;
  176. } elseif ($node->nodeType === XML_CDATA_SECTION_NODE) {
  177. // undo libxml's special treatment of <script> and <style> tags
  178. $last = end($tokens);
  179. $data = $node->data;
  180. // (note $node->tagname is already normalized)
  181. if ($last instanceof HTMLPurifier_Token_Start && ($last->name == 'script' || $last->name == 'style')) {
  182. $new_data = trim($data);
  183. if (substr($new_data, 0, 4) === '<!--') {
  184. $data = substr($new_data, 4);
  185. if (substr($data, -3) === '-->') {
  186. $data = substr($data, 0, -3);
  187. } else {
  188. // Highly suspicious! Not sure what to do...
  189. }
  190. }
  191. }
  192. $tokens[] = $this->factory->createText($this->parseText($data, $config));
  193. return false;
  194. } elseif ($node->nodeType === XML_COMMENT_NODE) {
  195. // this is code is only invoked for comments in script/style in versions
  196. // of libxml pre-2.6.28 (regular comments, of course, are still
  197. // handled regularly)
  198. $tokens[] = $this->factory->createComment($node->data);
  199. return false;
  200. } elseif ($node->nodeType !== XML_ELEMENT_NODE) {
  201. // not-well tested: there may be other nodes we have to grab
  202. return false;
  203. }
  204. $attr = $node->hasAttributes() ? $this->transformAttrToAssoc($node->attributes) : array();
  205. $tag_name = $this->getTagName($node); // Handle variable tagName property
  206. if (empty($tag_name)) {
  207. return (bool) $node->childNodes->length;
  208. }
  209. // We still have to make sure that the element actually IS empty
  210. if (!$node->childNodes->length) {
  211. if ($collect) {
  212. $tokens[] = $this->factory->createEmpty($tag_name, $attr);
  213. }
  214. return false;
  215. } else {
  216. if ($collect) {
  217. $tokens[] = $this->factory->createStart($tag_name, $attr);
  218. }
  219. return true;
  220. }
  221. }
  222. /**
  223. * @param DOMNode $node
  224. * @param HTMLPurifier_Token[] $tokens
  225. */
  226. protected function createEndNode($node, &$tokens)
  227. {
  228. $tag_name = $this->getTagName($node); // Handle variable tagName property
  229. $tokens[] = $this->factory->createEnd($tag_name);
  230. }
  231. /**
  232. * Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.
  233. *
  234. * @param DOMNamedNodeMap $node_map DOMNamedNodeMap of DOMAttr objects.
  235. * @return array Associative array of attributes.
  236. */
  237. protected function transformAttrToAssoc($node_map)
  238. {
  239. // NamedNodeMap is documented very well, so we're using undocumented
  240. // features, namely, the fact that it implements Iterator and
  241. // has a ->length attribute
  242. if ($node_map->length === 0) {
  243. return array();
  244. }
  245. $array = array();
  246. foreach ($node_map as $attr) {
  247. $array[$attr->name] = $attr->value;
  248. }
  249. return $array;
  250. }
  251. /**
  252. * An error handler that mutes all errors
  253. * @param int $errno
  254. * @param string $errstr
  255. */
  256. public function muteErrorHandler($errno, $errstr)
  257. {
  258. }
  259. /**
  260. * Callback function for undoing escaping of stray angled brackets
  261. * in comments
  262. * @param array $matches
  263. * @return string
  264. */
  265. public function callbackUndoCommentSubst($matches)
  266. {
  267. return '<!--' . strtr($matches[1], array('&amp;' => '&', '&lt;' => '<')) . $matches[2];
  268. }
  269. /**
  270. * Callback function that entity-izes ampersands in comments so that
  271. * callbackUndoCommentSubst doesn't clobber them
  272. * @param array $matches
  273. * @return string
  274. */
  275. public function callbackArmorCommentEntities($matches)
  276. {
  277. return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];
  278. }
  279. /**
  280. * Wraps an HTML fragment in the necessary HTML
  281. * @param string $html
  282. * @param HTMLPurifier_Config $config
  283. * @param HTMLPurifier_Context $context
  284. * @return string
  285. */
  286. protected function wrapHTML($html, $config, $context, $use_div = true)
  287. {
  288. $def = $config->getDefinition('HTML');
  289. $ret = '';
  290. if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {
  291. $ret .= '<!DOCTYPE html ';
  292. if (!empty($def->doctype->dtdPublic)) {
  293. $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';
  294. }
  295. if (!empty($def->doctype->dtdSystem)) {
  296. $ret .= '"' . $def->doctype->dtdSystem . '" ';
  297. }
  298. $ret .= '>';
  299. }
  300. $ret .= '<html><head>';
  301. $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  302. // No protection if $html contains a stray </div>!
  303. $ret .= '</head><body>';
  304. if ($use_div) $ret .= '<div>';
  305. $ret .= $html;
  306. if ($use_div) $ret .= '</div>';
  307. $ret .= '</body></html>';
  308. return $ret;
  309. }
  310. }
  311. // vim: et sw=4 sts=4