I18n.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. /* TODO: Once https://github.com/php/php-src/issues/24074 makes it into
  191. * all supported PHP releases, we can use the intl module like so:
  192. if (function_exists('locale_accept_from_http')) {
  193. $detectedBestLanguage = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE'], $availableLanguages);
  194. if ($detectedBestLanguage !== false) {
  195. return $detectedBestLanguage;
  196. }
  197. }
  198. * disabled for now as it's order depends on the ICU version installed
  199. * and showed large inconsistencies between different test environments
  200. */
  201. return self::_getMatchingLanguage(
  202. self::_normalizeBrowserLanguages(self::getBrowserLanguages(), $availableLanguages),
  203. $availableLanguages
  204. );
  205. }
  206. /**
  207. * get list of available translations based on files found
  208. *
  209. * @access public
  210. * @static
  211. * @return array
  212. */
  213. public static function getAvailableLanguages()
  214. {
  215. if (count(self::$_availableLanguages) === 0) {
  216. self::$_availableLanguages[] = 'en'; // en.json is not part of the release archive
  217. $languageIterator = new AppendIterator();
  218. $languageIterator->append(new GlobIterator(self::_getPath('??.json')));
  219. $languageIterator->append(new GlobIterator(self::_getPath('???.json'))); // for jbo
  220. $languageIterator->append(new GlobIterator(self::_getPath('??-??.json'))); // for regional variants like zh-tw
  221. foreach ($languageIterator as $file) {
  222. $language = $file->getBasename('.json');
  223. if ($language !== 'en') {
  224. self::$_availableLanguages[] = $language;
  225. }
  226. }
  227. }
  228. return self::$_availableLanguages;
  229. }
  230. /**
  231. * detect the clients supported languages and return them ordered by preference
  232. *
  233. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  234. *
  235. * @access public
  236. * @static
  237. * @return array
  238. */
  239. public static function getBrowserLanguages()
  240. {
  241. $languages = [];
  242. if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
  243. $languageRanges = explode(',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  244. foreach ($languageRanges as $languageRange) {
  245. if (preg_match(
  246. '/^(\*|[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})))?$/',
  247. trim($languageRange), $match
  248. )) {
  249. if (!isset($match[2])) {
  250. $match[2] = '1.0';
  251. } else {
  252. $match[2] = (string) floatval($match[2]);
  253. }
  254. if (!isset($languages[$match[2]])) {
  255. $languages[$match[2]] = [];
  256. }
  257. $languages[$match[2]][] = strtolower($match[1]);
  258. }
  259. }
  260. krsort($languages);
  261. }
  262. return $languages;
  263. }
  264. /**
  265. * normalize browser language aliases to available locale IDs
  266. *
  267. * @access protected
  268. * @static
  269. * @param array $languages
  270. * @param array $availableLanguages
  271. * @return array
  272. */
  273. protected static function _normalizeBrowserLanguages($languages, $availableLanguages)
  274. {
  275. // Base zh stays before zh-tw because regional locales are appended after base locales.
  276. $hasSimplifiedChinese = in_array('zh', $availableLanguages, true);
  277. $hasTraditionalChinese = in_array('zh-tw', $availableLanguages, true);
  278. foreach ($languages as $quality => $languageRanges) {
  279. foreach ($languageRanges as $index => $languageRange) {
  280. $isSimplifiedChinese = $languageRange === 'zh-hans' || str_starts_with($languageRange, 'zh-hans-') ||
  281. $languageRange === 'zh-cn' || str_starts_with($languageRange, 'zh-cn-') ||
  282. $languageRange === 'zh-sg' || str_starts_with($languageRange, 'zh-sg-');
  283. $isTraditionalChinese = str_starts_with($languageRange, 'zh-tw-') ||
  284. $languageRange === 'zh-hant' || str_starts_with($languageRange, 'zh-hant-') ||
  285. $languageRange === 'zh-hk' || str_starts_with($languageRange, 'zh-hk-') ||
  286. $languageRange === 'zh-mo' || str_starts_with($languageRange, 'zh-mo-');
  287. if ($hasSimplifiedChinese && $isSimplifiedChinese) {
  288. $languages[$quality][$index] = 'zh';
  289. } elseif ($hasTraditionalChinese && $isTraditionalChinese) {
  290. $languages[$quality][$index] = 'zh-tw';
  291. }
  292. }
  293. }
  294. return $languages;
  295. }
  296. /**
  297. * get currently loaded language
  298. *
  299. * @access public
  300. * @static
  301. * @return string
  302. */
  303. public static function getLanguage()
  304. {
  305. return self::$_language;
  306. }
  307. /**
  308. * get list of language labels
  309. *
  310. * Only for given language codes, otherwise all labels.
  311. *
  312. * @access public
  313. * @static
  314. * @param array $languages
  315. * @throws JsonException
  316. * @return array
  317. */
  318. public static function getLanguageLabels($languages = [])
  319. {
  320. $file = self::_getPath('languages.json');
  321. if (count(self::$_languageLabels) === 0 && is_readable($file)) {
  322. $data = file_get_contents($file);
  323. self::$_languageLabels = Json::decode($data);
  324. }
  325. if (count($languages) === 0) {
  326. return self::$_languageLabels;
  327. }
  328. return array_intersect_key(self::$_languageLabels, array_flip($languages));
  329. }
  330. /**
  331. * determines if the current language is written right-to-left (RTL)
  332. *
  333. * @access public
  334. * @static
  335. * @return bool
  336. */
  337. public static function isRtl()
  338. {
  339. return in_array(self::$_language, ['ar', 'fa', 'he']);
  340. }
  341. /**
  342. * get OS-specific copy hotkey modifier key name based on user agent
  343. *
  344. * @access public
  345. * @static
  346. * @return string 'Cmd' on macOS, 'Ctrl' otherwise
  347. */
  348. public static function getCopyHotkey()
  349. {
  350. return array_key_exists('HTTP_USER_AGENT', $_SERVER) &&
  351. str_contains($_SERVER['HTTP_USER_AGENT'], 'Mac') ? self::_('Cmd') : self::_('Ctrl');
  352. }
  353. /**
  354. * set the default language
  355. *
  356. * @access public
  357. * @static
  358. * @param string $lang
  359. */
  360. public static function setLanguageFallback($lang)
  361. {
  362. if (in_array($lang, self::getAvailableLanguages())) {
  363. self::$_languageFallback = $lang;
  364. }
  365. }
  366. /**
  367. * get language file path
  368. *
  369. * @access protected
  370. * @static
  371. * @param string $file
  372. * @return string
  373. */
  374. protected static function _getPath($file = '')
  375. {
  376. if (empty(self::$_path)) {
  377. self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
  378. }
  379. return self::$_path . (empty($file) ? '' : DIRECTORY_SEPARATOR . $file);
  380. }
  381. /**
  382. * determines the plural form to use based on current language and given number
  383. *
  384. * From: https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
  385. *
  386. * @access protected
  387. * @static
  388. * @param int $n
  389. * @return int
  390. */
  391. protected static function _getPluralForm($n)
  392. {
  393. switch (self::$_language) {
  394. case 'ar':
  395. return $n === 0 ? 0 : ($n === 1 ? 1 : ($n === 2 ? 2 : ($n % 100 >= 3 && $n % 100 <= 10 ? 3 : ($n % 100 >= 11 ? 4 : 5))));
  396. case 'cs':
  397. case 'sk':
  398. return $n === 1 ? 0 : ($n >= 2 && $n <= 4 ? 1 : 2);
  399. case 'co':
  400. case 'fa':
  401. case 'fr':
  402. case 'oc':
  403. case 'tr':
  404. case 'zh':
  405. case 'zh-tw':
  406. return $n > 1 ? 1 : 0;
  407. case 'he':
  408. return $n === 1 ? 0 : ($n === 2 ? 1 : (($n < 0 || $n > 10) && ($n % 10 === 0) ? 2 : 3));
  409. case 'id':
  410. case 'ja':
  411. case 'jbo':
  412. case 'ko':
  413. case 'th':
  414. return 0;
  415. case 'lt':
  416. return $n % 10 === 1 && $n % 100 !== 11 ? 0 : (($n % 10 >= 2 && ($n % 100 < 10 || $n % 100 >= 20)) ? 1 : 2);
  417. case 'pl':
  418. return $n === 1 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  419. case 'ro':
  420. return $n === 1 ? 0 : (($n === 0 || ($n % 100 > 0 && $n % 100 < 20)) ? 1 : 2);
  421. case 'ru':
  422. case 'uk':
  423. return $n % 10 === 1 && $n % 100 !== 11 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  424. case 'sl':
  425. return $n % 100 === 1 ? 1 : ($n % 100 === 2 ? 2 : ($n % 100 === 3 || $n % 100 === 4 ? 3 : 0));
  426. default:
  427. // bg, ca, de, el, en, es, et, fi, hu, it, nl, no, pt, sv
  428. return $n !== 1 ? 1 : 0;
  429. }
  430. }
  431. /**
  432. * compares two language preference arrays and returns the preferred match
  433. *
  434. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  435. *
  436. * @access protected
  437. * @static
  438. * @param array $acceptedLanguages
  439. * @param array $availableLanguages
  440. * @return string
  441. */
  442. protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages)
  443. {
  444. $matches = [];
  445. $any = false;
  446. foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) {
  447. $acceptedQuality = floatval($acceptedQuality);
  448. if ($acceptedQuality === 0.0) {
  449. continue;
  450. }
  451. foreach ($acceptedValues as $acceptedValue) {
  452. if ($acceptedValue === '*') {
  453. $any = true;
  454. }
  455. foreach ($availableLanguages as $availableValue) {
  456. $availableQuality = 1.0;
  457. $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
  458. if ($matchingGrade > 0) {
  459. $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
  460. if (!isset($matches[$q])) {
  461. $matches[$q] = [];
  462. }
  463. if (!in_array($availableValue, $matches[$q])) {
  464. $matches[$q][] = $availableValue;
  465. }
  466. }
  467. }
  468. }
  469. }
  470. if (count($matches) === 0 && $any) {
  471. if (count($availableLanguages) > 0) {
  472. $matches['1.0'] = $availableLanguages;
  473. }
  474. }
  475. if (count($matches) === 0) {
  476. return self::$_languageFallback;
  477. }
  478. krsort($matches);
  479. $topmatches = current($matches);
  480. return current($topmatches);
  481. }
  482. /**
  483. * compare two language IDs and return the degree they match
  484. *
  485. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  486. *
  487. * @access protected
  488. * @static
  489. * @param string $a
  490. * @param string $b
  491. * @return float
  492. */
  493. protected static function _matchLanguage($a, $b)
  494. {
  495. $a = explode('-', $a);
  496. $b = explode('-', $b);
  497. for ($i = 0, $n = min(count($a), count($b)); $i < $n; ++$i) {
  498. if ($a[$i] !== $b[$i]) {
  499. break;
  500. }
  501. }
  502. return $i === 0 ? 0 : (float) $i / count($a);
  503. }
  504. }