1
0

Manager.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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 OC\Memcache\WithLocalCache;
  37. use OCP\DB\QueryBuilder\IQueryBuilder;
  38. use OCP\EventDispatcher\IEventDispatcher;
  39. use OCP\HintException;
  40. use OCP\ICache;
  41. use OCP\ICacheFactory;
  42. use OCP\IConfig;
  43. use OCP\IGroup;
  44. use OCP\IUser;
  45. use OCP\IUserBackend;
  46. use OCP\IUserManager;
  47. use OCP\L10N\IFactory;
  48. use OCP\Server;
  49. use OCP\Support\Subscription\IAssertion;
  50. use OCP\User\Backend\ICheckPasswordBackend;
  51. use OCP\User\Backend\ICountUsersBackend;
  52. use OCP\User\Backend\IGetRealUIDBackend;
  53. use OCP\User\Backend\IProvideEnabledStateBackend;
  54. use OCP\User\Backend\ISearchKnownUsersBackend;
  55. use OCP\User\Events\BeforeUserCreatedEvent;
  56. use OCP\User\Events\UserCreatedEvent;
  57. use OCP\UserInterface;
  58. use Psr\Log\LoggerInterface;
  59. /**
  60. * Class Manager
  61. *
  62. * Hooks available in scope \OC\User:
  63. * - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  64. * - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
  65. * - preDelete(\OC\User\User $user)
  66. * - postDelete(\OC\User\User $user)
  67. * - preCreateUser(string $uid, string $password)
  68. * - postCreateUser(\OC\User\User $user, string $password)
  69. * - change(\OC\User\User $user)
  70. * - assignedUserId(string $uid)
  71. * - preUnassignedUserId(string $uid)
  72. * - postUnassignedUserId(string $uid)
  73. *
  74. * @package OC\User
  75. */
  76. class Manager extends PublicEmitter implements IUserManager {
  77. /**
  78. * @var \OCP\UserInterface[] $backends
  79. */
  80. private $backends = [];
  81. /**
  82. * @var \OC\User\User[] $cachedUsers
  83. */
  84. private $cachedUsers = [];
  85. /** @var IConfig */
  86. private $config;
  87. /** @var ICache */
  88. private $cache;
  89. /** @var IEventDispatcher */
  90. private $eventDispatcher;
  91. private DisplayNameCache $displayNameCache;
  92. public function __construct(IConfig $config,
  93. ICacheFactory $cacheFactory,
  94. IEventDispatcher $eventDispatcher) {
  95. $this->config = $config;
  96. $this->cache = new WithLocalCache($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. public 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->eventDispatcher, $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. \OCP\Server::get(LoggerInterface::class)->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 IUser[]
  268. * @deprecated since 27.0.0, use searchDisplayName instead
  269. */
  270. public function search($pattern, $limit = null, $offset = null) {
  271. $users = [];
  272. foreach ($this->backends as $backend) {
  273. $backendUsers = $backend->getUsers($pattern, $limit, $offset);
  274. if (is_array($backendUsers)) {
  275. foreach ($backendUsers as $uid) {
  276. $users[$uid] = new LazyUser($uid, $this, null, $backend);
  277. }
  278. }
  279. }
  280. uasort($users, function (IUser $a, IUser $b) {
  281. return strcasecmp($a->getUID(), $b->getUID());
  282. });
  283. return $users;
  284. }
  285. /**
  286. * Search by displayName
  287. *
  288. * @param string $pattern
  289. * @param int $limit
  290. * @param int $offset
  291. * @return IUser[]
  292. */
  293. public function searchDisplayName($pattern, $limit = null, $offset = null) {
  294. $users = [];
  295. foreach ($this->backends as $backend) {
  296. $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
  297. if (is_array($backendUsers)) {
  298. foreach ($backendUsers as $uid => $displayName) {
  299. $users[] = new LazyUser($uid, $this, $displayName, $backend);
  300. }
  301. }
  302. }
  303. usort($users, function (IUser $a, IUser $b) {
  304. return strcasecmp($a->getDisplayName(), $b->getDisplayName());
  305. });
  306. return $users;
  307. }
  308. /**
  309. * @return IUser[]
  310. */
  311. public function getDisabledUsers(?int $limit = null, int $offset = 0): array {
  312. $users = $this->config->getUsersForUserValue('core', 'enabled', 'false');
  313. $users = array_combine(
  314. $users,
  315. array_map(
  316. fn (string $uid): IUser => new LazyUser($uid, $this),
  317. $users
  318. )
  319. );
  320. $tempLimit = ($limit === null ? null : $limit + $offset);
  321. foreach ($this->backends as $backend) {
  322. if (($tempLimit !== null) && (count($users) >= $tempLimit)) {
  323. break;
  324. }
  325. if ($backend instanceof IProvideEnabledStateBackend) {
  326. $backendUsers = $backend->getDisabledUserList(($tempLimit === null ? null : $tempLimit - count($users)));
  327. foreach ($backendUsers as $uid) {
  328. $users[$uid] = new LazyUser($uid, $this, null, $backend);
  329. }
  330. }
  331. }
  332. return array_slice($users, $offset, $limit);
  333. }
  334. /**
  335. * Search known users (from phonebook sync) by displayName
  336. *
  337. * @param string $searcher
  338. * @param string $pattern
  339. * @param int|null $limit
  340. * @param int|null $offset
  341. * @return IUser[]
  342. */
  343. public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array {
  344. $users = [];
  345. foreach ($this->backends as $backend) {
  346. if ($backend instanceof ISearchKnownUsersBackend) {
  347. $backendUsers = $backend->searchKnownUsersByDisplayName($searcher, $pattern, $limit, $offset);
  348. } else {
  349. // Better than nothing, but filtering after pagination can remove lots of results.
  350. $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
  351. }
  352. if (is_array($backendUsers)) {
  353. foreach ($backendUsers as $uid => $displayName) {
  354. $users[] = $this->getUserObject($uid, $backend);
  355. }
  356. }
  357. }
  358. usort($users, function ($a, $b) {
  359. /**
  360. * @var IUser $a
  361. * @var IUser $b
  362. */
  363. return strcasecmp($a->getDisplayName(), $b->getDisplayName());
  364. });
  365. return $users;
  366. }
  367. /**
  368. * @param string $uid
  369. * @param string $password
  370. * @return false|IUser the created user or false
  371. * @throws \InvalidArgumentException
  372. * @throws HintException
  373. */
  374. public function createUser($uid, $password) {
  375. // DI injection is not used here as IRegistry needs the user manager itself for user count and thus it would create a cyclic dependency
  376. /** @var IAssertion $assertion */
  377. $assertion = \OC::$server->get(IAssertion::class);
  378. $assertion->createUserIsLegit();
  379. $localBackends = [];
  380. foreach ($this->backends as $backend) {
  381. if ($backend instanceof Database) {
  382. // First check if there is another user backend
  383. $localBackends[] = $backend;
  384. continue;
  385. }
  386. if ($backend->implementsActions(Backend::CREATE_USER)) {
  387. return $this->createUserFromBackend($uid, $password, $backend);
  388. }
  389. }
  390. foreach ($localBackends as $backend) {
  391. if ($backend->implementsActions(Backend::CREATE_USER)) {
  392. return $this->createUserFromBackend($uid, $password, $backend);
  393. }
  394. }
  395. return false;
  396. }
  397. /**
  398. * @param string $uid
  399. * @param string $password
  400. * @param UserInterface $backend
  401. * @return IUser|false
  402. * @throws \InvalidArgumentException
  403. */
  404. public function createUserFromBackend($uid, $password, UserInterface $backend) {
  405. $l = \OCP\Util::getL10N('lib');
  406. $this->validateUserId($uid, true);
  407. // No empty password
  408. if (trim($password) === '') {
  409. throw new \InvalidArgumentException($l->t('A valid password must be provided'));
  410. }
  411. // Check if user already exists
  412. if ($this->userExists($uid)) {
  413. throw new \InvalidArgumentException($l->t('The Login is already being used'));
  414. }
  415. /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
  416. $this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
  417. $this->eventDispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
  418. $state = $backend->createUser($uid, $password);
  419. if ($state === false) {
  420. throw new \InvalidArgumentException($l->t('Could not create account'));
  421. }
  422. $user = $this->getUserObject($uid, $backend);
  423. if ($user instanceof IUser) {
  424. /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
  425. $this->emit('\OC\User', 'postCreateUser', [$user, $password]);
  426. $this->eventDispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
  427. return $user;
  428. }
  429. return false;
  430. }
  431. /**
  432. * returns how many users per backend exist (if supported by backend)
  433. *
  434. * @param boolean $hasLoggedIn when true only users that have a lastLogin
  435. * entry in the preferences table will be affected
  436. * @return array<string, int> an array of backend class as key and count number as value
  437. */
  438. public function countUsers() {
  439. $userCountStatistics = [];
  440. foreach ($this->backends as $backend) {
  441. if ($backend instanceof ICountUsersBackend || $backend->implementsActions(Backend::COUNT_USERS)) {
  442. /** @var ICountUsersBackend|IUserBackend $backend */
  443. $backendUsers = $backend->countUsers();
  444. if ($backendUsers !== false) {
  445. if ($backend instanceof IUserBackend) {
  446. $name = $backend->getBackendName();
  447. } else {
  448. $name = get_class($backend);
  449. }
  450. if (isset($userCountStatistics[$name])) {
  451. $userCountStatistics[$name] += $backendUsers;
  452. } else {
  453. $userCountStatistics[$name] = $backendUsers;
  454. }
  455. }
  456. }
  457. }
  458. return $userCountStatistics;
  459. }
  460. /**
  461. * returns how many users per backend exist in the requested groups (if supported by backend)
  462. *
  463. * @param IGroup[] $groups an array of gid to search in
  464. * @return array|int an array of backend class as key and count number as value
  465. * if $hasLoggedIn is true only an int is returned
  466. */
  467. public function countUsersOfGroups(array $groups) {
  468. $users = [];
  469. foreach ($groups as $group) {
  470. $usersIds = array_map(function ($user) {
  471. return $user->getUID();
  472. }, $group->getUsers());
  473. $users = array_merge($users, $usersIds);
  474. }
  475. return count(array_unique($users));
  476. }
  477. /**
  478. * The callback is executed for each user on each backend.
  479. * If the callback returns false no further users will be retrieved.
  480. *
  481. * @psalm-param \Closure(\OCP\IUser):?bool $callback
  482. * @param string $search
  483. * @param boolean $onlySeen when true only users that have a lastLogin entry
  484. * in the preferences table will be affected
  485. * @since 9.0.0
  486. */
  487. public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
  488. if ($onlySeen) {
  489. $this->callForSeenUsers($callback);
  490. } else {
  491. foreach ($this->getBackends() as $backend) {
  492. $limit = 500;
  493. $offset = 0;
  494. do {
  495. $users = $backend->getUsers($search, $limit, $offset);
  496. foreach ($users as $uid) {
  497. if (!$backend->userExists($uid)) {
  498. continue;
  499. }
  500. $user = $this->getUserObject($uid, $backend, false);
  501. $return = $callback($user);
  502. if ($return === false) {
  503. break;
  504. }
  505. }
  506. $offset += $limit;
  507. } while (count($users) >= $limit);
  508. }
  509. }
  510. }
  511. /**
  512. * returns how many users are disabled
  513. *
  514. * @return int
  515. * @since 12.0.0
  516. */
  517. public function countDisabledUsers(): int {
  518. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  519. $queryBuilder->select($queryBuilder->func()->count('*'))
  520. ->from('preferences')
  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. $result = $queryBuilder->execute();
  525. $count = $result->fetchOne();
  526. $result->closeCursor();
  527. if ($count !== false) {
  528. $count = (int)$count;
  529. } else {
  530. $count = 0;
  531. }
  532. return $count;
  533. }
  534. /**
  535. * returns how many users are disabled in the requested groups
  536. *
  537. * @param array $groups groupids to search
  538. * @return int
  539. * @since 14.0.0
  540. */
  541. public function countDisabledUsersOfGroups(array $groups): int {
  542. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  543. $queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
  544. ->from('preferences', 'p')
  545. ->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
  546. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
  547. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
  548. ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
  549. ->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
  550. $result = $queryBuilder->execute();
  551. $count = $result->fetchOne();
  552. $result->closeCursor();
  553. if ($count !== false) {
  554. $count = (int)$count;
  555. } else {
  556. $count = 0;
  557. }
  558. return $count;
  559. }
  560. /**
  561. * returns how many users have logged in once
  562. *
  563. * @return int
  564. * @since 11.0.0
  565. */
  566. public function countSeenUsers() {
  567. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  568. $queryBuilder->select($queryBuilder->func()->count('*'))
  569. ->from('preferences')
  570. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
  571. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')));
  572. $query = $queryBuilder->execute();
  573. $result = (int)$query->fetchOne();
  574. $query->closeCursor();
  575. return $result;
  576. }
  577. /**
  578. * @param \Closure $callback
  579. * @psalm-param \Closure(\OCP\IUser):?bool $callback
  580. * @since 11.0.0
  581. */
  582. public function callForSeenUsers(\Closure $callback) {
  583. $limit = 1000;
  584. $offset = 0;
  585. do {
  586. $userIds = $this->getSeenUserIds($limit, $offset);
  587. $offset += $limit;
  588. foreach ($userIds as $userId) {
  589. foreach ($this->backends as $backend) {
  590. if ($backend->userExists($userId)) {
  591. $user = $this->getUserObject($userId, $backend, false);
  592. $return = $callback($user);
  593. if ($return === false) {
  594. return;
  595. }
  596. break;
  597. }
  598. }
  599. }
  600. } while (count($userIds) >= $limit);
  601. }
  602. /**
  603. * Getting all userIds that have a listLogin value requires checking the
  604. * value in php because on oracle you cannot use a clob in a where clause,
  605. * preventing us from doing a not null or length(value) > 0 check.
  606. *
  607. * @param int $limit
  608. * @param int $offset
  609. * @return string[] with user ids
  610. */
  611. private function getSeenUserIds($limit = null, $offset = null) {
  612. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  613. $queryBuilder->select(['userid'])
  614. ->from('preferences')
  615. ->where($queryBuilder->expr()->eq(
  616. 'appid', $queryBuilder->createNamedParameter('login'))
  617. )
  618. ->andWhere($queryBuilder->expr()->eq(
  619. 'configkey', $queryBuilder->createNamedParameter('lastLogin'))
  620. )
  621. ->andWhere($queryBuilder->expr()->isNotNull('configvalue')
  622. );
  623. if ($limit !== null) {
  624. $queryBuilder->setMaxResults($limit);
  625. }
  626. if ($offset !== null) {
  627. $queryBuilder->setFirstResult($offset);
  628. }
  629. $query = $queryBuilder->execute();
  630. $result = [];
  631. while ($row = $query->fetch()) {
  632. $result[] = $row['userid'];
  633. }
  634. $query->closeCursor();
  635. return $result;
  636. }
  637. /**
  638. * @param string $email
  639. * @return IUser[]
  640. * @since 9.1.0
  641. */
  642. public function getByEmail($email) {
  643. // looking for 'email' only (and not primary_mail) is intentional
  644. $userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
  645. $users = array_map(function ($uid) {
  646. return $this->get($uid);
  647. }, $userIds);
  648. return array_values(array_filter($users, function ($u) {
  649. return ($u instanceof IUser);
  650. }));
  651. }
  652. /**
  653. * @param string $uid
  654. * @param bool $checkDataDirectory
  655. * @throws \InvalidArgumentException Message is an already translated string with a reason why the id is not valid
  656. * @since 26.0.0
  657. */
  658. public function validateUserId(string $uid, bool $checkDataDirectory = false): void {
  659. $l = Server::get(IFactory::class)->get('lib');
  660. // Check the name for bad characters
  661. // Allowed are: "a-z", "A-Z", "0-9", spaces and "_.@-'"
  662. if (preg_match('/[^a-zA-Z0-9 _.@\-\']/', $uid)) {
  663. throw new \InvalidArgumentException($l->t('Only the following characters are allowed in an Login:'
  664. . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'));
  665. }
  666. // No empty username
  667. if (trim($uid) === '') {
  668. throw new \InvalidArgumentException($l->t('A valid Login must be provided'));
  669. }
  670. // No whitespace at the beginning or at the end
  671. if (trim($uid) !== $uid) {
  672. throw new \InvalidArgumentException($l->t('Login contains whitespace at the beginning or at the end'));
  673. }
  674. // Username only consists of 1 or 2 dots (directory traversal)
  675. if ($uid === '.' || $uid === '..') {
  676. throw new \InvalidArgumentException($l->t('Login must not consist of dots only'));
  677. }
  678. if (!$this->verifyUid($uid, $checkDataDirectory)) {
  679. throw new \InvalidArgumentException($l->t('Login is invalid because files already exist for this user'));
  680. }
  681. }
  682. private function verifyUid(string $uid, bool $checkDataDirectory = false): bool {
  683. $appdata = 'appdata_' . $this->config->getSystemValueString('instanceid');
  684. if (\in_array($uid, [
  685. '.htaccess',
  686. 'files_external',
  687. '__groupfolders',
  688. '.ocdata',
  689. 'owncloud.log',
  690. 'nextcloud.log',
  691. $appdata], true)) {
  692. return false;
  693. }
  694. if (!$checkDataDirectory) {
  695. return true;
  696. }
  697. $dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
  698. return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid);
  699. }
  700. public function getDisplayNameCache(): DisplayNameCache {
  701. return $this->displayNameCache;
  702. }
  703. }