-
Notifications
You must be signed in to change notification settings - Fork 54
/
lang.php
147 lines (126 loc) · 2.51 KB
/
lang.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
<?php
/*
+--------------------------------------------------------------------------
| WeCenter [#RELEASE_VERSION#]
| ========================================
| by WeCenter Software
| © 2011 - 2014 WeCenter. All Rights Reserved
| http://www.wecenter.com
| ========================================
| Support: WeCenter@qq.com
|
+---------------------------------------------------------------------------
*/
class core_lang
{
private $messages = [];
private $lang = null;
public function __construct()
{
if (defined('G_SYSTEM_LANG') AND !!G_SYSTEM_LANG)
{
$this->init_language(G_SYSTEM_LANG);
return;
}
$preferred = $this->parse_accept_language();
foreach ($preferred as $lang)
{
if ($this->init_language($lang))
{
return;
}
}
if (defined('G_DEFAULT_LANG') AND !!G_DEFAULT_LANG)
{
$this->init_language(G_DEFAULT_LANG);
return;
}
}
private function parse_accept_language($limit = 10)
{
$result = [];
$accept_language = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? null;
if (!$accept_language)
{
return $result;
}
$i = 0;
$locales = explode(',', $accept_language, $limit);
foreach ($locales as $locale)
{
$i++;
if (!$locale)
{
continue;
}
if ($i == $limit)
{
$locale = explode(',', $locale, 2)[0]; // 丢弃超出 $limit
}
$locale = explode(';', $locale, 2)[0]; // 偷懒不处理 q=
$locale = trim($locale);
if (!$locale)
{
continue;
}
$result[] = $locale;
}
return $result;
}
private function init_language($lang)
{
if (!is_string($lang))
{
return false;
}
$language_file = ROOT_PATH . 'language/' . $lang . '.php';
if (!file_exists($language_file))
{
return false;
}
require $language_file;
if (!is_array($language))
{
return false;
}
$this->messages = $language;
$this->lang = $lang;
return true;
}
public function get_language()
{
return $this->lang;
}
public function translate($string, $replace = null)
{
$search = '%s';
if (is_array($replace))
{
$search = array();
for ($i=0; $i<count($replace); $i++)
{
$search[] = '%s' . $i;
};
}
if ($translate = $this->messages[trim($string)] ?? null)
{
if (isset($replace))
{
$translate = str_replace($search, $replace, $translate);
}
return $translate;
}
else
{
if (isset($replace))
{
$string = str_replace($search, $replace, $string);
}
return $string;
}
}
public function _t($string, $replace = null)
{
return $this->translate($string, $replace);
}
}