Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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