I18n.php 17 KB

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