3 * @file src/Core/L10n.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
11 * Provide Language, Translation, and Localization functions to the application
12 * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
14 class L10n extends BaseObject
17 * A string indicating the current language used for translation:
18 * - Two-letter ISO 639-1 code.
19 * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
22 private static $lang = '';
24 * A language code saved for later after pushLang() has been called.
28 private static $langSave = '';
31 * An array of translation strings whose key is the neutral english message.
35 private static $strings = [];
37 * An array of translation strings saved for later after pushLang() has been called.
41 private static $stringsSave = [];
44 * Detects the language and sets the translation table
46 public static function init()
48 $lang = self::detectLanguage();
49 self::loadTranslationTable($lang);
53 * Returns the current language code
55 * @return string Language code
57 public static function getCurrentLang()
63 * Sets the language session variable
65 public static function setSessionVariable()
67 if (!empty($_SESSION['authenticated']) && empty($_SESSION['language'])) {
68 $_SESSION['language'] = self::$lang;
69 // we haven't loaded user data yet, but we need user language
70 if (!empty($_SESSION['uid'])) {
71 $user = DBA::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
72 if (DBA::isResult($user)) {
73 $_SESSION['language'] = $user['language'];
79 public static function setLangFromSession()
81 if (!empty($_SESSION['language']) && $_SESSION['language'] !== self::$lang) {
82 self::loadTranslationTable($_SESSION['language']);
87 * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
88 * @return string The two-letter language code
90 public static function detectLanguage()
94 if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
95 // break up string into pieces (languages and q factors)
96 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);
98 if (count($lang_parse[1])) {
99 // go through the list of prefered languages and add a generic language
100 // for sub-linguas (e.g. de-ch will add de) if not already in array
101 for ($i = 0; $i < count($lang_parse[1]); $i++) {
102 $lang_list[] = strtolower($lang_parse[1][$i]);
103 if (strlen($lang_parse[1][$i])>3) {
104 $dashpos = strpos($lang_parse[1][$i], '-');
105 if (!in_array(substr($lang_parse[1][$i], 0, $dashpos), $lang_list)) {
106 $lang_list[] = strtolower(substr($lang_parse[1][$i], 0, $dashpos));
113 // check if we have translations for the preferred languages and pick the 1st that has
114 foreach ($lang_list as $lang) {
115 if ($lang === 'en' || (file_exists("view/lang/$lang") && is_dir("view/lang/$lang"))) {
120 if (isset($preferred)) {
124 // in case none matches, get the system wide configured language, or fall back to English
125 return Config::get('system', 'language', 'en');
129 * This function should be called before formatting messages in a specific target language
130 * different from the current user/system language.
132 * It saves the current translation strings in a separate variable and loads new translations strings.
134 * If called repeatedly, it won't save the translation strings again, just load the new ones.
137 * @brief Stores the current language strings and load a different language.
138 * @param string $lang Language code
140 public static function pushLang($lang)
146 if ($lang === self::$lang) {
150 if (!self::$langSave) {
151 self::$langSave = self::$lang;
152 self::$stringsSave = self::$strings;
155 self::loadTranslationTable($lang);
159 * Restores the original user/system language after having used pushLang()
161 public static function popLang()
163 if (!self::$langSave) {
167 self::$strings = self::$stringsSave;
168 self::$lang = self::$langSave;
170 self::$stringsSave = [];
171 self::$langSave = '';
175 * Loads string translation table
177 * First addon strings are loaded, then globals
179 * Uses an App object shim since all the strings files refer to $a->strings
181 * @param string $lang language code to load
183 private static function loadTranslationTable($lang)
185 if ($lang === self::$lang) {
189 $a = new \stdClass();
192 // load enabled addons strings
193 $addons = DBA::select('addon', ['name'], ['installed' => true]);
194 while ($p = DBA::fetch($addons)) {
196 if (file_exists("addon/$name/lang/$lang/strings.php")) {
197 include "addon/$name/lang/$lang/strings.php";
201 if (file_exists("view/lang/$lang/strings.php")) {
202 include "view/lang/$lang/strings.php";
206 self::$strings = $a->strings;
212 * @brief Return the localized version of the provided string with optional string interpolation
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.
219 * - L10n::t('This is an example')
220 * - L10n::t('URL %s returned no result', $url)
221 * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version)
224 * @param array $vars Variables to interpolate in the translation string
227 public static function t($s, ...$vars)
237 if (!empty(self::$strings[$s])) {
238 $t = self::$strings[$s];
239 $s = is_array($t) ? $t[0] : $t;
242 if (count($vars) > 0) {
243 $s = sprintf($s, ...$vars);
250 * @brief Return the localized version of a singular/plural string with optional string interpolation
252 * This function takes two english strings as parameters, singular and plural, as
253 * well as a count. If a localized version exists for the current language, they
254 * are used instead. Discrimination between singular and plural is done using the
255 * localized function if any or the default one. Finally, a string interpolation
256 * is performed using the count as parameter.
259 * - L10n::tt('Like', 'Likes', $count)
260 * - L10n::tt("%s user deleted", "%s users deleted", count($users))
262 * @param string $singular
263 * @param string $plural
267 public static function tt($singular, $plural, $count)
269 if (!is_numeric($count)) {
270 Logger::log('Non numeric count called by ' . System::callstack(20));
277 if (!empty(self::$strings[$singular])) {
278 $t = self::$strings[$singular];
280 $plural_function = 'string_plural_select_' . str_replace('-', '_', self::$lang);
281 if (function_exists($plural_function)) {
282 $i = $plural_function($count);
284 $i = self::stringPluralSelectDefault($count);
287 // for some languages there is only a single array item
288 if (!isset($t[$i])) {
296 } elseif (self::stringPluralSelectDefault($count)) {
302 $s = @sprintf($s, $count);
308 * Provide a fallback which will not collide with a function defined in any language file
310 private static function stringPluralSelectDefault($n)
316 * @brief Return installed languages codes as associative array
318 * Scans the view/lang directory for the existence of "strings.php" files, and
319 * returns an alphabetical list of their folder names (@-char language codes).
320 * Adds the english language if it's missing from the list.
322 * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
326 public static function getAvailableLanguages()
329 $strings_file_paths = glob('view/lang/*/strings.php');
331 if (is_array($strings_file_paths) && count($strings_file_paths)) {
332 if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
333 $strings_file_paths[] = 'view/lang/en/strings.php';
335 asort($strings_file_paths);
336 foreach ($strings_file_paths as $strings_file_path) {
337 $path_array = explode('/', $strings_file_path);
338 $langs[$path_array[2]] = $path_array[2];
345 * @brief Translate days and months names.
347 * @param string $s String with day or month name.
348 * @return string Translated string.
350 public static function getDay($s)
352 $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
353 [self::t('Monday'), self::t('Tuesday'), self::t('Wednesday'), self::t('Thursday'), self::t('Friday'), self::t('Saturday'), self::t('Sunday')],
356 $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
357 [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 * @brief Translate short days and months names.
366 * @param string $s String with short day or month name.
367 * @return string Translated string.
369 public static function getDayShort($s)
371 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
372 [self::t('Mon'), self::t('Tue'), self::t('Wed'), self::t('Thu'), self::t('Fri'), self::t('Sat'), self::t('Sun')],
375 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
376 [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')],
385 * @return array index is present tense verb
386 * value is array containing past tense verb, translation of present, translation of past
387 * @hook poke_verbs pokes array
389 public static function getPokeVerbs()
391 // index is present tense verb
392 // value is array containing past tense verb, translation of present, translation of past
394 'poke' => ['poked', self::t('poke'), self::t('poked')],
395 'ping' => ['pinged', self::t('ping'), self::t('pinged')],
396 'prod' => ['prodded', self::t('prod'), self::t('prodded')],
397 'slap' => ['slapped', self::t('slap'), self::t('slapped')],
398 'finger' => ['fingered', self::t('finger'), self::t('fingered')],
399 'rebuff' => ['rebuffed', self::t('rebuff'), self::t('rebuffed')],
402 Hook::callAll('poke_verbs', $arr);