protected function execute(InputInterface $input, OutputInterface $output) { $importFile = $input->getArgument('file'); if ($importFile !== null) { $content = $this->getArrayFromFile($importFile); } else { $content = $this->getArrayFromStdin(); } try { $configs = $this->validateFileContent($content); } catch (\UnexpectedValueException $e) { $output->writeln('<error>' . $e->getMessage() . '</error>'); return; } if (!empty($configs['system'])) { $this->config->setSystemValues($configs['system']); } if (!empty($configs['apps'])) { foreach ($configs['apps'] as $app => $appConfigs) { foreach ($appConfigs as $key => $value) { if ($value === null) { $this->config->deleteAppValue($app, $key); } else { $this->config->setAppValue($app, $key, $value); } } } } $output->writeln('<info>Config successfully imported from: ' . $importFile . '</info>'); }
protected function execute(InputInterface $input, OutputInterface $output) { if ($this->config->getAppValue('core', 'encryption_enabled', 'no') === 'yes') { $output->writeln('Encryption is already enabled'); } else { $this->config->setAppValue('core', 'encryption_enabled', 'yes'); $output->writeln('<info>Encryption enabled</info>'); } $output->writeln(''); $modules = $this->encryptionManager->getEncryptionModules(); if (empty($modules)) { $output->writeln('<error>No encryption module is loaded</error>'); } else { $defaultModule = $this->config->getAppValue('core', 'default_encryption_module', null); if ($defaultModule === null) { $output->writeln('<error>No default module is set</error>'); } else { if (!isset($modules[$defaultModule])) { $output->writeln('<error>The current default module does not exist: ' . $defaultModule . '</error>'); } else { $output->writeln('Default module: ' . $defaultModule); } } } }
/** * Enables the files app if it is disabled */ public function run() { if ($this->config->getAppValue('files', 'enabled', 'no') !== 'yes') { $this->config->setAppValue('files', 'enabled', 'yes'); $this->emit('\\OC\\Repair', 'info', ['Files app was disabled - re-enabled']); } }
protected function tearDownEncryptionTrait() { if ($this->config) { $this->config->setAppValue('core', 'encryption_enabled', $this->encryptionWasEnabled); $this->config->setAppValue('core', 'default_encryption_module', $this->originalEncryptionModule); } }
/** * @param array $parameters * @return \OC_OCS_Result */ public function setAppValue($parameters) { $app = $parameters['appid']; $configKey = $parameters['configkey']; $value = $this->request->getParam('value'); $this->config->setAppValue($app, $configKey, $value); return new \OC_OCS_Result(); }
protected function run($argument) { $result = []; $result['instances'] = $this->getNumberOfInstances(); $result['categories'] = $this->getStatisticsOfCategories(); $result['apps'] = $this->getApps(); $this->config->setAppValue('popularitycontestserver', 'evaluated_statistics', json_encode($result)); }
/** * @param string $appName * @param string $oldId * @param string $newId * @return bool True if updated, false otherwise */ public function fixOcsId($appName, $oldId, $newId) { $existingId = $this->config->getAppValue($appName, 'ocsid'); if ($existingId === $oldId) { $this->config->setAppValue($appName, 'ocsid', $newId); return true; } return false; }
protected function execute(InputInterface $input, OutputInterface $output) { if ($this->config->getAppValue('core', 'encryption_enabled', 'no') !== 'yes') { $output->writeln('Encryption is already disabled'); } else { $this->config->setAppValue('core', 'encryption_enabled', 'no'); $output->writeln('<info>Encryption disabled</info>'); } }
/** * @return DataResponse */ public function createCredentials() { // Create a new job and store the creation date $this->jobList->add('OCA\\UpdateNotification\\ResetTokenBackgroundJob'); $this->config->setAppValue('core', 'updater.secret.created', $this->timeFactory->getTime()); // Create a new token $newToken = $this->secureRandom->generate(64); $this->config->setSystemValue('updater.secret', password_hash($newToken, PASSWORD_DEFAULT)); return new DataResponse($newToken); }
protected function execute(InputInterface $input, OutputInterface $output) { $appName = $input->getArgument('app'); $configName = $input->getArgument('name'); if (!in_array($configName, $this->config->getAppKeys($appName)) && $input->hasParameterOption('--update-only')) { $output->writeln('<comment>Config value ' . $configName . ' for app ' . $appName . ' not updated, as it has not been set before.</comment>'); return 1; } $configValue = $input->getOption('value'); $this->config->setAppValue($appName, $configName, $configValue); $output->writeln('<info>Config value ' . $configName . ' for app ' . $appName . ' set to ' . $configValue . '</info>'); return 0; }
protected function tearDown() { $user = \OC::$server->getUserManager()->get($this->user); if ($user) { $user->delete(); } $sql = 'DELETE FROM `*PREFIX*storages`'; $this->connection->executeQuery($sql); $sql = 'DELETE FROM `*PREFIX*filecache`'; $this->connection->executeQuery($sql); $this->config->setSystemValue('datadirectory', $this->oldDataDir); $this->config->setAppValue('core', 'repairlegacystoragesdone', 'no'); parent::tearDown(); }
protected function execute(InputInterface $input, OutputInterface $output) { $isAlreadyEnabled = $this->util->isMasterKeyEnabled(); if ($isAlreadyEnabled) { $output->writeln('Master key already enabled'); } else { $question = new ConfirmationQuestion('Warning: Only available for fresh installations with no existing encrypted data! ' . 'There is also no way to disable it again. Do you want to continue? (y/n) ', false); if ($this->questionHelper->ask($input, $output, $question)) { $this->config->setAppValue('encryption', 'useMasterKey', '1'); $output->writeln('Master key successfully enabled.'); } else { $output->writeln('aborted.'); } } }
/** * @param $argument * @throws \Exception */ protected function run($argument) { $maxAge = $this->expiration->getMaxAgeAsTimestamp(); if (!$maxAge) { return; } $offset = $this->config->getAppValue('files_trashbin', 'cronjob_user_offset', 0); $users = $this->userManager->search('', self::USERS_PER_SESSION, $offset); if (!count($users)) { // No users found, reset offset and retry $offset = 0; $users = $this->userManager->search('', self::USERS_PER_SESSION); } $offset += self::USERS_PER_SESSION; $this->config->setAppValue('files_trashbin', 'cronjob_user_offset', $offset); foreach ($users as $user) { $uid = $user->getUID(); if (!$this->setupFS($uid)) { continue; } $dirContent = Helper::getTrashFiles('/', $uid, 'mtime'); Trashbin::deleteExpiredFiles($dirContent, $uid); } \OC_Util::tearDownFS(); }
/** * @param IStorage $keyStorage * @param Crypt $crypt * @param IConfig $config * @param IUserSession $userSession * @param Session $session * @param ILogger $log * @param Util $util */ public function __construct(IStorage $keyStorage, Crypt $crypt, IConfig $config, IUserSession $userSession, Session $session, ILogger $log, Util $util) { $this->util = $util; $this->session = $session; $this->keyStorage = $keyStorage; $this->crypt = $crypt; $this->config = $config; $this->log = $log; $this->recoveryKeyId = $this->config->getAppValue('encryption', 'recoveryKeyId'); if (empty($this->recoveryKeyId)) { $this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8); $this->config->setAppValue('encryption', 'recoveryKeyId', $this->recoveryKeyId); } $this->publicShareKeyId = $this->config->getAppValue('encryption', 'publicShareKeyId'); if (empty($this->publicShareKeyId)) { $this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8); $this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId); } $shareKey = $this->getPublicShareKey(); if (empty($shareKey)) { $keyPair = $this->crypt->createKeyPair(); // Save public key $this->keyStorage->setSystemUserKey($this->publicShareKeyId . '.publicKey', $keyPair['publicKey']); // Encrypt private key empty passphrase $encryptedKey = $this->crypt->symmetricEncryptFileContent($keyPair['privateKey'], ''); $this->keyStorage->setSystemUserKey($this->publicShareKeyId . '.privateKey', $encryptedKey); } $this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false; $this->log = $log; }
/** * @param string $mountPoint * @param int $time */ protected function markDirty($mountPoint, $time = null) { if ($time === null) { $time = time(); } $this->config->setAppValue('files_external', $mountPoint, $time); }
/** * update database */ public function updateDB() { // make sure that we don't update the file cache multiple times // only update during the first run if ($this->installedVersion === '-1') { return; } // delete left-over from old encryption which is no longer needed $this->config->deleteAppValue('files_encryption', 'ocsid'); $this->config->deleteAppValue('files_encryption', 'types'); $this->config->deleteAppValue('files_encryption', 'enabled'); $oldAppValues = $this->connection->createQueryBuilder(); $oldAppValues->select('*')->from('`*PREFIX*appconfig`')->where($oldAppValues->expr()->eq('`appid`', ':appid'))->setParameter('appid', 'files_encryption'); $appSettings = $oldAppValues->execute(); while ($row = $appSettings->fetch()) { // 'installed_version' gets deleted at the end of the migration process if ($row['configkey'] !== 'installed_version') { $this->config->setAppValue('encryption', $row['configkey'], $row['configvalue']); $this->config->deleteAppValue('files_encryption', $row['configkey']); } } $oldPreferences = $this->connection->createQueryBuilder(); $oldPreferences->select('*')->from('`*PREFIX*preferences`')->where($oldPreferences->expr()->eq('`appid`', ':appid'))->setParameter('appid', 'files_encryption'); $preferenceSettings = $oldPreferences->execute(); while ($row = $preferenceSettings->fetch()) { $this->config->setUserValue($row['userid'], 'encryption', $row['configkey'], $row['configvalue']); $this->config->deleteUserValue($row['userid'], 'files_encryption', $row['configkey']); } }
/** * @param IStorage $keyStorage * @param Crypt $crypt * @param IConfig $config * @param IUserSession $userSession * @param Session $session * @param ILogger $log * @param Util $util */ public function __construct(IStorage $keyStorage, Crypt $crypt, IConfig $config, IUserSession $userSession, Session $session, ILogger $log, Util $util) { $this->util = $util; $this->session = $session; $this->keyStorage = $keyStorage; $this->crypt = $crypt; $this->config = $config; $this->log = $log; $this->recoveryKeyId = $this->config->getAppValue('encryption', 'recoveryKeyId'); if (empty($this->recoveryKeyId)) { $this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8); $this->config->setAppValue('encryption', 'recoveryKeyId', $this->recoveryKeyId); } $this->publicShareKeyId = $this->config->getAppValue('encryption', 'publicShareKeyId'); if (empty($this->publicShareKeyId)) { $this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8); $this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId); } $this->masterKeyId = $this->config->getAppValue('encryption', 'masterKeyId'); if (empty($this->masterKeyId)) { $this->masterKeyId = 'master_' . substr(md5(time()), 0, 8); $this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId); } $this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false; $this->log = $log; }
/** * @param array $share * @param float $time */ public function markDirty($share, $time = null) { if ($time === null) { $time = microtime(true); } $this->config->setAppValue('files_sharing', $share['id'], $time); }
/** * Copied from \OC_Util::isSharingDisabledForUser * * TODO: Deprecate fuction from OC_Util * * @param string $userId * @return bool */ public function sharingDisabledForUser($userId) { if ($userId === null) { return false; } if (isset($this->sharingDisabledForUsersCache[$userId])) { return $this->sharingDisabledForUsersCache[$userId]; } if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') { $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); $excludedGroups = json_decode($groupsList); if (is_null($excludedGroups)) { $excludedGroups = explode(',', $groupsList); $newValue = json_encode($excludedGroups); $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue); } $user = $this->userManager->get($userId); $usersGroups = $this->groupManager->getUserGroupIds($user); if (!empty($usersGroups)) { $remainingGroups = array_diff($usersGroups, $excludedGroups); // if the user is only in groups which are disabled for sharing then // sharing is also disabled for the user if (empty($remainingGroups)) { $this->sharingDisabledForUsersCache[$userId] = true; return true; } } } $this->sharingDisabledForUsersCache[$userId] = false; return false; }
/** * runs the update actions in maintenance mode, does not upgrade the source files * except the main .htaccess file * * @param string $currentVersion current version to upgrade to * @param string $installedVersion previous version from which to upgrade from * * @throws \Exception */ private function doUpgrade($currentVersion, $installedVersion) { // Stop update if the update is over several major versions $allowedPreviousVersion = $this->getAllowedPreviousVersion(); if (!self::isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersion)) { throw new \Exception('Updates between multiple major versions and downgrades are unsupported.'); } // Update .htaccess files try { Setup::updateHtaccess(); Setup::protectDataDirectory(); } catch (\Exception $e) { throw new \Exception($e->getMessage()); } // create empty file in data dir, so we can later find // out that this is indeed an ownCloud data directory // (in case it didn't exist before) file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', ''); // pre-upgrade repairs $repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher()); $repair->run(); // simulate DB upgrade if ($this->simulateStepEnabled) { $this->checkCoreUpgrade(); // simulate apps DB upgrade $this->checkAppUpgrade($currentVersion); } if ($this->updateStepEnabled) { $this->doCoreUpgrade(); // update all shipped apps $disabledApps = $this->checkAppsRequirements(); $this->doAppUpgrade(); // upgrade appstore apps $this->upgradeAppStoreApps($disabledApps); // install new shipped apps on upgrade OC_App::loadApps('authentication'); $errors = Installer::installShippedApps(true); foreach ($errors as $appId => $exception) { /** @var \Exception $exception */ $this->log->logException($exception, ['app' => $appId]); $this->emit('\\OC\\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]); } // post-upgrade repairs $repair = new Repair(Repair::getRepairSteps(), \OC::$server->getEventDispatcher()); $repair->run(); //Invalidate update feed $this->config->setAppValue('core', 'lastupdatedat', 0); // Check for code integrity if not disabled if (\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) { $this->emit('\\OC\\Updater', 'startCheckCodeIntegrity'); $this->checker->runInstanceVerification(); $this->emit('\\OC\\Updater', 'finishedCheckCodeIntegrity'); } // only set the final version if everything went well $this->config->setSystemValue('version', implode('.', \OCP\Util::getVersion())); } }
/** * set default encryption module Id * * @param string $moduleId * @return bool */ public function setDefaultEncryptionModule($moduleId) { try { $this->config->setAppValue('core', 'default_encryption_module', $moduleId); return true; } catch (\Exception $e) { return false; } }
/** * runs the update actions in maintenance mode, does not upgrade the source files * except the main .htaccess file * * @param string $currentVersion current version to upgrade to * @param string $installedVersion previous version from which to upgrade from * * @throws \Exception * @return bool true if the operation succeeded, false otherwise */ private function doUpgrade($currentVersion, $installedVersion) { // Stop update if the update is over several major versions if (!self::isUpgradePossible($installedVersion, $currentVersion)) { throw new \Exception('Updates between multiple major versions are unsupported.'); } // Update .htaccess files try { Setup::updateHtaccess(); Setup::protectDataDirectory(); } catch (\Exception $e) { throw new \Exception($e->getMessage()); } // create empty file in data dir, so we can later find // out that this is indeed an ownCloud data directory // (in case it didn't exist before) file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', ''); // pre-upgrade repairs $repair = new Repair(Repair::getBeforeUpgradeRepairSteps()); $this->emitRepairMessages($repair); $repair->run(); // simulate DB upgrade if ($this->simulateStepEnabled) { $this->checkCoreUpgrade(); // simulate apps DB upgrade $this->checkAppUpgrade($currentVersion); } if ($this->updateStepEnabled) { $this->doCoreUpgrade(); // update all shipped apps $disabledApps = $this->checkAppsRequirements(); $this->doAppUpgrade(); // upgrade appstore apps $this->upgradeAppStoreApps($disabledApps); // post-upgrade repairs $repair = new Repair(Repair::getRepairSteps()); $this->emitRepairMessages($repair); $repair->run(); //Invalidate update feed $this->config->setAppValue('core', 'lastupdatedat', 0); // only set the final version if everything went well $this->config->setSystemValue('version', implode('.', \OC_Util::getVersion())); } }
/** * @param string $recoveryPassword * @return bool */ public function disableAdminRecovery($recoveryPassword) { $keyManager = $this->keyManager; if ($keyManager->checkRecoveryPassword($recoveryPassword)) { // Set recoveryAdmin as disabled $this->config->setAppValue('encryption', 'recoveryAdminEnabled', 0); return true; } return false; }
/** * Check if a new version is available * * @param string $updaterUrl the url to check, i.e. 'http://apps.owncloud.com/updater.php' * @return array|bool */ public function check($updaterUrl = null) { // Look up the cache - it is invalidated all 30 minutes if ((int) $this->config->getAppValue('core', 'lastupdatedat') + 1800 > time()) { return json_decode($this->config->getAppValue('core', 'lastupdateResult'), true); } if (is_null($updaterUrl)) { $updaterUrl = 'https://updates.owncloud.com/server/'; } $this->config->setAppValue('core', 'lastupdatedat', time()); if ($this->config->getAppValue('core', 'installedat', '') === '') { $this->config->setAppValue('core', 'installedat', microtime(true)); } $version = Util::getVersion(); $version['installed'] = $this->config->getAppValue('core', 'installedat'); $version['updated'] = $this->config->getAppValue('core', 'lastupdatedat'); $version['updatechannel'] = \OC_Util::getChannel(); $version['edition'] = \OC_Util::getEditionString(); $version['build'] = \OC_Util::getBuild(); $versionString = implode('x', $version); //fetch xml data from updater $url = $updaterUrl . '?version=' . $versionString; $tmp = []; $xml = $this->getUrlContent($url); if ($xml) { $loadEntities = libxml_disable_entity_loader(true); $data = @simplexml_load_string($xml); libxml_disable_entity_loader($loadEntities); if ($data !== false) { $tmp['version'] = (string) $data->version; $tmp['versionstring'] = (string) $data->versionstring; $tmp['url'] = (string) $data->url; $tmp['web'] = (string) $data->web; } else { libxml_clear_errors(); } } else { $data = []; } // Cache the result $this->config->setAppValue('core', 'lastupdateResult', json_encode($data)); return $tmp; }
/** * Stores the results in the app config as well as cache * * @param string $scope * @param array $result */ private function storeResults($scope, array $result) { $resultArray = $this->getResults(); unset($resultArray[$scope]); if (!empty($result)) { $resultArray[$scope] = $result; } $this->config->setAppValue('core', self::CACHE_KEY, json_encode($resultArray)); $this->cache->set(self::CACHE_KEY, json_encode($resultArray)); }
protected function execute(InputInterface $input, OutputInterface $output) { try { if ($this->encryptionManager->isEnabled() === true) { $output->write('Disable server side encryption... '); $this->config->setAppValue('core', 'encryption_enabled', 'no'); $output->writeln('done.'); } else { $output->writeln('Server side encryption not enabled. Nothing to do.'); return; } $uid = $input->getArgument('user'); if ($uid === '') { $message = 'your ownCloud'; } else { $message = "{$uid}'s account"; } $output->writeln("\n"); $output->writeln("You are about to start to decrypt all files stored in {$message}."); $output->writeln('It will depend on the encryption module and your setup if this is possible.'); $output->writeln('Depending on the number and size of your files this can take some time'); $output->writeln('Please make sure that no user access his files during this process!'); $output->writeln(''); $question = new ConfirmationQuestion('Do you really want to continue? (y/n) ', false); if ($this->questionHelper->ask($input, $output, $question)) { $this->forceSingleUserAndTrashbin(); $user = $input->getArgument('user'); $result = $this->decryptAll->decryptAll($input, $output, $user); if ($result === false) { $output->writeln(' aborted.'); $output->writeln('Server side encryption remains enabled'); $this->config->setAppValue('core', 'encryption_enabled', 'yes'); } else { if ($uid !== '') { $output->writeln('Server side encryption remains enabled'); $this->config->setAppValue('core', 'encryption_enabled', 'yes'); } } $this->resetSingleUserAndTrashbin(); } else { $output->write('Enable server side encryption... '); $this->config->setAppValue('core', 'encryption_enabled', 'yes'); $output->writeln('done.'); $output->writeln('aborted'); } } catch (\Exception $e) { // enable server side encryption again if something went wrong $this->config->setAppValue('core', 'encryption_enabled', 'yes'); $this->resetSingleUserAndTrashbin(); throw $e; } }
/** * @param \OCP\IConfig $config * @param string $cacheDir */ public function gc(IConfig $config, $cacheDir) { $lastRun = $config->getAppValue('core', 'global_cache_gc_lastrun', 0); $now = time(); if ($now - $lastRun < 300) { // only do cleanup every 5 minutes return; } $config->setAppValue('core', 'global_cache_gc_lastrun', $now); if (!is_dir($cacheDir)) { return; } array_walk($this->getExpiredPaths($cacheDir, $now), 'unlink'); }
/** * @param $argument * @throws \Exception */ protected function run($argument) { $offset = $this->config->getAppValue('files', 'cronjob_scan_files', 0); $users = $this->userManager->search('', self::USERS_PER_SESSION, $offset); if (!count($users)) { // No users found, reset offset and retry $offset = 0; $users = $this->userManager->search('', self::USERS_PER_SESSION); } $offset += self::USERS_PER_SESSION; $this->config->setAppValue('files', 'cronjob_scan_files', $offset); foreach ($users as $user) { $this->runScanner($user); } }
/** * @return \OC_OCS_Result */ public function sendReport() { $report = $this->getReport(); $client = $this->clientService->newClient(); $this->config->setAppValue('popularitycontestclient', 'last_sent', time()); $this->config->setAppValue('popularitycontestclient', 'last_report', json_encode($report)); try { $response = $client->post(self::SURVEY_SERVER_URL . 'ocs/v2.php/apps/popularitycontestserver/api/v1/survey', ['timeout' => 5, 'query' => ['data' => json_encode($report)]]); } catch (\Exception $e) { return new \OC_OCS_Result($report, Http::STATUS_INTERNAL_SERVER_ERROR); } if ($response->getStatusCode() === Http::STATUS_OK) { return new \OC_OCS_Result($report, 100); } return new \OC_OCS_Result($report, Http::STATUS_INTERNAL_SERVER_ERROR); }
/** * @param \OCP\IConfig $config * @param string $cacheDir */ public function gc(IConfig $config, $cacheDir) { $lastRun = $config->getAppValue('core', 'global_cache_gc_lastrun', 0); $now = time(); if ($now - $lastRun < self::CLEANUP_TTL_SEC) { return; } $config->setAppValue('core', 'global_cache_gc_lastrun', $now); if (!is_dir($cacheDir)) { return; } $paths = $this->getExpiredPaths($cacheDir, $now); array_walk($paths, function ($file) { unlink($file); }); }