User.php 19 KB

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