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

/plugins/vjCommentPlugin/lib/tools/htmlpurifier/library/HTMLPurifier/Encoder.php

https://bitbucket.org/Kudlaty/360kdw
PHP | 426 lines | 242 code | 25 blank | 159 comment | 77 complexity | fc3fee6ae7b5cfa04ce2c4ba8699a98b MD5 | raw file
Possible License(s): LGPL-2.1
  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. trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);
  273. }
  274. /**
  275. * Converts a string from UTF-8 based on configuration.
  276. * @note Currently, this is a lossy conversion, with unexpressable
  277. * characters being omitted.
  278. */
  279. public static function convertFromUTF8($str, $config, $context) {
  280. $encoding = $config->get('Core.Encoding');
  281. if ($encoding === 'utf-8') return $str;
  282. static $iconv = null;
  283. if ($iconv === null) $iconv = function_exists('iconv');
  284. if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {
  285. $str = HTMLPurifier_Encoder::convertToASCIIDumbLossless($str);
  286. }
  287. set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
  288. if ($iconv && !$config->get('Test.ForceNoIconv')) {
  289. // Undo our previous fix in convertToUTF8, otherwise iconv will barf
  290. $ascii_fix = HTMLPurifier_Encoder::testEncodingSupportsASCII($encoding);
  291. if (!$escape && !empty($ascii_fix)) {
  292. $clear_fix = array();
  293. foreach ($ascii_fix as $utf8 => $native) $clear_fix[$utf8] = '';
  294. $str = strtr($str, $clear_fix);
  295. }
  296. $str = strtr($str, array_flip($ascii_fix));
  297. // Normal stuff
  298. $str = iconv('utf-8', $encoding . '//IGNORE', $str);
  299. restore_error_handler();
  300. return $str;
  301. } elseif ($encoding === 'iso-8859-1') {
  302. $str = utf8_decode($str);
  303. restore_error_handler();
  304. return $str;
  305. }
  306. trigger_error('Encoding not supported', E_USER_ERROR);
  307. }
  308. /**
  309. * Lossless (character-wise) conversion of HTML to ASCII
  310. * @param $str UTF-8 string to be converted to ASCII
  311. * @returns ASCII encoded string with non-ASCII character entity-ized
  312. * @warning Adapted from MediaWiki, claiming fair use: this is a common
  313. * algorithm. If you disagree with this license fudgery,
  314. * implement it yourself.
  315. * @note Uses decimal numeric entities since they are best supported.
  316. * @note This is a DUMB function: it has no concept of keeping
  317. * character entities that the projected character encoding
  318. * can allow. We could possibly implement a smart version
  319. * but that would require it to also know which Unicode
  320. * codepoints the charset supported (not an easy task).
  321. * @note Sort of with cleanUTF8() but it assumes that $str is
  322. * well-formed UTF-8
  323. */
  324. public static function convertToASCIIDumbLossless($str) {
  325. $bytesleft = 0;
  326. $result = '';
  327. $working = 0;
  328. $len = strlen($str);
  329. for( $i = 0; $i < $len; $i++ ) {
  330. $bytevalue = ord( $str[$i] );
  331. if( $bytevalue <= 0x7F ) { //0xxx xxxx
  332. $result .= chr( $bytevalue );
  333. $bytesleft = 0;
  334. } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
  335. $working = $working << 6;
  336. $working += ($bytevalue & 0x3F);
  337. $bytesleft--;
  338. if( $bytesleft <= 0 ) {
  339. $result .= "&#" . $working . ";";
  340. }
  341. } elseif( $bytevalue <= 0xDF ) { //110x xxxx
  342. $working = $bytevalue & 0x1F;
  343. $bytesleft = 1;
  344. } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
  345. $working = $bytevalue & 0x0F;
  346. $bytesleft = 2;
  347. } else { //1111 0xxx
  348. $working = $bytevalue & 0x07;
  349. $bytesleft = 3;
  350. }
  351. }
  352. return $result;
  353. }
  354. /**
  355. * This expensive function tests whether or not a given character
  356. * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will
  357. * fail this test, and require special processing. Variable width
  358. * encodings shouldn't ever fail.
  359. *
  360. * @param string $encoding Encoding name to test, as per iconv format
  361. * @param bool $bypass Whether or not to bypass the precompiled arrays.
  362. * @return Array of UTF-8 characters to their corresponding ASCII,
  363. * which can be used to "undo" any overzealous iconv action.
  364. */
  365. public static function testEncodingSupportsASCII($encoding, $bypass = false) {
  366. static $encodings = array();
  367. if (!$bypass) {
  368. if (isset($encodings[$encoding])) return $encodings[$encoding];
  369. $lenc = strtolower($encoding);
  370. switch ($lenc) {
  371. case 'shift_jis':
  372. return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~');
  373. case 'johab':
  374. return array("\xE2\x82\xA9" => '\\');
  375. }
  376. if (strpos($lenc, 'iso-8859-') === 0) return array();
  377. }
  378. $ret = array();
  379. set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
  380. if (iconv('UTF-8', $encoding, 'a') === false) return false;
  381. for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars
  382. $c = chr($i); // UTF-8 char
  383. $r = iconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion
  384. if (
  385. $r === '' ||
  386. // This line is needed for iconv implementations that do not
  387. // omit characters that do not exist in the target character set
  388. ($r === $c && iconv($encoding, 'UTF-8//IGNORE', $r) !== $c)
  389. ) {
  390. // Reverse engineer: what's the UTF-8 equiv of this byte
  391. // sequence? This assumes that there's no variable width
  392. // encoding that doesn't support ASCII.
  393. $ret[iconv($encoding, 'UTF-8//IGNORE', $c)] = $c;
  394. }
  395. }
  396. restore_error_handler();
  397. $encodings[$encoding] = $ret;
  398. return $ret;
  399. }
  400. }
  401. // vim: et sw=4 sts=4