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