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