setup.php 12 KB

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