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