Manager.php 22 KB

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