Factory.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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\IUserSession;
  34. use OCP\L10N\IFactory;
  35. /**
  36. * A factory that generates language instances
  37. */
  38. class Factory implements IFactory {
  39. /** @var string */
  40. protected $requestLanguage = '';
  41. /**
  42. * cached instances
  43. * @var array Structure: Lang => App => \OCP\IL10N
  44. */
  45. protected $instances = [];
  46. /**
  47. * @var array Structure: App => string[]
  48. */
  49. protected $availableLanguages = [];
  50. /**
  51. * @var array Structure: string => callable
  52. */
  53. protected $pluralFunctions = [];
  54. /** @var IConfig */
  55. protected $config;
  56. /** @var IRequest */
  57. protected $request;
  58. /** @var IUserSession */
  59. protected $userSession;
  60. /** @var string */
  61. protected $serverRoot;
  62. /**
  63. * @param IConfig $config
  64. * @param IRequest $request
  65. * @param IUserSession $userSession
  66. * @param string $serverRoot
  67. */
  68. public function __construct(IConfig $config,
  69. IRequest $request,
  70. IUserSession $userSession,
  71. $serverRoot) {
  72. $this->config = $config;
  73. $this->request = $request;
  74. $this->userSession = $userSession;
  75. $this->serverRoot = $serverRoot;
  76. }
  77. /**
  78. * Get a language instance
  79. *
  80. * @param string $app
  81. * @param string|null $lang
  82. * @return \OCP\IL10N
  83. */
  84. public function get($app, $lang = null) {
  85. $app = \OC_App::cleanAppId($app);
  86. if ($lang !== null) {
  87. $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
  88. }
  89. $forceLang = $this->config->getSystemValue('force_language', false);
  90. if (is_string($forceLang)) {
  91. $lang = $forceLang;
  92. }
  93. if ($lang === null || !$this->languageExists($app, $lang)) {
  94. $lang = $this->findLanguage($app);
  95. }
  96. if (!isset($this->instances[$lang][$app])) {
  97. $this->instances[$lang][$app] = new L10N(
  98. $this, $app, $lang,
  99. $this->getL10nFilesForApp($app, $lang)
  100. );
  101. }
  102. return $this->instances[$lang][$app];
  103. }
  104. /**
  105. * Find the best language
  106. *
  107. * @param string|null $app App id or null for core
  108. * @return string language If nothing works it returns 'en'
  109. */
  110. public function findLanguage($app = null) {
  111. $forceLang = $this->config->getSystemValue('force_language', false);
  112. if (is_string($forceLang)) {
  113. $this->requestLanguage = $forceLang;
  114. }
  115. if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
  116. return $this->requestLanguage;
  117. }
  118. /**
  119. * At this point Nextcloud might not yet be installed and thus the lookup
  120. * in the preferences table might fail. For this reason we need to check
  121. * whether the instance has already been installed
  122. *
  123. * @link https://github.com/owncloud/core/issues/21955
  124. */
  125. if($this->config->getSystemValue('installed', false)) {
  126. $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
  127. if(!is_null($userId)) {
  128. $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
  129. } else {
  130. $userLang = null;
  131. }
  132. } else {
  133. $userId = null;
  134. $userLang = null;
  135. }
  136. if ($userLang) {
  137. $this->requestLanguage = $userLang;
  138. if ($this->languageExists($app, $userLang)) {
  139. return $userLang;
  140. }
  141. }
  142. try {
  143. // Try to get the language from the Request
  144. $lang = $this->getLanguageFromRequest($app);
  145. if ($userId !== null && $app === null && !$userLang) {
  146. $this->config->setUserValue($userId, 'core', 'lang', $lang);
  147. }
  148. return $lang;
  149. } catch (LanguageNotFoundException $e) {
  150. // Finding language from request failed fall back to default language
  151. $defaultLanguage = $this->config->getSystemValue('default_language', false);
  152. if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
  153. return $defaultLanguage;
  154. }
  155. }
  156. // We could not find any language so fall back to english
  157. return 'en';
  158. }
  159. /**
  160. * Find all available languages for an app
  161. *
  162. * @param string|null $app App id or null for core
  163. * @return array an array of available languages
  164. */
  165. public function findAvailableLanguages($app = null) {
  166. $key = $app;
  167. if ($key === null) {
  168. $key = 'null';
  169. }
  170. // also works with null as key
  171. if (!empty($this->availableLanguages[$key])) {
  172. return $this->availableLanguages[$key];
  173. }
  174. $available = ['en']; //english is always available
  175. $dir = $this->findL10nDir($app);
  176. if (is_dir($dir)) {
  177. $files = scandir($dir);
  178. if ($files !== false) {
  179. foreach ($files as $file) {
  180. if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
  181. $available[] = substr($file, 0, -5);
  182. }
  183. }
  184. }
  185. }
  186. // merge with translations from theme
  187. $theme = $this->config->getSystemValue('theme');
  188. if (!empty($theme)) {
  189. $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
  190. if (is_dir($themeDir)) {
  191. $files = scandir($themeDir);
  192. if ($files !== false) {
  193. foreach ($files as $file) {
  194. if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
  195. $available[] = substr($file, 0, -5);
  196. }
  197. }
  198. }
  199. }
  200. }
  201. $this->availableLanguages[$key] = $available;
  202. return $available;
  203. }
  204. /**
  205. * @param string|null $app App id or null for core
  206. * @param string $lang
  207. * @return bool
  208. */
  209. public function languageExists($app, $lang) {
  210. if ($lang === 'en') {//english is always available
  211. return true;
  212. }
  213. $languages = $this->findAvailableLanguages($app);
  214. return array_search($lang, $languages) !== false;
  215. }
  216. /**
  217. * @param string|null $app
  218. * @return string
  219. * @throws LanguageNotFoundException
  220. */
  221. private function getLanguageFromRequest($app) {
  222. $header = $this->request->getHeader('ACCEPT_LANGUAGE');
  223. if ($header) {
  224. $available = $this->findAvailableLanguages($app);
  225. // E.g. make sure that 'de' is before 'de_DE'.
  226. sort($available);
  227. $preferences = preg_split('/,\s*/', strtolower($header));
  228. foreach ($preferences as $preference) {
  229. list($preferred_language) = explode(';', $preference);
  230. $preferred_language = str_replace('-', '_', $preferred_language);
  231. foreach ($available as $available_language) {
  232. if ($preferred_language === strtolower($available_language)) {
  233. return $available_language;
  234. }
  235. }
  236. // Fallback from de_De to de
  237. foreach ($available as $available_language) {
  238. if (substr($preferred_language, 0, 2) === $available_language) {
  239. return $available_language;
  240. }
  241. }
  242. }
  243. }
  244. throw new LanguageNotFoundException();
  245. }
  246. /**
  247. * Checks if $sub is a subdirectory of $parent
  248. *
  249. * @param string $sub
  250. * @param string $parent
  251. * @return bool
  252. */
  253. private function isSubDirectory($sub, $parent) {
  254. // Check whether $sub contains no ".."
  255. if(strpos($sub, '..') !== false) {
  256. return false;
  257. }
  258. // Check whether $sub is a subdirectory of $parent
  259. if (strpos($sub, $parent) === 0) {
  260. return true;
  261. }
  262. return false;
  263. }
  264. /**
  265. * Get a list of language files that should be loaded
  266. *
  267. * @param string $app
  268. * @param string $lang
  269. * @return string[]
  270. */
  271. // FIXME This method is only public, until OC_L10N does not need it anymore,
  272. // FIXME This is also the reason, why it is not in the public interface
  273. public function getL10nFilesForApp($app, $lang) {
  274. $languageFiles = [];
  275. $i18nDir = $this->findL10nDir($app);
  276. $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
  277. if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
  278. || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
  279. || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
  280. || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
  281. )
  282. && file_exists($transFile)) {
  283. // load the translations file
  284. $languageFiles[] = $transFile;
  285. }
  286. // merge with translations from theme
  287. $theme = $this->config->getSystemValue('theme');
  288. if (!empty($theme)) {
  289. $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
  290. if (file_exists($transFile)) {
  291. $languageFiles[] = $transFile;
  292. }
  293. }
  294. return $languageFiles;
  295. }
  296. /**
  297. * find the l10n directory
  298. *
  299. * @param string $app App id or empty string for core
  300. * @return string directory
  301. */
  302. protected function findL10nDir($app = null) {
  303. if (in_array($app, ['core', 'lib', 'settings'])) {
  304. if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
  305. return $this->serverRoot . '/' . $app . '/l10n/';
  306. }
  307. } else if ($app && \OC_App::getAppPath($app) !== false) {
  308. // Check if the app is in the app folder
  309. return \OC_App::getAppPath($app) . '/l10n/';
  310. }
  311. return $this->serverRoot . '/core/l10n/';
  312. }
  313. /**
  314. * Creates a function from the plural string
  315. *
  316. * Parts of the code is copied from Habari:
  317. * https://github.com/habari/system/blob/master/classes/locale.php
  318. * @param string $string
  319. * @return string
  320. */
  321. public function createPluralFunction($string) {
  322. if (isset($this->pluralFunctions[$string])) {
  323. return $this->pluralFunctions[$string];
  324. }
  325. if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
  326. // sanitize
  327. $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
  328. $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
  329. $body = str_replace(
  330. array( 'plural', 'n', '$n$plurals', ),
  331. array( '$plural', '$n', '$nplurals', ),
  332. 'nplurals='. $nplurals . '; plural=' . $plural
  333. );
  334. // add parents
  335. // important since PHP's ternary evaluates from left to right
  336. $body .= ';';
  337. $res = '';
  338. $p = 0;
  339. for($i = 0; $i < strlen($body); $i++) {
  340. $ch = $body[$i];
  341. switch ( $ch ) {
  342. case '?':
  343. $res .= ' ? (';
  344. $p++;
  345. break;
  346. case ':':
  347. $res .= ') : (';
  348. break;
  349. case ';':
  350. $res .= str_repeat( ')', $p ) . ';';
  351. $p = 0;
  352. break;
  353. default:
  354. $res .= $ch;
  355. }
  356. }
  357. $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
  358. $function = create_function('$n', $body);
  359. $this->pluralFunctions[$string] = $function;
  360. return $function;
  361. } else {
  362. // default: one plural form for all cases but n==1 (english)
  363. $function = create_function(
  364. '$n',
  365. '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
  366. );
  367. $this->pluralFunctions[$string] = $function;
  368. return $function;
  369. }
  370. }
  371. }