forked from miraheze/landing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetTranslations.php
95 lines (77 loc) · 2.27 KB
/
getTranslations.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
<?php
function getTranslation( $key ) {
if ( getLanguageCode() === 'qqx' ) {
return "({$key})";
}
switch ( json_last_error() ) {
case JSON_ERROR_NONE:
$error = false;
break;
case JSON_ERROR_DEPTH:
$error = 'The maximum stack depth has been exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$error = 'Invalid or malformed JSON';
break;
case JSON_ERROR_CTRL_CHAR:
$error = 'Control character error, possibly incorrectly encoded';
break;
case JSON_ERROR_SYNTAX:
$error = 'Syntax error';
break;
case JSON_ERROR_UTF8:
$error = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
case JSON_ERROR_UTF16:
$error = 'Malformed UTF-16 characters, possibly incorrectly encoded';
break;
default:
$error = 'There was an unknown problem with the JSON';
break;
}
if ( $error ) {
throw new Exception( $error );
}
return preg_replace( '/\[(.*?)[\|| ](.*?)\]/', '<a href="$1" title="$2">$2</a>',
nl2br( htmlspecialchars(
getLocalisation()[$key] ?? getFallback()[$key] ?? getDefault()[$key]
) )
);
}
function getLanguageCode() {
$languageCode = $_GET['lang'] ?? 'en';
if ( $languageCode === 'qqx' ) {
return $languageCode;
}
$basePath = __DIR__ . '/i18n/';
$realBasePath = realpath( $basePath );
$languagePath = $basePath . "{$languageCode}.json";
$realLanguagePath = realpath( $languagePath );
// Check for path traversal.
// Force language to 'en' if attempt was found.
if ( $realLanguagePath === false || strpos( $realLanguagePath, $realBasePath ) !== 0 ) {
$languageCode = 'en';
}
return $languageCode;
}
function getLocalisation() {
$lang = getLanguageCode();
if ( file_exists( __DIR__ . "/i18n/{$lang}.json" ) && $lang !== 'qqq' ) {
$translations = json_decode( file_get_contents( __DIR__ . "/i18n/{$lang}.json" ), true );
} else {
$translations = getDefault();
}
unset( $translations['@metadata'] );
return $translations;
}
function getFallback() {
$fallback = LOCALE_GET_PRIMARY_LANGUAGE( getLanguageCode() );
if ( file_exists( __DIR__ . "/i18n/{$fallback}.json" ) ) {
return json_decode( file_get_contents( __DIR__ . "/i18n/{$fallback}.json" ), true );
}
return getDefault();
}
function getDefault() {
return json_decode( file_get_contents( __DIR__ . '/i18n/en.json' ), true );
}
?>