Manager.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\User;
  8. use OC\Hooks\PublicEmitter;
  9. use OC\Memcache\WithLocalCache;
  10. use OCP\DB\QueryBuilder\IQueryBuilder;
  11. use OCP\EventDispatcher\IEventDispatcher;
  12. use OCP\HintException;
  13. use OCP\ICache;
  14. use OCP\ICacheFactory;
  15. use OCP\IConfig;
  16. use OCP\IGroup;
  17. use OCP\IUser;
  18. use OCP\IUserBackend;
  19. use OCP\IUserManager;
  20. use OCP\L10N\IFactory;
  21. use OCP\Server;
  22. use OCP\Support\Subscription\IAssertion;
  23. use OCP\User\Backend\ICheckPasswordBackend;
  24. use OCP\User\Backend\ICountUsersBackend;
  25. use OCP\User\Backend\IGetRealUIDBackend;
  26. use OCP\User\Backend\IProvideEnabledStateBackend;
  27. use OCP\User\Backend\ISearchKnownUsersBackend;
  28. use OCP\User\Events\BeforeUserCreatedEvent;
  29. use OCP\User\Events\UserCreatedEvent;
  30. use OCP\UserInterface;
  31. use Psr\Log\LoggerInterface;
  32. /**
  33. * Class Manager
  34. *
  35. * Hooks available in scope \OC\User:
  36. * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  37. * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  38. * - preDelete(\OC\User\User $user)
  39. * - postDelete(\OC\User\User $user)
  40. * - preCreateUser(string $uid, string $password)
  41. * - postCreateUser(\OC\User\User $user, string $password)
  42. * - change(\OC\User\User $user)
  43. * - assignedUserId(string $uid)
  44. * - preUnassignedUserId(string $uid)
  45. * - postUnassignedUserId(string $uid)
  46. *
  47. * @package OC\User
  48. */
  49. class Manager extends PublicEmitter implements IUserManager {
  50. /**
  51. * @var \OCP\UserInterface[] $backends
  52. */
  53. private array $backends = [];
  54. /**
  55. * @var array<string,\OC\User\User> $cachedUsers
  56. */
  57. private array $cachedUsers = [];
  58. private ICache $cache;
  59. private DisplayNameCache $displayNameCache;
  60. public function __construct(
  61. private IConfig $config,
  62. ICacheFactory $cacheFactory,
  63. private IEventDispatcher $eventDispatcher,
  64. private LoggerInterface $logger,
  65. ) {
  66. $this->cache = new WithLocalCache($cacheFactory->createDistributed('user_backend_map'));
  67. $this->listen('\OC\User', 'postDelete', function (IUser $user): void {
  68. unset($this->cachedUsers[$user->getUID()]);
  69. });
  70. $this->displayNameCache = new DisplayNameCache($cacheFactory, $this);
  71. }
  72. /**
  73. * Get the active backends
  74. * @return \OCP\UserInterface[]
  75. */
  76. public function getBackends() {
  77. return $this->backends;
  78. }
  79. /**
  80. * register a user backend
  81. *
  82. * @param \OCP\UserInterface $backend
  83. */
  84. public function registerBackend($backend) {
  85. $this->backends[] = $backend;
  86. }
  87. /**
  88. * remove a user backend
  89. *
  90. * @param \OCP\UserInterface $backend
  91. */
  92. public function removeBackend($backend) {
  93. $this->cachedUsers = [];
  94. if (($i = array_search($backend, $this->backends)) !== false) {
  95. unset($this->backends[$i]);
  96. }
  97. }
  98. /**
  99. * remove all user backends
  100. */
  101. public function clearBackends() {
  102. $this->cachedUsers = [];
  103. $this->backends = [];
  104. }
  105. /**
  106. * get a user by user id
  107. *
  108. * @param string $uid
  109. * @return \OC\User\User|null Either the user or null if the specified user does not exist
  110. */
  111. public function get($uid) {
  112. if (is_null($uid) || $uid === '' || $uid === false) {
  113. return null;
  114. }
  115. if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
  116. return $this->cachedUsers[$uid];
  117. }
  118. $cachedBackend = $this->cache->get(sha1($uid));
  119. if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) {
  120. // Cache has the info of the user backend already, so ask that one directly
  121. $backend = $this->backends[$cachedBackend];
  122. if ($backend->userExists($uid)) {
  123. return $this->getUserObject($uid, $backend);
  124. }
  125. }
  126. foreach ($this->backends as $i => $backend) {
  127. if ($i === $cachedBackend) {
  128. // Tried that one already
  129. continue;
  130. }
  131. if ($backend->userExists($uid)) {
  132. // Hash $uid to ensure that only valid characters are used for the cache key
  133. $this->cache->set(sha1($uid), $i, 300);
  134. return $this->getUserObject($uid, $backend);
  135. }
  136. }
  137. return null;
  138. }
  139. public function getDisplayName(string $uid): ?string {
  140. return $this->displayNameCache->getDisplayName($uid);
  141. }
  142. /**
  143. * get or construct the user object
  144. *
  145. * @param string $uid
  146. * @param \OCP\UserInterface $backend
  147. * @param bool $cacheUser If false the newly created user object will not be cached
  148. * @return \OC\User\User
  149. */
  150. public function getUserObject($uid, $backend, $cacheUser = true) {
  151. if ($backend instanceof IGetRealUIDBackend) {
  152. $uid = $backend->getRealUID($uid);
  153. }
  154. if (isset($this->cachedUsers[$uid])) {
  155. return $this->cachedUsers[$uid];
  156. }
  157. $user = new User($uid, $backend, $this->eventDispatcher, $this, $this->config);
  158. if ($cacheUser) {
  159. $this->cachedUsers[$uid] = $user;
  160. }
  161. return $user;
  162. }
  163. /**
  164. * check if a user exists
  165. *
  166. * @param string $uid
  167. * @return bool
  168. */
  169. public function userExists($uid) {
  170. $user = $this->get($uid);
  171. return ($user !== null);
  172. }
  173. /**
  174. * Check if the password is valid for the user
  175. *
  176. * @param string $loginName
  177. * @param string $password
  178. * @return IUser|false the User object on success, false otherwise
  179. */
  180. public function checkPassword($loginName, $password) {
  181. $result = $this->checkPasswordNoLogging($loginName, $password);
  182. if ($result === false) {
  183. $this->logger->warning('Login failed: \'' . $loginName . '\' (Remote IP: \'' . \OC::$server->getRequest()->getRemoteAddress() . '\')', ['app' => 'core']);
  184. }
  185. return $result;
  186. }
  187. /**
  188. * Check if the password is valid for the user
  189. *
  190. * @internal
  191. * @param string $loginName
  192. * @param string $password
  193. * @return IUser|false the User object on success, false otherwise
  194. */
  195. public function checkPasswordNoLogging($loginName, $password) {
  196. $loginName = str_replace("\0", '', $loginName);
  197. $password = str_replace("\0", '', $password);
  198. $cachedBackend = $this->cache->get($loginName);
  199. if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) {
  200. $backends = [$this->backends[$cachedBackend]];
  201. } else {
  202. $backends = $this->backends;
  203. }
  204. foreach ($backends as $backend) {
  205. if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) {
  206. /** @var ICheckPasswordBackend $backend */
  207. $uid = $backend->checkPassword($loginName, $password);
  208. if ($uid !== false) {
  209. return $this->getUserObject($uid, $backend);
  210. }
  211. }
  212. }
  213. // since http basic auth doesn't provide a standard way of handling non ascii password we allow password to be urlencoded
  214. // we only do this decoding after using the plain password fails to maintain compatibility with any password that happens
  215. // to contain urlencoded patterns by "accident".
  216. $password = urldecode($password);
  217. foreach ($backends as $backend) {
  218. if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) {
  219. /** @var ICheckPasswordBackend|UserInterface $backend */
  220. $uid = $backend->checkPassword($loginName, $password);
  221. if ($uid !== false) {
  222. return $this->getUserObject($uid, $backend);
  223. }
  224. }
  225. }
  226. return false;
  227. }
  228. /**
  229. * Search by user id
  230. *
  231. * @param string $pattern
  232. * @param int $limit
  233. * @param int $offset
  234. * @return IUser[]
  235. * @deprecated 27.0.0, use searchDisplayName instead
  236. */
  237. public function search($pattern, $limit = null, $offset = null) {
  238. $users = [];
  239. foreach ($this->backends as $backend) {
  240. $backendUsers = $backend->getUsers($pattern, $limit, $offset);
  241. if (is_array($backendUsers)) {
  242. foreach ($backendUsers as $uid) {
  243. $users[$uid] = new LazyUser($uid, $this, null, $backend);
  244. }
  245. }
  246. }
  247. uasort($users, function (IUser $a, IUser $b) {
  248. return strcasecmp($a->getUID(), $b->getUID());
  249. });
  250. return $users;
  251. }
  252. /**
  253. * Search by displayName
  254. *
  255. * @param string $pattern
  256. * @param int $limit
  257. * @param int $offset
  258. * @return IUser[]
  259. */
  260. public function searchDisplayName($pattern, $limit = null, $offset = null) {
  261. $users = [];
  262. foreach ($this->backends as $backend) {
  263. $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
  264. if (is_array($backendUsers)) {
  265. foreach ($backendUsers as $uid => $displayName) {
  266. $users[] = new LazyUser($uid, $this, $displayName, $backend);
  267. }
  268. }
  269. }
  270. usort($users, function (IUser $a, IUser $b) {
  271. return strcasecmp($a->getDisplayName(), $b->getDisplayName());
  272. });
  273. return $users;
  274. }
  275. /**
  276. * @return IUser[]
  277. */
  278. public function getDisabledUsers(?int $limit = null, int $offset = 0, string $search = ''): array {
  279. $users = $this->config->getUsersForUserValue('core', 'enabled', 'false');
  280. $users = array_combine(
  281. $users,
  282. array_map(
  283. fn (string $uid): IUser => new LazyUser($uid, $this),
  284. $users
  285. )
  286. );
  287. if ($search !== '') {
  288. $users = array_filter(
  289. $users,
  290. function (IUser $user) use ($search): bool {
  291. try {
  292. return mb_stripos($user->getUID(), $search) !== false ||
  293. mb_stripos($user->getDisplayName(), $search) !== false ||
  294. mb_stripos($user->getEMailAddress() ?? '', $search) !== false;
  295. } catch (NoUserException $ex) {
  296. $this->logger->error('Error while filtering disabled users', ['exception' => $ex, 'userUID' => $user->getUID()]);
  297. return false;
  298. }
  299. });
  300. }
  301. $tempLimit = ($limit === null ? null : $limit + $offset);
  302. foreach ($this->backends as $backend) {
  303. if (($tempLimit !== null) && (count($users) >= $tempLimit)) {
  304. break;
  305. }
  306. if ($backend instanceof IProvideEnabledStateBackend) {
  307. $backendUsers = $backend->getDisabledUserList(($tempLimit === null ? null : $tempLimit - count($users)), 0, $search);
  308. foreach ($backendUsers as $uid) {
  309. $users[$uid] = new LazyUser($uid, $this, null, $backend);
  310. }
  311. }
  312. }
  313. return array_slice($users, $offset, $limit);
  314. }
  315. /**
  316. * Search known users (from phonebook sync) by displayName
  317. *
  318. * @param string $searcher
  319. * @param string $pattern
  320. * @param int|null $limit
  321. * @param int|null $offset
  322. * @return IUser[]
  323. */
  324. public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array {
  325. $users = [];
  326. foreach ($this->backends as $backend) {
  327. if ($backend instanceof ISearchKnownUsersBackend) {
  328. $backendUsers = $backend->searchKnownUsersByDisplayName($searcher, $pattern, $limit, $offset);
  329. } else {
  330. // Better than nothing, but filtering after pagination can remove lots of results.
  331. $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
  332. }
  333. if (is_array($backendUsers)) {
  334. foreach ($backendUsers as $uid => $displayName) {
  335. $users[] = $this->getUserObject($uid, $backend);
  336. }
  337. }
  338. }
  339. usort($users, function ($a, $b) {
  340. /**
  341. * @var IUser $a
  342. * @var IUser $b
  343. */
  344. return strcasecmp($a->getDisplayName(), $b->getDisplayName());
  345. });
  346. return $users;
  347. }
  348. /**
  349. * @param string $uid
  350. * @param string $password
  351. * @return false|IUser the created user or false
  352. * @throws \InvalidArgumentException
  353. * @throws HintException
  354. */
  355. public function createUser($uid, $password) {
  356. // DI injection is not used here as IRegistry needs the user manager itself for user count and thus it would create a cyclic dependency
  357. /** @var IAssertion $assertion */
  358. $assertion = \OC::$server->get(IAssertion::class);
  359. $assertion->createUserIsLegit();
  360. $localBackends = [];
  361. foreach ($this->backends as $backend) {
  362. if ($backend instanceof Database) {
  363. // First check if there is another user backend
  364. $localBackends[] = $backend;
  365. continue;
  366. }
  367. if ($backend->implementsActions(Backend::CREATE_USER)) {
  368. return $this->createUserFromBackend($uid, $password, $backend);
  369. }
  370. }
  371. foreach ($localBackends as $backend) {
  372. if ($backend->implementsActions(Backend::CREATE_USER)) {
  373. return $this->createUserFromBackend($uid, $password, $backend);
  374. }
  375. }
  376. return false;
  377. }
  378. /**
  379. * @param string $uid
  380. * @param string $password
  381. * @param UserInterface $backend
  382. * @return IUser|false
  383. * @throws \InvalidArgumentException
  384. */
  385. public function createUserFromBackend($uid, $password, UserInterface $backend) {
  386. $l = \OCP\Util::getL10N('lib');
  387. $this->validateUserId($uid, true);
  388. // No empty password
  389. if (trim($password) === '') {
  390. throw new \InvalidArgumentException($l->t('A valid password must be provided'));
  391. }
  392. // Check if user already exists
  393. if ($this->userExists($uid)) {
  394. throw new \InvalidArgumentException($l->t('The Login is already being used'));
  395. }
  396. /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
  397. $this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
  398. $this->eventDispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
  399. $state = $backend->createUser($uid, $password);
  400. if ($state === false) {
  401. throw new \InvalidArgumentException($l->t('Could not create account'));
  402. }
  403. $user = $this->getUserObject($uid, $backend);
  404. if ($user instanceof IUser) {
  405. /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
  406. $this->emit('\OC\User', 'postCreateUser', [$user, $password]);
  407. $this->eventDispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
  408. return $user;
  409. }
  410. return false;
  411. }
  412. /**
  413. * returns how many users per backend exist (if supported by backend)
  414. *
  415. * @param boolean $hasLoggedIn when true only users that have a lastLogin
  416. * entry in the preferences table will be affected
  417. * @return array<string, int> an array of backend class as key and count number as value
  418. */
  419. public function countUsers() {
  420. $userCountStatistics = [];
  421. foreach ($this->backends as $backend) {
  422. if ($backend instanceof ICountUsersBackend || $backend->implementsActions(Backend::COUNT_USERS)) {
  423. /** @var ICountUsersBackend|IUserBackend $backend */
  424. $backendUsers = $backend->countUsers();
  425. if ($backendUsers !== false) {
  426. if ($backend instanceof IUserBackend) {
  427. $name = $backend->getBackendName();
  428. } else {
  429. $name = get_class($backend);
  430. }
  431. if (isset($userCountStatistics[$name])) {
  432. $userCountStatistics[$name] += $backendUsers;
  433. } else {
  434. $userCountStatistics[$name] = $backendUsers;
  435. }
  436. }
  437. }
  438. }
  439. return $userCountStatistics;
  440. }
  441. /**
  442. * returns how many users per backend exist in the requested groups (if supported by backend)
  443. *
  444. * @param IGroup[] $groups an array of gid to search in
  445. * @return array|int an array of backend class as key and count number as value
  446. * if $hasLoggedIn is true only an int is returned
  447. */
  448. public function countUsersOfGroups(array $groups) {
  449. $users = [];
  450. foreach ($groups as $group) {
  451. $usersIds = array_map(function ($user) {
  452. return $user->getUID();
  453. }, $group->getUsers());
  454. $users = array_merge($users, $usersIds);
  455. }
  456. return count(array_unique($users));
  457. }
  458. /**
  459. * The callback is executed for each user on each backend.
  460. * If the callback returns false no further users will be retrieved.
  461. *
  462. * @psalm-param \Closure(\OCP\IUser):?bool $callback
  463. * @param string $search
  464. * @param boolean $onlySeen when true only users that have a lastLogin entry
  465. * in the preferences table will be affected
  466. * @since 9.0.0
  467. */
  468. public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
  469. if ($onlySeen) {
  470. $this->callForSeenUsers($callback);
  471. } else {
  472. foreach ($this->getBackends() as $backend) {
  473. $limit = 500;
  474. $offset = 0;
  475. do {
  476. $users = $backend->getUsers($search, $limit, $offset);
  477. foreach ($users as $uid) {
  478. if (!$backend->userExists($uid)) {
  479. continue;
  480. }
  481. $user = $this->getUserObject($uid, $backend, false);
  482. $return = $callback($user);
  483. if ($return === false) {
  484. break;
  485. }
  486. }
  487. $offset += $limit;
  488. } while (count($users) >= $limit);
  489. }
  490. }
  491. }
  492. /**
  493. * returns how many users are disabled
  494. *
  495. * @return int
  496. * @since 12.0.0
  497. */
  498. public function countDisabledUsers(): int {
  499. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  500. $queryBuilder->select($queryBuilder->func()->count('*'))
  501. ->from('preferences')
  502. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
  503. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
  504. ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
  505. $result = $queryBuilder->execute();
  506. $count = $result->fetchOne();
  507. $result->closeCursor();
  508. if ($count !== false) {
  509. $count = (int)$count;
  510. } else {
  511. $count = 0;
  512. }
  513. return $count;
  514. }
  515. /**
  516. * returns how many users are disabled in the requested groups
  517. *
  518. * @param array $groups groupids to search
  519. * @return int
  520. * @since 14.0.0
  521. */
  522. public function countDisabledUsersOfGroups(array $groups): int {
  523. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  524. $queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
  525. ->from('preferences', 'p')
  526. ->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
  527. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
  528. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
  529. ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
  530. ->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
  531. $result = $queryBuilder->execute();
  532. $count = $result->fetchOne();
  533. $result->closeCursor();
  534. if ($count !== false) {
  535. $count = (int)$count;
  536. } else {
  537. $count = 0;
  538. }
  539. return $count;
  540. }
  541. /**
  542. * returns how many users have logged in once
  543. *
  544. * @return int
  545. * @since 11.0.0
  546. */
  547. public function countSeenUsers() {
  548. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  549. $queryBuilder->select($queryBuilder->func()->count('*'))
  550. ->from('preferences')
  551. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
  552. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')));
  553. $query = $queryBuilder->execute();
  554. $result = (int)$query->fetchOne();
  555. $query->closeCursor();
  556. return $result;
  557. }
  558. /**
  559. * @param \Closure $callback
  560. * @psalm-param \Closure(\OCP\IUser):?bool $callback
  561. * @since 11.0.0
  562. */
  563. public function callForSeenUsers(\Closure $callback) {
  564. $limit = 1000;
  565. $offset = 0;
  566. do {
  567. $userIds = $this->getSeenUserIds($limit, $offset);
  568. $offset += $limit;
  569. foreach ($userIds as $userId) {
  570. foreach ($this->backends as $backend) {
  571. if ($backend->userExists($userId)) {
  572. $user = $this->getUserObject($userId, $backend, false);
  573. $return = $callback($user);
  574. if ($return === false) {
  575. return;
  576. }
  577. break;
  578. }
  579. }
  580. }
  581. } while (count($userIds) >= $limit);
  582. }
  583. /**
  584. * Getting all userIds that have a listLogin value requires checking the
  585. * value in php because on oracle you cannot use a clob in a where clause,
  586. * preventing us from doing a not null or length(value) > 0 check.
  587. *
  588. * @param int $limit
  589. * @param int $offset
  590. * @return string[] with user ids
  591. */
  592. private function getSeenUserIds($limit = null, $offset = null) {
  593. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  594. $queryBuilder->select(['userid'])
  595. ->from('preferences')
  596. ->where($queryBuilder->expr()->eq(
  597. 'appid', $queryBuilder->createNamedParameter('login'))
  598. )
  599. ->andWhere($queryBuilder->expr()->eq(
  600. 'configkey', $queryBuilder->createNamedParameter('lastLogin'))
  601. )
  602. ->andWhere($queryBuilder->expr()->isNotNull('configvalue')
  603. );
  604. if ($limit !== null) {
  605. $queryBuilder->setMaxResults($limit);
  606. }
  607. if ($offset !== null) {
  608. $queryBuilder->setFirstResult($offset);
  609. }
  610. $query = $queryBuilder->execute();
  611. $result = [];
  612. while ($row = $query->fetch()) {
  613. $result[] = $row['userid'];
  614. }
  615. $query->closeCursor();
  616. return $result;
  617. }
  618. /**
  619. * @param string $email
  620. * @return IUser[]
  621. * @since 9.1.0
  622. */
  623. public function getByEmail($email) {
  624. // looking for 'email' only (and not primary_mail) is intentional
  625. $userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
  626. $users = array_map(function ($uid) {
  627. return $this->get($uid);
  628. }, $userIds);
  629. return array_values(array_filter($users, function ($u) {
  630. return ($u instanceof IUser);
  631. }));
  632. }
  633. /**
  634. * @param string $uid
  635. * @param bool $checkDataDirectory
  636. * @throws \InvalidArgumentException Message is an already translated string with a reason why the id is not valid
  637. * @since 26.0.0
  638. */
  639. public function validateUserId(string $uid, bool $checkDataDirectory = false): void {
  640. $l = Server::get(IFactory::class)->get('lib');
  641. // Check the name for bad characters
  642. // Allowed are: "a-z", "A-Z", "0-9", spaces and "_.@-'"
  643. if (preg_match('/[^a-zA-Z0-9 _.@\-\']/', $uid)) {
  644. throw new \InvalidArgumentException($l->t('Only the following characters are allowed in an Login:'
  645. . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'));
  646. }
  647. // No empty username
  648. if (trim($uid) === '') {
  649. throw new \InvalidArgumentException($l->t('A valid Login must be provided'));
  650. }
  651. // No whitespace at the beginning or at the end
  652. if (trim($uid) !== $uid) {
  653. throw new \InvalidArgumentException($l->t('Login contains whitespace at the beginning or at the end'));
  654. }
  655. // Username only consists of 1 or 2 dots (directory traversal)
  656. if ($uid === '.' || $uid === '..') {
  657. throw new \InvalidArgumentException($l->t('Login must not consist of dots only'));
  658. }
  659. if (!$this->verifyUid($uid, $checkDataDirectory)) {
  660. throw new \InvalidArgumentException($l->t('Login is invalid because files already exist for this user'));
  661. }
  662. }
  663. /**
  664. * Gets the list of user ids sorted by lastLogin, from most recent to least recent
  665. *
  666. * @param int|null $limit how many users to fetch
  667. * @param int $offset from which offset to fetch
  668. * @param string $search search users based on search params
  669. * @return list<string> list of user IDs
  670. */
  671. public function getLastLoggedInUsers(?int $limit = null, int $offset = 0, string $search = ''): array {
  672. $connection = \OC::$server->getDatabaseConnection();
  673. $queryBuilder = $connection->getQueryBuilder();
  674. $queryBuilder->selectDistinct('uid')
  675. ->from('users', 'u')
  676. ->leftJoin('u', 'preferences', 'p', $queryBuilder->expr()->andX(
  677. $queryBuilder->expr()->eq('p.userid', 'uid'),
  678. $queryBuilder->expr()->eq('p.appid', $queryBuilder->expr()->literal('login')),
  679. $queryBuilder->expr()->eq('p.configkey', $queryBuilder->expr()->literal('lastLogin')))
  680. );
  681. if ($search !== '') {
  682. $queryBuilder->leftJoin('u', 'preferences', 'p1', $queryBuilder->expr()->andX(
  683. $queryBuilder->expr()->eq('p1.userid', 'uid'),
  684. $queryBuilder->expr()->eq('p1.appid', $queryBuilder->expr()->literal('settings')),
  685. $queryBuilder->expr()->eq('p1.configkey', $queryBuilder->expr()->literal('email')))
  686. )
  687. // sqlite doesn't like re-using a single named parameter here
  688. ->where($queryBuilder->expr()->iLike('uid', $queryBuilder->createPositionalParameter('%' . $connection->escapeLikeParameter($search) . '%')))
  689. ->orWhere($queryBuilder->expr()->iLike('displayname', $queryBuilder->createPositionalParameter('%' . $connection->escapeLikeParameter($search) . '%')))
  690. ->orWhere($queryBuilder->expr()->iLike('p1.configvalue', $queryBuilder->createPositionalParameter('%' . $connection->escapeLikeParameter($search) . '%'))
  691. );
  692. }
  693. $queryBuilder->orderBy($queryBuilder->func()->lower('p.configvalue'), 'DESC')
  694. ->addOrderBy('uid_lower', 'ASC')
  695. ->setFirstResult($offset)
  696. ->setMaxResults($limit);
  697. $result = $queryBuilder->executeQuery();
  698. /** @var list<string> $uids */
  699. $uids = $result->fetchAll(\PDO::FETCH_COLUMN);
  700. $result->closeCursor();
  701. return $uids;
  702. }
  703. private function verifyUid(string $uid, bool $checkDataDirectory = false): bool {
  704. $appdata = 'appdata_' . $this->config->getSystemValueString('instanceid');
  705. if (\in_array($uid, [
  706. '.htaccess',
  707. 'files_external',
  708. '__groupfolders',
  709. '.ncdata',
  710. 'owncloud.log',
  711. 'nextcloud.log',
  712. 'updater.log',
  713. 'audit.log',
  714. $appdata], true)) {
  715. return false;
  716. }
  717. if (!$checkDataDirectory) {
  718. return true;
  719. }
  720. $dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
  721. return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid);
  722. }
  723. public function getDisplayNameCache(): DisplayNameCache {
  724. return $this->displayNameCache;
  725. }
  726. }