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