Setup.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Administrator "Administrator@WINDOWS-2012"
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  9. * @author Brice Maron <brice@bmaron.net>
  10. * @author Christoph Wurst <christoph@owncloud.com>
  11. * @author Frank Isemann <frank@isemann.name>
  12. * @author François Kubler <francois@kubler.org>
  13. * @author Jakob Sack <mail@jakobsack.de>
  14. * @author Joas Schilling <coding@schilljs.com>
  15. * @author KB7777 <k.burkowski@gmail.com>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Robert Scheck <robert@fedoraproject.org>
  19. * @author Robin Appelman <robin@icewind.nl>
  20. * @author Roeland Jago Douma <roeland@famdouma.nl>
  21. * @author Sean Comeau <sean@ftlnetworks.ca>
  22. * @author Serge Martin <edb@sigluy.net>
  23. * @author Thomas Müller <thomas.mueller@tmit.eu>
  24. * @author Vincent Petry <pvince81@owncloud.com>
  25. *
  26. * @license AGPL-3.0
  27. *
  28. * This code is free software: you can redistribute it and/or modify
  29. * it under the terms of the GNU Affero General Public License, version 3,
  30. * as published by the Free Software Foundation.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU Affero General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU Affero General Public License, version 3,
  38. * along with this program. If not, see <http://www.gnu.org/licenses/>
  39. *
  40. */
  41. namespace OC;
  42. use bantu\IniGetWrapper\IniGetWrapper;
  43. use Exception;
  44. use OC\App\AppStore\Bundles\BundleFetcher;
  45. use OC\Authentication\Token\DefaultTokenCleanupJob;
  46. use OC\Authentication\Token\DefaultTokenProvider;
  47. use OC\Log\Rotate;
  48. use OC\Preview\BackgroundCleanupJob;
  49. use OCP\Defaults;
  50. use OCP\IL10N;
  51. use OCP\ILogger;
  52. use OCP\Security\ISecureRandom;
  53. class Setup {
  54. /** @var SystemConfig */
  55. protected $config;
  56. /** @var IniGetWrapper */
  57. protected $iniWrapper;
  58. /** @var IL10N */
  59. protected $l10n;
  60. /** @var Defaults */
  61. protected $defaults;
  62. /** @var ILogger */
  63. protected $logger;
  64. /** @var ISecureRandom */
  65. protected $random;
  66. /** @var Installer */
  67. protected $installer;
  68. /**
  69. * @param SystemConfig $config
  70. * @param IniGetWrapper $iniWrapper
  71. * @param IL10N $l10n
  72. * @param Defaults $defaults
  73. * @param ILogger $logger
  74. * @param ISecureRandom $random
  75. * @param Installer $installer
  76. */
  77. public function __construct(SystemConfig $config,
  78. IniGetWrapper $iniWrapper,
  79. IL10N $l10n,
  80. Defaults $defaults,
  81. ILogger $logger,
  82. ISecureRandom $random,
  83. Installer $installer
  84. ) {
  85. $this->config = $config;
  86. $this->iniWrapper = $iniWrapper;
  87. $this->l10n = $l10n;
  88. $this->defaults = $defaults;
  89. $this->logger = $logger;
  90. $this->random = $random;
  91. $this->installer = $installer;
  92. }
  93. static protected $dbSetupClasses = [
  94. 'mysql' => \OC\Setup\MySQL::class,
  95. 'pgsql' => \OC\Setup\PostgreSQL::class,
  96. 'oci' => \OC\Setup\OCI::class,
  97. 'sqlite' => \OC\Setup\Sqlite::class,
  98. 'sqlite3' => \OC\Setup\Sqlite::class,
  99. ];
  100. /**
  101. * Wrapper around the "class_exists" PHP function to be able to mock it
  102. * @param string $name
  103. * @return bool
  104. */
  105. protected function class_exists($name) {
  106. return class_exists($name);
  107. }
  108. /**
  109. * Wrapper around the "is_callable" PHP function to be able to mock it
  110. * @param string $name
  111. * @return bool
  112. */
  113. protected function is_callable($name) {
  114. return is_callable($name);
  115. }
  116. /**
  117. * Wrapper around \PDO::getAvailableDrivers
  118. *
  119. * @return array
  120. */
  121. protected function getAvailableDbDriversForPdo() {
  122. return \PDO::getAvailableDrivers();
  123. }
  124. /**
  125. * Get the available and supported databases of this instance
  126. *
  127. * @param bool $allowAllDatabases
  128. * @return array
  129. * @throws Exception
  130. */
  131. public function getSupportedDatabases($allowAllDatabases = false) {
  132. $availableDatabases = [
  133. 'sqlite' => [
  134. 'type' => 'pdo',
  135. 'call' => 'sqlite',
  136. 'name' => 'SQLite',
  137. ],
  138. 'mysql' => [
  139. 'type' => 'pdo',
  140. 'call' => 'mysql',
  141. 'name' => 'MySQL/MariaDB',
  142. ],
  143. 'pgsql' => [
  144. 'type' => 'pdo',
  145. 'call' => 'pgsql',
  146. 'name' => 'PostgreSQL',
  147. ],
  148. 'oci' => [
  149. 'type' => 'function',
  150. 'call' => 'oci_connect',
  151. 'name' => 'Oracle',
  152. ],
  153. ];
  154. if ($allowAllDatabases) {
  155. $configuredDatabases = array_keys($availableDatabases);
  156. } else {
  157. $configuredDatabases = $this->config->getValue('supportedDatabases',
  158. ['sqlite', 'mysql', 'pgsql']);
  159. }
  160. if(!is_array($configuredDatabases)) {
  161. throw new Exception('Supported databases are not properly configured.');
  162. }
  163. $supportedDatabases = array();
  164. foreach($configuredDatabases as $database) {
  165. if(array_key_exists($database, $availableDatabases)) {
  166. $working = false;
  167. $type = $availableDatabases[$database]['type'];
  168. $call = $availableDatabases[$database]['call'];
  169. if ($type === 'function') {
  170. $working = $this->is_callable($call);
  171. } elseif($type === 'pdo') {
  172. $working = in_array($call, $this->getAvailableDbDriversForPdo(), true);
  173. }
  174. if($working) {
  175. $supportedDatabases[$database] = $availableDatabases[$database]['name'];
  176. }
  177. }
  178. }
  179. return $supportedDatabases;
  180. }
  181. /**
  182. * Gathers system information like database type and does
  183. * a few system checks.
  184. *
  185. * @return array of system info, including an "errors" value
  186. * in case of errors/warnings
  187. */
  188. public function getSystemInfo($allowAllDatabases = false) {
  189. $databases = $this->getSupportedDatabases($allowAllDatabases);
  190. $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT.'/data');
  191. $errors = [];
  192. // Create data directory to test whether the .htaccess works
  193. // Notice that this is not necessarily the same data directory as the one
  194. // that will effectively be used.
  195. if(!file_exists($dataDir)) {
  196. @mkdir($dataDir);
  197. }
  198. $htAccessWorking = true;
  199. if (is_dir($dataDir) && is_writable($dataDir)) {
  200. // Protect data directory here, so we can test if the protection is working
  201. self::protectDataDirectory();
  202. try {
  203. $util = new \OC_Util();
  204. $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
  205. } catch (\OC\HintException $e) {
  206. $errors[] = [
  207. 'error' => $e->getMessage(),
  208. 'hint' => $e->getHint(),
  209. ];
  210. $htAccessWorking = false;
  211. }
  212. }
  213. if (\OC_Util::runningOnMac()) {
  214. $errors[] = [
  215. 'error' => $this->l10n->t(
  216. 'Mac OS X is not supported and %s will not work properly on this platform. ' .
  217. 'Use it at your own risk! ',
  218. [$this->defaults->getName()]
  219. ),
  220. 'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
  221. ];
  222. }
  223. if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
  224. $errors[] = [
  225. 'error' => $this->l10n->t(
  226. 'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
  227. 'This will lead to problems with files over 4 GB and is highly discouraged.',
  228. [$this->defaults->getName()]
  229. ),
  230. 'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
  231. ];
  232. }
  233. return array(
  234. 'hasSQLite' => isset($databases['sqlite']),
  235. 'hasMySQL' => isset($databases['mysql']),
  236. 'hasPostgreSQL' => isset($databases['pgsql']),
  237. 'hasOracle' => isset($databases['oci']),
  238. 'databases' => $databases,
  239. 'directory' => $dataDir,
  240. 'htaccessWorking' => $htAccessWorking,
  241. 'errors' => $errors,
  242. );
  243. }
  244. /**
  245. * @param $options
  246. * @return array
  247. */
  248. public function install($options) {
  249. $l = $this->l10n;
  250. $error = array();
  251. $dbType = $options['dbtype'];
  252. if(empty($options['adminlogin'])) {
  253. $error[] = $l->t('Set an admin username.');
  254. }
  255. if(empty($options['adminpass'])) {
  256. $error[] = $l->t('Set an admin password.');
  257. }
  258. if(empty($options['directory'])) {
  259. $options['directory'] = \OC::$SERVERROOT."/data";
  260. }
  261. if (!isset(self::$dbSetupClasses[$dbType])) {
  262. $dbType = 'sqlite';
  263. }
  264. $username = htmlspecialchars_decode($options['adminlogin']);
  265. $password = htmlspecialchars_decode($options['adminpass']);
  266. $dataDir = htmlspecialchars_decode($options['directory']);
  267. $class = self::$dbSetupClasses[$dbType];
  268. /** @var \OC\Setup\AbstractDatabase $dbSetup */
  269. $dbSetup = new $class($l, $this->config, $this->logger, $this->random);
  270. $error = array_merge($error, $dbSetup->validate($options));
  271. // validate the data directory
  272. if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
  273. $error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
  274. }
  275. if (!empty($error)) {
  276. return $error;
  277. }
  278. $request = \OC::$server->getRequest();
  279. //no errors, good
  280. if(isset($options['trusted_domains'])
  281. && is_array($options['trusted_domains'])) {
  282. $trustedDomains = $options['trusted_domains'];
  283. } else {
  284. $trustedDomains = [$request->getInsecureServerHost()];
  285. }
  286. //use sqlite3 when available, otherwise sqlite2 will be used.
  287. if ($dbType === 'sqlite' && class_exists('SQLite3')) {
  288. $dbType = 'sqlite3';
  289. }
  290. //generate a random salt that is used to salt the local user passwords
  291. $salt = $this->random->generate(30);
  292. // generate a secret
  293. $secret = $this->random->generate(48);
  294. //write the config file
  295. $newConfigValues = [
  296. 'passwordsalt' => $salt,
  297. 'secret' => $secret,
  298. 'trusted_domains' => $trustedDomains,
  299. 'datadirectory' => $dataDir,
  300. 'dbtype' => $dbType,
  301. 'version' => implode('.', \OCP\Util::getVersion()),
  302. ];
  303. if ($this->config->getValue('overwrite.cli.url', null) === null) {
  304. $newConfigValues['overwrite.cli.url'] = $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT;
  305. }
  306. $this->config->setValues($newConfigValues);
  307. try {
  308. $dbSetup->initialize($options);
  309. $dbSetup->setupDatabase($username);
  310. // apply necessary migrations
  311. $dbSetup->runMigrations();
  312. } catch (\OC\DatabaseSetupException $e) {
  313. $error[] = [
  314. 'error' => $e->getMessage(),
  315. 'hint' => $e->getHint(),
  316. ];
  317. return $error;
  318. } catch (Exception $e) {
  319. $error[] = [
  320. 'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
  321. 'hint' => '',
  322. ];
  323. return $error;
  324. }
  325. //create the user and group
  326. $user = null;
  327. try {
  328. $user = \OC::$server->getUserManager()->createUser($username, $password);
  329. if (!$user) {
  330. $error[] = "User <$username> could not be created.";
  331. }
  332. } catch(Exception $exception) {
  333. $error[] = $exception->getMessage();
  334. }
  335. if (empty($error)) {
  336. $config = \OC::$server->getConfig();
  337. $config->setAppValue('core', 'installedat', microtime(true));
  338. $config->setAppValue('core', 'lastupdatedat', microtime(true));
  339. $config->setAppValue('core', 'vendor', $this->getVendor());
  340. $group =\OC::$server->getGroupManager()->createGroup('admin');
  341. $group->addUser($user);
  342. // Install shipped apps and specified app bundles
  343. Installer::installShippedApps();
  344. $bundleFetcher = new BundleFetcher(\OC::$server->getL10N('lib'));
  345. $defaultInstallationBundles = $bundleFetcher->getDefaultInstallationBundle();
  346. foreach($defaultInstallationBundles as $bundle) {
  347. try {
  348. $this->installer->installAppBundle($bundle);
  349. } catch (Exception $e) {}
  350. }
  351. // create empty file in data dir, so we can later find
  352. // out that this is indeed an ownCloud data directory
  353. file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
  354. // Update .htaccess files
  355. self::updateHtaccess();
  356. self::protectDataDirectory();
  357. self::installBackgroundJobs();
  358. //and we are done
  359. $config->setSystemValue('installed', true);
  360. // Create a session token for the newly created user
  361. // The token provider requires a working db, so it's not injected on setup
  362. /* @var $userSession User\Session */
  363. $userSession = \OC::$server->getUserSession();
  364. $defaultTokenProvider = \OC::$server->query(DefaultTokenProvider::class);
  365. $userSession->setTokenProvider($defaultTokenProvider);
  366. $userSession->login($username, $password);
  367. $userSession->createSessionToken($request, $userSession->getUser()->getUID(), $username, $password);
  368. }
  369. return $error;
  370. }
  371. public static function installBackgroundJobs() {
  372. $jobList = \OC::$server->getJobList();
  373. $jobList->add(DefaultTokenCleanupJob::class);
  374. $jobList->add(Rotate::class);
  375. $jobList->add(BackgroundCleanupJob::class);
  376. }
  377. /**
  378. * @return string Absolute path to htaccess
  379. */
  380. private function pathToHtaccess() {
  381. return \OC::$SERVERROOT.'/.htaccess';
  382. }
  383. /**
  384. * Append the correct ErrorDocument path for Apache hosts
  385. * @return bool True when success, False otherwise
  386. */
  387. public static function updateHtaccess() {
  388. $config = \OC::$server->getSystemConfig();
  389. // For CLI read the value from overwrite.cli.url
  390. if(\OC::$CLI) {
  391. $webRoot = $config->getValue('overwrite.cli.url', '');
  392. if($webRoot === '') {
  393. return false;
  394. }
  395. $webRoot = parse_url($webRoot, PHP_URL_PATH);
  396. if ($webRoot === null) {
  397. return false;
  398. }
  399. $webRoot = rtrim($webRoot, '/');
  400. } else {
  401. $webRoot = !empty(\OC::$WEBROOT) ? \OC::$WEBROOT : '/';
  402. }
  403. $setupHelper = new \OC\Setup(
  404. $config,
  405. \OC::$server->getIniWrapper(),
  406. \OC::$server->getL10N('lib'),
  407. \OC::$server->query(Defaults::class),
  408. \OC::$server->getLogger(),
  409. \OC::$server->getSecureRandom(),
  410. \OC::$server->query(Installer::class)
  411. );
  412. $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
  413. $content = "#### DO NOT CHANGE ANYTHING ABOVE THIS LINE ####\n";
  414. $htaccessContent = explode($content, $htaccessContent, 2)[0];
  415. //custom 403 error page
  416. $content.= "\nErrorDocument 403 ".$webRoot."/";
  417. //custom 404 error page
  418. $content.= "\nErrorDocument 404 ".$webRoot."/";
  419. // Add rewrite rules if the RewriteBase is configured
  420. $rewriteBase = $config->getValue('htaccess.RewriteBase', '');
  421. if($rewriteBase !== '') {
  422. $content .= "\n<IfModule mod_rewrite.c>";
  423. $content .= "\n Options -MultiViews";
  424. $content .= "\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
  425. $content .= "\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
  426. $content .= "\n RewriteCond %{REQUEST_FILENAME} !\\.(css|js|svg|gif|png|html|ttf|woff|ico|jpg|jpeg)$";
  427. $content .= "\n RewriteCond %{REQUEST_FILENAME} !core/img/favicon.ico$";
  428. $content .= "\n RewriteCond %{REQUEST_FILENAME} !core/img/manifest.json$";
  429. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/remote.php";
  430. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/public.php";
  431. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/cron.php";
  432. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update.php";
  433. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/status.php";
  434. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v1.php";
  435. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs/v2.php";
  436. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/robots.txt";
  437. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/updater/";
  438. $content .= "\n RewriteCond %{REQUEST_FILENAME} !/ocs-provider/";
  439. $content .= "\n RewriteCond %{REQUEST_URI} !^/\\.well-known/(acme-challenge|pki-validation)/.*";
  440. $content .= "\n RewriteRule . index.php [PT,E=PATH_INFO:$1]";
  441. $content .= "\n RewriteBase " . $rewriteBase;
  442. $content .= "\n <IfModule mod_env.c>";
  443. $content .= "\n SetEnv front_controller_active true";
  444. $content .= "\n <IfModule mod_dir.c>";
  445. $content .= "\n DirectorySlash off";
  446. $content .= "\n </IfModule>";
  447. $content .= "\n </IfModule>";
  448. $content .= "\n</IfModule>";
  449. }
  450. if ($content !== '') {
  451. //suppress errors in case we don't have permissions for it
  452. return (bool) @file_put_contents($setupHelper->pathToHtaccess(), $htaccessContent.$content . "\n");
  453. }
  454. return false;
  455. }
  456. public static function protectDataDirectory() {
  457. //Require all denied
  458. $now = date('Y-m-d H:i:s');
  459. $content = "# Generated by Nextcloud on $now\n";
  460. $content.= "# line below if for Apache 2.4\n";
  461. $content.= "<ifModule mod_authz_core.c>\n";
  462. $content.= "Require all denied\n";
  463. $content.= "</ifModule>\n\n";
  464. $content.= "# line below if for Apache 2.2\n";
  465. $content.= "<ifModule !mod_authz_core.c>\n";
  466. $content.= "deny from all\n";
  467. $content.= "Satisfy All\n";
  468. $content.= "</ifModule>\n\n";
  469. $content.= "# section for Apache 2.2 and 2.4\n";
  470. $content.= "<ifModule mod_autoindex.c>\n";
  471. $content.= "IndexIgnore *\n";
  472. $content.= "</ifModule>\n";
  473. $baseDir = \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data');
  474. file_put_contents($baseDir . '/.htaccess', $content);
  475. file_put_contents($baseDir . '/index.html', '');
  476. }
  477. /**
  478. * Return vendor from which this version was published
  479. *
  480. * @return string Get the vendor
  481. *
  482. * Copy of \OC\Updater::getVendor()
  483. */
  484. private function getVendor() {
  485. // this should really be a JSON file
  486. require \OC::$SERVERROOT . '/version.php';
  487. /** @var string $vendor */
  488. return (string) $vendor;
  489. }
  490. }