3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
6 * Copyright (c) 2001-2017 *
7 * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
9 * Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
10 * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
11 \***************************************************************************/
14 * Gestion des charsets et des conversions
16 * Ce fichier contient les fonctions relatives à la gestion de charsets,
17 * à la conversion de textes dans différents charsets et
18 * propose des fonctions émulant la librairie mb si elle est absente
20 * @package SPIP\Core\Texte\Charsets
24 if (!defined('_ECRIRE_INC_VERSION')) {
28 // se faciliter la lecture du charset
29 include_spip('inc/config');
32 * Charge en mémoire la liste des caractères d'un charset
34 * Charsets supportés en natif : voir les tables dans ecrire/charsets/
35 * Les autres charsets sont supportés via mbstring()
37 * @param string $charset
39 * Par défaut (AUTO), utilise le charset du site
42 * - false si le charset n'est pas décrit dans le répertoire charsets/
44 function load_charset($charset = 'AUTO') {
45 if ($charset == 'AUTO') {
46 $charset = $GLOBALS['meta']['charset'];
48 $charset = trim(strtolower($charset));
49 if (isset($GLOBALS['CHARSET'][$charset])) {
53 if ($charset == 'utf-8') {
54 $GLOBALS['CHARSET'][$charset] = array();
61 $charset = 'iso-8859-1';
63 if ($charset == 'windows-1250') {
66 if ($charset == 'windows-1251') {
69 if ($charset == 'windows-1256') {
76 if (find_in_path($charset . '.php', 'charsets/', true)) {
79 spip_log("Erreur: pas de fichier de conversion 'charsets/$charset'");
80 $GLOBALS['CHARSET'][$charset] = array();
88 * Vérifier qu'on peut utiliser mb_string
91 * true si toutes les fonctions mb nécessaires sont présentes
93 function init_mb_string() {
96 // verifier que tout est present (fonctions mb_string pour php >= 4.0.6)
97 // et que le charset interne est connu de mb_string
99 if (function_exists('mb_internal_encoding')
100 and function_exists('mb_detect_order')
101 and function_exists('mb_substr')
102 and function_exists('mb_strlen')
103 and function_exists('mb_strtolower')
104 and function_exists('mb_strtoupper')
105 and function_exists('mb_encode_mimeheader')
106 and function_exists('mb_encode_numericentity')
107 and function_exists('mb_decode_numericentity')
108 and mb_detect_order(lire_config('charset', _DEFAULT_CHARSET
))
110 mb_internal_encoding('utf-8');
121 * Test le fonctionnement correct d'iconv
123 * Celui-ci coupe sur certaines versions la chaine
124 * quand un caractère n'appartient pas au charset
126 * @link http://php.net/manual/fr/function.iconv.php
129 * true si iconv fonctionne correctement
131 function test_iconv() {
135 if (!function_exists('iconv')) {
138 if (utf_32_to_unicode(@iconv
('utf-8', 'utf-32', 'chaine de test')) == 'chaine de test') {
146 return ($iconv_ok == 1);
151 * Test de fonctionnement du support UTF-8 dans PCRE
153 * Contournement bug Debian Woody
156 * true si PCRE supporte l'UTF-8 correctement
158 function test_pcre_unicode() {
162 $s = " " . chr(195) . chr(169) . "t" . chr(195) . chr(169) . " ";
163 if (preg_match(',\W...\W,u', $s)) {
170 return $pcre_ok == 1;
174 * Renvoie une plage de caractères alphanumeriques unicodes (incomplet...)
176 * Retourne pour une expression rationnelle une plage
177 * de caractères alphanumériques à utiliser entre crochets [$plage]
181 * Servait à inc/ortho passé dans le grenier
183 * Plage de caractères
185 function pcre_lettres_unicode() {
186 static $plage_unicode;
188 if (!$plage_unicode) {
189 if (test_pcre_unicode()) {
190 // cf. http://www.unicode.org/charts/
191 $plage_unicode = '\w' // iso-latin
192 . '\x{100}-\x{24f}' // europeen etendu
193 . '\x{300}-\x{1cff}' // des tas de trucs
196 // fallback a trois sous
197 $plage_unicode = '\w';
201 return $plage_unicode;
206 * Renvoie une plage de caractères de ponctuation unicode de 0x2000 a 0x206F
208 * Retourne pour une expression rationnelle une plage
209 * de caractères de ponctuation à utiliser entre crochets [$plage]
210 * (i.e. de 226-128-128 a 226-129-176)
214 * Servait à inc/ortho passé dans le grenier
216 * Plage de caractères
218 function plage_punct_unicode() {
219 return '\xE2(\x80[\x80-\xBF]|\x81[\x80-\xAF])';
223 * Corriger des caractères non-conformes : 128-159
225 * Cf. charsets/iso-8859-1.php (qu'on recopie ici pour aller plus vite)
226 * On peut passer un charset cible en parametre pour accelerer le passage iso-8859-1 -> autre charset
228 * @param string|array $texte
229 * Le texte à corriger
230 * @param string $charset
231 * Charset d'origine du texte
232 * Par défaut (AUTO) utilise le charset du site
233 * @param string $charset_cible
234 * Charset de destination (unicode par défaut)
235 * @return string|array
238 function corriger_caracteres_windows($texte, $charset = 'AUTO', $charset_cible = 'unicode') {
241 if (is_array($texte)) {
242 return array_map('corriger_caracteres_windows', $texte);
245 if ($charset == 'AUTO') {
246 $charset = lire_config('charset', _DEFAULT_CHARSET
);
248 if ($charset == 'utf-8') {
250 if (strpos($texte, $p) == false) {
254 if ($charset == 'iso-8859-1') {
261 if (!isset($trans[$charset][$charset_cible])) {
262 $trans[$charset][$charset_cible] = array(
263 $p . chr(128) => "€",
264 $p . chr(129) => ' ', # pas affecte
265 $p . chr(130) => "‚",
266 $p . chr(131) => "ƒ",
267 $p . chr(132) => "„",
268 $p . chr(133) => "…",
269 $p . chr(134) => "†",
270 $p . chr(135) => "‡",
271 $p . chr(136) => "ˆ",
272 $p . chr(137) => "‰",
273 $p . chr(138) => "Š",
274 $p . chr(139) => "‹",
275 $p . chr(140) => "Œ",
276 $p . chr(141) => ' ', # pas affecte
277 $p . chr(142) => "Ž",
278 $p . chr(143) => ' ', # pas affecte
279 $p . chr(144) => ' ', # pas affecte
280 $p . chr(145) => "‘",
281 $p . chr(146) => "’",
282 $p . chr(147) => "“",
283 $p . chr(148) => "”",
284 $p . chr(149) => "•",
285 $p . chr(150) => "–",
286 $p . chr(151) => "—",
287 $p . chr(152) => "˜",
288 $p . chr(153) => "™",
289 $p . chr(154) => "š",
290 $p . chr(155) => "›",
291 $p . chr(156) => "œ",
292 $p . chr(157) => ' ', # pas affecte
293 $p . chr(158) => "ž",
294 $p . chr(159) => "Ÿ",
296 if ($charset_cible != 'unicode') {
297 foreach ($trans[$charset][$charset_cible] as $k => $c) {
298 $trans[$charset][$charset_cible][$k] = unicode2charset($c, $charset_cible);
303 return @str_replace
(array_keys($trans[$charset][$charset_cible]),
304 array_values($trans[$charset][$charset_cible]), $texte);
309 * Transforme les entités HTML en unicode
311 * Transforme les é en {
313 * @param string $texte
315 * @param bool $secure
316 * true pour *ne pas convertir* les caracteres malins < & etc.
320 function html2unicode($texte, $secure = false) {
321 if (strpos($texte, '&') === false) {
324 static $trans = array();
326 load_charset('html');
327 foreach ($GLOBALS['CHARSET']['html'] as $key => $val) {
328 $trans["&$key;"] = $val;
333 return str_replace(array_keys($trans), array_values($trans), $texte);
335 return str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'),
336 str_replace(array_keys($trans), array_values($trans), $texte)
343 * Transforme les entités mathématiques (MathML) en unicode
345 * Transforme ∠ en ∠ ainsi que toutes autres entités mathématiques
347 * @param string $texte
352 function mathml2unicode($texte) {
355 load_charset('mathml');
357 foreach ($GLOBALS['CHARSET']['mathml'] as $key => $val) {
358 $trans["&$key;"] = $val;
362 return str_replace(array_keys($trans), array_values($trans), $texte);
367 * Transforme une chaine en entites unicode 
369 * Utilise la librairie mb si elle est présente.
372 * Note: l'argument $forcer est obsolete : il visait a ne pas
373 * convertir les accents iso-8859-1
375 * @param string $texte
377 * @param string $charset
378 * Charset actuel du texte
379 * Par défaut (AUTO), le charset est celui du site.
381 * Texte converti en unicode
383 function charset2unicode($texte, $charset = 'AUTO' /* $forcer: obsolete*/) {
386 if ($charset == 'AUTO') {
387 $charset = lire_config('charset', _DEFAULT_CHARSET
);
390 if ($charset == '') {
391 $charset = 'iso-8859-1';
393 $charset = strtolower($charset);
398 return utf_8_to_unicode($texte);
401 $texte = corriger_caracteres_windows($texte, 'iso-8859-1');
402 // pas de break; ici, on suit sur default:
405 // mbstring presente ?
406 if (init_mb_string()) {
407 if ($order = mb_detect_order() # mb_string connait-il $charset?
408 and mb_detect_order($charset)
410 $s = mb_convert_encoding($texte, 'utf-8', $charset);
411 if ($s && $s != $texte) {
412 return utf_8_to_unicode($s);
415 mb_detect_order($order); # remettre comme precedemment
418 // Sinon, peut-etre connaissons-nous ce charset ?
419 if (!isset($trans[$charset])) {
420 if ($cset = load_charset($charset)
421 and is_array($GLOBALS['CHARSET'][$cset])
423 foreach ($GLOBALS['CHARSET'][$cset] as $key => $val) {
424 $trans[$charset][chr($key)] = '&#' . $val . ';';
428 if (count($trans[$charset])) {
429 return str_replace(array_keys($trans[$charset]), array_values($trans[$charset]), $texte);
432 // Sinon demander a iconv (malgre le fait qu'il coupe quand un
433 // caractere n'appartient pas au charset, mais c'est un probleme
434 // surtout en utf-8, gere ci-dessus)
436 $s = iconv($charset, 'utf-32le', $texte);
438 return utf_32_to_unicode($s);
442 // Au pire ne rien faire
443 spip_log("erreur charset '$charset' non supporte");
451 * Transforme les entites unicode  dans le charset specifie
453 * Attention on ne transforme pas les entites < € car si elles
454 * ont ete encodees ainsi c'est a dessein
456 * @param string $texte
457 * Texte unicode à transformer
458 * @param string $charset
459 * Charset à appliquer au texte
460 * Par défaut (AUTO), le charset sera celui du site.
462 * Texte transformé dans le charset souhaité
464 function unicode2charset($texte, $charset = 'AUTO') {
465 static $CHARSET_REVERSE;
466 static $trans = array();
468 if ($charset == 'AUTO') {
469 $charset = lire_config('charset', _DEFAULT_CHARSET
);
474 return unicode_to_utf_8($texte);
478 $charset = load_charset($charset);
480 if (!is_array($CHARSET_REVERSE[$charset])) {
481 $CHARSET_REVERSE[$charset] = array_flip($GLOBALS['CHARSET'][$charset]);
484 if (!isset($trans[$charset])) {
485 $trans[$charset] = array();
486 $t = &$trans[$charset];
487 for ($e = 128; $e < 255; $e++
) {
489 if ($s = isset($CHARSET_REVERSE[$charset][$e])) {
490 $s = $CHARSET_REVERSE[$charset][$e];
491 $t['&#' . $e . ';'] = $t['�' . $e . ';'] = $t['�' . $e . ';'] = chr($s);
492 $t['&#x' . $h . ';'] = $t['�' . $h . ';'] = $t['�' . $h . ';'] = chr($s);
494 $t['&#' . $e . ';'] = $t['�' . $e . ';'] = $t['�' . $e . ';'] = chr($e);
495 $t['&#x' . $h . ';'] = $t['�' . $h . ';'] = $t['�' . $h . ';'] = chr($e);
499 $texte = str_replace(array_keys($trans[$charset]), array_values($trans[$charset]), $texte);
507 * Importer un texte depuis un charset externe vers le charset du site
509 * Les caractères non resolus sont transformés en `{`;
511 * @param string $texte
512 * Texte unicode à importer
513 * @param string $charset
514 * Charset d'origine du texte
515 * Par défaut (AUTO), le charset d'origine est celui du site.
517 * Texte transformé dans le charset site
519 function importer_charset($texte, $charset = 'AUTO') {
520 static $trans = array();
521 // on traite le cas le plus frequent iso-8859-1 vers utf directement pour aller plus vite !
522 if (($charset == 'iso-8859-1') && ($GLOBALS['meta']['charset'] == 'utf-8')) {
523 $texte = corriger_caracteres_windows($texte, 'iso-8859-1', $GLOBALS['meta']['charset']);
524 if (init_mb_string()) {
525 if ($order = mb_detect_order() # mb_string connait-il $charset?
526 and mb_detect_order($charset)
528 $s = mb_convert_encoding($texte, 'utf-8', $charset);
530 mb_detect_order($order); # remettre comme precedemment
533 // Sinon, peut-etre connaissons-nous ce charset ?
534 if (!isset($trans[$charset])) {
535 if ($cset = load_charset($charset)
536 and is_array($GLOBALS['CHARSET'][$cset])
538 foreach ($GLOBALS['CHARSET'][$cset] as $key => $val) {
539 $trans[$charset][chr($key)] = unicode2charset('&#' . $val . ';');
543 if (count($trans[$charset])) {
544 return str_replace(array_keys($trans[$charset]), array_values($trans[$charset]), $texte);
550 return unicode2charset(charset2unicode($texte, $charset));
555 * Transforme un texte UTF-8 en unicode
557 * Utilise la librairie mb si présente
559 * @param string $source
560 * Texte UTF-8 à transformer
562 * Texte transformé en unicode
564 function utf_8_to_unicode($source) {
566 // mb_string : methode rapide
567 if (init_mb_string()) {
568 $convmap = array(0x7F, 0xFFFFFF, 0x0, 0xFFFFFF);
570 return mb_encode_numericentity($source, $convmap, 'UTF-8');
573 // Sinon methode pas a pas
577 // Cf. php.net, par Ronen. Adapte pour compatibilite < php4
578 if (!is_array($decrement)) {
579 // array used to figure what number to decrement from character order value
580 // according to number of characters used to map unicode to ascii by utf-8
585 // the number of bits to shift each charNum by
599 $len = strlen($source);
601 while ($pos < $len) {
604 $asciiPos = ord(substr($source, $pos, 1));
605 if (($asciiPos >= 240) && ($asciiPos <= 255)) {
606 // 4 chars representing one unicode character
607 $thisLetter = substr($source, $pos, 4);
610 if (($asciiPos >= 224) && ($asciiPos <= 239)) {
611 // 3 chars representing one unicode character
612 $thisLetter = substr($source, $pos, 3);
615 if (($asciiPos >= 192) && ($asciiPos <= 223)) {
616 // 2 chars representing one unicode character
617 $thisLetter = substr($source, $pos, 2);
620 // 1 char (lower ascii)
621 $thisLetter = substr($source, $pos, 1);
630 $encodedString .= $char;
631 } else { // process the string representing the letter to a unicode entity
632 $thisLen = strlen($thisLetter);
635 while ($thisPos < $thisLen) {
636 $thisCharOrd = ord(substr($thisLetter, $thisPos, 1));
638 $charNum = intval($thisCharOrd - $decrement[$thisLen]);
639 $decimalCode +
= ($charNum << $shift[$thisLen][$thisPos]);
641 $charNum = intval($thisCharOrd - 128);
642 $decimalCode +
= ($charNum << $shift[$thisLen][$thisPos]);
646 $encodedLetter = "&#" . preg_replace('/^0+/', '', $decimalCode) . ';';
647 $encodedString .= $encodedLetter;
651 return $encodedString;
655 * Transforme un texte UTF-32 en unicode
657 * UTF-32 ne sert plus que si on passe par iconv, c'est-a-dire quand
658 * mb_string est absente ou ne connait pas notre charset.
660 * Mais on l'optimise quand meme par mb_string
661 * => tout ca sera osolete quand on sera surs d'avoir mb_string
663 * @param string $source
664 * Texte UTF-8 à transformer
666 * Texte transformé en unicode
668 function utf_32_to_unicode($source) {
670 // mb_string : methode rapide
671 if (init_mb_string()) {
672 $convmap = array(0x7F, 0xFFFFFF, 0x0, 0xFFFFFF);
673 $source = mb_encode_numericentity($source, $convmap, 'UTF-32LE');
675 return str_replace(chr(0), '', $source);
678 // Sinon methode lente
681 $words = unpack("V*", substr($source, 0, 1024));
682 $source = substr($source, 1024);
683 foreach ($words as $word) {
685 $texte .= chr($word);
686 } // ignorer le BOM - http://www.unicode.org/faq/utf_bom.html
688 if ($word != 65279) {
689 $texte .= '&#' . $word . ';';
701 * Transforme un numéro unicode en caractère utf-8
703 * Ce bloc provient de php.net
708 * Numéro de l'entité unicode
710 * Caractère utf8 si trouvé, '' sinon
712 function caractere_utf_8($num) {
718 return chr(($num >> 6) +
192) . chr(($num & 63) +
128);
721 return chr(($num >> 12) +
224) . chr((($num >> 6) & 63) +
128) . chr(($num & 63) +
128);
723 if ($num < 1114112) {
724 return chr(($num >> 18) +
240) . chr((($num >> 12) & 63) +
128) . chr((($num >> 6) & 63) +
128) . chr(($num & 63) +
128);
731 * Convertit un texte unicode en utf-8
733 * @param string $texte
738 function unicode_to_utf_8($texte) {
740 // 1. Entites € et suivantes
742 if (preg_match_all(',�*([1-9][0-9][0-9]+);,S',
743 $texte, $regs, PREG_SET_ORDER
)) {
744 foreach ($regs as $reg) {
745 if ($reg[1] > 127 and !isset($vu[$reg[0]])) {
746 $vu[$reg[0]] = caractere_utf_8($reg[1]);
750 //$texte = str_replace(array_keys($vu), array_values($vu), $texte);
752 // 2. Entites > ÿ
754 if (preg_match_all(',�*([1-9a-f][0-9a-f][0-9a-f]+);,iS',
755 $texte, $regs, PREG_SET_ORDER
)) {
756 foreach ($regs as $reg) {
757 if (!isset($vu[$reg[0]])) {
758 $vu[$reg[0]] = caractere_utf_8(hexdec($reg[1]));
763 return str_replace(array_keys($vu), array_values($vu), $texte);
768 * Convertit les unicode Ĉ en javascript \u0108
770 * @param string $texte
775 function unicode_to_javascript($texte) {
777 while (preg_match(',�*([0-9]+);,S', $texte, $regs) and !isset($vu[$regs[1]])) {
780 $s = '\u' . sprintf("%04x", $num);
781 $texte = str_replace($regs[0], $s, $texte);
788 * Convertit les %uxxxx (envoyés par javascript) en &#yyy unicode
790 * @param string $texte
795 function javascript_to_unicode($texte) {
796 while (preg_match(",%u([0-9A-F][0-9A-F][0-9A-F][0-9A-F]),", $texte, $regs)) {
797 $texte = str_replace($regs[0], "&#" . hexdec($regs[1]) . ";", $texte);
804 * Convertit les %E9 (envoyés par le browser) en chaîne du charset du site (binaire)
806 * @param string $texte
811 function javascript_to_binary($texte) {
812 while (preg_match(",%([0-9A-F][0-9A-F]),", $texte, $regs)) {
813 $texte = str_replace($regs[0], chr(hexdec($regs[1])), $texte);
821 * Substition rapide de chaque graphème selon le charset sélectionné.
823 * @uses caractere_utf_8()
825 * @global array $CHARSET
826 * @staticvar array $trans
828 * @param string $texte
829 * @param string $charset
830 * @param string $complexe
833 function translitteration_rapide($texte, $charset = 'AUTO', $complexe = '') {
835 if ($charset == 'AUTO') {
836 $charset = $GLOBALS['meta']['charset'];
838 if (!strlen($texte)) {
842 $table_translit = 'translit' . $complexe;
844 // 2. Translitterer grace a la table predefinie
845 if (!$trans[$complexe]) {
846 load_charset($table_translit);
847 foreach ($GLOBALS['CHARSET'][$table_translit] as $key => $val) {
848 $trans[$complexe][caractere_utf_8($key)] = $val;
852 return str_replace(array_keys($trans[$complexe]), array_values($trans[$complexe]), $texte);
856 * Translittération charset => ascii (pour l'indexation)
858 * Permet, entre autres, d’enlever les accents,
859 * car la table ASCII non étendue ne les comporte pas.
861 * Attention les caractères non reconnus sont renvoyés en utf-8
863 * @uses corriger_caracteres()
864 * @uses unicode_to_utf_8()
865 * @uses html2unicode()
866 * @uses charset2unicode()
867 * @uses translitteration_rapide()
869 * @param string $texte
870 * @param string $charset
871 * @param string $complexe
874 function translitteration($texte, $charset = 'AUTO', $complexe = '') {
875 // 0. Supprimer les caracteres illegaux
876 include_spip('inc/filtres');
877 $texte = corriger_caracteres($texte);
879 // 1. Passer le charset et les é en utf-8
880 $texte = unicode_to_utf_8(html2unicode(charset2unicode($texte, $charset, true)));
882 return translitteration_rapide($texte, $charset, $complexe);
886 * Translittération complexe
888 * `à` est retourné sous la forme ``a` `` et pas `à`
889 * mais si `$chiffre=true`, on retourne `a8` (vietnamien)
891 * @uses translitteration()
892 * @param string $texte
893 * @param bool $chiffres
896 function translitteration_complexe($texte, $chiffres = false) {
897 $texte = translitteration($texte, 'AUTO', 'complexe');
900 $texte = preg_replace("/[aeiuoyd]['`?~.^+(-]{1,2}/eS",
901 "translitteration_chiffree('\\0')", $texte);
908 * Translittération chiffrée
910 * Remplace des caractères dans une chaîne par des chiffres
915 function translitteration_chiffree($car) {
916 return strtr($car, "'`?~.^+(-", "123456789");
921 * Reconnaitre le BOM utf-8 (0xEFBBBF)
923 * @param string $texte
924 * Texte dont on vérifie la présence du BOM
928 function bom_utf8($texte) {
929 return (substr($texte, 0, 3) == chr(0xEF) . chr(0xBB) . chr(0xBF));
933 * Vérifie qu'une chaîne est en utf-8 valide
935 * Note: preg_replace permet de contourner un "stack overflow" sur PCRE
937 * @link http://us2.php.net/manual/fr/function.mb-detect-encoding.php#50087
938 * @link http://w3.org/International/questions/qa-forms-utf-8.html
940 * @param string $string
941 * Texte dont on vérifie qu'il est de l'utf-8
943 * true si c'est le cas
945 function is_utf8($string) {
948 ',[\x09\x0A\x0D\x20-\x7E]' # ASCII
949 . '|[\xC2-\xDF][\x80-\xBF]' # non-overlong 2-byte
950 . '|\xE0[\xA0-\xBF][\x80-\xBF]' # excluding overlongs
951 . '|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}' # straight 3-byte
952 . '|\xED[\x80-\x9F][\x80-\xBF]' # excluding surrogates
953 . '|\xF0[\x90-\xBF][\x80-\xBF]{2}' # planes 1-3
954 . '|[\xF1-\xF3][\x80-\xBF]{3}' # planes 4-15
955 . '|\xF4[\x80-\x8F][\x80-\xBF]{2}' # plane 16
961 * Vérifie qu'une chaîne est en ascii valide
963 * @param string $string
964 * Texte dont on vérifie qu'il est de l'ascii
966 * true si c'est le cas
968 function is_ascii($string) {
971 ',[\x09\x0A\x0D\x20-\x7E],sS',
976 * Transcode une page vers le charset du site
978 * Transcode une page (attrapée sur le web, ou un squelette) vers le
979 * charset du site en essayant par tous les moyens de deviner son charset
980 * (y compris dans les headers HTTP)
982 * @param string $texte
983 * Page à transcoder, dont on souhaite découvrir son charset
984 * @param string $headers
985 * Éventuels headers HTTP liés à cette page
987 * Texte transcodé dans le charset du site
989 function transcoder_page($texte, $headers = '') {
991 // Si tout est < 128 pas la peine d'aller plus loin
992 if (is_ascii($texte)) {
993 #spip_log('charset: ascii');
997 // Reconnaitre le BOM utf-8 (0xEFBBBF)
998 if (bom_utf8($texte)) {
1000 $texte = substr($texte, 3);
1001 } // charset precise par le contenu (xml)
1004 ',<[?]xml[^>]*encoding[^>]*=[^>]*([-_a-z0-9]+?),UimsS', $texte, $regs)) {
1005 $charset = trim(strtolower($regs[1]));
1006 } // charset precise par le contenu (html)
1009 ',<(meta|html|body)[^>]*charset[^>]*=[^>]*([-_a-z0-9]+?),UimsS',
1011 # eviter #CHARSET des squelettes
1012 and (($tmp = trim(strtolower($regs[2]))) != 'charset')
1015 } // charset de la reponse http
1017 if (preg_match(',charset=([-_a-z0-9]+),i', $headers, $regs)) {
1018 $charset = trim(strtolower($regs[1]));
1025 // normaliser les noms du shif-jis japonais
1026 if (preg_match(',^(x|shift)[_-]s?jis$,i', $charset)) {
1027 $charset = 'shift-jis';
1031 spip_log("charset: $charset");
1033 // valeur par defaut
1034 if (is_utf8($texte)) {
1037 $charset = 'iso-8859-1';
1039 spip_log("charset probable: $charset");
1042 return importer_charset($texte, $charset);
1047 // Gerer les outils mb_string
1051 * Coupe un texte selon substr()
1053 * Coupe une chaîne en utilisant les outils mb* lorsque le site est en utf8
1055 * @link http://fr.php.net/manual/fr/function.mb-substr.php
1056 * @link http://www.php.net/manual/fr/function.substr.php
1057 * @uses spip_substr_manuelle() si les fonctions php mb sont absentes
1059 * @param string $c Le texte
1060 * @param int $start Début
1061 * @param null|int $length Longueur ou fin
1065 function spip_substr($c, $start = 0, $length = null) {
1066 // Si ce n'est pas utf-8, utiliser substr
1067 if ($GLOBALS['meta']['charset'] != 'utf-8') {
1069 return substr($c, $start, $length);
1075 // Si utf-8, voir si on dispose de mb_string
1076 if (init_mb_string()) {
1078 return mb_substr($c, $start, $length);
1080 return mb_substr($c, $start);
1084 // Version manuelle (cf. ci-dessous)
1085 return spip_substr_manuelle($c, $start, $length);
1090 * Coupe un texte comme mb_substr()
1092 * Version manuelle de substr utf8, pour php vieux et/ou mal installe
1094 * @link http://fr.php.net/manual/fr/function.mb-substr.php
1096 * @param string $c Le texte
1097 * @param int $start Début
1098 * @param null|int $length Longueur ou fin
1102 function spip_substr_manuelle($c, $start, $length = null) {
1105 if ($length === 0) {
1109 // S'il y a un demarrage, on se positionne
1111 $c = substr($c, strlen(spip_substr_manuelle($c, 0, $start)));
1112 } elseif ($start < 0) {
1113 return spip_substr_manuelle($c, spip_strlen($c) +
$start, $length);
1121 // on prend n fois la longueur desiree, pour etre surs d'avoir tout
1122 // (un caractere utf-8 prenant au maximum n bytes)
1124 while (preg_match(',[\x80-\xBF]{' . (++
$n) . '},', $c)) {
1127 $c = substr($c, 0, $n * $length);
1128 // puis, tant qu'on est trop long, on coupe...
1129 while (($l = spip_strlen($c)) > $length) {
1130 $c = substr($c, 0, $length - $l);
1137 return spip_substr_manuelle($c, 0, spip_strlen($c) +
$length);
1141 * Rend majuscule le premier caractère d'une chaîne utf-8
1143 * Version utf-8 d'ucfirst
1146 * La chaîne à transformer
1148 * La chaîne avec une majuscule sur le premier mot
1150 function spip_ucfirst($c) {
1151 // Si on n'a pas mb_* ou si ce n'est pas utf-8, utiliser ucfirst
1152 if (!init_mb_string() or $GLOBALS['meta']['charset'] != 'utf-8') {
1156 $lettre1 = mb_strtoupper(spip_substr($c, 0, 1));
1158 return $lettre1 . spip_substr($c, 1);
1162 * Passe une chaîne utf-8 en minuscules
1164 * Version utf-8 de strtolower
1167 * La chaîne à transformer
1169 * La chaîne en minuscules
1171 function spip_strtolower($c) {
1172 // Si on n'a pas mb_* ou si ce n'est pas utf-8, utiliser strtolower
1173 if (!init_mb_string() or $GLOBALS['meta']['charset'] != 'utf-8') {
1174 return strtolower($c);
1177 return mb_strtolower($c);
1181 * Retourne la longueur d'une chaîne utf-8
1183 * Version utf-8 de strlen
1186 * La chaîne à compter
1188 * Longueur de la chaîne
1190 function spip_strlen($c) {
1191 // On transforme les sauts de ligne pour ne pas compter deux caractères
1192 $c = str_replace("\r\n", "\n", $c);
1194 // Si ce n'est pas utf-8, utiliser strlen
1195 if ($GLOBALS['meta']['charset'] != 'utf-8') {
1199 // Sinon, utiliser mb_strlen() si disponible
1200 if (init_mb_string()) {
1201 return mb_strlen($c);
1204 // Methode manuelle : on supprime les bytes 10......,
1205 // on compte donc les ascii (0.......) et les demarrages
1206 // de caracteres utf-8 (11......)
1207 return strlen(preg_replace(',[\x80-\xBF],S', '', $c));
1211 $GLOBALS['CHARSET'] = array();
1213 // noter a l'occasion dans la meta pcre_u notre capacite a utiliser le flag /u
1214 // dans les preg_replace pour ne pas casser certaines lettres accentuees :
1215 // en utf-8 chr(195).chr(160) = a` alors qu'en iso-latin chr(160) = nbsp
1216 if (!isset($GLOBALS['meta']['pcre_u'])
1217 or (isset($_GET['var_mode']) and !isset($_GET['var_profile']))
1219 include_spip('inc/meta');
1220 ecrire_meta('pcre_u',
1221 $u = (lire_config('charset', _DEFAULT_CHARSET
) == 'utf-8'
1222 and test_pcre_unicode())
1229 * Transforme une chaîne utf-8 en utf-8 sans "planes"
1230 * ce qui permet de la donner à MySQL "utf8", qui n'est pas un utf-8 complet
1231 * L'alternative serait d'utiliser utf8mb4
1234 * La chaîne à transformer
1236 * La chaîne avec les caractères utf8 des hauts "planes" échappée
1237 * en unicode : 💩
1239 function utf8_noplanes($x) {
1240 $regexp_utf8_4bytes = '/(
1241 \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
1242 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
1243 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
1245 if (preg_match_all($regexp_utf8_4bytes, $x, $z, PREG_PATTERN_ORDER
)) {
1246 foreach ($z[0] as $k) {
1247 $ku = utf_8_to_unicode($k);
1248 $x = str_replace($k, $ku, $x);