I18n.php 16 KB

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