User.php 17 KB

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