InputStream.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. /*
  3. Copyright 2009 Geoffrey Sneddon <http://gsnedders.com/>
  4. Permission is hereby granted, free of charge, to any person obtaining a
  5. copy of this software and associated documentation files (the
  6. "Software"), to deal in the Software without restriction, including
  7. without limitation the rights to use, copy, modify, merge, publish,
  8. distribute, sublicense, and/or sell copies of the Software, and to
  9. permit persons to whom the Software is furnished to do so, subject to
  10. the following conditions:
  11. The above copyright notice and this permission notice shall be included
  12. in all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  17. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  18. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  19. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. */
  21. // Some conventions:
  22. // /* */ indicates verbatim text from the HTML 5 specification
  23. // // indicates regular comments
  24. class HTML5_InputStream {
  25. /**
  26. * The string data we're parsing.
  27. */
  28. private $data;
  29. /**
  30. * The current integer byte position we are in $data
  31. */
  32. private $char;
  33. /**
  34. * Length of $data; when $char === $data, we are at the end-of-file.
  35. */
  36. private $EOF;
  37. /**
  38. * Parse errors.
  39. */
  40. public $errors = array();
  41. /**
  42. * @param $data Data to parse
  43. */
  44. public function __construct($data) {
  45. /* Given an encoding, the bytes in the input stream must be
  46. converted to Unicode characters for the tokeniser, as
  47. described by the rules for that encoding, except that the
  48. leading U+FEFF BYTE ORDER MARK character, if any, must not
  49. be stripped by the encoding layer (it is stripped by the rule below).
  50. Bytes or sequences of bytes in the original byte stream that
  51. could not be converted to Unicode characters must be converted
  52. to U+FFFD REPLACEMENT CHARACTER code points. */
  53. // XXX currently assuming input data is UTF-8; once we
  54. // build encoding detection this will no longer be the case
  55. //
  56. // We previously had an mbstring implementation here, but that
  57. // implementation is heavily non-conforming, so it's been
  58. // omitted.
  59. if (extension_loaded('iconv')) {
  60. // non-conforming
  61. $data = @iconv('UTF-8', 'UTF-8//IGNORE', $data);
  62. } else {
  63. // we can make a conforming native implementation
  64. throw new Exception('Not implemented, please install mbstring or iconv');
  65. }
  66. /* One leading U+FEFF BYTE ORDER MARK character must be
  67. ignored if any are present. */
  68. if (substr($data, 0, 3) === "\xEF\xBB\xBF") {
  69. $data = substr($data, 3);
  70. }
  71. /* All U+0000 NULL characters in the input must be replaced
  72. by U+FFFD REPLACEMENT CHARACTERs. Any occurrences of such
  73. characters is a parse error. */
  74. for ($i = 0, $count = substr_count($data, "\0"); $i < $count; $i++) {
  75. $this->errors[] = array(
  76. 'type' => HTML5_Tokenizer::PARSEERROR,
  77. 'data' => 'null-character'
  78. );
  79. }
  80. /* U+000D CARRIAGE RETURN (CR) characters and U+000A LINE FEED
  81. (LF) characters are treated specially. Any CR characters
  82. that are followed by LF characters must be removed, and any
  83. CR characters not followed by LF characters must be converted
  84. to LF characters. Thus, newlines in HTML DOMs are represented
  85. by LF characters, and there are never any CR characters in the
  86. input to the tokenization stage. */
  87. $data = str_replace(
  88. array(
  89. "\0",
  90. "\r\n",
  91. "\r"
  92. ),
  93. array(
  94. "\xEF\xBF\xBD",
  95. "\n",
  96. "\n"
  97. ),
  98. $data
  99. );
  100. /* Any occurrences of any characters in the ranges U+0001 to
  101. U+0008, U+000B, U+000E to U+001F, U+007F to U+009F,
  102. U+D800 to U+DFFF , U+FDD0 to U+FDEF, and
  103. characters U+FFFE, U+FFFF, U+1FFFE, U+1FFFF, U+2FFFE, U+2FFFF,
  104. U+3FFFE, U+3FFFF, U+4FFFE, U+4FFFF, U+5FFFE, U+5FFFF, U+6FFFE,
  105. U+6FFFF, U+7FFFE, U+7FFFF, U+8FFFE, U+8FFFF, U+9FFFE, U+9FFFF,
  106. U+AFFFE, U+AFFFF, U+BFFFE, U+BFFFF, U+CFFFE, U+CFFFF, U+DFFFE,
  107. U+DFFFF, U+EFFFE, U+EFFFF, U+FFFFE, U+FFFFF, U+10FFFE, and
  108. U+10FFFF are parse errors. (These are all control characters
  109. or permanently undefined Unicode characters.) */
  110. // Check PCRE is loaded.
  111. if (extension_loaded('pcre')) {
  112. $count = preg_match_all(
  113. '/(?:
  114. [\x01-\x08\x0B\x0E-\x1F\x7F] # U+0001 to U+0008, U+000B, U+000E to U+001F and U+007F
  115. |
  116. \xC2[\x80-\x9F] # U+0080 to U+009F
  117. |
  118. \xED(?:\xA0[\x80-\xFF]|[\xA1-\xBE][\x00-\xFF]|\xBF[\x00-\xBF]) # U+D800 to U+DFFFF
  119. |
  120. \xEF\xB7[\x90-\xAF] # U+FDD0 to U+FDEF
  121. |
  122. \xEF\xBF[\xBE\xBF] # U+FFFE and U+FFFF
  123. |
  124. [\xF0-\xF4][\x8F-\xBF]\xBF[\xBE\xBF] # U+nFFFE and U+nFFFF (1 <= n <= 10_{16})
  125. )/x',
  126. $data,
  127. $matches
  128. );
  129. for ($i = 0; $i < $count; $i++) {
  130. $this->errors[] = array(
  131. 'type' => HTML5_Tokenizer::PARSEERROR,
  132. 'data' => 'invalid-codepoint'
  133. );
  134. }
  135. } else {
  136. // XXX: Need non-PCRE impl, probably using substr_count
  137. }
  138. $this->data = $data;
  139. $this->char = 0;
  140. $this->EOF = strlen($data);
  141. }
  142. /**
  143. * Returns the current line that the tokenizer is at.
  144. */
  145. public function getCurrentLine() {
  146. // Check the string isn't empty
  147. if($this->EOF) {
  148. // Add one to $this->char because we want the number for the next
  149. // byte to be processed.
  150. return substr_count($this->data, "\n", 0, min($this->char, $this->EOF)) + 1;
  151. } else {
  152. // If the string is empty, we are on the first line (sorta).
  153. return 1;
  154. }
  155. }
  156. /**
  157. * Returns the current column of the current line that the tokenizer is at.
  158. */
  159. public function getColumnOffset() {
  160. // strrpos is weird, and the offset needs to be negative for what we
  161. // want (i.e., the last \n before $this->char). This needs to not have
  162. // one (to make it point to the next character, the one we want the
  163. // position of) added to it because strrpos's behaviour includes the
  164. // final offset byte.
  165. $lastLine = strrpos($this->data, "\n", $this->char - 1 - strlen($this->data));
  166. // However, for here we want the length up until the next byte to be
  167. // processed, so add one to the current byte ($this->char).
  168. if($lastLine !== false) {
  169. $findLengthOf = substr($this->data, $lastLine + 1, $this->char - 1 - $lastLine);
  170. } else {
  171. $findLengthOf = substr($this->data, 0, $this->char);
  172. }
  173. // Get the length for the string we need.
  174. if(extension_loaded('iconv')) {
  175. return iconv_strlen($findLengthOf, 'utf-8');
  176. } elseif(extension_loaded('mbstring')) {
  177. return mb_strlen($findLengthOf, 'utf-8');
  178. } elseif(extension_loaded('xml')) {
  179. return strlen(utf8_decode($findLengthOf));
  180. } else {
  181. $count = count_chars($findLengthOf);
  182. // 0x80 = 0x7F - 0 + 1 (one added to get inclusive range)
  183. // 0x33 = 0xF4 - 0x2C + 1 (one added to get inclusive range)
  184. return array_sum(array_slice($count, 0, 0x80)) +
  185. array_sum(array_slice($count, 0xC2, 0x33));
  186. }
  187. }
  188. /**
  189. * Retrieve the currently consume character.
  190. * @note This performs bounds checking
  191. */
  192. public function char() {
  193. return ($this->char++ < $this->EOF)
  194. ? $this->data[$this->char - 1]
  195. : false;
  196. }
  197. /**
  198. * Get all characters until EOF.
  199. * @note This performs bounds checking
  200. */
  201. public function remainingChars() {
  202. if($this->char < $this->EOF) {
  203. $data = substr($this->data, $this->char);
  204. $this->char = $this->EOF;
  205. return $data;
  206. } else {
  207. return false;
  208. }
  209. }
  210. /**
  211. * Matches as far as possible until we reach a certain set of bytes
  212. * and returns the matched substring.
  213. * @param $bytes Bytes to match.
  214. */
  215. public function charsUntil($bytes, $max = null) {
  216. if ($this->char < $this->EOF) {
  217. if ($max === 0 || $max) {
  218. $len = strcspn($this->data, $bytes, $this->char, $max);
  219. } else {
  220. $len = strcspn($this->data, $bytes, $this->char);
  221. }
  222. $string = (string) substr($this->data, $this->char, $len);
  223. $this->char += $len;
  224. return $string;
  225. } else {
  226. return false;
  227. }
  228. }
  229. /**
  230. * Matches as far as possible with a certain set of bytes
  231. * and returns the matched substring.
  232. * @param $bytes Bytes to match.
  233. */
  234. public function charsWhile($bytes, $max = null) {
  235. if ($this->char < $this->EOF) {
  236. if ($max === 0 || $max) {
  237. $len = strspn($this->data, $bytes, $this->char, $max);
  238. } else {
  239. $len = strspn($this->data, $bytes, $this->char);
  240. }
  241. $string = (string) substr($this->data, $this->char, $len);
  242. $this->char += $len;
  243. return $string;
  244. } else {
  245. return false;
  246. }
  247. }
  248. /**
  249. * Unconsume one character.
  250. */
  251. public function unget() {
  252. if ($this->char <= $this->EOF) {
  253. $this->char--;
  254. }
  255. }
  256. }