ILIAS  release_4-4 Revision
HTMLPurifier_Lexer Class Reference

Forgivingly lexes HTML (SGML-style) markup into tokens. More...

+ Inheritance diagram for HTMLPurifier_Lexer:
+ Collaboration diagram for HTMLPurifier_Lexer:

Public Member Functions

 __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...
 

Static Public Member Functions

static create ($config)
 Retrieves or sets the default Lexer as a Prototype Factory. More...
 

Data Fields

 $tracksLineNumbers = false
 Whether or not this lexer implements line-number/column-number tracking. More...
 

Static Protected Member Functions

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

 $_special_entity2str
 Most common entity to raw value conversion table for special entities. More...
 

Detailed Description

Forgivingly lexes HTML (SGML-style) markup into tokens.

A lexer parses a string of SGML-style markup and converts them into corresponding tokens. It doesn't check for well-formedness, although its internal mechanism may make this automatic (such as the case of HTMLPurifier_Lexer_DOMLex). There are several implementations to choose from.

A lexer is HTML-oriented: it might work with XML, but it's not recommended, as we adhere to a subset of the specification for optimization reasons. This might change in the future. Also, most tokenizers are not expected to handle DTDs or PIs.

This class should not be directly instantiated, but you may use create() to retrieve a default copy of the lexer. Being a supertype, this class does not actually define any implementation, but offers commonly used convenience functions for subclasses.

Note
The unit tests will instantiate this class for testing purposes, as many of the utility functions require a class to be instantiated. This means that, even though this class is not runnable, it will not be declared abstract.
Note
We use tokens rather than create a DOM representation because DOM would:
  1. Require more processing and memory to create,
  2. Is not streamable, and
  3. Has the entire document structure (html and body not needed).
However, DOM is helpful in that it makes it easy to move around nodes without a lot of lookaheads to see when a tag is closed. This is a limitation of the token system and some workarounds would be nice.

Definition at line 42 of file Lexer.php.

Constructor & Destructor Documentation

◆ __construct()

HTMLPurifier_Lexer::__construct ( )

Definition at line 142 of file Lexer.php.

142  {
143  $this->_entity_parser = new HTMLPurifier_EntityParser();
144  }
Handles referencing and derefencing character entities.

Member Function Documentation

◆ CDATACallback()

static HTMLPurifier_Lexer::CDATACallback (   $matches)
staticprotected

Callback function for escapeCDATA() that does the work.

Warning
Though this is public in order to let the callback happen, calling it directly is not recommended. $matches PCRE matches array, with index 0 the entire match and 1 the inside of the CDATA section.
Returns
Escaped internals of the CDATA section.

Definition at line 253 of file Lexer.php.

253  {
254  // not exactly sure why the character set is needed, but whatever
255  return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');
256  }

◆ create()

static HTMLPurifier_Lexer::create (   $config)
static

Retrieves or sets the default Lexer as a Prototype Factory.

By default HTMLPurifier_Lexer_DOMLex will be returned. There are a few exceptions involving special features that only DirectLex implements.

Note
The behavior of this class has changed, rather than accepting a prototype object, it now accepts a configuration object. To specify your own prototype, set Core.LexerImpl to it. This change in behavior de-singletonizes the lexer object.
Parameters
$configInstance of HTMLPurifier_Config
Returns
Concrete lexer.

Definition at line 68 of file Lexer.php.

Referenced by HTMLPurifier\purify().

68  {
69 
70  if (!($config instanceof HTMLPurifier_Config)) {
71  $lexer = $config;
72  trigger_error("Passing a prototype to
73  HTMLPurifier_Lexer::create() is deprecated, please instead
74  use %Core.LexerImpl", E_USER_WARNING);
75  } else {
76  $lexer = $config->get('Core.LexerImpl');
77  }
78 
79  $needs_tracking =
80  $config->get('Core.MaintainLineNumbers') ||
81  $config->get('Core.CollectErrors');
82 
83  $inst = null;
84  if (is_object($lexer)) {
85  $inst = $lexer;
86  } else {
87 
88  if (is_null($lexer)) { do {
89  // auto-detection algorithm
90 
91  if ($needs_tracking) {
92  $lexer = 'DirectLex';
93  break;
94  }
95 
96  if (
97  class_exists('DOMDocument') &&
98  method_exists('DOMDocument', 'loadHTML') &&
99  !extension_loaded('domxml')
100  ) {
101  // check for DOM support, because while it's part of the
102  // core, it can be disabled compile time. Also, the PECL
103  // domxml extension overrides the default DOM, and is evil
104  // and nasty and we shan't bother to support it
105  $lexer = 'DOMLex';
106  } else {
107  $lexer = 'DirectLex';
108  }
109 
110  } while(0); } // do..while so we can break
111 
112  // instantiate recognized string names
113  switch ($lexer) {
114  case 'DOMLex':
115  $inst = new HTMLPurifier_Lexer_DOMLex();
116  break;
117  case 'DirectLex':
118  $inst = new HTMLPurifier_Lexer_DirectLex();
119  break;
120  case 'PH5P':
121  $inst = new HTMLPurifier_Lexer_PH5P();
122  break;
123  default:
124  throw new HTMLPurifier_Exception("Cannot instantiate unrecognized Lexer type " . htmlspecialchars($lexer));
125  }
126  }
127 
128  if (!$inst) throw new HTMLPurifier_Exception('No lexer was instantiated');
129 
130  // once PHP DOM implements native line numbers, or we
131  // hack out something using XSLT, remove this stipulation
132  if ($needs_tracking && !$inst->tracksLineNumbers) {
133  throw new HTMLPurifier_Exception('Cannot use lexer that does not support line numbers with Core.MaintainLineNumbers or Core.CollectErrors (use DirectLex instead)');
134  }
135 
136  return $inst;
137 
138  }
Experimental HTML5-based parser using Jeroen van der Meer&#39;s PH5P library.
Definition: PH5P.php:13
Parser that uses PHP 5&#39;s DOM extension (part of the core).
Definition: DOMLex.php:27
Our in-house implementation of a parser.
Definition: DirectLex.php:13
Global exception class for HTML Purifier; any exceptions we throw are from here.
Definition: Exception.php:7
Configuration object that triggers customizable behavior.
Definition: Config.php:17
+ Here is the caller graph for this function:

◆ escapeCDATA()

static HTMLPurifier_Lexer::escapeCDATA (   $string)
staticprotected

Translates CDATA sections into regular sections (through escaping).

Parameters
$stringHTML string to process.
Returns
HTML with CDATA sections escaped.

Definition at line 214 of file Lexer.php.

Referenced by normalize().

214  {
215  return preg_replace_callback(
216  '/<!\[CDATA\[(.+?)\]\]>/s',
217  array('HTMLPurifier_Lexer', 'CDATACallback'),
218  $string
219  );
220  }
+ Here is the caller graph for this function:

◆ escapeCommentedCDATA()

static HTMLPurifier_Lexer::escapeCommentedCDATA (   $string)
staticprotected

Special CDATA case that is especially convoluted for <script>

Definition at line 225 of file Lexer.php.

Referenced by normalize().

225  {
226  return preg_replace_callback(
227  '#<!--//--><!\[CDATA\[//><!--(.+?)//--><!\]\]>#s',
228  array('HTMLPurifier_Lexer', 'CDATACallback'),
229  $string
230  );
231  }
+ Here is the caller graph for this function:

◆ extractBody()

HTMLPurifier_Lexer::extractBody (   $html)

Takes a string of HTML (fragment or document) and returns the content.

Todo:
Consider making protected

Definition at line 314 of file Lexer.php.

References $result.

Referenced by normalize().

314  {
315  $matches = array();
316  $result = preg_match('!<body[^>]*>(.*)</body>!is', $html, $matches);
317  if ($result) {
318  return $matches[1];
319  } else {
320  return $html;
321  }
322  }
$result
+ Here is the caller graph for this function:

◆ normalize()

HTMLPurifier_Lexer::normalize (   $html,
  $config,
  $context 
)

Takes a piece of HTML and normalizes it by converting entities, fixing encoding, extracting bits, and other good stuff.

Todo:
Consider making protected

Definition at line 263 of file Lexer.php.

References HTMLPurifier_Encoder\cleanUTF8(), escapeCDATA(), escapeCommentedCDATA(), extractBody(), and removeIEConditional().

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

263  {
264 
265  // normalize newlines to \n
266  if ($config->get('Core.NormalizeNewlines')) {
267  $html = str_replace("\r\n", "\n", $html);
268  $html = str_replace("\r", "\n", $html);
269  }
270 
271  if ($config->get('HTML.Trusted')) {
272  // escape convoluted CDATA
273  $html = $this->escapeCommentedCDATA($html);
274  }
275 
276  // escape CDATA
277  $html = $this->escapeCDATA($html);
278 
279  $html = $this->removeIEConditional($html);
280 
281  // extract body from document if applicable
282  if ($config->get('Core.ConvertDocumentToFragment')) {
283  $e = false;
284  if ($config->get('Core.CollectErrors')) {
285  $e =& $context->get('ErrorCollector');
286  }
287  $new_html = $this->extractBody($html);
288  if ($e && $new_html != $html) {
289  $e->send(E_WARNING, 'Lexer: Extracted body');
290  }
291  $html = $new_html;
292  }
293 
294  // expand entities that aren't the big five
295  $html = $this->_entity_parser->substituteNonSpecialEntities($html);
296 
297  // clean into wellformed UTF-8 string for an SGML context: this has
298  // to be done after entity expansion because the entities sometimes
299  // represent non-SGML characters (horror, horror!)
300  $html = HTMLPurifier_Encoder::cleanUTF8($html);
301 
302  // if processing instructions are to removed, remove them now
303  if ($config->get('Core.RemoveProcessingInstructions')) {
304  $html = preg_replace('#<\?.+?\?>#s', '', $html);
305  }
306 
307  return $html;
308  }
static removeIEConditional($string)
Special Internet Explorer conditional comments should be removed.
Definition: Lexer.php:236
static cleanUTF8($str, $force_php=false)
Cleans a UTF-8 string for well-formedness and SGML validity.
Definition: Encoder.php:109
static escapeCDATA($string)
Translates CDATA sections into regular sections (through escaping).
Definition: Lexer.php:214
extractBody($html)
Takes a string of HTML (fragment or document) and returns the content.
Definition: Lexer.php:314
static escapeCommentedCDATA($string)
Special CDATA case that is especially convoluted for <script>
Definition: Lexer.php:225
+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ parseData()

HTMLPurifier_Lexer::parseData (   $string)

Parses special entities into the proper characters.

This string will translate escaped versions of the special characters into the correct ones.

Warning
You should be able to treat the output of this function as completely parsed, but that's only because all other entities should have been handled previously in substituteNonSpecialEntities()
Parameters
$stringString character data to be parsed.
Returns
Parsed character data.

Definition at line 174 of file Lexer.php.

Referenced by HTMLPurifier_Lexer_DOMLex\createStartNode(), HTMLPurifier_Lexer_DirectLex\parseAttributeString(), and HTMLPurifier_Lexer_DirectLex\tokenizeHTML().

174  {
175 
176  // following functions require at least one character
177  if ($string === '') return '';
178 
179  // subtracts amps that cannot possibly be escaped
180  $num_amp = substr_count($string, '&') - substr_count($string, '& ') -
181  ($string[strlen($string)-1] === '&' ? 1 : 0);
182 
183  if (!$num_amp) return $string; // abort if no entities
184  $num_esc_amp = substr_count($string, '&amp;');
185  $string = strtr($string, $this->_special_entity2str);
186 
187  // code duplication for sake of optimization, see above
188  $num_amp_2 = substr_count($string, '&') - substr_count($string, '& ') -
189  ($string[strlen($string)-1] === '&' ? 1 : 0);
190 
191  if ($num_amp_2 <= $num_esc_amp) return $string;
192 
193  // hmm... now we have some uncommon entities. Use the callback.
194  $string = $this->_entity_parser->substituteSpecialEntities($string);
195  return $string;
196  }
+ Here is the caller graph for this function:

◆ removeIEConditional()

static HTMLPurifier_Lexer::removeIEConditional (   $string)
staticprotected

Special Internet Explorer conditional comments should be removed.

Definition at line 236 of file Lexer.php.

Referenced by normalize().

236  {
237  return preg_replace(
238  '#<!--\[if [^>]+\]>.*?<!\[endif\]-->#si', // probably should generalize for all strings
239  '',
240  $string
241  );
242  }
+ Here is the caller graph for this function:

◆ tokenizeHTML()

HTMLPurifier_Lexer::tokenizeHTML (   $string,
  $config,
  $context 
)

Lexes an HTML string into tokens.

Parameters
$stringString HTML.
Returns
HTMLPurifier_Token array representation of HTML.

Definition at line 204 of file Lexer.php.

204  {
205  trigger_error('Call to abstract class', E_USER_ERROR);
206  }

Field Documentation

◆ $_special_entity2str

HTMLPurifier_Lexer::$_special_entity2str
protected
Initial value:
=
array(
'&quot;' => '"',
'&amp;' => '&',
'&lt;' => '<',
'&gt;' => '>',
'&#39;' => "'",
'&#039;' => "'",
'&#x27;' => "'"
)

Most common entity to raw value conversion table for special entities.

Definition at line 149 of file Lexer.php.

◆ $tracksLineNumbers

HTMLPurifier_Lexer::$tracksLineNumbers = false

Whether or not this lexer implements line-number/column-number tracking.

If it does, set to true.

Definition at line 49 of file Lexer.php.


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