migrate therinaldos.com data
Build & Deploy to DigitalOcean Space / build (push) Failing after 2m38s

This commit is contained in:
2024-05-05 15:50:45 -04:00
commit ef1ff240d4
23182 changed files with 3801898 additions and 0 deletions
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
/**
* @copyright 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Richard Steinmetz <richard@steinmetz.cloud>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OC\User;
use JsonException;
use OCA\DAV\AppInfo\Application;
use OCA\DAV\CalDAV\TimezoneService;
use OCA\DAV\Service\AbsenceService;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\IConfig;
use OCP\IUser;
use OCP\User\IAvailabilityCoordinator;
use OCP\User\IOutOfOfficeData;
use Psr\Log\LoggerInterface;
class AvailabilityCoordinator implements IAvailabilityCoordinator {
private ICache $cache;
public function __construct(
ICacheFactory $cacheFactory,
private IConfig $config,
private AbsenceService $absenceService,
private LoggerInterface $logger,
private TimezoneService $timezoneService,
) {
$this->cache = $cacheFactory->createLocal('OutOfOfficeData');
}
public function isEnabled(): bool {
return $this->config->getAppValue(Application::APP_ID, 'hide_absence_settings', 'no') === 'no';
}
private function getCachedOutOfOfficeData(IUser $user): ?OutOfOfficeData {
$cachedString = $this->cache->get($user->getUID());
if ($cachedString === null) {
return null;
}
try {
$cachedData = json_decode($cachedString, true, 10, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
$this->logger->error('Failed to deserialize cached out-of-office data: ' . $e->getMessage(), [
'exception' => $e,
'json' => $cachedString,
]);
return null;
}
return new OutOfOfficeData(
$cachedData['id'],
$user,
$cachedData['startDate'],
$cachedData['endDate'],
$cachedData['shortMessage'],
$cachedData['message'],
);
}
private function setCachedOutOfOfficeData(IOutOfOfficeData $data): void {
try {
$cachedString = json_encode([
'id' => $data->getId(),
'startDate' => $data->getStartDate(),
'endDate' => $data->getEndDate(),
'shortMessage' => $data->getShortMessage(),
'message' => $data->getMessage(),
], JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
$this->logger->error('Failed to serialize out-of-office data: ' . $e->getMessage(), [
'exception' => $e,
]);
return;
}
$this->cache->set($data->getUser()->getUID(), $cachedString, 300);
}
public function getCurrentOutOfOfficeData(IUser $user): ?IOutOfOfficeData {
$timezone = $this->getCachedTimezone($user->getUID());
if ($timezone === null) {
$timezone = $this->timezoneService->getUserTimezone($user->getUID()) ?? $this->timezoneService->getDefaultTimezone();
$this->setCachedTimezone($user->getUID(), $timezone);
}
$data = $this->getCachedOutOfOfficeData($user);
if ($data === null) {
$absenceData = $this->absenceService->getAbsence($user->getUID());
if ($absenceData === null) {
return null;
}
$data = $absenceData->toOutOufOfficeData($user, $timezone);
}
$this->setCachedOutOfOfficeData($data);
return $data;
}
private function getCachedTimezone(string $userId): ?string {
return $this->cache->get($userId . '_timezone') ?? null;
}
private function setCachedTimezone(string $userId, string $timezone): void {
$this->cache->set($userId . '_timezone', $timezone, 3600);
}
public function clearCache(string $userId): void {
$this->cache->set($userId, null, 300);
$this->cache->set($userId . '_timezone', null, 3600);
}
public function isInEffect(IOutOfOfficeData $data): bool {
return $this->absenceService->isInEffect($data);
}
}
+166
View File
@@ -0,0 +1,166 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Roeland Jago Douma <roeland@famdouma.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\User;
use OCP\UserInterface;
/**
* Abstract base class for user management. Provides methods for querying backend
* capabilities.
*/
abstract class Backend implements UserInterface {
/**
* error code for functions not provided by the user backend
*/
public const NOT_IMPLEMENTED = -501;
/**
* actions that user backends can define
*/
public const CREATE_USER = 1; // 1 << 0
public const SET_PASSWORD = 16; // 1 << 4
public const CHECK_PASSWORD = 256; // 1 << 8
public const GET_HOME = 4096; // 1 << 12
public const GET_DISPLAYNAME = 65536; // 1 << 16
public const SET_DISPLAYNAME = 1048576; // 1 << 20
public const PROVIDE_AVATAR = 16777216; // 1 << 24
public const COUNT_USERS = 268435456; // 1 << 28
protected $possibleActions = [
self::CREATE_USER => 'createUser',
self::SET_PASSWORD => 'setPassword',
self::CHECK_PASSWORD => 'checkPassword',
self::GET_HOME => 'getHome',
self::GET_DISPLAYNAME => 'getDisplayName',
self::SET_DISPLAYNAME => 'setDisplayName',
self::PROVIDE_AVATAR => 'canChangeAvatar',
self::COUNT_USERS => 'countUsers',
];
/**
* Get all supported actions
* @return int bitwise-or'ed actions
*
* Returns the supported actions as int to be
* compared with self::CREATE_USER etc.
*/
public function getSupportedActions() {
$actions = 0;
foreach ($this->possibleActions as $action => $methodName) {
if (method_exists($this, $methodName)) {
$actions |= $action;
}
}
return $actions;
}
/**
* Check if backend implements actions
* @param int $actions bitwise-or'ed actions
* @return boolean
*
* Returns the supported actions as int to be
* compared with self::CREATE_USER etc.
*/
public function implementsActions($actions) {
return (bool)($this->getSupportedActions() & $actions);
}
/**
* delete a user
* @param string $uid The username of the user to delete
* @return bool
*
* Deletes a user
*/
public function deleteUser($uid) {
return false;
}
/**
* Get a list of all users
*
* @param string $search
* @param null|int $limit
* @param null|int $offset
* @return string[] an array of all uids
*/
public function getUsers($search = '', $limit = null, $offset = null) {
return [];
}
/**
* check if a user exists
* @param string $uid the username
* @return boolean
*/
public function userExists($uid) {
return false;
}
/**
* get the user's home directory
* @param string $uid the username
* @return boolean
*/
public function getHome($uid) {
return false;
}
/**
* get display name of the user
* @param string $uid user ID of the user
* @return string display name
*/
public function getDisplayName($uid) {
return $uid;
}
/**
* Get a list of all display names and user ids.
*
* @param string $search
* @param int|null $limit
* @param int|null $offset
* @return array an array of all displayNames (value) and the corresponding uids (key)
*/
public function getDisplayNames($search = '', $limit = null, $offset = null) {
$displayNames = [];
$users = $this->getUsers($search, $limit, $offset);
foreach ($users as $user) {
$displayNames[$user] = $user;
}
return $displayNames;
}
/**
* Check if a user list is available or not
* @return boolean if users can be listed or not
*/
public function hasUserListings() {
return false;
}
}
+535
View File
@@ -0,0 +1,535 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author adrien <adrien.waksberg@believedigital.com>
* @author Aldo "xoen" Giambelluca <xoen@xoen.org>
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bart Visscher <bartv@thisnet.nl>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Daniel Calviño Sánchez <danxuliu@gmail.com>
* @author fabian <fabian@web2.0-apps.de>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Jakob Sack <mail@jakobsack.de>
* @author Joas Schilling <coding@schilljs.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Loki3000 <github@labcms.ru>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author nishiki <nishiki@yaegashi.fr>
* @author Robin Appelman <robin@icewind.nl>
* @author Robin McCorkell <robin@mccorkell.me.uk>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Vincent Petry <vincent@nextcloud.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\User;
use OCP\AppFramework\Db\TTransactional;
use OCP\Cache\CappedMemoryCache;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IDBConnection;
use OCP\Security\Events\ValidatePasswordPolicyEvent;
use OCP\User\Backend\ABackend;
use OCP\User\Backend\ICheckPasswordBackend;
use OCP\User\Backend\ICountUsersBackend;
use OCP\User\Backend\ICreateUserBackend;
use OCP\User\Backend\IGetDisplayNameBackend;
use OCP\User\Backend\IGetHomeBackend;
use OCP\User\Backend\IGetRealUIDBackend;
use OCP\User\Backend\ISearchKnownUsersBackend;
use OCP\User\Backend\ISetDisplayNameBackend;
use OCP\User\Backend\ISetPasswordBackend;
/**
* Class for user management in a SQL Database (e.g. MySQL, SQLite)
*/
class Database extends ABackend implements
ICreateUserBackend,
ISetPasswordBackend,
ISetDisplayNameBackend,
IGetDisplayNameBackend,
ICheckPasswordBackend,
IGetHomeBackend,
ICountUsersBackend,
ISearchKnownUsersBackend,
IGetRealUIDBackend {
/** @var CappedMemoryCache */
private $cache;
/** @var IEventDispatcher */
private $eventDispatcher;
/** @var IDBConnection */
private $dbConn;
/** @var string */
private $table;
use TTransactional;
/**
* \OC\User\Database constructor.
*
* @param IEventDispatcher $eventDispatcher
* @param string $table
*/
public function __construct($eventDispatcher = null, $table = 'users') {
$this->cache = new CappedMemoryCache();
$this->table = $table;
$this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OCP\Server::get(IEventDispatcher::class);
}
/**
* FIXME: This function should not be required!
*/
private function fixDI() {
if ($this->dbConn === null) {
$this->dbConn = \OC::$server->getDatabaseConnection();
}
}
/**
* Create a new user
*
* @param string $uid The username of the user to create
* @param string $password The password of the new user
* @return bool
*
* Creates a new user. Basic checking of username is done in OC_User
* itself, not in its subclasses.
*/
public function createUser(string $uid, string $password): bool {
$this->fixDI();
if (!$this->userExists($uid)) {
$this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
return $this->atomic(function () use ($uid, $password) {
$qb = $this->dbConn->getQueryBuilder();
$qb->insert($this->table)
->values([
'uid' => $qb->createNamedParameter($uid),
'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
]);
$result = $qb->executeStatement();
// Clear cache
unset($this->cache[$uid]);
// Repopulate the cache
$this->loadUser($uid);
return (bool) $result;
}, $this->dbConn);
}
return false;
}
/**
* delete a user
*
* @param string $uid The username of the user to delete
* @return bool
*
* Deletes a user
*/
public function deleteUser($uid) {
$this->fixDI();
// Delete user-group-relation
$query = $this->dbConn->getQueryBuilder();
$query->delete($this->table)
->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
$result = $query->execute();
if (isset($this->cache[$uid])) {
unset($this->cache[$uid]);
}
return $result ? true : false;
}
private function updatePassword(string $uid, string $passwordHash): bool {
$query = $this->dbConn->getQueryBuilder();
$query->update($this->table)
->set('password', $query->createNamedParameter($passwordHash))
->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
$result = $query->execute();
return $result ? true : false;
}
/**
* Set password
*
* @param string $uid The username
* @param string $password The new password
* @return bool
*
* Change the password of a user
*/
public function setPassword(string $uid, string $password): bool {
$this->fixDI();
if ($this->userExists($uid)) {
$this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
$hasher = \OC::$server->getHasher();
$hashedPassword = $hasher->hash($password);
$return = $this->updatePassword($uid, $hashedPassword);
if ($return) {
$this->cache[$uid]['password'] = $hashedPassword;
}
return $return;
}
return false;
}
/**
* Set display name
*
* @param string $uid The username
* @param string $displayName The new display name
* @return bool
*
* @throws \InvalidArgumentException
*
* Change the display name of a user
*/
public function setDisplayName(string $uid, string $displayName): bool {
if (mb_strlen($displayName) > 64) {
throw new \InvalidArgumentException('Invalid displayname');
}
$this->fixDI();
if ($this->userExists($uid)) {
$query = $this->dbConn->getQueryBuilder();
$query->update($this->table)
->set('displayname', $query->createNamedParameter($displayName))
->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
$query->execute();
$this->cache[$uid]['displayname'] = $displayName;
return true;
}
return false;
}
/**
* get display name of the user
*
* @param string $uid user ID of the user
* @return string display name
*/
public function getDisplayName($uid): string {
$uid = (string)$uid;
$this->loadUser($uid);
return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
}
/**
* Get a list of all display names and user ids.
*
* @param string $search
* @param int|null $limit
* @param int|null $offset
* @return array an array of all displayNames (value) and the corresponding uids (key)
*/
public function getDisplayNames($search = '', $limit = null, $offset = null) {
$limit = $this->fixLimit($limit);
$this->fixDI();
$query = $this->dbConn->getQueryBuilder();
$query->select('uid', 'displayname')
->from($this->table, 'u')
->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
$query->expr()->eq('userid', 'uid'),
$query->expr()->eq('appid', $query->expr()->literal('settings')),
$query->expr()->eq('configkey', $query->expr()->literal('email')))
)
// sqlite doesn't like re-using a single named parameter here
->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
->orderBy($query->func()->lower('displayname'), 'ASC')
->addOrderBy('uid_lower', 'ASC')
->setMaxResults($limit)
->setFirstResult($offset);
$result = $query->executeQuery();
$displayNames = [];
while ($row = $result->fetch()) {
$displayNames[(string)$row['uid']] = (string)$row['displayname'];
}
return $displayNames;
}
/**
* @param string $searcher
* @param string $pattern
* @param int|null $limit
* @param int|null $offset
* @return array
* @since 21.0.1
*/
public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array {
$limit = $this->fixLimit($limit);
$this->fixDI();
$query = $this->dbConn->getQueryBuilder();
$query->select('u.uid', 'u.displayname')
->from($this->table, 'u')
->leftJoin('u', 'known_users', 'k', $query->expr()->andX(
$query->expr()->eq('k.known_user', 'u.uid'),
$query->expr()->eq('k.known_to', $query->createNamedParameter($searcher))
))
->where($query->expr()->eq('k.known_to', $query->createNamedParameter($searcher)))
->andWhere($query->expr()->orX(
$query->expr()->iLike('u.uid', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($pattern) . '%')),
$query->expr()->iLike('u.displayname', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($pattern) . '%'))
))
->orderBy('u.displayname', 'ASC')
->addOrderBy('u.uid_lower', 'ASC')
->setMaxResults($limit)
->setFirstResult($offset);
$result = $query->execute();
$displayNames = [];
while ($row = $result->fetch()) {
$displayNames[(string)$row['uid']] = (string)$row['displayname'];
}
return $displayNames;
}
/**
* Check if the password is correct
*
* @param string $loginName The loginname
* @param string $password The password
* @return string
*
* Check if the password is correct without logging in the user
* returns the user id or false
*/
public function checkPassword(string $loginName, string $password) {
$found = $this->loadUser($loginName);
if ($found && is_array($this->cache[$loginName])) {
$storedHash = $this->cache[$loginName]['password'];
$newHash = '';
if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
if (!empty($newHash)) {
$this->updatePassword($loginName, $newHash);
}
return (string)$this->cache[$loginName]['uid'];
}
}
return false;
}
/**
* Load an user in the cache
*
* @param string $uid the username
* @return boolean true if user was found, false otherwise
*/
private function loadUser($uid) {
$this->fixDI();
$uid = (string)$uid;
if (!isset($this->cache[$uid])) {
//guests $uid could be NULL or ''
if ($uid === '') {
$this->cache[$uid] = false;
return true;
}
$qb = $this->dbConn->getQueryBuilder();
$qb->select('uid', 'displayname', 'password')
->from($this->table)
->where(
$qb->expr()->eq(
'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
)
);
$result = $qb->execute();
$row = $result->fetch();
$result->closeCursor();
// "uid" is primary key, so there can only be a single result
if ($row !== false) {
$this->cache[$uid] = [
'uid' => (string)$row['uid'],
'displayname' => (string)$row['displayname'],
'password' => (string)$row['password'],
];
} else {
$this->cache[$uid] = false;
return false;
}
}
return true;
}
/**
* Get a list of all users
*
* @param string $search
* @param null|int $limit
* @param null|int $offset
* @return string[] an array of all uids
*/
public function getUsers($search = '', $limit = null, $offset = null) {
$limit = $this->fixLimit($limit);
$users = $this->getDisplayNames($search, $limit, $offset);
$userIds = array_map(function ($uid) {
return (string)$uid;
}, array_keys($users));
sort($userIds, SORT_STRING | SORT_FLAG_CASE);
return $userIds;
}
/**
* check if a user exists
*
* @param string $uid the username
* @return boolean
*/
public function userExists($uid) {
$this->loadUser($uid);
return $this->cache[$uid] !== false;
}
/**
* get the user's home directory
*
* @param string $uid the username
* @return string|false
*/
public function getHome(string $uid) {
if ($this->userExists($uid)) {
return \OC::$server->getConfig()->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
}
return false;
}
/**
* @return bool
*/
public function hasUserListings() {
return true;
}
/**
* counts the users in the database
*
* @return int|false
*/
public function countUsers() {
$this->fixDI();
$query = $this->dbConn->getQueryBuilder();
$query->select($query->func()->count('uid'))
->from($this->table);
$result = $query->executeQuery();
return $result->fetchOne();
}
/**
* returns the username for the given login name in the correct casing
*
* @param string $loginName
* @return string|false
*/
public function loginName2UserName($loginName) {
if ($this->userExists($loginName)) {
return $this->cache[$loginName]['uid'];
}
return false;
}
/**
* Backend name to be shown in user management
*
* @return string the name of the backend to be shown
*/
public function getBackendName() {
return 'Database';
}
public static function preLoginNameUsedAsUserName($param) {
if (!isset($param['uid'])) {
throw new \Exception('key uid is expected to be set in $param');
}
$backends = \OC::$server->getUserManager()->getBackends();
foreach ($backends as $backend) {
if ($backend instanceof Database) {
/** @var \OC\User\Database $backend */
$uid = $backend->loginName2UserName($param['uid']);
if ($uid !== false) {
$param['uid'] = $uid;
return;
}
}
}
}
public function getRealUID(string $uid): string {
if (!$this->userExists($uid)) {
throw new \RuntimeException($uid . ' does not exist');
}
return $this->cache[$uid]['uid'];
}
private function fixLimit($limit) {
if (is_int($limit) && $limit >= 0) {
return $limit;
}
return null;
}
}
@@ -0,0 +1,91 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright 2022 Carl Schwan <carl@carlschwan.eu>
* @license AGPL-3.0-or-later
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\User;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\IUserManager;
use OCP\User\Events\UserChangedEvent;
use OCP\User\Events\UserDeletedEvent;
/**
* Class that cache the relation UserId -> Display name
*
* This saves fetching the user from a user backend and later on fetching
* their preferences. It's generally not an issue if this data is slightly
* outdated.
*/
class DisplayNameCache implements IEventListener {
private array $cache = [];
private ICache $memCache;
private IUserManager $userManager;
public function __construct(ICacheFactory $cacheFactory, IUserManager $userManager) {
$this->memCache = $cacheFactory->createDistributed('displayNameMappingCache');
$this->userManager = $userManager;
}
public function getDisplayName(string $userId): ?string {
if (isset($this->cache[$userId])) {
return $this->cache[$userId];
}
$displayName = $this->memCache->get($userId);
if ($displayName) {
$this->cache[$userId] = $displayName;
return $displayName;
}
$user = $this->userManager->get($userId);
if ($user) {
$displayName = $user->getDisplayName();
} else {
$displayName = null;
}
$this->cache[$userId] = $displayName;
$this->memCache->set($userId, $displayName, 60 * 10); // 10 minutes
return $displayName;
}
public function clear(): void {
$this->cache = [];
$this->memCache->clear();
}
public function handle(Event $event): void {
if ($event instanceof UserChangedEvent && $event->getFeature() === 'displayName') {
$userId = $event->getUser()->getUID();
$newDisplayName = $event->getValue();
$this->cache[$userId] = $newDisplayName;
$this->memCache->set($userId, $newDisplayName, 60 * 10); // 10 minutes
}
if ($event instanceof UserDeletedEvent) {
$userId = $event->getUser()->getUID();
unset($this->cache[$userId]);
$this->memCache->remove($userId);
}
}
}
+170
View File
@@ -0,0 +1,170 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Robin Appelman <robin@icewind.nl>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\User;
use OCP\IUser;
use OCP\IUserManager;
use OCP\UserInterface;
class LazyUser implements IUser {
private ?IUser $user = null;
private string $uid;
private ?string $displayName;
private IUserManager $userManager;
private ?UserInterface $backend;
public function __construct(string $uid, IUserManager $userManager, ?string $displayName = null, ?UserInterface $backend = null) {
$this->uid = $uid;
$this->userManager = $userManager;
$this->displayName = $displayName;
$this->backend = $backend;
}
private function getUser(): IUser {
if ($this->user === null) {
if ($this->backend) {
/** @var \OC\User\Manager $manager */
$manager = $this->userManager;
$this->user = $manager->getUserObject($this->uid, $this->backend);
} else {
$this->user = $this->userManager->get($this->uid);
}
}
/** @var IUser */
$user = $this->user;
return $user;
}
public function getUID() {
return $this->uid;
}
public function getDisplayName() {
if ($this->displayName) {
return $this->displayName;
}
return $this->userManager->getDisplayName($this->uid) ?? $this->uid;
}
public function setDisplayName($displayName) {
return $this->getUser()->setDisplayName($displayName);
}
public function getLastLogin() {
return $this->getUser()->getLastLogin();
}
public function updateLastLoginTimestamp() {
return $this->getUser()->updateLastLoginTimestamp();
}
public function delete() {
return $this->getUser()->delete();
}
public function setPassword($password, $recoveryPassword = null) {
return $this->getUser()->setPassword($password, $recoveryPassword);
}
public function getHome() {
return $this->getUser()->getHome();
}
public function getBackendClassName() {
return $this->getUser()->getBackendClassName();
}
public function getBackend(): ?UserInterface {
return $this->getUser()->getBackend();
}
public function canChangeAvatar() {
return $this->getUser()->canChangeAvatar();
}
public function canChangePassword() {
return $this->getUser()->canChangePassword();
}
public function canChangeDisplayName() {
return $this->getUser()->canChangeDisplayName();
}
public function isEnabled() {
return $this->getUser()->isEnabled();
}
public function setEnabled(bool $enabled = true) {
return $this->getUser()->setEnabled($enabled);
}
public function getEMailAddress() {
return $this->getUser()->getEMailAddress();
}
public function getSystemEMailAddress(): ?string {
return $this->getUser()->getSystemEMailAddress();
}
public function getPrimaryEMailAddress(): ?string {
return $this->getUser()->getPrimaryEMailAddress();
}
public function getAvatarImage($size) {
return $this->getUser()->getAvatarImage($size);
}
public function getCloudId() {
return $this->getUser()->getCloudId();
}
public function setEMailAddress($mailAddress) {
$this->getUser()->setEMailAddress($mailAddress);
}
public function setSystemEMailAddress(string $mailAddress): void {
$this->getUser()->setSystemEMailAddress($mailAddress);
}
public function setPrimaryEMailAddress(string $mailAddress): void {
$this->getUser()->setPrimaryEMailAddress($mailAddress);
}
public function getQuota() {
return $this->getUser()->getQuota();
}
public function setQuota($quota) {
$this->getUser()->setQuota($quota);
}
public function getManagerUids(): array {
return $this->getUser()->getManagerUids();
}
public function setManagerUids(array $uids): void {
$this->getUser()->setManagerUids($uids);
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Carl Schwan <carl@carlschwan.eu>
*
* @license AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\User\Listeners;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Files\NotFoundException;
use OCP\IAvatarManager;
use OCP\User\Events\BeforeUserDeletedEvent;
use Psr\Log\LoggerInterface;
/**
* @template-implements IEventListener<BeforeUserDeletedEvent>
*/
class BeforeUserDeletedListener implements IEventListener {
private IAvatarManager $avatarManager;
private LoggerInterface $logger;
public function __construct(LoggerInterface $logger, IAvatarManager $avatarManager) {
$this->avatarManager = $avatarManager;
$this->logger = $logger;
}
public function handle(Event $event): void {
if (!($event instanceof BeforeUserDeletedEvent)) {
return;
}
$user = $event->getUser();
// Delete avatar on user deletion
try {
$avatar = $this->avatarManager->getAvatar($user->getUID());
$avatar->remove(true);
} catch (NotFoundException $e) {
// no avatar to remove
} catch (\Exception $e) {
// Ignore exceptions
$this->logger->info('Could not cleanup avatar of ' . $user->getUID(), [
'exception' => $e,
]);
}
}
}
@@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
/**
* @copyright Copyright (c) 2022 Carl Schwan <carl@carlschwan.eu>
*
* @license AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OC\User\Listeners;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\Files\NotFoundException;
use OCP\IAvatarManager;
use OCP\User\Events\UserChangedEvent;
/**
* @template-implements IEventListener<UserChangedEvent>
*/
class UserChangedListener implements IEventListener {
private IAvatarManager $avatarManager;
public function __construct(IAvatarManager $avatarManager) {
$this->avatarManager = $avatarManager;
}
public function handle(Event $event): void {
if (!($event instanceof UserChangedEvent)) {
return;
}
$user = $event->getUser();
$feature = $event->getFeature();
$oldValue = $event->getOldValue();
$value = $event->getValue();
// We only change the avatar on display name changes
if ($feature === 'displayName') {
try {
$avatar = $this->avatarManager->getAvatar($user->getUID());
$avatar->userChanged($feature, $oldValue, $value);
} catch (NotFoundException $e) {
// no avatar to remove
}
}
}
}
@@ -0,0 +1,25 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Robin Appelman <robin@icewind.nl>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\User;
class LoginException extends \Exception {
}
+787
View File
@@ -0,0 +1,787 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bjoern Schiessle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Georg Ehrke <oc.list@georgehrke.com>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Vincent Chan <plus.vincchan@gmail.com>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\User;
use OC\Hooks\PublicEmitter;
use OC\Memcache\WithLocalCache;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\HintException;
use OCP\ICache;
use OCP\ICacheFactory;
use OCP\IConfig;
use OCP\IGroup;
use OCP\IUser;
use OCP\IUserBackend;
use OCP\IUserManager;
use OCP\L10N\IFactory;
use OCP\Server;
use OCP\Support\Subscription\IAssertion;
use OCP\User\Backend\ICheckPasswordBackend;
use OCP\User\Backend\ICountUsersBackend;
use OCP\User\Backend\IGetRealUIDBackend;
use OCP\User\Backend\IProvideEnabledStateBackend;
use OCP\User\Backend\ISearchKnownUsersBackend;
use OCP\User\Events\BeforeUserCreatedEvent;
use OCP\User\Events\UserCreatedEvent;
use OCP\UserInterface;
/**
* Class Manager
*
* Hooks available in scope \OC\User:
* - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - preDelete(\OC\User\User $user)
* - postDelete(\OC\User\User $user)
* - preCreateUser(string $uid, string $password)
* - postCreateUser(\OC\User\User $user, string $password)
* - change(\OC\User\User $user)
* - assignedUserId(string $uid)
* - preUnassignedUserId(string $uid)
* - postUnassignedUserId(string $uid)
*
* @package OC\User
*/
class Manager extends PublicEmitter implements IUserManager {
/**
* @var \OCP\UserInterface[] $backends
*/
private $backends = [];
/**
* @var \OC\User\User[] $cachedUsers
*/
private $cachedUsers = [];
/** @var IConfig */
private $config;
/** @var ICache */
private $cache;
/** @var IEventDispatcher */
private $eventDispatcher;
private DisplayNameCache $displayNameCache;
public function __construct(IConfig $config,
ICacheFactory $cacheFactory,
IEventDispatcher $eventDispatcher) {
$this->config = $config;
$this->cache = new WithLocalCache($cacheFactory->createDistributed('user_backend_map'));
$cachedUsers = &$this->cachedUsers;
$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
/** @var \OC\User\User $user */
unset($cachedUsers[$user->getUID()]);
});
$this->eventDispatcher = $eventDispatcher;
$this->displayNameCache = new DisplayNameCache($cacheFactory, $this);
}
/**
* Get the active backends
* @return \OCP\UserInterface[]
*/
public function getBackends() {
return $this->backends;
}
/**
* register a user backend
*
* @param \OCP\UserInterface $backend
*/
public function registerBackend($backend) {
$this->backends[] = $backend;
}
/**
* remove a user backend
*
* @param \OCP\UserInterface $backend
*/
public function removeBackend($backend) {
$this->cachedUsers = [];
if (($i = array_search($backend, $this->backends)) !== false) {
unset($this->backends[$i]);
}
}
/**
* remove all user backends
*/
public function clearBackends() {
$this->cachedUsers = [];
$this->backends = [];
}
/**
* get a user by user id
*
* @param string $uid
* @return \OC\User\User|null Either the user or null if the specified user does not exist
*/
public function get($uid) {
if (is_null($uid) || $uid === '' || $uid === false) {
return null;
}
if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
return $this->cachedUsers[$uid];
}
$cachedBackend = $this->cache->get(sha1($uid));
if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) {
// Cache has the info of the user backend already, so ask that one directly
$backend = $this->backends[$cachedBackend];
if ($backend->userExists($uid)) {
return $this->getUserObject($uid, $backend);
}
}
foreach ($this->backends as $i => $backend) {
if ($i === $cachedBackend) {
// Tried that one already
continue;
}
if ($backend->userExists($uid)) {
// Hash $uid to ensure that only valid characters are used for the cache key
$this->cache->set(sha1($uid), $i, 300);
return $this->getUserObject($uid, $backend);
}
}
return null;
}
public function getDisplayName(string $uid): ?string {
return $this->displayNameCache->getDisplayName($uid);
}
/**
* get or construct the user object
*
* @param string $uid
* @param \OCP\UserInterface $backend
* @param bool $cacheUser If false the newly created user object will not be cached
* @return \OC\User\User
*/
public function getUserObject($uid, $backend, $cacheUser = true) {
if ($backend instanceof IGetRealUIDBackend) {
$uid = $backend->getRealUID($uid);
}
if (isset($this->cachedUsers[$uid])) {
return $this->cachedUsers[$uid];
}
$user = new User($uid, $backend, $this->eventDispatcher, $this, $this->config);
if ($cacheUser) {
$this->cachedUsers[$uid] = $user;
}
return $user;
}
/**
* check if a user exists
*
* @param string $uid
* @return bool
*/
public function userExists($uid) {
$user = $this->get($uid);
return ($user !== null);
}
/**
* Check if the password is valid for the user
*
* @param string $loginName
* @param string $password
* @return IUser|false the User object on success, false otherwise
*/
public function checkPassword($loginName, $password) {
$result = $this->checkPasswordNoLogging($loginName, $password);
if ($result === false) {
\OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
}
return $result;
}
/**
* Check if the password is valid for the user
*
* @internal
* @param string $loginName
* @param string $password
* @return IUser|false the User object on success, false otherwise
*/
public function checkPasswordNoLogging($loginName, $password) {
$loginName = str_replace("\0", '', $loginName);
$password = str_replace("\0", '', $password);
$cachedBackend = $this->cache->get($loginName);
if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) {
$backends = [$this->backends[$cachedBackend]];
} else {
$backends = $this->backends;
}
foreach ($backends as $backend) {
if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) {
/** @var ICheckPasswordBackend $backend */
$uid = $backend->checkPassword($loginName, $password);
if ($uid !== false) {
return $this->getUserObject($uid, $backend);
}
}
}
// since http basic auth doesn't provide a standard way of handling non ascii password we allow password to be urlencoded
// we only do this decoding after using the plain password fails to maintain compatibility with any password that happens
// to contain urlencoded patterns by "accident".
$password = urldecode($password);
foreach ($backends as $backend) {
if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) {
/** @var ICheckPasswordBackend|UserInterface $backend */
$uid = $backend->checkPassword($loginName, $password);
if ($uid !== false) {
return $this->getUserObject($uid, $backend);
}
}
}
return false;
}
/**
* Search by user id
*
* @param string $pattern
* @param int $limit
* @param int $offset
* @return IUser[]
* @deprecated since 27.0.0, use searchDisplayName instead
*/
public function search($pattern, $limit = null, $offset = null) {
$users = [];
foreach ($this->backends as $backend) {
$backendUsers = $backend->getUsers($pattern, $limit, $offset);
if (is_array($backendUsers)) {
foreach ($backendUsers as $uid) {
$users[$uid] = new LazyUser($uid, $this, null, $backend);
}
}
}
uasort($users, function (IUser $a, IUser $b) {
return strcasecmp($a->getUID(), $b->getUID());
});
return $users;
}
/**
* Search by displayName
*
* @param string $pattern
* @param int $limit
* @param int $offset
* @return IUser[]
*/
public function searchDisplayName($pattern, $limit = null, $offset = null) {
$users = [];
foreach ($this->backends as $backend) {
$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
if (is_array($backendUsers)) {
foreach ($backendUsers as $uid => $displayName) {
$users[] = new LazyUser($uid, $this, $displayName, $backend);
}
}
}
usort($users, function (IUser $a, IUser $b) {
return strcasecmp($a->getDisplayName(), $b->getDisplayName());
});
return $users;
}
/**
* @return IUser[]
*/
public function getDisabledUsers(?int $limit = null, int $offset = 0): array {
$users = $this->config->getUsersForUserValue('core', 'enabled', 'false');
$users = array_combine(
$users,
array_map(
fn (string $uid): IUser => new LazyUser($uid, $this),
$users
)
);
$tempLimit = ($limit === null ? null : $limit + $offset);
foreach ($this->backends as $backend) {
if (($tempLimit !== null) && (count($users) >= $tempLimit)) {
break;
}
if ($backend instanceof IProvideEnabledStateBackend) {
$backendUsers = $backend->getDisabledUserList(($tempLimit === null ? null : $tempLimit - count($users)));
foreach ($backendUsers as $uid) {
$users[$uid] = new LazyUser($uid, $this, null, $backend);
}
}
}
return array_slice($users, $offset, $limit);
}
/**
* Search known users (from phonebook sync) by displayName
*
* @param string $searcher
* @param string $pattern
* @param int|null $limit
* @param int|null $offset
* @return IUser[]
*/
public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array {
$users = [];
foreach ($this->backends as $backend) {
if ($backend instanceof ISearchKnownUsersBackend) {
$backendUsers = $backend->searchKnownUsersByDisplayName($searcher, $pattern, $limit, $offset);
} else {
// Better than nothing, but filtering after pagination can remove lots of results.
$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
}
if (is_array($backendUsers)) {
foreach ($backendUsers as $uid => $displayName) {
$users[] = $this->getUserObject($uid, $backend);
}
}
}
usort($users, function ($a, $b) {
/**
* @var IUser $a
* @var IUser $b
*/
return strcasecmp($a->getDisplayName(), $b->getDisplayName());
});
return $users;
}
/**
* @param string $uid
* @param string $password
* @return false|IUser the created user or false
* @throws \InvalidArgumentException
* @throws HintException
*/
public function createUser($uid, $password) {
// DI injection is not used here as IRegistry needs the user manager itself for user count and thus it would create a cyclic dependency
/** @var IAssertion $assertion */
$assertion = \OC::$server->get(IAssertion::class);
$assertion->createUserIsLegit();
$localBackends = [];
foreach ($this->backends as $backend) {
if ($backend instanceof Database) {
// First check if there is another user backend
$localBackends[] = $backend;
continue;
}
if ($backend->implementsActions(Backend::CREATE_USER)) {
return $this->createUserFromBackend($uid, $password, $backend);
}
}
foreach ($localBackends as $backend) {
if ($backend->implementsActions(Backend::CREATE_USER)) {
return $this->createUserFromBackend($uid, $password, $backend);
}
}
return false;
}
/**
* @param string $uid
* @param string $password
* @param UserInterface $backend
* @return IUser|false
* @throws \InvalidArgumentException
*/
public function createUserFromBackend($uid, $password, UserInterface $backend) {
$l = \OC::$server->getL10N('lib');
$this->validateUserId($uid, true);
// No empty password
if (trim($password) === '') {
throw new \InvalidArgumentException($l->t('A valid password must be provided'));
}
// Check if user already exists
if ($this->userExists($uid)) {
throw new \InvalidArgumentException($l->t('The username is already being used'));
}
/** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
$this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
$this->eventDispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
$state = $backend->createUser($uid, $password);
if ($state === false) {
throw new \InvalidArgumentException($l->t('Could not create user'));
}
$user = $this->getUserObject($uid, $backend);
if ($user instanceof IUser) {
/** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
$this->emit('\OC\User', 'postCreateUser', [$user, $password]);
$this->eventDispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
return $user;
}
return false;
}
/**
* returns how many users per backend exist (if supported by backend)
*
* @param boolean $hasLoggedIn when true only users that have a lastLogin
* entry in the preferences table will be affected
* @return array<string, int> an array of backend class as key and count number as value
*/
public function countUsers() {
$userCountStatistics = [];
foreach ($this->backends as $backend) {
if ($backend instanceof ICountUsersBackend || $backend->implementsActions(Backend::COUNT_USERS)) {
/** @var ICountUsersBackend|IUserBackend $backend */
$backendUsers = $backend->countUsers();
if ($backendUsers !== false) {
if ($backend instanceof IUserBackend) {
$name = $backend->getBackendName();
} else {
$name = get_class($backend);
}
if (isset($userCountStatistics[$name])) {
$userCountStatistics[$name] += $backendUsers;
} else {
$userCountStatistics[$name] = $backendUsers;
}
}
}
}
return $userCountStatistics;
}
/**
* returns how many users per backend exist in the requested groups (if supported by backend)
*
* @param IGroup[] $groups an array of gid to search in
* @return array|int an array of backend class as key and count number as value
* if $hasLoggedIn is true only an int is returned
*/
public function countUsersOfGroups(array $groups) {
$users = [];
foreach ($groups as $group) {
$usersIds = array_map(function ($user) {
return $user->getUID();
}, $group->getUsers());
$users = array_merge($users, $usersIds);
}
return count(array_unique($users));
}
/**
* The callback is executed for each user on each backend.
* If the callback returns false no further users will be retrieved.
*
* @psalm-param \Closure(\OCP\IUser):?bool $callback
* @param string $search
* @param boolean $onlySeen when true only users that have a lastLogin entry
* in the preferences table will be affected
* @since 9.0.0
*/
public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
if ($onlySeen) {
$this->callForSeenUsers($callback);
} else {
foreach ($this->getBackends() as $backend) {
$limit = 500;
$offset = 0;
do {
$users = $backend->getUsers($search, $limit, $offset);
foreach ($users as $uid) {
if (!$backend->userExists($uid)) {
continue;
}
$user = $this->getUserObject($uid, $backend, false);
$return = $callback($user);
if ($return === false) {
break;
}
}
$offset += $limit;
} while (count($users) >= $limit);
}
}
}
/**
* returns how many users are disabled
*
* @return int
* @since 12.0.0
*/
public function countDisabledUsers(): int {
$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$queryBuilder->select($queryBuilder->func()->count('*'))
->from('preferences')
->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
$result = $queryBuilder->execute();
$count = $result->fetchOne();
$result->closeCursor();
if ($count !== false) {
$count = (int)$count;
} else {
$count = 0;
}
return $count;
}
/**
* returns how many users are disabled in the requested groups
*
* @param array $groups groupids to search
* @return int
* @since 14.0.0
*/
public function countDisabledUsersOfGroups(array $groups): int {
$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
->from('preferences', 'p')
->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
$result = $queryBuilder->execute();
$count = $result->fetchOne();
$result->closeCursor();
if ($count !== false) {
$count = (int)$count;
} else {
$count = 0;
}
return $count;
}
/**
* returns how many users have logged in once
*
* @return int
* @since 11.0.0
*/
public function countSeenUsers() {
$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$queryBuilder->select($queryBuilder->func()->count('*'))
->from('preferences')
->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')));
$query = $queryBuilder->execute();
$result = (int)$query->fetchOne();
$query->closeCursor();
return $result;
}
/**
* @param \Closure $callback
* @psalm-param \Closure(\OCP\IUser):?bool $callback
* @since 11.0.0
*/
public function callForSeenUsers(\Closure $callback) {
$limit = 1000;
$offset = 0;
do {
$userIds = $this->getSeenUserIds($limit, $offset);
$offset += $limit;
foreach ($userIds as $userId) {
foreach ($this->backends as $backend) {
if ($backend->userExists($userId)) {
$user = $this->getUserObject($userId, $backend, false);
$return = $callback($user);
if ($return === false) {
return;
}
break;
}
}
}
} while (count($userIds) >= $limit);
}
/**
* Getting all userIds that have a listLogin value requires checking the
* value in php because on oracle you cannot use a clob in a where clause,
* preventing us from doing a not null or length(value) > 0 check.
*
* @param int $limit
* @param int $offset
* @return string[] with user ids
*/
private function getSeenUserIds($limit = null, $offset = null) {
$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$queryBuilder->select(['userid'])
->from('preferences')
->where($queryBuilder->expr()->eq(
'appid', $queryBuilder->createNamedParameter('login'))
)
->andWhere($queryBuilder->expr()->eq(
'configkey', $queryBuilder->createNamedParameter('lastLogin'))
)
->andWhere($queryBuilder->expr()->isNotNull('configvalue')
);
if ($limit !== null) {
$queryBuilder->setMaxResults($limit);
}
if ($offset !== null) {
$queryBuilder->setFirstResult($offset);
}
$query = $queryBuilder->execute();
$result = [];
while ($row = $query->fetch()) {
$result[] = $row['userid'];
}
$query->closeCursor();
return $result;
}
/**
* @param string $email
* @return IUser[]
* @since 9.1.0
*/
public function getByEmail($email) {
// looking for 'email' only (and not primary_mail) is intentional
$userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
$users = array_map(function ($uid) {
return $this->get($uid);
}, $userIds);
return array_values(array_filter($users, function ($u) {
return ($u instanceof IUser);
}));
}
/**
* @param string $uid
* @param bool $checkDataDirectory
* @throws \InvalidArgumentException Message is an already translated string with a reason why the id is not valid
* @since 26.0.0
*/
public function validateUserId(string $uid, bool $checkDataDirectory = false): void {
$l = Server::get(IFactory::class)->get('lib');
// Check the name for bad characters
// Allowed are: "a-z", "A-Z", "0-9", spaces and "_.@-'"
if (preg_match('/[^a-zA-Z0-9 _.@\-\']/', $uid)) {
throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
. ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'));
}
// No empty username
if (trim($uid) === '') {
throw new \InvalidArgumentException($l->t('A valid username must be provided'));
}
// No whitespace at the beginning or at the end
if (trim($uid) !== $uid) {
throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
}
// Username only consists of 1 or 2 dots (directory traversal)
if ($uid === '.' || $uid === '..') {
throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
}
if (!$this->verifyUid($uid, $checkDataDirectory)) {
throw new \InvalidArgumentException($l->t('Username is invalid because files already exist for this user'));
}
}
private function verifyUid(string $uid, bool $checkDataDirectory = false): bool {
$appdata = 'appdata_' . $this->config->getSystemValueString('instanceid');
if (\in_array($uid, [
'.htaccess',
'files_external',
'__groupfolders',
'.ocdata',
'owncloud.log',
'nextcloud.log',
$appdata], true)) {
return false;
}
if (!$checkDataDirectory) {
return true;
}
$dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid);
}
public function getDisplayNameCache(): DisplayNameCache {
return $this->displayNameCache;
}
}
@@ -0,0 +1,26 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\User;
class NoUserException extends \Exception {
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
/**
* @copyright 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @author 2023 Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OC\User;
use OCP\IUser;
use OCP\User\IOutOfOfficeData;
class OutOfOfficeData implements IOutOfOfficeData {
public function __construct(private string $id,
private IUser $user,
private int $startDate,
private int $endDate,
private string $shortMessage,
private string $message) {
}
public function getId(): string {
return $this->id;
}
public function getUser(): IUser {
return $this->user;
}
public function getStartDate(): int {
return $this->startDate;
}
public function getEndDate(): int {
return $this->endDate;
}
public function getShortMessage(): string {
return $this->shortMessage;
}
public function getMessage(): string {
return $this->message;
}
public function jsonSerialize(): array {
return [
'id' => $this->getId(),
'userId' => $this->getUser()->getUID(),
'startDate' => $this->getStartDate(),
'endDate' => $this->getEndDate(),
'shortMessage' => $this->getShortMessage(),
'message' => $this->getMessage(),
];
}
}
File diff suppressed because it is too large Load Diff
+621
View File
@@ -0,0 +1,621 @@
<?php
/**
* @copyright Copyright (c) 2016, ownCloud, Inc.
*
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
* @author Bart Visscher <bartv@thisnet.nl>
* @author Björn Schießle <bjoern@schiessle.org>
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
* @author Joas Schilling <coding@schilljs.com>
* @author John Molakvoæ <skjnldsv@protonmail.com>
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
* @author Julius Härtl <jus@bitgrid.net>
* @author Leon Klingele <leon@struktur.de>
* @author Lukas Reschke <lukas@statuscode.ch>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <robin@icewind.nl>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\User;
use InvalidArgumentException;
use OC\Accounts\AccountManager;
use OC\Avatar\AvatarManager;
use OC\Hooks\Emitter;
use OC_Helper;
use OCP\Accounts\IAccountManager;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\Group\Events\BeforeUserRemovedEvent;
use OCP\Group\Events\UserRemovedEvent;
use OCP\IAvatarManager;
use OCP\IConfig;
use OCP\IImage;
use OCP\IURLGenerator;
use OCP\IUser;
use OCP\IUserBackend;
use OCP\User\Backend\IGetHomeBackend;
use OCP\User\Backend\IProvideAvatarBackend;
use OCP\User\Backend\IProvideEnabledStateBackend;
use OCP\User\Backend\ISetDisplayNameBackend;
use OCP\User\Backend\ISetPasswordBackend;
use OCP\User\Events\BeforePasswordUpdatedEvent;
use OCP\User\Events\BeforeUserDeletedEvent;
use OCP\User\Events\PasswordUpdatedEvent;
use OCP\User\Events\UserChangedEvent;
use OCP\User\Events\UserDeletedEvent;
use OCP\User\GetQuotaEvent;
use OCP\UserInterface;
use function json_decode;
use function json_encode;
class User implements IUser {
private const CONFIG_KEY_MANAGERS = 'manager';
/** @var IAccountManager */
protected $accountManager;
/** @var string */
private $uid;
/** @var string|null */
private $displayName;
/** @var UserInterface|null */
private $backend;
/** @var IEventDispatcher */
private $dispatcher;
/** @var bool|null */
private $enabled;
/** @var Emitter|Manager */
private $emitter;
/** @var string */
private $home;
/** @var int|null */
private $lastLogin;
/** @var \OCP\IConfig */
private $config;
/** @var IAvatarManager */
private $avatarManager;
/** @var IURLGenerator */
private $urlGenerator;
public function __construct(string $uid, ?UserInterface $backend, IEventDispatcher $dispatcher, $emitter = null, IConfig $config = null, $urlGenerator = null) {
$this->uid = $uid;
$this->backend = $backend;
$this->emitter = $emitter;
if (is_null($config)) {
$config = \OC::$server->getConfig();
}
$this->config = $config;
$this->urlGenerator = $urlGenerator;
if (is_null($this->urlGenerator)) {
$this->urlGenerator = \OC::$server->getURLGenerator();
}
$this->dispatcher = $dispatcher;
}
/**
* get the user id
*
* @return string
*/
public function getUID() {
return $this->uid;
}
/**
* get the display name for the user, if no specific display name is set it will fallback to the user id
*
* @return string
*/
public function getDisplayName() {
if ($this->displayName === null) {
$displayName = '';
if ($this->backend && $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
// get display name and strip whitespace from the beginning and end of it
$backendDisplayName = $this->backend->getDisplayName($this->uid);
if (is_string($backendDisplayName)) {
$displayName = trim($backendDisplayName);
}
}
if (!empty($displayName)) {
$this->displayName = $displayName;
} else {
$this->displayName = $this->uid;
}
}
return $this->displayName;
}
/**
* set the displayname for the user
*
* @param string $displayName
* @return bool
*
* @since 25.0.0 Throw InvalidArgumentException
* @throws \InvalidArgumentException
*/
public function setDisplayName($displayName) {
$displayName = trim($displayName);
$oldDisplayName = $this->getDisplayName();
if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName) && $displayName !== $oldDisplayName) {
/** @var ISetDisplayNameBackend $backend */
$backend = $this->backend;
$result = $backend->setDisplayName($this->uid, $displayName);
if ($result) {
$this->displayName = $displayName;
$this->triggerChange('displayName', $displayName, $oldDisplayName);
}
return $result !== false;
}
return false;
}
/**
* @inheritDoc
*/
public function setEMailAddress($mailAddress) {
$this->setSystemEMailAddress($mailAddress);
}
/**
* @inheritDoc
*/
public function setSystemEMailAddress(string $mailAddress): void {
$oldMailAddress = $this->getSystemEMailAddress();
if ($mailAddress === '') {
$this->config->deleteUserValue($this->uid, 'settings', 'email');
} else {
$this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
}
$primaryAddress = $this->getPrimaryEMailAddress();
if ($primaryAddress === $mailAddress) {
// on match no dedicated primary settings is necessary
$this->setPrimaryEMailAddress('');
}
if ($oldMailAddress !== strtolower($mailAddress)) {
$this->triggerChange('eMailAddress', $mailAddress, $oldMailAddress);
}
}
/**
* @inheritDoc
*/
public function setPrimaryEMailAddress(string $mailAddress): void {
if ($mailAddress === '') {
$this->config->deleteUserValue($this->uid, 'settings', 'primary_email');
return;
}
$this->ensureAccountManager();
$account = $this->accountManager->getAccount($this);
$property = $account->getPropertyCollection(IAccountManager::COLLECTION_EMAIL)
->getPropertyByValue($mailAddress);
if ($property === null || $property->getLocallyVerified() !== IAccountManager::VERIFIED) {
throw new InvalidArgumentException('Only verified emails can be set as primary');
}
$this->config->setUserValue($this->uid, 'settings', 'primary_email', $mailAddress);
}
private function ensureAccountManager() {
if (!$this->accountManager instanceof IAccountManager) {
$this->accountManager = \OC::$server->get(IAccountManager::class);
}
}
/**
* returns the timestamp of the user's last login or 0 if the user did never
* login
*
* @return int
*/
public function getLastLogin() {
if ($this->lastLogin === null) {
$this->lastLogin = (int) $this->config->getUserValue($this->uid, 'login', 'lastLogin', 0);
}
return (int) $this->lastLogin;
}
/**
* updates the timestamp of the most recent login of this user
*/
public function updateLastLoginTimestamp() {
$previousLogin = $this->getLastLogin();
$now = time();
$firstTimeLogin = $previousLogin === 0;
if ($now - $previousLogin > 60) {
$this->lastLogin = time();
$this->config->setUserValue(
$this->uid, 'login', 'lastLogin', (string)$this->lastLogin);
}
return $firstTimeLogin;
}
/**
* Delete the user
*
* @return bool
*/
public function delete() {
if ($this->emitter) {
/** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
$this->emitter->emit('\OC\User', 'preDelete', [$this]);
}
$this->dispatcher->dispatchTyped(new BeforeUserDeletedEvent($this));
$result = $this->backend->deleteUser($this->uid);
if ($result) {
// FIXME: Feels like an hack - suggestions?
$groupManager = \OC::$server->getGroupManager();
// We have to delete the user from all groups
foreach ($groupManager->getUserGroupIds($this) as $groupId) {
$group = $groupManager->get($groupId);
if ($group) {
$this->dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $this));
$group->removeUser($this);
$this->dispatcher->dispatchTyped(new UserRemovedEvent($group, $this));
}
}
// Delete the user's keys in preferences
\OC::$server->getConfig()->deleteAllUserValues($this->uid);
\OC::$server->getCommentsManager()->deleteReferencesOfActor('users', $this->uid);
\OC::$server->getCommentsManager()->deleteReadMarksFromUser($this);
/** @var AvatarManager $avatarManager */
$avatarManager = \OCP\Server::get(AvatarManager::class);
$avatarManager->deleteUserAvatar($this->uid);
$notification = \OC::$server->getNotificationManager()->createNotification();
$notification->setUser($this->uid);
\OC::$server->getNotificationManager()->markProcessed($notification);
/** @var AccountManager $accountManager */
$accountManager = \OCP\Server::get(AccountManager::class);
$accountManager->deleteUser($this);
if ($this->emitter) {
/** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
$this->emitter->emit('\OC\User', 'postDelete', [$this]);
}
$this->dispatcher->dispatchTyped(new UserDeletedEvent($this));
}
return !($result === false);
}
/**
* Set the password of the user
*
* @param string $password
* @param string $recoveryPassword for the encryption app to reset encryption keys
* @return bool
*/
public function setPassword($password, $recoveryPassword = null) {
$this->dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($this, $password, $recoveryPassword));
if ($this->emitter) {
$this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]);
}
if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
/** @var ISetPasswordBackend $backend */
$backend = $this->backend;
$result = $backend->setPassword($this->uid, $password);
if ($result !== false) {
$this->dispatcher->dispatchTyped(new PasswordUpdatedEvent($this, $password, $recoveryPassword));
if ($this->emitter) {
$this->emitter->emit('\OC\User', 'postSetPassword', [$this, $password, $recoveryPassword]);
}
}
return !($result === false);
} else {
return false;
}
}
/**
* get the users home folder to mount
*
* @return string
*/
public function getHome() {
if (!$this->home) {
/** @psalm-suppress UndefinedInterfaceMethod Once we get rid of the legacy implementsActions, psalm won't complain anymore */
if (($this->backend instanceof IGetHomeBackend || $this->backend->implementsActions(Backend::GET_HOME)) && $home = $this->backend->getHome($this->uid)) {
$this->home = $home;
} elseif ($this->config) {
$this->home = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
} else {
$this->home = \OC::$SERVERROOT . '/data/' . $this->uid;
}
}
return $this->home;
}
/**
* Get the name of the backend class the user is connected with
*
* @return string
*/
public function getBackendClassName() {
if ($this->backend instanceof IUserBackend) {
return $this->backend->getBackendName();
}
return get_class($this->backend);
}
public function getBackend(): ?UserInterface {
return $this->backend;
}
/**
* Check if the backend allows the user to change his avatar on Personal page
*
* @return bool
*/
public function canChangeAvatar() {
if ($this->backend instanceof IProvideAvatarBackend || $this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
/** @var IProvideAvatarBackend $backend */
$backend = $this->backend;
return $backend->canChangeAvatar($this->uid);
}
return true;
}
/**
* check if the backend supports changing passwords
*
* @return bool
*/
public function canChangePassword() {
return $this->backend->implementsActions(Backend::SET_PASSWORD);
}
/**
* check if the backend supports changing display names
*
* @return bool
*/
public function canChangeDisplayName() {
if (!$this->config->getSystemValueBool('allow_user_to_change_display_name', true)) {
return false;
}
return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
}
/**
* check if the user is enabled
*
* @return bool
*/
public function isEnabled() {
$queryDatabaseValue = function (): bool {
if ($this->enabled === null) {
$enabled = $this->config->getUserValue($this->uid, 'core', 'enabled', 'true');
$this->enabled = $enabled === 'true';
}
return $this->enabled;
};
if ($this->backend instanceof IProvideEnabledStateBackend) {
return $this->backend->isUserEnabled($this->uid, $queryDatabaseValue);
} else {
return $queryDatabaseValue();
}
}
/**
* set the enabled status for the user
*
* @return void
*/
public function setEnabled(bool $enabled = true) {
$oldStatus = $this->isEnabled();
$setDatabaseValue = function (bool $enabled): void {
$this->config->setUserValue($this->uid, 'core', 'enabled', $enabled ? 'true' : 'false');
$this->enabled = $enabled;
};
if ($this->backend instanceof IProvideEnabledStateBackend) {
$queryDatabaseValue = function (): bool {
if ($this->enabled === null) {
$enabled = $this->config->getUserValue($this->uid, 'core', 'enabled', 'true');
$this->enabled = $enabled === 'true';
}
return $this->enabled;
};
$enabled = $this->backend->setUserEnabled($this->uid, $enabled, $queryDatabaseValue, $setDatabaseValue);
if ($oldStatus !== $enabled) {
$this->triggerChange('enabled', $enabled, $oldStatus);
}
} elseif ($oldStatus !== $enabled) {
$setDatabaseValue($enabled);
$this->triggerChange('enabled', $enabled, $oldStatus);
}
}
/**
* get the users email address
*
* @return string|null
* @since 9.0.0
*/
public function getEMailAddress() {
return $this->getPrimaryEMailAddress() ?? $this->getSystemEMailAddress();
}
/**
* @inheritDoc
*/
public function getSystemEMailAddress(): ?string {
return $this->config->getUserValue($this->uid, 'settings', 'email', null);
}
/**
* @inheritDoc
*/
public function getPrimaryEMailAddress(): ?string {
return $this->config->getUserValue($this->uid, 'settings', 'primary_email', null);
}
/**
* get the users' quota
*
* @return string
* @since 9.0.0
*/
public function getQuota() {
// allow apps to modify the user quota by hooking into the event
$event = new GetQuotaEvent($this);
$this->dispatcher->dispatchTyped($event);
$overwriteQuota = $event->getQuota();
if ($overwriteQuota) {
$quota = $overwriteQuota;
} else {
$quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
}
if ($quota === 'default') {
$quota = $this->config->getAppValue('files', 'default_quota', 'none');
// if unlimited quota is not allowed => avoid getting 'unlimited' as default_quota fallback value
// use the first preset instead
$allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
if (!$allowUnlimitedQuota) {
$presets = $this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
$presets = array_filter(array_map('trim', explode(',', $presets)));
$quotaPreset = array_values(array_diff($presets, ['default', 'none']));
if (count($quotaPreset) > 0) {
$quota = $this->config->getAppValue('files', 'default_quota', $quotaPreset[0]);
}
}
}
return $quota;
}
/**
* set the users' quota
*
* @param string $quota
* @return void
* @throws InvalidArgumentException
* @since 9.0.0
*/
public function setQuota($quota) {
$oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', '');
if ($quota !== 'none' and $quota !== 'default') {
$bytesQuota = OC_Helper::computerFileSize($quota);
if ($bytesQuota === false) {
throw new InvalidArgumentException('Failed to set quota to invalid value '.$quota);
}
$quota = OC_Helper::humanFileSize($bytesQuota);
}
if ($quota !== $oldQuota) {
$this->config->setUserValue($this->uid, 'files', 'quota', $quota);
$this->triggerChange('quota', $quota, $oldQuota);
}
\OC_Helper::clearStorageInfo('/' . $this->uid . '/files');
}
public function getManagerUids(): array {
$encodedUids = $this->config->getUserValue(
$this->uid,
'settings',
self::CONFIG_KEY_MANAGERS,
'[]'
);
return json_decode($encodedUids, false, 512, JSON_THROW_ON_ERROR);
}
public function setManagerUids(array $uids): void {
$oldUids = $this->getManagerUids();
$this->config->setUserValue(
$this->uid,
'settings',
self::CONFIG_KEY_MANAGERS,
json_encode($uids, JSON_THROW_ON_ERROR)
);
$this->triggerChange('managers', $uids, $oldUids);
}
/**
* get the avatar image if it exists
*
* @param int $size
* @return IImage|null
* @since 9.0.0
*/
public function getAvatarImage($size) {
// delay the initialization
if (is_null($this->avatarManager)) {
$this->avatarManager = \OC::$server->get(IAvatarManager::class);
}
$avatar = $this->avatarManager->getAvatar($this->uid);
$image = $avatar->get($size);
if ($image) {
return $image;
}
return null;
}
/**
* get the federation cloud id
*
* @return string
* @since 9.0.0
*/
public function getCloudId() {
$uid = $this->getUID();
$server = rtrim($this->urlGenerator->getAbsoluteURL('/'), '/');
if (str_ends_with($server, '/index.php')) {
$server = substr($server, 0, -10);
}
$server = $this->removeProtocolFromUrl($server);
return $uid . '@' . $server;
}
private function removeProtocolFromUrl(string $url): string {
if (str_starts_with($url, 'https://')) {
return substr($url, strlen('https://'));
}
return $url;
}
public function triggerChange($feature, $value = null, $oldValue = null) {
$this->dispatcher->dispatchTyped(new UserChangedEvent($this, $feature, $value, $oldValue));
if ($this->emitter) {
$this->emitter->emit('\OC\User', 'changeUser', [$this, $feature, $value, $oldValue]);
}
}
}