1
0

Manager.php 22 KB

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