Factory.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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 all available languages for an app
  215. *
  216. * @param string|null $app App id or null for core
  217. * @return array an array of available languages
  218. */
  219. public function findAvailableLanguages($app = null) {
  220. $key = $app;
  221. if ($key === null) {
  222. $key = 'null';
  223. }
  224. // also works with null as key
  225. if (!empty($this->availableLanguages[$key])) {
  226. return $this->availableLanguages[$key];
  227. }
  228. $available = ['en']; //english is always available
  229. $dir = $this->findL10nDir($app);
  230. if (is_dir($dir)) {
  231. $files = scandir($dir);
  232. if ($files !== false) {
  233. foreach ($files as $file) {
  234. if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
  235. $available[] = substr($file, 0, -5);
  236. }
  237. }
  238. }
  239. }
  240. // merge with translations from theme
  241. $theme = $this->config->getSystemValue('theme');
  242. if (!empty($theme)) {
  243. $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
  244. if (is_dir($themeDir)) {
  245. $files = scandir($themeDir);
  246. if ($files !== false) {
  247. foreach ($files as $file) {
  248. if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
  249. $available[] = substr($file, 0, -5);
  250. }
  251. }
  252. }
  253. }
  254. }
  255. $this->availableLanguages[$key] = $available;
  256. return $available;
  257. }
  258. /**
  259. * @return array|mixed
  260. */
  261. public function findAvailableLocales() {
  262. if (!empty($this->availableLocales)) {
  263. return $this->availableLocales;
  264. }
  265. $localeData = file_get_contents(\OC::$SERVERROOT . '/resources/locales.json');
  266. $this->availableLocales = \json_decode($localeData, true);
  267. return $this->availableLocales;
  268. }
  269. /**
  270. * @param string|null $app App id or null for core
  271. * @param string $lang
  272. * @return bool
  273. */
  274. public function languageExists($app, $lang) {
  275. if ($lang === 'en') {//english is always available
  276. return true;
  277. }
  278. $languages = $this->findAvailableLanguages($app);
  279. return array_search($lang, $languages) !== false;
  280. }
  281. public function getLanguageIterator(IUser $user = null): ILanguageIterator {
  282. $user = $user ?? $this->userSession->getUser();
  283. if($user === null) {
  284. throw new \RuntimeException('Failed to get an IUser instance');
  285. }
  286. return new LanguageIterator($user, $this->config);
  287. }
  288. /**
  289. * @param string $locale
  290. * @return bool
  291. */
  292. public function localeExists($locale) {
  293. if ($locale === 'en') { //english is always available
  294. return true;
  295. }
  296. $locales = $this->findAvailableLocales();
  297. $userLocale = array_filter($locales, function($value) use ($locale) {
  298. return $locale === $value['code'];
  299. });
  300. return !empty($userLocale);
  301. }
  302. /**
  303. * @param string|null $app
  304. * @return string
  305. * @throws LanguageNotFoundException
  306. */
  307. private function getLanguageFromRequest($app) {
  308. $header = $this->request->getHeader('ACCEPT_LANGUAGE');
  309. if ($header !== '') {
  310. $available = $this->findAvailableLanguages($app);
  311. // E.g. make sure that 'de' is before 'de_DE'.
  312. sort($available);
  313. $preferences = preg_split('/,\s*/', strtolower($header));
  314. foreach ($preferences as $preference) {
  315. list($preferred_language) = explode(';', $preference);
  316. $preferred_language = str_replace('-', '_', $preferred_language);
  317. foreach ($available as $available_language) {
  318. if ($preferred_language === strtolower($available_language)) {
  319. return $this->respectDefaultLanguage($app, $available_language);
  320. }
  321. }
  322. // Fallback from de_De to de
  323. foreach ($available as $available_language) {
  324. if (substr($preferred_language, 0, 2) === $available_language) {
  325. return $available_language;
  326. }
  327. }
  328. }
  329. }
  330. throw new LanguageNotFoundException();
  331. }
  332. /**
  333. * if default language is set to de_DE (formal German) this should be
  334. * preferred to 'de' (non-formal German) if possible
  335. *
  336. * @param string|null $app
  337. * @param string $lang
  338. * @return string
  339. */
  340. protected function respectDefaultLanguage($app, $lang) {
  341. $result = $lang;
  342. $defaultLanguage = $this->config->getSystemValue('default_language', false);
  343. // use formal version of german ("Sie" instead of "Du") if the default
  344. // language is set to 'de_DE' if possible
  345. if (is_string($defaultLanguage) &&
  346. strtolower($lang) === 'de' &&
  347. strtolower($defaultLanguage) === 'de_de' &&
  348. $this->languageExists($app, 'de_DE')
  349. ) {
  350. $result = 'de_DE';
  351. }
  352. return $result;
  353. }
  354. /**
  355. * Checks if $sub is a subdirectory of $parent
  356. *
  357. * @param string $sub
  358. * @param string $parent
  359. * @return bool
  360. */
  361. private function isSubDirectory($sub, $parent) {
  362. // Check whether $sub contains no ".."
  363. if (strpos($sub, '..') !== false) {
  364. return false;
  365. }
  366. // Check whether $sub is a subdirectory of $parent
  367. if (strpos($sub, $parent) === 0) {
  368. return true;
  369. }
  370. return false;
  371. }
  372. /**
  373. * Get a list of language files that should be loaded
  374. *
  375. * @param string $app
  376. * @param string $lang
  377. * @return string[]
  378. */
  379. // FIXME This method is only public, until OC_L10N does not need it anymore,
  380. // FIXME This is also the reason, why it is not in the public interface
  381. public function getL10nFilesForApp($app, $lang) {
  382. $languageFiles = [];
  383. $i18nDir = $this->findL10nDir($app);
  384. $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
  385. if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
  386. || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
  387. || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
  388. || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
  389. )
  390. && file_exists($transFile)) {
  391. // load the translations file
  392. $languageFiles[] = $transFile;
  393. }
  394. // merge with translations from theme
  395. $theme = $this->config->getSystemValue('theme');
  396. if (!empty($theme)) {
  397. $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
  398. if (file_exists($transFile)) {
  399. $languageFiles[] = $transFile;
  400. }
  401. }
  402. return $languageFiles;
  403. }
  404. /**
  405. * find the l10n directory
  406. *
  407. * @param string $app App id or empty string for core
  408. * @return string directory
  409. */
  410. protected function findL10nDir($app = null) {
  411. if (in_array($app, ['core', 'lib', 'settings'])) {
  412. if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
  413. return $this->serverRoot . '/' . $app . '/l10n/';
  414. }
  415. } else if ($app && \OC_App::getAppPath($app) !== false) {
  416. // Check if the app is in the app folder
  417. return \OC_App::getAppPath($app) . '/l10n/';
  418. }
  419. return $this->serverRoot . '/core/l10n/';
  420. }
  421. /**
  422. * Creates a function from the plural string
  423. *
  424. * Parts of the code is copied from Habari:
  425. * https://github.com/habari/system/blob/master/classes/locale.php
  426. * @param string $string
  427. * @return string
  428. */
  429. public function createPluralFunction($string) {
  430. if (isset($this->pluralFunctions[$string])) {
  431. return $this->pluralFunctions[$string];
  432. }
  433. if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
  434. // sanitize
  435. $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
  436. $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
  437. $body = str_replace(
  438. array( 'plural', 'n', '$n$plurals', ),
  439. array( '$plural', '$n', '$nplurals', ),
  440. 'nplurals='. $nplurals . '; plural=' . $plural
  441. );
  442. // add parents
  443. // important since PHP's ternary evaluates from left to right
  444. $body .= ';';
  445. $res = '';
  446. $p = 0;
  447. $length = strlen($body);
  448. for($i = 0; $i < $length; $i++) {
  449. $ch = $body[$i];
  450. switch ( $ch ) {
  451. case '?':
  452. $res .= ' ? (';
  453. $p++;
  454. break;
  455. case ':':
  456. $res .= ') : (';
  457. break;
  458. case ';':
  459. $res .= str_repeat( ')', $p ) . ';';
  460. $p = 0;
  461. break;
  462. default:
  463. $res .= $ch;
  464. }
  465. }
  466. $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
  467. $function = create_function('$n', $body);
  468. $this->pluralFunctions[$string] = $function;
  469. return $function;
  470. } else {
  471. // default: one plural form for all cases but n==1 (english)
  472. $function = create_function(
  473. '$n',
  474. '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
  475. );
  476. $this->pluralFunctions[$string] = $function;
  477. return $function;
  478. }
  479. }
  480. /**
  481. * returns the common language and other languages in an
  482. * associative array
  483. *
  484. * @return array
  485. */
  486. public function getLanguages() {
  487. $forceLanguage = $this->config->getSystemValue('force_language', false);
  488. if ($forceLanguage !== false) {
  489. return [];
  490. }
  491. $languageCodes = $this->findAvailableLanguages();
  492. $commonLanguages = [];
  493. $languages = [];
  494. foreach($languageCodes as $lang) {
  495. $l = $this->get('lib', $lang);
  496. // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
  497. $potentialName = (string) $l->t('__language_name__');
  498. if ($l->getLanguageCode() === $lang && $potentialName[0] !== '_') {//first check if the language name is in the translation file
  499. $ln = array(
  500. 'code' => $lang,
  501. 'name' => $potentialName
  502. );
  503. } else if ($lang === 'en') {
  504. $ln = array(
  505. 'code' => $lang,
  506. 'name' => 'English (US)'
  507. );
  508. } else {//fallback to language code
  509. $ln = array(
  510. 'code' => $lang,
  511. 'name' => $lang
  512. );
  513. }
  514. // put appropriate languages into appropriate arrays, to print them sorted
  515. // common languages -> divider -> other languages
  516. if (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
  517. $commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
  518. } else {
  519. $languages[] = $ln;
  520. }
  521. }
  522. ksort($commonLanguages);
  523. // sort now by displayed language not the iso-code
  524. usort( $languages, function ($a, $b) {
  525. if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
  526. // If a doesn't have a name, but b does, list b before a
  527. return 1;
  528. }
  529. if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
  530. // If a does have a name, but b doesn't, list a before b
  531. return -1;
  532. }
  533. // Otherwise compare the names
  534. return strcmp($a['name'], $b['name']);
  535. });
  536. return [
  537. // reset indexes
  538. 'commonlanguages' => array_values($commonLanguages),
  539. 'languages' => $languages
  540. ];
  541. }
  542. }