1
0

i18n.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. if (preg_match(
  189. '/(\*|[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})))?/',
  190. trim($languageRange), $match
  191. ))
  192. {
  193. if (!isset($match[2]))
  194. {
  195. $match[2] = '1.0';
  196. }
  197. else
  198. {
  199. $match[2] = (string) floatval($match[2]);
  200. }
  201. if (!isset($languages[$match[2]]))
  202. {
  203. $languages[$match[2]] = array();
  204. }
  205. $languages[$match[2]][] = strtolower($match[1]);
  206. }
  207. }
  208. krsort($languages);
  209. }
  210. return $languages;
  211. }
  212. /**
  213. * get currently loaded language
  214. *
  215. * @access public
  216. * @static
  217. * @return string
  218. */
  219. public static function getLanguage()
  220. {
  221. return self::$_language;
  222. }
  223. /**
  224. * get list of language labels
  225. *
  226. * Only for given language codes, otherwise all labels.
  227. *
  228. * @access public
  229. * @static
  230. * @param array $languages
  231. * @return array
  232. */
  233. public static function getLanguageLabels($languages = array())
  234. {
  235. $file = self::_getPath('languages.json');
  236. if (count(self::$_languageLabels) == 0 && is_readable($file))
  237. {
  238. self::$_languageLabels = json_decode(file_get_contents($file), true);
  239. }
  240. if (count($languages) == 0) return self::$_languageLabels;
  241. return array_intersect_key(self::$_languageLabels, array_flip($languages));
  242. }
  243. /**
  244. * set the default language
  245. *
  246. * @access public
  247. * @static
  248. * @param string $lang
  249. * @return void
  250. */
  251. public static function setLanguageFallback($lang)
  252. {
  253. if (in_array($lang, self::getAvailableLanguages()))
  254. self::$_languageFallback = $lang;
  255. }
  256. /**
  257. * get language file path
  258. *
  259. * @access protected
  260. * @static
  261. * @param string $file
  262. * @return string
  263. */
  264. protected static function _getPath($file = '')
  265. {
  266. if (strlen(self::$_path) == 0)
  267. {
  268. self::$_path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'i18n';
  269. }
  270. return self::$_path . (strlen($file) ? DIRECTORY_SEPARATOR . $file : '');
  271. }
  272. /**
  273. * determines the plural form to use based on current language and given number
  274. *
  275. * From: http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html
  276. *
  277. * @access protected
  278. * @static
  279. * @param int $n
  280. * @return int
  281. */
  282. protected static function _getPluralForm($n)
  283. {
  284. switch (self::$_language) {
  285. case 'fr':
  286. return ($n > 1 ? 1 : 0);
  287. case 'pl':
  288. return ($n == 1 ? 0 : $n%10 >= 2 && $n %10 <=4 && ($n%100 < 10 || $n%100 >= 20) ? 1 : 2);
  289. // en, de
  290. default:
  291. return ($n != 1 ? 1 : 0);
  292. }
  293. }
  294. /**
  295. * compares two language preference arrays and returns the preferred match
  296. *
  297. * From: http://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  298. *
  299. * @access protected
  300. * @static
  301. * @param array $acceptedLanguages
  302. * @param array $availableLanguages
  303. * @return string
  304. */
  305. protected static function _getMatchingLanguage($acceptedLanguages, $availableLanguages) {
  306. $matches = array();
  307. $any = false;
  308. foreach ($acceptedLanguages as $acceptedQuality => $acceptedValues) {
  309. $acceptedQuality = floatval($acceptedQuality);
  310. if ($acceptedQuality === 0.0) continue;
  311. foreach ($availableLanguages as $availableValue)
  312. {
  313. $availableQuality = 1.0;
  314. foreach ($acceptedValues as $acceptedValue)
  315. {
  316. if ($acceptedValue === '*')
  317. {
  318. $any = true;
  319. }
  320. $matchingGrade = self::_matchLanguage($acceptedValue, $availableValue);
  321. if ($matchingGrade > 0)
  322. {
  323. $q = (string) ($acceptedQuality * $availableQuality * $matchingGrade);
  324. if (!isset($matches[$q]))
  325. {
  326. $matches[$q] = array();
  327. }
  328. if (!in_array($availableValue, $matches[$q]))
  329. {
  330. $matches[$q][] = $availableValue;
  331. }
  332. }
  333. }
  334. }
  335. }
  336. if (count($matches) === 0 && $any)
  337. {
  338. if (count($availableLanguages) > 0)
  339. {
  340. $matches['1.0'] = $availableLanguages;
  341. }
  342. }
  343. if (count($matches) === 0)
  344. {
  345. return self::$_languageFallback;
  346. }
  347. krsort($matches);
  348. $topmatches = current($matches);
  349. return current($topmatches);
  350. }
  351. /**
  352. * compare two language IDs and return the degree they match
  353. *
  354. * From: http://stackoverflow.com/questions/3770513/detect-browser-language-in-php#3771447
  355. *
  356. * @access protected
  357. * @static
  358. * @param string $a
  359. * @param string $b
  360. * @return float
  361. */
  362. protected static function _matchLanguage($a, $b) {
  363. $a = explode('-', $a);
  364. $b = explode('-', $b);
  365. for ($i=0, $n=min(count($a), count($b)); $i<$n; $i++)
  366. {
  367. if ($a[$i] !== $b[$i]) break;
  368. }
  369. return $i === 0 ? 0 : (float) $i / count($a);
  370. }
  371. }