I18n.php 17 KB

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