/** * Send an email to {$limit} users * * @param int $limit Number of users we want to send an email to * @return int Number of users we sent an email to */ protected function runStep($limit) { // We don't use time() but "time() - 1" here, so we don't run into // runtime issues later and delete emails, which were created in the // same second, but were not collected for the emails. $sendTime = time() - 1; // Get all users which should receive an email $affectedUsers = $this->mqHandler->getAffectedUsers($limit, $sendTime); if (empty($affectedUsers)) { // No users found to notify, mission abort return 0; } $userLanguages = $this->config->getUserValueForUsers('core', 'lang', $affectedUsers); $userTimezones = $this->config->getUserValueForUsers('core', 'timezone', $affectedUsers); $userEmails = $this->config->getUserValueForUsers('settings', 'email', $affectedUsers); // Get all items for these users $mailData = $this->mqHandler->getItemsForUsers($affectedUsers, $sendTime); // Send Email $default_lang = $this->config->getSystemValue('default_language', 'en'); $defaultTimeZone = date_default_timezone_get(); foreach ($mailData as $user => $data) { if (empty($userEmails[$user])) { // The user did not setup an email address // So we will not send an email :( $this->logger->debug("Couldn't send notification email to user '" . $user . "' (email address isn't set for that user)", ['app' => 'activity']); continue; } $language = !empty($userLanguages[$user]) ? $userLanguages[$user] : $default_lang; $timezone = !empty($userTimezones[$user]) ? $userTimezones[$user] : $defaultTimeZone; $this->mqHandler->sendEmailToUser($user, $userEmails[$user], $language, $timezone, $data); } // Delete all entries we dealt with $this->mqHandler->deleteSentItems($affectedUsers, $sendTime); return sizeof($affectedUsers); }
/** * Set single user mode and disable the trashbin app */ protected function forceSingleUserAndTrashbin() { $this->wasTrashbinEnabled = $this->appManager->isEnabledForUser('files_trashbin'); $this->wasSingleUserModeEnabled = $this->config->getSystemValue('singleuser', false); $this->config->setSystemValue('singleuser', true); $this->appManager->disableApp('files_trashbin'); }
/** * @param OutputInterface $output */ public function loadCommands(OutputInterface $output) { // $application is required to be defined in the register_command scripts $application = $this->application; require_once \OC::$SERVERROOT . '/core/register_command.php'; if ($this->config->getSystemValue('installed', false)) { if (!\OCP\Util::needUpgrade()) { OC_App::loadApps(); foreach (OC_App::getAllApps() as $app) { $file = OC_App::getAppPath($app) . '/appinfo/register_command.php'; if (file_exists($file)) { require $file; } } } else { $output->writeln("ownCloud or one of the apps require upgrade - only a limited number of commands are available"); } } else { $output->writeln("ownCloud is not installed - only a limited number of commands are available"); } $input = new ArgvInput(); if ($input->getFirstArgument() !== 'check') { $errors = \OC_Util::checkServer(\OC::$server->getConfig()); if (!empty($errors)) { foreach ($errors as $error) { $output->writeln($error['error']); $output->writeln($error['hint']); $output->writeln(''); } throw new \Exception("Environment not properly prepared."); } } }
/** * Validates a username and password * * This method should return true or false depending on if login * succeeded. * * @param string $username * @param string $password * * @return bool */ protected function validateUserPass($username, $password) { $linkItem = \OCP\Share::getShareByToken($username, false); \OC_User::setIncognitoMode(true); $this->share = $linkItem; if (!$linkItem) { return false; } // check if the share is password protected if (isset($linkItem['share_with'])) { if ($linkItem['share_type'] == \OCP\Share::SHARE_TYPE_LINK) { // Check Password $forcePortable = CRYPT_BLOWFISH != 1; $hasher = new \PasswordHash(8, $forcePortable); if (!$hasher->CheckPassword($password . $this->config->getSystemValue('passwordsalt', ''), $linkItem['share_with'])) { return false; } else { return true; } } else { return false; } } else { return true; } }
/** * Creates an url * @param string $app app * @param string $file file * @param array $args array with param=>value, will be appended to the returned url * The value of $args will be urlencoded * @return string the url * * Returns a url to the given app and file. */ public function linkTo($app, $file, $args = array()) { $frontControllerActive = $this->config->getSystemValue('front_controller_active', 'false') == 'true'; if ($app != '') { $app_path = \OC_App::getAppPath($app); // Check if the app is in the app folder if ($app_path && file_exists($app_path . '/' . $file)) { if (substr($file, -3) == 'php') { $urlLinkTo = \OC::$WEBROOT . '/index.php/apps/' . $app; if ($frontControllerActive) { $urlLinkTo = \OC::$WEBROOT . '/apps/' . $app; } $urlLinkTo .= $file != 'index.php' ? '/' . $file : ''; } else { $urlLinkTo = \OC_App::getAppWebPath($app) . '/' . $file; } } else { $urlLinkTo = \OC::$WEBROOT . '/' . $app . '/' . $file; } } else { if (file_exists(\OC::$SERVERROOT . '/core/' . $file)) { $urlLinkTo = \OC::$WEBROOT . '/core/' . $file; } else { if ($frontControllerActive && $file === 'index.php') { $urlLinkTo = \OC::$WEBROOT; } else { $urlLinkTo = \OC::$WEBROOT . '/' . $file; } } } if ($args && ($query = http_build_query($args, '', '&'))) { $urlLinkTo .= '?' . $query; } return $urlLinkTo; }
/** * Generate a keypair * * @return array ['privatekey' => $privateKey, 'publickey' => $publicKey] */ public function createKey() { $rsa = new RSACrypt(); $rsa->setPublicKeyFormat(RSACrypt::PUBLIC_FORMAT_OPENSSH); $rsa->setPassword($this->config->getSystemValue('secret', '')); return $rsa->createKey(self::CREATE_KEY_BITS); }
protected function execute(InputInterface $input, OutputInterface $output) { $includeExpensive = $input->getOption('include-expensive'); if ($includeExpensive) { foreach ($this->repair->getExpensiveRepairSteps() as $step) { $this->repair->addStep($step); } } $maintenanceMode = $this->config->getSystemValue('maintenance', false); $this->config->setSystemValue('maintenance', true); $this->repair->listen('\\OC\\Repair', 'step', function ($description) use($output) { $output->writeln(' - ' . $description); }); $this->repair->listen('\\OC\\Repair', 'info', function ($description) use($output) { $output->writeln(' - ' . $description); }); $this->repair->listen('\\OC\\Repair', 'warning', function ($description) use($output) { $output->writeln(' - WARNING: ' . $description); }); $this->repair->listen('\\OC\\Repair', 'error', function ($description) use($output) { $output->writeln(' - ERROR: ' . $description); }); $this->repair->run(); $this->config->setSystemValue('maintenance', $maintenanceMode); }
/** * @param IEvent $event * @param string $parameter The parameter to be formatted * @param bool $allowHtml Should HTML be used to format the parameter? * @param bool $verbose Should paths, names, etc be shortened or full length * @return string The formatted parameter */ public function format(IEvent $event, $parameter, $allowHtml, $verbose = false) { // If the username is empty, the action has been performed by a remote // user, or via a public share. We don't know the username in that case if ($parameter === '') { if ($allowHtml === null) { return '<user display-name="' . Util::sanitizeHTML($this->l->t('"remote user"')) . '">' . Util::sanitizeHTML('') . '</user>'; } if ($allowHtml) { return '<strong>' . $this->l->t('"remote user"') . '</strong>'; } else { return $this->l->t('"remote user"'); } } $user = $this->manager->get($parameter); $displayName = $user ? $user->getDisplayName() : $parameter; $parameter = Util::sanitizeHTML($parameter); if ($allowHtml === null) { return '<user display-name="' . Util::sanitizeHTML($displayName) . '">' . Util::sanitizeHTML($parameter) . '</user>'; } if ($allowHtml) { $avatarPlaceholder = ''; if ($this->config->getSystemValue('enable_avatars', true)) { $avatarPlaceholder = '<div class="avatar" data-user="******"></div>'; } return $avatarPlaceholder . '<strong>' . Util::sanitizeHTML($displayName) . '</strong>'; } else { return $displayName; } }
/** * Add a new trusted domain * @param string $newTrustedDomain The newly to add trusted domain * @return array */ public function trustedDomains($newTrustedDomain) { $trustedDomains = $this->config->getSystemValue('trusted_domains'); $trustedDomains[] = $newTrustedDomain; $this->config->setSystemValue('trusted_domains', $trustedDomains); return $this->returnSuccess(); }
protected function execute(InputInterface $input, OutputInterface $output) { // collate config setting to the end, to avoid partial configuration $toBeSet = []; if ($backend = $input->getOption('backend')) { $this->validateBackend($backend); $toBeSet['log_type'] = $backend; } if ($level = $input->getOption('level')) { if (is_numeric($level)) { $levelNum = $level; // sanity check $this->convertLevelNumber($levelNum); } else { $levelNum = $this->convertLevelString($level); } $toBeSet['loglevel'] = $levelNum; } if ($timezone = $input->getOption('timezone')) { $this->validateTimezone($timezone); $toBeSet['logtimezone'] = $timezone; } // set config foreach ($toBeSet as $option => $value) { $this->config->setSystemValue($option, $value); } // display configuration $backend = $this->config->getSystemValue('log_type', self::DEFAULT_BACKEND); $output->writeln('Enabled logging backend: ' . $backend); $levelNum = $this->config->getSystemValue('loglevel', self::DEFAULT_LOG_LEVEL); $level = $this->convertLevelNumber($levelNum); $output->writeln('Log level: ' . $level . ' (' . $levelNum . ')'); $timezone = $this->config->getSystemValue('logtimezone', self::DEFAULT_TIMEZONE); $output->writeln('Log timezone: ' . $timezone); }
/** * Returns all certificates trusted by the user * * @return \OCP\ICertificate[] */ public function listCertificates() { if (!$this->config->getSystemValue('installed', false)) { return array(); } $path = $this->getPathToCertificates() . 'uploads/'; if (!$this->view->is_dir($path)) { return array(); } $result = array(); $handle = $this->view->opendir($path); if (!is_resource($handle)) { return array(); } while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { try { $result[] = new Certificate($this->view->file_get_contents($path . $file), $file); } catch (\Exception $e) { } } } closedir($handle); return $result; }
protected function setUp() { parent::setUp(); $this->config = \OC::$server->getConfig(); $this->connection = \OC::$server->getDatabaseConnection(); $this->manager = new MDB2SchemaManager($this->connection); $this->testPrefix = strtolower($this->getUniqueID($this->config->getSystemValue('dbtableprefix', 'oc_'), 3)); }
public function run() { $ocVersionFromBeforeUpdate = $this->config->getSystemValue('version', '0.0.0'); if (version_compare($ocVersionFromBeforeUpdate, '8.2.0.7', '<')) { // this situation was only possible before 8.2 $this->removeExpirationDateFromNonLinkShares(); } }
protected function setUp() { parent::setUp(); $this->config = \OC::$server->getConfig(); $this->connection = \OC::$server->getDatabaseConnection(); $this->oldDataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/'); $this->repair = new \OC\Repair\RepairLegacyStorages($this->config, $this->connection); $this->outputMock = $this->getMockBuilder('\\OCP\\Migration\\IOutput')->disableOriginalConstructor()->getMock(); }
/** * Check if encryption is enabled * * @return bool true if enabled, false if not */ public function isEnabled() { $installed = $this->config->getSystemValue('installed', false); if (!$installed) { return false; } $enabled = $this->config->getAppValue('core', 'encryption_enabled', 'no'); return $enabled === 'yes'; }
/** * @param \Doctrine\DBAL\Connection $connection * @return string[] */ protected function getAllNonUTF8BinTables($connection) { $dbName = $this->config->getSystemValue("dbname"); $rows = $connection->fetchAll("SELECT DISTINCT(TABLE_NAME) AS `table`" . "\tFROM INFORMATION_SCHEMA . COLUMNS" . "\tWHERE TABLE_SCHEMA = ?" . "\tAND (COLLATION_NAME <> 'utf8_bin' OR CHARACTER_SET_NAME <> 'utf8')" . "\tAND TABLE_NAME LIKE \"*PREFIX*%\"", array($dbName)); $result = array(); foreach ($rows as $row) { $result[] = $row['table']; } return $result; }
/** * @param \OCP\IConfig $config * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform */ public function __construct(IConfig $config, AbstractPlatform $platform) { $this->platform = $platform; $this->DBNAME = $config->getSystemValue('dbname', 'owncloud'); $this->DBTABLEPREFIX = $config->getSystemValue('dbtableprefix', 'oc_'); // Oracle does not support longer index names then 30 characters. // We use this limit for all DBs to make sure it does not cause a // problem. $this->schemaConfig = new SchemaConfig(); $this->schemaConfig->setMaxIdentifierLength(30); }
public function setUp() { $this->connection = \OC_DB::getConnection(); $this->config = \OC::$server->getConfig(); if (!$this->connection->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\MySqlPlatform) { $this->markTestSkipped("Test only relevant on MySql"); } $dbPrefix = $this->config->getSystemValue("dbtableprefix"); $this->tableName = uniqid($dbPrefix . "_collation_test"); $this->connection->exec("CREATE TABLE {$this->tableName}(text VARCHAR(16)) COLLATE utf8_unicode_ci"); $this->repair = new TestCollationRepair($this->config, $this->connection); }
protected function setUp() { parent::setUp(); $this->config = \OC::$server->getConfig(); $this->connection = \OC::$server->getDatabaseConnection(); $this->oldDataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/'); $this->repair = new \OC\Repair\RepairLegacyStorages($this->config, $this->connection); $this->warnings = []; $this->repair->listen('\\OC\\Repair', 'warning', function ($description) { $this->warnings[] = $description; }); }
/** * @param IManager $encryptionManager * @param IAppManager $appManager * @param IConfig $config * @param QuestionHelper $questionHelper */ public function __construct(IManager $encryptionManager, IAppManager $appManager, IConfig $config, QuestionHelper $questionHelper) { parent::__construct(); $this->appManager = $appManager; $this->encryptionManager = $encryptionManager; $this->config = $config; $this->questionHelper = $questionHelper; $this->wasTrashbinEnabled = $this->appManager->isEnabledForUser('files_trashbin'); $this->wasSingleUserModeEnabled = $this->config->getSystemValue('singleuser', false); $this->config->setSystemValue('singleuser', true); $this->appManager->disableApp('files_trashbin'); }
/** * Verify legacy hashes * @param string $message Message to verify * @param string $hash Assumed hash of the message * @param null|string &$newHash Reference will contain the updated hash * @return bool Whether $hash is a valid hash of $message */ protected function legacyHashVerify($message, $hash, &$newHash = null) { if (empty($this->legacySalt)) { $this->legacySalt = $this->config->getSystemValue('passwordsalt', ''); } // Verify whether it matches a legacy PHPass or SHA1 string $hashLength = strlen($hash); if ($hashLength === 60 && password_verify($message . $this->legacySalt, $hash) || $hashLength === 40 && StringUtils::equals($hash, sha1($message))) { $newHash = $this->hash($message); return true; } return false; }
/** * Get the cache mount for a user * * @param IUser $user * @param IStorageFactory $loader * @return \OCP\Files\Mount\IMountPoint[] */ public function getMountsForUser(IUser $user, IStorageFactory $loader) { $cacheBaseDir = $this->config->getSystemValue('cache_path', ''); if ($cacheBaseDir !== '') { $cacheDir = rtrim($cacheBaseDir, '/') . '/' . $user->getUID(); if (!file_exists($cacheDir)) { mkdir($cacheDir, 0770, true); } return [new MountPoint('\\OC\\Files\\Storage\\Local', '/' . $user->getUID() . '/cache', ['datadir' => $cacheDir, $loader])]; } else { return []; } }
/** * Get the proxy URI * @return string */ private function getProxyUri() { $proxyHost = $this->config->getSystemValue('proxy', null); $proxyUserPwd = $this->config->getSystemValue('proxyuserpwd', null); $proxyUri = ''; if (!is_null($proxyUserPwd)) { $proxyUri .= $proxyUserPwd . '@'; } if (!is_null($proxyHost)) { $proxyUri .= $proxyHost; } return $proxyUri; }
/** * This method is called before any HTTP method and returns http status code 503 * in case the system is in maintenance mode. * * @throws ServiceUnavailable * @return bool */ public function checkMaintenanceMode() { if ($this->config->getSystemValue('singleuser', false)) { throw new ServiceUnavailable('System in single user mode.'); } if ($this->config->getSystemValue('maintenance', false)) { throw new ServiceUnavailable('System in maintenance mode.'); } if (\OC::checkUpgrade(false)) { throw new ServiceUnavailable('Upgrade needed'); } return true; }
protected function setUp() { parent::setUp(); $this->connection = \OC::$server->getDatabaseConnection(); $this->config = \OC::$server->getConfig(); if (!$this->connection->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) { $this->markTestSkipped("Test only relevant on Sqlite"); } $dbPrefix = $this->config->getSystemValue('dbtableprefix', 'oc_'); $this->tableName = $this->getUniqueID($dbPrefix . 'autoinc_test'); $this->connection->exec('CREATE TABLE ' . $this->tableName . '("someid" INTEGER NOT NULL, "text" VARCHAR(16), PRIMARY KEY("someid"))'); $this->repair = new \OC\Repair\SqliteAutoincrement($this->connection); }
/** * @param InputInterface $input * @param OutputInterface $output * @throws \Exception */ public function loadCommands(InputInterface $input, OutputInterface $output) { // $application is required to be defined in the register_command scripts $application = $this->application; $inputDefinition = $application->getDefinition(); $inputDefinition->addOption(new InputOption('no-warnings', null, InputOption::VALUE_NONE, 'Skip global warnings, show command output only', null)); try { $input->bind($inputDefinition); } catch (\RuntimeException $e) { //expected if there are extra options } if ($input->getOption('no-warnings')) { $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); } require_once __DIR__ . '/../../../core/register_command.php'; if ($this->config->getSystemValue('installed', false)) { if (\OCP\Util::needUpgrade()) { $output->writeln("ownCloud or one of the apps require upgrade - only a limited number of commands are available"); $output->writeln("You may use your browser or the occ upgrade command to do the upgrade"); } elseif ($this->config->getSystemValue('maintenance', false)) { $output->writeln("ownCloud is in maintenance mode - no app have been loaded"); } else { OC_App::loadApps(); foreach (\OC::$server->getAppManager()->getInstalledApps() as $app) { $appPath = \OC_App::getAppPath($app); if ($appPath === false) { continue; } \OC::$loader->addValidRoot($appPath); $file = $appPath . '/appinfo/register_command.php'; if (file_exists($file)) { require $file; } } } } else { $output->writeln("ownCloud is not installed - only a limited number of commands are available"); } $input = new ArgvInput(); if ($input->getFirstArgument() !== 'check') { $errors = \OC_Util::checkServer(\OC::$server->getConfig()); if (!empty($errors)) { foreach ($errors as $error) { $output->writeln((string) $error['error']); $output->writeln((string) $error['hint']); $output->writeln(''); } throw new \Exception("Environment not properly prepared."); } } }
/** * Checks whether a domain is considered as trusted from the list * of trusted domains. If no trusted domains have been configured, returns * true. * This is used to prevent Host Header Poisoning. * @param string $domainWithPort * @return bool true if the given domain is trusted or if no trusted domains * have been configured */ public function isTrustedDomain($domainWithPort) { $domain = $this->getDomainWithoutPort($domainWithPort); // Read trusted domains from config $trustedList = $this->config->getSystemValue('trusted_domains', []); if (!is_array($trustedList)) { return false; } // Always allow access from localhost if (preg_match(Request::REGEX_LOCALHOST, $domain) === 1) { return true; } return in_array($domain, $trustedList, true); }
/** * Get all available categories * @return array */ public function listCategories() { $categories = array(array('id' => 0, 'displayName' => (string) $this->l10n->t('Enabled')), array('id' => 1, 'displayName' => (string) $this->l10n->t('Not enabled'))); if ($this->config->getSystemValue('appstoreenabled', true)) { $categories[] = array('id' => 2, 'displayName' => (string) $this->l10n->t('Recommended')); // apps from external repo via OCS $ocs = \OC_OCSClient::getCategories(); foreach ($ocs as $k => $v) { $categories[] = array('id' => $k, 'displayName' => str_replace('ownCloud ', '', $v)); } } $categories['status'] = 'success'; return $categories; }
/** * register hooks */ public function registerHooks() { if (!$this->config->getSystemValue('maintenance', false)) { $container = $this->getContainer(); $server = $container->getServer(); // Register our hooks and fire them. $hookManager = new HookManager(); $hookManager->registerHook([new UserHooks($container->query('KeyManager'), $server->getUserManager(), $server->getLogger(), $container->query('UserSetup'), $server->getUserSession(), $container->query('Util'), $container->query('Session'), $container->query('Crypt'), $container->query('Recovery'))]); $hookManager->fireHooks(); } else { // Logout user if we are in maintenance to force re-login $this->getContainer()->getServer()->getUserSession()->logout(); } }
/** * Detects all unsupported clients and throws a \Sabre\DAV\Exception\Forbidden * exception which will result in a 403 to them. * @param RequestInterface $request * @throws \Sabre\DAV\Exception\Forbidden If the client version is not supported */ public function beforeHandler(RequestInterface $request) { $userAgent = $request->getHeader('User-Agent'); if ($userAgent === null) { return; } $minimumSupportedDesktopVersion = $this->config->getSystemValue('minimum.supported.desktop.version', '1.7.0'); // Match on the mirall version which is in scheme "Mozilla/5.0 (%1) mirall/%2" or // "mirall/%1" for older releases preg_match("/(?:mirall\\/)([\\d.]+)/i", $userAgent, $versionMatches); if (isset($versionMatches[1]) && version_compare($versionMatches[1], $minimumSupportedDesktopVersion) === -1) { throw new \Sabre\DAV\Exception\Forbidden('Unsupported client version.'); } }