i18n.php 10 KB

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