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