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

Manager.php 23KB

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