You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

User.php 17KB

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