I18n.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. <?php declare(strict_types=1);
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. */
  11. namespace PrivateBin;
  12. use AppendIterator;
  13. use GlobIterator;
  14. use function array_key_exists;
  15. use function in_array;
  16. /**
  17. * I18n
  18. *
  19. * provides internationalization tools like translation, browser language detection, etc.
  20. */
  21. class I18n
  22. {
  23. /**
  24. * language
  25. *
  26. * @access protected
  27. * @static
  28. * @var string
  29. */
  30. protected static $_language = 'en';
  31. /**
  32. * language fallback
  33. *
  34. * @access protected
  35. * @static
  36. * @var string
  37. */
  38. protected static $_languageFallback = 'en';
  39. /**
  40. * language labels
  41. *
  42. * @access protected
  43. * @static
  44. * @var array
  45. */
  46. protected static $_languageLabels = [];
  47. /**
  48. * available languages
  49. *
  50. * @access protected
  51. * @static
  52. * @var array
  53. */
  54. protected static $_availableLanguages = [];
  55. /**
  56. * path to language files
  57. *
  58. * @access protected
  59. * @static
  60. * @var string
  61. */
  62. protected static $_path = '';
  63. /**
  64. * translation cache
  65. *
  66. * @access protected
  67. * @static
  68. * @var array
  69. */
  70. protected static $_translations = [];
  71. /**
  72. * translate a string, alias for translate()
  73. *
  74. * @access public
  75. * @static
  76. * @param string|array $messageId
  77. * @param mixed $args one or multiple parameters injected into placeholders
  78. * @return string
  79. */
  80. public static function _($messageId, ...$args)
  81. {
  82. return forward_static_call_array('PrivateBin\I18n::translate', func_get_args());
  83. }
  84. /**
  85. * translate a string
  86. *
  87. * @access public
  88. * @static
  89. * @param string|array $messageId
  90. * @param mixed $args one or multiple parameters injected into placeholders
  91. * @return string
  92. */
  93. public static function translate($messageId, ...$args)
  94. {
  95. if (empty($messageId)) {
  96. return $messageId;
  97. }
  98. if (empty(self::$_translations)) {
  99. self::loadTranslations();
  100. }
  101. $messages = $messageId;
  102. if (is_array($messageId)) {
  103. $messageId = count($messageId) > 1 ? $messageId[1] : $messageId[0];
  104. }
  105. if (!array_key_exists($messageId, self::$_translations)) {
  106. self::$_translations[$messageId] = $messages;
  107. }
  108. array_unshift($args, $messageId);
  109. if (is_array(self::$_translations[$messageId])) {
  110. $number = (int) $args[1];
  111. $key = self::_getPluralForm($number);
  112. $max = count(self::$_translations[$messageId]) - 1;
  113. if ($key > $max) {
  114. $key = $max;
  115. }
  116. $args[0] = self::$_translations[$messageId][$key];
  117. $args[1] = $number;
  118. } else {
  119. $args[0] = self::$_translations[$messageId];
  120. }
  121. // encode any non-integer arguments, but not the message itself
  122. // The message ID comes from trusted sources (code or translation JSON files),
  123. // while parameters may come from untrusted sources and need HTML entity encoding
  124. // to prevent XSS attacks when the message is inserted into HTML context
  125. $argsCount = count($args);
  126. for ($i = 1; $i < $argsCount; ++$i) {
  127. if (is_int($args[$i])) {
  128. continue;
  129. }
  130. $args[$i] = self::encode($args[$i]);
  131. }
  132. return call_user_func_array('sprintf', $args);
  133. }
  134. /**
  135. * encode HTML entities for output into an HTML5 document
  136. *
  137. * @access public
  138. * @static
  139. * @param string $string
  140. * @return string
  141. */
  142. public static function encode($string)
  143. {
  144. return htmlspecialchars($string, ENT_QUOTES | ENT_HTML5 | ENT_DISALLOWED, 'UTF-8', false);
  145. }
  146. /**
  147. * loads translations
  148. *
  149. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  150. *
  151. * @access public
  152. * @static
  153. * @throws JsonException
  154. */
  155. public static function loadTranslations()
  156. {
  157. $availableLanguages = self::getAvailableLanguages();
  158. // check if the lang cookie was set and that language exists
  159. if (
  160. array_key_exists('lang', $_COOKIE) &&
  161. ($key = array_search($_COOKIE['lang'], $availableLanguages)) !== false
  162. ) {
  163. self::$_language = $availableLanguages[$key];
  164. }
  165. // find a translation file matching the browsers language preferences
  166. else {
  167. self::$_language = self::_getLanguageFromHttpHeader($availableLanguages);
  168. }
  169. // load translations
  170. if (self::$_language === 'en') {
  171. self::$_translations = [];
  172. } else {
  173. $data = file_get_contents(self::_getPath(self::$_language . '.json'));
  174. self::$_translations = Json::decode($data);
  175. }
  176. }
  177. /**
  178. * get languages based on the HTTP header
  179. *
  180. * @access private
  181. * @static
  182. * @param array $availableLanguages
  183. * @return string
  184. */
  185. private static function _getLanguageFromHttpHeader($availableLanguages)
  186. {
  187. if (!array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
  188. return self::$_languageFallback;
  189. }
  190. // ICU < 67 returns equivalent matches in alphabetical order instead of
  191. // the order passed, causing test inconsistencies (unicode-org/icu#1022).
  192. // Also, ICU doesn't properly handle some of our languages (co, jbo) or
  193. // regional zh variants (zh_TW, zh_HK) even in recent versions.
  194. if (
  195. function_exists('locale_accept_from_http') &&
  196. defined('INTL_ICU_VERSION') &&
  197. version_compare(INTL_ICU_VERSION, '67', '>=') &&
  198. !preg_match('/(co|jbo|zh-)/', $_SERVER['HTTP_ACCEPT_LANGUAGE'])
  199. ) {
  200. $detectedBestLocale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
  201. if (
  202. $detectedBestLocale !== false &&
  203. function_exists('locale_get_primary_language')
  204. ) {
  205. $detectedBestLanguage = locale_get_primary_language($detectedBestLocale);
  206. if (in_array($detectedBestLanguage, $availableLanguages)) {
  207. return $detectedBestLanguage;
  208. }
  209. }
  210. }
  211. return self::_getMatchingLanguage(
  212. self::_normalizeBrowserLanguages(self::getBrowserLanguages(), $availableLanguages),
  213. $availableLanguages
  214. );
  215. }
  216. /**
  217. * get list of available translations based on files found
  218. *
  219. * @access public
  220. * @static
  221. * @return array
  222. */
  223. public static function getAvailableLanguages()
  224. {
  225. if (count(self::$_availableLanguages) === 0) {
  226. self::$_availableLanguages[] = 'en'; // en.json is not part of the release archive
  227. $languageIterator = new AppendIterator();
  228. $languageIterator->append(new GlobIterator(self::_getPath('??.json')));
  229. $languageIterator->append(new GlobIterator(self::_getPath('???.json'))); // for jbo
  230. $languageIterator->append(new GlobIterator(self::_getPath('??-??.json'))); // for regional variants like zh-tw
  231. foreach ($languageIterator as $file) {
  232. $language = $file->getBasename('.json');
  233. if ($language !== 'en') {
  234. self::$_availableLanguages[] = $language;
  235. }
  236. }
  237. }
  238. return self::$_availableLanguages;
  239. }
  240. /**
  241. * detect the clients supported languages and return them ordered by preference
  242. *
  243. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  244. *
  245. * @access public
  246. * @static
  247. * @return array
  248. */
  249. public static function getBrowserLanguages()
  250. {
  251. $languages = [];
  252. if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
  253. $languageRanges = explode(',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  254. foreach ($languageRanges as $languageRange) {
  255. if (preg_match(
  256. '/^(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?$/',
  257. trim($languageRange), $match
  258. )) {
  259. if (!isset($match[2])) {
  260. $match[2] = '1.0';
  261. } else {
  262. $match[2] = (string) floatval($match[2]);
  263. }
  264. if (!isset($languages[$match[2]])) {
  265. $languages[$match[2]] = [];
  266. }
  267. $languages[$match[2]][] = strtolower($match[1]);
  268. }
  269. }
  270. krsort($languages);
  271. }
  272. return $languages;
  273. }
  274. /**
  275. * normalize browser language aliases to available locale IDs
  276. *
  277. * @access protected
  278. * @static
  279. * @param array $languages
  280. * @param array $availableLanguages
  281. * @return array
  282. */
  283. protected static function _normalizeBrowserLanguages($languages, $availableLanguages)
  284. {
  285. // Base zh stays before zh-tw because regional locales are appended after base locales.
  286. $hasSimplifiedChinese = in_array('zh', $availableLanguages, true);
  287. $hasTraditionalChinese = in_array('zh-tw', $availableLanguages, true);
  288. foreach ($languages as $quality => $languageRanges) {
  289. foreach ($languageRanges as $index => $languageRange) {
  290. $isSimplifiedChinese = $languageRange === 'zh-hans' || str_starts_with($languageRange, 'zh-hans-') ||
  291. $languageRange === 'zh-cn' || str_starts_with($languageRange, 'zh-cn-') ||
  292. $languageRange === 'zh-sg' || str_starts_with($languageRange, 'zh-sg-');
  293. $isTraditionalChinese = str_starts_with($languageRange, 'zh-tw-') ||
  294. $languageRange === 'zh-hant' || str_starts_with($languageRange, 'zh-hant-') ||
  295. $languageRange === 'zh-hk' || str_starts_with($languageRange, 'zh-hk-') ||
  296. $languageRange === 'zh-mo' || str_starts_with($languageRange, 'zh-mo-');
  297. if ($hasSimplifiedChinese && $isSimplifiedChinese) {
  298. $languages[$quality][$index] = 'zh';
  299. } elseif ($hasTraditionalChinese && $isTraditionalChinese) {
  300. $languages[$quality][$index] = 'zh-tw';
  301. }
  302. }
  303. }
  304. return $languages;
  305. }
  306. /**
  307. * get currently loaded language
  308. *
  309. * @access public
  310. * @static
  311. * @return string
  312. */
  313. public static function getLanguage()
  314. {
  315. return self::$_language;
  316. }
  317. /**
  318. * get list of language labels
  319. *
  320. * Only for given language codes, otherwise all labels.
  321. *
  322. * @access public
  323. * @static
  324. * @param array $languages
  325. * @throws JsonException
  326. * @return array
  327. */
  328. public static function getLanguageLabels($languages = [])
  329. {
  330. $file = self::_getPath('languages.json');
  331. if (count(self::$_languageLabels) === 0 && is_readable($file)) {
  332. $data = file_get_contents($file);
  333. self::$_languageLabels = Json::decode($data);
  334. }
  335. if (count($languages) === 0) {
  336. return self::$_languageLabels;
  337. }
  338. return array_intersect_key(self::$_languageLabels, array_flip($languages));
  339. }
  340. /**
  341. * determines if the current language is written right-to-left (RTL)
  342. *
  343. * @access public
  344. * @static
  345. * @return bool
  346. */
  347. public static function isRtl()
  348. {
  349. return in_array(self::$_language, ['ar', 'fa', 'he']);
  350. }
  351. /**
  352. * get OS-specific copy hotkey modifier key name based on user agent
  353. *
  354. * @access public
  355. * @static
  356. * @return string 'Cmd' on macOS, 'Ctrl' otherwise
  357. */
  358. public static function getCopyHotkey()
  359. {
  360. return array_key_exists('HTTP_USER_AGENT', $_SERVER) &&
  361. str_contains($_SERVER['HTTP_USER_AGENT'], 'Mac') ? self::_('Cmd') : self::_('Ctrl');
  362. }
  363. /**
  364. * set the default language
  365. *
  366. * @access public
  367. * @static
  368. * @param string $lang
  369. */
  370. public static function setLanguageFallback($lang)
  371. {
  372. if (in_array($lang, self::getAvailableLanguages())) {
  373. self::$_languageFallback = $lang;
  374. }
  375. }
  376. /**
  377. * get language file path
  378. *
  379. * @access protected
  380. * @static
  381. * @param string $file
  382. * @return string
  383. */
  384. protected static function _getPath($file = '')
  385. {
  386. if (empty(self::$_path)) {
  387. self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
  388. }
  389. return self::$_path . (empty($file) ? '' : DIRECTORY_SEPARATOR . $file);
  390. }
  391. /**
  392. * determines the plural form to use based on current language and given number
  393. *
  394. * From: https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
  395. *
  396. * @access protected
  397. * @static
  398. * @param int $n
  399. * @return int
  400. */
  401. protected static function _getPluralForm($n)
  402. {
  403. switch (self::$_language) {
  404. case 'ar':
  405. return $n === 0 ? 0 : ($n === 1 ? 1 : ($n === 2 ? 2 : ($n % 100 >= 3 && $n % 100 <= 10 ? 3 : ($n % 100 >= 11 ? 4 : 5))));
  406. case 'cs':
  407. case 'sk':
  408. return $n === 1 ? 0 : ($n >= 2 && $n <= 4 ? 1 : 2);
  409. case 'co':
  410. case 'fa':
  411. case 'fr':
  412. case 'oc':
  413. case 'tr':
  414. case 'zh':
  415. case 'zh-tw':
  416. return $n > 1 ? 1 : 0;
  417. case 'he':
  418. return $n === 1 ? 0 : ($n === 2 ? 1 : (($n < 0 || $n > 10) && ($n % 10 === 0) ? 2 : 3));
  419. case 'id':
  420. case 'ja':
  421. case 'jbo':
  422. case 'ko':
  423. case 'th':
  424. return 0;
  425. case 'lt':
  426. return $n % 10 === 1 && $n % 100 !== 11 ? 0 : (($n % 10 >= 2 && ($n % 100 < 10 || $n % 100 >= 20)) ? 1 : 2);
  427. case 'pl':
  428. return $n === 1 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  429. case 'ro':
  430. return $n === 1 ? 0 : (($n === 0 || ($n % 100 > 0 && $n % 100 < 20)) ? 1 : 2);
  431. case 'ru':
  432. case 'uk':
  433. return $n % 10 === 1 && $n % 100 !== 11 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  434. case 'sl':
  435. return $n % 100 === 1 ? 1 : ($n % 100 === 2 ? 2 : ($n % 100 === 3 || $n % 100 === 4 ? 3 : 0));
  436. default:
  437. // bg, ca, de, el, en, es, et, fi, hu, it, nl, no, pt, sv
  438. return $n !== 1 ? 1 : 0;
  439. }
  440. }
  441. /**
  442. * compares two language preference arrays and returns the preferred match
  443. *
  444. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  445. *
  446. * @access protected
  447. * @static
  448. * @param array $acceptedLanguages
  449. * @param array $availableLanguages
  450. * @return string
  451. */
  452. protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages)
  453. {
  454. $matches = [];
  455. $any = false;
  456. foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) {
  457. $acceptedQuality = floatval($acceptedQuality);
  458. if ($acceptedQuality === 0.0) {
  459. continue;
  460. }
  461. foreach ($acceptedValues as $acceptedValue) {
  462. if ($acceptedValue === '*') {
  463. $any = true;
  464. }
  465. foreach ($availableLanguages as $availableValue) {
  466. $availableQuality = 1.0;
  467. $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
  468. if ($matchingGrade > 0) {
  469. $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
  470. if (!isset($matches[$q])) {
  471. $matches[$q] = [];
  472. }
  473. if (!in_array($availableValue, $matches[$q])) {
  474. $matches[$q][] = $availableValue;
  475. }
  476. }
  477. }
  478. }
  479. }
  480. if (count($matches) === 0 && $any) {
  481. if (count($availableLanguages) > 0) {
  482. $matches['1.0'] = $availableLanguages;
  483. }
  484. }
  485. if (count($matches) === 0) {
  486. return self::$_languageFallback;
  487. }
  488. krsort($matches);
  489. $topmatches = current($matches);
  490. return current($topmatches);
  491. }
  492. /**
  493. * compare two language IDs and return the degree they match
  494. *
  495. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  496. *
  497. * @access protected
  498. * @static
  499. * @param string $a
  500. * @param string $b
  501. * @return float
  502. */
  503. protected static function _matchLanguage($a, $b)
  504. {
  505. $a = explode('-', $a);
  506. $b = explode('-', $b);
  507. for ($i = 0, $n = min(count($a), count($b)); $i < $n; ++$i) {
  508. if ($a[$i] !== $b[$i]) {
  509. break;
  510. }
  511. }
  512. return $i === 0 ? 0 : (float) $i / count($a);
  513. }
  514. }