i18n.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. <?php
  2. /**
  3. * ZeroBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 0.22
  11. */
  12. /**
  13. * i18n
  14. *
  15. * provides internationalization tools like translation, browser language detection, etc.
  16. */
  17. class i18n
  18. {
  19. /**
  20. * language
  21. *
  22. * @access protected
  23. * @static
  24. * @var string
  25. */
  26. protected static $_language = 'en';
  27. /**
  28. * language fallback
  29. *
  30. * @access protected
  31. * @static
  32. * @var string
  33. */
  34. protected static $_languageFallback = 'en';
  35. /**
  36. * language labels
  37. *
  38. * @access protected
  39. * @static
  40. * @var array
  41. */
  42. protected static $_languageLabels = array();
  43. /**
  44. * available languages
  45. *
  46. * @access protected
  47. * @static
  48. * @var array
  49. */
  50. protected static $_availableLanguages = array();
  51. /**
  52. * path to language files
  53. *
  54. * @access protected
  55. * @static
  56. * @var string
  57. */
  58. protected static $_path = '';
  59. /**
  60. * translation cache
  61. *
  62. * @access protected
  63. * @static
  64. * @var array
  65. */
  66. protected static $_translations = array();
  67. /**
  68. * translate a string, alias for translate()
  69. *
  70. * @access public
  71. * @static
  72. * @param string $messageId
  73. * @param mixed $args one or multiple parameters injected into placeholders
  74. * @return string
  75. */
  76. public static function _($messageId)
  77. {
  78. return call_user_func_array(array('i18n', 'translate'), func_get_args());
  79. }
  80. /**
  81. * translate a string
  82. *
  83. * @access public
  84. * @static
  85. * @param string $messageId
  86. * @param mixed $args one or multiple parameters injected into placeholders
  87. * @return string
  88. */
  89. public static function translate($messageId)
  90. {
  91. if (empty($messageId)) return $messageId;
  92. if (count(self::$_translations) === 0) self::loadTranslations();
  93. $messages = $messageId;
  94. if (is_array($messageId))
  95. {
  96. $messageId = count($messageId) > 1 ? $messageId[1] : $messageId[0];
  97. }
  98. if (!array_key_exists($messageId, self::$_translations))
  99. {
  100. self::$_translations[$messageId] = $messages;
  101. }
  102. $args = func_get_args();
  103. if (is_array(self::$_translations[$messageId]))
  104. {
  105. $number = (int) $args[1];
  106. $key = self::_getPluralForm($number);
  107. $max = count(self::$_translations[$messageId]) - 1;
  108. if ($key > $max) $key = $max;
  109. $args[0] = self::$_translations[$messageId][$key];
  110. $args[1] = $number;
  111. }
  112. else
  113. {
  114. $args[0] = self::$_translations[$messageId];
  115. }
  116. return call_user_func_array('sprintf', $args);
  117. }
  118. /**
  119. * loads translations
  120. *
  121. * From: http://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  122. *
  123. * @access public
  124. * @static
  125. * @return void
  126. */
  127. public static function loadTranslations()
  128. {
  129. $availableLanguages = self::getAvailableLanguages();
  130. // check if the lang cookie was set and that language exists
  131. if (array_key_exists('lang', $_COOKIE) && in_array($_COOKIE['lang'], $availableLanguages))
  132. {
  133. $match = $_COOKIE['lang'];
  134. }
  135. // find a translation file matching the browsers language preferences
  136. else
  137. {
  138. $match = self::_getMatchingLanguage(
  139. self::getBrowserLanguages(), $availableLanguages
  140. );
  141. }
  142. // load translations
  143. self::$_language = $match;
  144. self::$_translations = ($match == 'en') ? array() : json_decode(
  145. file_get_contents(self::_getPath($match . '.json')),
  146. true
  147. );
  148. }
  149. /**
  150. * get list of available translations based on files found
  151. *
  152. * @access public
  153. * @static
  154. * @return array
  155. */
  156. public static function getAvailableLanguages()
  157. {
  158. if (count(self::$_availableLanguages) == 0)
  159. {
  160. $i18n = dir(self::_getPath());
  161. while (false !== ($file = $i18n->read()))
  162. {
  163. if (preg_match('/^([a-z]{2}).json$/', $file, $match) === 1)
  164. {
  165. self::$_availableLanguages[] = $match[1];
  166. }
  167. }
  168. self::$_availableLanguages[] = 'en';
  169. }
  170. return self::$_availableLanguages;
  171. }
  172. /**
  173. * detect the clients supported languages and return them ordered by preference
  174. *
  175. * From: http://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  176. *
  177. * @access public
  178. * @static
  179. * @return array
  180. */
  181. public static function getBrowserLanguages()
  182. {
  183. $languages = array();
  184. if (array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER))
  185. {
  186. $languageRanges = explode(',', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']));
  187. foreach ($languageRanges as $languageRange)
  188. {
  189. if (preg_match(
  190. '/(\*|[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})))?/',
  191. trim($languageRange), $match
  192. ))
  193. {
  194. if (!isset($match[2]))
  195. {
  196. $match[2] = '1.0';
  197. }
  198. else
  199. {
  200. $match[2] = (string) floatval($match[2]);
  201. }
  202. if (!isset($languages[$match[2]]))
  203. {
  204. $languages[$match[2]] = array();
  205. }
  206. $languages[$match[2]][] = strtolower($match[1]);
  207. }
  208. }
  209. krsort($languages);
  210. }
  211. return $languages;
  212. }
  213. /**
  214. * get currently loaded language
  215. *
  216. * @access public
  217. * @static
  218. * @return string
  219. */
  220. public static function getLanguage()
  221. {
  222. return self::$_language;
  223. }
  224. /**
  225. * get list of language labels
  226. *
  227. * Only for given language codes, otherwise all labels.
  228. *
  229. * @access public
  230. * @static
  231. * @param array $languages
  232. * @return array
  233. */
  234. public static function getLanguageLabels($languages = array())
  235. {
  236. $file = self::_getPath('languages.json');
  237. if (count(self::$_languageLabels) == 0 && is_readable($file))
  238. {
  239. self::$_languageLabels = json_decode(file_get_contents($file), true);
  240. }
  241. if (count($languages) == 0) return self::$_languageLabels;
  242. return array_intersect_key(self::$_languageLabels, array_flip($languages));
  243. }
  244. /**
  245. * set the default language
  246. *
  247. * @access public
  248. * @static
  249. * @param string $lang
  250. * @return void
  251. */
  252. public static function setLanguageFallback($lang)
  253. {
  254. if (in_array($lang, self::getAvailableLanguages()))
  255. self::$_languageFallback = $lang;
  256. }
  257. /**
  258. * get language file path
  259. *
  260. * @access protected
  261. * @static
  262. * @param string $file
  263. * @return string
  264. */
  265. protected static function _getPath($file = '')
  266. {
  267. if (strlen(self::$_path) == 0)
  268. {
  269. self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
  270. }
  271. return self::$_path . (strlen($file) ? DIRECTORY_SEPARATOR . $file : '');
  272. }
  273. /**
  274. * determines the plural form to use based on current language and given number
  275. *
  276. * From: http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html
  277. *
  278. * @access protected
  279. * @static
  280. * @param int $n
  281. * @return int
  282. */
  283. protected static function _getPluralForm($n)
  284. {
  285. switch (self::$_language) {
  286. case 'fr':
  287. case 'zh':
  288. return ($n > 1 ? 1 : 0);
  289. case 'pl':
  290. return ($n == 1 ? 0 : $n%10 >= 2 && $n %10 <=4 && ($n%100 < 10 || $n%100 >= 20) ? 1 : 2);
  291. // en, de
  292. default:
  293. return ($n != 1 ? 1 : 0);
  294. }
  295. }
  296. /**
  297. * compares two language preference arrays and returns the preferred match
  298. *
  299. * From: http://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  300. *
  301. * @access protected
  302. * @static
  303. * @param array $acceptedLanguages
  304. * @param array $availableLanguages
  305. * @return string
  306. */
  307. protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages) {
  308. $matches = array();
  309. $any = false;
  310. foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues)
  311. {
  312. $acceptedQuality = floatval($acceptedQuality);
  313. if ($acceptedQuality === 0.0) continue;
  314. foreach ($availableLanguages as $availableValue)
  315. {
  316. $availableQuality = 1.0;
  317. foreach ($acceptedValues as $acceptedValue)
  318. {
  319. if ($acceptedValue === '*')
  320. {
  321. $any = true;
  322. }
  323. $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
  324. if ($matchingGrade > 0)
  325. {
  326. $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
  327. if (!isset($matches[$q]))
  328. {
  329. $matches[$q] = array();
  330. }
  331. if (!in_array($availableValue, $matches[$q]))
  332. {
  333. $matches[$q][] = $availableValue;
  334. }
  335. }
  336. }
  337. }
  338. }
  339. if (count($matches) === 0 && $any)
  340. {
  341. if (count($availableLanguages) > 0)
  342. {
  343. $matches['1.0'] = $availableLanguages;
  344. }
  345. }
  346. if (count($matches) === 0)
  347. {
  348. return self::$_languageFallback;
  349. }
  350. krsort($matches);
  351. $topmatches = current($matches);
  352. return current($topmatches);
  353. }
  354. /**
  355. * compare two language IDs and return the degree they match
  356. *
  357. * From: http://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  358. *
  359. * @access protected
  360. * @static
  361. * @param string $a
  362. * @param string $b
  363. * @return float
  364. */
  365. protected static function _matchLanguage($a, $b) {
  366. $a = explode('-', $a);
  367. $b = explode('-', $b);
  368. for ($i=0, $n=min(count($a), count($b)); $i<$n; $i++)
  369. {
  370. if ($a[$i] !== $b[$i]) break;
  371. }
  372. return $i === 0 ? 0 : (float) $i / count($a);
  373. }
  374. }