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