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