Encoder.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. <?php
  2. /**
  3. * A UTF-8 specific character encoder that handles cleaning and transforming.
  4. * @note All functions in this class should be static.
  5. */
  6. class HTMLPurifier_Encoder
  7. {
  8. /**
  9. * Constructor throws fatal error if you attempt to instantiate class
  10. */
  11. private function __construct() {
  12. trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR);
  13. }
  14. /**
  15. * Error-handler that mutes errors, alternative to shut-up operator.
  16. */
  17. public static function muteErrorHandler() {}
  18. /**
  19. * iconv wrapper which mutes errors, but doesn't work around bugs.
  20. */
  21. public static function unsafeIconv($in, $out, $text) {
  22. set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
  23. $r = iconv($in, $out, $text);
  24. restore_error_handler();
  25. return $r;
  26. }
  27. /**
  28. * iconv wrapper which mutes errors and works around bugs.
  29. */
  30. public static function iconv($in, $out, $text, $max_chunk_size = 8000) {
  31. $code = self::testIconvTruncateBug();
  32. if ($code == self::ICONV_OK) {
  33. return self::unsafeIconv($in, $out, $text);
  34. } elseif ($code == self::ICONV_TRUNCATES) {
  35. // we can only work around this if the input character set
  36. // is utf-8
  37. if ($in == 'utf-8') {
  38. if ($max_chunk_size < 4) {
  39. trigger_error('max_chunk_size is too small', E_USER_WARNING);
  40. return false;
  41. }
  42. // split into 8000 byte chunks, but be careful to handle
  43. // multibyte boundaries properly
  44. if (($c = strlen($text)) <= $max_chunk_size) {
  45. return self::unsafeIconv($in, $out, $text);
  46. }
  47. $r = '';
  48. $i = 0;
  49. while (true) {
  50. if ($i + $max_chunk_size >= $c) {
  51. $r .= self::unsafeIconv($in, $out, substr($text, $i));
  52. break;
  53. }
  54. // wibble the boundary
  55. if (0x80 != (0xC0 & ord($text[$i + $max_chunk_size]))) {
  56. $chunk_size = $max_chunk_size;
  57. } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 1]))) {
  58. $chunk_size = $max_chunk_size - 1;
  59. } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 2]))) {
  60. $chunk_size = $max_chunk_size - 2;
  61. } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 3]))) {
  62. $chunk_size = $max_chunk_size - 3;
  63. } else {
  64. return false; // rather confusing UTF-8...
  65. }
  66. $chunk = substr($text, $i, $chunk_size); // substr doesn't mind overlong lengths
  67. $r .= self::unsafeIconv($in, $out, $chunk);
  68. $i += $chunk_size;
  69. }
  70. return $r;
  71. } else {
  72. return false;
  73. }
  74. } else {
  75. return false;
  76. }
  77. }
  78. /**
  79. * Cleans a UTF-8 string for well-formedness and SGML validity
  80. *
  81. * It will parse according to UTF-8 and return a valid UTF8 string, with
  82. * non-SGML codepoints excluded.
  83. *
  84. * @note Just for reference, the non-SGML code points are 0 to 31 and
  85. * 127 to 159, inclusive. However, we allow code points 9, 10
  86. * and 13, which are the tab, line feed and carriage return
  87. * respectively. 128 and above the code points map to multibyte
  88. * UTF-8 representations.
  89. *
  90. * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and
  91. * hsivonen@iki.fi at <http://iki.fi/hsivonen/php-utf8/> under the
  92. * LGPL license. Notes on what changed are inside, but in general,
  93. * the original code transformed UTF-8 text into an array of integer
  94. * Unicode codepoints. Understandably, transforming that back to
  95. * a string would be somewhat expensive, so the function was modded to
  96. * directly operate on the string. However, this discourages code
  97. * reuse, and the logic enumerated here would be useful for any
  98. * function that needs to be able to understand UTF-8 characters.
  99. * As of right now, only smart lossless character encoding converters
  100. * would need that, and I'm probably not going to implement them.
  101. * Once again, PHP 6 should solve all our problems.
  102. */
  103. public static function cleanUTF8($str, $force_php = false) {
  104. // UTF-8 validity is checked since PHP 4.3.5
  105. // This is an optimization: if the string is already valid UTF-8, no
  106. // need to do PHP stuff. 99% of the time, this will be the case.
  107. // The regexp matches the XML char production, as well as well as excluding
  108. // non-SGML codepoints U+007F to U+009F
  109. if (preg_match('/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du', $str)) {
  110. return $str;
  111. }
  112. $mState = 0; // cached expected number of octets after the current octet
  113. // until the beginning of the next UTF8 character sequence
  114. $mUcs4 = 0; // cached Unicode character
  115. $mBytes = 1; // cached expected number of octets in the current sequence
  116. // original code involved an $out that was an array of Unicode
  117. // codepoints. Instead of having to convert back into UTF-8, we've
  118. // decided to directly append valid UTF-8 characters onto a string
  119. // $out once they're done. $char accumulates raw bytes, while $mUcs4
  120. // turns into the Unicode code point, so there's some redundancy.
  121. $out = '';
  122. $char = '';
  123. $len = strlen($str);
  124. for($i = 0; $i < $len; $i++) {
  125. $in = ord($str{$i});
  126. $char .= $str[$i]; // append byte to char
  127. if (0 == $mState) {
  128. // When mState is zero we expect either a US-ASCII character
  129. // or a multi-octet sequence.
  130. if (0 == (0x80 & ($in))) {
  131. // US-ASCII, pass straight through.
  132. if (($in <= 31 || $in == 127) &&
  133. !($in == 9 || $in == 13 || $in == 10) // save \r\t\n
  134. ) {
  135. // control characters, remove
  136. } else {
  137. $out .= $char;
  138. }
  139. // reset
  140. $char = '';
  141. $mBytes = 1;
  142. } elseif (0xC0 == (0xE0 & ($in))) {
  143. // First octet of 2 octet sequence
  144. $mUcs4 = ($in);
  145. $mUcs4 = ($mUcs4 & 0x1F) << 6;
  146. $mState = 1;
  147. $mBytes = 2;
  148. } elseif (0xE0 == (0xF0 & ($in))) {
  149. // First octet of 3 octet sequence
  150. $mUcs4 = ($in);
  151. $mUcs4 = ($mUcs4 & 0x0F) << 12;
  152. $mState = 2;
  153. $mBytes = 3;
  154. } elseif (0xF0 == (0xF8 & ($in))) {
  155. // First octet of 4 octet sequence
  156. $mUcs4 = ($in);
  157. $mUcs4 = ($mUcs4 & 0x07) << 18;
  158. $mState = 3;
  159. $mBytes = 4;
  160. } elseif (0xF8 == (0xFC & ($in))) {
  161. // First octet of 5 octet sequence.
  162. //
  163. // This is illegal because the encoded codepoint must be
  164. // either:
  165. // (a) not the shortest form or
  166. // (b) outside the Unicode range of 0-0x10FFFF.
  167. // Rather than trying to resynchronize, we will carry on
  168. // until the end of the sequence and let the later error
  169. // handling code catch it.
  170. $mUcs4 = ($in);
  171. $mUcs4 = ($mUcs4 & 0x03) << 24;
  172. $mState = 4;
  173. $mBytes = 5;
  174. } elseif (0xFC == (0xFE & ($in))) {
  175. // First octet of 6 octet sequence, see comments for 5
  176. // octet sequence.
  177. $mUcs4 = ($in);
  178. $mUcs4 = ($mUcs4 & 1) << 30;
  179. $mState = 5;
  180. $mBytes = 6;
  181. } else {
  182. // Current octet is neither in the US-ASCII range nor a
  183. // legal first octet of a multi-octet sequence.
  184. $mState = 0;
  185. $mUcs4 = 0;
  186. $mBytes = 1;
  187. $char = '';
  188. }
  189. } else {
  190. // When mState is non-zero, we expect a continuation of the
  191. // multi-octet sequence
  192. if (0x80 == (0xC0 & ($in))) {
  193. // Legal continuation.
  194. $shift = ($mState - 1) * 6;
  195. $tmp = $in;
  196. $tmp = ($tmp & 0x0000003F) << $shift;
  197. $mUcs4 |= $tmp;
  198. if (0 == --$mState) {
  199. // End of the multi-octet sequence. mUcs4 now contains
  200. // the final Unicode codepoint to be output
  201. // Check for illegal sequences and codepoints.
  202. // From Unicode 3.1, non-shortest form is illegal
  203. if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
  204. ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
  205. ((4 == $mBytes) && ($mUcs4 < 0x10000)) ||
  206. (4 < $mBytes) ||
  207. // From Unicode 3.2, surrogate characters = illegal
  208. (($mUcs4 & 0xFFFFF800) == 0xD800) ||
  209. // Codepoints outside the Unicode range are illegal
  210. ($mUcs4 > 0x10FFFF)
  211. ) {
  212. } elseif (0xFEFF != $mUcs4 && // omit BOM
  213. // check for valid Char unicode codepoints
  214. (
  215. 0x9 == $mUcs4 ||
  216. 0xA == $mUcs4 ||
  217. 0xD == $mUcs4 ||
  218. (0x20 <= $mUcs4 && 0x7E >= $mUcs4) ||
  219. // 7F-9F is not strictly prohibited by XML,
  220. // but it is non-SGML, and thus we don't allow it
  221. (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) ||
  222. (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4)
  223. )
  224. ) {
  225. $out .= $char;
  226. }
  227. // initialize UTF8 cache (reset)
  228. $mState = 0;
  229. $mUcs4 = 0;
  230. $mBytes = 1;
  231. $char = '';
  232. }
  233. } else {
  234. // ((0xC0 & (*in) != 0x80) && (mState != 0))
  235. // Incomplete multi-octet sequence.
  236. // used to result in complete fail, but we'll reset
  237. $mState = 0;
  238. $mUcs4 = 0;
  239. $mBytes = 1;
  240. $char ='';
  241. }
  242. }
  243. }
  244. return $out;
  245. }
  246. /**
  247. * Translates a Unicode codepoint into its corresponding UTF-8 character.
  248. * @note Based on Feyd's function at
  249. * <http://forums.devnetwork.net/viewtopic.php?p=191404#191404>,
  250. * which is in public domain.
  251. * @note While we're going to do code point parsing anyway, a good
  252. * optimization would be to refuse to translate code points that
  253. * are non-SGML characters. However, this could lead to duplication.
  254. * @note This is very similar to the unichr function in
  255. * maintenance/generate-entity-file.php (although this is superior,
  256. * due to its sanity checks).
  257. */
  258. // +----------+----------+----------+----------+
  259. // | 33222222 | 22221111 | 111111 | |
  260. // | 10987654 | 32109876 | 54321098 | 76543210 | bit
  261. // +----------+----------+----------+----------+
  262. // | | | | 0xxxxxxx | 1 byte 0x00000000..0x0000007F
  263. // | | | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF
  264. // | | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF
  265. // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF
  266. // +----------+----------+----------+----------+
  267. // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF)
  268. // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes
  269. // +----------+----------+----------+----------+
  270. public static function unichr($code) {
  271. if($code > 1114111 or $code < 0 or
  272. ($code >= 55296 and $code <= 57343) ) {
  273. // bits are set outside the "valid" range as defined
  274. // by UNICODE 4.1.0
  275. return '';
  276. }
  277. $x = $y = $z = $w = 0;
  278. if ($code < 128) {
  279. // regular ASCII character
  280. $x = $code;
  281. } else {
  282. // set up bits for UTF-8
  283. $x = ($code & 63) | 128;
  284. if ($code < 2048) {
  285. $y = (($code & 2047) >> 6) | 192;
  286. } else {
  287. $y = (($code & 4032) >> 6) | 128;
  288. if($code < 65536) {
  289. $z = (($code >> 12) & 15) | 224;
  290. } else {
  291. $z = (($code >> 12) & 63) | 128;
  292. $w = (($code >> 18) & 7) | 240;
  293. }
  294. }
  295. }
  296. // set up the actual character
  297. $ret = '';
  298. if($w) $ret .= chr($w);
  299. if($z) $ret .= chr($z);
  300. if($y) $ret .= chr($y);
  301. $ret .= chr($x);
  302. return $ret;
  303. }
  304. public static function iconvAvailable() {
  305. static $iconv = null;
  306. if ($iconv === null) {
  307. $iconv = function_exists('iconv') && self::testIconvTruncateBug() != self::ICONV_UNUSABLE;
  308. }
  309. return $iconv;
  310. }
  311. /**
  312. * Converts a string to UTF-8 based on configuration.
  313. */
  314. public static function convertToUTF8($str, $config, $context) {
  315. $encoding = $config->get('Core.Encoding');
  316. if ($encoding === 'utf-8') return $str;
  317. static $iconv = null;
  318. if ($iconv === null) $iconv = self::iconvAvailable();
  319. if ($iconv && !$config->get('Test.ForceNoIconv')) {
  320. // unaffected by bugs, since UTF-8 support all characters
  321. $str = self::unsafeIconv($encoding, 'utf-8//IGNORE', $str);
  322. if ($str === false) {
  323. // $encoding is not a valid encoding
  324. trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR);
  325. return '';
  326. }
  327. // If the string is bjorked by Shift_JIS or a similar encoding
  328. // that doesn't support all of ASCII, convert the naughty
  329. // characters to their true byte-wise ASCII/UTF-8 equivalents.
  330. $str = strtr($str, self::testEncodingSupportsASCII($encoding));
  331. return $str;
  332. } elseif ($encoding === 'iso-8859-1') {
  333. $str = utf8_encode($str);
  334. return $str;
  335. }
  336. $bug = HTMLPurifier_Encoder::testIconvTruncateBug();
  337. if ($bug == self::ICONV_OK) {
  338. trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);
  339. } else {
  340. trigger_error('You have a buggy version of iconv, see https://bugs.php.net/bug.php?id=48147 and http://sourceware.org/bugzilla/show_bug.cgi?id=13541', E_USER_ERROR);
  341. }
  342. }
  343. /**
  344. * Converts a string from UTF-8 based on configuration.
  345. * @note Currently, this is a lossy conversion, with unexpressable
  346. * characters being omitted.
  347. */
  348. public static function convertFromUTF8($str, $config, $context) {
  349. $encoding = $config->get('Core.Encoding');
  350. if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {
  351. $str = self::convertToASCIIDumbLossless($str);
  352. }
  353. if ($encoding === 'utf-8') return $str;
  354. static $iconv = null;
  355. if ($iconv === null) $iconv = self::iconvAvailable();
  356. if ($iconv && !$config->get('Test.ForceNoIconv')) {
  357. // Undo our previous fix in convertToUTF8, otherwise iconv will barf
  358. $ascii_fix = self::testEncodingSupportsASCII($encoding);
  359. if (!$escape && !empty($ascii_fix)) {
  360. $clear_fix = array();
  361. foreach ($ascii_fix as $utf8 => $native) $clear_fix[$utf8] = '';
  362. $str = strtr($str, $clear_fix);
  363. }
  364. $str = strtr($str, array_flip($ascii_fix));
  365. // Normal stuff
  366. $str = self::iconv('utf-8', $encoding . '//IGNORE', $str);
  367. return $str;
  368. } elseif ($encoding === 'iso-8859-1') {
  369. $str = utf8_decode($str);
  370. return $str;
  371. }
  372. trigger_error('Encoding not supported', E_USER_ERROR);
  373. // You might be tempted to assume that the ASCII representation
  374. // might be OK, however, this is *not* universally true over all
  375. // encodings. So we take the conservative route here, rather
  376. // than forcibly turn on %Core.EscapeNonASCIICharacters
  377. }
  378. /**
  379. * Lossless (character-wise) conversion of HTML to ASCII
  380. * @param $str UTF-8 string to be converted to ASCII
  381. * @returns ASCII encoded string with non-ASCII character entity-ized
  382. * @warning Adapted from MediaWiki, claiming fair use: this is a common
  383. * algorithm. If you disagree with this license fudgery,
  384. * implement it yourself.
  385. * @note Uses decimal numeric entities since they are best supported.
  386. * @note This is a DUMB function: it has no concept of keeping
  387. * character entities that the projected character encoding
  388. * can allow. We could possibly implement a smart version
  389. * but that would require it to also know which Unicode
  390. * codepoints the charset supported (not an easy task).
  391. * @note Sort of with cleanUTF8() but it assumes that $str is
  392. * well-formed UTF-8
  393. */
  394. public static function convertToASCIIDumbLossless($str) {
  395. $bytesleft = 0;
  396. $result = '';
  397. $working = 0;
  398. $len = strlen($str);
  399. for( $i = 0; $i < $len; $i++ ) {
  400. $bytevalue = ord( $str[$i] );
  401. if( $bytevalue <= 0x7F ) { //0xxx xxxx
  402. $result .= chr( $bytevalue );
  403. $bytesleft = 0;
  404. } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
  405. $working = $working << 6;
  406. $working += ($bytevalue & 0x3F);
  407. $bytesleft--;
  408. if( $bytesleft <= 0 ) {
  409. $result .= "&#" . $working . ";";
  410. }
  411. } elseif( $bytevalue <= 0xDF ) { //110x xxxx
  412. $working = $bytevalue & 0x1F;
  413. $bytesleft = 1;
  414. } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
  415. $working = $bytevalue & 0x0F;
  416. $bytesleft = 2;
  417. } else { //1111 0xxx
  418. $working = $bytevalue & 0x07;
  419. $bytesleft = 3;
  420. }
  421. }
  422. return $result;
  423. }
  424. /** No bugs detected in iconv. */
  425. const ICONV_OK = 0;
  426. /** Iconv truncates output if converting from UTF-8 to another
  427. * character set with //IGNORE, and a non-encodable character is found */
  428. const ICONV_TRUNCATES = 1;
  429. /** Iconv does not support //IGNORE, making it unusable for
  430. * transcoding purposes */
  431. const ICONV_UNUSABLE = 2;
  432. /**
  433. * glibc iconv has a known bug where it doesn't handle the magic
  434. * //IGNORE stanza correctly. In particular, rather than ignore
  435. * characters, it will return an EILSEQ after consuming some number
  436. * of characters, and expect you to restart iconv as if it were
  437. * an E2BIG. Old versions of PHP did not respect the errno, and
  438. * returned the fragment, so as a result you would see iconv
  439. * mysteriously truncating output. We can work around this by
  440. * manually chopping our input into segments of about 8000
  441. * characters, as long as PHP ignores the error code. If PHP starts
  442. * paying attention to the error code, iconv becomes unusable.
  443. *
  444. * @returns Error code indicating severity of bug.
  445. */
  446. public static function testIconvTruncateBug() {
  447. static $code = null;
  448. if ($code === null) {
  449. // better not use iconv, otherwise infinite loop!
  450. $r = self::unsafeIconv('utf-8', 'ascii//IGNORE', "\xCE\xB1" . str_repeat('a', 9000));
  451. if ($r === false) {
  452. $code = self::ICONV_UNUSABLE;
  453. } elseif (($c = strlen($r)) < 9000) {
  454. $code = self::ICONV_TRUNCATES;
  455. } elseif ($c > 9000) {
  456. trigger_error('Your copy of iconv is extremely buggy. Please notify HTML Purifier maintainers: include your iconv version as per phpversion()', E_USER_ERROR);
  457. } else {
  458. $code = self::ICONV_OK;
  459. }
  460. }
  461. return $code;
  462. }
  463. /**
  464. * This expensive function tests whether or not a given character
  465. * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will
  466. * fail this test, and require special processing. Variable width
  467. * encodings shouldn't ever fail.
  468. *
  469. * @param string $encoding Encoding name to test, as per iconv format
  470. * @param bool $bypass Whether or not to bypass the precompiled arrays.
  471. * @return Array of UTF-8 characters to their corresponding ASCII,
  472. * which can be used to "undo" any overzealous iconv action.
  473. */
  474. public static function testEncodingSupportsASCII($encoding, $bypass = false) {
  475. // All calls to iconv here are unsafe, proof by case analysis:
  476. // If ICONV_OK, no difference.
  477. // If ICONV_TRUNCATE, all calls involve one character inputs,
  478. // so bug is not triggered.
  479. // If ICONV_UNUSABLE, this call is irrelevant
  480. static $encodings = array();
  481. if (!$bypass) {
  482. if (isset($encodings[$encoding])) return $encodings[$encoding];
  483. $lenc = strtolower($encoding);
  484. switch ($lenc) {
  485. case 'shift_jis':
  486. return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~');
  487. case 'johab':
  488. return array("\xE2\x82\xA9" => '\\');
  489. }
  490. if (strpos($lenc, 'iso-8859-') === 0) return array();
  491. }
  492. $ret = array();
  493. if (self::unsafeIconv('UTF-8', $encoding, 'a') === false) return false;
  494. for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars
  495. $c = chr($i); // UTF-8 char
  496. $r = self::unsafeIconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion
  497. if (
  498. $r === '' ||
  499. // This line is needed for iconv implementations that do not
  500. // omit characters that do not exist in the target character set
  501. ($r === $c && self::unsafeIconv($encoding, 'UTF-8//IGNORE', $r) !== $c)
  502. ) {
  503. // Reverse engineer: what's the UTF-8 equiv of this byte
  504. // sequence? This assumes that there's no variable width
  505. // encoding that doesn't support ASCII.
  506. $ret[self::unsafeIconv($encoding, 'UTF-8//IGNORE', $c)] = $c;
  507. }
  508. }
  509. $encodings[$encoding] = $ret;
  510. return $ret;
  511. }
  512. }
  513. // vim: et sw=4 sts=4