i18n.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 0.22
  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 call_user_func_array(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)) return $messageId;
  93. if (count(self::$_translations) === 0) self::loadTranslations();
  94. $messages = $messageId;
  95. if (is_array($messageId))
  96. {
  97. $messageId = count($messageId) > 1 ? $messageId[1] : $messageId[0];
  98. }
  99. if (!array_key_exists($messageId, self::$_translations))
  100. {
  101. self::$_translations[$messageId] = $messages;
  102. }
  103. $args = func_get_args();
  104. if (is_array(self::$_translations[$messageId]))
  105. {
  106. $number = (int) $args[1];
  107. $key = self::_getPluralForm($number);
  108. $max = count(self::$_translations[$messageId]) - 1;
  109. if ($key > $max) $key = $max;
  110. $args[0] = self::$_translations[$messageId][$key];
  111. $args[1] = $number;
  112. }
  113. else
  114. {
  115. $args[0] = self::$_translations[$messageId];
  116. }
  117. return call_user_func_array('sprintf', $args);
  118. }
  119. /**
  120. * loads translations
  121. *
  122. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  123. *
  124. * @access public
  125. * @static
  126. * @return void
  127. */
  128. public static function loadTranslations()
  129. {
  130. $availableLanguages = self::getAvailableLanguages();
  131. // check if the lang cookie was set and that language exists
  132. if (array_key_exists('lang', $_COOKIE) && in_array($_COOKIE['lang'], $availableLanguages))
  133. {
  134. $match = $availableLanguages[array_search($_COOKIE['lang'], $availableLanguages)];
  135. }
  136. // find a translation file matching the browsers language preferences
  137. else
  138. {
  139. $match = self::_getMatchingLanguage(
  140. self::getBrowserLanguages(), $availableLanguages
  141. );
  142. }
  143. // load translations
  144. self::$_language = $match;
  145. self::$_translations = ($match == 'en') ? array() : json_decode(
  146. file_get_contents(self::_getPath($match . '.json')),
  147. true
  148. );
  149. }
  150. /**
  151. * get list of available translations based on files found
  152. *
  153. * @access public
  154. * @static
  155. * @return array
  156. */
  157. public static function getAvailableLanguages()
  158. {
  159. if (count(self::$_availableLanguages) == 0)
  160. {
  161. $i18n = dir(self::_getPath());
  162. while (false !== ($file = $i18n->read()))
  163. {
  164. if (preg_match('/^([a-z]{2}).json$/', $file, $match) === 1)
  165. {
  166. self::$_availableLanguages[] = $match[1];
  167. }
  168. }
  169. self::$_availableLanguages[] = 'en';
  170. }
  171. return self::$_availableLanguages;
  172. }
  173. /**
  174. * detect the clients supported languages and return them ordered by preference
  175. *
  176. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  177. *
  178. * @access public
  179. * @static
  180. * @return array
  181. */
  182. public static function getBrowserLanguages()
  183. {
  184. $languages = array();
  185. if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER))
  186. {
  187. $languageRanges = explode(',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  188. foreach ($languageRanges as $languageRange)
  189. {
  190. if (preg_match(
  191. '/(\*|[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})))?/',
  192. trim($languageRange), $match
  193. ))
  194. {
  195. if (!isset($match[2]))
  196. {
  197. $match[2] = '1.0';
  198. }
  199. else
  200. {
  201. $match[2] = (string) floatval($match[2]);
  202. }
  203. if (!isset($languages[$match[2]]))
  204. {
  205. $languages[$match[2]] = array();
  206. }
  207. $languages[$match[2]][] = strtolower($match[1]);
  208. }
  209. }
  210. krsort($languages);
  211. }
  212. return $languages;
  213. }
  214. /**
  215. * get currently loaded language
  216. *
  217. * @access public
  218. * @static
  219. * @return string
  220. */
  221. public static function getLanguage()
  222. {
  223. return self::$_language;
  224. }
  225. /**
  226. * get list of language labels
  227. *
  228. * Only for given language codes, otherwise all labels.
  229. *
  230. * @access public
  231. * @static
  232. * @param array $languages
  233. * @return array
  234. */
  235. public static function getLanguageLabels($languages = array())
  236. {
  237. $file = self::_getPath('languages.json');
  238. if (count(self::$_languageLabels) == 0 && is_readable($file))
  239. {
  240. self::$_languageLabels = json_decode(file_get_contents($file), true);
  241. }
  242. if (count($languages) == 0) return self::$_languageLabels;
  243. return array_intersect_key(self::$_languageLabels, array_flip($languages));
  244. }
  245. /**
  246. * set the default language
  247. *
  248. * @access public
  249. * @static
  250. * @param string $lang
  251. * @return void
  252. */
  253. public static function setLanguageFallback($lang)
  254. {
  255. if (in_array($lang, self::getAvailableLanguages()))
  256. self::$_languageFallback = $lang;
  257. }
  258. /**
  259. * get language file path
  260. *
  261. * @access protected
  262. * @static
  263. * @param string $file
  264. * @return string
  265. */
  266. protected static function _getPath($file = '')
  267. {
  268. if (strlen(self::$_path) == 0)
  269. {
  270. self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
  271. }
  272. return self::$_path . (strlen($file) ? DIRECTORY_SEPARATOR . $file : '');
  273. }
  274. /**
  275. * determines the plural form to use based on current language and given number
  276. *
  277. * From: http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html
  278. *
  279. * @access protected
  280. * @static
  281. * @param int $n
  282. * @return int
  283. */
  284. protected static function _getPluralForm($n)
  285. {
  286. switch (self::$_language) {
  287. case 'fr':
  288. case 'zh':
  289. return ($n > 1 ? 1 : 0);
  290. case 'pl':
  291. return ($n == 1 ? 0 : $n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20) ? 1 : 2);
  292. // en, de
  293. default:
  294. return ($n != 1 ? 1 : 0);
  295. }
  296. }
  297. /**
  298. * compares two language preference arrays and returns the preferred match
  299. *
  300. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  301. *
  302. * @access protected
  303. * @static
  304. * @param array $acceptedLanguages
  305. * @param array $availableLanguages
  306. * @return string
  307. */
  308. protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages) {
  309. $matches = array();
  310. $any = false;
  311. foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues)
  312. {
  313. $acceptedQuality = floatval($acceptedQuality);
  314. if ($acceptedQuality === 0.0) continue;
  315. foreach ($availableLanguages as $availableValue)
  316. {
  317. $availableQuality = 1.0;
  318. foreach ($acceptedValues as $acceptedValue)
  319. {
  320. if ($acceptedValue === '*')
  321. {
  322. $any = true;
  323. }
  324. $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
  325. if ($matchingGrade > 0)
  326. {
  327. $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
  328. if (!isset($matches[$q]))
  329. {
  330. $matches[$q] = array();
  331. }
  332. if (!in_array($availableValue, $matches[$q]))
  333. {
  334. $matches[$q][] = $availableValue;
  335. }
  336. }
  337. }
  338. }
  339. }
  340. if (count($matches) === 0 && $any)
  341. {
  342. if (count($availableLanguages) > 0)
  343. {
  344. $matches['1.0'] = $availableLanguages;
  345. }
  346. }
  347. if (count($matches) === 0)
  348. {
  349. return self::$_languageFallback;
  350. }
  351. krsort($matches);
  352. $topmatches = current($matches);
  353. return current($topmatches);
  354. }
  355. /**
  356. * compare two language IDs and return the degree they match
  357. *
  358. * From: https://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  359. *
  360. * @access protected
  361. * @static
  362. * @param string $a
  363. * @param string $b
  364. * @return float
  365. */
  366. protected static function _matchLanguage($a, $b) {
  367. $a = explode('-', $a);
  368. $b = explode('-', $b);
  369. for ($i=0, $n = min(count($a), count($b)); $i < $n; ++$i)
  370. {
  371. if ($a[$i] !== $b[$i]) break;
  372. }
  373. return $i === 0 ? 0 : (float) $i / count($a);
  374. }
  375. }