Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

rcube_charset.php 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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. * Windows codepages
  68. *
  69. * @var array
  70. */
  71. static public $windows_codepages = array(
  72. 37 => 'IBM037', // IBM EBCDIC US-Canada
  73. 437 => 'IBM437', // OEM United States
  74. 500 => 'IBM500', // IBM EBCDIC International
  75. 708 => 'ASMO-708', // Arabic (ASMO 708)
  76. 720 => 'DOS-720', // Arabic (Transparent ASMO); Arabic (DOS)
  77. 737 => 'IBM737', // OEM Greek (formerly 437G); Greek (DOS)
  78. 775 => 'IBM775', // OEM Baltic; Baltic (DOS)
  79. 850 => 'IBM850', // OEM Multilingual Latin 1; Western European (DOS)
  80. 852 => 'IBM852', // OEM Latin 2; Central European (DOS)
  81. 855 => 'IBM855', // OEM Cyrillic (primarily Russian)
  82. 857 => 'IBM857', // OEM Turkish; Turkish (DOS)
  83. 858 => 'IBM00858', // OEM Multilingual Latin 1 + Euro symbol
  84. 860 => 'IBM860', // OEM Portuguese; Portuguese (DOS)
  85. 861 => 'IBM861', // OEM Icelandic; Icelandic (DOS)
  86. 862 => 'DOS-862', // OEM Hebrew; Hebrew (DOS)
  87. 863 => 'IBM863', // OEM French Canadian; French Canadian (DOS)
  88. 864 => 'IBM864', // OEM Arabic; Arabic (864)
  89. 865 => 'IBM865', // OEM Nordic; Nordic (DOS)
  90. 866 => 'cp866', // OEM Russian; Cyrillic (DOS)
  91. 869 => 'IBM869', // OEM Modern Greek; Greek, Modern (DOS)
  92. 870 => 'IBM870', // IBM EBCDIC Multilingual/ROECE (Latin 2); IBM EBCDIC Multilingual Latin 2
  93. 874 => 'windows-874', // ANSI/OEM Thai (ISO 8859-11); Thai (Windows)
  94. 875 => 'cp875', // IBM EBCDIC Greek Modern
  95. 932 => 'shift_jis', // ANSI/OEM Japanese; Japanese (Shift-JIS)
  96. 936 => 'gb2312', // ANSI/OEM Simplified Chinese (PRC, Singapore); Chinese Simplified (GB2312)
  97. 950 => 'big5', // ANSI/OEM Traditional Chinese (Taiwan; Hong Kong SAR, PRC); Chinese Traditional (Big5)
  98. 1026 => 'IBM1026', // IBM EBCDIC Turkish (Latin 5)
  99. 1047 => 'IBM01047', // IBM EBCDIC Latin 1/Open System
  100. 1140 => 'IBM01140', // IBM EBCDIC US-Canada (037 + Euro symbol); IBM EBCDIC (US-Canada-Euro)
  101. 1141 => 'IBM01141', // IBM EBCDIC Germany (20273 + Euro symbol); IBM EBCDIC (Germany-Euro)
  102. 1142 => 'IBM01142', // IBM EBCDIC Denmark-Norway (20277 + Euro symbol); IBM EBCDIC (Denmark-Norway-Euro)
  103. 1143 => 'IBM01143', // IBM EBCDIC Finland-Sweden (20278 + Euro symbol); IBM EBCDIC (Finland-Sweden-Euro)
  104. 1144 => 'IBM01144', // IBM EBCDIC Italy (20280 + Euro symbol); IBM EBCDIC (Italy-Euro)
  105. 1145 => 'IBM01145', // IBM EBCDIC Latin America-Spain (20284 + Euro symbol); IBM EBCDIC (Spain-Euro)
  106. 1146 => 'IBM01146', // IBM EBCDIC United Kingdom (20285 + Euro symbol); IBM EBCDIC (UK-Euro)
  107. 1147 => 'IBM01147', // IBM EBCDIC France (20297 + Euro symbol); IBM EBCDIC (France-Euro)
  108. 1148 => 'IBM01148', // IBM EBCDIC International (500 + Euro symbol); IBM EBCDIC (International-Euro)
  109. 1149 => 'IBM01149', // IBM EBCDIC Icelandic (20871 + Euro symbol); IBM EBCDIC (Icelandic-Euro)
  110. 1200 => 'UTF-16', // Unicode UTF-16, little endian byte order (BMP of ISO 10646); available only to managed applications
  111. 1201 => 'UTF-16BE', // Unicode UTF-16, big endian byte order; available only to managed applications
  112. 1250 => 'windows-1250', // ANSI Central European; Central European (Windows)
  113. 1251 => 'windows-1251', // ANSI Cyrillic; Cyrillic (Windows)
  114. 1252 => 'windows-1252', // ANSI Latin 1; Western European (Windows)
  115. 1253 => 'windows-1253', // ANSI Greek; Greek (Windows)
  116. 1254 => 'windows-1254', // ANSI Turkish; Turkish (Windows)
  117. 1255 => 'windows-1255', // ANSI Hebrew; Hebrew (Windows)
  118. 1256 => 'windows-1256', // ANSI Arabic; Arabic (Windows)
  119. 1257 => 'windows-1257', // ANSI Baltic; Baltic (Windows)
  120. 1258 => 'windows-1258', // ANSI/OEM Vietnamese; Vietnamese (Windows)
  121. 10000 => 'macintosh', // MAC Roman; Western European (Mac)
  122. 12000 => 'UTF-32', // Unicode UTF-32, little endian byte order; available only to managed applications
  123. 12001 => 'UTF-32BE', // Unicode UTF-32, big endian byte order; available only to managed applications
  124. 20127 => 'US-ASCII', // US-ASCII (7-bit)
  125. 20273 => 'IBM273', // IBM EBCDIC Germany
  126. 20277 => 'IBM277', // IBM EBCDIC Denmark-Norway
  127. 20278 => 'IBM278', // IBM EBCDIC Finland-Sweden
  128. 20280 => 'IBM280', // IBM EBCDIC Italy
  129. 20284 => 'IBM284', // IBM EBCDIC Latin America-Spain
  130. 20285 => 'IBM285', // IBM EBCDIC United Kingdom
  131. 20290 => 'IBM290', // IBM EBCDIC Japanese Katakana Extended
  132. 20297 => 'IBM297', // IBM EBCDIC France
  133. 20420 => 'IBM420', // IBM EBCDIC Arabic
  134. 20423 => 'IBM423', // IBM EBCDIC Greek
  135. 20424 => 'IBM424', // IBM EBCDIC Hebrew
  136. 20838 => 'IBM-Thai', // IBM EBCDIC Thai
  137. 20866 => 'koi8-r', // Russian (KOI8-R); Cyrillic (KOI8-R)
  138. 20871 => 'IBM871', // IBM EBCDIC Icelandic
  139. 20880 => 'IBM880', // IBM EBCDIC Cyrillic Russian
  140. 20905 => 'IBM905', // IBM EBCDIC Turkish
  141. 20924 => 'IBM00924', // IBM EBCDIC Latin 1/Open System (1047 + Euro symbol)
  142. 20932 => 'EUC-JP', // Japanese (JIS 0208-1990 and 0212-1990)
  143. 20936 => 'cp20936', // Simplified Chinese (GB2312); Chinese Simplified (GB2312-80)
  144. 20949 => 'cp20949', // Korean Wansung
  145. 21025 => 'cp1025', // IBM EBCDIC Cyrillic Serbian-Bulgarian
  146. 21866 => 'koi8-u', // Ukrainian (KOI8-U); Cyrillic (KOI8-U)
  147. 28591 => 'iso-8859-1', // ISO 8859-1 Latin 1; Western European (ISO)
  148. 28592 => 'iso-8859-2', // ISO 8859-2 Central European; Central European (ISO)
  149. 28593 => 'iso-8859-3', // ISO 8859-3 Latin 3
  150. 28594 => 'iso-8859-4', // ISO 8859-4 Baltic
  151. 28595 => 'iso-8859-5', // ISO 8859-5 Cyrillic
  152. 28596 => 'iso-8859-6', // ISO 8859-6 Arabic
  153. 28597 => 'iso-8859-7', // ISO 8859-7 Greek
  154. 28598 => 'iso-8859-8', // ISO 8859-8 Hebrew; Hebrew (ISO-Visual)
  155. 28599 => 'iso-8859-9', // ISO 8859-9 Turkish
  156. 28603 => 'iso-8859-13', // ISO 8859-13 Estonian
  157. 28605 => 'iso-8859-15', // ISO 8859-15 Latin 9
  158. 38598 => 'iso-8859-8-i', // ISO 8859-8 Hebrew; Hebrew (ISO-Logical)
  159. 50220 => 'iso-2022-jp', // ISO 2022 Japanese with no halfwidth Katakana; Japanese (JIS)
  160. 50221 => 'csISO2022JP', // ISO 2022 Japanese with halfwidth Katakana; Japanese (JIS-Allow 1 byte Kana)
  161. 50222 => 'iso-2022-jp', // ISO 2022 Japanese JIS X 0201-1989; Japanese (JIS-Allow 1 byte Kana - SO/SI)
  162. 50225 => 'iso-2022-kr', // ISO 2022 Korean
  163. 51932 => 'EUC-JP', // EUC Japanese
  164. 51936 => 'EUC-CN', // EUC Simplified Chinese; Chinese Simplified (EUC)
  165. 51949 => 'EUC-KR', // EUC Korean
  166. 52936 => 'hz-gb-2312', // HZ-GB2312 Simplified Chinese; Chinese Simplified (HZ)
  167. 54936 => 'GB18030', // Windows XP and later: GB18030 Simplified Chinese (4 byte); Chinese Simplified (GB18030)
  168. 65000 => 'UTF-7',
  169. 65001 => 'UTF-8',
  170. );
  171. /**
  172. * Catch an error and throw an exception.
  173. *
  174. * @param int $errno Level of the error
  175. * @param string $errstr Error message
  176. */
  177. public static function error_handler($errno, $errstr)
  178. {
  179. throw new ErrorException($errstr, 0, $errno);
  180. }
  181. /**
  182. * Parse and validate charset name string (see #1485758).
  183. * Sometimes charset string is malformed, there are also charset aliases
  184. * but we need strict names for charset conversion (specially utf8 class)
  185. *
  186. * @param string $input Input charset name
  187. *
  188. * @return string The validated charset name
  189. */
  190. public static function parse_charset($input)
  191. {
  192. static $charsets = array();
  193. $charset = strtoupper($input);
  194. if (isset($charsets[$input])) {
  195. return $charsets[$input];
  196. }
  197. $charset = preg_replace(array(
  198. '/^[^0-9A-Z]+/', // e.g. _ISO-8859-JP$SIO
  199. '/\$.*$/', // e.g. _ISO-8859-JP$SIO
  200. '/UNICODE-1-1-*/', // RFC1641/1642
  201. '/^X-/', // X- prefix (e.g. X-ROMAN8 => ROMAN8)
  202. ), '', $charset);
  203. if ($charset == 'BINARY') {
  204. return $charsets[$input] = null;
  205. }
  206. // allow A-Z and 0-9 only
  207. $str = preg_replace('/[^A-Z0-9]/', '', $charset);
  208. if (isset(self::$aliases[$str])) {
  209. $result = self::$aliases[$str];
  210. }
  211. // UTF
  212. else if (preg_match('/U[A-Z][A-Z](7|8|16|32)(BE|LE)*/', $str, $m)) {
  213. $result = 'UTF-' . $m[1] . $m[2];
  214. }
  215. // ISO-8859
  216. else if (preg_match('/ISO8859([0-9]{0,2})/', $str, $m)) {
  217. $iso = 'ISO-8859-' . ($m[1] ?: 1);
  218. // some clients sends windows-1252 text as latin1,
  219. // it is safe to use windows-1252 for all latin1
  220. $result = $iso == 'ISO-8859-1' ? 'WINDOWS-1252' : $iso;
  221. }
  222. // handle broken charset names e.g. WINDOWS-1250HTTP-EQUIVCONTENT-TYPE
  223. else if (preg_match('/(WIN|WINDOWS)([0-9]+)/', $str, $m)) {
  224. $result = 'WINDOWS-' . $m[2];
  225. }
  226. // LATIN
  227. else if (preg_match('/LATIN(.*)/', $str, $m)) {
  228. $aliases = array('2' => 2, '3' => 3, '4' => 4, '5' => 9, '6' => 10,
  229. '7' => 13, '8' => 14, '9' => 15, '10' => 16,
  230. 'ARABIC' => 6, 'CYRILLIC' => 5, 'GREEK' => 7, 'GREEK1' => 7, 'HEBREW' => 8
  231. );
  232. // some clients sends windows-1252 text as latin1,
  233. // it is safe to use windows-1252 for all latin1
  234. if ($m[1] == 1) {
  235. $result = 'WINDOWS-1252';
  236. }
  237. // if iconv is not supported we need ISO labels, it's also safe for iconv
  238. else if (!empty($aliases[$m[1]])) {
  239. $result = 'ISO-8859-'.$aliases[$m[1]];
  240. }
  241. // iconv requires conversion of e.g. LATIN-1 to LATIN1
  242. else {
  243. $result = $str;
  244. }
  245. }
  246. else {
  247. $result = $charset;
  248. }
  249. $charsets[$input] = $result;
  250. return $result;
  251. }
  252. /**
  253. * Convert a string from one charset to another.
  254. * Uses mbstring and iconv functions if possible
  255. *
  256. * @param string $str Input string
  257. * @param string $from Suspected charset of the input string
  258. * @param string $to Target charset to convert to; defaults to RCUBE_CHARSET
  259. *
  260. * @return string Converted string
  261. */
  262. public static function convert($str, $from, $to = null)
  263. {
  264. static $iconv_options = null;
  265. static $mbstring_sc = null;
  266. $to = empty($to) ? RCUBE_CHARSET : strtoupper($to);
  267. $from = self::parse_charset($from);
  268. // It is a common case when UTF-16 charset is used with US-ASCII content (#1488654)
  269. // In that case we can just skip the conversion (use UTF-8)
  270. if ($from == 'UTF-16' && !preg_match('/[^\x00-\x7F]/', $str)) {
  271. $from = 'UTF-8';
  272. }
  273. if ($from == $to || empty($str) || empty($from)) {
  274. return $str;
  275. }
  276. if ($iconv_options === null) {
  277. if (function_exists('iconv')) {
  278. // ignore characters not available in output charset
  279. $iconv_options = '//IGNORE';
  280. if (iconv('', $iconv_options, '') === false) {
  281. // iconv implementation does not support options
  282. $iconv_options = '';
  283. }
  284. }
  285. else {
  286. $iconv_options = false;
  287. }
  288. }
  289. // convert charset using iconv module
  290. if ($iconv_options !== false && $from != 'UTF7-IMAP' && $to != 'UTF7-IMAP'
  291. && $from !== 'ISO-2022-JP'
  292. ) {
  293. // throw an exception if iconv reports an illegal character in input
  294. // it means that input string has been truncated
  295. set_error_handler(array('rcube_charset', 'error_handler'), E_NOTICE);
  296. try {
  297. $out = iconv($from, $to . $iconv_options, $str);
  298. }
  299. catch (ErrorException $e) {
  300. $out = false;
  301. }
  302. restore_error_handler();
  303. if ($out !== false) {
  304. return $out;
  305. }
  306. }
  307. if ($mbstring_sc === null) {
  308. $mbstring_sc = extension_loaded('mbstring') ? mb_substitute_character() : false;
  309. }
  310. // convert charset using mbstring module
  311. if ($mbstring_sc !== false) {
  312. $aliases = array(
  313. 'WINDOWS-1257' => 'ISO-8859-13',
  314. 'US-ASCII' => 'ASCII',
  315. 'ISO-2022-JP' => 'ISO-2022-JP-MS',
  316. );
  317. $mb_from = $aliases[$from] ?: $from;
  318. $mb_to = $aliases[$to] ?: $to;
  319. // Do the same as //IGNORE with iconv
  320. mb_substitute_character('none');
  321. // throw an exception if mbstring reports an illegal character in input
  322. // using mb_check_encoding() is much slower
  323. set_error_handler(array('rcube_charset', 'error_handler'), E_WARNING);
  324. try {
  325. $out = mb_convert_encoding($str, $mb_to, $mb_from);
  326. }
  327. catch (ErrorException $e) {
  328. $out = false;
  329. }
  330. restore_error_handler();
  331. mb_substitute_character($mbstring_sc);
  332. if ($out !== false) {
  333. return $out;
  334. }
  335. }
  336. // convert charset using bundled classes/functions
  337. if ($to == 'UTF-8') {
  338. if ($from == 'UTF7-IMAP') {
  339. if ($out = self::utf7imap_to_utf8($str)) {
  340. return $out;
  341. }
  342. }
  343. else if ($from == 'UTF-7') {
  344. if ($out = self::utf7_to_utf8($str)) {
  345. return $out;
  346. }
  347. }
  348. }
  349. // encode string for output
  350. if ($from == 'UTF-8') {
  351. // @TODO: we need a function for UTF-7 (RFC2152) conversion
  352. if ($to == 'UTF7-IMAP' || $to == 'UTF-7') {
  353. if ($out = self::utf8_to_utf7imap($str)) {
  354. return $out;
  355. }
  356. }
  357. }
  358. if (!isset($out)) {
  359. trigger_error("No suitable function found for '$from' to '$to' conversion");
  360. }
  361. // return original string
  362. return $str;
  363. }
  364. /**
  365. * Converts string from standard UTF-7 (RFC 2152) to UTF-8.
  366. *
  367. * @param string $str Input string (UTF-7)
  368. *
  369. * @return string Converted string (UTF-8)
  370. */
  371. public static function utf7_to_utf8($str)
  372. {
  373. $Index_64 = array(
  374. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  375. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  376. 0,0,0,0, 0,0,0,0, 0,0,0,1, 0,0,0,0,
  377. 1,1,1,1, 1,1,1,1, 1,1,0,0, 0,0,0,0,
  378. 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
  379. 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
  380. 0,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1,
  381. 1,1,1,1, 1,1,1,1, 1,1,1,0, 0,0,0,0,
  382. );
  383. $u7len = strlen($str);
  384. $str = strval($str);
  385. $res = '';
  386. for ($i=0; $u7len > 0; $i++, $u7len--) {
  387. $u7 = $str[$i];
  388. if ($u7 == '+') {
  389. $i++;
  390. $u7len--;
  391. $ch = '';
  392. for (; $u7len > 0; $i++, $u7len--) {
  393. $u7 = $str[$i];
  394. if (!$Index_64[ord($u7)]) {
  395. break;
  396. }
  397. $ch .= $u7;
  398. }
  399. if ($ch == '') {
  400. if ($u7 == '-') {
  401. $res .= '+';
  402. }
  403. continue;
  404. }
  405. $res .= self::utf16_to_utf8(base64_decode($ch));
  406. }
  407. else {
  408. $res .= $u7;
  409. }
  410. }
  411. return $res;
  412. }
  413. /**
  414. * Converts string from UTF-16 to UTF-8 (helper for utf-7 to utf-8 conversion)
  415. *
  416. * @param string $str Input string
  417. *
  418. * @return string The converted string
  419. */
  420. public static function utf16_to_utf8($str)
  421. {
  422. $len = strlen($str);
  423. $dec = '';
  424. for ($i = 0; $i < $len; $i += 2) {
  425. $c = ord($str[$i]) << 8 | ord($str[$i + 1]);
  426. if ($c >= 0x0001 && $c <= 0x007F) {
  427. $dec .= chr($c);
  428. }
  429. else if ($c > 0x07FF) {
  430. $dec .= chr(0xE0 | (($c >> 12) & 0x0F));
  431. $dec .= chr(0x80 | (($c >> 6) & 0x3F));
  432. $dec .= chr(0x80 | (($c >> 0) & 0x3F));
  433. }
  434. else {
  435. $dec .= chr(0xC0 | (($c >> 6) & 0x1F));
  436. $dec .= chr(0x80 | (($c >> 0) & 0x3F));
  437. }
  438. }
  439. return $dec;
  440. }
  441. /**
  442. * Convert the data ($str) from RFC 2060's UTF-7 to UTF-8.
  443. * If input data is invalid, return the original input string.
  444. * RFC 2060 obviously intends the encoding to be unique (see
  445. * point 5 in section 5.1.3), so we reject any non-canonical
  446. * form, such as &ACY- (instead of &-) or &AMA-&AMA- (instead
  447. * of &AMAAwA-).
  448. *
  449. * Translated from C to PHP by Thomas Bruederli <roundcube@gmail.com>
  450. *
  451. * @param string $str Input string (UTF7-IMAP)
  452. *
  453. * @return string Output string (UTF-8)
  454. */
  455. public static function utf7imap_to_utf8($str)
  456. {
  457. $Index_64 = array(
  458. -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
  459. -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
  460. -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, 63,-1,-1,-1,
  461. 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1,
  462. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
  463. 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
  464. -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
  465. 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
  466. );
  467. $u7len = strlen($str);
  468. $str = strval($str);
  469. $p = '';
  470. $err = '';
  471. for ($i=0; $u7len > 0; $i++, $u7len--) {
  472. $u7 = $str[$i];
  473. if ($u7 == '&') {
  474. $i++;
  475. $u7len--;
  476. $u7 = $str[$i];
  477. if ($u7len && $u7 == '-') {
  478. $p .= '&';
  479. continue;
  480. }
  481. $ch = 0;
  482. $k = 10;
  483. for (; $u7len > 0; $i++, $u7len--) {
  484. $u7 = $str[$i];
  485. if ((ord($u7) & 0x80) || ($b = $Index_64[ord($u7)]) == -1) {
  486. break;
  487. }
  488. if ($k > 0) {
  489. $ch |= $b << $k;
  490. $k -= 6;
  491. }
  492. else {
  493. $ch |= $b >> (-$k);
  494. if ($ch < 0x80) {
  495. // Printable US-ASCII
  496. if (0x20 <= $ch && $ch < 0x7f) {
  497. return $err;
  498. }
  499. $p .= chr($ch);
  500. }
  501. else if ($ch < 0x800) {
  502. $p .= chr(0xc0 | ($ch >> 6));
  503. $p .= chr(0x80 | ($ch & 0x3f));
  504. }
  505. else {
  506. $p .= chr(0xe0 | ($ch >> 12));
  507. $p .= chr(0x80 | (($ch >> 6) & 0x3f));
  508. $p .= chr(0x80 | ($ch & 0x3f));
  509. }
  510. $ch = ($b << (16 + $k)) & 0xffff;
  511. $k += 10;
  512. }
  513. }
  514. // Non-zero or too many extra bits
  515. if ($ch || $k < 6) {
  516. return $err;
  517. }
  518. // BASE64 not properly terminated
  519. if (!$u7len || $u7 != '-') {
  520. return $err;
  521. }
  522. // Adjacent BASE64 sections
  523. if ($u7len > 2 && $str[$i+1] == '&' && $str[$i+2] != '-') {
  524. return $err;
  525. }
  526. }
  527. // Not printable US-ASCII
  528. else if (ord($u7) < 0x20 || ord($u7) >= 0x7f) {
  529. return $err;
  530. }
  531. else {
  532. $p .= $u7;
  533. }
  534. }
  535. return $p;
  536. }
  537. /**
  538. * Convert the data ($str) from UTF-8 to RFC 2060's UTF-7.
  539. * Unicode characters above U+FFFF are replaced by U+FFFE.
  540. * If input data is invalid, return an empty string.
  541. *
  542. * Translated from C to PHP by Thomas Bruederli <roundcube@gmail.com>
  543. *
  544. * @param string $str Input string (UTF-8)
  545. *
  546. * @return string Output string (UTF7-IMAP)
  547. */
  548. public static function utf8_to_utf7imap($str)
  549. {
  550. $B64Chars = array(
  551. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  552. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
  553. 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  554. 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
  555. '8', '9', '+', ','
  556. );
  557. $u8len = strlen($str);
  558. $base64 = 0;
  559. $i = 0;
  560. $p = '';
  561. $err = '';
  562. while ($u8len) {
  563. $u8 = $str[$i];
  564. $c = ord($u8);
  565. if ($c < 0x80) {
  566. $ch = $c;
  567. $n = 0;
  568. }
  569. else if ($c < 0xc2) {
  570. return $err;
  571. }
  572. else if ($c < 0xe0) {
  573. $ch = $c & 0x1f;
  574. $n = 1;
  575. }
  576. else if ($c < 0xf0) {
  577. $ch = $c & 0x0f;
  578. $n = 2;
  579. }
  580. else if ($c < 0xf8) {
  581. $ch = $c & 0x07;
  582. $n = 3;
  583. }
  584. else if ($c < 0xfc) {
  585. $ch = $c & 0x03;
  586. $n = 4;
  587. }
  588. else if ($c < 0xfe) {
  589. $ch = $c & 0x01;
  590. $n = 5;
  591. }
  592. else {
  593. return $err;
  594. }
  595. $i++;
  596. $u8len--;
  597. if ($n > $u8len) {
  598. return $err;
  599. }
  600. for ($j=0; $j < $n; $j++) {
  601. $o = ord($str[$i+$j]);
  602. if (($o & 0xc0) != 0x80) {
  603. return $err;
  604. }
  605. $ch = ($ch << 6) | ($o & 0x3f);
  606. }
  607. if ($n > 1 && !($ch >> ($n * 5 + 1))) {
  608. return $err;
  609. }
  610. $i += $n;
  611. $u8len -= $n;
  612. if ($ch < 0x20 || $ch >= 0x7f) {
  613. if (!$base64) {
  614. $p .= '&';
  615. $base64 = 1;
  616. $b = 0;
  617. $k = 10;
  618. }
  619. if ($ch & ~0xffff) {
  620. $ch = 0xfffe;
  621. }
  622. $p .= $B64Chars[($b | $ch >> $k)];
  623. $k -= 6;
  624. for (; $k >= 0; $k -= 6) {
  625. $p .= $B64Chars[(($ch >> $k) & 0x3f)];
  626. }
  627. $b = ($ch << (-$k)) & 0x3f;
  628. $k += 16;
  629. }
  630. else {
  631. if ($base64) {
  632. if ($k > 10) {
  633. $p .= $B64Chars[$b];
  634. }
  635. $p .= '-';
  636. $base64 = 0;
  637. }
  638. $p .= chr($ch);
  639. if (chr($ch) == '&') {
  640. $p .= '-';
  641. }
  642. }
  643. }
  644. if ($base64) {
  645. if ($k > 10) {
  646. $p .= $B64Chars[$b];
  647. }
  648. $p .= '-';
  649. }
  650. return $p;
  651. }
  652. /**
  653. * A method to guess character set of a string.
  654. *
  655. * @param string $string String
  656. * @param string $failover Default result for failover
  657. * @param string $language User language
  658. *
  659. * @return string Charset name
  660. */
  661. public static function detect($string, $failover = null, $language = null)
  662. {
  663. if (substr($string, 0, 4) == "\0\0\xFE\xFF") return 'UTF-32BE'; // Big Endian
  664. if (substr($string, 0, 4) == "\xFF\xFE\0\0") return 'UTF-32LE'; // Little Endian
  665. if (substr($string, 0, 2) == "\xFE\xFF") return 'UTF-16BE'; // Big Endian
  666. if (substr($string, 0, 2) == "\xFF\xFE") return 'UTF-16LE'; // Little Endian
  667. if (substr($string, 0, 3) == "\xEF\xBB\xBF") return 'UTF-8';
  668. // heuristics
  669. if ($string[0] == "\0" && $string[1] == "\0" && $string[2] == "\0" && $string[3] != "\0") return 'UTF-32BE';
  670. if ($string[0] != "\0" && $string[1] == "\0" && $string[2] == "\0" && $string[3] == "\0") return 'UTF-32LE';
  671. if ($string[0] == "\0" && $string[1] != "\0" && $string[2] == "\0" && $string[3] != "\0") return 'UTF-16BE';
  672. if ($string[0] != "\0" && $string[1] == "\0" && $string[2] != "\0" && $string[3] == "\0") return 'UTF-16LE';
  673. if (empty($language)) {
  674. $rcube = rcube::get_instance();
  675. $language = $rcube->get_user_language();
  676. }
  677. // Prioritize charsets according to current language (#1485669)
  678. switch ($language) {
  679. case 'ja_JP':
  680. $prio = array('ISO-2022-JP', 'JIS', 'UTF-8', 'EUC-JP', 'eucJP-win', 'SJIS', 'SJIS-win');
  681. break;
  682. case 'zh_CN':
  683. case 'zh_TW':
  684. $prio = array('UTF-8', 'BIG-5', 'GB2312', 'EUC-TW');
  685. break;
  686. case 'ko_KR':
  687. $prio = array('UTF-8', 'EUC-KR', 'ISO-2022-KR');
  688. break;
  689. case 'ru_RU':
  690. $prio = array('UTF-8', 'WINDOWS-1251', 'KOI8-R');
  691. break;
  692. case 'tr_TR':
  693. $prio = array('UTF-8', 'ISO-8859-9', 'WINDOWS-1254');
  694. break;
  695. }
  696. // mb_detect_encoding() is not reliable for some charsets (#1490135)
  697. // use mb_check_encoding() to make charset priority lists really working
  698. if ($prio && function_exists('mb_check_encoding')) {
  699. foreach ($prio as $encoding) {
  700. if (mb_check_encoding($string, $encoding)) {
  701. return $encoding;
  702. }
  703. }
  704. }
  705. if (function_exists('mb_detect_encoding')) {
  706. if (!$prio) {
  707. $prio = array('UTF-8', 'SJIS', 'GB2312',
  708. 'ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
  709. 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8', 'ISO-8859-9',
  710. 'ISO-8859-10', 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'ISO-8859-16',
  711. 'WINDOWS-1252', 'WINDOWS-1251', 'EUC-JP', 'EUC-TW', 'KOI8-R', 'BIG-5',
  712. 'ISO-2022-KR', 'ISO-2022-JP',
  713. );
  714. }
  715. $encodings = array_unique(array_merge($prio, mb_list_encodings()));
  716. if ($encoding = mb_detect_encoding($string, $encodings)) {
  717. return $encoding;
  718. }
  719. }
  720. // No match, check for UTF-8
  721. // from http://w3.org/International/questions/qa-forms-utf-8.html
  722. if (preg_match('/\A(
  723. [\x09\x0A\x0D\x20-\x7E]
  724. | [\xC2-\xDF][\x80-\xBF]
  725. | \xE0[\xA0-\xBF][\x80-\xBF]
  726. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}
  727. | \xED[\x80-\x9F][\x80-\xBF]
  728. | \xF0[\x90-\xBF][\x80-\xBF]{2}
  729. | [\xF1-\xF3][\x80-\xBF]{3}
  730. | \xF4[\x80-\x8F][\x80-\xBF]{2}
  731. )*\z/xs', substr($string, 0, 2048))
  732. ) {
  733. return 'UTF-8';
  734. }
  735. return $failover;
  736. }
  737. /**
  738. * Removes non-unicode characters from input.
  739. *
  740. * @param mixed $input String or array.
  741. *
  742. * @return mixed String or array
  743. */
  744. public static function clean($input)
  745. {
  746. // handle input of type array
  747. if (is_array($input)) {
  748. foreach ($input as $idx => $val) {
  749. $input[$idx] = self::clean($val);
  750. }
  751. return $input;
  752. }
  753. if (!is_string($input) || $input == '') {
  754. return $input;
  755. }
  756. // iconv/mbstring are much faster (especially with long strings)
  757. if (function_exists('mb_convert_encoding')) {
  758. $msch = mb_substitute_character();
  759. mb_substitute_character('none');
  760. $res = mb_convert_encoding($input, 'UTF-8', 'UTF-8');
  761. mb_substitute_character($msch);
  762. if ($res !== false) {
  763. return $res;
  764. }
  765. }
  766. if (function_exists('iconv')) {
  767. if (($res = @iconv('UTF-8', 'UTF-8//IGNORE', $input)) !== false) {
  768. return $res;
  769. }
  770. }
  771. $seq = '';
  772. $out = '';
  773. $regexp = '/^('.
  774. // '[\x00-\x7F]'. // UTF8-1
  775. '|[\xC2-\xDF][\x80-\xBF]'. // UTF8-2
  776. '|\xE0[\xA0-\xBF][\x80-\xBF]'. // UTF8-3
  777. '|[\xE1-\xEC][\x80-\xBF][\x80-\xBF]'. // UTF8-3
  778. '|\xED[\x80-\x9F][\x80-\xBF]'. // UTF8-3
  779. '|[\xEE-\xEF][\x80-\xBF][\x80-\xBF]'. // UTF8-3
  780. '|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]'. // UTF8-4
  781. '|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]'.// UTF8-4
  782. '|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF]'. // UTF8-4
  783. ')$/';
  784. for ($i = 0, $len = strlen($input); $i < $len; $i++) {
  785. $chr = $input[$i];
  786. $ord = ord($chr);
  787. // 1-byte character
  788. if ($ord <= 0x7F) {
  789. if ($seq !== '') {
  790. $out .= preg_match($regexp, $seq) ? $seq : '';
  791. $seq = '';
  792. }
  793. $out .= $chr;
  794. }
  795. // first byte of multibyte sequence
  796. else if ($ord >= 0xC0) {
  797. if ($seq !== '') {
  798. $out .= preg_match($regexp, $seq) ? $seq : '';
  799. $seq = '';
  800. }
  801. $seq = $chr;
  802. }
  803. // next byte of multibyte sequence
  804. else if ($seq !== '') {
  805. $seq .= $chr;
  806. }
  807. }
  808. if ($seq !== '') {
  809. $out .= preg_match($regexp, $seq) ? $seq : '';
  810. }
  811. return $out;
  812. }
  813. }