Setup.php 16 KB

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