I18n.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 and the message ID, if it doesn't contain a link or keyboard input
  120. $argsCount = count($args);
  121. for ($i = 0; $i < $argsCount; ++$i) {
  122. if ($i === 0) {
  123. if (strpos($args[0], '<a') !== false || strpos($args[0], '<kbd>') !== false) {
  124. continue;
  125. }
  126. } else {
  127. if (is_int($args[$i])) {
  128. continue;
  129. }
  130. }
  131. $args[$i] = self::encode($args[$i]);
  132. }
  133. return call_user_func_array('sprintf', $args);
  134. }
  135. /**
  136. * encode HTML entities for output into an HTML5 document
  137. *
  138. * @access public
  139. * @static
  140. * @param string $string
  141. * @return string
  142. */
  143. public static function encode($string)
  144. {
  145. return htmlspecialchars($string, ENT_QUOTES | ENT_HTML5 | ENT_DISALLOWED, 'UTF-8', false);
  146. }
  147. /**
  148. * loads translations
  149. *
  150. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  151. *
  152. * @access public
  153. * @static
  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. $match = $availableLanguages[$key];
  164. }
  165. // find a translation file matching the browsers language preferences
  166. else {
  167. $match = self::_getMatchingLanguage(
  168. self::getBrowserLanguages(), $availableLanguages
  169. );
  170. }
  171. // load translations
  172. self::$_language = $match;
  173. self::$_translations = ($match == 'en') ? array() : Json::decode(
  174. file_get_contents(self::_getPath($match . '.json'))
  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. * @return array
  254. */
  255. public static function getLanguageLabels($languages = array())
  256. {
  257. $file = self::_getPath('languages.json');
  258. if (count(self::$_languageLabels) == 0 && is_readable($file)) {
  259. self::$_languageLabels = Json::decode(file_get_contents($file));
  260. }
  261. if (count($languages) == 0) {
  262. return self::$_languageLabels;
  263. }
  264. return array_intersect_key(self::$_languageLabels, array_flip($languages));
  265. }
  266. /**
  267. * determines if the current language is written right-to-left (RTL)
  268. *
  269. * @access public
  270. * @static
  271. * @return bool
  272. */
  273. public static function isRtl()
  274. {
  275. return in_array(self::$_language, array('ar', 'he'));
  276. }
  277. /**
  278. * set the default language
  279. *
  280. * @access public
  281. * @static
  282. * @param string $lang
  283. */
  284. public static function setLanguageFallback($lang)
  285. {
  286. if (in_array($lang, self::getAvailableLanguages())) {
  287. self::$_languageFallback = $lang;
  288. }
  289. }
  290. /**
  291. * get language file path
  292. *
  293. * @access protected
  294. * @static
  295. * @param string $file
  296. * @return string
  297. */
  298. protected static function _getPath($file = '')
  299. {
  300. if (empty(self::$_path)) {
  301. self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
  302. }
  303. return self::$_path . (empty($file) ? '' : DIRECTORY_SEPARATOR . $file);
  304. }
  305. /**
  306. * determines the plural form to use based on current language and given number
  307. *
  308. * From: https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
  309. *
  310. * @access protected
  311. * @static
  312. * @param int $n
  313. * @return int
  314. */
  315. protected static function _getPluralForm($n)
  316. {
  317. switch (self::$_language) {
  318. case 'ar':
  319. return $n === 0 ? 0 : ($n === 1 ? 1 : ($n === 2 ? 2 : ($n % 100 >= 3 && $n % 100 <= 10 ? 3 : ($n % 100 >= 11 ? 4 : 5))));
  320. case 'cs':
  321. case 'sk':
  322. return $n === 1 ? 0 : ($n >= 2 && $n <= 4 ? 1 : 2);
  323. case 'co':
  324. case 'fr':
  325. case 'oc':
  326. case 'tr':
  327. case 'zh':
  328. return $n > 1 ? 1 : 0;
  329. case 'he':
  330. return $n === 1 ? 0 : ($n === 2 ? 1 : (($n < 0 || $n > 10) && ($n % 10 === 0) ? 2 : 3));
  331. case 'id':
  332. case 'ja':
  333. case 'jbo':
  334. case 'th':
  335. return 0;
  336. case 'lt':
  337. return $n % 10 === 1 && $n % 100 !== 11 ? 0 : (($n % 10 >= 2 && $n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  338. case 'pl':
  339. return $n === 1 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  340. case 'ro':
  341. return $n === 1 ? 0 : (($n === 0 || ($n % 100 > 0 && $n % 100 < 20)) ? 1 : 2);
  342. case 'ru':
  343. case 'uk':
  344. return $n % 10 === 1 && $n % 100 != 11 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  345. case 'sl':
  346. return $n % 100 === 1 ? 1 : ($n % 100 === 2 ? 2 : ($n % 100 === 3 || $n % 100 === 4 ? 3 : 0));
  347. default:
  348. // bg, ca, de, el, en, es, et, fi, hu, it, nl, no, pt
  349. return $n !== 1 ? 1 : 0;
  350. }
  351. }
  352. /**
  353. * compares two language preference arrays and returns the preferred match
  354. *
  355. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  356. *
  357. * @access protected
  358. * @static
  359. * @param array $acceptedLanguages
  360. * @param array $availableLanguages
  361. * @return string
  362. */
  363. protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages)
  364. {
  365. $matches = array();
  366. $any = false;
  367. foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) {
  368. $acceptedQuality = floatval($acceptedQuality);
  369. if ($acceptedQuality === 0.0) {
  370. continue;
  371. }
  372. foreach ($availableLanguages as $availableValue) {
  373. $availableQuality = 1.0;
  374. foreach ($acceptedValues as $acceptedValue) {
  375. if ($acceptedValue === '*') {
  376. $any = true;
  377. }
  378. $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
  379. if ($matchingGrade > 0) {
  380. $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
  381. if (!isset($matches[$q])) {
  382. $matches[$q] = array();
  383. }
  384. if (!in_array($availableValue, $matches[$q])) {
  385. $matches[$q][] = $availableValue;
  386. }
  387. }
  388. }
  389. }
  390. }
  391. if (count($matches) === 0 && $any) {
  392. if (count($availableLanguages) > 0) {
  393. $matches['1.0'] = $availableLanguages;
  394. }
  395. }
  396. if (count($matches) === 0) {
  397. return self::$_languageFallback;
  398. }
  399. krsort($matches);
  400. $topmatches = current($matches);
  401. return current($topmatches);
  402. }
  403. /**
  404. * compare two language IDs and return the degree they match
  405. *
  406. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  407. *
  408. * @access protected
  409. * @static
  410. * @param string $a
  411. * @param string $b
  412. * @return float
  413. */
  414. protected static function _matchLanguage($a, $b)
  415. {
  416. $a = explode('-', $a);
  417. $b = explode('-', $b);
  418. for ($i = 0, $n = min(count($a), count($b)); $i < $n; ++$i) {
  419. if ($a[$i] !== $b[$i]) {
  420. break;
  421. }
  422. }
  423. return $i === 0 ? 0 : (float) $i / count($a);
  424. }
  425. }