DOMLex.php 14 KB

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