setup.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. <?php
  2. /**
  3. * @author Administrator <Administrator@WINDOWS-2012>
  4. * @author Arthur Schiwon <blizzz@owncloud.com>
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  7. * @author Brice Maron <brice@bmaron.net>
  8. * @author François Kubler <francois@kubler.org>
  9. * @author Jakob Sack <mail@jakobsack.de>
  10. * @author Joas Schilling <nickvergessen@owncloud.com>
  11. * @author Lukas Reschke <lukas@owncloud.com>
  12. * @author Martin Mattel <martin.mattel@diemattels.at>
  13. * @author Robin Appelman <icewind@owncloud.com>
  14. * @author Sean Comeau <sean@ftlnetworks.ca>
  15. * @author Serge Martin <edb@sigluy.net>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. * @author Vincent Petry <pvince81@owncloud.com>
  18. *
  19. * @copyright Copyright (c) 2015, ownCloud, Inc.
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OC;
  36. use bantu\IniGetWrapper\IniGetWrapper;
  37. use Exception;
  38. use OCP\IConfig;
  39. use OCP\IL10N;
  40. use OCP\ILogger;
  41. use OCP\Security\ISecureRandom;
  42. class Setup {
  43. /** @var \OCP\IConfig */
  44. protected $config;
  45. /** @var IniGetWrapper */
  46. protected $iniWrapper;
  47. /** @var IL10N */
  48. protected $l10n;
  49. /** @var \OC_Defaults */
  50. protected $defaults;
  51. /** @var ILogger */
  52. protected $logger;
  53. /** @var ISecureRandom */
  54. protected $random;
  55. /**
  56. * @param IConfig $config
  57. * @param IniGetWrapper $iniWrapper
  58. * @param \OC_Defaults $defaults
  59. */
  60. function __construct(IConfig $config,
  61. IniGetWrapper $iniWrapper,
  62. IL10N $l10n,
  63. \OC_Defaults $defaults,
  64. ILogger $logger,
  65. ISecureRandom $random
  66. ) {
  67. $this->config = $config;
  68. $this->iniWrapper = $iniWrapper;
  69. $this->l10n = $l10n;
  70. $this->defaults = $defaults;
  71. $this->logger = $logger;
  72. $this->random = $random;
  73. }
  74. static $dbSetupClasses = array(
  75. 'mysql' => '\OC\Setup\MySQL',
  76. 'pgsql' => '\OC\Setup\PostgreSQL',
  77. 'oci' => '\OC\Setup\OCI',
  78. 'sqlite' => '\OC\Setup\Sqlite',
  79. 'sqlite3' => '\OC\Setup\Sqlite',
  80. );
  81. /**
  82. * Wrapper around the "class_exists" PHP function to be able to mock it
  83. * @param string $name
  84. * @return bool
  85. */
  86. protected function class_exists($name) {
  87. return class_exists($name);
  88. }
  89. /**
  90. * Wrapper around the "is_callable" PHP function to be able to mock it
  91. * @param string $name
  92. * @return bool
  93. */
  94. protected function is_callable($name) {
  95. return is_callable($name);
  96. }
  97. /**
  98. * Wrapper around \PDO::getAvailableDrivers
  99. *
  100. * @return array
  101. */
  102. protected function getAvailableDbDriversForPdo() {
  103. return \PDO::getAvailableDrivers();
  104. }
  105. /**
  106. * Get the available and supported databases of this instance
  107. *
  108. * @param bool $allowAllDatabases
  109. * @return array
  110. * @throws Exception
  111. */
  112. public function getSupportedDatabases($allowAllDatabases = false) {
  113. $availableDatabases = array(
  114. 'sqlite' => array(
  115. 'type' => 'class',
  116. 'call' => 'SQLite3',
  117. 'name' => 'SQLite'
  118. ),
  119. 'mysql' => array(
  120. 'type' => 'pdo',
  121. 'call' => 'mysql',
  122. 'name' => 'MySQL/MariaDB'
  123. ),
  124. 'pgsql' => array(
  125. 'type' => 'function',
  126. 'call' => 'pg_connect',
  127. 'name' => 'PostgreSQL'
  128. ),
  129. 'oci' => array(
  130. 'type' => 'function',
  131. 'call' => 'oci_connect',
  132. 'name' => 'Oracle'
  133. )
  134. );
  135. if ($allowAllDatabases) {
  136. $configuredDatabases = array_keys($availableDatabases);
  137. } else {
  138. $configuredDatabases = $this->config->getSystemValue('supportedDatabases',
  139. array('sqlite', 'mysql', 'pgsql'));
  140. }
  141. if(!is_array($configuredDatabases)) {
  142. throw new Exception('Supported databases are not properly configured.');
  143. }
  144. $supportedDatabases = array();
  145. foreach($configuredDatabases as $database) {
  146. if(array_key_exists($database, $availableDatabases)) {
  147. $working = false;
  148. $type = $availableDatabases[$database]['type'];
  149. $call = $availableDatabases[$database]['call'];
  150. if($type === 'class') {
  151. $working = $this->class_exists($call);
  152. } elseif ($type === 'function') {
  153. $working = $this->is_callable($call);
  154. } elseif($type === 'pdo') {
  155. $working = in_array($call, $this->getAvailableDbDriversForPdo(), TRUE);
  156. }
  157. if($working) {
  158. $supportedDatabases[$database] = $availableDatabases[$database]['name'];
  159. }
  160. }
  161. }
  162. return $supportedDatabases;
  163. }
  164. /**
  165. * Gathers system information like database type and does
  166. * a few system checks.
  167. *
  168. * @return array of system info, including an "errors" value
  169. * in case of errors/warnings
  170. */
  171. public function getSystemInfo($allowAllDatabases = false) {
  172. $databases = $this->getSupportedDatabases($allowAllDatabases);
  173. $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data');
  174. $errors = array();
  175. // Create data directory to test whether the .htaccess works
  176. // Notice that this is not necessarily the same data directory as the one
  177. // that will effectively be used.
  178. @mkdir($dataDir);
  179. $htAccessWorking = true;
  180. if (is_dir($dataDir) && is_writable($dataDir)) {
  181. // Protect data directory here, so we can test if the protection is working
  182. \OC\Setup::protectDataDirectory();
  183. try {
  184. $util = new \OC_Util();
  185. $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig());
  186. } catch (\OC\HintException $e) {
  187. $errors[] = array(
  188. 'error' => $e->getMessage(),
  189. 'hint' => $e->getHint()
  190. );
  191. $htAccessWorking = false;
  192. }
  193. }
  194. if (\OC_Util::runningOnMac()) {
  195. $errors[] = array(
  196. 'error' => $this->l10n->t(
  197. 'Mac OS X is not supported and %s will not work properly on this platform. ' .
  198. 'Use it at your own risk! ',
  199. $this->defaults->getName()
  200. ),
  201. 'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.')
  202. );
  203. }
  204. if($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
  205. $errors[] = array(
  206. 'error' => $this->l10n->t(
  207. 'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
  208. 'This will lead to problems with files over 4 GB and is highly discouraged.',
  209. $this->defaults->getName()
  210. ),
  211. 'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.')
  212. );
  213. }
  214. return array(
  215. 'hasSQLite' => isset($databases['sqlite']),
  216. 'hasMySQL' => isset($databases['mysql']),
  217. 'hasPostgreSQL' => isset($databases['pgsql']),
  218. 'hasOracle' => isset($databases['oci']),
  219. 'databases' => $databases,
  220. 'directory' => $dataDir,
  221. 'htaccessWorking' => $htAccessWorking,
  222. 'errors' => $errors,
  223. );
  224. }
  225. /**
  226. * @param $options
  227. * @return array
  228. */
  229. public function install($options) {
  230. $l = $this->l10n;
  231. $error = array();
  232. $dbType = $options['dbtype'];
  233. if(empty($options['adminlogin'])) {
  234. $error[] = $l->t('Set an admin username.');
  235. }
  236. if(empty($options['adminpass'])) {
  237. $error[] = $l->t('Set an admin password.');
  238. }
  239. if(empty($options['directory'])) {
  240. $options['directory'] = \OC::$SERVERROOT."/data";
  241. }
  242. if (!isset(self::$dbSetupClasses[$dbType])) {
  243. $dbType = 'sqlite';
  244. }
  245. $username = htmlspecialchars_decode($options['adminlogin']);
  246. $password = htmlspecialchars_decode($options['adminpass']);
  247. $dataDir = htmlspecialchars_decode($options['directory']);
  248. $class = self::$dbSetupClasses[$dbType];
  249. /** @var \OC\Setup\AbstractDatabase $dbSetup */
  250. $dbSetup = new $class($l, 'db_structure.xml', $this->config,
  251. $this->logger, $this->random);
  252. $error = array_merge($error, $dbSetup->validate($options));
  253. // validate the data directory
  254. if (
  255. (!is_dir($dataDir) and !mkdir($dataDir)) or
  256. !is_writable($dataDir)
  257. ) {
  258. $error[] = $l->t("Can't create or write into the data directory %s", array($dataDir));
  259. }
  260. if(count($error) != 0) {
  261. return $error;
  262. }
  263. $request = \OC::$server->getRequest();
  264. //no errors, good
  265. if(isset($options['trusted_domains'])
  266. && is_array($options['trusted_domains'])) {
  267. $trustedDomains = $options['trusted_domains'];
  268. } else {
  269. $trustedDomains = [$request->getInsecureServerHost()];
  270. }
  271. if (\OC_Util::runningOnWindows()) {
  272. $dataDir = rtrim(realpath($dataDir), '\\');
  273. }
  274. //use sqlite3 when available, otherwise sqlite2 will be used.
  275. if($dbType=='sqlite' and class_exists('SQLite3')) {
  276. $dbType='sqlite3';
  277. }
  278. //generate a random salt that is used to salt the local user passwords
  279. $salt = $this->random->getLowStrengthGenerator()->generate(30);
  280. // generate a secret
  281. $secret = $this->random->getMediumStrengthGenerator()->generate(48);
  282. //write the config file
  283. $this->config->setSystemValues([
  284. 'passwordsalt' => $salt,
  285. 'secret' => $secret,
  286. 'trusted_domains' => $trustedDomains,
  287. 'datadirectory' => $dataDir,
  288. 'overwrite.cli.url' => $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT,
  289. 'dbtype' => $dbType,
  290. 'version' => implode('.', \OC_Util::getVersion()),
  291. ]);
  292. try {
  293. $dbSetup->initialize($options);
  294. $dbSetup->setupDatabase($username);
  295. } catch (\OC\DatabaseSetupException $e) {
  296. $error[] = array(
  297. 'error' => $e->getMessage(),
  298. 'hint' => $e->getHint()
  299. );
  300. return($error);
  301. } catch (Exception $e) {
  302. $error[] = array(
  303. 'error' => 'Error while trying to create admin user: ' . $e->getMessage(),
  304. 'hint' => ''
  305. );
  306. return($error);
  307. }
  308. //create the user and group
  309. $user = null;
  310. try {
  311. $user = \OC::$server->getUserManager()->createUser($username, $password);
  312. if (!$user) {
  313. $error[] = "User <$username> could not be created.";
  314. }
  315. } catch(Exception $exception) {
  316. $error[] = $exception->getMessage();
  317. }
  318. if(count($error) == 0) {
  319. $config = \OC::$server->getConfig();
  320. $config->setAppValue('core', 'installedat', microtime(true));
  321. $config->setAppValue('core', 'lastupdatedat', microtime(true));
  322. $group =\OC::$server->getGroupManager()->createGroup('admin');
  323. $group->addUser($user);
  324. \OC_User::login($username, $password);
  325. //guess what this does
  326. \OC_Installer::installShippedApps();
  327. // create empty file in data dir, so we can later find
  328. // out that this is indeed an ownCloud data directory
  329. file_put_contents($config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data').'/.ocdata', '');
  330. // Update htaccess files for apache hosts
  331. if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) {
  332. self::updateHtaccess();
  333. self::protectDataDirectory();
  334. }
  335. //try to write logtimezone
  336. if (date_default_timezone_get()) {
  337. $config->setSystemValue('logtimezone', date_default_timezone_get());
  338. }
  339. //and we are done
  340. $config->setSystemValue('installed', true);
  341. }
  342. return $error;
  343. }
  344. /**
  345. * @return string Absolute path to htaccess
  346. */
  347. private function pathToHtaccess() {
  348. return \OC::$SERVERROOT.'/.htaccess';
  349. }
  350. /**
  351. * Checks if the .htaccess contains the current version parameter
  352. *
  353. * @return bool
  354. */
  355. private function isCurrentHtaccess() {
  356. $version = \OC_Util::getVersion();
  357. unset($version[3]);
  358. return !strpos(
  359. file_get_contents($this->pathToHtaccess()),
  360. 'Version: '.implode('.', $version)
  361. ) === false;
  362. }
  363. /**
  364. * Append the correct ErrorDocument path for Apache hosts
  365. *
  366. * @throws \OC\HintException If .htaccess does not include the current version
  367. */
  368. public static function updateHtaccess() {
  369. $setupHelper = new \OC\Setup(\OC::$server->getConfig(), \OC::$server->getIniWrapper(),
  370. \OC::$server->getL10N('lib'), new \OC_Defaults(), \OC::$server->getLogger(),
  371. \OC::$server->getSecureRandom());
  372. if(!$setupHelper->isCurrentHtaccess()) {
  373. throw new \OC\HintException('.htaccess file has the wrong version. Please upload the correct version. Maybe you forgot to replace it after updating?');
  374. }
  375. $htaccessContent = file_get_contents($setupHelper->pathToHtaccess());
  376. $content = '';
  377. if (strpos($htaccessContent, 'ErrorDocument 403') === false) {
  378. //custom 403 error page
  379. $content.= "\nErrorDocument 403 ".\OC::$WEBROOT."/core/templates/403.php";
  380. }
  381. if (strpos($htaccessContent, 'ErrorDocument 404') === false) {
  382. //custom 404 error page
  383. $content.= "\nErrorDocument 404 ".\OC::$WEBROOT."/core/templates/404.php";
  384. }
  385. if ($content !== '') {
  386. //suppress errors in case we don't have permissions for it
  387. @file_put_contents($setupHelper->pathToHtaccess(), $content . "\n", FILE_APPEND);
  388. }
  389. }
  390. public static function protectDataDirectory() {
  391. //Require all denied
  392. $now = date('Y-m-d H:i:s');
  393. $content = "# Generated by ownCloud on $now\n";
  394. $content.= "# line below if for Apache 2.4\n";
  395. $content.= "<ifModule mod_authz_core.c>\n";
  396. $content.= "Require all denied\n";
  397. $content.= "</ifModule>\n\n";
  398. $content.= "# line below if for Apache 2.2\n";
  399. $content.= "<ifModule !mod_authz_core.c>\n";
  400. $content.= "deny from all\n";
  401. $content.= "Satisfy All\n";
  402. $content.= "</ifModule>\n\n";
  403. $content.= "# section for Apache 2.2 and 2.4\n";
  404. $content.= "IndexIgnore *\n";
  405. file_put_contents(\OC_Config::getValue('datadirectory', \OC::$SERVERROOT.'/data').'/.htaccess', $content);
  406. file_put_contents(\OC_Config::getValue('datadirectory', \OC::$SERVERROOT.'/data').'/index.html', '');
  407. }
  408. }