aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Setup.php
diff options
context:
space:
mode:
Diffstat (limited to 'lib/private/Setup.php')
-rw-r--r--lib/private/Setup.php213
1 files changed, 153 insertions, 60 deletions
diff --git a/lib/private/Setup.php b/lib/private/Setup.php
index a5683655447..4082cd5df50 100644
--- a/lib/private/Setup.php
+++ b/lib/private/Setup.php
@@ -14,24 +14,29 @@ use Exception;
use InvalidArgumentException;
use OC\Authentication\Token\PublicKeyTokenProvider;
use OC\Authentication\Token\TokenCleanupJob;
+use OC\Core\BackgroundJobs\GenerateMetadataJob;
use OC\Log\Rotate;
use OC\Preview\BackgroundCleanupJob;
use OC\TextProcessing\RemoveOldTasksBackgroundJob;
+use OC\User\BackgroundJobs\CleanupDeletedUsers;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\Defaults;
+use OCP\Http\Client\IClientService;
use OCP\IAppConfig;
use OCP\IConfig;
use OCP\IGroup;
use OCP\IGroupManager;
use OCP\IL10N;
use OCP\IRequest;
+use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\L10N\IFactory as IL10NFactory;
use OCP\Migration\IOutput;
use OCP\Security\ISecureRandom;
use OCP\Server;
+use OCP\ServerVersion;
use Psr\Log\LoggerInterface;
class Setup {
@@ -44,7 +49,7 @@ class Setup {
protected Defaults $defaults,
protected LoggerInterface $logger,
protected ISecureRandom $random,
- protected Installer $installer
+ protected Installer $installer,
) {
$this->l10n = $l10nFactory->get('lib');
}
@@ -147,7 +152,7 @@ class Setup {
* a few system checks.
*
* @return array of system info, including an "errors" value
- * in case of errors/warnings
+ * in case of errors/warnings
*/
public function getSystemInfo(bool $allowAllDatabases = false): array {
$databases = $this->getSupportedDatabases($allowAllDatabases);
@@ -168,8 +173,7 @@ class Setup {
self::protectDataDirectory();
try {
- $util = new \OC_Util();
- $htAccessWorking = $util->isHtaccessWorking(Server::get(IConfig::class));
+ $htAccessWorking = $this->isHtaccessWorking($dataDir);
} catch (\OCP\HintException $e) {
$errors[] = [
'error' => $e->getMessage(),
@@ -183,8 +187,8 @@ class Setup {
if (\OC_Util::runningOnMac()) {
$errors[] = [
'error' => $this->l10n->t(
- 'Mac OS X is not supported and %s will not work properly on this platform. ' .
- 'Use it at your own risk! ',
+ 'Mac OS X is not supported and %s will not work properly on this platform. '
+ . 'Use it at your own risk!',
[$this->defaults->getProductName()]
),
'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.'),
@@ -194,8 +198,8 @@ class Setup {
if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) {
$errors[] = [
'error' => $this->l10n->t(
- 'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' .
- 'This will lead to problems with files over 4 GB and is highly discouraged.',
+ 'It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. '
+ . 'This will lead to problems with files over 4 GB and is highly discouraged.',
[$this->defaults->getProductName()]
),
'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.'),
@@ -203,10 +207,6 @@ class Setup {
}
return [
- 'hasSQLite' => isset($databases['sqlite']),
- 'hasMySQL' => isset($databases['mysql']),
- 'hasPostgreSQL' => isset($databases['pgsql']),
- 'hasOracle' => isset($databases['oci']),
'databases' => $databases,
'directory' => $dataDir,
'htaccessWorking' => $htAccessWorking,
@@ -214,6 +214,87 @@ class Setup {
];
}
+ public function createHtaccessTestFile(string $dataDir): string|false {
+ // php dev server does not support htaccess
+ if (php_sapi_name() === 'cli-server') {
+ return false;
+ }
+
+ // testdata
+ $fileName = '/htaccesstest.txt';
+ $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
+
+ // creating a test file
+ $testFile = $dataDir . '/' . $fileName;
+
+ if (file_exists($testFile)) {// already running this test, possible recursive call
+ return false;
+ }
+
+ $fp = @fopen($testFile, 'w');
+ if (!$fp) {
+ throw new \OCP\HintException('Can\'t create test file to check for working .htaccess file.',
+ 'Make sure it is possible for the web server to write to ' . $testFile);
+ }
+ fwrite($fp, $testContent);
+ fclose($fp);
+
+ return $testContent;
+ }
+
+ /**
+ * Check if the .htaccess file is working
+ *
+ * @param \OCP\IConfig $config
+ * @return bool
+ * @throws Exception
+ * @throws \OCP\HintException If the test file can't get written.
+ */
+ public function isHtaccessWorking(string $dataDir) {
+ $config = Server::get(IConfig::class);
+
+ if (\OC::$CLI || !$config->getSystemValueBool('check_for_working_htaccess', true)) {
+ return true;
+ }
+
+ $testContent = $this->createHtaccessTestFile($dataDir);
+ if ($testContent === false) {
+ return false;
+ }
+
+ $fileName = '/htaccesstest.txt';
+ $testFile = $dataDir . '/' . $fileName;
+
+ // accessing the file via http
+ $url = Server::get(IURLGenerator::class)->getAbsoluteURL(\OC::$WEBROOT . '/data' . $fileName);
+ try {
+ $content = Server::get(IClientService::class)->newClient()->get($url)->getBody();
+ } catch (\Exception $e) {
+ $content = false;
+ }
+
+ if (str_starts_with($url, 'https:')) {
+ $url = 'http:' . substr($url, 6);
+ } else {
+ $url = 'https:' . substr($url, 5);
+ }
+
+ try {
+ $fallbackContent = Server::get(IClientService::class)->newClient()->get($url)->getBody();
+ } catch (\Exception $e) {
+ $fallbackContent = false;
+ }
+
+ // cleanup
+ @unlink($testFile);
+
+ /*
+ * If the content is not equal to test content our .htaccess
+ * is working as required
+ */
+ return $content !== $testContent && $fallbackContent !== $testContent;
+ }
+
/**
* @return array<string|array> errors
*/
@@ -223,22 +304,24 @@ class Setup {
$error = [];
$dbType = $options['dbtype'];
- if (empty($options['adminlogin'])) {
- $error[] = $l->t('Set an admin Login.');
- }
- if (empty($options['adminpass'])) {
- $error[] = $l->t('Set an admin password.');
+ $disableAdminUser = (bool)($options['admindisable'] ?? false);
+
+ if (!$disableAdminUser) {
+ if (empty($options['adminlogin'])) {
+ $error[] = $l->t('Set an admin Login.');
+ }
+ if (empty($options['adminpass'])) {
+ $error[] = $l->t('Set an admin password.');
+ }
}
if (empty($options['directory'])) {
- $options['directory'] = \OC::$SERVERROOT . "/data";
+ $options['directory'] = \OC::$SERVERROOT . '/data';
}
if (!isset(self::$dbSetupClasses[$dbType])) {
$dbType = 'sqlite';
}
- $username = htmlspecialchars_decode($options['adminlogin']);
- $password = htmlspecialchars_decode($options['adminpass']);
$dataDir = htmlspecialchars_decode($options['directory']);
$class = self::$dbSetupClasses[$dbType];
@@ -248,7 +331,7 @@ class Setup {
// validate the data directory
if ((!is_dir($dataDir) && !mkdir($dataDir)) || !is_writable($dataDir)) {
- $error[] = $l->t("Cannot create or write into the data directory %s", [$dataDir]);
+ $error[] = $l->t('Cannot create or write into the data directory %s', [$dataDir]);
}
if (!empty($error)) {
@@ -294,7 +377,7 @@ class Setup {
$this->outputDebug($output, 'Configuring database');
$dbSetup->initialize($options);
try {
- $dbSetup->setupDatabase($username);
+ $dbSetup->setupDatabase();
} catch (\OC\DatabaseSetupException $e) {
$error[] = [
'error' => $e->getMessage(),
@@ -324,19 +407,22 @@ class Setup {
return $error;
}
- $this->outputDebug($output, 'Create admin account');
-
- // create the admin account and group
$user = null;
- try {
- $user = Server::get(IUserManager::class)->createUser($username, $password);
- if (!$user) {
- $error[] = "Account <$username> could not be created.";
+ if (!$disableAdminUser) {
+ $username = htmlspecialchars_decode($options['adminlogin']);
+ $password = htmlspecialchars_decode($options['adminpass']);
+ $this->outputDebug($output, 'Create admin account');
+
+ try {
+ $user = Server::get(IUserManager::class)->createUser($username, $password);
+ if (!$user) {
+ $error[] = "Account <$username> could not be created.";
+ return $error;
+ }
+ } catch (Exception $exception) {
+ $error[] = $exception->getMessage();
return $error;
}
- } catch (Exception $exception) {
- $error[] = $exception->getMessage();
- return $error;
}
$config = Server::get(IConfig::class);
@@ -351,7 +437,7 @@ class Setup {
}
$group = Server::get(IGroupManager::class)->createGroup('admin');
- if ($group instanceof IGroup) {
+ if ($user !== null && $group instanceof IGroup) {
$group->addUser($user);
}
@@ -360,9 +446,12 @@ class Setup {
Installer::installShippedApps(false, $output);
// create empty file in data dir, so we can later find
- // out that this is indeed an ownCloud data directory
+ // out that this is indeed a Nextcloud data directory
$this->outputDebug($output, 'Setup data directory');
- file_put_contents($config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
+ file_put_contents(
+ $config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/.ncdata',
+ "# Nextcloud data directory\n# Do not change this file",
+ );
// Update .htaccess files
self::updateHtaccess();
@@ -374,32 +463,34 @@ class Setup {
//and we are done
$config->setSystemValue('installed', true);
if (self::shouldRemoveCanInstallFile()) {
- unlink(\OC::$configDir.'/CAN_INSTALL');
+ unlink(\OC::$configDir . '/CAN_INSTALL');
}
- $bootstrapCoordinator = \OCP\Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
+ $bootstrapCoordinator = Server::get(\OC\AppFramework\Bootstrap\Coordinator::class);
$bootstrapCoordinator->runInitialRegistration();
- // Create a session token for the newly created user
- // The token provider requires a working db, so it's not injected on setup
- /** @var \OC\User\Session $userSession */
- $userSession = Server::get(IUserSession::class);
- $provider = Server::get(PublicKeyTokenProvider::class);
- $userSession->setTokenProvider($provider);
- $userSession->login($username, $password);
- $user = $userSession->getUser();
- if (!$user) {
- $error[] = "No account found in session.";
- return $error;
- }
- $userSession->createSessionToken($request, $user->getUID(), $username, $password);
+ if (!$disableAdminUser) {
+ // Create a session token for the newly created user
+ // The token provider requires a working db, so it's not injected on setup
+ /** @var \OC\User\Session $userSession */
+ $userSession = Server::get(IUserSession::class);
+ $provider = Server::get(PublicKeyTokenProvider::class);
+ $userSession->setTokenProvider($provider);
+ $userSession->login($username, $password);
+ $user = $userSession->getUser();
+ if (!$user) {
+ $error[] = 'No account found in session.';
+ return $error;
+ }
+ $userSession->createSessionToken($request, $user->getUID(), $username, $password);
- $session = $userSession->getSession();
- $session->set('last-password-confirm', Server::get(ITimeFactory::class)->getTime());
+ $session = $userSession->getSession();
+ $session->set('last-password-confirm', Server::get(ITimeFactory::class)->getTime());
- // Set email for admin
- if (!empty($options['adminemail'])) {
- $user->setSystemEMailAddress($options['adminemail']);
+ // Set email for admin
+ if (!empty($options['adminemail'])) {
+ $user->setSystemEMailAddress($options['adminemail']);
+ }
}
return $error;
@@ -411,6 +502,8 @@ class Setup {
$jobList->add(Rotate::class);
$jobList->add(BackgroundCleanupJob::class);
$jobList->add(RemoveOldTasksBackgroundJob::class);
+ $jobList->add(CleanupDeletedUsers::class);
+ $jobList->add(GenerateMetadataJob::class);
}
/**
@@ -481,7 +574,7 @@ class Setup {
$content .= "\n Options -MultiViews";
$content .= "\n RewriteRule ^core/js/oc.js$ index.php [PT,E=PATH_INFO:$1]";
$content .= "\n RewriteRule ^core/preview.png$ index.php [PT,E=PATH_INFO:$1]";
- $content .= "\n RewriteCond %{REQUEST_FILENAME} !\\.(css|js|mjs|svg|gif|png|html|ttf|woff2?|ico|jpg|jpeg|map|webm|mp4|mp3|ogg|wav|flac|wasm|tflite)$";
+ $content .= "\n RewriteCond %{REQUEST_FILENAME} !\\.(css|js|mjs|svg|gif|ico|jpg|jpeg|png|webp|html|otf|ttf|woff2?|map|webm|mp4|mp3|ogg|wav|flac|wasm|tflite)$";
$content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/ajax/update\\.php";
$content .= "\n RewriteCond %{REQUEST_FILENAME} !/core/img/(favicon\\.ico|manifest\\.json)$";
$content .= "\n RewriteCond %{REQUEST_FILENAME} !/(cron|public|remote|status)\\.php";
@@ -506,7 +599,7 @@ class Setup {
$df = disk_free_space(\OC::$SERVERROOT);
$size = strlen($content) + 10240;
if ($df !== false && $df < (float)$size) {
- throw new \Exception(\OC::$SERVERROOT . " does not have enough space for writing the htaccess file! Not writing it back!");
+ throw new \Exception(\OC::$SERVERROOT . ' does not have enough space for writing the htaccess file! Not writing it back!');
}
}
//suppress errors in case we don't have permissions for it
@@ -539,7 +632,7 @@ class Setup {
$content .= "# Section for Apache 2.2 to 2.6\n";
$content .= "<IfModule mod_autoindex.c>\n";
$content .= " IndexIgnore *\n";
- $content .= "</IfModule>";
+ $content .= '</IfModule>';
$baseDir = Server::get(IConfig::class)->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
file_put_contents($baseDir . '/.htaccess', $content);
@@ -558,11 +651,11 @@ class Setup {
}
public function shouldRemoveCanInstallFile(): bool {
- return \OC_Util::getChannel() !== 'git' && is_file(\OC::$configDir.'/CAN_INSTALL');
+ return Server::get(ServerVersion::class)->getChannel() !== 'git' && is_file(\OC::$configDir . '/CAN_INSTALL');
}
public function canInstallFileExists(): bool {
- return is_file(\OC::$configDir.'/CAN_INSTALL');
+ return is_file(\OC::$configDir . '/CAN_INSTALL');
}
protected function outputDebug(?IOutput $output, string $message): void {