setup.php 15 KB

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