-
Notifications
You must be signed in to change notification settings - Fork 112
/
i18n.class.php
371 lines (310 loc) · 12 KB
/
i18n.class.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php
/*
* Fork this project on GitHub!
* https://github.com/Philipp15b/php-i18n
*
* License: MIT
*/
class i18n {
/**
* Language file path
* This is the path for the language files. You must use the '{LANGUAGE}' placeholder for the language or the script wont find any language files.
*
* @var string
*/
protected $filePath = './lang/lang_{LANGUAGE}.ini';
/**
* Cache file path
* This is the path for all the cache files. Best is an empty directory with no other files in it.
*
* @var string
*/
protected $cachePath = './langcache/';
/**
* Enable region variants
* Allow region variants such as "en-us", "en-gb" etc. If set to false, "en" will be provided.
* Defaults to false for backward compatibility.
*
* @var bool
*/
protected $isLangVariantEnabled = false;
/**
* Fallback language
* This is the language which is used when there is no language file for all other user languages. It has the lowest priority.
* Remember to create a language file for the fallback!!
*
* @var string
*/
protected $fallbackLang = 'en';
/**
* Merge in fallback language
* Whether to merge current language's strings with the strings of the fallback language ($fallbackLang).
*
* @var bool
*/
protected $mergeFallback = false;
/**
* The class name of the compiled class that contains the translated texts.
* @var string
*/
protected $prefix = 'L';
/**
* Forced language
* If you want to force a specific language define it here.
*
* @var string
*/
protected $forcedLang = NULL;
/**
* This is the separator used if you use sections in your ini-file.
* For example, if you have a string 'greeting' in a section 'welcomepage' you will can access it via 'L::welcomepage_greeting'.
* If you changed it to 'ABC' you could access your string via 'L::welcomepageABCgreeting'
*
* @var string
*/
protected $sectionSeparator = '_';
/*
* The following properties are only available after calling init().
*/
/**
* User languages
* These are the languages the user uses.
* Normally, if you use the getUserLangs-method this array will be filled in like this:
* 1. Forced language
* 2. Language in $_GET['lang']
* 3. Language in $_SESSION['lang']
* 4. HTTP_ACCEPT_LANGUAGE
* 5. Language in $_COOKIE['lang']
* 6. Fallback language
*
* @var array
*/
protected $userLangs = array();
protected $appliedLang = NULL;
protected $langFilePath = NULL;
protected $cacheFilePath = NULL;
protected $isInitialized = false;
/**
* Constructor
* The constructor sets all important settings. All params are optional, you can set the options via extra functions too.
*
* @param string [$filePath] This is the path for the language files. You must use the '{LANGUAGE}' placeholder for the language.
* @param string [$cachePath] This is the path for all the cache files. Best is an empty directory with no other files in it. No placeholders.
* @param string [$fallbackLang] This is the language which is used when there is no language file for all other user languages. It has the lowest priority.
* @param string [$prefix] The class name of the compiled class that contains the translated texts. Defaults to 'L'.
*/
public function __construct($filePath = NULL, $cachePath = NULL, $fallbackLang = NULL, $prefix = NULL) {
// Apply settings
if ($filePath != NULL) {
$this->filePath = $filePath;
}
if ($cachePath != NULL) {
$this->cachePath = $cachePath;
}
if ($fallbackLang != NULL) {
$this->fallbackLang = $fallbackLang;
}
if ($prefix != NULL) {
$this->prefix = $prefix;
}
}
public function init() {
if ($this->isInitialized()) {
throw new BadMethodCallException('This object from class ' . __CLASS__ . ' is already initialized. It is not possible to init one object twice!');
}
$this->isInitialized = true;
$this->userLangs = $this->getUserLangs();
// search for language file
$this->appliedLang = NULL;
foreach ($this->userLangs as $priority => $langcode) {
$this->langFilePath = $this->getConfigFilename($langcode);
if (file_exists($this->langFilePath)) {
$this->appliedLang = $langcode;
break;
}
}
if ($this->appliedLang == NULL) {
throw new RuntimeException('No language file was found.');
}
// search for cache file
$this->cacheFilePath = $this->cachePath . '/php_i18n_' . md5_file(__FILE__) . '_' . $this->prefix . '_' . $this->appliedLang . '.cache.php';
// whether we need to create a new cache file
$outdated = !file_exists($this->cacheFilePath) ||
filemtime($this->cacheFilePath) < filemtime($this->langFilePath) || // the language config was updated
($this->mergeFallback && filemtime($this->cacheFilePath) < filemtime($this->getConfigFilename($this->fallbackLang))); // the fallback language config was updated
if ($outdated) {
$config = $this->load($this->langFilePath);
if ($this->mergeFallback)
$config = array_replace_recursive($this->load($this->getConfigFilename($this->fallbackLang)), $config);
$compiled = "<?php class " . $this->prefix . " {\n"
. $this->compile($config)
. 'public static function __callStatic($string, $args) {' . "\n"
. ' return vsprintf(constant("self::" . $string), $args);'
. "\n}\n}\n"
. "function ".$this->prefix .'($string, $args=NULL) {'."\n"
. ' $return = constant("'.$this->prefix.'::".$string);'."\n"
. ' return $args ? vsprintf($return,$args) : $return;'
. "\n}";
if( ! is_dir($this->cachePath))
mkdir($this->cachePath, 0755, true);
if (file_put_contents($this->cacheFilePath, $compiled) === FALSE) {
throw new Exception("Could not write cache file to path '" . $this->cacheFilePath . "'. Is it writable?");
}
chmod($this->cacheFilePath, 0755);
}
require_once $this->cacheFilePath;
}
public function isInitialized() {
return $this->isInitialized;
}
public function getAppliedLang() {
return $this->appliedLang;
}
public function getCachePath() {
return $this->cachePath;
}
public function getLangVariantEnabled() {
return $this->isLangVariantEnabled;
}
public function getFallbackLang() {
return $this->fallbackLang;
}
public function setFilePath($filePath) {
$this->fail_after_init();
$this->filePath = $filePath;
}
public function setCachePath($cachePath) {
$this->fail_after_init();
$this->cachePath = $cachePath;
}
public function setLangVariantEnabled($isLangVariantEnabled) {
$this->fail_after_init();
$this->isLangVariantEnabled = $isLangVariantEnabled;
}
public function setFallbackLang($fallbackLang) {
$this->fail_after_init();
$this->fallbackLang = $fallbackLang;
}
public function setMergeFallback($mergeFallback) {
$this->fail_after_init();
$this->mergeFallback = $mergeFallback;
}
public function setPrefix($prefix) {
$this->fail_after_init();
$this->prefix = $prefix;
}
public function setForcedLang($forcedLang) {
$this->fail_after_init();
$this->forcedLang = $forcedLang;
}
public function setSectionSeparator($sectionSeparator) {
$this->fail_after_init();
$this->sectionSeparator = $sectionSeparator;
}
/**
* @deprecated Use setSectionSeparator.
*/
public function setSectionSeperator($sectionSeparator) {
$this->setSectionSeparator($sectionSeparator);
}
/**
* getUserLangs()
* Returns the user languages
* Normally it returns an array like this:
* 1. Forced language
* 2. Language in $_GET['lang']
* 3. Language in $_SESSION['lang']
* 4. HTTP_ACCEPT_LANGUAGE
* 5. Language in $_COOKIE['lang']
* 6. Fallback language
* Note: duplicate values are deleted.
*
* @return array with the user languages sorted by priority.
*/
public function getUserLangs() {
$userLangs = array();
// Highest priority: forced language
if ($this->forcedLang != NULL) {
$userLangs[] = $this->forcedLang;
}
// 2nd highest priority: GET parameter 'lang'
if (isset($_GET['lang']) && is_string($_GET['lang'])) {
$userLangs[] = $_GET['lang'];
}
// 3rd highest priority: SESSION parameter 'lang'
if (isset($_SESSION['lang']) && is_string($_SESSION['lang'])) {
$userLangs[] = $_SESSION['lang'];
}
// 4th highest priority: HTTP_ACCEPT_LANGUAGE
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $part) {
$userLang = strtolower(explode(';q=', $part)[0]);
// Trim language variant section if not configured to allow
if (!$this->isLangVariantEnabled)
$userLang = explode('-', $userLang)[0];
$userLangs[] = $userLang;
}
}
// 5th highest priority: COOKIE
if (isset($_COOKIE['lang'])) {
$userLangs[] = $_COOKIE['lang'];
}
// Lowest priority: fallback
$userLangs[] = $this->fallbackLang;
// remove duplicate elements
$userLangs = array_unique($userLangs);
// remove illegal userLangs
$userLangs2 = array();
foreach ($userLangs as $key => $value) {
// only allow a-z, A-Z and 0-9 and _ and -
if (preg_match('/^[a-zA-Z0-9_-]+$/', $value) === 1)
$userLangs2[$key] = $value;
}
return $userLangs2;
}
protected function getConfigFilename($langcode) {
return str_replace('{LANGUAGE}', $langcode, $this->filePath);
}
protected function load($filename) {
$ext = substr(strrchr($filename, '.'), 1);
switch ($ext) {
case 'properties':
case 'ini':
$config = parse_ini_file($filename, true);
break;
case 'yml':
case 'yaml':
$config = spyc_load_file($filename);
break;
case 'json':
$config = json_decode(file_get_contents($filename), true);
break;
default:
throw new InvalidArgumentException($ext . " is not a valid extension!");
}
return $config;
}
/**
* Recursively compile an associative array to PHP code.
*/
protected function compile($config, $prefix = '') {
$code = '';
foreach ($config as $key => $value) {
if (is_array($value)) {
$code .= $this->compile($value, $prefix . $key . $this->sectionSeparator);
} else {
$fullName = $prefix . $key;
if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $fullName)) {
throw new InvalidArgumentException(__CLASS__ . ": Cannot compile translation key " . $fullName . " because it is not a valid PHP identifier.");
}
$code .= 'const ' . $fullName . ' = \'' . str_replace('\'', '\\\'', $value) . "';\n";
}
}
return $code;
}
protected function fail_after_init() {
if ($this->isInitialized()) {
throw new BadMethodCallException('This ' . __CLASS__ . ' object is already initalized, so you can not change any settings.');
}
}
}