setup.php 13 KB

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