Encoder.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. * Cleans a UTF-8 string for well-formedness and SGML validity
  20. *
  21. * It will parse according to UTF-8 and return a valid UTF8 string, with
  22. * non-SGML codepoints excluded.
  23. *
  24. * @note Just for reference, the non-SGML code points are 0 to 31 and
  25. * 127 to 159, inclusive. However, we allow code points 9, 10
  26. * and 13, which are the tab, line feed and carriage return
  27. * respectively. 128 and above the code points map to multibyte
  28. * UTF-8 representations.
  29. *
  30. * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and
  31. * hsivonen@iki.fi at <http://iki.fi/hsivonen/php-utf8/> under the
  32. * LGPL license. Notes on what changed are inside, but in general,
  33. * the original code transformed UTF-8 text into an array of integer
  34. * Unicode codepoints. Understandably, transforming that back to
  35. * a string would be somewhat expensive, so the function was modded to
  36. * directly operate on the string. However, this discourages code
  37. * reuse, and the logic enumerated here would be useful for any
  38. * function that needs to be able to understand UTF-8 characters.
  39. * As of right now, only smart lossless character encoding converters
  40. * would need that, and I'm probably not going to implement them.
  41. * Once again, PHP 6 should solve all our problems.
  42. */
  43. public static function cleanUTF8($str, $force_php = false) {
  44. // UTF-8 validity is checked since PHP 4.3.5
  45. // This is an optimization: if the string is already valid UTF-8, no
  46. // need to do PHP stuff. 99% of the time, this will be the case.
  47. // The regexp matches the XML char production, as well as well as excluding
  48. // non-SGML codepoints U+007F to U+009F
  49. 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)) {
  50. return $str;
  51. }
  52. $mState = 0; // cached expected number of octets after the current octet
  53. // until the beginning of the next UTF8 character sequence
  54. $mUcs4 = 0; // cached Unicode character
  55. $mBytes = 1; // cached expected number of octets in the current sequence
  56. // original code involved an $out that was an array of Unicode
  57. // codepoints. Instead of having to convert back into UTF-8, we've
  58. // decided to directly append valid UTF-8 characters onto a string
  59. // $out once they're done. $char accumulates raw bytes, while $mUcs4
  60. // turns into the Unicode code point, so there's some redundancy.
  61. $out = '';
  62. $char = '';
  63. $len = strlen($str);
  64. for($i = 0; $i < $len; $i++) {
  65. $in = ord($str{$i});
  66. $char .= $str[$i]; // append byte to char
  67. if (0 == $mState) {
  68. // When mState is zero we expect either a US-ASCII character
  69. // or a multi-octet sequence.
  70. if (0 == (0x80 & ($in))) {
  71. // US-ASCII, pass straight through.
  72. if (($in <= 31 || $in == 127) &&
  73. !($in == 9 || $in == 13 || $in == 10) // save \r\t\n
  74. ) {
  75. // control characters, remove
  76. } else {
  77. $out .= $char;
  78. }
  79. // reset
  80. $char = '';
  81. $mBytes = 1;
  82. } elseif (0xC0 == (0xE0 & ($in))) {
  83. // First octet of 2 octet sequence
  84. $mUcs4 = ($in);
  85. $mUcs4 = ($mUcs4 & 0x1F) << 6;
  86. $mState = 1;
  87. $mBytes = 2;
  88. } elseif (0xE0 == (0xF0 & ($in))) {
  89. // First octet of 3 octet sequence
  90. $mUcs4 = ($in);
  91. $mUcs4 = ($mUcs4 & 0x0F) << 12;
  92. $mState = 2;
  93. $mBytes = 3;
  94. } elseif (0xF0 == (0xF8 & ($in))) {
  95. // First octet of 4 octet sequence
  96. $mUcs4 = ($in);
  97. $mUcs4 = ($mUcs4 & 0x07) << 18;
  98. $mState = 3;
  99. $mBytes = 4;
  100. } elseif (0xF8 == (0xFC & ($in))) {
  101. // First octet of 5 octet sequence.
  102. //
  103. // This is illegal because the encoded codepoint must be
  104. // either:
  105. // (a) not the shortest form or
  106. // (b) outside the Unicode range of 0-0x10FFFF.
  107. // Rather than trying to resynchronize, we will carry on
  108. // until the end of the sequence and let the later error
  109. // handling code catch it.
  110. $mUcs4 = ($in);
  111. $mUcs4 = ($mUcs4 & 0x03) << 24;
  112. $mState = 4;
  113. $mBytes = 5;
  114. } elseif (0xFC == (0xFE & ($in))) {
  115. // First octet of 6 octet sequence, see comments for 5
  116. // octet sequence.
  117. $mUcs4 = ($in);
  118. $mUcs4 = ($mUcs4 & 1) << 30;
  119. $mState = 5;
  120. $mBytes = 6;
  121. } else {
  122. // Current octet is neither in the US-ASCII range nor a
  123. // legal first octet of a multi-octet sequence.
  124. $mState = 0;
  125. $mUcs4 = 0;
  126. $mBytes = 1;
  127. $char = '';
  128. }
  129. } else {
  130. // When mState is non-zero, we expect a continuation of the
  131. // multi-octet sequence
  132. if (0x80 == (0xC0 & ($in))) {
  133. // Legal continuation.
  134. $shift = ($mState - 1) * 6;
  135. $tmp = $in;
  136. $tmp = ($tmp & 0x0000003F) << $shift;
  137. $mUcs4 |= $tmp;
  138. if (0 == --$mState) {
  139. // End of the multi-octet sequence. mUcs4 now contains
  140. // the final Unicode codepoint to be output
  141. // Check for illegal sequences and codepoints.
  142. // From Unicode 3.1, non-shortest form is illegal
  143. if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
  144. ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
  145. ((4 == $mBytes) && ($mUcs4 < 0x10000)) ||
  146. (4 < $mBytes) ||
  147. // From Unicode 3.2, surrogate characters = illegal
  148. (($mUcs4 & 0xFFFFF800) == 0xD800) ||
  149. // Codepoints outside the Unicode range are illegal
  150. ($mUcs4 > 0x10FFFF)
  151. ) {
  152. } elseif (0xFEFF != $mUcs4 && // omit BOM
  153. // check for valid Char unicode codepoints
  154. (
  155. 0x9 == $mUcs4 ||
  156. 0xA == $mUcs4 ||
  157. 0xD == $mUcs4 ||
  158. (0x20 <= $mUcs4 && 0x7E >= $mUcs4) ||
  159. // 7F-9F is not strictly prohibited by XML,
  160. // but it is non-SGML, and thus we don't allow it
  161. (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) ||
  162. (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4)
  163. )
  164. ) {
  165. $out .= $char;
  166. }
  167. // initialize UTF8 cache (reset)
  168. $mState = 0;
  169. $mUcs4 = 0;
  170. $mBytes = 1;
  171. $char = '';
  172. }
  173. } else {
  174. // ((0xC0 & (*in) != 0x80) && (mState != 0))
  175. // Incomplete multi-octet sequence.
  176. // used to result in complete fail, but we'll reset
  177. $mState = 0;
  178. $mUcs4 = 0;
  179. $mBytes = 1;
  180. $char ='';
  181. }
  182. }
  183. }
  184. return $out;
  185. }
  186. /**
  187. * Translates a Unicode codepoint into its corresponding UTF-8 character.
  188. * @note Based on Feyd's function at
  189. * <http://forums.devnetwork.net/viewtopic.php?p=191404#191404>,
  190. * which is in public domain.
  191. * @note While we're going to do code point parsing anyway, a good
  192. * optimization would be to refuse to translate code points that
  193. * are non-SGML characters. However, this could lead to duplication.
  194. * @note This is very similar to the unichr function in
  195. * maintenance/generate-entity-file.php (although this is superior,
  196. * due to its sanity checks).
  197. */
  198. // +----------+----------+----------+----------+
  199. // | 33222222 | 22221111 | 111111 | |
  200. // | 10987654 | 32109876 | 54321098 | 76543210 | bit
  201. // +----------+----------+----------+----------+
  202. // | | | | 0xxxxxxx | 1 byte 0x00000000..0x0000007F
  203. // | | | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF
  204. // | | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF
  205. // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF
  206. // +----------+----------+----------+----------+
  207. // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF)
  208. // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes
  209. // +----------+----------+----------+----------+
  210. public static function unichr($code) {
  211. if($code > 1114111 or $code < 0 or
  212. ($code >= 55296 and $code <= 57343) ) {
  213. // bits are set outside the "valid" range as defined
  214. // by UNICODE 4.1.0
  215. return '';
  216. }
  217. $x = $y = $z = $w = 0;
  218. if ($code < 128) {
  219. // regular ASCII character
  220. $x = $code;
  221. } else {
  222. // set up bits for UTF-8
  223. $x = ($code & 63) | 128;
  224. if ($code < 2048) {
  225. $y = (($code & 2047) >> 6) | 192;
  226. } else {
  227. $y = (($code & 4032) >> 6) | 128;
  228. if($code < 65536) {
  229. $z = (($code >> 12) & 15) | 224;
  230. } else {
  231. $z = (($code >> 12) & 63) | 128;
  232. $w = (($code >> 18) & 7) | 240;
  233. }
  234. }
  235. }
  236. // set up the actual character
  237. $ret = '';
  238. if($w) $ret .= chr($w);
  239. if($z) $ret .= chr($z);
  240. if($y) $ret .= chr($y);
  241. $ret .= chr($x);
  242. return $ret;
  243. }
  244. /**
  245. * Converts a string to UTF-8 based on configuration.
  246. */
  247. public static function convertToUTF8($str, $config, $context) {
  248. $encoding = $config->get('Core.Encoding');
  249. if ($encoding === 'utf-8') return $str;
  250. static $iconv = null;
  251. if ($iconv === null) $iconv = function_exists('iconv');
  252. set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
  253. if ($iconv && !$config->get('Test.ForceNoIconv')) {
  254. $str = iconv($encoding, 'utf-8//IGNORE', $str);
  255. if ($str === false) {
  256. // $encoding is not a valid encoding
  257. restore_error_handler();
  258. trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR);
  259. return '';
  260. }
  261. // If the string is bjorked by Shift_JIS or a similar encoding
  262. // that doesn't support all of ASCII, convert the naughty
  263. // characters to their true byte-wise ASCII/UTF-8 equivalents.
  264. $str = strtr($str, HTMLPurifier_Encoder::testEncodingSupportsASCII($encoding));
  265. restore_error_handler();
  266. return $str;
  267. } elseif ($encoding === 'iso-8859-1') {
  268. $str = utf8_encode($str);
  269. restore_error_handler();
  270. return $str;
  271. }
  272. // Added by Ivan Tcholakov, 25-JUN-2010.
  273. // Using a custom encoding conversion function from Chamilo LMS,
  274. // for some encodings it works even without iconv or mbstring installed.
  275. elseif (function_exists('api_is_encoding_supported')) {
  276. if (api_is_encoding_supported($encoding)) {
  277. $str = api_utf8_encode($str, $encoding);
  278. restore_error_handler();
  279. return $str;
  280. }
  281. }
  282. //
  283. trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);
  284. }
  285. /**
  286. * Converts a string from UTF-8 based on configuration.
  287. * @note Currently, this is a lossy conversion, with unexpressable
  288. * characters being omitted.
  289. */
  290. public static function convertFromUTF8($str, $config, $context) {
  291. $encoding = $config->get('Core.Encoding');
  292. if ($encoding === 'utf-8') return $str;
  293. static $iconv = null;
  294. if ($iconv === null) $iconv = function_exists('iconv');
  295. if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {
  296. $str = HTMLPurifier_Encoder::convertToASCIIDumbLossless($str);
  297. }
  298. set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
  299. if ($iconv && !$config->get('Test.ForceNoIconv')) {
  300. // Undo our previous fix in convertToUTF8, otherwise iconv will barf
  301. $ascii_fix = HTMLPurifier_Encoder::testEncodingSupportsASCII($encoding);
  302. if (!$escape && !empty($ascii_fix)) {
  303. $clear_fix = array();
  304. foreach ($ascii_fix as $utf8 => $native) $clear_fix[$utf8] = '';
  305. $str = strtr($str, $clear_fix);
  306. }
  307. $str = strtr($str, array_flip($ascii_fix));
  308. // Normal stuff
  309. $str = iconv('utf-8', $encoding . '//IGNORE', $str);
  310. restore_error_handler();
  311. return $str;
  312. } elseif ($encoding === 'iso-8859-1') {
  313. $str = utf8_decode($str);
  314. restore_error_handler();
  315. return $str;
  316. }
  317. // Added by Ivan Tcholakov, 25-JUN-2010.
  318. // Using a custom encoding conversion function from Chamilo LMS,
  319. // for some encodings it works even without iconv or mbstring installed.
  320. elseif (function_exists('api_is_encoding_supported')) {
  321. if (api_is_encoding_supported($encoding)) {
  322. $str = api_utf8_decode($str, $encoding);
  323. restore_error_handler();
  324. return $str;
  325. }
  326. }
  327. //
  328. trigger_error('Encoding not supported', E_USER_ERROR);
  329. }
  330. /**
  331. * Lossless (character-wise) conversion of HTML to ASCII
  332. * @param $str UTF-8 string to be converted to ASCII
  333. * @returns ASCII encoded string with non-ASCII character entity-ized
  334. * @warning Adapted from MediaWiki, claiming fair use: this is a common
  335. * algorithm. If you disagree with this license fudgery,
  336. * implement it yourself.
  337. * @note Uses decimal numeric entities since they are best supported.
  338. * @note This is a DUMB function: it has no concept of keeping
  339. * character entities that the projected character encoding
  340. * can allow. We could possibly implement a smart version
  341. * but that would require it to also know which Unicode
  342. * codepoints the charset supported (not an easy task).
  343. * @note Sort of with cleanUTF8() but it assumes that $str is
  344. * well-formed UTF-8
  345. */
  346. public static function convertToASCIIDumbLossless($str) {
  347. $bytesleft = 0;
  348. $result = '';
  349. $working = 0;
  350. $len = strlen($str);
  351. for( $i = 0; $i < $len; $i++ ) {
  352. $bytevalue = ord( $str[$i] );
  353. if( $bytevalue <= 0x7F ) { //0xxx xxxx
  354. $result .= chr( $bytevalue );
  355. $bytesleft = 0;
  356. } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
  357. $working = $working << 6;
  358. $working += ($bytevalue & 0x3F);
  359. $bytesleft--;
  360. if( $bytesleft <= 0 ) {
  361. $result .= "&#" . $working . ";";
  362. }
  363. } elseif( $bytevalue <= 0xDF ) { //110x xxxx
  364. $working = $bytevalue & 0x1F;
  365. $bytesleft = 1;
  366. } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
  367. $working = $bytevalue & 0x0F;
  368. $bytesleft = 2;
  369. } else { //1111 0xxx
  370. $working = $bytevalue & 0x07;
  371. $bytesleft = 3;
  372. }
  373. }
  374. return $result;
  375. }
  376. /**
  377. * This expensive function tests whether or not a given character
  378. * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will
  379. * fail this test, and require special processing. Variable width
  380. * encodings shouldn't ever fail.
  381. *
  382. * @param string $encoding Encoding name to test, as per iconv format
  383. * @param bool $bypass Whether or not to bypass the precompiled arrays.
  384. * @return Array of UTF-8 characters to their corresponding ASCII,
  385. * which can be used to "undo" any overzealous iconv action.
  386. */
  387. public static function testEncodingSupportsASCII($encoding, $bypass = false) {
  388. static $encodings = array();
  389. if (!$bypass) {
  390. if (isset($encodings[$encoding])) return $encodings[$encoding];
  391. $lenc = strtolower($encoding);
  392. switch ($lenc) {
  393. case 'shift_jis':
  394. return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~');
  395. case 'johab':
  396. return array("\xE2\x82\xA9" => '\\');
  397. }
  398. if (strpos($lenc, 'iso-8859-') === 0) return array();
  399. }
  400. $ret = array();
  401. set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
  402. if (iconv('UTF-8', $encoding, 'a') === false) return false;
  403. for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars
  404. $c = chr($i); // UTF-8 char
  405. $r = iconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion
  406. if (
  407. $r === '' ||
  408. // This line is needed for iconv implementations that do not
  409. // omit characters that do not exist in the target character set
  410. ($r === $c && iconv($encoding, 'UTF-8//IGNORE', $r) !== $c)
  411. ) {
  412. // Reverse engineer: what's the UTF-8 equiv of this byte
  413. // sequence? This assumes that there's no variable width
  414. // encoding that doesn't support ASCII.
  415. $ret[iconv($encoding, 'UTF-8//IGNORE', $c)] = $c;
  416. }
  417. }
  418. restore_error_handler();
  419. $encodings[$encoding] = $ret;
  420. return $ret;
  421. }
  422. }
  423. // vim: et sw=4 sts=4