I18n.php 16 KB

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