Simplify mbstring code path in rcube_charset::convert()

pull/5754/head
Aleksander Machniak 8 years ago
parent af4ddddb21
commit 0c8419e31c

@ -171,8 +171,7 @@ class rcube_charset
public static function convert($str, $from, $to = null) public static function convert($str, $from, $to = null)
{ {
static $iconv_options = null; static $iconv_options = null;
static $mbstring_list = null; static $mbstring_sc = null;
static $mbstring_sch = null;
$to = empty($to) ? RCUBE_CHARSET : strtoupper($to); $to = empty($to) ? RCUBE_CHARSET : strtoupper($to);
$from = self::parse_charset($from); $from = self::parse_charset($from);
@ -219,49 +218,38 @@ class rcube_charset
} }
} }
if ($mbstring_list === null) { if ($mbstring_sc === null) {
if (extension_loaded('mbstring')) { $mbstring_sc = extension_loaded('mbstring') ? mb_substitute_character() : false;
$mbstring_sch = mb_substitute_character();
$mbstring_list = mb_list_encodings();
$mbstring_list = array_map('strtoupper', $mbstring_list);
}
else {
$mbstring_list = false;
}
} }
// convert charset using mbstring module // convert charset using mbstring module
if ($mbstring_list !== false) { if ($mbstring_sc !== false) {
$aliases['WINDOWS-1257'] = 'ISO-8859-13'; $aliases = array(
// it happens that mbstring supports ASCII but not US-ASCII 'WINDOWS-1257' => 'ISO-8859-13',
if (($from == 'US-ASCII' || $to == 'US-ASCII') && !in_array('US-ASCII', $mbstring_list)) { 'US-ASCII' => 'ASCII',
$aliases['US-ASCII'] = 'ASCII'; );
}
$mb_from = $aliases[$from] ?: $from; $mb_from = $aliases[$from] ?: $from;
$mb_to = $aliases[$to] ?: $to; $mb_to = $aliases[$to] ?: $to;
// return if encoding found, string matches encoding and convert succeeded // Do the same as //IGNORE with iconv
if (in_array($mb_from, $mbstring_list) && in_array($mb_to, $mbstring_list)) { mb_substitute_character('none');
// Do the same as //IGNORE with iconv
mb_substitute_character('none');
// throw an exception if mbstring reports an illegal character in input // throw an exception if mbstring reports an illegal character in input
// using mb_check_encoding() is much slower // using mb_check_encoding() is much slower
set_error_handler(array('rcube_charset', 'error_handler'), E_WARNING); set_error_handler(array('rcube_charset', 'error_handler'), E_WARNING);
try { try {
$out = mb_convert_encoding($str, $mb_to, $mb_from); $out = mb_convert_encoding($str, $mb_to, $mb_from);
} }
catch (ErrorException $e) { catch (ErrorException $e) {
$out = false; $out = false;
} }
restore_error_handler(); restore_error_handler();
mb_substitute_character($mbstring_sch); mb_substitute_character($mbstring_sc);
if ($out !== false) { if ($out !== false) {
return $out; return $out;
}
} }
} }

Loading…
Cancel
Save