You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Setup.php 20KB

8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
11 years ago
8 years ago
11 years ago
Do not automatically try to enable index.php-less URLs (#24539) The current logic for mod_rewrite relies on the fact that people have properly configured ownCloud, basically it reads from the `overwrite.cli.ur l` entry and then derives the `RewriteBase` from it. This usually works. However, since the ownCloud packages seem to install themselves at `/owncloud` (because subfolders are cool or so…) _a lot_ of people have just created a new Virtual Host for it or have simply symlinked the path etc. This means that `overwrite.cli.url` is wrong, which fails hard if it is used as RewriteBase since Apache does not know where it should serve files from. In the end the ownCloud instance will not be accessible anymore and users will be frustrated. Also some shared hosters like 1&1 (because using shared hosters is so awesome… ;-)) have somewhat dubious Apache configurations or use versions of mod_rewrite from the mediveal age. (because updating is money or so…) Anyhow. This makes this explicitly an opt-in configuration flag. If `htaccess.RewriteBase` is set then it will configure index.php-less URLs, if admins set that after installation and don't want to wait until the next ownCloud version they can run `occ maintenance:update:htaccess`. For ownCloud 9.0 we also have to add a repair step to make sure that instances that already have a RewriteBase configured continue to use it by copying it into the config file. That way all existing URLs stay valid. That one is not in this PR since this is unneccessary in master. Effectively this reduces another risk of breakage when updating from ownCloud 8 to ownCloud 9. Fixes https://github.com/owncloud/core/issues/24525, https://github.com/owncloud/core/issues/24426 and probably some more.
8 years ago
Do not automatically try to enable index.php-less URLs (#24539) The current logic for mod_rewrite relies on the fact that people have properly configured ownCloud, basically it reads from the `overwrite.cli.ur l` entry and then derives the `RewriteBase` from it. This usually works. However, since the ownCloud packages seem to install themselves at `/owncloud` (because subfolders are cool or so…) _a lot_ of people have just created a new Virtual Host for it or have simply symlinked the path etc. This means that `overwrite.cli.url` is wrong, which fails hard if it is used as RewriteBase since Apache does not know where it should serve files from. In the end the ownCloud instance will not be accessible anymore and users will be frustrated. Also some shared hosters like 1&1 (because using shared hosters is so awesome… ;-)) have somewhat dubious Apache configurations or use versions of mod_rewrite from the mediveal age. (because updating is money or so…) Anyhow. This makes this explicitly an opt-in configuration flag. If `htaccess.RewriteBase` is set then it will configure index.php-less URLs, if admins set that after installation and don't want to wait until the next ownCloud version they can run `occ maintenance:update:htaccess`. For ownCloud 9.0 we also have to add a repair step to make sure that instances that already have a RewriteBase configured continue to use it by copying it into the config file. That way all existing URLs stay valid. That one is not in this PR since this is unneccessary in master. Effectively this reduces another risk of breakage when updating from ownCloud 8 to ownCloud 9. Fixes https://github.com/owncloud/core/issues/24525, https://github.com/owncloud/core/issues/24426 and probably some more.
8 years ago
Do not automatically try to enable index.php-less URLs (#24539) The current logic for mod_rewrite relies on the fact that people have properly configured ownCloud, basically it reads from the `overwrite.cli.ur l` entry and then derives the `RewriteBase` from it. This usually works. However, since the ownCloud packages seem to install themselves at `/owncloud` (because subfolders are cool or so…) _a lot_ of people have just created a new Virtual Host for it or have simply symlinked the path etc. This means that `overwrite.cli.url` is wrong, which fails hard if it is used as RewriteBase since Apache does not know where it should serve files from. In the end the ownCloud instance will not be accessible anymore and users will be frustrated. Also some shared hosters like 1&1 (because using shared hosters is so awesome… ;-)) have somewhat dubious Apache configurations or use versions of mod_rewrite from the mediveal age. (because updating is money or so…) Anyhow. This makes this explicitly an opt-in configuration flag. If `htaccess.RewriteBase` is set then it will configure index.php-less URLs, if admins set that after installation and don't want to wait until the next ownCloud version they can run `occ maintenance:update:htaccess`. For ownCloud 9.0 we also have to add a repair step to make sure that instances that already have a RewriteBase configured continue to use it by copying it into the config file. That way all existing URLs stay valid. That one is not in this PR since this is unneccessary in master. Effectively this reduces another risk of breakage when updating from ownCloud 8 to ownCloud 9. Fixes https://github.com/owncloud/core/issues/24525, https://github.com/owncloud/core/issues/24426 and probably some more.
8 years ago
Do not automatically try to enable index.php-less URLs (#24539) The current logic for mod_rewrite relies on the fact that people have properly configured ownCloud, basically it reads from the `overwrite.cli.ur l` entry and then derives the `RewriteBase` from it. This usually works. However, since the ownCloud packages seem to install themselves at `/owncloud` (because subfolders are cool or so…) _a lot_ of people have just created a new Virtual Host for it or have simply symlinked the path etc. This means that `overwrite.cli.url` is wrong, which fails hard if it is used as RewriteBase since Apache does not know where it should serve files from. In the end the ownCloud instance will not be accessible anymore and users will be frustrated. Also some shared hosters like 1&1 (because using shared hosters is so awesome… ;-)) have somewhat dubious Apache configurations or use versions of mod_rewrite from the mediveal age. (because updating is money or so…) Anyhow. This makes this explicitly an opt-in configuration flag. If `htaccess.RewriteBase` is set then it will configure index.php-less URLs, if admins set that after installation and don't want to wait until the next ownCloud version they can run `occ maintenance:update:htaccess`. For ownCloud 9.0 we also have to add a repair step to make sure that instances that already have a RewriteBase configured continue to use it by copying it into the config file. That way all existing URLs stay valid. That one is not in this PR since this is unneccessary in master. Effectively this reduces another risk of breakage when updating from ownCloud 8 to ownCloud 9. Fixes https://github.com/owncloud/core/issues/24525, https://github.com/owncloud/core/issues/24426 and probably some more.
8 years ago
Do not automatically try to enable index.php-less URLs (#24539) The current logic for mod_rewrite relies on the fact that people have properly configured ownCloud, basically it reads from the `overwrite.cli.ur l` entry and then derives the `RewriteBase` from it. This usually works. However, since the ownCloud packages seem to install themselves at `/owncloud` (because subfolders are cool or so…) _a lot_ of people have just created a new Virtual Host for it or have simply symlinked the path etc. This means that `overwrite.cli.url` is wrong, which fails hard if it is used as RewriteBase since Apache does not know where it should serve files from. In the end the ownCloud instance will not be accessible anymore and users will be frustrated. Also some shared hosters like 1&1 (because using shared hosters is so awesome… ;-)) have somewhat dubious Apache configurations or use versions of mod_rewrite from the mediveal age. (because updating is money or so…) Anyhow. This makes this explicitly an opt-in configuration flag. If `htaccess.RewriteBase` is set then it will configure index.php-less URLs, if admins set that after installation and don't want to wait until the next ownCloud version they can run `occ maintenance:update:htaccess`. For ownCloud 9.0 we also have to add a repair step to make sure that instances that already have a RewriteBase configured continue to use it by copying it into the config file. That way all existing URLs stay valid. That one is not in this PR since this is unneccessary in master. Effectively this reduces another risk of breakage when updating from ownCloud 8 to ownCloud 9. Fixes https://github.com/owncloud/core/issues/24525, https://github.com/owncloud/core/issues/24426 and probably some more.
8 years ago
Do not automatically try to enable index.php-less URLs (#24539) The current logic for mod_rewrite relies on the fact that people have properly configured ownCloud, basically it reads from the `overwrite.cli.ur l` entry and then derives the `RewriteBase` from it. This usually works. However, since the ownCloud packages seem to install themselves at `/owncloud` (because subfolders are cool or so…) _a lot_ of people have just created a new Virtual Host for it or have simply symlinked the path etc. This means that `overwrite.cli.url` is wrong, which fails hard if it is used as RewriteBase since Apache does not know where it should serve files from. In the end the ownCloud instance will not be accessible anymore and users will be frustrated. Also some shared hosters like 1&1 (because using shared hosters is so awesome… ;-)) have somewhat dubious Apache configurations or use versions of mod_rewrite from the mediveal age. (because updating is money or so…) Anyhow. This makes this explicitly an opt-in configuration flag. If `htaccess.RewriteBase` is set then it will configure index.php-less URLs, if admins set that after installation and don't want to wait until the next ownCloud version they can run `occ maintenance:update:htaccess`. For ownCloud 9.0 we also have to add a repair step to make sure that instances that already have a RewriteBase configured continue to use it by copying it into the config file. That way all existing URLs stay valid. That one is not in this PR since this is unneccessary in master. Effectively this reduces another risk of breakage when updating from ownCloud 8 to ownCloud 9. Fixes https://github.com/owncloud/core/issues/24525, https://github.com/owncloud/core/issues/24426 and probably some more.
8 years ago
Do not automatically try to enable index.php-less URLs (#24539) The current logic for mod_rewrite relies on the fact that people have properly configured ownCloud, basically it reads from the `overwrite.cli.ur l` entry and then derives the `RewriteBase` from it. This usually works. However, since the ownCloud packages seem to install themselves at `/owncloud` (because subfolders are cool or so…) _a lot_ of people have just created a new Virtual Host for it or have simply symlinked the path etc. This means that `overwrite.cli.url` is wrong, which fails hard if it is used as RewriteBase since Apache does not know where it should serve files from. In the end the ownCloud instance will not be accessible anymore and users will be frustrated. Also some shared hosters like 1&1 (because using shared hosters is so awesome… ;-)) have somewhat dubious Apache configurations or use versions of mod_rewrite from the mediveal age. (because updating is money or so…) Anyhow. This makes this explicitly an opt-in configuration flag. If `htaccess.RewriteBase` is set then it will configure index.php-less URLs, if admins set that after installation and don't want to wait until the next ownCloud version they can run `occ maintenance:update:htaccess`. For ownCloud 9.0 we also have to add a repair step to make sure that instances that already have a RewriteBase configured continue to use it by copying it into the config file. That way all existing URLs stay valid. That one is not in this PR since this is unneccessary in master. Effectively this reduces another risk of breakage when updating from ownCloud 8 to ownCloud 9. Fixes https://github.com/owncloud/core/issues/24525, https://github.com/owncloud/core/issues/24426 and probably some more.
8 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Administrator "Administrator@WINDOWS-2012"
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Bart Visscher <bartv@thisnet.nl>
  9. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  10. * @author Bjoern Schiessle <bjoern@schiessle.org>
  11. * @author Brice Maron <brice@bmaron.net>
  12. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  13. * @author Dan Callahan <dan.callahan@gmail.com>
  14. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  15. * @author François Kubler <francois@kubler.org>
  16. * @author Frank Isemann <frank@isemann.name>
  17. * @author Jakob Sack <mail@jakobsack.de>
  18. * @author Joas Schilling <coding@schilljs.com>
  19. * @author Julius Härtl <jus@bitgrid.net>
  20. * @author KB7777 <k.burkowski@gmail.com>
  21. * @author Kevin Lanni <therealklanni@gmail.com>
  22. * @author Lukas Reschke <lukas@statuscode.ch>
  23. * @author MichaIng <28480705+MichaIng@users.noreply.github.com>
  24. * @author MichaIng <micha@dietpi.com>
  25. * @author Morris Jobke <hey@morrisjobke.de>
  26. * @author Robin Appelman <robin@icewind.nl>
  27. * @author Roeland Jago Douma <roeland@famdouma.nl>
  28. * @author Sean Comeau <sean@ftlnetworks.ca>
  29. * @author Serge Martin <edb@sigluy.net>
  30. * @author Simounet <contact@simounet.net>
  31. * @author Thomas Müller <thomas.mueller@tmit.eu>
  32. * @author Valdnet <47037905+Valdnet@users.noreply.github.com>
  33. * @author Vincent Petry <vincent@nextcloud.com>
  34. *
  35. * @license AGPL-3.0
  36. *
  37. * This code is free software: you can redistribute it and/or modify
  38. * it under the terms of the GNU Affero General Public License, version 3,
  39. * as published by the Free Software Foundation.
  40. *
  41. * This program is distributed in the hope that it will be useful,
  42. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  43. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  44. * GNU Affero General Public License for more details.
  45. *
  46. * You should have received a copy of the GNU Affero General Public License, version 3,
  47. * along with this program. If not, see <http://www.gnu.org/licenses/>
  48. *
  49. */
  50. namespace OC;
  51. use bantu\IniGetWrapper\IniGetWrapper;
  52. use Exception;
  53. use InvalidArgumentException;
  54. use OC\Authentication\Token\PublicKeyTokenProvider;
  55. use OC\Authentication\Token\TokenCleanupJob;
  56. use OC\Log\Rotate;
  57. use OC\Preview\BackgroundCleanupJob;
  58. use OC\TextProcessing\RemoveOldTasksBackgroundJob;
  59. use OCP\AppFramework\Utility\ITimeFactory;
  60. use OCP\BackgroundJob\IJobList;
  61. use OCP\Defaults;
  62. use OCP\IAppConfig;
  63. use OCP\IConfig;
  64. use OCP\IGroup;
  65. use OCP\IGroupManager;
  66. use OCP\IL10N;
  67. use OCP\IRequest;
  68. use OCP\IUserManager;
  69. use OCP\IUserSession;
  70. use OCP\L10N\IFactory as IL10NFactory;
  71. use OCP\Migration\IOutput;
  72. use OCP\Security\ISecureRandom;
  73. use OCP\Server;
  74. use Psr\Log\LoggerInterface;
  75. class Setup {
  76. protected IL10N $l10n;
  77. public function __construct(
  78. protected SystemConfig $config,
  79. protected IniGetWrapper $iniWrapper,
  80. IL10NFactory $l10nFactory,
  81. protected Defaults $defaults,
  82. protected LoggerInterface $logger,
  83. protected ISecureRandom $random,
  84. protected Installer $installer
  85. ) {
  86. $this->l10n = $l10nFactory->get('lib');
  87. }
  88. protected static array $dbSetupClasses = [
  89. 'mysql' => \OC\Setup\MySQL::class,
  90. 'pgsql' => \OC\Setup\PostgreSQL::class,
  91. 'oci' => \OC\Setup\OCI::class,
  92. 'sqlite' => \OC\Setup\Sqlite::class,
  93. 'sqlite3' => \OC\Setup\Sqlite::class,
  94. ];
  95. /**
  96. * Wrapper around the "class_exists" PHP function to be able to mock it
  97. */
  98. protected function class_exists(string $name): bool {
  99. return class_exists($name);
  100. }
  101. /**
  102. * Wrapper around the "is_callable" PHP function to be able to mock it
  103. */
  104. protected function is_callable(string $name): bool {
  105. return is_callable($name);
  106. }
  107. /**
  108. * Wrapper around \PDO::getAvailableDrivers
  109. */
  110. protected function getAvailableDbDriversForPdo(): array {
  111. if (class_exists(\PDO::class)) {
  112. return \PDO::getAvailableDrivers();
  113. }
  114. return [];
  115. }
  116. /**
  117. * Get the available and supported databases of this instance
  118. *
  119. * @return array
  120. * @throws Exception
  121. */
  122. public function getSupportedDatabases(bool $allowAllDatabases = false): array {
  123. $availableDatabases = [
  124. 'sqlite' => [
  125. 'type' => 'pdo',
  126. 'call' => 'sqlite',
  127. 'name' => 'SQLite',
  128. ],
  129. 'mysql' => [
  130. 'type' => 'pdo',
  131. 'call' => 'mysql',
  132. 'name' => 'MySQL/MariaDB',
  133. ],
  134. 'pgsql' => [
  135. 'type' => 'pdo',
  136. 'call' => 'pgsql',
  137. 'name' => 'PostgreSQL',
  138. ],
  139. 'oci' => [
  140. 'type' => 'function',
  141. 'call' => 'oci_connect',
  142. 'name' => 'Oracle',
  143. ],
  144. ];
  145. if ($allowAllDatabases) {
  146. $configuredDatabases = array_keys($availableDatabases);
  147. } else {
  148. $configuredDatabases = $this->config->getValue('supportedDatabases',
  149. ['sqlite', 'mysql', 'pgsql']);
  150. }
  151. if (!is_array($configuredDatabases)) {
  152. throw new Exception('Supported databases are not properly configured.');
  153. }
  154. $supportedDatabases = [];
  155. foreach ($configuredDatabases as $database) {
  156. if (array_key_exists($database, $availableDatabases)) {
  157. $working = false;
  158. $type = $availableDatabases[$database]['type'];
  159. $call = $availableDatabases[$database]['call'];
  160. if ($type === 'function') {
  161. $working = $this->is_callable($call);
  162. } elseif ($type === 'pdo') {
  163. $working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
  164. }
  165. if ($working) {
  166. $supportedDatabases[$database] = $availableDatabases[$database]['name'];
  167. }
  168. }
  169. }
  170. return $supportedDatabases;
  171. }
  172. /**
  173. * Gathers system information like database type and does
  174. * a few system checks.
  175. *
  176. * @return array of system info, including an "errors" value
  177. * in case of errors/warnings
  178. */
  179. public function getSystemInfo(bool $allowAllDatabases = false): array {
  180. $databases = $this->getSupportedDatabases($allowAllDatabases);
  181. $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data');
  182. $errors = [];
  183. // Create data directory to test whether the .htaccess works
  184. // Notice that this is not necessarily the same data directory as the one
  185. // that will effectively be used.
  186. if (!file_exists($dataDir)) {
  187. @mkdir($dataDir);
  188. }
  189. $htAccessWorking = true;
  190. if (is_dir($dataDir) && is_writable($dataDir)) {
  191. // Protect data directory here, so we can test if the protection is working
  192. self::protectDataDirectory();
  193. try {
  194. $util = new \OC_Util();
  195. $htAccessWorking = $util->isHtaccessWorking(Server::get(IConfig::class));
  196. } catch (\OCP\HintException $e) {
  197. $errors[] = [
  198. 'error' => $e->getMessage(),
  199. 'exception' => $e,
  200. 'hint' => $e->getHint(),
  201. ];
  202. $htAccessWorking = false;
  203. }
  204. }
  205. if (\OC_Util::runningOnMac()) {
  206. $errors[] = [
  207. 'error' => $this->l10n->t(
  208. 'Mac OS X is not supported and %s will not work properly on this platform. ' .
  209. 'Use it at your own risk! ',
  210. [$this->defaults->getProductName()]
  211. ),
  212. 'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
  213. ];
  214. }
  215. if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
  216. $errors[] = [
  217. 'error' => $this->l10n->t(
  218. 'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
  219. 'This will lead to problems with files over 4 GB and is highly discouraged.',
  220. [$this->defaults->getProductName()]
  221. ),
  222. 'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
  223. ];
  224. }
  225. return [
  226. 'hasSQLite' => isset($databases['sqlite']),
  227. 'hasMySQL' => isset($databases['mysql']),
  228. 'hasPostgreSQL' => isset($databases['pgsql']),
  229. 'hasOracle' => isset($databases['oci']),
  230. 'databases' => $databases,
  231. 'directory' => $dataDir,
  232. 'htaccessWorking' => $htAccessWorking,
  233. 'errors' => $errors,
  234. ];
  235. }
  236. /**
  237. * @return array<string|array> errors
  238. */
  239. public function install(array $options, ?IOutput $output = null): array {
  240. $l = $this->l10n;
  241. $error = [];
  242. $dbType = $options['dbtype'];
  243. if (empty($options['adminlogin'])) {
  244. $error[] = $l->t('Set an admin Login.');
  245. }
  246. if (empty($options['adminpass'])) {
  247. $error[] = $l->t('Set an admin password.');
  248. }
  249. if (empty($options['directory'])) {
  250. $options['directory'] = \OC::$SERVERROOT . "/data";
  251. }
  252. if (!isset(self::$dbSetupClasses[$dbType])) {
  253. $dbType = 'sqlite';
  254. }
  255. $username = htmlspecialchars_decode($options['adminlogin']);
  256. $password = htmlspecialchars_decode($options['adminpass']);
  257. $dataDir = htmlspecialchars_decode($options['directory']);
  258. $class = self::$dbSetupClasses[$dbType];
  259. /** @var \OC\Setup\AbstractDatabase $dbSetup */
  260. $dbSetup = new $class($l, $this->config, $this->logger, $this->random);
  261. $error = array_merge($error, $dbSetup->validate($options));
  262. // validate the data directory
  263. if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
  264. $error[] = $l->t("Cannot create or write into the data directory %s", [$dataDir]);
  265. }
  266. if (!empty($error)) {
  267. return $error;
  268. }
  269. $request = Server::get(IRequest::class);
  270. //no errors, good
  271. if (isset($options['trusted_domains'])
  272. && is_array($options['trusted_domains'])) {
  273. $trustedDomains = $options['trusted_domains'];
  274. } else {
  275. $trustedDomains = [$request->getInsecureServerHost()];
  276. }
  277. //use sqlite3 when available, otherwise sqlite2 will be used.
  278. if ($dbType === 'sqlite' && class_exists('SQLite3')) {
  279. $dbType = 'sqlite3';
  280. }
  281. //generate a random salt that is used to salt the local passwords
  282. $salt = $this->random->generate(30);
  283. // generate a secret
  284. $secret = $this->random->generate(48);
  285. //write the config file
  286. $newConfigValues = [
  287. 'passwordsalt' => $salt,
  288. 'secret' => $secret,
  289. 'trusted_domains' => $trustedDomains,
  290. 'datadirectory' => $dataDir,
  291. 'dbtype' => $dbType,
  292. 'version' => implode('.', \OCP\Util::getVersion()),
  293. ];
  294. if ($this->config->getValue('overwrite.cli.url', null) === null) {
  295. $newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
  296. }
  297. $this->config->setValues($newConfigValues);
  298. $this->outputDebug($output, 'Configuring database');
  299. $dbSetup->initialize($options);
  300. try {
  301. $dbSetup->setupDatabase($username);
  302. } catch (\OC\DatabaseSetupException $e) {
  303. $error[] = [
  304. 'error' => $e->getMessage(),
  305. 'exception' => $e,
  306. 'hint' => $e->getHint(),
  307. ];
  308. return $error;
  309. } catch (Exception $e) {
  310. $error[] = [
  311. 'error' => 'Error while trying to create admin account: ' . $e->getMessage(),
  312. 'exception' => $e,
  313. 'hint' => '',
  314. ];
  315. return $error;
  316. }
  317. $this->outputDebug($output, 'Run server migrations');
  318. try {
  319. // apply necessary migrations
  320. $dbSetup->runMigrations($output);
  321. } catch (Exception $e) {
  322. $error[] = [
  323. 'error' => 'Error while trying to initialise the database: ' . $e->getMessage(),
  324. 'exception' => $e,
  325. 'hint' => '',
  326. ];
  327. return $error;
  328. }
  329. $this->outputDebug($output, 'Create admin account');
  330. // create the admin account and group
  331. $user = null;
  332. try {
  333. $user = Server::get(IUserManager::class)->createUser($username, $password);
  334. if (!$user) {
  335. $error[] = "Account <$username> could not be created.";
  336. return $error;
  337. }
  338. } catch (Exception $exception) {
  339. $error[] = $exception->getMessage();
  340. return $error;
  341. }
  342. $config = Server::get(IConfig::class);
  343. $config->setAppValue('core', 'installedat', (string)microtime(true));
  344. $appConfig = Server::get(IAppConfig::class);
  345. $appConfig->setValueInt('core', 'lastupdatedat', time());
  346. $vendorData = $this->getVendorData();
  347. $config->setAppValue('core', 'vendor', $vendorData['vendor']);
  348. if ($vendorData['channel'] !== 'stable') {
  349. $config->setSystemValue('updater.release.channel', $vendorData['channel']);
  350. }
  351. $group = Server::get(IGroupManager::class)->createGroup('admin');
  352. if ($group instanceof IGroup) {
  353. $group->addUser($user);
  354. }
  355. // Install shipped apps and specified app bundles
  356. $this->outputDebug($output, 'Install default apps');
  357. Installer::installShippedApps(false, $output);
  358. // create empty file in data dir, so we can later find
  359. // out that this is indeed an ownCloud data directory
  360. $this->outputDebug($output, 'Setup data directory');
  361. file_put_contents($config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
  362. // Update .htaccess files
  363. self::updateHtaccess();
  364. self::protectDataDirectory();
  365. $this->outputDebug($output, 'Install background jobs');
  366. self::installBackgroundJobs();
  367. //and we are done
  368. $config->setSystemValue('installed', true);
  369. if (self::shouldRemoveCanInstallFile()) {
  370. unlink(\OC::$configDir.'/CAN_INSTALL');
  371. }
  372. $bootstrapCoordinator = \OCP\Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
  373. $bootstrapCoordinator->runInitialRegistration();
  374. // Create a session token for the newly created user
  375. // The token provider requires a working db, so it's not injected on setup
  376. /** @var \OC\User\Session $userSession */
  377. $userSession = Server::get(IUserSession::class);
  378. $provider = Server::get(PublicKeyTokenProvider::class);
  379. $userSession->setTokenProvider($provider);
  380. $userSession->login($username, $password);
  381. $user = $userSession->getUser();
  382. if (!$user) {
  383. $error[] = "No account found in session.";
  384. return $error;
  385. }
  386. $userSession->createSessionToken($request, $user->getUID(), $username, $password);
  387. $session = $userSession->getSession();
  388. $session->set('last-password-confirm', Server::get(ITimeFactory::class)->getTime());
  389. // Set email for admin
  390. if (!empty($options['adminemail'])) {
  391. $user->setSystemEMailAddress($options['adminemail']);
  392. }
  393. return $error;
  394. }
  395. public static function installBackgroundJobs(): void {
  396. $jobList = Server::get(IJobList::class);
  397. $jobList->add(TokenCleanupJob::class);
  398. $jobList->add(Rotate::class);
  399. $jobList->add(BackgroundCleanupJob::class);
  400. $jobList->add(RemoveOldTasksBackgroundJob::class);
  401. }
  402. /**
  403. * @return string Absolute path to htaccess
  404. */
  405. private function pathToHtaccess(): string {
  406. return \OC::$SERVERROOT . '/.htaccess';
  407. }
  408. /**
  409. * Find webroot from config
  410. *
  411. * @throws InvalidArgumentException when invalid value for overwrite.cli.url
  412. */
  413. private static function findWebRoot(SystemConfig $config): string {
  414. // For CLI read the value from overwrite.cli.url
  415. if (\OC::$CLI) {
  416. $webRoot = $config->getValue('overwrite.cli.url', '');
  417. if ($webRoot === '') {
  418. throw new InvalidArgumentException('overwrite.cli.url is empty');
  419. }
  420. if (!filter_var($webRoot, FILTER_VALIDATE_URL)) {
  421. throw new InvalidArgumentException('invalid value for overwrite.cli.url');
  422. }
  423. $webRoot = rtrim((parse_url($webRoot, PHP_URL_PATH) ?? ''), '/');
  424. } else {
  425. $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
  426. }
  427. return $webRoot;
  428. }
  429. /**
  430. * Append the correct ErrorDocument path for Apache hosts
  431. *
  432. * @return bool True when success, False otherwise
  433. * @throws \OCP\AppFramework\QueryException
  434. */
  435. public static function updateHtaccess(): bool {
  436. $config = Server::get(SystemConfig::class);
  437. try {
  438. $webRoot = self::findWebRoot($config);
  439. } catch (InvalidArgumentException $e) {
  440. return false;
  441. }
  442. $setupHelper = Server::get(\OC\Setup::class);
  443. if (!is_writable($setupHelper->pathToHtaccess())) {
  444. return false;
  445. }
  446. $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
  447. $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
  448. $htaccessContent = explode($content, $htaccessContent, 2)[0];
  449. //custom 403 error page
  450. $content .= "\nErrorDocument 403 " . $webRoot . '/index.php/error/403';
  451. //custom 404 error page
  452. $content .= "\nErrorDocument 404 " . $webRoot . '/index.php/error/404';
  453. // Add rewrite rules if the RewriteBase is configured
  454. $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
  455. if ($rewriteBase !== '') {
  456. $content .= "\n<IfModule mod_rewrite.c>";
  457. $content .= "\n Options -MultiViews";
  458. $content .= "\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
  459. $content .= "\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
  460. $content .= "\n RewriteCond %{REQUEST_FILENAME} !\\.(css|js|mjs|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav|flac|wasm|tflite)$";
  461. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\.php";
  462. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\.ico|manifest\\.json)$";
  463. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\.php";
  464. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v(1|2)\\.php";
  465. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/robots\\.txt";
  466. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/(ocs-provider|updater)/";
  467. $content .= "\n RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
  468. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/richdocumentscode(_arm64)?/proxy.php$";
  469. $content .= "\n RewriteRule . index.php [PT,E=PATH_INFO:$1]";
  470. $content .= "\n RewriteBase " . $rewriteBase;
  471. $content .= "\n <IfModule mod_env.c>";
  472. $content .= "\n SetEnv front_controller_active true";
  473. $content .= "\n <IfModule mod_dir.c>";
  474. $content .= "\n DirectorySlash off";
  475. $content .= "\n </IfModule>";
  476. $content .= "\n </IfModule>";
  477. $content .= "\n</IfModule>";
  478. }
  479. // Never write file back if disk space should be too low
  480. if (function_exists('disk_free_space')) {
  481. $df = disk_free_space(\OC::$SERVERROOT);
  482. $size = strlen($content) + 10240;
  483. if ($df !== false && $df < (float)$size) {
  484. throw new \Exception(\OC::$SERVERROOT . " does not have enough space for writing the htaccess file! Not writing it back!");
  485. }
  486. }
  487. //suppress errors in case we don't have permissions for it
  488. return (bool)@file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent . $content . "\n");
  489. }
  490. public static function protectDataDirectory(): void {
  491. //Require all denied
  492. $now = date('Y-m-d H:i:s');
  493. $content = "# Generated by Nextcloud on $now\n";
  494. $content .= "# Section for Apache 2.4 to 2.6\n";
  495. $content .= "<IfModule mod_authz_core.c>\n";
  496. $content .= " Require all denied\n";
  497. $content .= "</IfModule>\n";
  498. $content .= "<IfModule mod_access_compat.c>\n";
  499. $content .= " Order Allow,Deny\n";
  500. $content .= " Deny from all\n";
  501. $content .= " Satisfy All\n";
  502. $content .= "</IfModule>\n\n";
  503. $content .= "# Section for Apache 2.2\n";
  504. $content .= "<IfModule !mod_authz_core.c>\n";
  505. $content .= " <IfModule !mod_access_compat.c>\n";
  506. $content .= " <IfModule mod_authz_host.c>\n";
  507. $content .= " Order Allow,Deny\n";
  508. $content .= " Deny from all\n";
  509. $content .= " </IfModule>\n";
  510. $content .= " Satisfy All\n";
  511. $content .= " </IfModule>\n";
  512. $content .= "</IfModule>\n\n";
  513. $content .= "# Section for Apache 2.2 to 2.6\n";
  514. $content .= "<IfModule mod_autoindex.c>\n";
  515. $content .= " IndexIgnore *\n";
  516. $content .= "</IfModule>";
  517. $baseDir = Server::get(IConfig::class)->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
  518. file_put_contents($baseDir . '/.htaccess', $content);
  519. file_put_contents($baseDir . '/index.html', '');
  520. }
  521. private function getVendorData(): array {
  522. // this should really be a JSON file
  523. require \OC::$SERVERROOT . '/version.php';
  524. /** @var mixed $vendor */
  525. /** @var mixed $OC_Channel */
  526. return [
  527. 'vendor' => (string)$vendor,
  528. 'channel' => (string)$OC_Channel,
  529. ];
  530. }
  531. public function shouldRemoveCanInstallFile(): bool {
  532. return \OC_Util::getChannel() !== 'git' && is_file(\OC::$configDir.'/CAN_INSTALL');
  533. }
  534. public function canInstallFileExists(): bool {
  535. return is_file(\OC::$configDir.'/CAN_INSTALL');
  536. }
  537. protected function outputDebug(?IOutput $output, string $message): void {
  538. if ($output instanceof IOutput) {
  539. $output->debug($message);
  540. }
  541. }
  542. }