<?php
+/**
+ * @copyright Copyright (C) 2010-2023, the Friendica project
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
namespace Friendica\Core;
-use Friendica\Core\Config\IConfiguration;
-use Friendica\Core\Session\ISession;
+use Friendica\Core\Config\Capability\IManageConfigValues;
+use Friendica\Core\Session\Capability\IHandleSessions;
use Friendica\Database\Database;
use Friendica\Util\Strings;
-use Psr\Log\LoggerInterface;
/**
* Provide Language, Translation, and Localization functions to the application
*/
class L10n
{
+ /** @var string The default language */
+ const DEFAULT = 'en';
+ /** @var string[] The language names in their language */
+ const LANG_NAMES = [
+ 'ar' => 'العربية',
+ 'bg' => 'Български',
+ 'ca' => 'Català',
+ 'cs' => 'Česky',
+ 'da-dk' => 'Dansk (Danmark)',
+ 'de' => 'Deutsch',
+ 'en-gb' => 'English (United Kingdom)',
+ 'en-us' => 'English (United States)',
+ 'en' => 'English (Default)',
+ 'eo' => 'Esperanto',
+ 'es' => 'Español',
+ 'et' => 'Eesti',
+ 'fi-fi' => 'Suomi',
+ 'fr' => 'Français',
+ 'gd' => 'Gàidhlig',
+ 'hu' => 'Magyar',
+ 'is' => 'Íslenska',
+ 'it' => 'Italiano',
+ 'ja' => '日本語',
+ 'nb-no' => 'Norsk bokmål',
+ 'nl' => 'Nederlands',
+ 'pl' => 'Polski',
+ 'pt-br' => 'Português Brasileiro',
+ 'ro' => 'Română',
+ 'ru' => 'Русский',
+ 'sv' => 'Svenska',
+ 'zh-cn' => '简体中文',
+ ];
+
/**
* A string indicating the current language used for translation:
* - Two-letter ISO 639-1 code.
* @var Database
*/
private $dba;
-
/**
- * @var LoggerInterface
+ * @var IManageConfigValues
*/
- private $logger;
+ private $config;
- public function __construct(IConfiguration $config, Database $dba, LoggerInterface $logger, ISession $session, array $server, array $get)
+ public function __construct(IManageConfigValues $config, Database $dba, IHandleSessions $session, array $server, array $get)
{
$this->dba = $dba;
- $this->logger = $logger;
+ $this->config = $config;
- $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', 'en')));
+ $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', self::DEFAULT)));
$this->setSessionVariable($session);
$this->setLangFromSession($session);
}
/**
* Sets the language session variable
*/
- private function setSessionVariable(ISession $session)
+ private function setSessionVariable(IHandleSessions $session)
{
if ($session->get('authenticated') && !$session->get('language')) {
$session->set('language', $this->lang);
}
}
- private function setLangFromSession(ISession $session)
+ private function setLangFromSession(IHandleSessions $session)
{
if ($session->get('language') !== $this->lang) {
- $this->loadTranslationTable($session->get('language'));
+ $this->loadTranslationTable($session->get('language') ?? $this->lang);
}
}
* Uses an App object shim since all the strings files refer to $a->strings
*
* @param string $lang language code to load
- *
+ * @return void
* @throws \Exception
*/
- private function loadTranslationTable($lang)
+ private function loadTranslationTable(string $lang)
{
$lang = Strings::sanitizeFilePathItem($lang);
$a->strings = [];
// load enabled addons strings
- $addons = $this->dba->select('addon', ['name'], ['installed' => true]);
- while ($p = $this->dba->fetch($addons)) {
- $name = Strings::sanitizeFilePathItem($p['name']);
- if (file_exists("addon/$name/lang/$lang/strings.php")) {
- include __DIR__ . "/../../../addon/$name/lang/$lang/strings.php";
+ $addons = array_keys($this->config->get('addons') ?? []);
+ foreach ($addons as $addon) {
+ $name = Strings::sanitizeFilePathItem($addon);
+ if (file_exists(__DIR__ . "/../../addon/$name/lang/$lang/strings.php")) {
+ include __DIR__ . "/../../addon/$name/lang/$lang/strings.php";
}
}
- if (file_exists(__DIR__ . "/../../../view/lang/$lang/strings.php")) {
- include __DIR__ . "/../../../view/lang/$lang/strings.php";
+ if (file_exists(__DIR__ . "/../../view/lang/$lang/strings.php")) {
+ include __DIR__ . "/../../view/lang/$lang/strings.php";
}
$this->lang = $lang;
}
/**
- * @brief Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
+ * Returns the preferred language from the HTTP_ACCEPT_LANGUAGE header
*
* @param string $sysLang The default fallback language
* @param array $server The $_SERVER array
*
* @return string The two-letter language code
*/
- public static function detectLanguage(array $server, array $get, string $sysLang = 'en')
+ public static function detectLanguage(array $server, array $get, string $sysLang = self::DEFAULT): string
{
$lang_variable = $server['HTTP_ACCEPT_LANGUAGE'] ?? null;
- $acceptedLanguages = preg_split('/,\s*/', $lang_variable);
-
- if (empty($acceptedLanguages)) {
+ if (empty($lang_variable)) {
$acceptedLanguages = [];
+ } else {
+ $acceptedLanguages = preg_split('/,\s*/', $lang_variable);
}
// Add get as absolute quality accepted language (except this language isn't valid)
while (count($lang_code)) {
// try to mix them so we can get double-code parts too
$match_lang = strtolower(join('-', $lang_code));
- if (file_exists(__DIR__ . "/../../../view/lang/$match_lang") &&
- is_dir(__DIR__ . "/../../../view/lang/$match_lang")) {
+ if (file_exists(__DIR__ . "/../../view/lang/$match_lang") &&
+ is_dir(__DIR__ . "/../../view/lang/$match_lang")) {
if ($lang_quality > $current_q) {
$current_lang = $match_lang;
$current_q = $lang_quality;
*
* @return string
*/
- public function t($s, ...$vars)
+ public function t(string $s, ...$vars): string
{
if (empty($s)) {
return '';
* @param string $singular
* @param string $plural
* @param int $count
+ * @param array $vars Variables to interpolate in the translation string
*
* @return string
* @throws \Exception
*/
- public function tt(string $singular, string $plural, int $count)
+ public function tt(string $singular, string $plural, int $count, ...$vars): string
{
+ $s = null;
+
if (!empty($this->strings[$singular])) {
$t = $this->strings[$singular];
if (is_array($t)) {
$i = $this->stringPluralSelectDefault($count);
}
- // for some languages there is only a single array item
- if (!isset($t[$i])) {
- $s = $t[0];
- } else {
+ if (isset($t[$i])) {
$s = $t[$i];
+ } elseif (count($t) > 0) {
+ // for some languages there is only a single array item
+ $s = $t[0];
}
+ // if $t is empty, skip it, because empty strings array are intended
+ // to make string file smaller when there's no translation
} else {
$s = $t;
}
- } elseif ($this->stringPluralSelectDefault($count)) {
+ }
+
+ if (is_null($s) && $this->stringPluralSelectDefault($count)) {
$s = $plural;
- } else {
+ } elseif (is_null($s)) {
$s = $singular;
}
- $s = @sprintf($s, $count);
+ // We mute errors here because the translation strings may not be referencing the count at all,
+ // but we still have to try the interpolation just in case it is indeed referenced.
+ $s = @sprintf($s, $count, ...$vars);
return $s;
}
*
* @return bool
*/
- private function stringPluralSelectDefault($n)
+ private function stringPluralSelectDefault(int $n): bool
{
return $n != 1;
}
*
* Scans the view/lang directory for the existence of "strings.php" files, and
* returns an alphabetical list of their folder names (@-char language codes).
- * Adds the english language if it's missing from the list.
+ * Adds the english language if it's missing from the list. Folder names are
+ * replaced by nativ language names.
*
- * Ex: array('de' => 'de', 'en' => 'en', 'fr' => 'fr', ...)
+ * Ex: array('de' => 'Deutsch', 'en' => 'English', 'fr' => 'Français', ...)
*
* @return array
*/
- public static function getAvailableLanguages()
+ public function getAvailableLanguages(bool $additional = false): array
{
$langs = [];
$strings_file_paths = glob('view/lang/*/strings.php');
asort($strings_file_paths);
foreach ($strings_file_paths as $strings_file_path) {
$path_array = explode('/', $strings_file_path);
- $langs[$path_array[2]] = $path_array[2];
+ $langs[$path_array[2]] = self::LANG_NAMES[$path_array[2]] ?? $path_array[2];
+ }
+
+ if ($additional) {
+ // See https://github.com/friendica/friendica/issues/10511
+ // Persian is manually added to language detection until a persian translation is provided for the interface, at
+ // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
+ // Additionally some more languages are added to that list that are used in the Fediverse.
+ $additional_langs = [
+ 'af' => 'Afrikaans',
+ 'az-Latn' => 'azərbaycan dili',
+ 'bs-Latn' => 'bosanski jezik',
+ 'be' => 'беларуская мова',
+ 'bn' => 'বাংলা',
+ 'cy' => 'Cymraeg',
+ 'el-monoton' => 'Ελληνικά',
+ 'eu' => 'euskara',
+ 'fa' => 'فارسی',
+ 'ga' => 'Gaeilge',
+ 'gl' => 'Galego',
+ 'he' => 'עברית',
+ 'hi' => 'हिन्दी',
+ 'hr' => 'Hrvatski',
+ 'hy' => 'Հայերեն',
+ 'id' => 'bahasa Indonesia',
+ 'jv' => 'Basa Jawa',
+ 'ka' => 'ქართული',
+ 'ko' => '한국인',
+ 'lt' => 'lietuvių',
+ 'lv' => 'latviešu',
+ 'ms-Latn' => 'Bahasa Melayu',
+ 'sr-Cyrl' => 'српски језик',
+ 'sk' => 'slovenský',
+ 'sl' => 'Slovenščina',
+ 'sq' => 'Shqip',
+ 'sw' => 'Kiswahili',
+ 'ta' => 'தமிழ்',
+ 'th' => 'แบบไทย',
+ 'tl' => 'Wikang Tagalog',
+ 'tr' => 'Türkçe',
+ 'pt-PT' => 'Português',
+ 'uk' => 'Українська',
+ 'uz' => 'Ўзбек',
+ 'vi' => 'Tiếng Việt',
+ 'zh-hant' => '繁體',
+ ];
+ $langs = array_merge($additional_langs, $langs);
+ ksort($langs);
}
}
return $langs;
}
+ /**
+ * The language detection routine uses some slightly different language codes.
+ * This function changes the language array accordingly.
+ *
+ * @param array $languages
+ * @return array
+ */
+ public function convertForLanguageDetection(array $languages): array
+ {
+ foreach ($languages as $key => $language) {
+ $newkey = $this->convertCodeForLanguageDetection($key);
+ if ($newkey != $key) {
+ if (!isset($languages[$newkey])) {
+ $languages[$newkey] = $language;
+ }
+ unset($languages[$key]);
+ }
+ }
+
+ ksort($languages);
+
+ return $languages;
+ }
+
+ /**
+ * The language detection routine uses some slightly different language codes.
+ * This function changes the language codes accordingly.
+ *
+ * @param string $language
+ * @return string
+ */
+ public function convertCodeForLanguageDetection(string $language): string
+ {
+ switch ($language) {
+ case 'da-dk':
+ return 'da';
+ case 'en-us':
+ case 'en-gb':
+ return 'en';
+ case 'fi-fi':
+ return 'fi';
+ case 'nb-no':
+ return 'nb';
+ case 'pt-br':
+ return 'pt-BR';
+ case 'zh-cn':
+ return 'zh-Hans';
+ default:
+ return $language;
+ }
+ }
+
/**
* Translate days and months names.
*
* @param string $s String with day or month name.
- *
* @return string Translated string.
*/
- public function getDay($s)
+ public function getDay(string $s): string
{
$ret = str_replace(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
[$this->t('Monday'), $this->t('Tuesday'), $this->t('Wednesday'), $this->t('Thursday'), $this->t('Friday'), $this->t('Saturday'), $this->t('Sunday')],
* Translate short days and months names.
*
* @param string $s String with short day or month name.
- *
* @return string Translated string.
*/
- public function getDayShort($s)
+ public function getDayShort(string $s): string
{
$ret = str_replace(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
[$this->t('Mon'), $this->t('Tue'), $this->t('Wed'), $this->t('Thu'), $this->t('Fri'), $this->t('Sat'), $this->t('Sun')],
return $ret;
}
- /**
- * Load poke verbs
- *
- * @return array index is present tense verb
- * value is array containing past tense verb, translation of present, translation of past
- * @throws \Friendica\Network\HTTPException\InternalServerErrorException
- * @hook poke_verbs pokes array
- */
- public function getPokeVerbs()
- {
- // index is present tense verb
- // value is array containing past tense verb, translation of present, translation of past
- $arr = [
- 'poke' => ['poked', $this->t('poke'), $this->t('poked')],
- 'ping' => ['pinged', $this->t('ping'), $this->t('pinged')],
- 'prod' => ['prodded', $this->t('prod'), $this->t('prodded')],
- 'slap' => ['slapped', $this->t('slap'), $this->t('slapped')],
- 'finger' => ['fingered', $this->t('finger'), $this->t('fingered')],
- 'rebuff' => ['rebuffed', $this->t('rebuff'), $this->t('rebuffed')],
- ];
-
- Hook::callAll('poke_verbs', $arr);
-
- return $arr;
- }
-
/**
* Creates a new L10n instance based on the given langauge
*
* @return static A new L10n instance
* @throws \Exception
*/
- public function withLang(string $lang)
+ public function withLang(string $lang): L10n
{
// Don't create a new instance for same language
if ($lang === $this->lang) {