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.

109 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. //var_dump(self::$locale);
  43. putenv('LANG=' . self::$locale);
  44. setlocale(LC_ALL, self::$locale . '.UTF-8');
  45. bindtextdomain(self::$domain, PATH . '/' . APP . '/src/i18n/');
  46. textdomain(self::$domain);
  47. bind_textdomain_codeset(self::$domain, 'UTF-8');
  48. }
  49. static protected function getAcceptLanguage()
  50. {
  51. $lang = self::$default;
  52. if ($accept = Env::Server('HTTP_ACCEPT_LANGUAGE')) {
  53. $accept = explode(',', $accept);
  54. foreach ($accept as $a) {
  55. if (($pos = strpos($a, ';q=')) !== false) {
  56. $a = substr($a, 0, $pos);
  57. }
  58. if (($pos = strpos($a, '-')) !== false) {
  59. $a = substr($a, 0, $pos) . '_' . strtoupper(substr($a, $pos + 1));
  60. }
  61. if (isset(self::$locales[$a])) {
  62. $lang = $a;
  63. break;
  64. }
  65. if ($key = array_search($a, self::$locales)) {
  66. $lang = $key;
  67. break;
  68. }
  69. }
  70. }
  71. return $lang;
  72. }
  73. static protected function setLang($lang)
  74. {
  75. if (!array_key_exists($lang, self::$locales)) {
  76. $lang = self::$default;
  77. }
  78. Env::setCookie('lang', $lang, time()+60*60*24*30, '/');
  79. }
  80. static public function getLang()
  81. {
  82. return self::$lang;
  83. }
  84. static public function setLangs($langs = array())
  85. {
  86. self::$langs = $langs;
  87. }
  88. static public function getLangs()
  89. {
  90. return self::$langs;
  91. }
  92. }