您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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