Manager.php 22 KB

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