Factory.php 17 KB

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