I18n.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. <?php
  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. * @version 1.7.1
  11. */
  12. namespace PrivateBin;
  13. use AppendIterator;
  14. use GlobIterator;
  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 = array();
  46. /**
  47. * available languages
  48. *
  49. * @access protected
  50. * @static
  51. * @var array
  52. */
  53. protected static $_availableLanguages = array();
  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 = array();
  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 and the message ID, if it doesn't contain a link
  121. $argsCount = count($args);
  122. for ($i = 0; $i < $argsCount; ++$i) {
  123. if ($i > 0 ? !is_int($args[$i]) : strpos($args[0], '<a') === false) {
  124. $args[$i] = self::encode($args[$i]);
  125. }
  126. }
  127. return call_user_func_array('sprintf', $args);
  128. }
  129. /**
  130. * encode HTML entities for output into an HTML5 document
  131. *
  132. * @access public
  133. * @static
  134. * @param string $string
  135. * @return string
  136. */
  137. public static function encode($string)
  138. {
  139. return htmlspecialchars($string, ENT_QUOTES | ENT_HTML5 | ENT_DISALLOWED, 'UTF-8', false);
  140. }
  141. /**
  142. * loads translations
  143. *
  144. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  145. *
  146. * @access public
  147. * @static
  148. */
  149. public static function loadTranslations()
  150. {
  151. $availableLanguages = self::getAvailableLanguages();
  152. // check if the lang cookie was set and that language exists
  153. if (
  154. array_key_exists('lang', $_COOKIE) &&
  155. ($key = array_search($_COOKIE['lang'], $availableLanguages)) !== false
  156. ) {
  157. $match = $availableLanguages[$key];
  158. }
  159. // find a translation file matching the browsers language preferences
  160. else {
  161. $match = self::_getMatchingLanguage(
  162. self::getBrowserLanguages(), $availableLanguages
  163. );
  164. }
  165. // load translations
  166. self::$_language = $match;
  167. self::$_translations = ($match == 'en') ? array() : Json::decode(
  168. file_get_contents(self::_getPath($match . '.json'))
  169. );
  170. }
  171. /**
  172. * get list of available translations based on files found
  173. *
  174. * @access public
  175. * @static
  176. * @return array
  177. */
  178. public static function getAvailableLanguages()
  179. {
  180. if (count(self::$_availableLanguages) == 0) {
  181. self::$_availableLanguages[] = 'en'; // en.json is not part of the release archive
  182. $languageIterator = new AppendIterator();
  183. $languageIterator->append(new GlobIterator(self::_getPath('??.json')));
  184. $languageIterator->append(new GlobIterator(self::_getPath('???.json'))); // for jbo
  185. foreach ($languageIterator as $file) {
  186. $language = $file->getBasename('.json');
  187. if ($language != 'en') {
  188. self::$_availableLanguages[] = $language;
  189. }
  190. }
  191. }
  192. return self::$_availableLanguages;
  193. }
  194. /**
  195. * detect the clients supported languages and return them ordered by preference
  196. *
  197. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  198. *
  199. * @access public
  200. * @static
  201. * @return array
  202. */
  203. public static function getBrowserLanguages()
  204. {
  205. $languages = array();
  206. if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
  207. $languageRanges = explode(',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  208. foreach ($languageRanges as $languageRange) {
  209. if (preg_match(
  210. '/(\*|[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})))?/',
  211. trim($languageRange), $match
  212. )) {
  213. if (!isset($match[2])) {
  214. $match[2] = '1.0';
  215. } else {
  216. $match[2] = (string) floatval($match[2]);
  217. }
  218. if (!isset($languages[$match[2]])) {
  219. $languages[$match[2]] = array();
  220. }
  221. $languages[$match[2]][] = strtolower($match[1]);
  222. }
  223. }
  224. krsort($languages);
  225. }
  226. return $languages;
  227. }
  228. /**
  229. * get currently loaded language
  230. *
  231. * @access public
  232. * @static
  233. * @return string
  234. */
  235. public static function getLanguage()
  236. {
  237. return self::$_language;
  238. }
  239. /**
  240. * get list of language labels
  241. *
  242. * Only for given language codes, otherwise all labels.
  243. *
  244. * @access public
  245. * @static
  246. * @param array $languages
  247. * @return array
  248. */
  249. public static function getLanguageLabels($languages = array())
  250. {
  251. $file = self::_getPath('languages.json');
  252. if (count(self::$_languageLabels) == 0 && is_readable($file)) {
  253. self::$_languageLabels = Json::decode(file_get_contents($file));
  254. }
  255. if (count($languages) == 0) {
  256. return self::$_languageLabels;
  257. }
  258. return array_intersect_key(self::$_languageLabels, array_flip($languages));
  259. }
  260. /**
  261. * determines if the current language is written right-to-left (RTL)
  262. *
  263. * @access public
  264. * @static
  265. * @return bool
  266. */
  267. public static function isRtl()
  268. {
  269. return in_array(self::$_language, array('ar', 'he'));
  270. }
  271. /**
  272. * set the default language
  273. *
  274. * @access public
  275. * @static
  276. * @param string $lang
  277. */
  278. public static function setLanguageFallback($lang)
  279. {
  280. if (in_array($lang, self::getAvailableLanguages())) {
  281. self::$_languageFallback = $lang;
  282. }
  283. }
  284. /**
  285. * get language file path
  286. *
  287. * @access protected
  288. * @static
  289. * @param string $file
  290. * @return string
  291. */
  292. protected static function _getPath($file = '')
  293. {
  294. if (empty(self::$_path)) {
  295. self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
  296. }
  297. return self::$_path . (empty($file) ? '' : DIRECTORY_SEPARATOR . $file);
  298. }
  299. /**
  300. * determines the plural form to use based on current language and given number
  301. *
  302. * From: https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
  303. *
  304. * @access protected
  305. * @static
  306. * @param int $n
  307. * @return int
  308. */
  309. protected static function _getPluralForm($n)
  310. {
  311. switch (self::$_language) {
  312. case 'ar':
  313. return $n === 0 ? 0 : ($n === 1 ? 1 : ($n === 2 ? 2 : ($n % 100 >= 3 && $n % 100 <= 10 ? 3 : ($n % 100 >= 11 ? 4 : 5))));
  314. case 'cs':
  315. case 'sk':
  316. return $n === 1 ? 0 : ($n >= 2 && $n <= 4 ? 1 : 2);
  317. case 'co':
  318. case 'fr':
  319. case 'oc':
  320. case 'tr':
  321. case 'zh':
  322. return $n > 1 ? 1 : 0;
  323. case 'he':
  324. return $n === 1 ? 0 : ($n === 2 ? 1 : (($n < 0 || $n > 10) && ($n % 10 === 0) ? 2 : 3));
  325. case 'id':
  326. case 'ja':
  327. case 'jbo':
  328. case 'th':
  329. return 0;
  330. case 'lt':
  331. return $n % 10 === 1 && $n % 100 !== 11 ? 0 : (($n % 10 >= 2 && $n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  332. case 'pl':
  333. return $n === 1 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  334. case 'ro':
  335. return $n === 1 ? 0 : (($n === 0 || ($n % 100 > 0 && $n % 100 < 20)) ? 1 : 2);
  336. case 'ru':
  337. case 'uk':
  338. return $n % 10 === 1 && $n % 100 != 11 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  339. case 'sl':
  340. return $n % 100 === 1 ? 1 : ($n % 100 === 2 ? 2 : ($n % 100 === 3 || $n % 100 === 4 ? 3 : 0));
  341. default:
  342. // bg, ca, de, el, en, es, et, fi, hu, it, nl, no, pt
  343. return $n !== 1 ? 1 : 0;
  344. }
  345. }
  346. /**
  347. * compares two language preference arrays and returns the preferred match
  348. *
  349. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  350. *
  351. * @access protected
  352. * @static
  353. * @param array $acceptedLanguages
  354. * @param array $availableLanguages
  355. * @return string
  356. */
  357. protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages)
  358. {
  359. $matches = array();
  360. $any = false;
  361. foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) {
  362. $acceptedQuality = floatval($acceptedQuality);
  363. if ($acceptedQuality === 0.0) {
  364. continue;
  365. }
  366. foreach ($availableLanguages as $availableValue) {
  367. $availableQuality = 1.0;
  368. foreach ($acceptedValues as $acceptedValue) {
  369. if ($acceptedValue === '*') {
  370. $any = true;
  371. }
  372. $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
  373. if ($matchingGrade > 0) {
  374. $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
  375. if (!isset($matches[$q])) {
  376. $matches[$q] = array();
  377. }
  378. if (!in_array($availableValue, $matches[$q])) {
  379. $matches[$q][] = $availableValue;
  380. }
  381. }
  382. }
  383. }
  384. }
  385. if (count($matches) === 0 && $any) {
  386. if (count($availableLanguages) > 0) {
  387. $matches['1.0'] = $availableLanguages;
  388. }
  389. }
  390. if (count($matches) === 0) {
  391. return self::$_languageFallback;
  392. }
  393. krsort($matches);
  394. $topmatches = current($matches);
  395. return current($topmatches);
  396. }
  397. /**
  398. * compare two language IDs and return the degree they match
  399. *
  400. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  401. *
  402. * @access protected
  403. * @static
  404. * @param string $a
  405. * @param string $b
  406. * @return float
  407. */
  408. protected static function _matchLanguage($a, $b)
  409. {
  410. $a = explode('-', $a);
  411. $b = explode('-', $b);
  412. for ($i = 0, $n = min(count($a), count($b)); $i < $n; ++$i) {
  413. if ($a[$i] !== $b[$i]) {
  414. break;
  415. }
  416. }
  417. return $i === 0 ? 0 : (float) $i / count($a);
  418. }
  419. }