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)
59 $this->logger = $logger;
61 $this->loadTranslationTable(L10n::detectLanguage($config->get('system', 'language', 'en')));
63 \Friendica\Core\L10n::init($this);
67 * Returns the current language code
69 * @return string Language code
71 public function getCurrentLang()
77 * Sets the language session variable
79 public function setSessionVariable()
81 if (Session::get('authenticated') && !Session::get('language')) {
82 $_SESSION['language'] = $this->lang;
83 // we haven't loaded user data yet, but we need user language
84 if (Session::get('uid')) {
85 $user = $this->dba->selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
86 if ($this->dba->isResult($user)) {
87 $_SESSION['language'] = $user['language'];
92 if (isset($_GET['lang'])) {
93 Session::set('language', $_GET['lang']);
97 public function setLangFromSession()
99 if (Session::get('language') !== $this->lang) {
100 $this->loadTranslationTable(Session::get('language'));
105 * This function should be called before formatting messages in a specific target language
106 * different from the current user/system language.
108 * It saves the current translation strings in a separate variable and loads new translations strings.
110 * If called repeatedly, it won't save the translation strings again, just load the new ones.
112 * @param string $lang Language code
116 * @brief Stores the current language strings and load a different language.
118 public function pushLang($lang)
120 if ($lang === $this->lang) {
124 if (empty($this->langSave)) {
125 $this->langSave = $this->lang;
126 $this->stringsSave = $this->strings;
129 $this->loadTranslationTable($lang);
133 * Restores the original user/system language after having used pushLang()
135 public function popLang()
137 if (!isset($this->langSave)) {
141 $this->strings = $this->stringsSave;
142 $this->lang = $this->langSave;
144 $this->stringsSave = null;
145 $this->langSave = null;
149 * Loads string translation table
151 * First addon strings are loaded, then globals
153 * Uses an App object shim since all the strings files refer to $a->strings
155 * @param string $lang language code to load
159 private function loadTranslationTable($lang)
161 $lang = Strings::sanitizeFilePathItem($lang);
163 $a = new \stdClass();
166 // load enabled addons strings
167 $addons = $this->dba->select('addon', ['name'], ['installed' => true]);
168 while ($p = $this->dba->fetch($addons)) {
169 $name = Strings::sanitizeFilePathItem($p['name']);
170 if (file_exists("addon/$name/lang/$lang/strings.php")) {
171 include "addon/$name/lang/$lang/strings.php";
175 if (file_exists("view/lang/$lang/strings.php")) {
176 include "view/lang/$lang/strings.php";
180 $this->strings = $a->strings;
186 * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
188 * @param string $sysLang The default fallback language
190 * @return string The two-letter language code
192 public static function detectLanguage(string $sysLang = 'en')
196 if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
197 // break up string into pieces (languages and q factors)
198 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);
200 if (count($lang_parse[1])) {
201 // go through the list of prefered languages and add a generic language
202 // for sub-linguas (e.g. de-ch will add de) if not already in array
203 for ($i = 0; $i < count($lang_parse[1]); $i++) {
204 $lang_list[] = strtolower($lang_parse[1][$i]);
205 if (strlen($lang_parse[1][$i]) > 3) {
206 $dashpos = strpos($lang_parse[1][$i], '-');
207 if (!in_array(substr($lang_parse[1][$i], 0, $dashpos), $lang_list)) {
208 $lang_list[] = strtolower(substr($lang_parse[1][$i], 0, $dashpos));
215 if (isset($_GET['lang'])) {
216 $lang_list = [$_GET['lang']];
219 // check if we have translations for the preferred languages and pick the 1st that has
220 foreach ($lang_list as $lang) {
221 if ($lang === 'en' || (file_exists("view/lang/$lang") && is_dir("view/lang/$lang"))) {
226 if (isset($preferred)) {
230 // in case none matches, get the system wide configured language, or fall back to English
235 * @brief Return the localized version of the provided string with optional string interpolation
237 * This function takes a english string as parameter, and if a localized version
238 * exists for the current language, substitutes it before performing an eventual
239 * string interpolation (sprintf) with additional optional arguments.
242 * - L10n::t('This is an example')
243 * - L10n::t('URL %s returned no result', $url)
244 * - L10n::t('Current version: %s, new version: %s', $current_version, $new_version)
247 * @param array $vars Variables to interpolate in the translation string
251 public function t($s, ...$vars)
257 if (!empty($this->strings[$s])) {
258 $t = $this->strings[$s];
259 $s = is_array($t) ? $t[0] : $t;
262 if (count($vars) > 0) {
263 $s = sprintf($s, ...$vars);
270 * @brief Return the localized version of a singular/plural string with optional string interpolation
272 * This function takes two english strings as parameters, singular and plural, as
273 * well as a count. If a localized version exists for the current language, they
274 * are used instead. Discrimination between singular and plural is done using the
275 * localized function if any or the default one. Finally, a string interpolation
276 * is performed using the count as parameter.
279 * - L10n::tt('Like', 'Likes', $count)
280 * - L10n::tt("%s user deleted", "%s users deleted", count($users))
282 * @param string $singular
283 * @param string $plural
289 public function tt(string $singular, string $plural, int $count)
291 if (!empty($this->strings[$singular])) {
292 $t = $this->strings[$singular];
294 $plural_function = 'string_plural_select_' . str_replace('-', '_', $this->lang);
295 if (function_exists($plural_function)) {
296 $i = $plural_function($count);
298 $i = $this->stringPluralSelectDefault($count);
301 // for some languages there is only a single array item
302 if (!isset($t[$i])) {
310 } elseif ($this->stringPluralSelectDefault($count)) {
316 $s = @sprintf($s, $count);
322 * Provide a fallback which will not collide with a function defined in any language file
328 private function stringPluralSelectDefault($n)
334 * Return installed languages codes as associative array
336 * Scans the view/lang directory for the existence of "strings.php" files, and
337 * returns an alphabetical list of their folder names (@-char language codes).
338 * Adds the english language if it's missing from the list.
340 * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
344 public static function getAvailableLanguages()
347 $strings_file_paths = glob('view/lang/*/strings.php');
349 if (is_array($strings_file_paths) && count($strings_file_paths)) {
350 if (!in_array('view/lang/en/strings.php', $strings_file_paths)) {
351 $strings_file_paths[] = 'view/lang/en/strings.php';
353 asort($strings_file_paths);
354 foreach ($strings_file_paths as $strings_file_path) {
355 $path_array = explode('/', $strings_file_path);
356 $langs[$path_array[2]] = $path_array[2];
363 * Translate days and months names.
365 * @param string $s String with day or month name.
367 * @return string Translated string.
369 public function getDay($s)
371 $ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
372 [$this->t('Monday'), $this->t('Tuesday'), $this->t('Wednesday'), $this->t('Thursday'), $this->t('Friday'), $this->t('Saturday'), $this->t('Sunday')],
375 $ret = str_replace(['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
376 [$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')],
383 * Translate short days and months names.
385 * @param string $s String with short day or month name.
387 * @return string Translated string.
389 public function getDayShort($s)
391 $ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
392 [$this->t('Mon'), $this->t('Tue'), $this->t('Wed'), $this->t('Thu'), $this->t('Fri'), $this->t('Sat'), $this->t('Sun')],
395 $ret = str_replace(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
396 [$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')],
405 * @return array index is present tense verb
406 * value is array containing past tense verb, translation of present, translation of past
407 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
408 * @hook poke_verbs pokes array
410 public function getPokeVerbs()
412 // index is present tense verb
413 // value is array containing past tense verb, translation of present, translation of past
415 'poke' => ['poked', $this->t('poke'), $this->t('poked')],
416 'ping' => ['pinged', $this->t('ping'), $this->t('pinged')],
417 'prod' => ['prodded', $this->t('prod'), $this->t('prodded')],
418 'slap' => ['slapped', $this->t('slap'), $this->t('slapped')],
419 'finger' => ['fingered', $this->t('finger'), $this->t('fingered')],
420 'rebuff' => ['rebuffed', $this->t('rebuff'), $this->t('rebuffed')],
423 Hook::callAll('poke_verbs', $arr);