Encoder.php 25 KB

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