User.php 18 KB

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