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