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