]> git.mxchange.org Git - friendica.git/blob - src/Core/L10n.php
40aa24732b4bee711e3e1a7fd95e8282464a083e
[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 use Psr\Log\LoggerInterface;
29
30 /**
31  * Provide Language, Translation, and Localization functions to the application
32  * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
33  */
34 class L10n
35 {
36         /** @var string The default language */
37         const DEFAULT = 'en';
38         /** @var string[] The language names in their language */
39         const LANG_NAMES = [
40                 'ar'    => 'العربية',
41                 'bg'    => 'Български',
42                 'ca'    => 'Català',
43                 'cs'    => 'Česky',
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                 'hu'    => 'Magyar',
54                 'is'    => 'Íslenska',
55                 'it'    => 'Italiano',
56                 'ja'    => '日本語',
57                 'nb-no' => 'Norsk bokmål',
58                 'nl'    => 'Nederlands',
59                 'pl'    => 'Polski',
60                 'pt-br' => 'Português Brasileiro',
61                 'ro'    => 'Română',
62                 'ru'    => 'Русский',
63                 'sv'    => 'Svenska',
64                 'zh-cn' => '简体中文',
65         ];
66
67         /**
68          * A string indicating the current language used for translation:
69          * - Two-letter ISO 639-1 code.
70          * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
71          *
72          * @var string
73          */
74         private $lang = '';
75
76         /**
77          * An array of translation strings whose key is the neutral english message.
78          *
79          * @var array
80          */
81         private $strings = [];
82
83         /**
84          * @var Database
85          */
86         private $dba;
87
88         /**
89          * @var LoggerInterface
90          */
91         private $logger;
92
93         public function __construct(IManageConfigValues $config, Database $dba, LoggerInterface $logger, IHandleSessions $session, array $server, array $get)
94         {
95                 $this->dba    = $dba;
96                 $this->logger = $logger;
97
98                 $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', self::DEFAULT)));
99                 $this->setSessionVariable($session);
100                 $this->setLangFromSession($session);
101         }
102
103         /**
104          * Returns the current language code
105          *
106          * @return string Language code
107          */
108         public function getCurrentLang()
109         {
110                 return $this->lang;
111         }
112
113         /**
114          * Sets the language session variable
115          */
116         private function setSessionVariable(IHandleSessions $session)
117         {
118                 if ($session->get('authenticated') && !$session->get('language')) {
119                         $session->set('language', $this->lang);
120                         // we haven't loaded user data yet, but we need user language
121                         if ($session->get('uid')) {
122                                 $user = $this->dba->selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
123                                 if ($this->dba->isResult($user)) {
124                                         $session->set('language', $user['language']);
125                                 }
126                         }
127                 }
128
129                 if (isset($_GET['lang'])) {
130                         $session->set('language', $_GET['lang']);
131                 }
132         }
133
134         private function setLangFromSession(IHandleSessions $session)
135         {
136                 if ($session->get('language') !== $this->lang) {
137                         $this->loadTranslationTable($session->get('language'));
138                 }
139         }
140
141         /**
142          * Loads string translation table
143          *
144          * First addon strings are loaded, then globals
145          *
146          * Uses an App object shim since all the strings files refer to $a->strings
147          *
148          * @param string $lang language code to load
149          *
150          * @throws \Exception
151          */
152         private function loadTranslationTable($lang)
153         {
154                 $lang = Strings::sanitizeFilePathItem($lang);
155
156                 // Don't override the language setting with empty languages
157                 if (empty($lang)) {
158                         return;
159                 }
160
161                 $a          = new \stdClass();
162                 $a->strings = [];
163
164                 // load enabled addons strings
165                 $addons = $this->dba->select('addon', ['name'], ['installed' => true]);
166                 while ($p = $this->dba->fetch($addons)) {
167                         $name = Strings::sanitizeFilePathItem($p['name']);
168                         if (file_exists(__DIR__ . "/../../addon/$name/lang/$lang/strings.php")) {
169                                 include __DIR__ . "/../../addon/$name/lang/$lang/strings.php";
170                         }
171                 }
172
173                 if (file_exists(__DIR__ . "/../../view/lang/$lang/strings.php")) {
174                         include __DIR__ . "/../../view/lang/$lang/strings.php";
175                 }
176
177                 $this->lang    = $lang;
178                 $this->strings = $a->strings;
179
180                 unset($a);
181         }
182
183         /**
184          * Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
185          *
186          * @param string $sysLang The default fallback language
187          * @param array  $server  The $_SERVER array
188          * @param array  $get     The $_GET array
189          *
190          * @return string The two-letter language code
191          */
192         public static function detectLanguage(array $server, array $get, string $sysLang = self::DEFAULT)
193         {
194                 $lang_variable = $server['HTTP_ACCEPT_LANGUAGE'] ?? null;
195
196                 $acceptedLanguages = preg_split('/,\s*/', $lang_variable);
197
198                 if (empty($acceptedLanguages)) {
199                         $acceptedLanguages = [];
200                 }
201
202                 // Add get as absolute quality accepted language (except this language isn't valid)
203                 if (!empty($get['lang'])) {
204                         $acceptedLanguages[] = $get['lang'];
205                 }
206
207                 // return the sys language in case there's nothing to do
208                 if (empty($acceptedLanguages)) {
209                         return $sysLang;
210                 }
211
212                 // Set the syslang as default fallback
213                 $current_lang = $sysLang;
214                 // start with quality zero (every guessed language is more acceptable ..)
215                 $current_q = 0;
216
217                 foreach ($acceptedLanguages as $acceptedLanguage) {
218                         $res = preg_match(
219                                 '/^([a-z]{1,8}(?:-[a-z]{1,8})*)(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i',
220                                 $acceptedLanguage,
221                                 $matches
222                         );
223
224                         // Invalid language? -> skip
225                         if (!$res) {
226                                 continue;
227                         }
228
229                         // split language codes based on it's "-"
230                         $lang_code = explode('-', $matches[1]);
231
232                         // determine the quality of the guess
233                         if (isset($matches[2])) {
234                                 $lang_quality = (float)$matches[2];
235                         } else {
236                                 // fallback so without a quality parameter, it's probably the best
237                                 $lang_quality = 1;
238                         }
239
240                         // loop through each part of the code-parts
241                         while (count($lang_code)) {
242                                 // try to mix them so we can get double-code parts too
243                                 $match_lang = strtolower(join('-', $lang_code));
244                                 if (file_exists(__DIR__ . "/../../view/lang/$match_lang") &&
245                                     is_dir(__DIR__ . "/../../view/lang/$match_lang")) {
246                                         if ($lang_quality > $current_q) {
247                                                 $current_lang = $match_lang;
248                                                 $current_q    = $lang_quality;
249                                                 break;
250                                         }
251                                 }
252
253                                 // remove the most right code-part
254                                 array_pop($lang_code);
255                         }
256                 }
257
258                 return $current_lang;
259         }
260
261         /**
262          * Return the localized version of the provided string with optional string interpolation
263          *
264          * This function takes a english string as parameter, and if a localized version
265          * exists for the current language, substitutes it before performing an eventual
266          * string interpolation (sprintf) with additional optional arguments.
267          *
268          * Usages:
269          * - DI::l10n()->t('This is an example')
270          * - DI::l10n()->t('URL %s returned no result', $url)
271          * - DI::l10n()->t('Current version: %s, new version: %s', $current_version, $new_version)
272          *
273          * @param string $s
274          * @param array  $vars Variables to interpolate in the translation string
275          *
276          * @return string
277          */
278         public function t($s, ...$vars)
279         {
280                 if (empty($s)) {
281                         return '';
282                 }
283
284                 if (!empty($this->strings[$s])) {
285                         $t = $this->strings[$s];
286                         $s = is_array($t) ? $t[0] : $t;
287                 }
288
289                 if (count($vars) > 0) {
290                         $s = sprintf($s, ...$vars);
291                 }
292
293                 return $s;
294         }
295
296         /**
297          * Return the localized version of a singular/plural string with optional string interpolation
298          *
299          * This function takes two english strings as parameters, singular and plural, as
300          * well as a count. If a localized version exists for the current language, they
301          * are used instead. Discrimination between singular and plural is done using the
302          * localized function if any or the default one. Finally, a string interpolation
303          * is performed using the count as parameter.
304          *
305          * Usages:
306          * - DI::l10n()->tt('Like', 'Likes', $count)
307          * - DI::l10n()->tt("%s user deleted", "%s users deleted", count($users))
308          *
309          * @param string $singular
310          * @param string $plural
311          * @param int    $count
312          *
313          * @return string
314          * @throws \Exception
315          */
316         public function tt(string $singular, string $plural, int $count)
317         {
318                 $s = null;
319
320                 if (!empty($this->strings[$singular])) {
321                         $t = $this->strings[$singular];
322                         if (is_array($t)) {
323                                 $plural_function = 'string_plural_select_' . str_replace('-', '_', $this->lang);
324                                 if (function_exists($plural_function)) {
325                                         $i = $plural_function($count);
326                                 } else {
327                                         $i = $this->stringPluralSelectDefault($count);
328                                 }
329
330                                 if (isset($t[$i])) {
331                                         $s = $t[$i];
332                                 } elseif (count($t) > 0) {
333                                         // for some languages there is only a single array item
334                                         $s = $t[0];
335                                 }
336                                 // if $t is empty, skip it, because empty strings array are indended
337                                 // to make string file smaller when there's no translation
338                         } else {
339                                 $s = $t;
340                         }
341                 }
342
343                 if (is_null($s) && $this->stringPluralSelectDefault($count)) {
344                         $s = $plural;
345                 } elseif (is_null($s)) {
346                         $s = $singular;
347                 }
348
349                 $s = @sprintf($s, $count);
350
351                 return $s;
352         }
353
354         /**
355          * Provide a fallback which will not collide with a function defined in any language file
356          *
357          * @param int $n
358          *
359          * @return bool
360          */
361         private function stringPluralSelectDefault($n)
362         {
363                 return $n != 1;
364         }
365
366         /**
367          * Return installed languages codes as associative array
368          *
369          * Scans the view/lang directory for the existence of "strings.php" files, and
370          * returns an alphabetical list of their folder names (@-char language codes).
371          * Adds the english language if it's missing from the list. Folder names are
372          * replaced by nativ language names.
373          *
374          * Ex: array('de' => 'Deutsch', 'en' => 'English', 'fr' => 'Français', ...)
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]] = self::LANG_NAMES[$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
462         /**
463          * Creates a new L10n instance based on the given langauge
464          *
465          * @param string $lang The new language
466          *
467          * @return static A new L10n instance
468          * @throws \Exception
469          */
470         public function withLang(string $lang)
471         {
472                 // Don't create a new instance for same language
473                 if ($lang === $this->lang) {
474                         return $this;
475                 }
476
477                 $newL10n = clone $this;
478                 $newL10n->loadTranslationTable($lang);
479                 return $newL10n;
480         }
481 }