Factory.php 11 KB

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