You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

281 lines
10KB

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