ILIAS  release_5-2 Revision v5.2.25-18-g3f80b82851
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
 HTMLPurifier_TokenFactory More...
 

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 35 of file DOMLex.php.

36  {
37  // setup the factory
38  parent::__construct();
39  $this->factory = new HTMLPurifier_TokenFactory();
40  }
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.

Parameters
array$matches
Returns
string

Definition at line 243 of file DOMLex.php.

244  {
245  return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];
246  }

◆ callbackUndoCommentSubst()

HTMLPurifier_Lexer_DOMLex::callbackUndoCommentSubst (   $matches)

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

Parameters
array$matches
Returns
string

Definition at line 232 of file DOMLex.php.

References array.

233  {
234  return '<!--' . strtr($matches[1], array('&amp;' => '&', '&lt;' => '<')) . $matches[2];
235  }
Create styles array
The data for the language used.

◆ createEndNode()

HTMLPurifier_Lexer_DOMLex::createEndNode (   $node,
$tokens 
)
protected
Parameters
DOMNode$node
HTMLPurifier_Token[]$tokens

Definition at line 190 of file DOMLex.php.

Referenced by tokenizeDOM().

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

◆ createStartNode()

HTMLPurifier_Lexer_DOMLex::createStartNode (   $node,
$tokens,
  $collect 
)
protected
Parameters
DOMNode$nodeDOMNode to be tokenized.
HTMLPurifier_Token[]$tokens Array-list of already tokenized tokens.
bool$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
Todo:
data and tagName properties don't seem to exist in DOMNode?

Definition at line 130 of file DOMLex.php.

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

Referenced by tokenizeDOM().

131  {
132  // intercept non element nodes. WE MUST catch all of them,
133  // but we're not getting the character reference nodes because
134  // those should have been preprocessed
135  if ($node->nodeType === XML_TEXT_NODE) {
136  $tokens[] = $this->factory->createText($node->data);
137  return false;
138  } elseif ($node->nodeType === XML_CDATA_SECTION_NODE) {
139  // undo libxml's special treatment of <script> and <style> tags
140  $last = end($tokens);
141  $data = $node->data;
142  // (note $node->tagname is already normalized)
143  if ($last instanceof HTMLPurifier_Token_Start && ($last->name == 'script' || $last->name == 'style')) {
144  $new_data = trim($data);
145  if (substr($new_data, 0, 4) === '<!--') {
146  $data = substr($new_data, 4);
147  if (substr($data, -3) === '-->') {
148  $data = substr($data, 0, -3);
149  } else {
150  // Highly suspicious! Not sure what to do...
151  }
152  }
153  }
154  $tokens[] = $this->factory->createText($this->parseData($data));
155  return false;
156  } elseif ($node->nodeType === XML_COMMENT_NODE) {
157  // this is code is only invoked for comments in script/style in versions
158  // of libxml pre-2.6.28 (regular comments, of course, are still
159  // handled regularly)
160  $tokens[] = $this->factory->createComment($node->data);
161  return false;
162  } elseif ($node->nodeType !== XML_ELEMENT_NODE) {
163  // not-well tested: there may be other nodes we have to grab
164  return false;
165  }
166 
167  $attr = $node->hasAttributes() ? $this->transformAttrToAssoc($node->attributes) : array();
168 
169  // We still have to make sure that the element actually IS empty
170  if (!$node->childNodes->length) {
171  if ($collect) {
172  $tokens[] = $this->factory->createEmpty($node->tagName, $attr);
173  }
174  return false;
175  } else {
176  if ($collect) {
177  $tokens[] = $this->factory->createStart(
178  $tag_name = $node->tagName, // somehow, it get's dropped
179  $attr
180  );
181  }
182  return true;
183  }
184  }
transformAttrToAssoc($node_map)
Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.
Definition: DOMLex.php:202
Concrete start token class.
Definition: Start.php:6
parseData($string)
Parses special entities into the proper characters.
Definition: Lexer.php:186
Create styles array
The data for the language used.
+ 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.

Parameters
int$errno
string$errstr

Definition at line 222 of file DOMLex.php.

223  {
224  }

◆ 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
DOMNode$nodeDOMNode to be tokenized.
HTMLPurifier_Token[]$tokens Array-list of already tokenized tokens.
Returns
HTMLPurifier_Token of node appended to previously passed tokens.

Definition at line 91 of file DOMLex.php.

References array, createEndNode(), and createStartNode().

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

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);
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  }
A simple array-backed queue, based off of the classic Okasaki persistent amortized queue...
Definition: Queue.php:20
createEndNode($node, &$tokens)
Definition: DOMLex.php:190
createStartNode($node, &$tokens, $collect)
Definition: DOMLex.php:130
Create styles array
The data for the language used.
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ tokenizeHTML()

HTMLPurifier_Lexer_DOMLex::tokenizeHTML (   $html,
  $config,
  $context 
)
Parameters
string$html
HTMLPurifier_Config$config
HTMLPurifier_Context$context
Returns
HTMLPurifier_Token[]

Definition at line 48 of file DOMLex.php.

References $comment, $config, $html, $old, array, HTMLPurifier_Lexer\normalize(), tokenizeDOM(), and wrapHTML().

49  {
50  $html = $this->normalize($html, $config, $context);
51 
52  // attempt to armor stray angled brackets that cannot possibly
53  // form tags and thus are probably being used as emoticons
54  if ($config->get('Core.AggressivelyFixLt')) {
55  $char = '[^a-z!\/]';
56  $comment = "/<!--(.*?)(-->|\z)/is";
57  $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html);
58  do {
59  $old = $html;
60  $html = preg_replace("/<($char)/i", '&lt;\\1', $html);
61  } while ($html !== $old);
62  $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments
63  }
64 
65  // preprocess html, essential for UTF-8
66  $html = $this->wrapHTML($html, $config, $context);
67 
68  $doc = new DOMDocument();
69  $doc->encoding = 'UTF-8'; // theoretically, the above has this covered
70 
71  set_error_handler(array($this, 'muteErrorHandler'));
72  $doc->loadHTML($html);
73  restore_error_handler();
74 
75  $tokens = array();
76  $this->tokenizeDOM(
77  $doc->getElementsByTagName('html')->item(0)-> // <html>
78  getElementsByTagName('body')->item(0), // <body>
79  $tokens
80  );
81  return $tokens;
82  }
tokenizeDOM($node, &$tokens)
Iterative function that tokenizes a node, putting it into an accumulator.
Definition: DOMLex.php:91
wrapHTML($html, $config, $context)
Wraps an HTML fragment in the necessary HTML.
Definition: DOMLex.php:255
normalize($html, $config, $context)
Takes a piece of HTML and normalizes it by converting entities, fixing encoding, extracting bits...
Definition: Lexer.php:294
$old
$comment
Definition: buildRTE.php:83
Create styles array
The data for the language used.
$html
Definition: example_001.php:87
+ 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
DOMNamedNodeMap$node_mapDOMNamedNodeMap of DOMAttr objects.
Returns
array Associative array of attributes.

Definition at line 202 of file DOMLex.php.

References array.

Referenced by createStartNode().

203  {
204  // NamedNodeMap is documented very well, so we're using undocumented
205  // features, namely, the fact that it implements Iterator and
206  // has a ->length attribute
207  if ($node_map->length === 0) {
208  return array();
209  }
210  $array = array();
211  foreach ($node_map as $attr) {
212  $array[$attr->name] = $attr->value;
213  }
214  return $array;
215  }
Create styles array
The data for the language used.
+ 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.

Parameters
string$html
HTMLPurifier_Config$config
HTMLPurifier_Context$context
Returns
string

Definition at line 255 of file DOMLex.php.

References $config, $html, and $ret.

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

256  {
257  $def = $config->getDefinition('HTML');
258  $ret = '';
259 
260  if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {
261  $ret .= '<!DOCTYPE html ';
262  if (!empty($def->doctype->dtdPublic)) {
263  $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';
264  }
265  if (!empty($def->doctype->dtdSystem)) {
266  $ret .= '"' . $def->doctype->dtdSystem . '" ';
267  }
268  $ret .= '>';
269  }
270 
271  $ret .= '<html><head>';
272  $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
273  // No protection if $html contains a stray </div>!
274  $ret .= '</head><body>' . $html . '</body></html>';
275  return $ret;
276  }
$ret
Definition: parser.php:6
$html
Definition: example_001.php:87
+ Here is the caller graph for this function:

Field Documentation

◆ $factory

HTMLPurifier_Lexer_DOMLex::$factory
private

HTMLPurifier_TokenFactory

Definition at line 33 of file DOMLex.php.


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