Manager.php 24 KB

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