1
0

User.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\User;
  8. use InvalidArgumentException;
  9. use OC\Accounts\AccountManager;
  10. use OC\Avatar\AvatarManager;
  11. use OC\Hooks\Emitter;
  12. use OC_Helper;
  13. use OCP\Accounts\IAccountManager;
  14. use OCP\Comments\ICommentsManager;
  15. use OCP\EventDispatcher\IEventDispatcher;
  16. use OCP\Group\Events\BeforeUserRemovedEvent;
  17. use OCP\Group\Events\UserRemovedEvent;
  18. use OCP\IAvatarManager;
  19. use OCP\IConfig;
  20. use OCP\IDBConnection;
  21. use OCP\IGroupManager;
  22. use OCP\IImage;
  23. use OCP\IURLGenerator;
  24. use OCP\IUser;
  25. use OCP\IUserBackend;
  26. use OCP\Notification\IManager as INotificationManager;
  27. use OCP\User\Backend\IGetHomeBackend;
  28. use OCP\User\Backend\IPasswordHashBackend;
  29. use OCP\User\Backend\IProvideAvatarBackend;
  30. use OCP\User\Backend\IProvideEnabledStateBackend;
  31. use OCP\User\Backend\ISetDisplayNameBackend;
  32. use OCP\User\Backend\ISetPasswordBackend;
  33. use OCP\User\Events\BeforePasswordUpdatedEvent;
  34. use OCP\User\Events\BeforeUserDeletedEvent;
  35. use OCP\User\Events\PasswordUpdatedEvent;
  36. use OCP\User\Events\UserChangedEvent;
  37. use OCP\User\Events\UserDeletedEvent;
  38. use OCP\User\GetQuotaEvent;
  39. use OCP\UserInterface;
  40. use Psr\Log\LoggerInterface;
  41. use function json_decode;
  42. use function json_encode;
  43. class User implements IUser {
  44. private const CONFIG_KEY_MANAGERS = 'manager';
  45. private IConfig $config;
  46. private IURLGenerator $urlGenerator;
  47. /** @var IAccountManager */
  48. protected $accountManager;
  49. /** @var string|null */
  50. private $displayName;
  51. /** @var bool|null */
  52. private $enabled;
  53. /** @var Emitter|Manager|null */
  54. private $emitter;
  55. /** @var string */
  56. private $home;
  57. /** @var int|null */
  58. private $lastLogin;
  59. /** @var IAvatarManager */
  60. private $avatarManager;
  61. public function __construct(
  62. private string $uid,
  63. private ?UserInterface $backend,
  64. private IEventDispatcher $dispatcher,
  65. $emitter = null,
  66. ?IConfig $config = null,
  67. $urlGenerator = null,
  68. ) {
  69. $this->emitter = $emitter;
  70. $this->config = $config ?? \OCP\Server::get(IConfig::class);
  71. $this->urlGenerator = $urlGenerator ?? \OCP\Server::get(IURLGenerator::class);
  72. }
  73. /**
  74. * get the user id
  75. *
  76. * @return string
  77. */
  78. public function getUID() {
  79. return $this->uid;
  80. }
  81. /**
  82. * get the display name for the user, if no specific display name is set it will fallback to the user id
  83. *
  84. * @return string
  85. */
  86. public function getDisplayName() {
  87. if ($this->displayName === null) {
  88. $displayName = '';
  89. if ($this->backend && $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) {
  90. // get display name and strip whitespace from the beginning and end of it
  91. $backendDisplayName = $this->backend->getDisplayName($this->uid);
  92. if (is_string($backendDisplayName)) {
  93. $displayName = trim($backendDisplayName);
  94. }
  95. }
  96. if (!empty($displayName)) {
  97. $this->displayName = $displayName;
  98. } else {
  99. $this->displayName = $this->uid;
  100. }
  101. }
  102. return $this->displayName;
  103. }
  104. /**
  105. * set the displayname for the user
  106. *
  107. * @param string $displayName
  108. * @return bool
  109. *
  110. * @since 25.0.0 Throw InvalidArgumentException
  111. * @throws \InvalidArgumentException
  112. */
  113. public function setDisplayName($displayName) {
  114. $displayName = trim($displayName);
  115. $oldDisplayName = $this->getDisplayName();
  116. if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName) && $displayName !== $oldDisplayName) {
  117. /** @var ISetDisplayNameBackend $backend */
  118. $backend = $this->backend;
  119. $result = $backend->setDisplayName($this->uid, $displayName);
  120. if ($result) {
  121. $this->displayName = $displayName;
  122. $this->triggerChange('displayName', $displayName, $oldDisplayName);
  123. }
  124. return $result !== false;
  125. }
  126. return false;
  127. }
  128. /**
  129. * @inheritDoc
  130. */
  131. public function setEMailAddress($mailAddress) {
  132. $this->setSystemEMailAddress($mailAddress);
  133. }
  134. /**
  135. * @inheritDoc
  136. */
  137. public function setSystemEMailAddress(string $mailAddress): void {
  138. $oldMailAddress = $this->getSystemEMailAddress();
  139. if ($mailAddress === '') {
  140. $this->config->deleteUserValue($this->uid, 'settings', 'email');
  141. } else {
  142. $this->config->setUserValue($this->uid, 'settings', 'email', $mailAddress);
  143. }
  144. $primaryAddress = $this->getPrimaryEMailAddress();
  145. if ($primaryAddress === $mailAddress) {
  146. // on match no dedicated primary settings is necessary
  147. $this->setPrimaryEMailAddress('');
  148. }
  149. if ($oldMailAddress !== strtolower($mailAddress)) {
  150. $this->triggerChange('eMailAddress', $mailAddress, $oldMailAddress);
  151. }
  152. }
  153. /**
  154. * @inheritDoc
  155. */
  156. public function setPrimaryEMailAddress(string $mailAddress): void {
  157. if ($mailAddress === '') {
  158. $this->config->deleteUserValue($this->uid, 'settings', 'primary_email');
  159. return;
  160. }
  161. $this->ensureAccountManager();
  162. $account = $this->accountManager->getAccount($this);
  163. $property = $account->getPropertyCollection(IAccountManager::COLLECTION_EMAIL)
  164. ->getPropertyByValue($mailAddress);
  165. if ($property === null || $property->getLocallyVerified() !== IAccountManager::VERIFIED) {
  166. throw new InvalidArgumentException('Only verified emails can be set as primary');
  167. }
  168. $this->config->setUserValue($this->uid, 'settings', 'primary_email', $mailAddress);
  169. }
  170. private function ensureAccountManager() {
  171. if (!$this->accountManager instanceof IAccountManager) {
  172. $this->accountManager = \OC::$server->get(IAccountManager::class);
  173. }
  174. }
  175. /**
  176. * returns the timestamp of the user's last login or 0 if the user did never
  177. * login
  178. *
  179. * @return int
  180. */
  181. public function getLastLogin() {
  182. if ($this->lastLogin === null) {
  183. $this->lastLogin = (int)$this->config->getUserValue($this->uid, 'login', 'lastLogin', 0);
  184. }
  185. return (int)$this->lastLogin;
  186. }
  187. /**
  188. * updates the timestamp of the most recent login of this user
  189. */
  190. public function updateLastLoginTimestamp() {
  191. $previousLogin = $this->getLastLogin();
  192. $now = time();
  193. $firstTimeLogin = $previousLogin === 0;
  194. if ($now - $previousLogin > 60) {
  195. $this->lastLogin = time();
  196. $this->config->setUserValue(
  197. $this->uid, 'login', 'lastLogin', (string)$this->lastLogin);
  198. }
  199. return $firstTimeLogin;
  200. }
  201. /**
  202. * Delete the user
  203. *
  204. * @return bool
  205. */
  206. public function delete() {
  207. if ($this->backend === null) {
  208. \OCP\Server::get(LoggerInterface::class)->error('Cannot delete user: No backend set');
  209. return false;
  210. }
  211. if ($this->emitter) {
  212. /** @deprecated 21.0.0 use BeforeUserDeletedEvent event with the IEventDispatcher instead */
  213. $this->emitter->emit('\OC\User', 'preDelete', [$this]);
  214. }
  215. $this->dispatcher->dispatchTyped(new BeforeUserDeletedEvent($this));
  216. // Set delete flag on the user - this is needed to ensure that the user data is removed if there happen any exception in the backend
  217. // because we can not restore the user meaning we could not rollback to any stable state otherwise.
  218. $this->config->setUserValue($this->uid, 'core', 'deleted', 'true');
  219. // We also need to backup the home path as this can not be reconstructed later if the original backend uses custom home paths
  220. $this->config->setUserValue($this->uid, 'core', 'deleted.home-path', $this->getHome());
  221. // Try to delete the user on the backend
  222. $result = $this->backend->deleteUser($this->uid);
  223. if ($result === false) {
  224. // The deletion was aborted or something else happened, we are in a defined state, so remove the delete flag
  225. $this->config->deleteUserValue($this->uid, 'core', 'deleted');
  226. return false;
  227. }
  228. // We have to delete the user from all groups
  229. $groupManager = \OCP\Server::get(IGroupManager::class);
  230. foreach ($groupManager->getUserGroupIds($this) as $groupId) {
  231. $group = $groupManager->get($groupId);
  232. if ($group) {
  233. $this->dispatcher->dispatchTyped(new BeforeUserRemovedEvent($group, $this));
  234. $group->removeUser($this);
  235. $this->dispatcher->dispatchTyped(new UserRemovedEvent($group, $this));
  236. }
  237. }
  238. $commentsManager = \OCP\Server::get(ICommentsManager::class);
  239. $commentsManager->deleteReferencesOfActor('users', $this->uid);
  240. $commentsManager->deleteReadMarksFromUser($this);
  241. $avatarManager = \OCP\Server::get(AvatarManager::class);
  242. $avatarManager->deleteUserAvatar($this->uid);
  243. $notificationManager = \OCP\Server::get(INotificationManager::class);
  244. $notification = $notificationManager->createNotification();
  245. $notification->setUser($this->uid);
  246. $notificationManager->markProcessed($notification);
  247. $accountManager = \OCP\Server::get(AccountManager::class);
  248. $accountManager->deleteUser($this);
  249. $database = \OCP\Server::get(IDBConnection::class);
  250. try {
  251. // We need to create a transaction to make sure we are in a defined state
  252. // because if all user values are removed also the flag is gone, but if an exception happens (e.g. database lost connection on the set operation)
  253. // exactly here we are in an undefined state as the data is still present but the user does not exist on the system anymore.
  254. $database->beginTransaction();
  255. // Remove all user settings
  256. $this->config->deleteAllUserValues($this->uid);
  257. // But again set flag that this user is about to be deleted
  258. $this->config->setUserValue($this->uid, 'core', 'deleted', 'true');
  259. $this->config->setUserValue($this->uid, 'core', 'deleted.home-path', $this->getHome());
  260. // Commit the transaction so we are in a defined state: either the preferences are removed or an exception occurred but the delete flag is still present
  261. $database->commit();
  262. } catch (\Throwable $e) {
  263. $database->rollback();
  264. throw $e;
  265. }
  266. if ($this->emitter !== null) {
  267. /** @deprecated 21.0.0 use UserDeletedEvent event with the IEventDispatcher instead */
  268. $this->emitter->emit('\OC\User', 'postDelete', [$this]);
  269. }
  270. $this->dispatcher->dispatchTyped(new UserDeletedEvent($this));
  271. // Finally we can unset the delete flag and all other states
  272. $this->config->deleteAllUserValues($this->uid);
  273. return true;
  274. }
  275. /**
  276. * Set the password of the user
  277. *
  278. * @param string $password
  279. * @param string $recoveryPassword for the encryption app to reset encryption keys
  280. * @return bool
  281. */
  282. public function setPassword($password, $recoveryPassword = null) {
  283. $this->dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($this, $password, $recoveryPassword));
  284. if ($this->emitter) {
  285. $this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]);
  286. }
  287. if ($this->backend->implementsActions(Backend::SET_PASSWORD)) {
  288. /** @var ISetPasswordBackend $backend */
  289. $backend = $this->backend;
  290. $result = $backend->setPassword($this->uid, $password);
  291. if ($result !== false) {
  292. $this->dispatcher->dispatchTyped(new PasswordUpdatedEvent($this, $password, $recoveryPassword));
  293. if ($this->emitter) {
  294. $this->emitter->emit('\OC\User', 'postSetPassword', [$this, $password, $recoveryPassword]);
  295. }
  296. }
  297. return !($result === false);
  298. } else {
  299. return false;
  300. }
  301. }
  302. public function getPasswordHash(): ?string {
  303. if (!($this->backend instanceof IPasswordHashBackend)) {
  304. return null;
  305. }
  306. return $this->backend->getPasswordHash($this->uid);
  307. }
  308. public function setPasswordHash(string $passwordHash): bool {
  309. if (!($this->backend instanceof IPasswordHashBackend)) {
  310. return false;
  311. }
  312. return $this->backend->setPasswordHash($this->uid, $passwordHash);
  313. }
  314. /**
  315. * get the users home folder to mount
  316. *
  317. * @return string
  318. */
  319. public function getHome() {
  320. if (!$this->home) {
  321. /** @psalm-suppress UndefinedInterfaceMethod Once we get rid of the legacy implementsActions, psalm won't complain anymore */
  322. if (($this->backend instanceof IGetHomeBackend || $this->backend->implementsActions(Backend::GET_HOME)) && $home = $this->backend->getHome($this->uid)) {
  323. $this->home = $home;
  324. } else {
  325. $this->home = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $this->uid;
  326. }
  327. }
  328. return $this->home;
  329. }
  330. /**
  331. * Get the name of the backend class the user is connected with
  332. *
  333. * @return string
  334. */
  335. public function getBackendClassName() {
  336. if ($this->backend instanceof IUserBackend) {
  337. return $this->backend->getBackendName();
  338. }
  339. return get_class($this->backend);
  340. }
  341. public function getBackend(): ?UserInterface {
  342. return $this->backend;
  343. }
  344. /**
  345. * Check if the backend allows the user to change their avatar on Personal page
  346. *
  347. * @return bool
  348. */
  349. public function canChangeAvatar() {
  350. if ($this->backend instanceof IProvideAvatarBackend || $this->backend->implementsActions(Backend::PROVIDE_AVATAR)) {
  351. /** @var IProvideAvatarBackend $backend */
  352. $backend = $this->backend;
  353. return $backend->canChangeAvatar($this->uid);
  354. }
  355. return true;
  356. }
  357. /**
  358. * check if the backend supports changing passwords
  359. *
  360. * @return bool
  361. */
  362. public function canChangePassword() {
  363. return $this->backend->implementsActions(Backend::SET_PASSWORD);
  364. }
  365. /**
  366. * check if the backend supports changing display names
  367. *
  368. * @return bool
  369. */
  370. public function canChangeDisplayName() {
  371. if (!$this->config->getSystemValueBool('allow_user_to_change_display_name', true)) {
  372. return false;
  373. }
  374. return $this->backend->implementsActions(Backend::SET_DISPLAYNAME);
  375. }
  376. /**
  377. * check if the user is enabled
  378. *
  379. * @return bool
  380. */
  381. public function isEnabled() {
  382. $queryDatabaseValue = function (): bool {
  383. if ($this->enabled === null) {
  384. $enabled = $this->config->getUserValue($this->uid, 'core', 'enabled', 'true');
  385. $this->enabled = $enabled === 'true';
  386. }
  387. return $this->enabled;
  388. };
  389. if ($this->backend instanceof IProvideEnabledStateBackend) {
  390. return $this->backend->isUserEnabled($this->uid, $queryDatabaseValue);
  391. } else {
  392. return $queryDatabaseValue();
  393. }
  394. }
  395. /**
  396. * set the enabled status for the user
  397. *
  398. * @return void
  399. */
  400. public function setEnabled(bool $enabled = true) {
  401. $oldStatus = $this->isEnabled();
  402. $setDatabaseValue = function (bool $enabled): void {
  403. $this->config->setUserValue($this->uid, 'core', 'enabled', $enabled ? 'true' : 'false');
  404. $this->enabled = $enabled;
  405. };
  406. if ($this->backend instanceof IProvideEnabledStateBackend) {
  407. $queryDatabaseValue = function (): bool {
  408. if ($this->enabled === null) {
  409. $enabled = $this->config->getUserValue($this->uid, 'core', 'enabled', 'true');
  410. $this->enabled = $enabled === 'true';
  411. }
  412. return $this->enabled;
  413. };
  414. $enabled = $this->backend->setUserEnabled($this->uid, $enabled, $queryDatabaseValue, $setDatabaseValue);
  415. if ($oldStatus !== $enabled) {
  416. $this->triggerChange('enabled', $enabled, $oldStatus);
  417. }
  418. } elseif ($oldStatus !== $enabled) {
  419. $setDatabaseValue($enabled);
  420. $this->triggerChange('enabled', $enabled, $oldStatus);
  421. }
  422. }
  423. /**
  424. * get the users email address
  425. *
  426. * @return string|null
  427. * @since 9.0.0
  428. */
  429. public function getEMailAddress() {
  430. return $this->getPrimaryEMailAddress() ?? $this->getSystemEMailAddress();
  431. }
  432. /**
  433. * @inheritDoc
  434. */
  435. public function getSystemEMailAddress(): ?string {
  436. return $this->config->getUserValue($this->uid, 'settings', 'email', null);
  437. }
  438. /**
  439. * @inheritDoc
  440. */
  441. public function getPrimaryEMailAddress(): ?string {
  442. return $this->config->getUserValue($this->uid, 'settings', 'primary_email', null);
  443. }
  444. /**
  445. * get the users' quota
  446. *
  447. * @return string
  448. * @since 9.0.0
  449. */
  450. public function getQuota() {
  451. // allow apps to modify the user quota by hooking into the event
  452. $event = new GetQuotaEvent($this);
  453. $this->dispatcher->dispatchTyped($event);
  454. $overwriteQuota = $event->getQuota();
  455. if ($overwriteQuota) {
  456. $quota = $overwriteQuota;
  457. } else {
  458. $quota = $this->config->getUserValue($this->uid, 'files', 'quota', 'default');
  459. }
  460. if ($quota === 'default') {
  461. $quota = $this->config->getAppValue('files', 'default_quota', 'none');
  462. // if unlimited quota is not allowed => avoid getting 'unlimited' as default_quota fallback value
  463. // use the first preset instead
  464. $allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
  465. if (!$allowUnlimitedQuota) {
  466. $presets = $this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
  467. $presets = array_filter(array_map('trim', explode(',', $presets)));
  468. $quotaPreset = array_values(array_diff($presets, ['default', 'none']));
  469. if (count($quotaPreset) > 0) {
  470. $quota = $this->config->getAppValue('files', 'default_quota', $quotaPreset[0]);
  471. }
  472. }
  473. }
  474. return $quota;
  475. }
  476. /**
  477. * set the users' quota
  478. *
  479. * @param string $quota
  480. * @return void
  481. * @throws InvalidArgumentException
  482. * @since 9.0.0
  483. */
  484. public function setQuota($quota) {
  485. $oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', '');
  486. if ($quota !== 'none' and $quota !== 'default') {
  487. $bytesQuota = OC_Helper::computerFileSize($quota);
  488. if ($bytesQuota === false) {
  489. throw new InvalidArgumentException('Failed to set quota to invalid value ' . $quota);
  490. }
  491. $quota = OC_Helper::humanFileSize($bytesQuota);
  492. }
  493. if ($quota !== $oldQuota) {
  494. $this->config->setUserValue($this->uid, 'files', 'quota', $quota);
  495. $this->triggerChange('quota', $quota, $oldQuota);
  496. }
  497. \OC_Helper::clearStorageInfo('/' . $this->uid . '/files');
  498. }
  499. public function getManagerUids(): array {
  500. $encodedUids = $this->config->getUserValue(
  501. $this->uid,
  502. 'settings',
  503. self::CONFIG_KEY_MANAGERS,
  504. '[]'
  505. );
  506. return json_decode($encodedUids, false, 512, JSON_THROW_ON_ERROR);
  507. }
  508. public function setManagerUids(array $uids): void {
  509. $oldUids = $this->getManagerUids();
  510. $this->config->setUserValue(
  511. $this->uid,
  512. 'settings',
  513. self::CONFIG_KEY_MANAGERS,
  514. json_encode($uids, JSON_THROW_ON_ERROR)
  515. );
  516. $this->triggerChange('managers', $uids, $oldUids);
  517. }
  518. /**
  519. * get the avatar image if it exists
  520. *
  521. * @param int $size
  522. * @return IImage|null
  523. * @since 9.0.0
  524. */
  525. public function getAvatarImage($size) {
  526. // delay the initialization
  527. if (is_null($this->avatarManager)) {
  528. $this->avatarManager = \OC::$server->get(IAvatarManager::class);
  529. }
  530. $avatar = $this->avatarManager->getAvatar($this->uid);
  531. $image = $avatar->get($size);
  532. if ($image) {
  533. return $image;
  534. }
  535. return null;
  536. }
  537. /**
  538. * get the federation cloud id
  539. *
  540. * @return string
  541. * @since 9.0.0
  542. */
  543. public function getCloudId() {
  544. $uid = $this->getUID();
  545. $server = rtrim($this->urlGenerator->getAbsoluteURL('/'), '/');
  546. if (str_ends_with($server, '/index.php')) {
  547. $server = substr($server, 0, -10);
  548. }
  549. $server = $this->removeProtocolFromUrl($server);
  550. return $uid . '@' . $server;
  551. }
  552. private function removeProtocolFromUrl(string $url): string {
  553. if (str_starts_with($url, 'https://')) {
  554. return substr($url, strlen('https://'));
  555. }
  556. return $url;
  557. }
  558. public function triggerChange($feature, $value = null, $oldValue = null) {
  559. $this->dispatcher->dispatchTyped(new UserChangedEvent($this, $feature, $value, $oldValue));
  560. if ($this->emitter) {
  561. $this->emitter->emit('\OC\User', 'changeUser', [$this, $feature, $value, $oldValue]);
  562. }
  563. }
  564. }