3 * @file src/Core/L10n.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Core\System;
11 require_once 'boot.php';
12 require_once 'include/dba.php';
15 * Provide Language, Translation, and Localization functions to the application
16 * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
18 class L10n extends BaseObject
21 * A string indicating the current language used for translation:
22 * - Two-letter ISO 639-1 code.
23 * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
28 * A language code saved for later after pushLang() has been called.
32 private $langSave = '';
35 * An array of translation strings whose key is the neutral english message.
39 private $strings = [];
41 * An array of translation strings saved for later after pushLang() has been called.
45 private $stringsSave = [];
48 * Detects the language and sets the translation table
50 public static function init()
52 $lang = self::detectLanguage();
53 self::loadTranslationTable($lang);
57 * Returns the current language code
59 * @return string Language code
61 public static function getCurrentLang()
67 * Sets the language session variable
69 public static function setSessionVariable()
71 if (!empty($_SESSION['authenticated']) && empty($_SESSION['language'])) {
72 $_SESSION['language'] = self::$lang;
73 // we haven't loaded user data yet, but we need user language
74 if (!empty($_SESSION['uid'])) {
75 $user = DBA::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
76 if (DBA::isResult($user)) {
77 $_SESSION['language'] = $user['language'];
83 public static function setLangFromSession()
85 if (!empty($_SESSION['language']) && $_SESSION['language'] !== self::$lang) {
86 self::loadTranslationTable($_SESSION['language']);
91 * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
92 * @return string The two-letter language code
94 public static function detectLanguage()
98 if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
99 // break up string into pieces (languages and q factors)
100 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);
102 if (count($lang_parse[1])) {
103 // go through the list of prefered languages and add a generic language
104 // for sub-linguas (e.g. de-ch will add de) if not already in array
105 for ($i = 0; $i < count($lang_parse[1]); $i++) {
106 $lang_list[] = strtolower($lang_parse[1][$i]);
107 if (strlen($lang_parse[1][$i])>3) {
108 $dashpos = strpos($lang_parse[1][$i], '-');
109 if (!in_array(substr($lang_parse[1][$i], 0, $dashpos), $lang_list)) {
110 $lang_list[] = strtolower(substr($lang_parse[1][$i], 0, $dashpos));
117 // check if we have translations for the preferred languages and pick the 1st that has
118 foreach ($lang_list as $lang) {
119 if ($lang === 'en' || (file_exists("view/lang/$lang") && is_dir("view/lang/$lang"))) {
124 if (isset($preferred)) {
128 // in case none matches, get the system wide configured language, or fall back to English
129 return Config::get('system', 'language', 'en');
133 * This function should be called before formatting messages in a specific target language
134 * different from the current user/system language.
136 * It saves the current translation strings in a separate variable and loads new translations strings.
138 * If called repeatedly, it won't save the translation strings again, just load the new ones.
141 * @brief Stores the current language strings and load a different language.
142 * @param string $lang Language code
144 public static function pushLang($lang)
150 if ($lang === self::$lang) {
154 if (!self::$langSave) {
155 self::$langSave = self::$lang;
156 self::$stringsSave = self::$strings;
159 self::loadTranslationTable($lang);
163 * Restores the original user/system language after having used pushLang()
165 public static function popLang()
167 if (!self::$langSave) {
171 self::$strings = self::$stringsSave;
172 self::$lang = self::$langSave;
174 self::$stringsSave = [];
175 self::$langSave = '';
179 * Loads string translation table
181 * First addon strings are loaded, then globals
183 * Uses an App object shim since all the strings files refer to $a->strings
185 * @param string $lang language code to load
187 private static function loadTranslationTable($lang)
189 if ($lang === self::$lang) {
193 $a = new \stdClass();
196 // load enabled addons strings
197 $addons = DBA::select('addon', ['name'], ['installed' => true]);
198 while ($p = DBA::fetch($addons)) {
200 if (file_exists("addon/$name/lang/$lang/strings.php")) {
201 include "addon/$name/lang/$lang/strings.php";
205 if (file_exists("view/lang/$lang/strings.php")) {
206 include "view/lang/$lang/strings.php";
210 self::$strings = $a->strings;
216 * @brief Return the localized version of the provided string with optional string interpolation
218 * This function takes a english string as parameter, and if a localized version
219 * exists for the current language, substitutes it before performing an eventual
220 * string interpolation (sprintf) with additional optional arguments.
223 * - L10n::t('This is an example')
224 * - L10n::t('URL %s returned no result', $url)
225 * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version)
228 * @param array $vars Variables to interpolate in the translation string
231 public static function t($s, ...$vars)
241 if (!empty(self::$strings[$s])) {
242 $t = self::$strings[$s];
243 $s = is_array($t) ? $t[0] : $t;
246 if (count($vars) > 0) {
247 $s = sprintf($s, ...$vars);
254 * @brief Return the localized version of a singular/plural string with optional string interpolation
256 * This function takes two english strings as parameters, singular and plural, as
257 * well as a count. If a localized version exists for the current language, they
258 * are used instead. Discrimination between singular and plural is done using the
259 * localized function if any or the default one. Finally, a string interpolation
260 * is performed using the count as parameter.
263 * - L10n::tt('Like', 'Likes', $count)
264 * - L10n::tt("%s user deleted", "%s users deleted", count($users))
266 * @param string $singular
267 * @param string $plural
271 public static function tt($singular, $plural, $count)
273 if (!is_numeric($count)) {
274 logger('Non numeric count called by ' . System::callstack(20));
281 if (!empty(self::$strings[$singular])) {
282 $t = self::$strings[$singular];
284 $plural_function = 'string_plural_select_' . str_replace('-', '_', self::$lang);
285 if (function_exists($plural_function)) {
286 $i = $plural_function($count);
288 $i = self::stringPluralSelectDefault($count);
291 // for some languages there is only a single array item
292 if (!isset($t[$i])) {
300 } elseif (self::stringPluralSelectDefault($count)) {
306 $s = @sprintf($s, $count);
312 * Provide a fallback which will not collide with a function defined in any language file
314 private static function stringPluralSelectDefault($n)
320 * @brief Return installed languages codes as associative array
322 * Scans the view/lang directory for the existence of "strings.php" files, and
323 * returns an alphabetical list of their folder names (@-char language codes).
324 * Adds the english language if it's missing from the list.
326 * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
330 public static function getAvailableLanguages()
333 $strings_file_paths = glob('view/lang/*/strings.php');
335 if (is_array($strings_file_paths) && count($strings_file_paths)) {
336 if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
337 $strings_file_paths[] = 'view/lang/en/strings.php';
339 asort($strings_file_paths);
340 foreach ($strings_file_paths as $strings_file_path) {
341 $path_array = explode('/', $strings_file_path);
342 $langs[$path_array[2]] = $path_array[2];