]> git.mxchange.org Git - friendica.git/blob - src/Core/L10n.php
05f710cd76c2f6cf603199ac71f50b73b3b1e2ef
[friendica.git] / src / Core / L10n.php
1 <?php
2 /**
3  * @file src/Core/L10n.php
4  */
5 namespace Friendica\Core;
6
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Core\System;
10
11 require_once 'boot.php';
12 require_once 'include/dba.php';
13
14 /**
15  * Provide Language, Translation, and Localization functions to the application
16  * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
17  */
18 class L10n extends BaseObject
19 {
20         /**
21          * A string indicating the current language used for translation:
22          * - Two-letter ISO 639-1 code.
23          * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
24          * @var string
25          */
26         private $lang = '';
27         /**
28          * A language code saved for later after pushLang() has been called.
29          *
30          * @var string
31          */
32         private $langSave = '';
33
34         /**
35          * An array of translation strings whose key is the neutral english message.
36          *
37          * @var array
38          */
39         private $strings = [];
40         /**
41          * An array of translation strings saved for later after pushLang() has been called.
42          *
43          * @var array
44          */
45         private $stringsSave = [];
46
47         /**
48          * Detects the language and sets the translation table
49          */
50         public static function init()
51         {
52                 $lang = self::detectLanguage();
53                 self::loadTranslationTable($lang);
54         }
55
56         /**
57          * Returns the current language code
58          *
59          * @return string Language code
60          */
61         public static function getCurrentLang()
62         {
63                 return self::$lang;
64         }
65
66         /**
67          * Sets the language session variable
68          */
69         public static function setSessionVariable()
70         {
71                 if (!empty($_SESSION['authenticated']) && empty($_SESSION['language'])) {
72                         $_SESSION['language'] = self::$lang;
73                         // we haven't loaded user data yet, but we need user language
74                         if (!empty($_SESSION['uid'])) {
75                                 $user = DBA::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
76                                 if (DBA::isResult($user)) {
77                                         $_SESSION['language'] = $user['language'];
78                                 }
79                         }
80                 }
81         }
82
83         public static function setLangFromSession()
84         {
85                 if (!empty($_SESSION['language']) && $_SESSION['language'] !== self::$lang) {
86                         self::loadTranslationTable($_SESSION['language']);
87                 }
88         }
89
90         /**
91          * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
92          * @return string The two-letter language code
93          */
94         public static function detectLanguage()
95         {
96                 $lang_list = [];
97
98                 if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
99                         // break up string into pieces (languages and q factors)
100                         preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);
101
102                         if (count($lang_parse[1])) {
103                                 // go through the list of prefered languages and add a generic language
104                                 // for sub-linguas (e.g. de-ch will add de) if not already in array
105                                 for ($i = 0; $i < count($lang_parse[1]); $i++) {
106                                         $lang_list[] = strtolower($lang_parse[1][$i]);
107                                         if (strlen($lang_parse[1][$i])>3) {
108                                                 $dashpos = strpos($lang_parse[1][$i], '-');
109                                                 if (!in_array(substr($lang_parse[1][$i], 0, $dashpos), $lang_list)) {
110                                                         $lang_list[] = strtolower(substr($lang_parse[1][$i], 0, $dashpos));
111                                                 }
112                                         }
113                                 }
114                         }
115                 }
116
117                 // check if we have translations for the preferred languages and pick the 1st that has
118                 foreach ($lang_list as $lang) {
119                         if ($lang === 'en' || (file_exists("view/lang/$lang") && is_dir("view/lang/$lang"))) {
120                                 $preferred = $lang;
121                                 break;
122                         }
123                 }
124                 if (isset($preferred)) {
125                         return $preferred;
126                 }
127
128                 // in case none matches, get the system wide configured language, or fall back to English
129                 return Config::get('system', 'language', 'en');
130         }
131
132         /**
133          * This function should be called before formatting messages in a specific target language
134          * different from the current user/system language.
135          *
136          * It saves the current translation strings in a separate variable and loads new translations strings.
137          *
138          * If called repeatedly, it won't save the translation strings again, just load the new ones.
139          *
140          * @see popLang()
141          * @brief Stores the current language strings and load a different language.
142          * @param string $lang Language code
143          */
144         public static function pushLang($lang)
145         {
146                 if (!self::$lang) {
147                         self::init();
148                 }
149
150                 if ($lang === self::$lang) {
151                         return;
152                 }
153
154                 if (!self::$langSave) {
155                         self::$langSave = self::$lang;
156                         self::$stringsSave = self::$strings;
157                 }
158
159                 self::loadTranslationTable($lang);
160         }
161
162         /**
163          * Restores the original user/system language after having used pushLang()
164          */
165         public static function popLang()
166         {
167                 if (!self::$langSave) {
168                         return;
169                 }
170
171                 self::$strings = self::$stringsSave;
172                 self::$lang = self::$langSave;
173
174                 self::$stringsSave = [];
175                 self::$langSave = '';
176         }
177
178         /**
179          * Loads string translation table
180          *
181          * First addon strings are loaded, then globals
182          *
183          * Uses an App object shim since all the strings files refer to $a->strings
184          *
185          * @param string $lang language code to load
186          */
187         private static function loadTranslationTable($lang)
188         {
189                 if ($lang === self::$lang) {
190                         return;
191                 }
192
193                 $a = new \stdClass();
194                 $a->strings = [];
195
196                 // load enabled addons strings
197                 $addons = DBA::select('addon', ['name'], ['installed' => true]);
198                 while ($p = DBA::fetch($addons)) {
199                         $name = $p['name'];
200                         if (file_exists("addon/$name/lang/$lang/strings.php")) {
201                                 include "addon/$name/lang/$lang/strings.php";
202                         }
203                 }
204
205                 if (file_exists("view/lang/$lang/strings.php")) {
206                         include "view/lang/$lang/strings.php";
207                 }
208
209                 self::$lang = $lang;
210                 self::$strings = $a->strings;
211
212                 unset($a);
213         }
214
215         /**
216          * @brief Return the localized version of the provided string with optional string interpolation
217          *
218          * This function takes a english string as parameter, and if a localized version
219          * exists for the current language, substitutes it before performing an eventual
220          * string interpolation (sprintf) with additional optional arguments.
221          *
222          * Usages:
223          * - L10n::t('This is an example')
224          * - L10n::t('URL %s returned no result', $url)
225          * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version)
226          *
227          * @param string $s
228          * @param array  $vars Variables to interpolate in the translation string
229          * @return string
230          */
231         public static function t($s, ...$vars)
232         {
233                 if (empty($s)) {
234                         return '';
235                 }
236
237                 if (!self::$lang) {
238                         self::init();
239                 }
240
241                 if (!empty(self::$strings[$s])) {
242                         $t = self::$strings[$s];
243                         $s = is_array($t) ? $t[0] : $t;
244                 }
245
246                 if (count($vars) > 0) {
247                         $s = sprintf($s, ...$vars);
248                 }
249
250                 return $s;
251         }
252
253         /**
254          * @brief Return the localized version of a singular/plural string with optional string interpolation
255          *
256          * This function takes two english strings as parameters, singular and plural, as
257          * well as a count. If a localized version exists for the current language, they
258          * are used instead. Discrimination between singular and plural is done using the
259          * localized function if any or the default one. Finally, a string interpolation
260          * is performed using the count as parameter.
261          *
262          * Usages:
263          * - L10n::tt('Like', 'Likes', $count)
264          * - L10n::tt("%s user deleted", "%s users deleted", count($users))
265          *
266          * @param string $singular
267          * @param string $plural
268          * @param int $count
269          * @return string
270          */
271         public static function tt($singular, $plural, $count)
272         {
273                 if (!is_numeric($count)) {
274                         logger('Non numeric count called by ' . System::callstack(20));
275                 }
276
277                 if (!self::$lang) {
278                         self::init();
279                 }
280
281                 if (!empty(self::$strings[$singular])) {
282                         $t = self::$strings[$singular];
283                         if (is_array($t)) {
284                                 $plural_function = 'string_plural_select_' . str_replace('-', '_', self::$lang);
285                                 if (function_exists($plural_function)) {
286                                         $i = $plural_function($count);
287                                 } else {
288                                         $i = self::stringPluralSelectDefault($count);
289                                 }
290
291                                 // for some languages there is only a single array item
292                                 if (!isset($t[$i])) {
293                                         $s = $t[0];
294                                 } else {
295                                         $s = $t[$i];
296                                 }
297                         } else {
298                                 $s = $t;
299                         }
300                 } elseif (self::stringPluralSelectDefault($count)) {
301                         $s = $plural;
302                 } else {
303                         $s = $singular;
304                 }
305
306                 $s = @sprintf($s, $count);
307
308                 return $s;
309         }
310
311         /**
312          * Provide a fallback which will not collide with a function defined in any language file
313          */
314         private static function stringPluralSelectDefault($n)
315         {
316                 return $n != 1;
317         }
318
319         /**
320          * @brief Return installed languages codes as associative array
321          *
322          * Scans the view/lang directory for the existence of "strings.php" files, and
323          * returns an alphabetical list of their folder names (@-char language codes).
324          * Adds the english language if it's missing from the list.
325          *
326          * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
327          *
328          * @return array
329          */
330         public static function getAvailableLanguages()
331         {
332                 $langs = [];
333                 $strings_file_paths = glob('view/lang/*/strings.php');
334
335                 if (is_array($strings_file_paths) && count($strings_file_paths)) {
336                         if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
337                                 $strings_file_paths[] = 'view/lang/en/strings.php';
338                         }
339                         asort($strings_file_paths);
340                         foreach ($strings_file_paths as $strings_file_path) {
341                                 $path_array = explode('/', $strings_file_path);
342                                 $langs[$path_array[2]] = $path_array[2];
343                         }
344                 }
345                 return $langs;
346         }
347 }