Lexer.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. /**
  3. * Forgivingly lexes HTML (SGML-style) markup into tokens.
  4. *
  5. * A lexer parses a string of SGML-style markup and converts them into
  6. * corresponding tokens. It doesn't check for well-formedness, although its
  7. * internal mechanism may make this automatic (such as the case of
  8. * HTMLPurifier_Lexer_DOMLex). There are several implementations to choose
  9. * from.
  10. *
  11. * A lexer is HTML-oriented: it might work with XML, but it's not
  12. * recommended, as we adhere to a subset of the specification for optimization
  13. * reasons. This might change in the future. Also, most tokenizers are not
  14. * expected to handle DTDs or PIs.
  15. *
  16. * This class should not be directly instantiated, but you may use create() to
  17. * retrieve a default copy of the lexer. Being a supertype, this class
  18. * does not actually define any implementation, but offers commonly used
  19. * convenience functions for subclasses.
  20. *
  21. * @note The unit tests will instantiate this class for testing purposes, as
  22. * many of the utility functions require a class to be instantiated.
  23. * This means that, even though this class is not runnable, it will
  24. * not be declared abstract.
  25. *
  26. * @par
  27. *
  28. * @note
  29. * We use tokens rather than create a DOM representation because DOM would:
  30. *
  31. * @par
  32. * -# Require more processing and memory to create,
  33. * -# Is not streamable, and
  34. * -# Has the entire document structure (html and body not needed).
  35. *
  36. * @par
  37. * However, DOM is helpful in that it makes it easy to move around nodes
  38. * without a lot of lookaheads to see when a tag is closed. This is a
  39. * limitation of the token system and some workarounds would be nice.
  40. */
  41. class HTMLPurifier_Lexer
  42. {
  43. /**
  44. * Whether or not this lexer implements line-number/column-number tracking.
  45. * If it does, set to true.
  46. */
  47. public $tracksLineNumbers = false;
  48. // -- STATIC ----------------------------------------------------------
  49. /**
  50. * Retrieves or sets the default Lexer as a Prototype Factory.
  51. *
  52. * By default HTMLPurifier_Lexer_DOMLex will be returned. There are
  53. * a few exceptions involving special features that only DirectLex
  54. * implements.
  55. *
  56. * @note The behavior of this class has changed, rather than accepting
  57. * a prototype object, it now accepts a configuration object.
  58. * To specify your own prototype, set %Core.LexerImpl to it.
  59. * This change in behavior de-singletonizes the lexer object.
  60. *
  61. * @param $config Instance of HTMLPurifier_Config
  62. * @return Concrete lexer.
  63. */
  64. public static function create($config) {
  65. if (!($config instanceof HTMLPurifier_Config)) {
  66. $lexer = $config;
  67. trigger_error("Passing a prototype to
  68. HTMLPurifier_Lexer::create() is deprecated, please instead
  69. use %Core.LexerImpl", E_USER_WARNING);
  70. } else {
  71. $lexer = $config->get('Core.LexerImpl');
  72. }
  73. $needs_tracking =
  74. $config->get('Core.MaintainLineNumbers') ||
  75. $config->get('Core.CollectErrors');
  76. $inst = null;
  77. if (is_object($lexer)) {
  78. $inst = $lexer;
  79. } else {
  80. if (is_null($lexer)) { do {
  81. // auto-detection algorithm
  82. if ($needs_tracking) {
  83. $lexer = 'DirectLex';
  84. break;
  85. }
  86. if (
  87. class_exists('DOMDocument') &&
  88. method_exists('DOMDocument', 'loadHTML') &&
  89. !extension_loaded('domxml')
  90. ) {
  91. // check for DOM support, because while it's part of the
  92. // core, it can be disabled compile time. Also, the PECL
  93. // domxml extension overrides the default DOM, and is evil
  94. // and nasty and we shan't bother to support it
  95. $lexer = 'DOMLex';
  96. } else {
  97. $lexer = 'DirectLex';
  98. }
  99. } while(0); } // do..while so we can break
  100. // instantiate recognized string names
  101. switch ($lexer) {
  102. case 'DOMLex':
  103. $inst = new HTMLPurifier_Lexer_DOMLex();
  104. break;
  105. case 'DirectLex':
  106. $inst = new HTMLPurifier_Lexer_DirectLex();
  107. break;
  108. case 'PH5P':
  109. $inst = new HTMLPurifier_Lexer_PH5P();
  110. break;
  111. default:
  112. throw new HTMLPurifier_Exception("Cannot instantiate unrecognized Lexer type " . htmlspecialchars($lexer));
  113. }
  114. }
  115. if (!$inst) throw new HTMLPurifier_Exception('No lexer was instantiated');
  116. // once PHP DOM implements native line numbers, or we
  117. // hack out something using XSLT, remove this stipulation
  118. if ($needs_tracking && !$inst->tracksLineNumbers) {
  119. throw new HTMLPurifier_Exception('Cannot use lexer that does not support line numbers with Core.MaintainLineNumbers or Core.CollectErrors (use DirectLex instead)');
  120. }
  121. return $inst;
  122. }
  123. // -- CONVENIENCE MEMBERS ---------------------------------------------
  124. public function __construct() {
  125. $this->_entity_parser = new HTMLPurifier_EntityParser();
  126. }
  127. /**
  128. * Most common entity to raw value conversion table for special entities.
  129. */
  130. protected $_special_entity2str =
  131. array(
  132. '&quot;' => '"',
  133. '&amp;' => '&',
  134. '&lt;' => '<',
  135. '&gt;' => '>',
  136. '&#39;' => "'",
  137. '&#039;' => "'",
  138. '&#x27;' => "'"
  139. );
  140. /**
  141. * Parses special entities into the proper characters.
  142. *
  143. * This string will translate escaped versions of the special characters
  144. * into the correct ones.
  145. *
  146. * @warning
  147. * You should be able to treat the output of this function as
  148. * completely parsed, but that's only because all other entities should
  149. * have been handled previously in substituteNonSpecialEntities()
  150. *
  151. * @param $string String character data to be parsed.
  152. * @returns Parsed character data.
  153. */
  154. public function parseData($string) {
  155. // following functions require at least one character
  156. if ($string === '') return '';
  157. // subtracts amps that cannot possibly be escaped
  158. $num_amp = substr_count($string, '&') - substr_count($string, '& ') -
  159. ($string[strlen($string)-1] === '&' ? 1 : 0);
  160. if (!$num_amp) return $string; // abort if no entities
  161. $num_esc_amp = substr_count($string, '&amp;');
  162. $string = strtr($string, $this->_special_entity2str);
  163. // code duplication for sake of optimization, see above
  164. $num_amp_2 = substr_count($string, '&') - substr_count($string, '& ') -
  165. ($string[strlen($string)-1] === '&' ? 1 : 0);
  166. if ($num_amp_2 <= $num_esc_amp) return $string;
  167. // hmm... now we have some uncommon entities. Use the callback.
  168. $string = $this->_entity_parser->substituteSpecialEntities($string);
  169. return $string;
  170. }
  171. /**
  172. * Lexes an HTML string into tokens.
  173. *
  174. * @param $string String HTML.
  175. * @return HTMLPurifier_Token array representation of HTML.
  176. */
  177. public function tokenizeHTML($string, $config, $context) {
  178. trigger_error('Call to abstract class', E_USER_ERROR);
  179. }
  180. /**
  181. * Translates CDATA sections into regular sections (through escaping).
  182. *
  183. * @param $string HTML string to process.
  184. * @returns HTML with CDATA sections escaped.
  185. */
  186. protected static function escapeCDATA($string) {
  187. return preg_replace_callback(
  188. '/<!\[CDATA\[(.+?)\]\]>/s',
  189. array('HTMLPurifier_Lexer', 'CDATACallback'),
  190. $string
  191. );
  192. }
  193. /**
  194. * Special CDATA case that is especially convoluted for <script>
  195. */
  196. protected static function escapeCommentedCDATA($string) {
  197. return preg_replace_callback(
  198. '#<!--//--><!\[CDATA\[//><!--(.+?)//--><!\]\]>#s',
  199. array('HTMLPurifier_Lexer', 'CDATACallback'),
  200. $string
  201. );
  202. }
  203. /**
  204. * Special Internet Explorer conditional comments should be removed.
  205. */
  206. protected static function removeIEConditional($string) {
  207. return preg_replace(
  208. '#<!--\[if [^>]+\]>.*?<!\[endif\]-->#si', // probably should generalize for all strings
  209. '',
  210. $string
  211. );
  212. }
  213. /**
  214. * Callback function for escapeCDATA() that does the work.
  215. *
  216. * @warning Though this is public in order to let the callback happen,
  217. * calling it directly is not recommended.
  218. * @params $matches PCRE matches array, with index 0 the entire match
  219. * and 1 the inside of the CDATA section.
  220. * @returns Escaped internals of the CDATA section.
  221. */
  222. protected static function CDATACallback($matches) {
  223. // not exactly sure why the character set is needed, but whatever
  224. return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');
  225. }
  226. /**
  227. * Takes a piece of HTML and normalizes it by converting entities, fixing
  228. * encoding, extracting bits, and other good stuff.
  229. * @todo Consider making protected
  230. */
  231. public function normalize($html, $config, $context) {
  232. // normalize newlines to \n
  233. if ($config->get('Core.NormalizeNewlines')) {
  234. $html = str_replace("\r\n", "\n", $html);
  235. $html = str_replace("\r", "\n", $html);
  236. }
  237. if ($config->get('HTML.Trusted')) {
  238. // escape convoluted CDATA
  239. $html = $this->escapeCommentedCDATA($html);
  240. }
  241. // escape CDATA
  242. $html = $this->escapeCDATA($html);
  243. $html = $this->removeIEConditional($html);
  244. // extract body from document if applicable
  245. if ($config->get('Core.ConvertDocumentToFragment')) {
  246. $e = false;
  247. if ($config->get('Core.CollectErrors')) {
  248. $e =& $context->get('ErrorCollector');
  249. }
  250. $new_html = $this->extractBody($html);
  251. if ($e && $new_html != $html) {
  252. $e->send(E_WARNING, 'Lexer: Extracted body');
  253. }
  254. $html = $new_html;
  255. }
  256. // expand entities that aren't the big five
  257. $html = $this->_entity_parser->substituteNonSpecialEntities($html);
  258. // clean into wellformed UTF-8 string for an SGML context: this has
  259. // to be done after entity expansion because the entities sometimes
  260. // represent non-SGML characters (horror, horror!)
  261. $html = HTMLPurifier_Encoder::cleanUTF8($html);
  262. // if processing instructions are to removed, remove them now
  263. if ($config->get('Core.RemoveProcessingInstructions')) {
  264. $html = preg_replace('#<\?.+?\?>#s', '', $html);
  265. }
  266. return $html;
  267. }
  268. /**
  269. * Takes a string of HTML (fragment or document) and returns the content
  270. * @todo Consider making protected
  271. */
  272. public function extractBody($html) {
  273. $matches = array();
  274. $result = preg_match('!<body[^>]*>(.*)</body>!is', $html, $matches);
  275. if ($result) {
  276. return $matches[1];
  277. } else {
  278. return $html;
  279. }
  280. }
  281. }
  282. // vim: et sw=4 sts=4