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