Bootup.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. <?php // vi: set fenc=utf-8 ts=4 sw=4 et:
  2. /*
  3. * Copyright (C) 2013 Nicolas Grekas - p@tchwork.com
  4. *
  5. * This library is free software; you can redistribute it and/or modify it
  6. * under the terms of the (at your option):
  7. * Apache License v2.0 (http://apache.org/licenses/LICENSE-2.0.txt), or
  8. * GNU General Public License v2.0 (http://gnu.org/licenses/gpl-2.0.txt).
  9. */
  10. namespace Patchwork\Utf8;
  11. use Normalizer as n;
  12. use Patchwork\Utf8 as u;
  13. class Bootup
  14. {
  15. static function initAll()
  16. {
  17. self::initUtf8Encode();
  18. self::initMbstring();
  19. self::initIconv();
  20. self::initExif();
  21. self::initIntl();
  22. self::initLocale();
  23. }
  24. static function initUtf8Encode()
  25. {
  26. function_exists('utf8_encode') or require __DIR__ . '/Bootup/utf8_encode.php';
  27. }
  28. static function initMbstring()
  29. {
  30. if (extension_loaded('mbstring'))
  31. {
  32. if ( ((int) ini_get('mbstring.encoding_translation') || in_array(strtolower(ini_get('mbstring.encoding_translation')), array('on', 'yes', 'true')))
  33. && !in_array(strtolower(ini_get('mbstring.http_input')), array('pass', '8bit', 'utf-8')) )
  34. {
  35. user_error('php.ini settings: Please disable mbstring.encoding_translation or set mbstring.http_input to "pass"', E_USER_WARNING);
  36. }
  37. if (MB_OVERLOAD_STRING & (int) ini_get('mbstring.func_overload'))
  38. {
  39. user_error('php.ini settings: Please disable mbstring.func_overload', E_USER_WARNING);
  40. }
  41. mb_regex_encoding('UTF-8');
  42. ini_set('mbstring.script_encoding', 'pass');
  43. if ('utf-8' !== strtolower(mb_internal_encoding()))
  44. {
  45. mb_internal_encoding('UTF-8');
  46. ini_set('mbstring.internal_encoding', 'UTF-8');
  47. }
  48. if ('none' !== strtolower(mb_substitute_character()))
  49. {
  50. mb_substitute_character('none');
  51. ini_set('mbstring.substitute_character', 'none');
  52. }
  53. if (!in_array(strtolower(mb_http_output()), array('pass', '8bit')))
  54. {
  55. mb_http_output('pass');
  56. ini_set('mbstring.http_output', 'pass');
  57. }
  58. if (!in_array(strtolower(mb_language()), array('uni', 'neutral')))
  59. {
  60. mb_language('uni');
  61. ini_set('mbstring.language', 'uni');
  62. }
  63. }
  64. else if (!defined('MB_OVERLOAD_MAIL'))
  65. {
  66. require __DIR__ . '/Bootup/mbstring.php';
  67. }
  68. }
  69. static function initIconv()
  70. {
  71. if (extension_loaded('iconv'))
  72. {
  73. if ('UTF-8' !== iconv_get_encoding('input_encoding'))
  74. {
  75. iconv_set_encoding('input_encoding', 'UTF-8');
  76. ini_set('iconv.input_encoding', 'UTF-8');
  77. }
  78. if ('UTF-8' !== iconv_get_encoding('internal_encoding'))
  79. {
  80. iconv_set_encoding('internal_encoding', 'UTF-8');
  81. ini_set('iconv.internal_encoding', 'UTF-8');
  82. }
  83. if ('UTF-8' !== iconv_get_encoding('output_encoding'))
  84. {
  85. iconv_set_encoding('output_encoding' , 'UTF-8');
  86. ini_set('iconv.output_encoding', 'UTF-8');
  87. }
  88. }
  89. else if (!defined('ICONV_IMPL'))
  90. {
  91. require __DIR__ . '/Bootup/iconv.php';
  92. }
  93. }
  94. static function initExif()
  95. {
  96. if (extension_loaded('exif'))
  97. {
  98. if (ini_get('exif.encode_unicode') && 'UTF-8' !== strtoupper(ini_get('exif.encode_unicode')))
  99. {
  100. ini_set('exif.encode_unicode', 'UTF-8');
  101. }
  102. if (ini_get('exif.encode_jis') && 'UTF-8' !== strtoupper(ini_get('exif.encode_jis')))
  103. {
  104. ini_set('exif.encode_jis', 'UTF-8');
  105. }
  106. }
  107. }
  108. static function initIntl()
  109. {
  110. if (defined('GRAPHEME_CLUSTER_RX')) return;
  111. preg_match('/^.$/u', '§') or user_error('PCRE is compiled without UTF-8 support', E_USER_WARNING);
  112. extension_loaded('intl') or require __DIR__ . '/Bootup/intl.php';
  113. if (PCRE_VERSION < '8.32')
  114. {
  115. // (CRLF|([ZWNJ-ZWJ]|T+|L*(LV?V+|LV|LVT)T*|L+|[^Control])[Extend]*|[Control])
  116. // This regular expression is not up to date with the latest unicode grapheme cluster definition.
  117. // However, until http://bugs.exim.org/show_bug.cgi?id=1279 is fixed, it's still better than \X
  118. define('GRAPHEME_CLUSTER_RX', '(?:\r\n|(?:[ -~\x{200C}\x{200D}]|[ᆨ-ᇹ]+|[ᄀ-ᅟ]*(?:[가개갸걔거게겨계고과괘괴교구궈궤귀규그긔기까깨꺄꺠꺼께껴꼐꼬꽈꽤꾀꾜꾸꿔꿰뀌뀨끄끠끼나내냐냬너네녀녜노놔놰뇌뇨누눠눼뉘뉴느늬니다대댜댸더데뎌뎨도돠돼되됴두둬뒈뒤듀드듸디따때땨떄떠떼뗘뗴또똬뙈뙤뚀뚜뚸뛔뛰뜌뜨띄띠라래랴럐러레려례로롸뢔뢰료루뤄뤠뤼류르릐리마매먀먜머메며몌모뫄뫠뫼묘무뭐뭬뮈뮤므믜미바배뱌뱨버베벼볘보봐봬뵈뵤부붜붸뷔뷰브븨비빠빼뺘뺴뻐뻬뼈뼤뽀뽜뽸뾔뾰뿌뿨쀄쀠쀼쁘쁴삐사새샤섀서세셔셰소솨쇄쇠쇼수숴쉐쉬슈스싀시싸쌔쌰썌써쎄쎠쎼쏘쏴쐐쐬쑈쑤쒀쒜쒸쓔쓰씌씨아애야얘어에여예오와왜외요우워웨위유으의이자재쟈쟤저제져졔조좌좨죄죠주줘줴쥐쥬즈즤지짜째쨔쨰쩌쩨쪄쪠쪼쫘쫴쬐쬬쭈쭤쮀쮜쮸쯔쯰찌차채챠챼처체쳐쳬초촤쵀최쵸추춰췌취츄츠츼치카캐캬컈커케켜켸코콰쾌쾨쿄쿠쿼퀘퀴큐크킈키타태탸턔터테텨톄토톼퇘퇴툐투퉈퉤튀튜트틔티파패퍄퍠퍼페펴폐포퐈퐤푀표푸풔풰퓌퓨프픠피하해햐햬허헤혀혜호화홰회효후훠훼휘휴흐희히]?[ᅠ-ᆢ]+|[가-힣])[ᆨ-ᇹ]*|[ᄀ-ᅟ]+|[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}])[\p{Mn}\p{Me}\x{09BE}\x{09D7}\x{0B3E}\x{0B57}\x{0BBE}\x{0BD7}\x{0CC2}\x{0CD5}\x{0CD6}\x{0D3E}\x{0D57}\x{0DCF}\x{0DDF}\x{200C}\x{200D}\x{1D165}\x{1D16E}-\x{1D172}]*|[\p{Cc}\p{Cf}\p{Zl}\p{Zp}])');
  119. }
  120. else
  121. {
  122. define('GRAPHEME_CLUSTER_RX', '\X');
  123. }
  124. }
  125. static function initLocale()
  126. {
  127. // With non-UTF-8 locale, basename() bugs.
  128. // Be aware that setlocale() can be slow.
  129. // You'd better properly configure your LANG environment variable to an UTF-8 locale.
  130. if ('' === basename('§'))
  131. {
  132. setlocale(LC_ALL, 'C.UTF-8', 'C');
  133. setlocale(LC_CTYPE, 'en_US.UTF-8', 'fr_FR.UTF-8', 'es_ES.UTF-8', 'de_DE.UTF-8', 'ru_RU.UTF-8', 'pt_BR.UTF-8', 'it_IT.UTF-8', 'ja_JP.UTF-8', 'zh_CN.UTF-8', 0);
  134. }
  135. }
  136. static function filterRequestUri()
  137. {
  138. // Ensures the URL is well formed UTF-8
  139. // When not, assumes Windows-1252 and redirects to the corresponding UTF-8 encoded URL
  140. if (isset($_SERVER['REQUEST_URI']) && !preg_match('//u', urldecode($a = $_SERVER['REQUEST_URI'])))
  141. {
  142. if ($a === u::utf8_decode($a))
  143. {
  144. $a = preg_replace_callback(
  145. '/(?:%[89A-F][0-9A-F])+/i',
  146. function($m) {return urlencode(u::utf8_encode(urldecode($m[0])));},
  147. $a
  148. );
  149. }
  150. else $a = '/';
  151. header('HTTP/1.1 301 Moved Permanently');
  152. header('Location: ' . $a);
  153. exit;
  154. }
  155. }
  156. static function filterRequestInputs($normalization_form = /* n::NFC = */ 4, $pre_lead_comb = '◌')
  157. {
  158. // Ensures inputs are well formed UTF-8
  159. // When not, assumes Windows-1252 and converts to UTF-8
  160. // Tests only values, not keys
  161. $a = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST, &$_ENV);
  162. foreach ($_FILES as &$v) $a[] = array(&$v['name'], &$v['type']);
  163. $len = count($a);
  164. for ($i = 0; $i < $len; ++$i)
  165. {
  166. foreach ($a[$i] as &$v)
  167. {
  168. if (is_array($v)) $a[$len++] =& $v;
  169. else if (preg_match('/[\x80-\xFF]/', $v))
  170. {
  171. if (n::isNormalized($v, $normalization_form)) $w = '';
  172. else
  173. {
  174. $w = n::normalize($v, $normalization_form);
  175. if (false === $w) $v = u::utf8_encode($v);
  176. else $v = $w;
  177. }
  178. if ($v[0] >= "\x80" && false !== $w && isset($pre_lead_comb[0]) && preg_match('/^\p{Mn}/u', $v))
  179. {
  180. // Prevent leading combining chars
  181. // for NFC-safe concatenations.
  182. $v = $pre_lead_comb . $v;
  183. }
  184. }
  185. }
  186. reset($a[$i]);
  187. unset($a[$i]);
  188. }
  189. }
  190. }