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