3 * @file src/Core/L10n.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Core\Logger;
10 use Friendica\Core\System;
12 require_once 'boot.php';
13 require_once 'include/dba.php';
16 * Provide Language, Translation, and Localization functions to the application
17 * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
19 class L10n extends BaseObject
22 * A string indicating the current language used for translation:
23 * - Two-letter ISO 639-1 code.
24 * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
27 private static $lang = '';
29 * A language code saved for later after pushLang() has been called.
33 private static $langSave = '';
36 * An array of translation strings whose key is the neutral english message.
40 private static $strings = [];
42 * An array of translation strings saved for later after pushLang() has been called.
46 private static $stringsSave = [];
49 * Detects the language and sets the translation table
51 public static function init()
53 $lang = self::detectLanguage();
54 self::loadTranslationTable($lang);
58 * Returns the current language code
60 * @return string Language code
62 public static function getCurrentLang()
68 * Sets the language session variable
70 public static function setSessionVariable()
72 if (!empty($_SESSION['authenticated']) && empty($_SESSION['language'])) {
73 $_SESSION['language'] = self::$lang;
74 // we haven't loaded user data yet, but we need user language
75 if (!empty($_SESSION['uid'])) {
76 $user = DBA::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
77 if (DBA::isResult($user)) {
78 $_SESSION['language'] = $user['language'];
84 public static function setLangFromSession()
86 if (!empty($_SESSION['language']) && $_SESSION['language'] !== self::$lang) {
87 self::loadTranslationTable($_SESSION['language']);
92 * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
93 * @return string The two-letter language code
95 public static function detectLanguage()
99 if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
100 // break up string into pieces (languages and q factors)
101 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 if (count($lang_parse[1])) {
104 // go through the list of prefered languages and add a generic language
105 // for sub-linguas (e.g. de-ch will add de) if not already in array
106 for ($i = 0; $i < count($lang_parse[1]); $i++) {
107 $lang_list[] = strtolower($lang_parse[1][$i]);
108 if (strlen($lang_parse[1][$i])>3) {
109 $dashpos = strpos($lang_parse[1][$i], '-');
110 if (!in_array(substr($lang_parse[1][$i], 0, $dashpos), $lang_list)) {
111 $lang_list[] = strtolower(substr($lang_parse[1][$i], 0, $dashpos));
118 // check if we have translations for the preferred languages and pick the 1st that has
119 foreach ($lang_list as $lang) {
120 if ($lang === 'en' || (file_exists("view/lang/$lang") && is_dir("view/lang/$lang"))) {
125 if (isset($preferred)) {
129 // in case none matches, get the system wide configured language, or fall back to English
130 return Config::get('system', 'language', 'en');
134 * This function should be called before formatting messages in a specific target language
135 * different from the current user/system language.
137 * It saves the current translation strings in a separate variable and loads new translations strings.
139 * If called repeatedly, it won't save the translation strings again, just load the new ones.
142 * @brief Stores the current language strings and load a different language.
143 * @param string $lang Language code
145 public static function pushLang($lang)
151 if ($lang === self::$lang) {
155 if (!self::$langSave) {
156 self::$langSave = self::$lang;
157 self::$stringsSave = self::$strings;
160 self::loadTranslationTable($lang);
164 * Restores the original user/system language after having used pushLang()
166 public static function popLang()
168 if (!self::$langSave) {
172 self::$strings = self::$stringsSave;
173 self::$lang = self::$langSave;
175 self::$stringsSave = [];
176 self::$langSave = '';
180 * Loads string translation table
182 * First addon strings are loaded, then globals
184 * Uses an App object shim since all the strings files refer to $a->strings
186 * @param string $lang language code to load
188 private static function loadTranslationTable($lang)
190 if ($lang === self::$lang) {
194 $a = new \stdClass();
197 // load enabled addons strings
198 $addons = DBA::select('addon', ['name'], ['installed' => true]);
199 while ($p = DBA::fetch($addons)) {
201 if (file_exists("addon/$name/lang/$lang/strings.php")) {
202 include "addon/$name/lang/$lang/strings.php";
206 if (file_exists("view/lang/$lang/strings.php")) {
207 include "view/lang/$lang/strings.php";
211 self::$strings = $a->strings;
217 * @brief Return the localized version of the provided string with optional string interpolation
219 * This function takes a english string as parameter, and if a localized version
220 * exists for the current language, substitutes it before performing an eventual
221 * string interpolation (sprintf) with additional optional arguments.
224 * - L10n::t('This is an example')
225 * - L10n::t('URL %s returned no result', $url)
226 * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version)
229 * @param array $vars Variables to interpolate in the translation string
232 public static function t($s, ...$vars)
242 if (!empty(self::$strings[$s])) {
243 $t = self::$strings[$s];
244 $s = is_array($t) ? $t[0] : $t;
247 if (count($vars) > 0) {
248 $s = sprintf($s, ...$vars);
255 * @brief Return the localized version of a singular/plural string with optional string interpolation
257 * This function takes two english strings as parameters, singular and plural, as
258 * well as a count. If a localized version exists for the current language, they
259 * are used instead. Discrimination between singular and plural is done using the
260 * localized function if any or the default one. Finally, a string interpolation
261 * is performed using the count as parameter.
264 * - L10n::tt('Like', 'Likes', $count)
265 * - L10n::tt("%s user deleted", "%s users deleted", count($users))
267 * @param string $singular
268 * @param string $plural
272 public static function tt($singular, $plural, $count)
274 if (!is_numeric($count)) {
275 Logger::log('Non numeric count called by ' . System::callstack(20));
282 if (!empty(self::$strings[$singular])) {
283 $t = self::$strings[$singular];
285 $plural_function = 'string_plural_select_' . str_replace('-', '_', self::$lang);
286 if (function_exists($plural_function)) {
287 $i = $plural_function($count);
289 $i = self::stringPluralSelectDefault($count);
292 // for some languages there is only a single array item
293 if (!isset($t[$i])) {
301 } elseif (self::stringPluralSelectDefault($count)) {
307 $s = @sprintf($s, $count);
313 * Provide a fallback which will not collide with a function defined in any language file
315 private static function stringPluralSelectDefault($n)
321 * @brief Return installed languages codes as associative array
323 * Scans the view/lang directory for the existence of "strings.php" files, and
324 * returns an alphabetical list of their folder names (@-char language codes).
325 * Adds the english language if it's missing from the list.
327 * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
331 public static function getAvailableLanguages()
334 $strings_file_paths = glob('view/lang/*/strings.php');
336 if (is_array($strings_file_paths) && count($strings_file_paths)) {
337 if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
338 $strings_file_paths[] = 'view/lang/en/strings.php';
340 asort($strings_file_paths);
341 foreach ($strings_file_paths as $strings_file_path) {
342 $path_array = explode('/', $strings_file_path);
343 $langs[$path_array[2]] = $path_array[2];