Manager.php 23 KB

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