1
0

Manager.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Georg Ehrke <oc.list@georgehrke.com>
  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 Lukas Reschke <lukas@statuscode.ch>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. * @author Vincent Chan <plus.vincchan@gmail.com>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OC\User;
  35. use OC\Hooks\PublicEmitter;
  36. use OCP\DB\QueryBuilder\IQueryBuilder;
  37. use OCP\EventDispatcher\IEventDispatcher;
  38. use OCP\HintException;
  39. use OCP\ICache;
  40. use OCP\ICacheFactory;
  41. use OCP\IConfig;
  42. use OCP\IGroup;
  43. use OCP\IUser;
  44. use OCP\IUserBackend;
  45. use OCP\IUserManager;
  46. use OCP\Support\Subscription\IAssertion;
  47. use OCP\User\Backend\IGetRealUIDBackend;
  48. use OCP\User\Backend\ISearchKnownUsersBackend;
  49. use OCP\User\Backend\ICheckPasswordBackend;
  50. use OCP\User\Backend\ICountUsersBackend;
  51. use OCP\User\Events\BeforeUserCreatedEvent;
  52. use OCP\User\Events\UserCreatedEvent;
  53. use OCP\UserInterface;
  54. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  55. /**
  56. * Class Manager
  57. *
  58. * Hooks available in scope \OC\User:
  59. * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  60. * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  61. * - preDelete(\OC\User\User $user)
  62. * - postDelete(\OC\User\User $user)
  63. * - preCreateUser(string $uid, string $password)
  64. * - postCreateUser(\OC\User\User $user, string $password)
  65. * - change(\OC\User\User $user)
  66. * - assignedUserId(string $uid)
  67. * - preUnassignedUserId(string $uid)
  68. * - postUnassignedUserId(string $uid)
  69. *
  70. * @package OC\User
  71. */
  72. class Manager extends PublicEmitter implements IUserManager {
  73. /**
  74. * @var \OCP\UserInterface[] $backends
  75. */
  76. private $backends = [];
  77. /**
  78. * @var \OC\User\User[] $cachedUsers
  79. */
  80. private $cachedUsers = [];
  81. /** @var IConfig */
  82. private $config;
  83. /** @var EventDispatcherInterface */
  84. private $dispatcher;
  85. /** @var ICache */
  86. private $cache;
  87. /** @var IEventDispatcher */
  88. private $eventDispatcher;
  89. private DisplayNameCache $displayNameCache;
  90. public function __construct(IConfig $config,
  91. EventDispatcherInterface $oldDispatcher,
  92. ICacheFactory $cacheFactory,
  93. IEventDispatcher $eventDispatcher) {
  94. $this->config = $config;
  95. $this->dispatcher = $oldDispatcher;
  96. $this->cache = $cacheFactory->createDistributed('user_backend_map');
  97. $cachedUsers = &$this->cachedUsers;
  98. $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
  99. /** @var \OC\User\User $user */
  100. unset($cachedUsers[$user->getUID()]);
  101. });
  102. $this->eventDispatcher = $eventDispatcher;
  103. $this->displayNameCache = new DisplayNameCache($cacheFactory, $this);
  104. }
  105. /**
  106. * Get the active backends
  107. * @return \OCP\UserInterface[]
  108. */
  109. public function getBackends() {
  110. return $this->backends;
  111. }
  112. /**
  113. * register a user backend
  114. *
  115. * @param \OCP\UserInterface $backend
  116. */
  117. public function registerBackend($backend) {
  118. $this->backends[] = $backend;
  119. }
  120. /**
  121. * remove a user backend
  122. *
  123. * @param \OCP\UserInterface $backend
  124. */
  125. public function removeBackend($backend) {
  126. $this->cachedUsers = [];
  127. if (($i = array_search($backend, $this->backends)) !== false) {
  128. unset($this->backends[$i]);
  129. }
  130. }
  131. /**
  132. * remove all user backends
  133. */
  134. public function clearBackends() {
  135. $this->cachedUsers = [];
  136. $this->backends = [];
  137. }
  138. /**
  139. * get a user by user id
  140. *
  141. * @param string $uid
  142. * @return \OC\User\User|null Either the user or null if the specified user does not exist
  143. */
  144. public function get($uid) {
  145. if (is_null($uid) || $uid === '' || $uid === false) {
  146. return null;
  147. }
  148. if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
  149. return $this->cachedUsers[$uid];
  150. }
  151. $cachedBackend = $this->cache->get(sha1($uid));
  152. if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) {
  153. // Cache has the info of the user backend already, so ask that one directly
  154. $backend = $this->backends[$cachedBackend];
  155. if ($backend->userExists($uid)) {
  156. return $this->getUserObject($uid, $backend);
  157. }
  158. }
  159. foreach ($this->backends as $i => $backend) {
  160. if ($i === $cachedBackend) {
  161. // Tried that one already
  162. continue;
  163. }
  164. if ($backend->userExists($uid)) {
  165. // Hash $uid to ensure that only valid characters are used for the cache key
  166. $this->cache->set(sha1($uid), $i, 300);
  167. return $this->getUserObject($uid, $backend);
  168. }
  169. }
  170. return null;
  171. }
  172. public function getDisplayName(string $uid): ?string {
  173. return $this->displayNameCache->getDisplayName($uid);
  174. }
  175. /**
  176. * get or construct the user object
  177. *
  178. * @param string $uid
  179. * @param \OCP\UserInterface $backend
  180. * @param bool $cacheUser If false the newly created user object will not be cached
  181. * @return \OC\User\User
  182. */
  183. protected function getUserObject($uid, $backend, $cacheUser = true) {
  184. if ($backend instanceof IGetRealUIDBackend) {
  185. $uid = $backend->getRealUID($uid);
  186. }
  187. if (isset($this->cachedUsers[$uid])) {
  188. return $this->cachedUsers[$uid];
  189. }
  190. $user = new User($uid, $backend, $this->dispatcher, $this, $this->config);
  191. if ($cacheUser) {
  192. $this->cachedUsers[$uid] = $user;
  193. }
  194. return $user;
  195. }
  196. /**
  197. * check if a user exists
  198. *
  199. * @param string $uid
  200. * @return bool
  201. */
  202. public function userExists($uid) {
  203. $user = $this->get($uid);
  204. return ($user !== null);
  205. }
  206. /**
  207. * Check if the password is valid for the user
  208. *
  209. * @param string $loginName
  210. * @param string $password
  211. * @return IUser|false the User object on success, false otherwise
  212. */
  213. public function checkPassword($loginName, $password) {
  214. $result = $this->checkPasswordNoLogging($loginName, $password);
  215. if ($result === false) {
  216. \OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
  217. }
  218. return $result;
  219. }
  220. /**
  221. * Check if the password is valid for the user
  222. *
  223. * @internal
  224. * @param string $loginName
  225. * @param string $password
  226. * @return IUser|false the User object on success, false otherwise
  227. */
  228. public function checkPasswordNoLogging($loginName, $password) {
  229. $loginName = str_replace("\0", '', $loginName);
  230. $password = str_replace("\0", '', $password);
  231. $cachedBackend = $this->cache->get($loginName);
  232. if ($cachedBackend !== null && isset($this->backends[$cachedBackend])) {
  233. $backends = [$this->backends[$cachedBackend]];
  234. } else {
  235. $backends = $this->backends;
  236. }
  237. foreach ($backends as $backend) {
  238. if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) {
  239. /** @var ICheckPasswordBackend $backend */
  240. $uid = $backend->checkPassword($loginName, $password);
  241. if ($uid !== false) {
  242. return $this->getUserObject($uid, $backend);
  243. }
  244. }
  245. }
  246. // since http basic auth doesn't provide a standard way of handling non ascii password we allow password to be urlencoded
  247. // we only do this decoding after using the plain password fails to maintain compatibility with any password that happens
  248. // to contain urlencoded patterns by "accident".
  249. $password = urldecode($password);
  250. foreach ($backends as $backend) {
  251. if ($backend instanceof ICheckPasswordBackend || $backend->implementsActions(Backend::CHECK_PASSWORD)) {
  252. /** @var ICheckPasswordBackend|UserInterface $backend */
  253. $uid = $backend->checkPassword($loginName, $password);
  254. if ($uid !== false) {
  255. return $this->getUserObject($uid, $backend);
  256. }
  257. }
  258. }
  259. return false;
  260. }
  261. /**
  262. * search by user id
  263. *
  264. * @param string $pattern
  265. * @param int $limit
  266. * @param int $offset
  267. * @return \OC\User\User[]
  268. */
  269. public function search($pattern, $limit = null, $offset = null) {
  270. $users = [];
  271. foreach ($this->backends as $backend) {
  272. $backendUsers = $backend->getUsers($pattern, $limit, $offset);
  273. if (is_array($backendUsers)) {
  274. foreach ($backendUsers as $uid) {
  275. $users[$uid] = $this->getUserObject($uid, $backend);
  276. }
  277. }
  278. }
  279. uasort($users, function ($a, $b) {
  280. /**
  281. * @var \OC\User\User $a
  282. * @var \OC\User\User $b
  283. */
  284. return strcasecmp($a->getUID(), $b->getUID());
  285. });
  286. return $users;
  287. }
  288. /**
  289. * search by displayName
  290. *
  291. * @param string $pattern
  292. * @param int $limit
  293. * @param int $offset
  294. * @return \OC\User\User[]
  295. */
  296. public function searchDisplayName($pattern, $limit = null, $offset = null) {
  297. $users = [];
  298. foreach ($this->backends as $backend) {
  299. $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
  300. if (is_array($backendUsers)) {
  301. foreach ($backendUsers as $uid => $displayName) {
  302. $users[] = $this->getUserObject($uid, $backend);
  303. }
  304. }
  305. }
  306. usort($users, function ($a, $b) {
  307. /**
  308. * @var \OC\User\User $a
  309. * @var \OC\User\User $b
  310. */
  311. return strcasecmp($a->getDisplayName(), $b->getDisplayName());
  312. });
  313. return $users;
  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 = \OC::$server->getL10N('lib');
  387. // Check the name for bad characters
  388. // Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
  389. if (preg_match('/[^a-zA-Z0-9 _.@\-\']/', $uid)) {
  390. throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
  391. . ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
  392. }
  393. // No empty username
  394. if (trim($uid) === '') {
  395. throw new \InvalidArgumentException($l->t('A valid username must be provided'));
  396. }
  397. // No whitespace at the beginning or at the end
  398. if (trim($uid) !== $uid) {
  399. throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
  400. }
  401. // Username only consists of 1 or 2 dots (directory traversal)
  402. if ($uid === '.' || $uid === '..') {
  403. throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
  404. }
  405. if (!$this->verifyUid($uid)) {
  406. throw new \InvalidArgumentException($l->t('Username is invalid because files already exist for this user'));
  407. }
  408. // No empty password
  409. if (trim($password) === '') {
  410. throw new \InvalidArgumentException($l->t('A valid password must be provided'));
  411. }
  412. // Check if user already exists
  413. if ($this->userExists($uid)) {
  414. throw new \InvalidArgumentException($l->t('The username is already being used'));
  415. }
  416. /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
  417. $this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
  418. $this->eventDispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
  419. $state = $backend->createUser($uid, $password);
  420. if ($state === false) {
  421. throw new \InvalidArgumentException($l->t('Could not create user'));
  422. }
  423. $user = $this->getUserObject($uid, $backend);
  424. if ($user instanceof IUser) {
  425. /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
  426. $this->emit('\OC\User', 'postCreateUser', [$user, $password]);
  427. $this->eventDispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
  428. return $user;
  429. }
  430. return false;
  431. }
  432. /**
  433. * returns how many users per backend exist (if supported by backend)
  434. *
  435. * @param boolean $hasLoggedIn when true only users that have a lastLogin
  436. * entry in the preferences table will be affected
  437. * @return array<string, int> an array of backend class as key and count number as value
  438. */
  439. public function countUsers() {
  440. $userCountStatistics = [];
  441. foreach ($this->backends as $backend) {
  442. if ($backend instanceof ICountUsersBackend || $backend->implementsActions(Backend::COUNT_USERS)) {
  443. /** @var ICountUsersBackend|IUserBackend $backend */
  444. $backendUsers = $backend->countUsers();
  445. if ($backendUsers !== false) {
  446. if ($backend instanceof IUserBackend) {
  447. $name = $backend->getBackendName();
  448. } else {
  449. $name = get_class($backend);
  450. }
  451. if (isset($userCountStatistics[$name])) {
  452. $userCountStatistics[$name] += $backendUsers;
  453. } else {
  454. $userCountStatistics[$name] = $backendUsers;
  455. }
  456. }
  457. }
  458. }
  459. return $userCountStatistics;
  460. }
  461. /**
  462. * returns how many users per backend exist in the requested groups (if supported by backend)
  463. *
  464. * @param IGroup[] $groups an array of gid to search in
  465. * @return array|int an array of backend class as key and count number as value
  466. * if $hasLoggedIn is true only an int is returned
  467. */
  468. public function countUsersOfGroups(array $groups) {
  469. $users = [];
  470. foreach ($groups as $group) {
  471. $usersIds = array_map(function ($user) {
  472. return $user->getUID();
  473. }, $group->getUsers());
  474. $users = array_merge($users, $usersIds);
  475. }
  476. return count(array_unique($users));
  477. }
  478. /**
  479. * The callback is executed for each user on each backend.
  480. * If the callback returns false no further users will be retrieved.
  481. *
  482. * @psalm-param \Closure(\OCP\IUser):?bool $callback
  483. * @param string $search
  484. * @param boolean $onlySeen when true only users that have a lastLogin entry
  485. * in the preferences table will be affected
  486. * @since 9.0.0
  487. */
  488. public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
  489. if ($onlySeen) {
  490. $this->callForSeenUsers($callback);
  491. } else {
  492. foreach ($this->getBackends() as $backend) {
  493. $limit = 500;
  494. $offset = 0;
  495. do {
  496. $users = $backend->getUsers($search, $limit, $offset);
  497. foreach ($users as $uid) {
  498. if (!$backend->userExists($uid)) {
  499. continue;
  500. }
  501. $user = $this->getUserObject($uid, $backend, false);
  502. $return = $callback($user);
  503. if ($return === false) {
  504. break;
  505. }
  506. }
  507. $offset += $limit;
  508. } while (count($users) >= $limit);
  509. }
  510. }
  511. }
  512. /**
  513. * returns how many users are disabled
  514. *
  515. * @return int
  516. * @since 12.0.0
  517. */
  518. public function countDisabledUsers(): int {
  519. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  520. $queryBuilder->select($queryBuilder->func()->count('*'))
  521. ->from('preferences')
  522. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
  523. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
  524. ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
  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 are disabled in the requested groups
  537. *
  538. * @param array $groups groupids to search
  539. * @return int
  540. * @since 14.0.0
  541. */
  542. public function countDisabledUsersOfGroups(array $groups): int {
  543. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  544. $queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
  545. ->from('preferences', 'p')
  546. ->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
  547. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
  548. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
  549. ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
  550. ->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
  551. $result = $queryBuilder->execute();
  552. $count = $result->fetchOne();
  553. $result->closeCursor();
  554. if ($count !== false) {
  555. $count = (int)$count;
  556. } else {
  557. $count = 0;
  558. }
  559. return $count;
  560. }
  561. /**
  562. * returns how many users have logged in once
  563. *
  564. * @return int
  565. * @since 11.0.0
  566. */
  567. public function countSeenUsers() {
  568. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  569. $queryBuilder->select($queryBuilder->func()->count('*'))
  570. ->from('preferences')
  571. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
  572. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')));
  573. $query = $queryBuilder->execute();
  574. $result = (int)$query->fetchOne();
  575. $query->closeCursor();
  576. return $result;
  577. }
  578. /**
  579. * @param \Closure $callback
  580. * @psalm-param \Closure(\OCP\IUser):?bool $callback
  581. * @since 11.0.0
  582. */
  583. public function callForSeenUsers(\Closure $callback) {
  584. $limit = 1000;
  585. $offset = 0;
  586. do {
  587. $userIds = $this->getSeenUserIds($limit, $offset);
  588. $offset += $limit;
  589. foreach ($userIds as $userId) {
  590. foreach ($this->backends as $backend) {
  591. if ($backend->userExists($userId)) {
  592. $user = $this->getUserObject($userId, $backend, false);
  593. $return = $callback($user);
  594. if ($return === false) {
  595. return;
  596. }
  597. break;
  598. }
  599. }
  600. }
  601. } while (count($userIds) >= $limit);
  602. }
  603. /**
  604. * Getting all userIds that have a listLogin value requires checking the
  605. * value in php because on oracle you cannot use a clob in a where clause,
  606. * preventing us from doing a not null or length(value) > 0 check.
  607. *
  608. * @param int $limit
  609. * @param int $offset
  610. * @return string[] with user ids
  611. */
  612. private function getSeenUserIds($limit = null, $offset = null) {
  613. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  614. $queryBuilder->select(['userid'])
  615. ->from('preferences')
  616. ->where($queryBuilder->expr()->eq(
  617. 'appid', $queryBuilder->createNamedParameter('login'))
  618. )
  619. ->andWhere($queryBuilder->expr()->eq(
  620. 'configkey', $queryBuilder->createNamedParameter('lastLogin'))
  621. )
  622. ->andWhere($queryBuilder->expr()->isNotNull('configvalue')
  623. );
  624. if ($limit !== null) {
  625. $queryBuilder->setMaxResults($limit);
  626. }
  627. if ($offset !== null) {
  628. $queryBuilder->setFirstResult($offset);
  629. }
  630. $query = $queryBuilder->execute();
  631. $result = [];
  632. while ($row = $query->fetch()) {
  633. $result[] = $row['userid'];
  634. }
  635. $query->closeCursor();
  636. return $result;
  637. }
  638. /**
  639. * @param string $email
  640. * @return IUser[]
  641. * @since 9.1.0
  642. */
  643. public function getByEmail($email) {
  644. // looking for 'email' only (and not primary_mail) is intentional
  645. $userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
  646. $users = array_map(function ($uid) {
  647. return $this->get($uid);
  648. }, $userIds);
  649. return array_values(array_filter($users, function ($u) {
  650. return ($u instanceof IUser);
  651. }));
  652. }
  653. private function verifyUid(string $uid): bool {
  654. $appdata = 'appdata_' . $this->config->getSystemValueString('instanceid');
  655. if (\in_array($uid, [
  656. '.htaccess',
  657. 'files_external',
  658. '__groupfolders',
  659. '.ocdata',
  660. 'owncloud.log',
  661. 'nextcloud.log',
  662. $appdata], true)) {
  663. return false;
  664. }
  665. $dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
  666. return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid);
  667. }
  668. public function getDisplayNameCache(): DisplayNameCache {
  669. return $this->displayNameCache;
  670. }
  671. }