3 namespace Friendica\Core;
5 use Friendica\Core\Config\IConfiguration;
6 use Friendica\Core\Session\ISession;
7 use Friendica\Database\Database;
8 use Friendica\Util\Strings;
9 use Psr\Log\LoggerInterface;
12 * Provide Language, Translation, and Localization functions to the application
13 * Localization can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N").
18 * A string indicating the current language used for translation:
19 * - Two-letter ISO 639-1 code.
20 * - Two-letter ISO 639-1 code + dash + Two-letter ISO 3166-1 alpha-2 country code.
27 * An array of translation strings whose key is the neutral english message.
31 private $strings = [];
39 * @var LoggerInterface
43 public function __construct(IConfiguration $config, Database $dba, LoggerInterface $logger, ISession $session, array $server, array $get)
46 $this->logger = $logger;
48 $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', 'en')));
49 $this->setSessionVariable($session);
50 $this->setLangFromSession($session);
54 * Returns the current language code
56 * @return string Language code
58 public function getCurrentLang()
64 * Sets the language session variable
66 private function setSessionVariable(ISession $session)
68 if ($session->get('authenticated') && !$session->get('language')) {
69 $session->set('language', $this->lang);
70 // we haven't loaded user data yet, but we need user language
71 if ($session->get('uid')) {
72 $user = $this->dba->selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
73 if ($this->dba->isResult($user)) {
74 $session->set('language', $user['language']);
79 if (isset($_GET['lang'])) {
80 $session->set('language', $_GET['lang']);
84 private function setLangFromSession(ISession $session)
86 if ($session->get('language') !== $this->lang) {
87 $this->loadTranslationTable($session->get('language'));
92 * Loads string translation table
94 * First addon strings are loaded, then globals
96 * Uses an App object shim since all the strings files refer to $a->strings
98 * @param string $lang language code to load
102 private function loadTranslationTable($lang)
104 $lang = Strings::sanitizeFilePathItem($lang);
106 // Don't override the language setting with empty languages
111 $a = new \stdClass();
114 // load enabled addons strings
115 $addons = $this->dba->select('addon', ['name'], ['installed' => true]);
116 while ($p = $this->dba->fetch($addons)) {
117 $name = Strings::sanitizeFilePathItem($p['name']);
118 if (file_exists(__DIR__ . "/../../addon/$name/lang/$lang/strings.php")) {
119 include __DIR__ . "/../../addon/$name/lang/$lang/strings.php";
123 if (file_exists(__DIR__ . "/../../view/lang/$lang/strings.php")) {
124 include __DIR__ . "/../../view/lang/$lang/strings.php";
128 $this->strings = $a->strings;
134 * Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
136 * @param string $sysLang The default fallback language
137 * @param array $server The $_SERVER array
138 * @param array $get The $_GET array
140 * @return string The two-letter language code
142 public static function detectLanguage(array $server, array $get, string $sysLang = 'en')
144 $lang_variable = $server['HTTP_ACCEPT_LANGUAGE'] ?? null;
146 $acceptedLanguages = preg_split('/,\s*/', $lang_variable);
148 if (empty($acceptedLanguages)) {
149 $acceptedLanguages = [];
152 // Add get as absolute quality accepted language (except this language isn't valid)
153 if (!empty($get['lang'])) {
154 $acceptedLanguages[] = $get['lang'];
157 // return the sys language in case there's nothing to do
158 if (empty($acceptedLanguages)) {
162 // Set the syslang as default fallback
163 $current_lang = $sysLang;
164 // start with quality zero (every guessed language is more acceptable ..)
167 foreach ($acceptedLanguages as $acceptedLanguage) {
169 '/^([a-z]{1,8}(?:-[a-z]{1,8})*)(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i',
174 // Invalid language? -> skip
179 // split language codes based on it's "-"
180 $lang_code = explode('-', $matches[1]);
182 // determine the quality of the guess
183 if (isset($matches[2])) {
184 $lang_quality = (float)$matches[2];
186 // fallback so without a quality parameter, it's probably the best
190 // loop through each part of the code-parts
191 while (count($lang_code)) {
192 // try to mix them so we can get double-code parts too
193 $match_lang = strtolower(join('-', $lang_code));
194 if (file_exists(__DIR__ . "/../../view/lang/$match_lang") &&
195 is_dir(__DIR__ . "/../../view/lang/$match_lang")) {
196 if ($lang_quality > $current_q) {
197 $current_lang = $match_lang;
198 $current_q = $lang_quality;
203 // remove the most right code-part
204 array_pop($lang_code);
208 return $current_lang;
212 * 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 * - DI::l10n()->t('This is an example')
220 * - DI::l10n()->t('URL %s returned no result', $url)
221 * - DI::l10n()->t('Current version: %s, new version: %s', $current_version, $new_version)
224 * @param array $vars Variables to interpolate in the translation string
228 public function t($s, ...$vars)
234 if (!empty($this->strings[$s])) {
235 $t = $this->strings[$s];
236 $s = is_array($t) ? $t[0] : $t;
239 if (count($vars) > 0) {
240 $s = sprintf($s, ...$vars);
247 * Return the localized version of a singular/plural string with optional string interpolation
249 * This function takes two english strings as parameters, singular and plural, as
250 * well as a count. If a localized version exists for the current language, they
251 * are used instead. Discrimination between singular and plural is done using the
252 * localized function if any or the default one. Finally, a string interpolation
253 * is performed using the count as parameter.
256 * - DI::l10n()->tt('Like', 'Likes', $count)
257 * - DI::l10n()->tt("%s user deleted", "%s users deleted", count($users))
259 * @param string $singular
260 * @param string $plural
266 public function tt(string $singular, string $plural, int $count)
268 if (!empty($this->strings[$singular])) {
269 $t = $this->strings[$singular];
271 $plural_function = 'string_plural_select_' . str_replace('-', '_', $this->lang);
272 if (function_exists($plural_function)) {
273 $i = $plural_function($count);
275 $i = $this->stringPluralSelectDefault($count);
278 // for some languages there is only a single array item
279 if (!isset($t[$i])) {
287 } elseif ($this->stringPluralSelectDefault($count)) {
293 $s = @sprintf($s, $count);
299 * Provide a fallback which will not collide with a function defined in any language file
305 private function stringPluralSelectDefault($n)
311 * Return installed languages codes as associative array
313 * Scans the view/lang directory for the existence of "strings.php" files, and
314 * returns an alphabetical list of their folder names (@-char language codes).
315 * Adds the english language if it's missing from the list.
317 * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
321 public static function getAvailableLanguages()
324 $strings_file_paths = glob('view/lang/*/strings.php');
326 if (is_array($strings_file_paths) && count($strings_file_paths)) {
327 if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
328 $strings_file_paths[] = 'view/lang/en/strings.php';
330 asort($strings_file_paths);
331 foreach ($strings_file_paths as $strings_file_path) {
332 $path_array = explode('/', $strings_file_path);
333 $langs[$path_array[2]] = $path_array[2];
340 * Translate days and months names.
342 * @param string $s String with day or month name.
344 * @return string Translated string.
346 public function getDay($s)
348 $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
349 [$this->t('Monday'), $this->t('Tuesday'), $this->t('Wednesday'), $this->t('Thursday'), $this->t('Friday'), $this->t('Saturday'), $this->t('Sunday')],
352 $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
353 [$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')],
360 * Translate short days and months names.
362 * @param string $s String with short day or month name.
364 * @return string Translated string.
366 public function getDayShort($s)
368 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
369 [$this->t('Mon'), $this->t('Tue'), $this->t('Wed'), $this->t('Thu'), $this->t('Fri'), $this->t('Sat'), $this->t('Sun')],
372 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
373 [$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')],
382 * @return array index is present tense verb
383 * value is array containing past tense verb, translation of present, translation of past
384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
385 * @hook poke_verbs pokes array
387 public function getPokeVerbs()
389 // index is present tense verb
390 // value is array containing past tense verb, translation of present, translation of past
392 'poke' => ['poked', $this->t('poke'), $this->t('poked')],
393 'ping' => ['pinged', $this->t('ping'), $this->t('pinged')],
394 'prod' => ['prodded', $this->t('prod'), $this->t('prodded')],
395 'slap' => ['slapped', $this->t('slap'), $this->t('slapped')],
396 'finger' => ['fingered', $this->t('finger'), $this->t('fingered')],
397 'rebuff' => ['rebuffed', $this->t('rebuff'), $this->t('rebuffed')],
400 Hook::callAll('poke_verbs', $arr);
406 * Creates a new L10n instance based on the given langauge
408 * @param string $lang The new language
410 * @return static A new L10n instance
413 public function withLang(string $lang)
415 // Don't create a new instance for same language
416 if ($lang === $this->lang) {
420 $newL10n = clone $this;
421 $newL10n->loadTranslationTable($lang);