Lexer.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. /**
  49. * @type HTMLPurifier_EntityParser
  50. */
  51. private $_entity_parser;
  52. // -- STATIC ----------------------------------------------------------
  53. /**
  54. * Retrieves or sets the default Lexer as a Prototype Factory.
  55. *
  56. * By default HTMLPurifier_Lexer_DOMLex will be returned. There are
  57. * a few exceptions involving special features that only DirectLex
  58. * implements.
  59. *
  60. * @note The behavior of this class has changed, rather than accepting
  61. * a prototype object, it now accepts a configuration object.
  62. * To specify your own prototype, set %Core.LexerImpl to it.
  63. * This change in behavior de-singletonizes the lexer object.
  64. *
  65. * @param HTMLPurifier_Config $config
  66. * @return HTMLPurifier_Lexer
  67. * @throws HTMLPurifier_Exception
  68. */
  69. public static function create($config)
  70. {
  71. if (!($config instanceof HTMLPurifier_Config)) {
  72. $lexer = $config;
  73. trigger_error(
  74. "Passing a prototype to
  75. HTMLPurifier_Lexer::create() is deprecated, please instead
  76. use %Core.LexerImpl",
  77. E_USER_WARNING
  78. );
  79. } else {
  80. $lexer = $config->get('Core.LexerImpl');
  81. }
  82. $needs_tracking =
  83. $config->get('Core.MaintainLineNumbers') ||
  84. $config->get('Core.CollectErrors');
  85. $inst = null;
  86. if (is_object($lexer)) {
  87. $inst = $lexer;
  88. } else {
  89. if (is_null($lexer)) {
  90. do {
  91. // auto-detection algorithm
  92. if ($needs_tracking) {
  93. $lexer = 'DirectLex';
  94. break;
  95. }
  96. if (class_exists('DOMDocument', false) &&
  97. method_exists('DOMDocument', 'loadHTML') &&
  98. !extension_loaded('domxml')
  99. ) {
  100. // check for DOM support, because while it's part of the
  101. // core, it can be disabled compile time. Also, the PECL
  102. // domxml extension overrides the default DOM, and is evil
  103. // and nasty and we shan't bother to support it
  104. $lexer = 'DOMLex';
  105. } else {
  106. $lexer = 'DirectLex';
  107. }
  108. } while (0);
  109. } // do..while so we can break
  110. // instantiate recognized string names
  111. switch ($lexer) {
  112. case 'DOMLex':
  113. $inst = new HTMLPurifier_Lexer_DOMLex();
  114. break;
  115. case 'DirectLex':
  116. $inst = new HTMLPurifier_Lexer_DirectLex();
  117. break;
  118. case 'PH5P':
  119. $inst = new HTMLPurifier_Lexer_PH5P();
  120. break;
  121. default:
  122. throw new HTMLPurifier_Exception(
  123. "Cannot instantiate unrecognized Lexer type " .
  124. htmlspecialchars($lexer)
  125. );
  126. }
  127. }
  128. if (!$inst) {
  129. throw new HTMLPurifier_Exception('No lexer was instantiated');
  130. }
  131. // once PHP DOM implements native line numbers, or we
  132. // hack out something using XSLT, remove this stipulation
  133. if ($needs_tracking && !$inst->tracksLineNumbers) {
  134. throw new HTMLPurifier_Exception(
  135. 'Cannot use lexer that does not support line numbers with ' .
  136. 'Core.MaintainLineNumbers or Core.CollectErrors (use DirectLex instead)'
  137. );
  138. }
  139. return $inst;
  140. }
  141. // -- CONVENIENCE MEMBERS ---------------------------------------------
  142. public function __construct()
  143. {
  144. $this->_entity_parser = new HTMLPurifier_EntityParser();
  145. }
  146. /**
  147. * Most common entity to raw value conversion table for special entities.
  148. * @type array
  149. */
  150. protected $_special_entity2str =
  151. array(
  152. '&quot;' => '"',
  153. '&amp;' => '&',
  154. '&lt;' => '<',
  155. '&gt;' => '>',
  156. '&#39;' => "'",
  157. '&#039;' => "'",
  158. '&#x27;' => "'"
  159. );
  160. public function parseText($string, $config) {
  161. return $this->parseData($string, false, $config);
  162. }
  163. public function parseAttr($string, $config) {
  164. return $this->parseData($string, true, $config);
  165. }
  166. /**
  167. * Parses special entities into the proper characters.
  168. *
  169. * This string will translate escaped versions of the special characters
  170. * into the correct ones.
  171. *
  172. * @param string $string String character data to be parsed.
  173. * @return string Parsed character data.
  174. */
  175. public function parseData($string, $is_attr, $config)
  176. {
  177. // following functions require at least one character
  178. if ($string === '') {
  179. return '';
  180. }
  181. // subtracts amps that cannot possibly be escaped
  182. $num_amp = substr_count($string, '&') - substr_count($string, '& ') -
  183. ($string[strlen($string) - 1] === '&' ? 1 : 0);
  184. if (!$num_amp) {
  185. return $string;
  186. } // abort if no entities
  187. $num_esc_amp = substr_count($string, '&amp;');
  188. $string = strtr($string, $this->_special_entity2str);
  189. // code duplication for sake of optimization, see above
  190. $num_amp_2 = substr_count($string, '&') - substr_count($string, '& ') -
  191. ($string[strlen($string) - 1] === '&' ? 1 : 0);
  192. if ($num_amp_2 <= $num_esc_amp) {
  193. return $string;
  194. }
  195. // hmm... now we have some uncommon entities. Use the callback.
  196. if ($config->get('Core.LegacyEntityDecoder')) {
  197. $string = $this->_entity_parser->substituteSpecialEntities($string);
  198. } else {
  199. if ($is_attr) {
  200. $string = $this->_entity_parser->substituteAttrEntities($string);
  201. } else {
  202. $string = $this->_entity_parser->substituteTextEntities($string);
  203. }
  204. }
  205. return $string;
  206. }
  207. /**
  208. * Lexes an HTML string into tokens.
  209. * @param $string String HTML.
  210. * @param HTMLPurifier_Config $config
  211. * @param HTMLPurifier_Context $context
  212. * @return HTMLPurifier_Token[] array representation of HTML.
  213. */
  214. public function tokenizeHTML($string, $config, $context)
  215. {
  216. trigger_error('Call to abstract class', E_USER_ERROR);
  217. }
  218. /**
  219. * Translates CDATA sections into regular sections (through escaping).
  220. * @param string $string HTML string to process.
  221. * @return string HTML with CDATA sections escaped.
  222. */
  223. protected static function escapeCDATA($string)
  224. {
  225. return preg_replace_callback(
  226. '/<!\[CDATA\[(.+?)\]\]>/s',
  227. array('HTMLPurifier_Lexer', 'CDATACallback'),
  228. $string
  229. );
  230. }
  231. /**
  232. * Special CDATA case that is especially convoluted for <script>
  233. * @param string $string HTML string to process.
  234. * @return string HTML with CDATA sections escaped.
  235. */
  236. protected static function escapeCommentedCDATA($string)
  237. {
  238. return preg_replace_callback(
  239. '#<!--//--><!\[CDATA\[//><!--(.+?)//--><!\]\]>#s',
  240. array('HTMLPurifier_Lexer', 'CDATACallback'),
  241. $string
  242. );
  243. }
  244. /**
  245. * Special Internet Explorer conditional comments should be removed.
  246. * @param string $string HTML string to process.
  247. * @return string HTML with conditional comments removed.
  248. */
  249. protected static function removeIEConditional($string)
  250. {
  251. return preg_replace(
  252. '#<!--\[if [^>]+\]>.*?<!\[endif\]-->#si', // probably should generalize for all strings
  253. '',
  254. $string
  255. );
  256. }
  257. /**
  258. * Callback function for escapeCDATA() that does the work.
  259. *
  260. * @warning Though this is public in order to let the callback happen,
  261. * calling it directly is not recommended.
  262. * @param array $matches PCRE matches array, with index 0 the entire match
  263. * and 1 the inside of the CDATA section.
  264. * @return string Escaped internals of the CDATA section.
  265. */
  266. protected static function CDATACallback($matches)
  267. {
  268. // not exactly sure why the character set is needed, but whatever
  269. return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');
  270. }
  271. /**
  272. * Takes a piece of HTML and normalizes it by converting entities, fixing
  273. * encoding, extracting bits, and other good stuff.
  274. * @param string $html HTML.
  275. * @param HTMLPurifier_Config $config
  276. * @param HTMLPurifier_Context $context
  277. * @return string
  278. * @todo Consider making protected
  279. */
  280. public function normalize($html, $config, $context)
  281. {
  282. // normalize newlines to \n
  283. if ($config->get('Core.NormalizeNewlines')) {
  284. $html = str_replace("\r\n", "\n", (string)$html);
  285. $html = str_replace("\r", "\n", (string)$html);
  286. }
  287. if ($config->get('HTML.Trusted')) {
  288. // escape convoluted CDATA
  289. $html = $this->escapeCommentedCDATA($html);
  290. }
  291. // escape CDATA
  292. $html = $this->escapeCDATA($html);
  293. $html = $this->removeIEConditional($html);
  294. // extract body from document if applicable
  295. if ($config->get('Core.ConvertDocumentToFragment')) {
  296. $e = false;
  297. if ($config->get('Core.CollectErrors')) {
  298. $e =& $context->get('ErrorCollector');
  299. }
  300. $new_html = $this->extractBody($html);
  301. if ($e && $new_html != $html) {
  302. $e->send(E_WARNING, 'Lexer: Extracted body');
  303. }
  304. $html = $new_html;
  305. }
  306. // expand entities that aren't the big five
  307. if ($config->get('Core.LegacyEntityDecoder')) {
  308. $html = $this->_entity_parser->substituteNonSpecialEntities($html);
  309. }
  310. // clean into wellformed UTF-8 string for an SGML context: this has
  311. // to be done after entity expansion because the entities sometimes
  312. // represent non-SGML characters (horror, horror!)
  313. $html = HTMLPurifier_Encoder::cleanUTF8($html);
  314. // if processing instructions are to removed, remove them now
  315. if ($config->get('Core.RemoveProcessingInstructions')) {
  316. $html = preg_replace('#<\?.+?\?>#s', '', $html);
  317. }
  318. $hidden_elements = $config->get('Core.HiddenElements');
  319. if ($config->get('Core.AggressivelyRemoveScript') &&
  320. !($config->get('HTML.Trusted') || !$config->get('Core.RemoveScriptContents')
  321. || empty($hidden_elements["script"]))) {
  322. $html = preg_replace('#<script[^>]*>.*?</script>#i', '', $html);
  323. }
  324. return $html;
  325. }
  326. /**
  327. * Takes a string of HTML (fragment or document) and returns the content
  328. * @todo Consider making protected
  329. */
  330. public function extractBody($html)
  331. {
  332. $matches = array();
  333. $result = preg_match('|(.*?)<body[^>]*>(.*)</body>|is', $html, $matches);
  334. if ($result) {
  335. // Make sure it's not in a comment
  336. $comment_start = strrpos($matches[1], '<!--');
  337. $comment_end = strrpos($matches[1], '-->');
  338. if ($comment_start === false ||
  339. ($comment_end !== false && $comment_end > $comment_start)) {
  340. return $matches[2];
  341. }
  342. }
  343. return $html;
  344. }
  345. }
  346. // vim: et sw=4 sts=4