選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Setup.php 15KB

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