]> git.mxchange.org Git - friendica.git/blob - src/Core/L10n/L10n.php
Optimize L10n usage for Session (reduce "App" complexity even more)
[friendica.git] / src / Core / L10n / L10n.php
1 <?php
2
3 namespace Friendica\Core\L10n;
4
5 use Friendica\Core\Config\Configuration;
6 use Friendica\Core\Hook;
7 use Friendica\Core\Session\ISession;
8 use Friendica\Database\Database;
9 use Friendica\Util\Strings;
10 use Psr\Log\LoggerInterface;
11
12 /**
13  * Provide Language, Translation, and Localization functions to the application
14  * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
15  */
16 class L10n
17 {
18         /**
19          * A string indicating the current language used for translation:
20          * - Two-letter ISO 639-1 code.
21          * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
22          *
23          * @var string
24          */
25         private $lang = '';
26         /**
27          * A language code saved for later after pushLang() has been called.
28          *
29          * @var string
30          */
31         private $langSave = '';
32
33         /**
34          * An array of translation strings whose key is the neutral english message.
35          *
36          * @var array
37          */
38         private $strings = [];
39         /**
40          * An array of translation strings saved for later after pushLang() has been called.
41          *
42          * @var array
43          */
44         private $stringsSave = [];
45
46         /**
47          * @var Database
48          */
49         private $dba;
50
51         /**
52          * @var LoggerInterface
53          */
54         private $logger;
55
56         public function __construct(Configuration $config, Database $dba, LoggerInterface $logger, ISession $session,  array $server, array $get)
57         {
58                 $this->dba    = $dba;
59                 $this->logger = $logger;
60
61                 $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', 'en')));
62                 $this->setSessionVariable($session);
63                 $this->setLangFromSession($session);
64         }
65
66         /**
67          * Returns the current language code
68          *
69          * @return string Language code
70          */
71         public function getCurrentLang()
72         {
73                 return $this->lang;
74         }
75
76         /**
77          * Sets the language session variable
78          */
79         private function setSessionVariable(ISession $session)
80         {
81                 if ($session->get('authenticated') && !$session->get('language')) {
82                         $session->set('language', $this->lang);
83                         // we haven't loaded user data yet, but we need user language
84                         if ($session->get('uid')) {
85                                 $user = $this->dba->selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
86                                 if ($this->dba->isResult($user)) {
87                                         $session->set('language', $user['language']);
88                                 }
89                         }
90                 }
91
92                 if (isset($_GET['lang'])) {
93                         $session->set('language', $_GET['lang']);
94                 }
95         }
96
97         private function setLangFromSession(ISession $session)
98         {
99                 if ($session->get('language') !== $this->lang) {
100                         $this->loadTranslationTable($session->get('language'));
101                 }
102         }
103
104         /**
105          * This function should be called before formatting messages in a specific target language
106          * different from the current user/system language.
107          *
108          * It saves the current translation strings in a separate variable and loads new translations strings.
109          *
110          * If called repeatedly, it won't save the translation strings again, just load the new ones.
111          *
112          * @param string $lang Language code
113          *
114          * @throws \Exception
115          * @see   popLang()
116          * @brief Stores the current language strings and load a different language.
117          */
118         public function pushLang($lang)
119         {
120                 if ($lang === $this->lang) {
121                         return;
122                 }
123
124                 if (empty($this->langSave)) {
125                         $this->langSave    = $this->lang;
126                         $this->stringsSave = $this->strings;
127                 }
128
129                 $this->loadTranslationTable($lang);
130         }
131
132         /**
133          * Restores the original user/system language after having used pushLang()
134          */
135         public function popLang()
136         {
137                 if (!isset($this->langSave)) {
138                         return;
139                 }
140
141                 $this->strings = $this->stringsSave;
142                 $this->lang    = $this->langSave;
143
144                 $this->stringsSave = null;
145                 $this->langSave    = null;
146         }
147
148         /**
149          * Loads string translation table
150          *
151          * First addon strings are loaded, then globals
152          *
153          * Uses an App object shim since all the strings files refer to $a->strings
154          *
155          * @param string $lang language code to load
156          *
157          * @throws \Exception
158          */
159         private function loadTranslationTable($lang)
160         {
161                 $lang = Strings::sanitizeFilePathItem($lang);
162
163                 // Don't override the language setting with empty languages
164                 if (empty($lang)) {
165                         return;
166                 }
167
168                 $a          = new \stdClass();
169                 $a->strings = [];
170
171                 // load enabled addons strings
172                 $addons = $this->dba->select('addon', ['name'], ['installed' => true]);
173                 while ($p = $this->dba->fetch($addons)) {
174                         $name = Strings::sanitizeFilePathItem($p['name']);
175                         if (file_exists("addon/$name/lang/$lang/strings.php")) {
176                                 include __DIR__ . "/../../../addon/$name/lang/$lang/strings.php";
177                         }
178                 }
179
180                 if (file_exists(__DIR__ . "/../../../view/lang/$lang/strings.php")) {
181                         include __DIR__ . "/../../../view/lang/$lang/strings.php";
182                 }
183
184                 $this->lang    = $lang;
185                 $this->strings = $a->strings;
186
187                 unset($a);
188         }
189
190         /**
191          * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
192          *
193          * @param string $sysLang The default fallback language
194          * @param array  $server  The $_SERVER array
195          * @param array  $get     The $_GET array
196          *
197          * @return string The two-letter language code
198          */
199         public static function detectLanguage(array $server, array $get, string $sysLang = 'en')
200         {
201                 $lang_variable = $server['HTTP_ACCEPT_LANGUAGE'] ?? null;
202
203                 $acceptedLanguages = preg_split('/,\s*/', $lang_variable);
204
205                 if (empty($acceptedLanguages)) {
206                         $acceptedLanguages = [];
207                 }
208
209                 // Add get as absolute quality accepted language (except this language isn't valid)
210                 if (!empty($get['lang'])) {
211                         $acceptedLanguages[] = $get['lang'];
212                 }
213
214                 // return the sys language in case there's nothing to do
215                 if (empty($acceptedLanguages)) {
216                         return $sysLang;
217                 }
218
219                 // Set the syslang as default fallback
220                 $current_lang = $sysLang;
221                 // start with quality zero (every guessed language is more acceptable ..)
222                 $current_q = 0;
223
224                 foreach ($acceptedLanguages as $acceptedLanguage) {
225                         $res = preg_match(
226                                 '/^([a-z]{1,8}(?:-[a-z]{1,8})*)(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i',
227                                 $acceptedLanguage,
228                                 $matches
229                         );
230
231                         // Invalid language? -> skip
232                         if (!$res) {
233                                 continue;
234                         }
235
236                         // split language codes based on it's "-"
237                         $lang_code = explode('-', $matches[1]);
238
239                         // determine the quality of the guess
240                         if (isset($matches[2])) {
241                                 $lang_quality = (float)$matches[2];
242                         } else {
243                                 // fallback so without a quality parameter, it's probably the best
244                                 $lang_quality = 1;
245                         }
246
247                         // loop through each part of the code-parts
248                         while (count($lang_code)) {
249                                 // try to mix them so we can get double-code parts too
250                                 $match_lang = strtolower(join('-', $lang_code));
251                                 if (file_exists(__DIR__ . "/../../../view/lang/$match_lang") &&
252                                     is_dir(__DIR__ . "/../../../view/lang/$match_lang")) {
253                                         if ($lang_quality > $current_q) {
254                                                 $current_lang = $match_lang;
255                                                 $current_q    = $lang_quality;
256                                                 break;
257                                         }
258                                 }
259
260                                 // remove the most right code-part
261                                 array_pop($lang_code);
262                         }
263                 }
264
265                 return $current_lang;
266         }
267
268         /**
269          * @brief Return the localized version of the provided string with optional string interpolation
270          *
271          * This function takes a english string as parameter, and if a localized version
272          * exists for the current language, substitutes it before performing an eventual
273          * string interpolation (sprintf) with additional optional arguments.
274          *
275          * Usages:
276          * - L10n::t('This is an example')
277          * - L10n::t('URL %s returned no result', $url)
278          * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version)
279          *
280          * @param string $s
281          * @param array  $vars Variables to interpolate in the translation string
282          *
283          * @return string
284          */
285         public function t($s, ...$vars)
286         {
287                 if (empty($s)) {
288                         return '';
289                 }
290
291                 if (!empty($this->strings[$s])) {
292                         $t = $this->strings[$s];
293                         $s = is_array($t) ? $t[0] : $t;
294                 }
295
296                 if (count($vars) > 0) {
297                         $s = sprintf($s, ...$vars);
298                 }
299
300                 return $s;
301         }
302
303         /**
304          * @brief Return the localized version of a singular/plural string with optional string interpolation
305          *
306          * This function takes two english strings as parameters, singular and plural, as
307          * well as a count. If a localized version exists for the current language, they
308          * are used instead. Discrimination between singular and plural is done using the
309          * localized function if any or the default one. Finally, a string interpolation
310          * is performed using the count as parameter.
311          *
312          * Usages:
313          * - L10n::tt('Like', 'Likes', $count)
314          * - L10n::tt("%s user deleted", "%s users deleted", count($users))
315          *
316          * @param string $singular
317          * @param string $plural
318          * @param int    $count
319          *
320          * @return string
321          * @throws \Exception
322          */
323         public function tt(string $singular, string $plural, int $count)
324         {
325                 if (!empty($this->strings[$singular])) {
326                         $t = $this->strings[$singular];
327                         if (is_array($t)) {
328                                 $plural_function = 'string_plural_select_' . str_replace('-', '_', $this->lang);
329                                 if (function_exists($plural_function)) {
330                                         $i = $plural_function($count);
331                                 } else {
332                                         $i = $this->stringPluralSelectDefault($count);
333                                 }
334
335                                 // for some languages there is only a single array item
336                                 if (!isset($t[$i])) {
337                                         $s = $t[0];
338                                 } else {
339                                         $s = $t[$i];
340                                 }
341                         } else {
342                                 $s = $t;
343                         }
344                 } elseif ($this->stringPluralSelectDefault($count)) {
345                         $s = $plural;
346                 } else {
347                         $s = $singular;
348                 }
349
350                 $s = @sprintf($s, $count);
351
352                 return $s;
353         }
354
355         /**
356          * Provide a fallback which will not collide with a function defined in any language file
357          *
358          * @param int $n
359          *
360          * @return bool
361          */
362         private function stringPluralSelectDefault($n)
363         {
364                 return $n != 1;
365         }
366
367         /**
368          * Return installed languages codes as associative array
369          *
370          * Scans the view/lang directory for the existence of "strings.php" files, and
371          * returns an alphabetical list of their folder names (@-char language codes).
372          * Adds the english language if it's missing from the list.
373          *
374          * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
375          *
376          * @return array
377          */
378         public static function getAvailableLanguages()
379         {
380                 $langs              = [];
381                 $strings_file_paths = glob('view/lang/*/strings.php');
382
383                 if (is_array($strings_file_paths) && count($strings_file_paths)) {
384                         if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
385                                 $strings_file_paths[] = 'view/lang/en/strings.php';
386                         }
387                         asort($strings_file_paths);
388                         foreach ($strings_file_paths as $strings_file_path) {
389                                 $path_array            = explode('/', $strings_file_path);
390                                 $langs[$path_array[2]] = $path_array[2];
391                         }
392                 }
393                 return $langs;
394         }
395
396         /**
397          * Translate days and months names.
398          *
399          * @param string $s String with day or month name.
400          *
401          * @return string Translated string.
402          */
403         public function getDay($s)
404         {
405                 $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
406                         [$this->t('Monday'), $this->t('Tuesday'), $this->t('Wednesday'), $this->t('Thursday'), $this->t('Friday'), $this->t('Saturday'), $this->t('Sunday')],
407                         $s);
408
409                 $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
410                         [$this->t('January'), $this->t('February'), $this->t('March'), $this->t('April'), $this->t('May'), $this->t('June'), $this->t('July'), $this->t('August'), $this->t('September'), $this->t('October'), $this->t('November'), $this->t('December')],
411                         $ret);
412
413                 return $ret;
414         }
415
416         /**
417          * Translate short days and months names.
418          *
419          * @param string $s String with short day or month name.
420          *
421          * @return string Translated string.
422          */
423         public function getDayShort($s)
424         {
425                 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
426                         [$this->t('Mon'), $this->t('Tue'), $this->t('Wed'), $this->t('Thu'), $this->t('Fri'), $this->t('Sat'), $this->t('Sun')],
427                         $s);
428
429                 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
430                         [$this->t('Jan'), $this->t('Feb'), $this->t('Mar'), $this->t('Apr'), $this->t('May'), $this->t('Jun'), $this->t('Jul'), $this->t('Aug'), $this->t('Sep'), $this->t('Oct'), $this->t('Nov'), $this->t('Dec')],
431                         $ret);
432
433                 return $ret;
434         }
435
436         /**
437          * Load poke verbs
438          *
439          * @return array index is present tense verb
440          *                 value is array containing past tense verb, translation of present, translation of past
441          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
442          * @hook poke_verbs pokes array
443          */
444         public function getPokeVerbs()
445         {
446                 // index is present tense verb
447                 // value is array containing past tense verb, translation of present, translation of past
448                 $arr = [
449                         'poke'   => ['poked', $this->t('poke'), $this->t('poked')],
450                         'ping'   => ['pinged', $this->t('ping'), $this->t('pinged')],
451                         'prod'   => ['prodded', $this->t('prod'), $this->t('prodded')],
452                         'slap'   => ['slapped', $this->t('slap'), $this->t('slapped')],
453                         'finger' => ['fingered', $this->t('finger'), $this->t('fingered')],
454                         'rebuff' => ['rebuffed', $this->t('rebuff'), $this->t('rebuffed')],
455                 ];
456
457                 Hook::callAll('poke_verbs', $arr);
458
459                 return $arr;
460         }
461 }