User.php 18 KB

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