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