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