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