Factory.php 17 KB

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