PageRenderTime 26ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/include/htmlpurifier/library/HTMLPurifier/Lexer.php

https://bitbucket.org/jhunsinfotech/blue-blues
PHP | 298 lines | 140 code | 40 blank | 118 comment | 19 complexity | 8ec8d7147d51cee1b833a6553bebd467 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, LGPL-3.0
  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. * Callback function for escapeCDATA() that does the work.
  205. *
  206. * @warning Though this is public in order to let the callback happen,
  207. * calling it directly is not recommended.
  208. * @params $matches PCRE matches array, with index 0 the entire match
  209. * and 1 the inside of the CDATA section.
  210. * @returns Escaped internals of the CDATA section.
  211. */
  212. protected static function CDATACallback($matches) {
  213. // not exactly sure why the character set is needed, but whatever
  214. return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');
  215. }
  216. /**
  217. * Takes a piece of HTML and normalizes it by converting entities, fixing
  218. * encoding, extracting bits, and other good stuff.
  219. * @todo Consider making protected
  220. */
  221. public function normalize($html, $config, $context) {
  222. // normalize newlines to \n
  223. $html = str_replace("\r\n", "\n", $html);
  224. $html = str_replace("\r", "\n", $html);
  225. if ($config->get('HTML', 'Trusted')) {
  226. // escape convoluted CDATA
  227. $html = $this->escapeCommentedCDATA($html);
  228. }
  229. // escape CDATA
  230. $html = $this->escapeCDATA($html);
  231. // extract body from document if applicable
  232. if ($config->get('Core', 'ConvertDocumentToFragment')) {
  233. $html = $this->extractBody($html);
  234. }
  235. // expand entities that aren't the big five
  236. $html = $this->_entity_parser->substituteNonSpecialEntities($html);
  237. // clean into wellformed UTF-8 string for an SGML context: this has
  238. // to be done after entity expansion because the entities sometimes
  239. // represent non-SGML characters (horror, horror!)
  240. $html = HTMLPurifier_Encoder::cleanUTF8($html);
  241. return $html;
  242. }
  243. /**
  244. * Takes a string of HTML (fragment or document) and returns the content
  245. * @todo Consider making protected
  246. */
  247. public function extractBody($html) {
  248. $matches = array();
  249. $result = preg_match('!<body[^>]*>(.+?)</body>!is', $html, $matches);
  250. if ($result) {
  251. return $matches[1];
  252. } else {
  253. return $html;
  254. }
  255. }
  256. }
  257. // vim: et sw=4 sts=4