User.php 18 KB

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