I18n.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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.3.5
  11. */
  12. namespace PrivateBin;
  13. /**
  14. * I18n
  15. *
  16. * provides internationalization tools like translation, browser language detection, etc.
  17. */
  18. class I18n
  19. {
  20. /**
  21. * language
  22. *
  23. * @access protected
  24. * @static
  25. * @var string
  26. */
  27. protected static $_language = 'en';
  28. /**
  29. * language fallback
  30. *
  31. * @access protected
  32. * @static
  33. * @var string
  34. */
  35. protected static $_languageFallback = 'en';
  36. /**
  37. * language labels
  38. *
  39. * @access protected
  40. * @static
  41. * @var array
  42. */
  43. protected static $_languageLabels = array();
  44. /**
  45. * available languages
  46. *
  47. * @access protected
  48. * @static
  49. * @var array
  50. */
  51. protected static $_availableLanguages = array();
  52. /**
  53. * path to language files
  54. *
  55. * @access protected
  56. * @static
  57. * @var string
  58. */
  59. protected static $_path = '';
  60. /**
  61. * translation cache
  62. *
  63. * @access protected
  64. * @static
  65. * @var array
  66. */
  67. protected static $_translations = array();
  68. /**
  69. * translate a string, alias for translate()
  70. *
  71. * @access public
  72. * @static
  73. * @param string $messageId
  74. * @param mixed $args one or multiple parameters injected into placeholders
  75. * @return string
  76. */
  77. public static function _($messageId)
  78. {
  79. return forward_static_call_array('self::translate', func_get_args());
  80. }
  81. /**
  82. * translate a string
  83. *
  84. * @access public
  85. * @static
  86. * @param string $messageId
  87. * @param mixed $args one or multiple parameters injected into placeholders
  88. * @return string
  89. */
  90. public static function translate($messageId)
  91. {
  92. if (empty($messageId)) {
  93. return $messageId;
  94. }
  95. if (count(self::$_translations) === 0) {
  96. self::loadTranslations();
  97. }
  98. $messages = $messageId;
  99. if (is_array($messageId)) {
  100. $messageId = count($messageId) > 1 ? $messageId[1] : $messageId[0];
  101. }
  102. if (!array_key_exists($messageId, self::$_translations)) {
  103. self::$_translations[$messageId] = $messages;
  104. }
  105. $args = func_get_args();
  106. if (is_array(self::$_translations[$messageId])) {
  107. $number = (int) $args[1];
  108. $key = self::_getPluralForm($number);
  109. $max = count(self::$_translations[$messageId]) - 1;
  110. if ($key > $max) {
  111. $key = $max;
  112. }
  113. $args[0] = self::$_translations[$messageId][$key];
  114. $args[1] = $number;
  115. } else {
  116. $args[0] = self::$_translations[$messageId];
  117. }
  118. // encode any non-integer arguments and the message ID, if it doesn't contain a link
  119. $argsCount = count($args);
  120. if ($argsCount > 1) {
  121. for ($i = 0; $i < $argsCount; ++$i) {
  122. if (($i > 0 && !is_int($args[$i])) || strpos($args[0], '<a') === false) {
  123. $args[$i] = self::encode($args[$i]);
  124. }
  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. $i18n = dir(self::_getPath());
  182. while (false !== ($file = $i18n->read())) {
  183. if (preg_match('/^([a-z]{2}).json$/', $file, $match) === 1) {
  184. self::$_availableLanguages[] = $match[1];
  185. }
  186. }
  187. }
  188. return self::$_availableLanguages;
  189. }
  190. /**
  191. * detect the clients supported languages and return them ordered by preference
  192. *
  193. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  194. *
  195. * @access public
  196. * @static
  197. * @return array
  198. */
  199. public static function getBrowserLanguages()
  200. {
  201. $languages = array();
  202. if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
  203. $languageRanges = explode(',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  204. foreach ($languageRanges as $languageRange) {
  205. if (preg_match(
  206. '/(\*|[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})))?/',
  207. trim($languageRange), $match
  208. )) {
  209. if (!isset($match[2])) {
  210. $match[2] = '1.0';
  211. } else {
  212. $match[2] = (string) floatval($match[2]);
  213. }
  214. if (!isset($languages[$match[2]])) {
  215. $languages[$match[2]] = array();
  216. }
  217. $languages[$match[2]][] = strtolower($match[1]);
  218. }
  219. }
  220. krsort($languages);
  221. }
  222. return $languages;
  223. }
  224. /**
  225. * get currently loaded language
  226. *
  227. * @access public
  228. * @static
  229. * @return string
  230. */
  231. public static function getLanguage()
  232. {
  233. return self::$_language;
  234. }
  235. /**
  236. * get list of language labels
  237. *
  238. * Only for given language codes, otherwise all labels.
  239. *
  240. * @access public
  241. * @static
  242. * @param array $languages
  243. * @return array
  244. */
  245. public static function getLanguageLabels($languages = array())
  246. {
  247. $file = self::_getPath('languages.json');
  248. if (count(self::$_languageLabels) == 0 && is_readable($file)) {
  249. self::$_languageLabels = Json::decode(file_get_contents($file));
  250. }
  251. if (count($languages) == 0) {
  252. return self::$_languageLabels;
  253. }
  254. return array_intersect_key(self::$_languageLabels, array_flip($languages));
  255. }
  256. /**
  257. * set the default language
  258. *
  259. * @access public
  260. * @static
  261. * @param string $lang
  262. */
  263. public static function setLanguageFallback($lang)
  264. {
  265. if (in_array($lang, self::getAvailableLanguages())) {
  266. self::$_languageFallback = $lang;
  267. }
  268. }
  269. /**
  270. * get language file path
  271. *
  272. * @access protected
  273. * @static
  274. * @param string $file
  275. * @return string
  276. */
  277. protected static function _getPath($file = '')
  278. {
  279. if (strlen(self::$_path) == 0) {
  280. self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
  281. }
  282. return self::$_path . (strlen($file) ? DIRECTORY_SEPARATOR . $file : '');
  283. }
  284. /**
  285. * determines the plural form to use based on current language and given number
  286. *
  287. * From: https://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html
  288. *
  289. * @access protected
  290. * @static
  291. * @param int $n
  292. * @return int
  293. */
  294. protected static function _getPluralForm($n)
  295. {
  296. switch (self::$_language) {
  297. case 'cs':
  298. return $n == 1 ? 0 : ($n >= 2 && $n <= 4 ? 1 : 2);
  299. case 'fr':
  300. case 'oc':
  301. case 'zh':
  302. return $n > 1 ? 1 : 0;
  303. case 'he':
  304. return $n === 1 ? 0 : ($n === 2 ? 1 : (($n < 0 || $n > 10) && ($n % 10 === 0) ? 2 : 3));
  305. case 'id':
  306. return 0;
  307. case 'lt':
  308. return $n % 10 === 1 && $n % 100 !== 11 ? 0 : (($n % 10 >= 2 && $n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  309. case 'pl':
  310. return $n == 1 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  311. case 'ru':
  312. case 'uk':
  313. return $n % 10 == 1 && $n % 100 != 11 ? 0 : ($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  314. case 'sl':
  315. return $n % 100 == 1 ? 1 : ($n % 100 == 2 ? 2 : ($n % 100 == 3 || $n % 100 == 4 ? 3 : 0));
  316. // bg, ca, de, en, es, et, hu, it, nl, no, pt
  317. default:
  318. return $n != 1 ? 1 : 0;
  319. }
  320. }
  321. /**
  322. * compares two language preference arrays and returns the preferred match
  323. *
  324. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  325. *
  326. * @access protected
  327. * @static
  328. * @param array $acceptedLanguages
  329. * @param array $availableLanguages
  330. * @return string
  331. */
  332. protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages)
  333. {
  334. $matches = array();
  335. $any = false;
  336. foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) {
  337. $acceptedQuality = floatval($acceptedQuality);
  338. if ($acceptedQuality === 0.0) {
  339. continue;
  340. }
  341. foreach ($availableLanguages as $availableValue) {
  342. $availableQuality = 1.0;
  343. foreach ($acceptedValues as $acceptedValue) {
  344. if ($acceptedValue === '*') {
  345. $any = true;
  346. }
  347. $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
  348. if ($matchingGrade > 0) {
  349. $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
  350. if (!isset($matches[$q])) {
  351. $matches[$q] = array();
  352. }
  353. if (!in_array($availableValue, $matches[$q])) {
  354. $matches[$q][] = $availableValue;
  355. }
  356. }
  357. }
  358. }
  359. }
  360. if (count($matches) === 0 && $any) {
  361. if (count($availableLanguages) > 0) {
  362. $matches['1.0'] = $availableLanguages;
  363. }
  364. }
  365. if (count($matches) === 0) {
  366. return self::$_languageFallback;
  367. }
  368. krsort($matches);
  369. $topmatches = current($matches);
  370. return current($topmatches);
  371. }
  372. /**
  373. * compare two language IDs and return the degree they match
  374. *
  375. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  376. *
  377. * @access protected
  378. * @static
  379. * @param string $a
  380. * @param string $b
  381. * @return float
  382. */
  383. protected static function _matchLanguage($a, $b)
  384. {
  385. $a = explode('-', $a);
  386. $b = explode('-', $b);
  387. for ($i = 0, $n = min(count($a), count($b)); $i < $n; ++$i) {
  388. if ($a[$i] !== $b[$i]) {
  389. break;
  390. }
  391. }
  392. return $i === 0 ? 0 : (float) $i / count($a);
  393. }
  394. }