1
0

I18n.php 14 KB

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