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