ILIAS  release_4-4 Revision
HTMLPurifier_Lexer_DOMLex Class Reference

Parser that uses PHP 5's DOM extension (part of the core). More...

+ Inheritance diagram for HTMLPurifier_Lexer_DOMLex:
+ Collaboration diagram for HTMLPurifier_Lexer_DOMLex:

Public Member Functions

 __construct ()
 
 tokenizeHTML ($html, $config, $context)
 
 muteErrorHandler ($errno, $errstr)
 An error handler that mutes all errors. More...
 
 callbackUndoCommentSubst ($matches)
 Callback function for undoing escaping of stray angled brackets in comments. More...
 
 callbackArmorCommentEntities ($matches)
 Callback function that entity-izes ampersands in comments so that callbackUndoCommentSubst doesn't clobber them. More...
 
- Public Member Functions inherited from HTMLPurifier_Lexer
 __construct ()
 
 parseData ($string)
 Parses special entities into the proper characters. More...
 
 tokenizeHTML ($string, $config, $context)
 Lexes an HTML string into tokens. More...
 
 normalize ($html, $config, $context)
 Takes a piece of HTML and normalizes it by converting entities, fixing encoding, extracting bits, and other good stuff. More...
 
 extractBody ($html)
 Takes a string of HTML (fragment or document) and returns the content. More...
 

Protected Member Functions

 tokenizeDOM ($node, &$tokens)
 Iterative function that tokenizes a node, putting it into an accumulator. More...
 
 createStartNode ($node, &$tokens, $collect)
 
 createEndNode ($node, &$tokens)
 
 transformAttrToAssoc ($node_map)
 Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array. More...
 
 wrapHTML ($html, $config, $context)
 Wraps an HTML fragment in the necessary HTML. More...
 

Private Attributes

 $factory
 

Additional Inherited Members

- Static Public Member Functions inherited from HTMLPurifier_Lexer
static create ($config)
 Retrieves or sets the default Lexer as a Prototype Factory. More...
 
- Data Fields inherited from HTMLPurifier_Lexer
 $tracksLineNumbers = false
 Whether or not this lexer implements line-number/column-number tracking. More...
 
- Static Protected Member Functions inherited from HTMLPurifier_Lexer
static escapeCDATA ($string)
 Translates CDATA sections into regular sections (through escaping). More...
 
static escapeCommentedCDATA ($string)
 Special CDATA case that is especially convoluted for <script> More...
 
static removeIEConditional ($string)
 Special Internet Explorer conditional comments should be removed. More...
 
static CDATACallback ($matches)
 Callback function for escapeCDATA() that does the work. More...
 
- Protected Attributes inherited from HTMLPurifier_Lexer
 $_special_entity2str
 Most common entity to raw value conversion table for special entities. More...
 

Detailed Description

Parser that uses PHP 5's DOM extension (part of the core).

In PHP 5, the DOM XML extension was revamped into DOM and added to the core. It gives us a forgiving HTML parser, which we use to transform the HTML into a DOM, and then into the tokens. It is blazingly fast (for large documents, it performs twenty times faster than HTMLPurifier_Lexer_DirectLex,and is the default choice for PHP 5.

Note
Any empty elements will have empty tokens associated with them, even if this is prohibited by the spec. This is cannot be fixed until the spec comes into play.
PHP's DOM extension does not actually parse any entities, we use our own function to do that.
Warning
DOM tends to drop whitespace, which may wreak havoc on indenting. If this is a huge problem, due to the fact that HTML is hand edited and you are unable to get a parser cache that caches the the output of HTML Purifier while keeping the original HTML lying around, you may want to run Tidy on the resulting output or use HTMLPurifier_DirectLex

Definition at line 27 of file DOMLex.php.

Constructor & Destructor Documentation

◆ __construct()

HTMLPurifier_Lexer_DOMLex::__construct ( )

Definition at line 32 of file DOMLex.php.

32  {
33  // setup the factory
34  parent::__construct();
35  $this->factory = new HTMLPurifier_TokenFactory();
36  }
Factory for token generation.

Member Function Documentation

◆ callbackArmorCommentEntities()

HTMLPurifier_Lexer_DOMLex::callbackArmorCommentEntities (   $matches)

Callback function that entity-izes ampersands in comments so that callbackUndoCommentSubst doesn't clobber them.

Definition at line 216 of file DOMLex.php.

216  {
217  return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];
218  }

◆ callbackUndoCommentSubst()

HTMLPurifier_Lexer_DOMLex::callbackUndoCommentSubst (   $matches)

Callback function for undoing escaping of stray angled brackets in comments.

Definition at line 208 of file DOMLex.php.

208  {
209  return '<!--' . strtr($matches[1], array('&amp;'=>'&','&lt;'=>'<')) . $matches[2];
210  }

◆ createEndNode()

HTMLPurifier_Lexer_DOMLex::createEndNode (   $node,
$tokens 
)
protected

Definition at line 176 of file DOMLex.php.

Referenced by tokenizeDOM().

176  {
177  $tokens[] = $this->factory->createEnd($node->tagName);
178  }
+ Here is the caller graph for this function:

◆ createStartNode()

HTMLPurifier_Lexer_DOMLex::createStartNode (   $node,
$tokens,
  $collect 
)
protected
Parameters
$nodeDOMNode to be tokenized.
$tokensArray-list of already tokenized tokens.
$collectSays whether or start and close are collected, set to false at first recursion because it's the implicit DIV tag you're dealing with.
Returns
bool if the token needs an endtoken

Definition at line 119 of file DOMLex.php.

References $data, HTMLPurifier_Lexer\parseData(), and transformAttrToAssoc().

Referenced by tokenizeDOM().

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 (
151  // not-well tested: there may be other nodes we have to grab
152  $node->nodeType !== XML_ELEMENT_NODE
153  ) {
154  return false;
155  }
156 
157  $attr = $node->hasAttributes() ? $this->transformAttrToAssoc($node->attributes) : array();
158 
159  // We still have to make sure that the element actually IS empty
160  if (!$node->childNodes->length) {
161  if ($collect) {
162  $tokens[] = $this->factory->createEmpty($node->tagName, $attr);
163  }
164  return false;
165  } else {
166  if ($collect) {
167  $tokens[] = $this->factory->createStart(
168  $tag_name = $node->tagName, // somehow, it get's dropped
169  $attr
170  );
171  }
172  return true;
173  }
174  }
transformAttrToAssoc($node_map)
Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.
Definition: DOMLex.php:187
Concrete start token class.
Definition: Start.php:6
parseData($string)
Parses special entities into the proper characters.
Definition: Lexer.php:174
while($lm_rec=$ilDB->fetchAssoc($lm_set)) $data
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ muteErrorHandler()

HTMLPurifier_Lexer_DOMLex::muteErrorHandler (   $errno,
  $errstr 
)

An error handler that mutes all errors.

Definition at line 202 of file DOMLex.php.

202 {}

◆ tokenizeDOM()

HTMLPurifier_Lexer_DOMLex::tokenizeDOM (   $node,
$tokens 
)
protected

Iterative function that tokenizes a node, putting it into an accumulator.

To iterate is human, to recurse divine - L. Peter Deutsch

Parameters
$nodeDOMNode to be tokenized.
$tokensArray-list of already tokenized tokens.
Returns
Tokens of node appended to previously passed tokens.

Definition at line 81 of file DOMLex.php.

References createEndNode(), and createStartNode().

Referenced by HTMLPurifier_Lexer_PH5P\tokenizeHTML(), and tokenizeHTML().

81  {
82 
83  $level = 0;
84  $nodes = array($level => array($node));
85  $closingNodes = array();
86  do {
87  while (!empty($nodes[$level])) {
88  $node = array_shift($nodes[$level]); // 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] = array();
97  foreach ($node->childNodes as $childNode) {
98  array_push($nodes[$level], $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  }
createEndNode($node, &$tokens)
Definition: DOMLex.php:176
createStartNode($node, &$tokens, $collect)
Definition: DOMLex.php:119
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ tokenizeHTML()

HTMLPurifier_Lexer_DOMLex::tokenizeHTML (   $html,
  $config,
  $context 
)

Definition at line 38 of file DOMLex.php.

References $comment, HTMLPurifier_Lexer\normalize(), tokenizeDOM(), and wrapHTML().

38  {
39 
40  $html = $this->normalize($html, $config, $context);
41 
42  // attempt to armor stray angled brackets that cannot possibly
43  // form tags and thus are probably being used as emoticons
44  if ($config->get('Core.AggressivelyFixLt')) {
45  $char = '[^a-z!\/]';
46  $comment = "/<!--(.*?)(-->|\z)/is";
47  $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html);
48  do {
49  $old = $html;
50  $html = preg_replace("/<($char)/i", '&lt;\\1', $html);
51  } while ($html !== $old);
52  $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments
53  }
54 
55  // preprocess html, essential for UTF-8
56  $html = $this->wrapHTML($html, $config, $context);
57 
58  $doc = new DOMDocument();
59  $doc->encoding = 'UTF-8'; // theoretically, the above has this covered
60 
61  set_error_handler(array($this, 'muteErrorHandler'));
62  $doc->loadHTML($html);
63  restore_error_handler();
64 
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  return $tokens;
72  }
tokenizeDOM($node, &$tokens)
Iterative function that tokenizes a node, putting it into an accumulator.
Definition: DOMLex.php:81
wrapHTML($html, $config, $context)
Wraps an HTML fragment in the necessary HTML.
Definition: DOMLex.php:223
normalize($html, $config, $context)
Takes a piece of HTML and normalizes it by converting entities, fixing encoding, extracting bits...
Definition: Lexer.php:263
$comment
Definition: buildRTE.php:83
+ Here is the call graph for this function:

◆ transformAttrToAssoc()

HTMLPurifier_Lexer_DOMLex::transformAttrToAssoc (   $node_map)
protected

Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.

Parameters
$attribute_listDOMNamedNodeMap of DOMAttr objects.
Returns
Associative array of attributes.

Definition at line 187 of file DOMLex.php.

Referenced by createStartNode().

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) return array();
192  $array = array();
193  foreach ($node_map as $attr) {
194  $array[$attr->name] = $attr->value;
195  }
196  return $array;
197  }
+ Here is the caller graph for this function:

◆ wrapHTML()

HTMLPurifier_Lexer_DOMLex::wrapHTML (   $html,
  $config,
  $context 
)
protected

Wraps an HTML fragment in the necessary HTML.

Definition at line 223 of file DOMLex.php.

References $ret.

Referenced by HTMLPurifier_Lexer_PH5P\tokenizeHTML(), and tokenizeHTML().

223  {
224  $def = $config->getDefinition('HTML');
225  $ret = '';
226 
227  if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {
228  $ret .= '<!DOCTYPE html ';
229  if (!empty($def->doctype->dtdPublic)) $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';
230  if (!empty($def->doctype->dtdSystem)) $ret .= '"' . $def->doctype->dtdSystem . '" ';
231  $ret .= '>';
232  }
233 
234  $ret .= '<html><head>';
235  $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
236  // No protection if $html contains a stray </div>!
237  $ret .= '</head><body><div>'.$html.'</div></body></html>';
238  return $ret;
239  }
+ Here is the caller graph for this function:

Field Documentation

◆ $factory

HTMLPurifier_Lexer_DOMLex::$factory
private

Definition at line 30 of file DOMLex.php.


The documentation for this class was generated from the following file: