Merge branch 'develop' of https://github.com/friendica/friendica into develop
[friendica.git/.git] / src / Core / L10n.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Core;
23
24 use Friendica\Core\Config\Capability\IManageConfigValues;
25 use Friendica\Core\Session\Capability\IHandleSessions;
26 use Friendica\Database\Database;
27 use Friendica\Util\Strings;
28
29 /**
30  * Provide Language, Translation, and Localization functions to the application
31  * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
32  */
33 class L10n
34 {
35         /** @var string The default language */
36         const DEFAULT = 'en';
37         /** @var string[] The language names in their language */
38         const LANG_NAMES = [
39                 'ar'    => 'العربية',
40                 'bg'    => 'Български',
41                 'ca'    => 'Català',
42                 'cs'    => 'Česky',
43                 'da-dk' => 'Dansk (Danmark)',
44                 'de'    => 'Deutsch',
45                 'en-gb' => 'English (United Kingdom)',
46                 'en-us' => 'English (United States)',
47                 'en'    => 'English (Default)',
48                 'eo'    => 'Esperanto',
49                 'es'    => 'Español',
50                 'et'    => 'Eesti',
51                 'fi-fi' => 'Suomi',
52                 'fr'    => 'Français',
53                 'gd'    => 'Gàidhlig',
54                 'hu'    => 'Magyar',
55                 'is'    => 'Íslenska',
56                 'it'    => 'Italiano',
57                 'ja'    => '日本語',
58                 'nb-no' => 'Norsk bokmål',
59                 'nl'    => 'Nederlands',
60                 'pl'    => 'Polski',
61                 'pt-br' => 'Português Brasileiro',
62                 'ro'    => 'Română',
63                 'ru'    => 'Русский',
64                 'sv'    => 'Svenska',
65                 'zh-cn' => '简体中文',
66         ];
67
68         /** @var string Undetermined language */
69         const UNDETERMINED_LANGUAGE = 'un';
70
71         /**
72          * A string indicating the current language used for translation:
73          * - Two-letter ISO 639-1 code.
74          * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
75          *
76          * @var string
77          */
78         private $lang = '';
79
80         /**
81          * An array of translation strings whose key is the neutral english message.
82          *
83          * @var array
84          */
85         private $strings = [];
86
87         /**
88          * @var Database
89          */
90         private $dba;
91         /**
92          * @var IManageConfigValues
93          */
94         private $config;
95
96         public function __construct(IManageConfigValues $config, Database $dba, IHandleSessions $session, array $server, array $get)
97         {
98                 $this->dba    = $dba;
99                 $this->config = $config;
100
101                 $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', self::DEFAULT)));
102                 $this->setSessionVariable($session);
103                 $this->setLangFromSession($session);
104         }
105
106         /**
107          * Returns the current language code
108          *
109          * @return string Language code
110          */
111         public function getCurrentLang()
112         {
113                 return $this->lang;
114         }
115
116         /**
117          * Sets the language session variable
118          */
119         private function setSessionVariable(IHandleSessions $session)
120         {
121                 if ($session->get('authenticated') && !$session->get('language')) {
122                         $session->set('language', $this->lang);
123                         // we haven't loaded user data yet, but we need user language
124                         if ($session->get('uid')) {
125                                 $user = $this->dba->selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
126                                 if ($this->dba->isResult($user)) {
127                                         $session->set('language', $user['language']);
128                                 }
129                         }
130                 }
131
132                 if (isset($_GET['lang'])) {
133                         $session->set('language', $_GET['lang']);
134                 }
135         }
136
137         private function setLangFromSession(IHandleSessions $session)
138         {
139                 if ($session->get('language') !== $this->lang) {
140                         $this->loadTranslationTable($session->get('language') ?? $this->lang);
141                 }
142         }
143
144         /**
145          * Loads string translation table
146          *
147          * First addon strings are loaded, then globals
148          *
149          * Uses an App object shim since all the strings files refer to $a->strings
150          *
151          * @param string $lang language code to load
152          * @return void
153          * @throws \Exception
154          */
155         private function loadTranslationTable(string $lang)
156         {
157                 $lang = Strings::sanitizeFilePathItem($lang);
158
159                 // Don't override the language setting with empty languages
160                 if (empty($lang)) {
161                         return;
162                 }
163
164                 $a          = new \stdClass();
165                 $a->strings = [];
166
167                 // load enabled addons strings
168                 $addons = array_keys($this->config->get('addons') ?? []);
169                 foreach ($addons as $addon) {
170                         $name = Strings::sanitizeFilePathItem($addon);
171                         if (file_exists(__DIR__ . "/../../addon/$name/lang/$lang/strings.php")) {
172                                 include __DIR__ . "/../../addon/$name/lang/$lang/strings.php";
173                         }
174                 }
175
176                 if (file_exists(__DIR__ . "/../../view/lang/$lang/strings.php")) {
177                         include __DIR__ . "/../../view/lang/$lang/strings.php";
178                 }
179
180                 $this->lang    = $lang;
181                 $this->strings = $a->strings;
182
183                 unset($a);
184         }
185
186         /**
187          * Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
188          *
189          * @param string $sysLang The default fallback language
190          * @param array  $server  The $_SERVER array
191          * @param array  $get     The $_GET array
192          *
193          * @return string The two-letter language code
194          */
195         public static function detectLanguage(array $server, array $get, string $sysLang = self::DEFAULT): string
196         {
197                 $lang_variable = $server['HTTP_ACCEPT_LANGUAGE'] ?? null;
198
199                 if (empty($lang_variable)) {
200                         $acceptedLanguages = [];
201                 } else {
202                         $acceptedLanguages = preg_split('/,\s*/', $lang_variable);
203                 }
204
205                 // Add get as absolute quality accepted language (except this language isn't valid)
206                 if (!empty($get['lang'])) {
207                         $acceptedLanguages[] = $get['lang'];
208                 }
209
210                 // return the sys language in case there's nothing to do
211                 if (empty($acceptedLanguages)) {
212                         return $sysLang;
213                 }
214
215                 // Set the syslang as default fallback
216                 $current_lang = $sysLang;
217                 // start with quality zero (every guessed language is more acceptable ..)
218                 $current_q = 0;
219
220                 foreach ($acceptedLanguages as $acceptedLanguage) {
221                         $res = preg_match(
222                                 '/^([a-z]{1,8}(?:-[a-z]{1,8})*)(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i',
223                                 $acceptedLanguage,
224                                 $matches
225                         );
226
227                         // Invalid language? -> skip
228                         if (!$res) {
229                                 continue;
230                         }
231
232                         // split language codes based on it's "-"
233                         $lang_code = explode('-', $matches[1]);
234
235                         // determine the quality of the guess
236                         if (isset($matches[2])) {
237                                 $lang_quality = (float)$matches[2];
238                         } else {
239                                 // fallback so without a quality parameter, it's probably the best
240                                 $lang_quality = 1;
241                         }
242
243                         // loop through each part of the code-parts
244                         while (count($lang_code)) {
245                                 // try to mix them so we can get double-code parts too
246                                 $match_lang = strtolower(join('-', $lang_code));
247                                 if (file_exists(__DIR__ . "/../../view/lang/$match_lang") &&
248                                     is_dir(__DIR__ . "/../../view/lang/$match_lang")) {
249                                         if ($lang_quality > $current_q) {
250                                                 $current_lang = $match_lang;
251                                                 $current_q    = $lang_quality;
252                                                 break;
253                                         }
254                                 }
255
256                                 // remove the most right code-part
257                                 array_pop($lang_code);
258                         }
259                 }
260
261                 return $current_lang;
262         }
263
264         /**
265          * Return the localized version of the provided string with optional string interpolation
266          *
267          * This function takes a english string as parameter, and if a localized version
268          * exists for the current language, substitutes it before performing an eventual
269          * string interpolation (sprintf) with additional optional arguments.
270          *
271          * Usages:
272          * - DI::l10n()->t('This is an example')
273          * - DI::l10n()->t('URL %s returned no result', $url)
274          * - DI::l10n()->t('Current version: %s, new version: %s', $current_version, $new_version)
275          *
276          * @param string $s
277          * @param array  $vars Variables to interpolate in the translation string
278          *
279          * @return string
280          */
281         public function t(string $s, ...$vars): string
282         {
283                 if (empty($s)) {
284                         return '';
285                 }
286
287                 if (!empty($this->strings[$s])) {
288                         $t = $this->strings[$s];
289                         $s = is_array($t) ? $t[0] : $t;
290                 }
291
292                 if (count($vars) > 0) {
293                         $s = sprintf($s, ...$vars);
294                 }
295
296                 return $s;
297         }
298
299         /**
300          * Return the localized version of a singular/plural string with optional string interpolation
301          *
302          * This function takes two english strings as parameters, singular and plural, as
303          * well as a count. If a localized version exists for the current language, they
304          * are used instead. Discrimination between singular and plural is done using the
305          * localized function if any or the default one. Finally, a string interpolation
306          * is performed using the count as parameter.
307          *
308          * Usages:
309          * - DI::l10n()->tt('Like', 'Likes', $count)
310          * - DI::l10n()->tt("%s user deleted", "%s users deleted", count($users))
311          *
312          * @param string $singular
313          * @param string $plural
314          * @param float  $count
315          * @param array  $vars Variables to interpolate in the translation string
316          *
317          * @return string
318          * @throws \Exception
319          */
320         public function tt(string $singular, string $plural, float $count, ...$vars): string
321         {
322                 $s = null;
323
324                 if (!empty($this->strings[$singular])) {
325                         $t = $this->strings[$singular];
326                         if (is_array($t)) {
327                                 $plural_function = 'string_plural_select_' . str_replace('-', '_', $this->lang);
328                                 if (function_exists($plural_function)) {
329                                         $i = $plural_function($count);
330                                 } else {
331                                         $i = $this->stringPluralSelectDefault($count);
332                                 }
333
334                                 if (isset($t[$i])) {
335                                         $s = $t[$i];
336                                 } elseif (count($t) > 0) {
337                                         // for some languages there is only a single array item
338                                         $s = $t[0];
339                                 }
340                                 // if $t is empty, skip it, because empty strings array are intended
341                                 // to make string file smaller when there's no translation
342                         } else {
343                                 $s = $t;
344                         }
345                 }
346
347                 if (is_null($s) && $this->stringPluralSelectDefault($count)) {
348                         $s = $plural;
349                 } elseif (is_null($s)) {
350                         $s = $singular;
351                 }
352
353                 // We mute errors here because the translation strings may not be referencing the count at all,
354                 // but we still have to try the interpolation just in case it is indeed referenced.
355                 $s = @sprintf($s, $count, ...$vars);
356
357                 return $s;
358         }
359
360         /**
361          * Provide a fallback which will not collide with a function defined in any language file
362          *
363          * @param int $n
364          *
365          * @return bool
366          */
367         private function stringPluralSelectDefault(float $n): bool
368         {
369                 return intval($n) != 1;
370         }
371
372         /**
373          * Return installed languages codes as associative array
374          *
375          * Scans the view/lang directory for the existence of "strings.php" files, and
376          * returns an alphabetical list of their folder names (@-char language codes).
377          * Adds the english language if it's missing from the list. Folder names are
378          * replaced by nativ language names.
379          *
380          * Ex: array('de' => 'Deutsch', 'en' => 'English', 'fr' => 'Français', ...)
381          *
382          * @return array
383          */
384         public function getAvailableLanguages(): array
385         {
386                 $langs              = [];
387                 $strings_file_paths = glob('view/lang/*/strings.php');
388
389                 if (is_array($strings_file_paths) && count($strings_file_paths)) {
390                         if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
391                                 $strings_file_paths[] = 'view/lang/en/strings.php';
392                         }
393                         asort($strings_file_paths);
394                         foreach ($strings_file_paths as $strings_file_path) {
395                                 $path_array            = explode('/', $strings_file_path);
396                                 $langs[$path_array[2]] = self::LANG_NAMES[$path_array[2]] ?? $path_array[2];
397                         }
398                 }
399                 return $langs;
400         }
401
402         /**
403          * Get language codes that are detectable by our language detection routines.
404          * Languages are excluded that aren't used often and that tend to false detections.
405          * The listed codes are a collection of both the official ISO 639-1 codes and
406          * the codes that are used by our built-in language detection routine.
407          * When the detection is done, the result only consists of the official ISO 639-1 codes.
408          *
409          * @return array
410          */
411         public function getDetectableLanguages(): array
412         {
413                 $additional_langs = [
414                         'af', 'az', 'az-Cyrl', 'az-Latn', 'be', 'bn', 'bs', 'bs-Cyrl', 'bs-Latn',
415                         'cy', 'da', 'el', 'el-monoton', 'el-polyton', 'en', 'eu', 'fa', 'fi',
416                         'ga', 'gl', 'gu', 'he', 'hi', 'hr', 'hy', 'id', 'in', 'iu', 'iw', 'jv', 'jw',
417                         'ka', 'km', 'ko', 'lt', 'lv', 'mo', 'ms', 'ms-Arab', 'ms-Latn', 'nb', 'nn', 'no',
418                         'pt', 'pt-PT', 'pt-BR', 'ro', 'sa', 'sk', 'sl', 'sq', 'sr', 'sr-Cyrl', 'sr-Latn', 'sw',
419                         'ta', 'th', 'tl', 'tr', 'ug', 'uk', 'uz', 'vi', 'zh', 'zh-Hant', 'zh-Hans',
420                 ];
421
422                 if (in_array('cld2', get_loaded_extensions())) {
423                         $additional_langs = array_merge($additional_langs,
424                                 ['dv', 'kn', 'lo', 'ml', 'or', 'pa', 'sd', 'si', 'te', 'yi']);
425                 }
426
427                 $langs = array_merge($additional_langs, array_keys($this->getAvailableLanguages()));
428                 sort($langs);
429                 return $langs;
430         }
431
432         /**
433          * Return a list of supported languages with their two byte language codes.
434          *
435          * @param bool $international If set to true, additionally the international language name is returned as well.
436          * @return array
437          */
438         public function getLanguageCodes(bool $international = false): array
439         {
440                 $iso639 = new \Matriphe\ISO639\ISO639;
441
442                 // In ISO 639-2 undetermined languages have got the code "und".
443                 // There is no official code for ISO 639-1, but "un" is not assigned to any language.   
444                 $languages = [self::UNDETERMINED_LANGUAGE => $this->t('Undetermined')];
445
446                 foreach ($this->getDetectableLanguages() as $code) {
447                         $code     = $this->toISO6391($code);
448                         $native   = $iso639->nativeByCode1($code);
449                         $language = $iso639->languageByCode1($code);
450                         if ($native != $language && $international) {
451                                 $languages[$code] = $this->t('%s (%s)', $native, $language);
452                         } else {
453                                 $languages[$code] = $native;
454                         }
455                 }
456
457                 return $languages;
458         }
459
460         /**
461          * Convert the language code to ISO639-1
462          * It also converts old codes to their new counterparts.
463          *
464          * @param string $code
465          * @return string
466          */
467         public function toISO6391(string $code): string
468         {
469                 if ((strlen($code) > 2) && (substr($code, 2, 1) == '-')) {
470                         $code = substr($code, 0, 2);
471                 }
472                 if (in_array($code, ['nb', 'nn'])) {
473                         $code = 'no';
474                 }
475                 if ($code == 'in') {
476                         $code = 'id';
477                 }
478                 if ($code == 'iw') {
479                         $code = 'he';
480                 }
481                 if ($code == 'jw') {
482                         $code = 'jv';
483                 }
484                 if ($code == 'mo') {
485                         $code = 'ro';
486                 }
487                 return $code;
488         }
489
490         /**
491          * Translate days and months names.
492          *
493          * @param string $s String with day or month name.
494          * @return string Translated string.
495          */
496         public function getDay(string $s): string
497         {
498                 $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
499                         [$this->t('Monday'), $this->t('Tuesday'), $this->t('Wednesday'), $this->t('Thursday'), $this->t('Friday'), $this->t('Saturday'), $this->t('Sunday')],
500                         $s);
501
502                 $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
503                         [$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')],
504                         $ret);
505
506                 return $ret;
507         }
508
509         /**
510          * Translate short days and months names.
511          *
512          * @param string $s String with short day or month name.
513          * @return string Translated string.
514          */
515         public function getDayShort(string $s): string
516         {
517                 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
518                         [$this->t('Mon'), $this->t('Tue'), $this->t('Wed'), $this->t('Thu'), $this->t('Fri'), $this->t('Sat'), $this->t('Sun')],
519                         $s);
520
521                 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
522                         [$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')],
523                         $ret);
524
525                 return $ret;
526         }
527
528         /**
529          * Creates a new L10n instance based on the given langauge
530          *
531          * @param string $lang The new language
532          *
533          * @return static A new L10n instance
534          * @throws \Exception
535          */
536         public function withLang(string $lang): L10n
537         {
538                 // Don't create a new instance for same language
539                 if ($lang === $this->lang) {
540                         return $this;
541                 }
542
543                 $newL10n = clone $this;
544                 $newL10n->loadTranslationTable($lang);
545                 return $newL10n;
546         }
547 }