Manager.php 25 KB

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