Manager.php 23 KB

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