]> git.mxchange.org Git - friendica.git/blob - src/Core/L10n.php
2fcf6bf44a3067a92ebc32c33af53814d6de812e
[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
10 /**
11  * Provide Language, Translation, and Localization functions to the application
12  * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
13  */
14 class L10n extends BaseObject
15 {
16         /**
17          * A string indicating the current language used for translation:
18          * - Two-letter ISO 639-1 code.
19          * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
20          * @var string
21          */
22         private static $lang = '';
23         /**
24          * A language code saved for later after pushLang() has been called.
25          *
26          * @var string
27          */
28         private static $langSave = '';
29
30         /**
31          * An array of translation strings whose key is the neutral english message.
32          *
33          * @var array
34          */
35         private static $strings = [];
36         /**
37          * An array of translation strings saved for later after pushLang() has been called.
38          *
39          * @var array
40          */
41         private static $stringsSave = [];
42
43         /**
44          * Detects the language and sets the translation table
45          */
46         public static function init()
47         {
48                 $lang = self::detectLanguage();
49                 self::loadTranslationTable($lang);
50         }
51
52         /**
53          * Returns the current language code
54          *
55          * @return string Language code
56          */
57         public static function getCurrentLang()
58         {
59                 return self::$lang;
60         }
61
62         /**
63          * Sets the language session variable
64          */
65         public static function setSessionVariable()
66         {
67                 if (!empty($_SESSION['authenticated']) && empty($_SESSION['language'])) {
68                         $_SESSION['language'] = self::$lang;
69                         // we haven't loaded user data yet, but we need user language
70                         if (!empty($_SESSION['uid'])) {
71                                 $user = DBA::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
72                                 if (DBA::isResult($user)) {
73                                         $_SESSION['language'] = $user['language'];
74                                 }
75                         }
76                 }
77                 //if $_GET['lang'] is set force $_GET['lang']
78                 if (isset($_GET['lang'])) {
79                         $_SESSION['language'] = $_GET['lang'];
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                 //if $_GET['lang'] is set force $_GET['lang']
117                 if (isset($_GET['lang'])) {
118                         $lang_list = [$_GET['lang']];
119                 }
120                 // check if we have translations for the preferred languages and pick the 1st that has
121                 foreach ($lang_list as $lang) {
122                         if ($lang === 'en' || (file_exists("view/lang/$lang") && is_dir("view/lang/$lang"))) {
123                                 $preferred = $lang;
124                                 break;
125                         }
126                 }
127                 if (isset($preferred)) {
128                         return $preferred;
129                 }
130
131                 // in case none matches, get the system wide configured language, or fall back to English
132                 return Config::get('system', 'language', 'en');
133         }
134
135         /**
136          * This function should be called before formatting messages in a specific target language
137          * different from the current user/system language.
138          *
139          * It saves the current translation strings in a separate variable and loads new translations strings.
140          *
141          * If called repeatedly, it won't save the translation strings again, just load the new ones.
142          *
143          * @see popLang()
144          * @brief Stores the current language strings and load a different language.
145          * @param string $lang Language code
146          */
147         public static function pushLang($lang)
148         {
149                 if (!self::$lang) {
150                         self::init();
151                 }
152
153                 if ($lang === self::$lang) {
154                         return;
155                 }
156
157                 if (!self::$langSave) {
158                         self::$langSave = self::$lang;
159                         self::$stringsSave = self::$strings;
160                 }
161
162                 self::loadTranslationTable($lang);
163         }
164
165         /**
166          * Restores the original user/system language after having used pushLang()
167          */
168         public static function popLang()
169         {
170                 if (!self::$langSave) {
171                         return;
172                 }
173
174                 self::$strings = self::$stringsSave;
175                 self::$lang = self::$langSave;
176
177                 self::$stringsSave = [];
178                 self::$langSave = '';
179         }
180
181         /**
182          * Loads string translation table
183          *
184          * First addon strings are loaded, then globals
185          *
186          * Uses an App object shim since all the strings files refer to $a->strings
187          *
188          * @param string $lang language code to load
189          */
190         private static function loadTranslationTable($lang)
191         {
192                 if ($lang === self::$lang) {
193                         return;
194                 }
195
196                 $a = new \stdClass();
197                 $a->strings = [];
198
199                 // load enabled addons strings
200                 $addons = DBA::select('addon', ['name'], ['installed' => true]);
201                 while ($p = DBA::fetch($addons)) {
202                         $name = $p['name'];
203                         if (file_exists("addon/$name/lang/$lang/strings.php")) {
204                                 include "addon/$name/lang/$lang/strings.php";
205                         }
206                 }
207
208                 if (file_exists("view/lang/$lang/strings.php")) {
209                         include "view/lang/$lang/strings.php";
210                 }
211
212                 self::$lang = $lang;
213                 self::$strings = $a->strings;
214
215                 unset($a);
216         }
217
218         /**
219          * @brief Return the localized version of the provided string with optional string interpolation
220          *
221          * This function takes a english string as parameter, and if a localized version
222          * exists for the current language, substitutes it before performing an eventual
223          * string interpolation (sprintf) with additional optional arguments.
224          *
225          * Usages:
226          * - L10n::t('This is an example')
227          * - L10n::t('URL %s returned no result', $url)
228          * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version)
229          *
230          * @param string $s
231          * @param array  $vars Variables to interpolate in the translation string
232          * @return string
233          */
234         public static function t($s, ...$vars)
235         {
236                 if (empty($s)) {
237                         return '';
238                 }
239
240                 if (!self::$lang) {
241                         self::init();
242                 }
243
244                 if (!empty(self::$strings[$s])) {
245                         $t = self::$strings[$s];
246                         $s = is_array($t) ? $t[0] : $t;
247                 }
248
249                 if (count($vars) > 0) {
250                         $s = sprintf($s, ...$vars);
251                 }
252
253                 return $s;
254         }
255
256         /**
257          * @brief Return the localized version of a singular/plural string with optional string interpolation
258          *
259          * This function takes two english strings as parameters, singular and plural, as
260          * well as a count. If a localized version exists for the current language, they
261          * are used instead. Discrimination between singular and plural is done using the
262          * localized function if any or the default one. Finally, a string interpolation
263          * is performed using the count as parameter.
264          *
265          * Usages:
266          * - L10n::tt('Like', 'Likes', $count)
267          * - L10n::tt("%s user deleted", "%s users deleted", count($users))
268          *
269          * @param string $singular
270          * @param string $plural
271          * @param int $count
272          * @return string
273          */
274         public static function tt($singular, $plural, $count)
275         {
276                 if (!is_numeric($count)) {
277                         Logger::log('Non numeric count called by ' . System::callstack(20));
278                 }
279
280                 if (!self::$lang) {
281                         self::init();
282                 }
283
284                 if (!empty(self::$strings[$singular])) {
285                         $t = self::$strings[$singular];
286                         if (is_array($t)) {
287                                 $plural_function = 'string_plural_select_' . str_replace('-', '_', self::$lang);
288                                 if (function_exists($plural_function)) {
289                                         $i = $plural_function($count);
290                                 } else {
291                                         $i = self::stringPluralSelectDefault($count);
292                                 }
293
294                                 // for some languages there is only a single array item
295                                 if (!isset($t[$i])) {
296                                         $s = $t[0];
297                                 } else {
298                                         $s = $t[$i];
299                                 }
300                         } else {
301                                 $s = $t;
302                         }
303                 } elseif (self::stringPluralSelectDefault($count)) {
304                         $s = $plural;
305                 } else {
306                         $s = $singular;
307                 }
308
309                 $s = @sprintf($s, $count);
310
311                 return $s;
312         }
313
314         /**
315          * Provide a fallback which will not collide with a function defined in any language file
316          */
317         private static function stringPluralSelectDefault($n)
318         {
319                 return $n != 1;
320         }
321
322         /**
323          * @brief Return installed languages codes as associative array
324          *
325          * Scans the view/lang directory for the existence of "strings.php" files, and
326          * returns an alphabetical list of their folder names (@-char language codes).
327          * Adds the english language if it's missing from the list.
328          *
329          * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
330          *
331          * @return array
332          */
333         public static function getAvailableLanguages()
334         {
335                 $langs = [];
336                 $strings_file_paths = glob('view/lang/*/strings.php');
337
338                 if (is_array($strings_file_paths) && count($strings_file_paths)) {
339                         if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
340                                 $strings_file_paths[] = 'view/lang/en/strings.php';
341                         }
342                         asort($strings_file_paths);
343                         foreach ($strings_file_paths as $strings_file_path) {
344                                 $path_array = explode('/', $strings_file_path);
345                                 $langs[$path_array[2]] = $path_array[2];
346                         }
347                 }
348                 return $langs;
349         }
350
351         /**
352          * @brief Translate days and months names.
353          *
354          * @param string $s String with day or month name.
355          * @return string Translated string.
356          */
357         public static function getDay($s)
358         {
359                 $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
360                         [self::t('Monday'), self::t('Tuesday'), self::t('Wednesday'), self::t('Thursday'), self::t('Friday'), self::t('Saturday'), self::t('Sunday')],
361                         $s);
362
363                 $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
364                         [self::t('January'), self::t('February'), self::t('March'), self::t('April'), self::t('May'), self::t('June'), self::t('July'), self::t('August'), self::t('September'), self::t('October'), self::t('November'), self::t('December')],
365                         $ret);
366
367                 return $ret;
368         }
369
370         /**
371          * @brief Translate short days and months names.
372          *
373          * @param string $s String with short day or month name.
374          * @return string Translated string.
375          */
376         public static function getDayShort($s)
377         {
378                 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
379                         [self::t('Mon'), self::t('Tue'), self::t('Wed'), self::t('Thu'), self::t('Fri'), self::t('Sat'), self::t('Sun')],
380                         $s);
381
382                 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
383                         [self::t('Jan'), self::t('Feb'), self::t('Mar'), self::t('Apr'), self::t('May'), ('Jun'), self::t('Jul'), self::t('Aug'), self::t('Sep'), self::t('Oct'), self::t('Nov'), self::t('Dec')],
384                         $ret);
385
386                 return $ret;
387         }
388
389         /**
390          * Load poke verbs
391          *
392          * @return array index is present tense verb
393          *                               value is array containing past tense verb, translation of present, translation of past
394          * @hook poke_verbs pokes array
395          */
396         public static function getPokeVerbs()
397         {
398                 // index is present tense verb
399                 // value is array containing past tense verb, translation of present, translation of past
400                 $arr = [
401                         'poke' => ['poked', self::t('poke'), self::t('poked')],
402                         'ping' => ['pinged', self::t('ping'), self::t('pinged')],
403                         'prod' => ['prodded', self::t('prod'), self::t('prodded')],
404                         'slap' => ['slapped', self::t('slap'), self::t('slapped')],
405                         'finger' => ['fingered', self::t('finger'), self::t('fingered')],
406                         'rebuff' => ['rebuffed', self::t('rebuff'), self::t('rebuffed')],
407                 ];
408
409                 Hook::callAll('poke_verbs', $arr);
410
411                 return $arr;
412         }
413 }