3 require_once 'HTMLPurifier/Lexer.php';
4 require_once 'HTMLPurifier/TokenFactory.php';
7 * Parser that uses PHP 5's DOM extension (part of the core).
9 * In PHP 5, the DOM XML extension was revamped into DOM and added to the core.
10 * It gives us a forgiving HTML parser, which we use to transform the HTML
11 * into a DOM, and then into the tokens. It is blazingly fast (for large
12 * documents, it performs twenty times faster than
13 * HTMLPurifier_Lexer_DirectLex,and is the default choice for PHP 5.
15 * @note Any empty elements will have empty tokens associated with them, even if
16 * this is prohibited by the spec. This is cannot be fixed until the spec
19 * @note PHP's DOM extension does not actually parse any entities, we use
20 * our own function to do that.
22 * @warning DOM tends to drop whitespace, which may wreak havoc on indenting.
23 * If this is a huge problem, due to the fact that HTML is hand
24 * edited and you are unable to get a parser cache that caches the
25 * the output of HTML Purifier while keeping the original HTML lying
26 * around, you may want to run Tidy on the resulting output or use
27 * HTMLPurifier_DirectLex
30 class HTMLPurifier_Lexer_DOMLex
extends HTMLPurifier_Lexer
35 public function __construct() {
37 parent
::HTMLPurifier_Lexer();
38 $this->factory
= new HTMLPurifier_TokenFactory();
41 public function tokenizeHTML($html, $config, &$context) {
43 $html = $this->normalize($html, $config, $context);
45 // attempt to armor stray angled brackets that cannot possibly
46 // form tags and thus are probably being used as emoticons
47 if ($config->get('Core', 'AggressivelyFixLt')) {
49 $comment = "/<!--(.*?)(-->|\z)/is";
50 $html = preg_replace_callback($comment, array('HTMLPurifier_Lexer_DOMLex', 'callbackArmorCommentEntities'), $html);
51 $html = preg_replace("/<($char)/i", '<\\1', $html);
52 $html = preg_replace_callback($comment, array('HTMLPurifier_Lexer_DOMLex', 'callbackUndoCommentSubst'), $html); // fix comments
55 // preprocess html, essential for UTF-8
56 $html = $this->wrapHTML($html, $config, $context);
58 $doc = new DOMDocument();
59 $doc->encoding
= 'UTF-8'; // theoretically, the above has this covered
61 set_error_handler(array($this, 'muteErrorHandler'));
62 $doc->loadHTML($html);
63 restore_error_handler();
67 $doc->getElementsByTagName('html')->item(0)-> // <html>
68 getElementsByTagName('body')->item(0)-> // <body>
69 getElementsByTagName('div')->item(0) // <div>
75 * Recursive function that tokenizes a node, putting it into an accumulator.
77 * @param $node DOMNode to be tokenized.
78 * @param $tokens Array-list of already tokenized tokens.
79 * @param $collect Says whether or start and close are collected, set to
80 * false at first recursion because it's the implicit DIV
81 * tag you're dealing with.
82 * @returns Tokens of node appended to previously passed tokens.
84 protected function tokenizeDOM($node, &$tokens, $collect = false) {
86 // intercept non element nodes. WE MUST catch all of them,
87 // but we're not getting the character reference nodes because
88 // those should have been preprocessed
89 if ($node->nodeType
=== XML_TEXT_NODE
) {
90 $tokens[] = $this->factory
->createText($node->data
);
92 } elseif ($node->nodeType
=== XML_CDATA_SECTION_NODE
) {
93 // undo libxml's special treatment of <script> and <style> tags
96 // (note $node->tagname is already normalized)
97 if ($last instanceof HTMLPurifier_Token_Start
&& $last->name
== 'script') {
98 $new_data = trim($data);
99 if (substr($new_data, 0, 4) === '<!--') {
100 $data = substr($new_data, 4);
101 if (substr($data, -3) === '-->') {
102 $data = substr($data, 0, -3);
104 // Highly suspicious! Not sure what to do...
108 $tokens[] = $this->factory
->createText($this->parseData($data));
110 } elseif ($node->nodeType
=== XML_COMMENT_NODE
) {
111 // this is code is only invoked for comments in script/style in versions
112 // of libxml pre-2.6.28 (regular comments, of course, are still
113 // handled regularly)
114 $tokens[] = $this->factory
->createComment($node->data
);
117 // not-well tested: there may be other nodes we have to grab
118 $node->nodeType
!== XML_ELEMENT_NODE
123 $attr = $node->hasAttributes() ?
124 $this->transformAttrToAssoc($node->attributes
) :
127 // We still have to make sure that the element actually IS empty
128 if (!$node->childNodes
->length
) {
130 $tokens[] = $this->factory
->createEmpty($node->tagName
, $attr);
133 if ($collect) { // don't wrap on first iteration
134 $tokens[] = $this->factory
->createStart(
135 $tag_name = $node->tagName
, // somehow, it get's dropped
139 foreach ($node->childNodes
as $node) {
140 // remember, it's an accumulator. Otherwise, we'd have
141 // to use array_merge
142 $this->tokenizeDOM($node, $tokens, true);
145 $tokens[] = $this->factory
->createEnd($tag_name);
152 * Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.
154 * @param $attribute_list DOMNamedNodeMap of DOMAttr objects.
155 * @returns Associative array of attributes.
157 protected function transformAttrToAssoc($node_map) {
158 // NamedNodeMap is documented very well, so we're using undocumented
159 // features, namely, the fact that it implements Iterator and
160 // has a ->length attribute
161 if ($node_map->length
=== 0) return array();
163 foreach ($node_map as $attr) {
164 $array[$attr->name
] = $attr->value
;
170 * An error handler that mutes all errors
172 public function muteErrorHandler($errno, $errstr) {}
175 * Callback function for undoing escaping of stray angled brackets
178 function callbackUndoCommentSubst($matches) {
179 return '<!--' . strtr($matches[1], array('&'=>'&','<'=>'<')) . $matches[2];
183 * Callback function that entity-izes ampersands in comments so that
184 * callbackUndoCommentSubst doesn't clobber them
186 function callbackArmorCommentEntities($matches) {
187 return '<!--' . str_replace('&', '&', $matches[1]) . $matches[2];
191 * Wraps an HTML fragment in the necessary HTML
193 function wrapHTML($html, $config, &$context) {
194 $def = $config->getDefinition('HTML');
197 if (!empty($def->doctype
->dtdPublic
) ||
!empty($def->doctype
->dtdSystem
)) {
198 $ret .= '<!DOCTYPE html ';
199 if (!empty($def->doctype
->dtdPublic
)) $ret .= 'PUBLIC "' . $def->doctype
->dtdPublic
. '" ';
200 if (!empty($def->doctype
->dtdSystem
)) $ret .= '"' . $def->doctype
->dtdSystem
. '" ';
204 $ret .= '<html><head>';
205 $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
206 $ret .= '</head><body><div>'.$html.'</div></body></html>';