rcube_charset.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2005-2012, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2012, Kolab Systems AG |
  7. | Copyright (C) 2000 Edmund Grimley Evans <edmundo@rano.org> |
  8. | |
  9. | Licensed under the GNU General Public License version 3 or |
  10. | any later version with exceptions for skins & plugins. |
  11. | See the README file for a full license statement. |
  12. | |
  13. | PURPOSE: |
  14. | Provide charset conversion functionality |
  15. +-----------------------------------------------------------------------+
  16. | Author: Thomas Bruederli <roundcube@gmail.com> |
  17. | Author: Aleksander Machniak <alec@alec.pl> |
  18. +-----------------------------------------------------------------------+
  19. */
  20. /**
  21. * Character sets conversion functionality
  22. *
  23. * @package Framework
  24. * @subpackage Core
  25. * @author Thomas Bruederli <roundcube@gmail.com>
  26. * @author Aleksander Machniak <alec@alec.pl>
  27. * @author Edmund Grimley Evans <edmundo@rano.org>
  28. */
  29. class rcube_charset
  30. {
  31. // Aliases: some of them from HTML5 spec.
  32. static public $aliases = array(
  33. 'USASCII' => 'WINDOWS-1252',
  34. 'ANSIX31101983' => 'WINDOWS-1252',
  35. 'ANSIX341968' => 'WINDOWS-1252',
  36. 'UNKNOWN8BIT' => 'ISO-8859-15',
  37. 'UNKNOWN' => 'ISO-8859-15',
  38. 'USERDEFINED' => 'ISO-8859-15',
  39. 'KSC56011987' => 'EUC-KR',
  40. 'GB2312' => 'GBK',
  41. 'GB231280' => 'GBK',
  42. 'UNICODE' => 'UTF-8',
  43. 'UTF7IMAP' => 'UTF7-IMAP',
  44. 'TIS620' => 'WINDOWS-874',
  45. 'ISO88599' => 'WINDOWS-1254',
  46. 'ISO885911' => 'WINDOWS-874',
  47. 'MACROMAN' => 'MACINTOSH',
  48. '77' => 'MAC',
  49. '128' => 'SHIFT-JIS',
  50. '129' => 'CP949',
  51. '130' => 'CP1361',
  52. '134' => 'GBK',
  53. '136' => 'BIG5',
  54. '161' => 'WINDOWS-1253',
  55. '162' => 'WINDOWS-1254',
  56. '163' => 'WINDOWS-1258',
  57. '177' => 'WINDOWS-1255',
  58. '178' => 'WINDOWS-1256',
  59. '186' => 'WINDOWS-1257',
  60. '204' => 'WINDOWS-1251',
  61. '222' => 'WINDOWS-874',
  62. '238' => 'WINDOWS-1250',
  63. 'MS950' => 'CP950',
  64. 'WINDOWS949' => 'UHC',
  65. );
  66. /**
  67. * Catch an error and throw an exception.
  68. *
  69. * @param int $errno Level of the error
  70. * @param string $errstr Error message
  71. */
  72. public static function error_handler($errno, $errstr)
  73. {
  74. throw new ErrorException($errstr, 0, $errno);
  75. }
  76. /**
  77. * Parse and validate charset name string (see #1485758).
  78. * Sometimes charset string is malformed, there are also charset aliases
  79. * but we need strict names for charset conversion (specially utf8 class)
  80. *
  81. * @param string $input Input charset name
  82. *
  83. * @return string The validated charset name
  84. */
  85. public static function parse_charset($input)
  86. {
  87. static $charsets = array();
  88. $charset = strtoupper($input);
  89. if (isset($charsets[$input])) {
  90. return $charsets[$input];
  91. }
  92. $charset = preg_replace(array(
  93. '/^[^0-9A-Z]+/', // e.g. _ISO-8859-JP$SIO
  94. '/\$.*$/', // e.g. _ISO-8859-JP$SIO
  95. '/UNICODE-1-1-*/', // RFC1641/1642
  96. '/^X-/', // X- prefix (e.g. X-ROMAN8 => ROMAN8)
  97. ), '', $charset);
  98. if ($charset == 'BINARY') {
  99. return $charsets[$input] = null;
  100. }
  101. // allow A-Z and 0-9 only
  102. $str = preg_replace('/[^A-Z0-9]/', '', $charset);
  103. if (isset(self::$aliases[$str])) {
  104. $result = self::$aliases[$str];
  105. }
  106. // UTF
  107. else if (preg_match('/U[A-Z][A-Z](7|8|16|32)(BE|LE)*/', $str, $m)) {
  108. $result = 'UTF-' . $m[1] . $m[2];
  109. }
  110. // ISO-8859
  111. else if (preg_match('/ISO8859([0-9]{0,2})/', $str, $m)) {
  112. $iso = 'ISO-8859-' . ($m[1] ?: 1);
  113. // some clients sends windows-1252 text as latin1,
  114. // it is safe to use windows-1252 for all latin1
  115. $result = $iso == 'ISO-8859-1' ? 'WINDOWS-1252' : $iso;
  116. }
  117. // handle broken charset names e.g. WINDOWS-1250HTTP-EQUIVCONTENT-TYPE
  118. else if (preg_match('/(WIN|WINDOWS)([0-9]+)/', $str, $m)) {
  119. $result = 'WINDOWS-' . $m[2];
  120. }
  121. // LATIN
  122. else if (preg_match('/LATIN(.*)/', $str, $m)) {
  123. $aliases = array('2' => 2, '3' => 3, '4' => 4, '5' => 9, '6' => 10,
  124. '7' => 13, '8' => 14, '9' => 15, '10' => 16,
  125. 'ARABIC' => 6, 'CYRILLIC' => 5, 'GREEK' => 7, 'GREEK1' => 7, 'HEBREW' => 8
  126. );
  127. // some clients sends windows-1252 text as latin1,
  128. // it is safe to use windows-1252 for all latin1
  129. if ($m[1] == 1) {
  130. $result = 'WINDOWS-1252';
  131. }
  132. // if iconv is not supported we need ISO labels, it's also safe for iconv
  133. else if (!empty($aliases[$m[1]])) {
  134. $result = 'ISO-8859-'.$aliases[$m[1]];
  135. }
  136. // iconv requires convertion of e.g. LATIN-1 to LATIN1
  137. else {
  138. $result = $str;
  139. }
  140. }
  141. else {
  142. $result = $charset;
  143. }
  144. $charsets[$input] = $result;
  145. return $result;
  146. }
  147. /**
  148. * Convert a string from one charset to another.
  149. * Uses mbstring and iconv functions if possible
  150. *
  151. * @param string $str Input string
  152. * @param string $from Suspected charset of the input string
  153. * @param string $to Target charset to convert to; defaults to RCUBE_CHARSET
  154. *
  155. * @return string Converted string
  156. */
  157. public static function convert($str, $from, $to = null)
  158. {
  159. static $iconv_options = null;
  160. static $mbstring_sc = null;
  161. $to = empty($to) ? RCUBE_CHARSET : strtoupper($to);
  162. $from = self::parse_charset($from);
  163. // It is a common case when UTF-16 charset is used with US-ASCII content (#1488654)
  164. // In that case we can just skip the conversion (use UTF-8)
  165. if ($from == 'UTF-16' && !preg_match('/[^\x00-\x7F]/', $str)) {
  166. $from = 'UTF-8';
  167. }
  168. if ($from == $to || empty($str) || empty($from)) {
  169. return $str;
  170. }
  171. if ($iconv_options === null) {
  172. if (function_exists('iconv')) {
  173. // ignore characters not available in output charset
  174. $iconv_options = '//IGNORE';
  175. if (iconv('', $iconv_options, '') === false) {
  176. // iconv implementation does not support options
  177. $iconv_options = '';
  178. }
  179. }
  180. else {
  181. $iconv_options = false;
  182. }
  183. }
  184. // convert charset using iconv module
  185. if ($iconv_options !== false && $from != 'UTF7-IMAP' && $to != 'UTF7-IMAP') {
  186. // throw an exception if iconv reports an illegal character in input
  187. // it means that input string has been truncated
  188. set_error_handler(array('rcube_charset', 'error_handler'), E_NOTICE);
  189. try {
  190. $out = iconv($from, $to . $iconv_options, $str);
  191. }
  192. catch (ErrorException $e) {
  193. $out = false;
  194. }
  195. restore_error_handler();
  196. if ($out !== false) {
  197. return $out;
  198. }
  199. }
  200. if ($mbstring_sc === null) {
  201. $mbstring_sc = extension_loaded('mbstring') ? mb_substitute_character() : false;
  202. }
  203. // convert charset using mbstring module
  204. if ($mbstring_sc !== false) {
  205. $aliases = array(
  206. 'WINDOWS-1257' => 'ISO-8859-13',
  207. 'US-ASCII' => 'ASCII',
  208. );
  209. $mb_from = $aliases[$from] ?: $from;
  210. $mb_to = $aliases[$to] ?: $to;
  211. // Do the same as //IGNORE with iconv
  212. mb_substitute_character('none');
  213. // throw an exception if mbstring reports an illegal character in input
  214. // using mb_check_encoding() is much slower
  215. set_error_handler(array('rcube_charset', 'error_handler'), E_WARNING);
  216. try {
  217. $out = mb_convert_encoding($str, $mb_to, $mb_from);
  218. }
  219. catch (ErrorException $e) {
  220. $out = false;
  221. }
  222. restore_error_handler();
  223. mb_substitute_character($mbstring_sc);
  224. if ($out !== false) {
  225. return $out;
  226. }
  227. }
  228. // convert charset using bundled classes/functions
  229. if ($to == 'UTF-8') {
  230. if ($from == 'UTF7-IMAP') {
  231. if ($out = self::utf7imap_to_utf8($str)) {
  232. return $out;
  233. }
  234. }
  235. else if ($from == 'UTF-7') {
  236. if ($out = self::utf7_to_utf8($str)) {
  237. return $out;
  238. }
  239. }
  240. }
  241. // encode string for output
  242. if ($from == 'UTF-8') {
  243. // @TODO: we need a function for UTF-7 (RFC2152) conversion
  244. if ($to == 'UTF7-IMAP' || $to == 'UTF-7') {
  245. if ($out = self::utf8_to_utf7imap($str)) {
  246. return $out;
  247. }
  248. }
  249. }
  250. if (!isset($out)) {
  251. trigger_error("No suitable function found for '$from' to '$to' conversion");
  252. }
  253. // return original string
  254. return $str;
  255. }
  256. /**
  257. * Converts string from standard UTF-7 (RFC 2152) to UTF-8.
  258. *
  259. * @param string $str Input string (UTF-7)
  260. *
  261. * @return string Converted string (UTF-8)
  262. */
  263. public static function utf7_to_utf8($str)
  264. {
  265. $Index_64 = array(
  266. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  267. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  268. 0,0,0,0, 0,0,0,0, 0,0,0,1, 0,0,0,0,
  269. 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0,
  270. 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
  271. 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
  272. 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
  273. 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
  274. );
  275. $u7len = strlen($str);
  276. $str = strval($str);
  277. $res = '';
  278. for ($i=0; $u7len > 0; $i++, $u7len--) {
  279. $u7 = $str[$i];
  280. if ($u7 == '+') {
  281. $i++;
  282. $u7len--;
  283. $ch = '';
  284. for (; $u7len > 0; $i++, $u7len--) {
  285. $u7 = $str[$i];
  286. if (!$Index_64[ord($u7)]) {
  287. break;
  288. }
  289. $ch .= $u7;
  290. }
  291. if ($ch == '') {
  292. if ($u7 == '-') {
  293. $res .= '+';
  294. }
  295. continue;
  296. }
  297. $res .= self::utf16_to_utf8(base64_decode($ch));
  298. }
  299. else {
  300. $res .= $u7;
  301. }
  302. }
  303. return $res;
  304. }
  305. /**
  306. * Converts string from UTF-16 to UTF-8 (helper for utf-7 to utf-8 conversion)
  307. *
  308. * @param string $str Input string
  309. *
  310. * @return string The converted string
  311. */
  312. public static function utf16_to_utf8($str)
  313. {
  314. $len = strlen($str);
  315. $dec = '';
  316. for ($i = 0; $i < $len; $i += 2) {
  317. $c = ord($str[$i]) << 8 | ord($str[$i + 1]);
  318. if ($c >= 0x0001 && $c <= 0x007F) {
  319. $dec .= chr($c);
  320. }
  321. else if ($c > 0x07FF) {
  322. $dec .= chr(0xE0 | (($c >> 12) & 0x0F));
  323. $dec .= chr(0x80 | (($c >> 6) & 0x3F));
  324. $dec .= chr(0x80 | (($c >> 0) & 0x3F));
  325. }
  326. else {
  327. $dec .= chr(0xC0 | (($c >> 6) & 0x1F));
  328. $dec .= chr(0x80 | (($c >> 0) & 0x3F));
  329. }
  330. }
  331. return $dec;
  332. }
  333. /**
  334. * Convert the data ($str) from RFC 2060's UTF-7 to UTF-8.
  335. * If input data is invalid, return the original input string.
  336. * RFC 2060 obviously intends the encoding to be unique (see
  337. * point 5 in section 5.1.3), so we reject any non-canonical
  338. * form, such as &ACY- (instead of &-) or &AMA-&AMA- (instead
  339. * of &AMAAwA-).
  340. *
  341. * Translated from C to PHP by Thomas Bruederli <roundcube@gmail.com>
  342. *
  343. * @param string $str Input string (UTF7-IMAP)
  344. *
  345. * @return string Output string (UTF-8)
  346. */
  347. public static function utf7imap_to_utf8($str)
  348. {
  349. $Index_64 = array(
  350. -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
  351. -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
  352. -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, 63,-1,-1,-1,
  353. 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1,
  354. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
  355. 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
  356. -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
  357. 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
  358. );
  359. $u7len = strlen($str);
  360. $str = strval($str);
  361. $p = '';
  362. $err = '';
  363. for ($i=0; $u7len > 0; $i++, $u7len--) {
  364. $u7 = $str[$i];
  365. if ($u7 == '&') {
  366. $i++;
  367. $u7len--;
  368. $u7 = $str[$i];
  369. if ($u7len && $u7 == '-') {
  370. $p .= '&';
  371. continue;
  372. }
  373. $ch = 0;
  374. $k = 10;
  375. for (; $u7len > 0; $i++, $u7len--) {
  376. $u7 = $str[$i];
  377. if ((ord($u7) & 0x80) || ($b = $Index_64[ord($u7)]) == -1) {
  378. break;
  379. }
  380. if ($k > 0) {
  381. $ch |= $b << $k;
  382. $k -= 6;
  383. }
  384. else {
  385. $ch |= $b >> (-$k);
  386. if ($ch < 0x80) {
  387. // Printable US-ASCII
  388. if (0x20 <= $ch && $ch < 0x7f) {
  389. return $err;
  390. }
  391. $p .= chr($ch);
  392. }
  393. else if ($ch < 0x800) {
  394. $p .= chr(0xc0 | ($ch >> 6));
  395. $p .= chr(0x80 | ($ch & 0x3f));
  396. }
  397. else {
  398. $p .= chr(0xe0 | ($ch >> 12));
  399. $p .= chr(0x80 | (($ch >> 6) & 0x3f));
  400. $p .= chr(0x80 | ($ch & 0x3f));
  401. }
  402. $ch = ($b << (16 + $k)) & 0xffff;
  403. $k += 10;
  404. }
  405. }
  406. // Non-zero or too many extra bits
  407. if ($ch || $k < 6) {
  408. return $err;
  409. }
  410. // BASE64 not properly terminated
  411. if (!$u7len || $u7 != '-') {
  412. return $err;
  413. }
  414. // Adjacent BASE64 sections
  415. if ($u7len > 2 && $str[$i+1] == '&' && $str[$i+2] != '-') {
  416. return $err;
  417. }
  418. }
  419. // Not printable US-ASCII
  420. else if (ord($u7) < 0x20 || ord($u7) >= 0x7f) {
  421. return $err;
  422. }
  423. else {
  424. $p .= $u7;
  425. }
  426. }
  427. return $p;
  428. }
  429. /**
  430. * Convert the data ($str) from UTF-8 to RFC 2060's UTF-7.
  431. * Unicode characters above U+FFFF are replaced by U+FFFE.
  432. * If input data is invalid, return an empty string.
  433. *
  434. * Translated from C to PHP by Thomas Bruederli <roundcube@gmail.com>
  435. *
  436. * @param string $str Input string (UTF-8)
  437. *
  438. * @return string Output string (UTF7-IMAP)
  439. */
  440. public static function utf8_to_utf7imap($str)
  441. {
  442. $B64Chars = array(
  443. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  444. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
  445. 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  446. 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
  447. '8', '9', '+', ','
  448. );
  449. $u8len = strlen($str);
  450. $base64 = 0;
  451. $i = 0;
  452. $p = '';
  453. $err = '';
  454. while ($u8len) {
  455. $u8 = $str[$i];
  456. $c = ord($u8);
  457. if ($c < 0x80) {
  458. $ch = $c;
  459. $n = 0;
  460. }
  461. else if ($c < 0xc2) {
  462. return $err;
  463. }
  464. else if ($c < 0xe0) {
  465. $ch = $c & 0x1f;
  466. $n = 1;
  467. }
  468. else if ($c < 0xf0) {
  469. $ch = $c & 0x0f;
  470. $n = 2;
  471. }
  472. else if ($c < 0xf8) {
  473. $ch = $c & 0x07;
  474. $n = 3;
  475. }
  476. else if ($c < 0xfc) {
  477. $ch = $c & 0x03;
  478. $n = 4;
  479. }
  480. else if ($c < 0xfe) {
  481. $ch = $c & 0x01;
  482. $n = 5;
  483. }
  484. else {
  485. return $err;
  486. }
  487. $i++;
  488. $u8len--;
  489. if ($n > $u8len) {
  490. return $err;
  491. }
  492. for ($j=0; $j < $n; $j++) {
  493. $o = ord($str[$i+$j]);
  494. if (($o & 0xc0) != 0x80) {
  495. return $err;
  496. }
  497. $ch = ($ch << 6) | ($o & 0x3f);
  498. }
  499. if ($n > 1 && !($ch >> ($n * 5 + 1))) {
  500. return $err;
  501. }
  502. $i += $n;
  503. $u8len -= $n;
  504. if ($ch < 0x20 || $ch >= 0x7f) {
  505. if (!$base64) {
  506. $p .= '&';
  507. $base64 = 1;
  508. $b = 0;
  509. $k = 10;
  510. }
  511. if ($ch & ~0xffff) {
  512. $ch = 0xfffe;
  513. }
  514. $p .= $B64Chars[($b | $ch >> $k)];
  515. $k -= 6;
  516. for (; $k >= 0; $k -= 6) {
  517. $p .= $B64Chars[(($ch >> $k) & 0x3f)];
  518. }
  519. $b = ($ch << (-$k)) & 0x3f;
  520. $k += 16;
  521. }
  522. else {
  523. if ($base64) {
  524. if ($k > 10) {
  525. $p .= $B64Chars[$b];
  526. }
  527. $p .= '-';
  528. $base64 = 0;
  529. }
  530. $p .= chr($ch);
  531. if (chr($ch) == '&') {
  532. $p .= '-';
  533. }
  534. }
  535. }
  536. if ($base64) {
  537. if ($k > 10) {
  538. $p .= $B64Chars[$b];
  539. }
  540. $p .= '-';
  541. }
  542. return $p;
  543. }
  544. /**
  545. * A method to guess character set of a string.
  546. *
  547. * @param string $string String
  548. * @param string $failover Default result for failover
  549. * @param string $language User language
  550. *
  551. * @return string Charset name
  552. */
  553. public static function detect($string, $failover = null, $language = null)
  554. {
  555. if (substr($string, 0, 4) == "\0\0\xFE\xFF") return 'UTF-32BE'; // Big Endian
  556. if (substr($string, 0, 4) == "\xFF\xFE\0\0") return 'UTF-32LE'; // Little Endian
  557. if (substr($string, 0, 2) == "\xFE\xFF") return 'UTF-16BE'; // Big Endian
  558. if (substr($string, 0, 2) == "\xFF\xFE") return 'UTF-16LE'; // Little Endian
  559. if (substr($string, 0, 3) == "\xEF\xBB\xBF") return 'UTF-8';
  560. // heuristics
  561. if ($string[0] == "\0" && $string[1] == "\0" && $string[2] == "\0" && $string[3] != "\0") return 'UTF-32BE';
  562. if ($string[0] != "\0" && $string[1] == "\0" && $string[2] == "\0" && $string[3] == "\0") return 'UTF-32LE';
  563. if ($string[0] == "\0" && $string[1] != "\0" && $string[2] == "\0" && $string[3] != "\0") return 'UTF-16BE';
  564. if ($string[0] != "\0" && $string[1] == "\0" && $string[2] != "\0" && $string[3] == "\0") return 'UTF-16LE';
  565. if (empty($language)) {
  566. $rcube = rcube::get_instance();
  567. $language = $rcube->get_user_language();
  568. }
  569. // Prioritize charsets according to current language (#1485669)
  570. switch ($language) {
  571. case 'ja_JP':
  572. $prio = array('ISO-2022-JP', 'JIS', 'UTF-8', 'EUC-JP', 'eucJP-win', 'SJIS', 'SJIS-win');
  573. break;
  574. case 'zh_CN':
  575. case 'zh_TW':
  576. $prio = array('UTF-8', 'BIG-5', 'GB2312', 'EUC-TW');
  577. break;
  578. case 'ko_KR':
  579. $prio = array('UTF-8', 'EUC-KR', 'ISO-2022-KR');
  580. break;
  581. case 'ru_RU':
  582. $prio = array('UTF-8', 'WINDOWS-1251', 'KOI8-R');
  583. break;
  584. case 'tr_TR':
  585. $prio = array('UTF-8', 'ISO-8859-9', 'WINDOWS-1254');
  586. break;
  587. }
  588. // mb_detect_encoding() is not reliable for some charsets (#1490135)
  589. // use mb_check_encoding() to make charset priority lists really working
  590. if ($prio && function_exists('mb_check_encoding')) {
  591. foreach ($prio as $encoding) {
  592. if (mb_check_encoding($string, $encoding)) {
  593. return $encoding;
  594. }
  595. }
  596. }
  597. if (function_exists('mb_detect_encoding')) {
  598. if (!$prio) {
  599. $prio = array('UTF-8', 'SJIS', 'GB2312',
  600. 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
  601. 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
  602. 'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
  603. 'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R', 'BIG-5',
  604. 'ISO-2022-KR', 'ISO-2022-JP',
  605. );
  606. }
  607. $encodings = array_unique(array_merge($prio, mb_list_encodings()));
  608. if ($encoding = mb_detect_encoding($string, $encodings)) {
  609. return $encoding;
  610. }
  611. }
  612. // No match, check for UTF-8
  613. // from http://w3.org/International/questions/qa-forms-utf-8.html
  614. if (preg_match('/\A(
  615. [\x09\x0A\x0D\x20-\x7E]
  616. | [\xC2-\xDF][\x80-\xBF]
  617. | \xE0[\xA0-\xBF][\x80-\xBF]
  618. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
  619. | \xED[\x80-\x9F][\x80-\xBF]
  620. | \xF0[\x90-\xBF][\x80-\xBF]{2}
  621. | [\xF1-\xF3][\x80-\xBF]{3}
  622. | \xF4[\x80-\x8F][\x80-\xBF]{2}
  623. )*\z/xs', substr($string, 0, 2048))
  624. ) {
  625. return 'UTF-8';
  626. }
  627. return $failover;
  628. }
  629. /**
  630. * Removes non-unicode characters from input.
  631. *
  632. * @param mixed $input String or array.
  633. *
  634. * @return mixed String or array
  635. */
  636. public static function clean($input)
  637. {
  638. // handle input of type array
  639. if (is_array($input)) {
  640. foreach ($input as $idx => $val) {
  641. $input[$idx] = self::clean($val);
  642. }
  643. return $input;
  644. }
  645. if (!is_string($input) || $input == '') {
  646. return $input;
  647. }
  648. // iconv/mbstring are much faster (especially with long strings)
  649. if (function_exists('mb_convert_encoding')) {
  650. $msch = mb_substitute_character();
  651. mb_substitute_character('none');
  652. $res = mb_convert_encoding($input, 'UTF-8', 'UTF-8');
  653. mb_substitute_character($msch);
  654. if ($res !== false) {
  655. return $res;
  656. }
  657. }
  658. if (function_exists('iconv')) {
  659. if (($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false) {
  660. return $res;
  661. }
  662. }
  663. $seq = '';
  664. $out = '';
  665. $regexp = '/^('.
  666. // '[\x00-\x7F]'. // UTF8-1
  667. '|[\xC2-\xDF][\x80-\xBF]'. // UTF8-2
  668. '|\xE0[\xA0-\xBF][\x80-\xBF]'. // UTF8-3
  669. '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'. // UTF8-3
  670. '|\xED[\x80-\x9F][\x80-\xBF]'. // UTF8-3
  671. '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'. // UTF8-3
  672. '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'. // UTF8-4
  673. '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
  674. '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'. // UTF8-4
  675. ')$/';
  676. for ($i = 0, $len = strlen($input); $i < $len; $i++) {
  677. $chr = $input[$i];
  678. $ord = ord($chr);
  679. // 1-byte character
  680. if ($ord <= 0x7F) {
  681. if ($seq !== '') {
  682. $out .= preg_match($regexp, $seq) ? $seq : '';
  683. $seq = '';
  684. }
  685. $out .= $chr;
  686. }
  687. // first byte of multibyte sequence
  688. else if ($ord >= 0xC0) {
  689. if ($seq !== '') {
  690. $out .= preg_match($regexp, $seq) ? $seq : '';
  691. $seq = '';
  692. }
  693. $seq = $chr;
  694. }
  695. // next byte of multibyte sequence
  696. else if ($seq !== '') {
  697. $seq .= $chr;
  698. }
  699. }
  700. if ($seq !== '') {
  701. $out .= preg_match($regexp, $seq) ? $seq : '';
  702. }
  703. return $out;
  704. }
  705. }