Factory.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\L10N;
  9. use OCP\App\AppPathNotFoundException;
  10. use OCP\App\IAppManager;
  11. use OCP\ICache;
  12. use OCP\ICacheFactory;
  13. use OCP\IConfig;
  14. use OCP\IRequest;
  15. use OCP\IUser;
  16. use OCP\IUserSession;
  17. use OCP\L10N\IFactory;
  18. use OCP\L10N\ILanguageIterator;
  19. use function is_null;
  20. /**
  21. * A factory that generates language instances
  22. */
  23. class Factory implements IFactory {
  24. /** @var string */
  25. protected $requestLanguage = '';
  26. /**
  27. * cached instances
  28. * @var array Structure: Lang => App => \OCP\IL10N
  29. */
  30. protected $instances = [];
  31. /**
  32. * @var array Structure: App => string[]
  33. */
  34. protected $availableLanguages = [];
  35. /**
  36. * @var array
  37. */
  38. protected $localeCache = [];
  39. /**
  40. * @var array
  41. */
  42. protected $availableLocales = [];
  43. /**
  44. * @var array Structure: string => callable
  45. */
  46. protected $pluralFunctions = [];
  47. public const COMMON_LANGUAGE_CODES = [
  48. 'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
  49. 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
  50. ];
  51. private ICache $cache;
  52. public function __construct(
  53. protected IConfig $config,
  54. protected IRequest $request,
  55. protected IUserSession $userSession,
  56. ICacheFactory $cacheFactory,
  57. protected string $serverRoot,
  58. protected IAppManager $appManager,
  59. ) {
  60. $this->cache = $cacheFactory->createLocal('L10NFactory');
  61. }
  62. /**
  63. * Get a language instance
  64. *
  65. * @param string $app
  66. * @param string|null $lang
  67. * @param string|null $locale
  68. * @return \OCP\IL10N
  69. */
  70. public function get($app, $lang = null, $locale = null) {
  71. return new LazyL10N(function () use ($app, $lang, $locale) {
  72. $app = \OC_App::cleanAppId($app);
  73. if ($lang !== null) {
  74. $lang = str_replace(['\0', '/', '\\', '..'], '', $lang);
  75. }
  76. $forceLang = $this->config->getSystemValue('force_language', false);
  77. if (is_string($forceLang)) {
  78. $lang = $forceLang;
  79. }
  80. $forceLocale = $this->config->getSystemValue('force_locale', false);
  81. if (is_string($forceLocale)) {
  82. $locale = $forceLocale;
  83. }
  84. if ($lang === null || !$this->languageExists($app, $lang)) {
  85. $lang = $this->findLanguage($app);
  86. }
  87. if ($locale === null || !$this->localeExists($locale)) {
  88. $locale = $this->findLocale($lang);
  89. }
  90. if (!isset($this->instances[$lang][$app])) {
  91. $this->instances[$lang][$app] = new L10N(
  92. $this,
  93. $app,
  94. $lang,
  95. $locale,
  96. $this->getL10nFilesForApp($app, $lang)
  97. );
  98. }
  99. return $this->instances[$lang][$app];
  100. });
  101. }
  102. /**
  103. * Find the best language
  104. *
  105. * @param string|null $appId App id or null for core
  106. *
  107. * @return string language If nothing works it returns 'en'
  108. */
  109. public function findLanguage(?string $appId = null): string {
  110. // Step 1: Forced language always has precedence over anything else
  111. $forceLang = $this->config->getSystemValue('force_language', false);
  112. if (is_string($forceLang)) {
  113. $this->requestLanguage = $forceLang;
  114. }
  115. // Step 2: Return cached language
  116. if ($this->requestLanguage !== '' && $this->languageExists($appId, $this->requestLanguage)) {
  117. return $this->requestLanguage;
  118. }
  119. /**
  120. * Step 3: At this point Nextcloud might not yet be installed and thus the lookup
  121. * in the preferences table might fail. For this reason we need to check
  122. * whether the instance has already been installed
  123. *
  124. * @link https://github.com/owncloud/core/issues/21955
  125. */
  126. if ($this->config->getSystemValueBool('installed', false)) {
  127. $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
  128. if (!is_null($userId)) {
  129. $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
  130. } else {
  131. $userLang = null;
  132. }
  133. } else {
  134. $userId = null;
  135. $userLang = null;
  136. }
  137. if ($userLang) {
  138. $this->requestLanguage = $userLang;
  139. if ($this->languageExists($appId, $userLang)) {
  140. return $userLang;
  141. }
  142. }
  143. // Step 4: Check the request headers
  144. try {
  145. // Try to get the language from the Request
  146. $lang = $this->getLanguageFromRequest($appId);
  147. if ($userId !== null && $appId === null && !$userLang) {
  148. $this->config->setUserValue($userId, 'core', 'lang', $lang);
  149. }
  150. return $lang;
  151. } catch (LanguageNotFoundException $e) {
  152. // Finding language from request failed fall back to default language
  153. $defaultLanguage = $this->config->getSystemValue('default_language', false);
  154. if ($defaultLanguage !== false && $this->languageExists($appId, $defaultLanguage)) {
  155. return $defaultLanguage;
  156. }
  157. }
  158. // Step 5: fall back to English
  159. return 'en';
  160. }
  161. public function findGenericLanguage(?string $appId = null): string {
  162. // Step 1: Forced language always has precedence over anything else
  163. $forcedLanguage = $this->config->getSystemValue('force_language', false);
  164. if ($forcedLanguage !== false) {
  165. return $forcedLanguage;
  166. }
  167. // Step 2: Check if we have a default language
  168. $defaultLanguage = $this->config->getSystemValue('default_language', false);
  169. if ($defaultLanguage !== false && $this->languageExists($appId, $defaultLanguage)) {
  170. return $defaultLanguage;
  171. }
  172. // Step 3.1: Check if Nextcloud is already installed before we try to access user info
  173. if (!$this->config->getSystemValueBool('installed', false)) {
  174. return 'en';
  175. }
  176. // Step 3.2: Check the current user (if any) for their preferred language
  177. $user = $this->userSession->getUser();
  178. if ($user !== null) {
  179. $userLang = $this->config->getUserValue($user->getUID(), 'core', 'lang', null);
  180. if ($userLang !== null) {
  181. return $userLang;
  182. }
  183. }
  184. // Step 4: Check the request headers
  185. try {
  186. return $this->getLanguageFromRequest($appId);
  187. } catch (LanguageNotFoundException $e) {
  188. // Ignore and continue
  189. }
  190. // Step 5: fall back to English
  191. return 'en';
  192. }
  193. /**
  194. * find the best locale
  195. *
  196. * @param string $lang
  197. * @return null|string
  198. */
  199. public function findLocale($lang = null) {
  200. $forceLocale = $this->config->getSystemValue('force_locale', false);
  201. if (is_string($forceLocale) && $this->localeExists($forceLocale)) {
  202. return $forceLocale;
  203. }
  204. if ($this->config->getSystemValueBool('installed', false)) {
  205. $userId = $this->userSession->getUser() !== null ? $this->userSession->getUser()->getUID() : null;
  206. $userLocale = null;
  207. if ($userId !== null) {
  208. $userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
  209. }
  210. } else {
  211. $userId = null;
  212. $userLocale = null;
  213. }
  214. if ($userLocale && $this->localeExists($userLocale)) {
  215. return $userLocale;
  216. }
  217. // Default : use system default locale
  218. $defaultLocale = $this->config->getSystemValue('default_locale', false);
  219. if ($defaultLocale !== false && $this->localeExists($defaultLocale)) {
  220. return $defaultLocale;
  221. }
  222. // If no user locale set, use lang as locale
  223. if ($lang !== null && $this->localeExists($lang)) {
  224. return $lang;
  225. }
  226. // At last, return USA
  227. return 'en_US';
  228. }
  229. /**
  230. * find the matching lang from the locale
  231. *
  232. * @param string $app
  233. * @param string $locale
  234. * @return null|string
  235. */
  236. public function findLanguageFromLocale(string $app = 'core', ?string $locale = null) {
  237. if ($this->languageExists($app, $locale)) {
  238. return $locale;
  239. }
  240. // Try to split e.g: fr_FR => fr
  241. $locale = explode('_', $locale)[0];
  242. if ($this->languageExists($app, $locale)) {
  243. return $locale;
  244. }
  245. }
  246. /**
  247. * Find all available languages for an app
  248. *
  249. * @param string|null $app App id or null for core
  250. * @return string[] an array of available languages
  251. */
  252. public function findAvailableLanguages($app = null): array {
  253. $key = $app;
  254. if ($key === null) {
  255. $key = 'null';
  256. }
  257. if ($availableLanguages = $this->cache->get($key)) {
  258. $this->availableLanguages[$key] = $availableLanguages;
  259. }
  260. // also works with null as key
  261. if (!empty($this->availableLanguages[$key])) {
  262. return $this->availableLanguages[$key];
  263. }
  264. $available = ['en']; //english is always available
  265. $dir = $this->findL10nDir($app);
  266. if (is_dir($dir)) {
  267. $files = scandir($dir);
  268. if ($files !== false) {
  269. foreach ($files as $file) {
  270. if (str_ends_with($file, '.json') && !str_starts_with($file, 'l10n')) {
  271. $available[] = substr($file, 0, -5);
  272. }
  273. }
  274. }
  275. }
  276. // merge with translations from theme
  277. $theme = $this->config->getSystemValueString('theme');
  278. if (!empty($theme)) {
  279. $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
  280. if (is_dir($themeDir)) {
  281. $files = scandir($themeDir);
  282. if ($files !== false) {
  283. foreach ($files as $file) {
  284. if (str_ends_with($file, '.json') && !str_starts_with($file, 'l10n')) {
  285. $available[] = substr($file, 0, -5);
  286. }
  287. }
  288. }
  289. }
  290. }
  291. $this->availableLanguages[$key] = $available;
  292. $this->cache->set($key, $available, 60);
  293. return $available;
  294. }
  295. /**
  296. * @return array|mixed
  297. */
  298. public function findAvailableLocales() {
  299. if (!empty($this->availableLocales)) {
  300. return $this->availableLocales;
  301. }
  302. $localeData = file_get_contents(\OC::$SERVERROOT . '/resources/locales.json');
  303. $this->availableLocales = \json_decode($localeData, true);
  304. return $this->availableLocales;
  305. }
  306. /**
  307. * @param string|null $app App id or null for core
  308. * @param string $lang
  309. * @return bool
  310. */
  311. public function languageExists($app, $lang) {
  312. if ($lang === 'en') { //english is always available
  313. return true;
  314. }
  315. $languages = $this->findAvailableLanguages($app);
  316. return in_array($lang, $languages);
  317. }
  318. public function getLanguageIterator(?IUser $user = null): ILanguageIterator {
  319. $user = $user ?? $this->userSession->getUser();
  320. if ($user === null) {
  321. throw new \RuntimeException('Failed to get an IUser instance');
  322. }
  323. return new LanguageIterator($user, $this->config);
  324. }
  325. /**
  326. * Return the language to use when sending something to a user
  327. *
  328. * @param IUser|null $user
  329. * @return string
  330. * @since 20.0.0
  331. */
  332. public function getUserLanguage(?IUser $user = null): string {
  333. $language = $this->config->getSystemValue('force_language', false);
  334. if ($language !== false) {
  335. return $language;
  336. }
  337. if ($user instanceof IUser) {
  338. $language = $this->config->getUserValue($user->getUID(), 'core', 'lang', null);
  339. if ($language !== null) {
  340. return $language;
  341. }
  342. // Use language from request
  343. if ($this->userSession->getUser() instanceof IUser &&
  344. $user->getUID() === $this->userSession->getUser()->getUID()) {
  345. try {
  346. return $this->getLanguageFromRequest();
  347. } catch (LanguageNotFoundException $e) {
  348. }
  349. }
  350. }
  351. return $this->config->getSystemValueString('default_language', 'en');
  352. }
  353. /**
  354. * @param string $locale
  355. * @return bool
  356. */
  357. public function localeExists($locale) {
  358. if ($locale === 'en') { //english is always available
  359. return true;
  360. }
  361. if ($this->localeCache === []) {
  362. $locales = $this->findAvailableLocales();
  363. foreach ($locales as $l) {
  364. $this->localeCache[$l['code']] = true;
  365. }
  366. }
  367. return isset($this->localeCache[$locale]);
  368. }
  369. /**
  370. * @throws LanguageNotFoundException
  371. */
  372. private function getLanguageFromRequest(?string $app = null): string {
  373. $header = $this->request->getHeader('ACCEPT_LANGUAGE');
  374. if ($header !== '') {
  375. $available = $this->findAvailableLanguages($app);
  376. // E.g. make sure that 'de' is before 'de_DE'.
  377. sort($available);
  378. $preferences = preg_split('/,\s*/', strtolower($header));
  379. foreach ($preferences as $preference) {
  380. [$preferred_language] = explode(';', $preference);
  381. $preferred_language = str_replace('-', '_', $preferred_language);
  382. $preferred_language_parts = explode('_', $preferred_language);
  383. foreach ($available as $available_language) {
  384. if ($preferred_language === strtolower($available_language)) {
  385. return $this->respectDefaultLanguage($app, $available_language);
  386. }
  387. if (strtolower($available_language) === $preferred_language_parts[0].'_'.end($preferred_language_parts)) {
  388. return $available_language;
  389. }
  390. }
  391. // Fallback from de_De to de
  392. foreach ($available as $available_language) {
  393. if (substr($preferred_language, 0, 2) === $available_language) {
  394. return $available_language;
  395. }
  396. }
  397. }
  398. }
  399. throw new LanguageNotFoundException();
  400. }
  401. /**
  402. * if default language is set to de_DE (formal German) this should be
  403. * preferred to 'de' (non-formal German) if possible
  404. */
  405. protected function respectDefaultLanguage(?string $app, string $lang): string {
  406. $result = $lang;
  407. $defaultLanguage = $this->config->getSystemValue('default_language', false);
  408. // use formal version of german ("Sie" instead of "Du") if the default
  409. // language is set to 'de_DE' if possible
  410. if (
  411. is_string($defaultLanguage) &&
  412. strtolower($lang) === 'de' &&
  413. strtolower($defaultLanguage) === 'de_de' &&
  414. $this->languageExists($app, 'de_DE')
  415. ) {
  416. $result = 'de_DE';
  417. }
  418. return $result;
  419. }
  420. /**
  421. * Checks if $sub is a subdirectory of $parent
  422. *
  423. * @param string $sub
  424. * @param string $parent
  425. * @return bool
  426. */
  427. private function isSubDirectory($sub, $parent) {
  428. // Check whether $sub contains no ".."
  429. if (str_contains($sub, '..')) {
  430. return false;
  431. }
  432. // Check whether $sub is a subdirectory of $parent
  433. if (str_starts_with($sub, $parent)) {
  434. return true;
  435. }
  436. return false;
  437. }
  438. /**
  439. * Get a list of language files that should be loaded
  440. *
  441. * @return string[]
  442. */
  443. private function getL10nFilesForApp(string $app, string $lang): array {
  444. $languageFiles = [];
  445. $i18nDir = $this->findL10nDir($app);
  446. $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
  447. if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
  448. || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
  449. || $this->isSubDirectory($transFile, $this->appManager->getAppPath($app) . '/l10n/'))
  450. && file_exists($transFile)
  451. ) {
  452. // load the translations file
  453. $languageFiles[] = $transFile;
  454. }
  455. // merge with translations from theme
  456. $theme = $this->config->getSystemValueString('theme');
  457. if (!empty($theme)) {
  458. $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
  459. if (file_exists($transFile)) {
  460. $languageFiles[] = $transFile;
  461. }
  462. }
  463. return $languageFiles;
  464. }
  465. /**
  466. * find the l10n directory
  467. *
  468. * @param string $app App id or empty string for core
  469. * @return string directory
  470. */
  471. protected function findL10nDir($app = null) {
  472. if (in_array($app, ['core', 'lib'])) {
  473. if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
  474. return $this->serverRoot . '/' . $app . '/l10n/';
  475. }
  476. } elseif ($app) {
  477. try {
  478. return $this->appManager->getAppPath($app) . '/l10n/';
  479. } catch (AppPathNotFoundException) {
  480. /* App not found, continue */
  481. }
  482. }
  483. return $this->serverRoot . '/core/l10n/';
  484. }
  485. /**
  486. * @inheritDoc
  487. */
  488. public function getLanguages(): array {
  489. $forceLanguage = $this->config->getSystemValue('force_language', false);
  490. if ($forceLanguage !== false) {
  491. $l = $this->get('lib', $forceLanguage);
  492. $potentialName = $l->t('__language_name__');
  493. return [
  494. 'commonLanguages' => [[
  495. 'code' => $forceLanguage,
  496. 'name' => $potentialName,
  497. ]],
  498. 'otherLanguages' => [],
  499. ];
  500. }
  501. $languageCodes = $this->findAvailableLanguages();
  502. $commonLanguages = [];
  503. $otherLanguages = [];
  504. foreach ($languageCodes as $lang) {
  505. $l = $this->get('lib', $lang);
  506. // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
  507. $potentialName = $l->t('__language_name__');
  508. if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') { //first check if the language name is in the translation file
  509. $ln = [
  510. 'code' => $lang,
  511. 'name' => $potentialName
  512. ];
  513. } elseif ($lang === 'en') {
  514. $ln = [
  515. 'code' => $lang,
  516. 'name' => 'English (US)'
  517. ];
  518. } else { //fallback to language code
  519. $ln = [
  520. 'code' => $lang,
  521. 'name' => $lang
  522. ];
  523. }
  524. // put appropriate languages into appropriate arrays, to print them sorted
  525. // common languages -> divider -> other languages
  526. if (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
  527. $commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
  528. } else {
  529. $otherLanguages[] = $ln;
  530. }
  531. }
  532. ksort($commonLanguages);
  533. // sort now by displayed language not the iso-code
  534. usort($otherLanguages, function ($a, $b) {
  535. if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
  536. // If a doesn't have a name, but b does, list b before a
  537. return 1;
  538. }
  539. if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
  540. // If a does have a name, but b doesn't, list a before b
  541. return -1;
  542. }
  543. // Otherwise compare the names
  544. return strcmp($a['name'], $b['name']);
  545. });
  546. return [
  547. // reset indexes
  548. 'commonLanguages' => array_values($commonLanguages),
  549. 'otherLanguages' => $otherLanguages
  550. ];
  551. }
  552. }