Factory.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright 2016 Roeland Jago Douma <roeland@famdouma.nl>
  5. * @copyright 2016 Lukas Reschke <lukas@statuscode.ch>
  6. *
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Bart Visscher <bartv@thisnet.nl>
  9. * @author Bjoern Schiessle <bjoern@schiessle.org>
  10. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  11. * @author Georg Ehrke <oc.list@georgehrke.com>
  12. * @author GretaD <gretadoci@gmail.com>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author John Molakvoæ <skjnldsv@protonmail.com>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author Morris Jobke <hey@morrisjobke.de>
  17. * @author Robin Appelman <robin@icewind.nl>
  18. * @author Robin McCorkell <robin@mccorkell.me.uk>
  19. * @author Roeland Jago Douma <roeland@famdouma.nl>
  20. * @author Thomas Citharel <nextcloud@tcit.fr>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OC\L10N;
  38. use OCP\IConfig;
  39. use OCP\IRequest;
  40. use OCP\IUser;
  41. use OCP\IUserSession;
  42. use OCP\L10N\IFactory;
  43. use OCP\L10N\ILanguageIterator;
  44. /**
  45. * A factory that generates language instances
  46. */
  47. class Factory implements IFactory {
  48. /** @var string */
  49. protected $requestLanguage = '';
  50. /**
  51. * cached instances
  52. * @var array Structure: Lang => App => \OCP\IL10N
  53. */
  54. protected $instances = [];
  55. /**
  56. * @var array Structure: App => string[]
  57. */
  58. protected $availableLanguages = [];
  59. /**
  60. * @var array
  61. */
  62. protected $localeCache = [];
  63. /**
  64. * @var array
  65. */
  66. protected $availableLocales = [];
  67. /**
  68. * @var array Structure: string => callable
  69. */
  70. protected $pluralFunctions = [];
  71. public const COMMON_LANGUAGE_CODES = [
  72. 'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
  73. 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
  74. ];
  75. /** @var IConfig */
  76. protected $config;
  77. /** @var IRequest */
  78. protected $request;
  79. /** @var IUserSession */
  80. protected $userSession;
  81. /** @var string */
  82. protected $serverRoot;
  83. /**
  84. * @param IConfig $config
  85. * @param IRequest $request
  86. * @param IUserSession $userSession
  87. * @param string $serverRoot
  88. */
  89. public function __construct(IConfig $config,
  90. IRequest $request,
  91. IUserSession $userSession,
  92. $serverRoot) {
  93. $this->config = $config;
  94. $this->request = $request;
  95. $this->userSession = $userSession;
  96. $this->serverRoot = $serverRoot;
  97. }
  98. /**
  99. * Get a language instance
  100. *
  101. * @param string $app
  102. * @param string|null $lang
  103. * @param string|null $locale
  104. * @return \OCP\IL10N
  105. */
  106. public function get($app, $lang = null, $locale = null) {
  107. return new LazyL10N(function () use ($app, $lang, $locale) {
  108. $app = \OC_App::cleanAppId($app);
  109. if ($lang !== null) {
  110. $lang = str_replace(['\0', '/', '\\', '..'], '', $lang);
  111. }
  112. $forceLang = $this->config->getSystemValue('force_language', false);
  113. if (is_string($forceLang)) {
  114. $lang = $forceLang;
  115. }
  116. $forceLocale = $this->config->getSystemValue('force_locale', false);
  117. if (is_string($forceLocale)) {
  118. $locale = $forceLocale;
  119. }
  120. if ($lang === null || !$this->languageExists($app, $lang)) {
  121. $lang = $this->findLanguage($app);
  122. }
  123. if ($locale === null || !$this->localeExists($locale)) {
  124. $locale = $this->findLocale($lang);
  125. }
  126. if (!isset($this->instances[$lang][$app])) {
  127. $this->instances[$lang][$app] = new L10N(
  128. $this, $app, $lang, $locale,
  129. $this->getL10nFilesForApp($app, $lang)
  130. );
  131. }
  132. return $this->instances[$lang][$app];
  133. });
  134. }
  135. /**
  136. * Find the best language
  137. *
  138. * @param string|null $app App id or null for core
  139. * @return string language If nothing works it returns 'en'
  140. */
  141. public function findLanguage($app = null) {
  142. $forceLang = $this->config->getSystemValue('force_language', false);
  143. if (is_string($forceLang)) {
  144. $this->requestLanguage = $forceLang;
  145. }
  146. if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
  147. return $this->requestLanguage;
  148. }
  149. /**
  150. * At this point Nextcloud might not yet be installed and thus the lookup
  151. * in the preferences table might fail. For this reason we need to check
  152. * whether the instance has already been installed
  153. *
  154. * @link https://github.com/owncloud/core/issues/21955
  155. */
  156. if ($this->config->getSystemValue('installed', false)) {
  157. $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
  158. if (!is_null($userId)) {
  159. $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
  160. } else {
  161. $userLang = null;
  162. }
  163. } else {
  164. $userId = null;
  165. $userLang = null;
  166. }
  167. if ($userLang) {
  168. $this->requestLanguage = $userLang;
  169. if ($this->languageExists($app, $userLang)) {
  170. return $userLang;
  171. }
  172. }
  173. try {
  174. // Try to get the language from the Request
  175. $lang = $this->getLanguageFromRequest($app);
  176. if ($userId !== null && $app === null && !$userLang) {
  177. $this->config->setUserValue($userId, 'core', 'lang', $lang);
  178. }
  179. return $lang;
  180. } catch (LanguageNotFoundException $e) {
  181. // Finding language from request failed fall back to default language
  182. $defaultLanguage = $this->config->getSystemValue('default_language', false);
  183. if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
  184. return $defaultLanguage;
  185. }
  186. }
  187. // We could not find any language so fall back to english
  188. return 'en';
  189. }
  190. /**
  191. * find the best locale
  192. *
  193. * @param string $lang
  194. * @return null|string
  195. */
  196. public function findLocale($lang = null) {
  197. $forceLocale = $this->config->getSystemValue('force_locale', false);
  198. if (is_string($forceLocale) && $this->localeExists($forceLocale)) {
  199. return $forceLocale;
  200. }
  201. if ($this->config->getSystemValue('installed', false)) {
  202. $userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() : null;
  203. $userLocale = null;
  204. if (null !== $userId) {
  205. $userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
  206. }
  207. } else {
  208. $userId = null;
  209. $userLocale = null;
  210. }
  211. if ($userLocale && $this->localeExists($userLocale)) {
  212. return $userLocale;
  213. }
  214. // Default : use system default locale
  215. $defaultLocale = $this->config->getSystemValue('default_locale', false);
  216. if ($defaultLocale !== false && $this->localeExists($defaultLocale)) {
  217. return $defaultLocale;
  218. }
  219. // If no user locale set, use lang as locale
  220. if (null !== $lang && $this->localeExists($lang)) {
  221. return $lang;
  222. }
  223. // At last, return USA
  224. return 'en_US';
  225. }
  226. /**
  227. * find the matching lang from the locale
  228. *
  229. * @param string $app
  230. * @param string $locale
  231. * @return null|string
  232. */
  233. public function findLanguageFromLocale(string $app = 'core', string $locale = null) {
  234. if ($this->languageExists($app, $locale)) {
  235. return $locale;
  236. }
  237. // Try to split e.g: fr_FR => fr
  238. $locale = explode('_', $locale)[0];
  239. if ($this->languageExists($app, $locale)) {
  240. return $locale;
  241. }
  242. }
  243. /**
  244. * Find all available languages for an app
  245. *
  246. * @param string|null $app App id or null for core
  247. * @return array an array of available languages
  248. */
  249. public function findAvailableLanguages($app = null) {
  250. $key = $app;
  251. if ($key === null) {
  252. $key = 'null';
  253. }
  254. // also works with null as key
  255. if (!empty($this->availableLanguages[$key])) {
  256. return $this->availableLanguages[$key];
  257. }
  258. $available = ['en']; //english is always available
  259. $dir = $this->findL10nDir($app);
  260. if (is_dir($dir)) {
  261. $files = scandir($dir);
  262. if ($files !== false) {
  263. foreach ($files as $file) {
  264. if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
  265. $available[] = substr($file, 0, -5);
  266. }
  267. }
  268. }
  269. }
  270. // merge with translations from theme
  271. $theme = $this->config->getSystemValue('theme');
  272. if (!empty($theme)) {
  273. $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
  274. if (is_dir($themeDir)) {
  275. $files = scandir($themeDir);
  276. if ($files !== false) {
  277. foreach ($files as $file) {
  278. if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
  279. $available[] = substr($file, 0, -5);
  280. }
  281. }
  282. }
  283. }
  284. }
  285. $this->availableLanguages[$key] = $available;
  286. return $available;
  287. }
  288. /**
  289. * @return array|mixed
  290. */
  291. public function findAvailableLocales() {
  292. if (!empty($this->availableLocales)) {
  293. return $this->availableLocales;
  294. }
  295. $localeData = file_get_contents(\OC::$SERVERROOT . '/resources/locales.json');
  296. $this->availableLocales = \json_decode($localeData, true);
  297. return $this->availableLocales;
  298. }
  299. /**
  300. * @param string|null $app App id or null for core
  301. * @param string $lang
  302. * @return bool
  303. */
  304. public function languageExists($app, $lang) {
  305. if ($lang === 'en') {//english is always available
  306. return true;
  307. }
  308. $languages = $this->findAvailableLanguages($app);
  309. return array_search($lang, $languages) !== false;
  310. }
  311. public function getLanguageIterator(IUser $user = null): ILanguageIterator {
  312. $user = $user ?? $this->userSession->getUser();
  313. if ($user === null) {
  314. throw new \RuntimeException('Failed to get an IUser instance');
  315. }
  316. return new LanguageIterator($user, $this->config);
  317. }
  318. /**
  319. * Return the language to use when sending something to a user
  320. *
  321. * @param IUser|null $user
  322. * @return string
  323. * @since 20.0.0
  324. */
  325. public function getUserLanguage(IUser $user = null): string {
  326. $language = $this->config->getSystemValue('force_language', false);
  327. if ($language !== false) {
  328. return $language;
  329. }
  330. if ($user instanceof IUser) {
  331. $language = $this->config->getUserValue($user->getUID(), 'core', 'lang', null);
  332. if ($language !== null) {
  333. return $language;
  334. }
  335. }
  336. return $this->config->getSystemValue('default_language', 'en');
  337. }
  338. /**
  339. * @param string $locale
  340. * @return bool
  341. */
  342. public function localeExists($locale) {
  343. if ($locale === 'en') { //english is always available
  344. return true;
  345. }
  346. if ($this->localeCache === []) {
  347. $locales = $this->findAvailableLocales();
  348. foreach ($locales as $l) {
  349. $this->localeCache[$l['code']] = true;
  350. }
  351. }
  352. return isset($this->localeCache[$locale]);
  353. }
  354. /**
  355. * @param string|null $app
  356. * @return string
  357. * @throws LanguageNotFoundException
  358. */
  359. private function getLanguageFromRequest($app) {
  360. $header = $this->request->getHeader('ACCEPT_LANGUAGE');
  361. if ($header !== '') {
  362. $available = $this->findAvailableLanguages($app);
  363. // E.g. make sure that 'de' is before 'de_DE'.
  364. sort($available);
  365. $preferences = preg_split('/,\s*/', strtolower($header));
  366. foreach ($preferences as $preference) {
  367. [$preferred_language] = explode(';', $preference);
  368. $preferred_language = str_replace('-', '_', $preferred_language);
  369. foreach ($available as $available_language) {
  370. if ($preferred_language === strtolower($available_language)) {
  371. return $this->respectDefaultLanguage($app, $available_language);
  372. }
  373. }
  374. // Fallback from de_De to de
  375. foreach ($available as $available_language) {
  376. if (substr($preferred_language, 0, 2) === $available_language) {
  377. return $available_language;
  378. }
  379. }
  380. }
  381. }
  382. throw new LanguageNotFoundException();
  383. }
  384. /**
  385. * if default language is set to de_DE (formal German) this should be
  386. * preferred to 'de' (non-formal German) if possible
  387. *
  388. * @param string|null $app
  389. * @param string $lang
  390. * @return string
  391. */
  392. protected function respectDefaultLanguage($app, $lang) {
  393. $result = $lang;
  394. $defaultLanguage = $this->config->getSystemValue('default_language', false);
  395. // use formal version of german ("Sie" instead of "Du") if the default
  396. // language is set to 'de_DE' if possible
  397. if (is_string($defaultLanguage) &&
  398. strtolower($lang) === 'de' &&
  399. strtolower($defaultLanguage) === 'de_de' &&
  400. $this->languageExists($app, 'de_DE')
  401. ) {
  402. $result = 'de_DE';
  403. }
  404. return $result;
  405. }
  406. /**
  407. * Checks if $sub is a subdirectory of $parent
  408. *
  409. * @param string $sub
  410. * @param string $parent
  411. * @return bool
  412. */
  413. private function isSubDirectory($sub, $parent) {
  414. // Check whether $sub contains no ".."
  415. if (strpos($sub, '..') !== false) {
  416. return false;
  417. }
  418. // Check whether $sub is a subdirectory of $parent
  419. if (strpos($sub, $parent) === 0) {
  420. return true;
  421. }
  422. return false;
  423. }
  424. /**
  425. * Get a list of language files that should be loaded
  426. *
  427. * @param string $app
  428. * @param string $lang
  429. * @return string[]
  430. */
  431. // FIXME This method is only public, until OC_L10N does not need it anymore,
  432. // FIXME This is also the reason, why it is not in the public interface
  433. public function getL10nFilesForApp($app, $lang) {
  434. $languageFiles = [];
  435. $i18nDir = $this->findL10nDir($app);
  436. $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
  437. if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
  438. || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
  439. || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
  440. )
  441. && file_exists($transFile)) {
  442. // load the translations file
  443. $languageFiles[] = $transFile;
  444. }
  445. // merge with translations from theme
  446. $theme = $this->config->getSystemValue('theme');
  447. if (!empty($theme)) {
  448. $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
  449. if (file_exists($transFile)) {
  450. $languageFiles[] = $transFile;
  451. }
  452. }
  453. return $languageFiles;
  454. }
  455. /**
  456. * find the l10n directory
  457. *
  458. * @param string $app App id or empty string for core
  459. * @return string directory
  460. */
  461. protected function findL10nDir($app = null) {
  462. if (in_array($app, ['core', 'lib'])) {
  463. if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
  464. return $this->serverRoot . '/' . $app . '/l10n/';
  465. }
  466. } elseif ($app && \OC_App::getAppPath($app) !== false) {
  467. // Check if the app is in the app folder
  468. return \OC_App::getAppPath($app) . '/l10n/';
  469. }
  470. return $this->serverRoot . '/core/l10n/';
  471. }
  472. /**
  473. * Creates a function from the plural string
  474. *
  475. * Parts of the code is copied from Habari:
  476. * https://github.com/habari/system/blob/master/classes/locale.php
  477. * @param string $string
  478. * @return string
  479. */
  480. public function createPluralFunction($string) {
  481. if (isset($this->pluralFunctions[$string])) {
  482. return $this->pluralFunctions[$string];
  483. }
  484. if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
  485. // sanitize
  486. $nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
  487. $plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
  488. $body = str_replace(
  489. [ 'plural', 'n', '$n$plurals', ],
  490. [ '$plural', '$n', '$nplurals', ],
  491. 'nplurals='. $nplurals . '; plural=' . $plural
  492. );
  493. // add parents
  494. // important since PHP's ternary evaluates from left to right
  495. $body .= ';';
  496. $res = '';
  497. $p = 0;
  498. $length = strlen($body);
  499. for ($i = 0; $i < $length; $i++) {
  500. $ch = $body[$i];
  501. switch ($ch) {
  502. case '?':
  503. $res .= ' ? (';
  504. $p++;
  505. break;
  506. case ':':
  507. $res .= ') : (';
  508. break;
  509. case ';':
  510. $res .= str_repeat(')', $p) . ';';
  511. $p = 0;
  512. break;
  513. default:
  514. $res .= $ch;
  515. }
  516. }
  517. $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
  518. $function = create_function('$n', $body);
  519. $this->pluralFunctions[$string] = $function;
  520. return $function;
  521. } else {
  522. // default: one plural form for all cases but n==1 (english)
  523. $function = create_function(
  524. '$n',
  525. '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
  526. );
  527. $this->pluralFunctions[$string] = $function;
  528. return $function;
  529. }
  530. }
  531. /**
  532. * returns the common language and other languages in an
  533. * associative array
  534. *
  535. * @return array
  536. */
  537. public function getLanguages() {
  538. $forceLanguage = $this->config->getSystemValue('force_language', false);
  539. if ($forceLanguage !== false) {
  540. $l = $this->get('lib', $forceLanguage);
  541. $potentialName = $l->t('__language_name__');
  542. return [
  543. 'commonlanguages' => [[
  544. 'code' => $forceLanguage,
  545. 'name' => $potentialName,
  546. ]],
  547. 'languages' => [],
  548. ];
  549. }
  550. $languageCodes = $this->findAvailableLanguages();
  551. $commonLanguages = [];
  552. $languages = [];
  553. foreach ($languageCodes as $lang) {
  554. $l = $this->get('lib', $lang);
  555. // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
  556. $potentialName = $l->t('__language_name__');
  557. if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') {//first check if the language name is in the translation file
  558. $ln = [
  559. 'code' => $lang,
  560. 'name' => $potentialName
  561. ];
  562. } elseif ($lang === 'en') {
  563. $ln = [
  564. 'code' => $lang,
  565. 'name' => 'English (US)'
  566. ];
  567. } else {//fallback to language code
  568. $ln = [
  569. 'code' => $lang,
  570. 'name' => $lang
  571. ];
  572. }
  573. // put appropriate languages into appropriate arrays, to print them sorted
  574. // common languages -> divider -> other languages
  575. if (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
  576. $commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
  577. } else {
  578. $languages[] = $ln;
  579. }
  580. }
  581. ksort($commonLanguages);
  582. // sort now by displayed language not the iso-code
  583. usort($languages, function ($a, $b) {
  584. if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
  585. // If a doesn't have a name, but b does, list b before a
  586. return 1;
  587. }
  588. if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
  589. // If a does have a name, but b doesn't, list a before b
  590. return -1;
  591. }
  592. // Otherwise compare the names
  593. return strcmp($a['name'], $b['name']);
  594. });
  595. return [
  596. // reset indexes
  597. 'commonlanguages' => array_values($commonLanguages),
  598. 'languages' => $languages
  599. ];
  600. }
  601. }