/** * @NoAdminRequired * * @param int $id * @return DataResponse */ public function get($id) { // save the last viewed note $this->settings->setUserValue($this->userId, $this->appName, 'notesLastViewedNote', $id); return $this->respond(function () use($id) { return $this->notesService->get($id, $this->userId); }); }
/** * @param $enabled * @return bool */ public function setRecoveryForUser($enabled) { $value = $enabled ? '1' : '0'; try { $this->config->setUserValue($this->user->getUID(), 'encryption', 'recoveryEnabled', $value); return true; } catch (PreConditionNotMetException $e) { return false; } }
/** * Propagate the etag changes for all shares marked as dirty and mark the shares as clean * * @param array $shares the shares for the users * @param int $time */ public function propagateDirtyMountPoints(array $shares, $time = null) { if ($time === null) { $time = microtime(true); } $dirtyShares = $this->getDirtyShares($shares); foreach ($dirtyShares as $share) { $this->changePropagator->addChange($share['file_target']); } if (count($dirtyShares)) { $this->config->setUserValue($this->userId, 'files_sharing', 'last_propagate', $time); $this->changePropagator->propagateChanges(floor($time)); } }
/** * Propagate the etag changes for all mountpoints marked as dirty and mark the mountpoints as clean * * @param int $time */ public function propagateDirtyMountPoints($time = null) { if ($time === null) { $time = time(); } $mountPoints = $this->getDirtyMountPoints(); foreach ($mountPoints as $mountPoint) { $this->changePropagator->addChange($mountPoint); $this->config->setUserValue($this->user->getUID(), 'files_external', $mountPoint, $time); } if (count($mountPoints)) { $this->changePropagator->propagateChanges($time); } }
/** * set a new view * * @param string $view * @return JSONResponse * * @NoAdminRequired */ public function setView($view) { if (!$this->isViewAllowed($view)) { return new JSONResponse([], Http::STATUS_UNPROCESSABLE_ENTITY); } $userId = $this->userSession->getUser()->getUID(); $app = $this->appName; try { $this->config->setUserValue($userId, $app, 'currentView', $view); } catch (\Exception $e) { return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR); } return new JSONResponse(); }
/** * set a config value * * @param string $value * @return JSONResponse * * @NoAdminRequired * @NoCSRFRequired */ public function setValue($value) { try { $userId = $this->user->getUID(); $app = $this->appName; $info = $this->getInfoFromRoute(); if (isset($info['options']) && !in_array($value, $info['options'])) { throw new Exception('Value not supported', HTTP::STATUS_UNPROCESSABLE_ENTITY); } $this->config->setUserValue($userId, $app, $info['configKey'], $value); return new JSONResponse(['message' => 'Value stored successfully'], HTTP::STATUS_OK); } catch (\Exception $ex) { return $this->handleException($ex); } }
/** * @param string $user * @throws \Exception */ protected function sendEmail($user) { if (!$this->userManager->userExists($user)) { throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.')); } $email = $this->config->getUserValue($user, 'settings', 'email'); if (empty($email)) { throw new \Exception($this->l10n->t('Couldn\'t send reset email because there is no ' . 'email address for this username. Please ' . 'contact your administrator.')); } $token = $this->secureRandom->getMediumStrengthGenerator()->generate(21, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER); $this->config->setUserValue($user, 'owncloud', 'lostpassword', $token); $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token)); $tmpl = new \OC_Template('core/lostpassword', 'email'); $tmpl->assign('link', $link, false); $msg = $tmpl->fetchPage(); try { $message = $this->mailer->createMessage(); $message->setTo([$email => $user]); $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()])); $message->setPlainBody($msg); $message->setFrom([$this->from => $this->defaults->getName()]); $this->mailer->send($message); } catch (\Exception $e) { throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please contact your administrator.')); } }
/** * 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']); } }
/** * Set the mail address of a user * * @NoAdminRequired * @NoSubadminRequired * * @param string $id * @param string $mailAddress * @return DataResponse */ public function setMailAddress($id, $mailAddress) { $userId = $this->userSession->getUser()->getUID(); $user = $this->userManager->get($id); if ($userId !== $id && !$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Forbidden'))), Http::STATUS_FORBIDDEN); } if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Invalid mail address'))), Http::STATUS_UNPROCESSABLE_ENTITY); } if (!$user) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Invalid user'))), Http::STATUS_UNPROCESSABLE_ENTITY); } // this is the only permission a backend provides and is also used // for the permission of setting a email address if (!$user->canChangeDisplayName()) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Unable to change mail address'))), Http::STATUS_FORBIDDEN); } // delete user value if email address is empty if ($mailAddress === '') { $this->config->deleteUserValue($id, 'settings', 'email'); } else { $this->config->setUserValue($id, 'settings', 'email', $mailAddress); } return new DataResponse(array('status' => 'success', 'data' => array('username' => $id, 'mailAddress' => $mailAddress, 'message' => (string) $this->l10n->t('Email saved'))), Http::STATUS_OK); }
protected function sendEmail($user, $proceed) { if ($this->isDataEncrypted && !$proceed) { throw new EncryptedDataException(); } if (!$this->userManager->userExists($user)) { throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure ' . 'your username is correct.')); } $token = hash('sha256', \OC_Util::generateRandomBytes(30)); // Hash the token again to prevent timing attacks $this->config->setUserValue($user, 'owncloud', 'lostpassword', hash('sha256', $token)); $email = $this->config->getUserValue($user, 'settings', 'email'); if (empty($email)) { throw new \Exception($this->l10n->t('Couldn\'t send reset email because there is no ' . 'email address for this username. Please ' . 'contact your administrator.')); } $link = $this->getLink('core.lost.resetform', $user, $token); $tmpl = new \OC_Template('core/lostpassword', 'email'); $tmpl->assign('link', $link, false); $msg = $tmpl->fetchPage(); try { // FIXME: should be added to the container and injected in here \OC_Mail::send($email, $user, $this->l10n->t('%s password reset', array($this->defaults->getName())), $msg, $this->from, $this->defaults->getName()); } catch (\Exception $e) { throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please contact your administrator.')); } }
/** * @NoAdminRequired * * @param string $key * @param string $value * @return JSONResponse */ public function set($key = '', $value = '') { $response = new JSONResponse(); if ($key === '' || $value === '') { $response->setStatus(Http::STATUS_PRECONDITION_FAILED); return $response; } try { $this->config->setUserValue($this->userId, $this->appName, $key, $value); $response->setData(['key' => $key, 'value' => $value]); return $response; } catch (\Exception $e) { $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR); return $response; } }
/** * @param IUser $user * @return array|null */ private function getMultiBucketObjectStoreConfig(IUser $user) { $config = $this->config->getSystemValue('objectstore_multibucket'); if (!is_array($config)) { return null; } // sanity checks if (empty($config['class'])) { \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR); } if (!isset($config['arguments'])) { $config['arguments'] = []; } $config['arguments']['user'] = $user; $bucket = $this->config->getUserValue($user->getUID(), 'homeobjectstore', 'bucket', null); if ($bucket === null) { /* * Use any provided bucket argument as prefix * and add the mapping from username => bucket */ if (!isset($config['arguments']['bucket'])) { $config['arguments']['bucket'] = ''; } $mapper = new \OC\Files\ObjectStore\Mapper($user); $config['arguments']['bucket'] .= $mapper->getBucket(); $this->config->setUserValue($user->getUID(), 'homeobjectstore', 'bucket', $config['arguments']['bucket']); } else { $config['arguments']['bucket'] = $bucket; } // instantiate object store implementation $config['arguments']['objectstore'] = new $config['class']($config['arguments']); return $config; }
/** * set the enabled status for the user * * @param bool $enabled */ public function setEnabled($enabled) { $this->enabled = $enabled; if ($this->config) { $enabled = $enabled ? 'true' : 'false'; $this->config->setUserValue($this->uid, 'core', 'enabled', $enabled); } }
/** * sets a value in the preferences * @param string $user user * @param string $app app * @param string $key key * @param string $value value * @param string $preCondition only set value if the key had a specific value before * @return bool true if value was set, otherwise false * @deprecated use setUserValue of \OCP\IConfig instead * * Adds a value to the preferences. If the key did not exist before, it * will be added automagically. */ public function setValue($user, $app, $key, $value, $preCondition = null) { try { $this->config->setUserValue($user, $app, $key, $value, $preCondition); return true; } catch (PreConditionNotMetException $e) { return false; } }
/** * set the users' quota * * @param string $quota * @return void * @since 9.0.0 */ public function setQuota($quota) { if ($quota !== 'none' and $quota !== 'default') { $quota = OC_Helper::computerFileSize($quota); $quota = OC_Helper::humanFileSize($quota); } $this->config->setUserValue($this->uid, 'files', 'quota', $quota); $this->triggerChange('quota', $quota); }
/** * checks whether a user is still existing in LDAP * @param string[] $user */ private function checkUser($user) { if ($this->userBackend->userExistsOnLDAP($user['name'])) { //still available, all good return; } // TODO FIXME consolidate next line in DeletedUsersIndex // (impractical now, because of class dependencies) $this->ocConfig->setUserValue($user['name'], 'user_ldap', 'isDeleted', '1'); }
protected function execute(InputInterface $input, OutputInterface $output) { try { $uid = $input->getArgument('ocName'); $this->isAllowed($input->getOption('force')); $this->confirmUserIsMapped($uid); $exists = $this->backend->userExistsOnLDAP($uid); if ($exists === true) { $output->writeln('The user is still available on LDAP.'); return; } // TODO FIXME consolidate next line in DeletedUsersIndex // (impractical now, because of class dependencies) $this->config->setUserValue($uid, 'user_ldap', 'isDeleted', '1'); $output->writeln('The user does not exists on LDAP anymore.'); $output->writeln('Clean up the user\'s remnants by: ./occ user:delete "' . $uid . '"'); } catch (\Exception $e) { $output->writeln('<error>' . $e->getMessage() . '</error>'); } }
/** * Migrate personal storages configured by the current user */ public function migrateUser() { $userId = $this->userSession->getUser()->getUID(); $userVersion = $this->config->getUserValue($userId, 'files_external', 'config_version', '0.0.0'); if (version_compare($userVersion, '0.5.0', '<')) { $this->config->setUserValue($userId, 'files_external', 'config_version', '0.5.0'); $legacyService = new UserLegacyStoragesService($this->backendService, $this->userSession); $storageService = new UserStoragesService($this->backendService, $this->dbConfig, $this->userSession); $this->migrate($legacyService, $storageService); } }
/** * @param string $value * @return bool */ public function setRecoveryForUser($value) { try { $this->config->setUserValue($this->user->getUID(), 'encryption', 'recoveryEnabled', $value); if ($value === '1') { $this->addRecoveryKeys('/' . $this->user->getUID() . '/files/'); } else { $this->removeRecoveryKeys('/' . $this->user->getUID() . '/files/'); } return true; } catch (PreConditionNotMetException $e) { return false; } }
/** * get the user's home directory * @param string $uid the username * @return string|bool */ public function getHome($uid) { // user Exists check required as it is not done in user proxy! if(!$this->userExists($uid)) { return false; } if(isset($this->homesToKill[$uid]) && !empty($this->homesToKill[$uid])) { //a deleted user who needs some clean up return $this->homesToKill[$uid]; } $cacheKey = 'getHome'.$uid; if($this->access->connection->isCached($cacheKey)) { return $this->access->connection->getFromCache($cacheKey); } if(strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0) { $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:')); $homedir = $this->access->readAttribute( $this->access->username2dn($uid), $attr); if($homedir && isset($homedir[0])) { $path = $homedir[0]; //if attribute's value is an absolute path take this, otherwise append it to data dir //check for / at the beginning or pattern c:\ resp. c:/ if( '/' === $path[0] || (3 < strlen($path) && ctype_alpha($path[0]) && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2])) ) { $homedir = $path; } else { $homedir = $this->ocConfig->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data' ) . '/' . $homedir[0]; } $this->access->connection->writeToCache($cacheKey, $homedir); //we need it to store it in the DB as well in case a user gets //deleted so we can clean up afterwards $this->ocConfig->setUserValue( $uid, 'user_ldap', 'homePath', $homedir ); //TODO: if home directory changes, the old one needs to be removed. return $homedir; } } //false will apply default behaviour as defined and done by OC_User $this->access->connection->writeToCache($cacheKey, false); $this->ocConfig->setUserValue($uid, 'user_ldap', 'homePath', ''); return false; }
/** * @NoAdminRequired * * @param string $enable 'true' if the feed is enabled * @return DataResponse */ public function feed($enable) { $token = $tokenUrl = ''; if ($enable === 'true') { $conflicts = true; // Check for collisions while (!empty($conflicts)) { $token = $this->random->generate(30); $conflicts = $this->config->getUsersForUserValue('activity', 'rsstoken', $token); } $tokenUrl = $this->urlGenerator->linkToRouteAbsolute('activity.Feed.show', ['token' => $token]); } $this->config->setUserValue($this->user, 'activity', 'rsstoken', $token); return new DataResponse(array('data' => array('message' => (string) $this->l10n->t('Your settings have been updated.'), 'rsslink' => $tokenUrl))); }
/** * fetches the quota from LDAP and stores it as ownCloud user value * @param string $valueFromLDAP the quota attribute's value can be passed, * to save the readAttribute request * @return null */ public function updateQuota($valueFromLDAP = null) { if ($this->wasRefreshed('quota')) { return; } //can be null $quotaDefault = $this->connection->ldapQuotaDefault; $quota = !is_null($valueFromLDAP) ? $valueFromLDAP : $quotaDefault !== '' ? $quotaDefault : null; if (is_null($valueFromLDAP)) { $quotaAttribute = $this->connection->ldapQuotaAttribute; if (!empty($quotaAttribute)) { $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute); if ($aQuota && count($aQuota) > 0) { $quota = $aQuota[0]; } } } if (!is_null($quota)) { $this->config->setUserValue($this->uid, 'files', 'quota', $quota); } }
/** * @brief fetches the quota from LDAP and stores it as ownCloud user value * @return null */ public function updateQuota() { if ($this->wasRefreshed('quota')) { return; } $quota = null; $quotaDefault = $this->connection->ldapQuotaDefault; $quotaAttribute = $this->connection->ldapQuotaAttribute; if (!empty($quotaDefault)) { $quota = $quotaDefault; } if (!empty($quotaAttribute)) { $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute); if ($aQuota && count($aQuota) > 0) { $quota = $aQuota[0]; } } if (!is_null($quota)) { $this->config->setUserValue($this->uid, 'files', 'quota', $quota); } }
/** * Set the mail address of a user * * @NoAdminRequired * @NoSubadminRequired * * @param string $id * @param string $mailAddress * @return DataResponse * * TODO: Tidy up and write unit tests - code is mainly static method calls */ public function setMailAddress($id, $mailAddress) { // FIXME: Remove this static function call at some point… if ($this->userSession->getUser()->getUID() !== $id && !$this->isAdmin && !\OC_SubAdmin::isUserAccessible($this->userSession->getUser()->getUID(), $id)) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Forbidden'))), Http::STATUS_FORBIDDEN); } if ($mailAddress !== '' && !$this->mail->validateAddress($mailAddress)) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Invalid mail address'))), Http::STATUS_UNPROCESSABLE_ENTITY); } $user = $this->userManager->get($id); if (!$user) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Invalid user'))), Http::STATUS_UNPROCESSABLE_ENTITY); } // this is the only permission a backend provides and is also used // for the permission of setting a email address if (!$user->canChangeDisplayName()) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Unable to change mail address'))), Http::STATUS_FORBIDDEN); } $this->config->setUserValue($id, 'settings', 'email', $mailAddress); return new DataResponse(array('status' => 'success', 'data' => array('username' => $id, 'mailAddress' => $mailAddress, 'message' => (string) $this->l10n->t('Email saved'))), Http::STATUS_OK); }
/** * Find the best language * * @param string|null $app App id or null for core * @return string language If nothing works it returns 'en' */ public function findLanguage($app = null) { if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) { return $this->requestLanguage; } /** * At this point ownCloud might not yet be installed and thus the lookup * in the preferences table might fail. For this reason we need to check * whether the instance has already been installed * * @link https://github.com/owncloud/core/issues/21955 */ if ($this->config->getSystemValue('installed', false)) { $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null; if (!is_null($userId)) { $userLang = $this->config->getUserValue($userId, 'core', 'lang', null); } else { $userLang = null; } } else { $userId = null; $userLang = null; } if ($userLang) { $this->requestLanguage = $userLang; if ($this->languageExists($app, $userLang)) { return $userLang; } } $defaultLanguage = $this->config->getSystemValue('default_language', false); if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) { return $defaultLanguage; } $lang = $this->setLanguageFromRequest($app); if ($userId !== null && $app === null && !$userLang) { $this->config->setUserValue($userId, 'core', 'lang', $lang); } return $lang; }
/** * Find the best language * * @param string|null $app App id or null for core * @return string language If nothing works it returns 'en' */ public function findLanguage($app = null) { if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) { return $this->requestLanguage; } $userId = \OC_User::getUser(); // FIXME not available in non-static? $userLang = $userId !== false ? $this->config->getUserValue($userId, 'core', 'lang') : null; if ($userLang) { $this->requestLanguage = $userLang; if ($this->languageExists($app, $userLang)) { return $userLang; } } $defaultLanguage = $this->config->getSystemValue('default_language', false); if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) { return $defaultLanguage; } $lang = $this->setLanguageFromRequest($app); if ($userId !== false && $app === null && !$userLang) { $this->config->setUserValue($userId, 'core', 'lang', $lang); } return $lang; }
/** * update database */ public function updateDB() { // 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->getQueryBuilder(); $oldAppValues->select('*')->from('*PREFIX*appconfig')->where($oldAppValues->expr()->eq('appid', $oldAppValues->createParameter('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->getQueryBuilder(); $oldPreferences->select('*')->from('*PREFIX*preferences')->where($oldPreferences->expr()->eq('appid', $oldPreferences->createParameter('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']); } }
/** * remove the Delete-flag from the user. */ public function unmark() { $this->config->setUserValue($this->ocName, 'user_ldap', 'isDeleted', '0'); }
/** * Stores a key-value pair in relation to this user * * @param string $key * @param string $value */ private function store($key, $value) { $this->config->setUserValue($this->uid, 'user_ldap', $key, $value); }
/** * @NoAdminRequired * * @param string $markdown * @return DataResponse */ public function setConfig($markdown) { $this->settings->setUserValue($this->userId, $this->appName, 'notesMarkdown', $markdown); return new DataResponse(); }