Manager.php 22 KB

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