Setup.php 16 KB

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