3 namespace Friendica\Core\L10n;
5 use Friendica\Core\Config\Configuration;
6 use Friendica\Core\Hook;
7 use Friendica\Core\Session;
8 use Friendica\Database\Database;
9 use Friendica\Util\Strings;
10 use Psr\Log\LoggerInterface;
13 * Provide Language, Translation, and Localization functions to the application
14 * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
19 * A string indicating the current language used for translation:
20 * - Two-letter ISO 639-1 code.
21 * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
27 * A language code saved for later after pushLang() has been called.
31 private $langSave = '';
34 * An array of translation strings whose key is the neutral english message.
38 private $strings = [];
40 * An array of translation strings saved for later after pushLang() has been called.
44 private $stringsSave = [];
52 * @var LoggerInterface
56 public function __construct(Configuration $config, Database $dba, LoggerInterface $logger, array $server, array $get)
59 $this->logger = $logger;
61 $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', 'en')));
65 * Returns the current language code
67 * @return string Language code
69 public function getCurrentLang()
75 * Sets the language session variable
77 public function setSessionVariable()
79 if (Session::get('authenticated') && !Session::get('language')) {
80 $_SESSION['language'] = $this->lang;
81 // we haven't loaded user data yet, but we need user language
82 if (Session::get('uid')) {
83 $user = $this->dba->selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
84 if ($this->dba->isResult($user)) {
85 $_SESSION['language'] = $user['language'];
90 if (isset($_GET['lang'])) {
91 Session::set('language', $_GET['lang']);
95 public function setLangFromSession()
97 if (Session::get('language') !== $this->lang) {
98 $this->loadTranslationTable(Session::get('language'));
103 * This function should be called before formatting messages in a specific target language
104 * different from the current user/system language.
106 * It saves the current translation strings in a separate variable and loads new translations strings.
108 * If called repeatedly, it won't save the translation strings again, just load the new ones.
110 * @param string $lang Language code
114 * @brief Stores the current language strings and load a different language.
116 public function pushLang($lang)
118 if ($lang === $this->lang) {
122 if (empty($this->langSave)) {
123 $this->langSave = $this->lang;
124 $this->stringsSave = $this->strings;
127 $this->loadTranslationTable($lang);
131 * Restores the original user/system language after having used pushLang()
133 public function popLang()
135 if (!isset($this->langSave)) {
139 $this->strings = $this->stringsSave;
140 $this->lang = $this->langSave;
142 $this->stringsSave = null;
143 $this->langSave = null;
147 * Loads string translation table
149 * First addon strings are loaded, then globals
151 * Uses an App object shim since all the strings files refer to $a->strings
153 * @param string $lang language code to load
157 private function loadTranslationTable($lang)
159 $lang = Strings::sanitizeFilePathItem($lang);
161 // Don't override the language setting with empty languages
166 $a = new \stdClass();
169 // load enabled addons strings
170 $addons = $this->dba->select('addon', ['name'], ['installed' => true]);
171 while ($p = $this->dba->fetch($addons)) {
172 $name = Strings::sanitizeFilePathItem($p['name']);
173 if (file_exists("addon/$name/lang/$lang/strings.php")) {
174 include __DIR__ . "/../../../addon/$name/lang/$lang/strings.php";
178 if (file_exists(__DIR__ . "/../../../view/lang/$lang/strings.php")) {
179 include __DIR__ . "/../../../view/lang/$lang/strings.php";
183 $this->strings = $a->strings;
189 * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
191 * @param string $sysLang The default fallback language
192 * @param array $server The $_SERVER array
193 * @param array $get The $_GET array
195 * @return string The two-letter language code
197 public static function detectLanguage(array $server, array $get, string $sysLang = 'en')
199 $lang_variable = $server['HTTP_ACCEPT_LANGUAGE'] ?? null;
201 $acceptedLanguages = preg_split('/,\s*/', $lang_variable);
203 if (empty($acceptedLanguages)) {
204 $acceptedLanguages = [];
207 // Add get as absolute quality accepted language (except this language isn't valid)
208 if (!empty($get['lang'])) {
209 $acceptedLanguages[] = $get['lang'];
212 // return the sys language in case there's nothing to do
213 if (empty($acceptedLanguages)) {
217 // Set the syslang as default fallback
218 $current_lang = $sysLang;
219 // start with quality zero (every guessed language is more acceptable ..)
222 foreach ($acceptedLanguages as $acceptedLanguage) {
224 '/^([a-z]{1,8}(?:-[a-z]{1,8})*)(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i',
229 // Invalid language? -> skip
234 // split language codes based on it's "-"
235 $lang_code = explode('-', $matches[1]);
237 // determine the quality of the guess
238 if (isset($matches[2])) {
239 $lang_quality = (float)$matches[2];
241 // fallback so without a quality parameter, it's probably the best
245 // loop through each part of the code-parts
246 while (count($lang_code)) {
247 // try to mix them so we can get double-code parts too
248 $match_lang = strtolower(join('-', $lang_code));
249 if (file_exists(__DIR__ . "/../../../view/lang/$match_lang") &&
250 is_dir(__DIR__ . "/../../../view/lang/$match_lang")) {
251 if ($lang_quality > $current_q) {
252 $current_lang = $match_lang;
253 $current_q = $lang_quality;
258 // remove the most right code-part
259 array_pop($lang_code);
263 return $current_lang;
267 * @brief Return the localized version of the provided string with optional string interpolation
269 * This function takes a english string as parameter, and if a localized version
270 * exists for the current language, substitutes it before performing an eventual
271 * string interpolation (sprintf) with additional optional arguments.
274 * - L10n::t('This is an example')
275 * - L10n::t('URL %s returned no result', $url)
276 * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version)
279 * @param array $vars Variables to interpolate in the translation string
283 public function t($s, ...$vars)
289 if (!empty($this->strings[$s])) {
290 $t = $this->strings[$s];
291 $s = is_array($t) ? $t[0] : $t;
294 if (count($vars) > 0) {
295 $s = sprintf($s, ...$vars);
302 * @brief Return the localized version of a singular/plural string with optional string interpolation
304 * This function takes two english strings as parameters, singular and plural, as
305 * well as a count. If a localized version exists for the current language, they
306 * are used instead. Discrimination between singular and plural is done using the
307 * localized function if any or the default one. Finally, a string interpolation
308 * is performed using the count as parameter.
311 * - L10n::tt('Like', 'Likes', $count)
312 * - L10n::tt("%s user deleted", "%s users deleted", count($users))
314 * @param string $singular
315 * @param string $plural
321 public function tt(string $singular, string $plural, int $count)
323 if (!empty($this->strings[$singular])) {
324 $t = $this->strings[$singular];
326 $plural_function = 'string_plural_select_' . str_replace('-', '_', $this->lang);
327 if (function_exists($plural_function)) {
328 $i = $plural_function($count);
330 $i = $this->stringPluralSelectDefault($count);
333 // for some languages there is only a single array item
334 if (!isset($t[$i])) {
342 } elseif ($this->stringPluralSelectDefault($count)) {
348 $s = @sprintf($s, $count);
354 * Provide a fallback which will not collide with a function defined in any language file
360 private function stringPluralSelectDefault($n)
366 * Return installed languages codes as associative array
368 * Scans the view/lang directory for the existence of "strings.php" files, and
369 * returns an alphabetical list of their folder names (@-char language codes).
370 * Adds the english language if it's missing from the list.
372 * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
376 public static function getAvailableLanguages()
379 $strings_file_paths = glob('view/lang/*/strings.php');
381 if (is_array($strings_file_paths) && count($strings_file_paths)) {
382 if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
383 $strings_file_paths[] = 'view/lang/en/strings.php';
385 asort($strings_file_paths);
386 foreach ($strings_file_paths as $strings_file_path) {
387 $path_array = explode('/', $strings_file_path);
388 $langs[$path_array[2]] = $path_array[2];
395 * Translate days and months names.
397 * @param string $s String with day or month name.
399 * @return string Translated string.
401 public function getDay($s)
403 $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
404 [$this->t('Monday'), $this->t('Tuesday'), $this->t('Wednesday'), $this->t('Thursday'), $this->t('Friday'), $this->t('Saturday'), $this->t('Sunday')],
407 $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
408 [$this->t('January'), $this->t('February'), $this->t('March'), $this->t('April'), $this->t('May'), $this->t('June'), $this->t('July'), $this->t('August'), $this->t('September'), $this->t('October'), $this->t('November'), $this->t('December')],
415 * Translate short days and months names.
417 * @param string $s String with short day or month name.
419 * @return string Translated string.
421 public function getDayShort($s)
423 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
424 [$this->t('Mon'), $this->t('Tue'), $this->t('Wed'), $this->t('Thu'), $this->t('Fri'), $this->t('Sat'), $this->t('Sun')],
427 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
428 [$this->t('Jan'), $this->t('Feb'), $this->t('Mar'), $this->t('Apr'), $this->t('May'), $this->t('Jun'), $this->t('Jul'), $this->t('Aug'), $this->t('Sep'), $this->t('Oct'), $this->t('Nov'), $this->t('Dec')],
437 * @return array index is present tense verb
438 * value is array containing past tense verb, translation of present, translation of past
439 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
440 * @hook poke_verbs pokes array
442 public function getPokeVerbs()
444 // index is present tense verb
445 // value is array containing past tense verb, translation of present, translation of past
447 'poke' => ['poked', $this->t('poke'), $this->t('poked')],
448 'ping' => ['pinged', $this->t('ping'), $this->t('pinged')],
449 'prod' => ['prodded', $this->t('prod'), $this->t('prodded')],
450 'slap' => ['slapped', $this->t('slap'), $this->t('slapped')],
451 'finger' => ['fingered', $this->t('finger'), $this->t('fingered')],
452 'rebuff' => ['rebuffed', $this->t('rebuff'), $this->t('rebuffed')],
455 Hook::callAll('poke_verbs', $arr);