You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.9 KiB

  1. <?php
  2. /**
  3. * @copyright NetMonsters <team@netmonsters.ru>
  4. * @link http://netmonsters.ru
  5. * @package Majestic
  6. * @subpackage Model
  7. * @since 2010-02-23
  8. * @version SVN: $Id$
  9. * @filesource $URL$
  10. */
  11. class I18N
  12. {
  13. static protected $domain = 'default';
  14. static protected $locales = array();
  15. static protected $bidi = array();
  16. static protected $langs = array();
  17. static protected $default = 'ru';
  18. static protected $lang = '';
  19. static protected $locale = '';
  20. /**
  21. * @param mixed $lang default language set
  22. */
  23. static public function init()
  24. {
  25. $config = Config::get(__CLASS__);
  26. self::$locales = $config['locales'];
  27. if (isset($config['bidi'])) {
  28. self::$bidi = $config['bidi'];
  29. }
  30. if (isset($config['default'])) {
  31. self::$default = $config['default'];
  32. }
  33. // language switching
  34. if ($lang = Env::Post('lang')) {
  35. self::setLang($lang);
  36. header('Location: ' . Env::getRequestUri());
  37. exit();
  38. }
  39. self::$lang = Env::Cookie('lang', self::getAcceptLanguage());
  40. self::setLang(self::$lang);
  41. self::$locale = self::$locales[self::$lang];
  42. putenv('LANG=' . self::$locale);
  43. setlocale(LC_ALL, self::$locale . '.UTF-8');
  44. bindtextdomain(self::$domain, PATH . '/' . APP . '/src/i18n/');
  45. textdomain(self::$domain);
  46. bind_textdomain_codeset(self::$domain, 'UTF-8');
  47. }
  48. static protected function getAcceptLanguage()
  49. {
  50. $lang = self::$default;
  51. if ($accept = Env::Server('HTTP_ACCEPT_LANGUAGE')) {
  52. $accept = explode(',', $accept);
  53. foreach ($accept as $a) {
  54. if (($pos = strpos($a, ';q=')) !== false) {
  55. $a = substr($a, 0, $pos);
  56. }
  57. if (($pos = strpos($a, '-')) !== false) {
  58. $a = substr($a, 0, $pos) . '_' . strtoupper(substr($a, $pos + 1));
  59. }
  60. if (isset(self::$locales[$a])) {
  61. $lang = $a;
  62. break;
  63. }
  64. if ($key = array_search($a, self::$locales)) {
  65. $lang = $key;
  66. break;
  67. }
  68. }
  69. }
  70. return $lang;
  71. }
  72. static protected function setLang($lang)
  73. {
  74. if (!array_key_exists($lang, self::$locales)) {
  75. $lang = self::$default;
  76. }
  77. Env::setCookie('lang', $lang, time()+60*60*24*30, '/');
  78. }
  79. static public function getLang()
  80. {
  81. return self::$lang;
  82. }
  83. static public function getDefaultLang()
  84. {
  85. return self::$default;
  86. }
  87. static public function setLangs($langs = array())
  88. {
  89. self::$langs = $langs;
  90. }
  91. static public function getLangs()
  92. {
  93. return self::$langs;
  94. }
  95. }