1
0

Manager.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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. public 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 IUser[]
  271. * @deprecated since 27.0.0, use searchDisplayName instead
  272. */
  273. public function search($pattern, $limit = null, $offset = null) {
  274. $users = [];
  275. foreach ($this->backends as $backend) {
  276. $backendUsers = $backend->getUsers($pattern, $limit, $offset);
  277. if (is_array($backendUsers)) {
  278. foreach ($backendUsers as $uid) {
  279. $users[$uid] = new LazyUser($uid, $this, null, $backend);
  280. }
  281. }
  282. }
  283. uasort($users, function (IUser $a, IUser $b) {
  284. return strcasecmp($a->getUID(), $b->getUID());
  285. });
  286. return $users;
  287. }
  288. /**
  289. * Search by displayName
  290. *
  291. * @param string $pattern
  292. * @param int $limit
  293. * @param int $offset
  294. * @return IUser[]
  295. */
  296. public function searchDisplayName($pattern, $limit = null, $offset = null) {
  297. $users = [];
  298. foreach ($this->backends as $backend) {
  299. $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
  300. if (is_array($backendUsers)) {
  301. foreach ($backendUsers as $uid => $displayName) {
  302. $users[] = new LazyUser($uid, $this, $displayName, $backend);
  303. }
  304. }
  305. }
  306. usort($users, function (IUser $a, IUser $b) {
  307. return strcasecmp($a->getDisplayName(), $b->getDisplayName());
  308. });
  309. return $users;
  310. }
  311. /**
  312. * Search known users (from phonebook sync) by displayName
  313. *
  314. * @param string $searcher
  315. * @param string $pattern
  316. * @param int|null $limit
  317. * @param int|null $offset
  318. * @return IUser[]
  319. */
  320. public function searchKnownUsersByDisplayName(string $searcher, string $pattern, ?int $limit = null, ?int $offset = null): array {
  321. $users = [];
  322. foreach ($this->backends as $backend) {
  323. if ($backend instanceof ISearchKnownUsersBackend) {
  324. $backendUsers = $backend->searchKnownUsersByDisplayName($searcher, $pattern, $limit, $offset);
  325. } else {
  326. // Better than nothing, but filtering after pagination can remove lots of results.
  327. $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
  328. }
  329. if (is_array($backendUsers)) {
  330. foreach ($backendUsers as $uid => $displayName) {
  331. $users[] = $this->getUserObject($uid, $backend);
  332. }
  333. }
  334. }
  335. usort($users, function ($a, $b) {
  336. /**
  337. * @var IUser $a
  338. * @var IUser $b
  339. */
  340. return strcasecmp($a->getDisplayName(), $b->getDisplayName());
  341. });
  342. return $users;
  343. }
  344. /**
  345. * @param string $uid
  346. * @param string $password
  347. * @return false|IUser the created user or false
  348. * @throws \InvalidArgumentException
  349. * @throws HintException
  350. */
  351. public function createUser($uid, $password) {
  352. // DI injection is not used here as IRegistry needs the user manager itself for user count and thus it would create a cyclic dependency
  353. /** @var IAssertion $assertion */
  354. $assertion = \OC::$server->get(IAssertion::class);
  355. $assertion->createUserIsLegit();
  356. $localBackends = [];
  357. foreach ($this->backends as $backend) {
  358. if ($backend instanceof Database) {
  359. // First check if there is another user backend
  360. $localBackends[] = $backend;
  361. continue;
  362. }
  363. if ($backend->implementsActions(Backend::CREATE_USER)) {
  364. return $this->createUserFromBackend($uid, $password, $backend);
  365. }
  366. }
  367. foreach ($localBackends as $backend) {
  368. if ($backend->implementsActions(Backend::CREATE_USER)) {
  369. return $this->createUserFromBackend($uid, $password, $backend);
  370. }
  371. }
  372. return false;
  373. }
  374. /**
  375. * @param string $uid
  376. * @param string $password
  377. * @param UserInterface $backend
  378. * @return IUser|false
  379. * @throws \InvalidArgumentException
  380. */
  381. public function createUserFromBackend($uid, $password, UserInterface $backend) {
  382. $l = \OC::$server->getL10N('lib');
  383. $this->validateUserId($uid, true);
  384. // No empty password
  385. if (trim($password) === '') {
  386. throw new \InvalidArgumentException($l->t('A valid password must be provided'));
  387. }
  388. // Check if user already exists
  389. if ($this->userExists($uid)) {
  390. throw new \InvalidArgumentException($l->t('The username is already being used'));
  391. }
  392. /** @deprecated 21.0.0 use BeforeUserCreatedEvent event with the IEventDispatcher instead */
  393. $this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
  394. $this->eventDispatcher->dispatchTyped(new BeforeUserCreatedEvent($uid, $password));
  395. $state = $backend->createUser($uid, $password);
  396. if ($state === false) {
  397. throw new \InvalidArgumentException($l->t('Could not create user'));
  398. }
  399. $user = $this->getUserObject($uid, $backend);
  400. if ($user instanceof IUser) {
  401. /** @deprecated 21.0.0 use UserCreatedEvent event with the IEventDispatcher instead */
  402. $this->emit('\OC\User', 'postCreateUser', [$user, $password]);
  403. $this->eventDispatcher->dispatchTyped(new UserCreatedEvent($user, $password));
  404. return $user;
  405. }
  406. return false;
  407. }
  408. /**
  409. * returns how many users per backend exist (if supported by backend)
  410. *
  411. * @param boolean $hasLoggedIn when true only users that have a lastLogin
  412. * entry in the preferences table will be affected
  413. * @return array<string, int> an array of backend class as key and count number as value
  414. */
  415. public function countUsers() {
  416. $userCountStatistics = [];
  417. foreach ($this->backends as $backend) {
  418. if ($backend instanceof ICountUsersBackend || $backend->implementsActions(Backend::COUNT_USERS)) {
  419. /** @var ICountUsersBackend|IUserBackend $backend */
  420. $backendUsers = $backend->countUsers();
  421. if ($backendUsers !== false) {
  422. if ($backend instanceof IUserBackend) {
  423. $name = $backend->getBackendName();
  424. } else {
  425. $name = get_class($backend);
  426. }
  427. if (isset($userCountStatistics[$name])) {
  428. $userCountStatistics[$name] += $backendUsers;
  429. } else {
  430. $userCountStatistics[$name] = $backendUsers;
  431. }
  432. }
  433. }
  434. }
  435. return $userCountStatistics;
  436. }
  437. /**
  438. * returns how many users per backend exist in the requested groups (if supported by backend)
  439. *
  440. * @param IGroup[] $groups an array of gid to search in
  441. * @return array|int an array of backend class as key and count number as value
  442. * if $hasLoggedIn is true only an int is returned
  443. */
  444. public function countUsersOfGroups(array $groups) {
  445. $users = [];
  446. foreach ($groups as $group) {
  447. $usersIds = array_map(function ($user) {
  448. return $user->getUID();
  449. }, $group->getUsers());
  450. $users = array_merge($users, $usersIds);
  451. }
  452. return count(array_unique($users));
  453. }
  454. /**
  455. * The callback is executed for each user on each backend.
  456. * If the callback returns false no further users will be retrieved.
  457. *
  458. * @psalm-param \Closure(\OCP\IUser):?bool $callback
  459. * @param string $search
  460. * @param boolean $onlySeen when true only users that have a lastLogin entry
  461. * in the preferences table will be affected
  462. * @since 9.0.0
  463. */
  464. public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
  465. if ($onlySeen) {
  466. $this->callForSeenUsers($callback);
  467. } else {
  468. foreach ($this->getBackends() as $backend) {
  469. $limit = 500;
  470. $offset = 0;
  471. do {
  472. $users = $backend->getUsers($search, $limit, $offset);
  473. foreach ($users as $uid) {
  474. if (!$backend->userExists($uid)) {
  475. continue;
  476. }
  477. $user = $this->getUserObject($uid, $backend, false);
  478. $return = $callback($user);
  479. if ($return === false) {
  480. break;
  481. }
  482. }
  483. $offset += $limit;
  484. } while (count($users) >= $limit);
  485. }
  486. }
  487. }
  488. /**
  489. * returns how many users are disabled
  490. *
  491. * @return int
  492. * @since 12.0.0
  493. */
  494. public function countDisabledUsers(): int {
  495. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  496. $queryBuilder->select($queryBuilder->func()->count('*'))
  497. ->from('preferences')
  498. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
  499. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
  500. ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
  501. $result = $queryBuilder->execute();
  502. $count = $result->fetchOne();
  503. $result->closeCursor();
  504. if ($count !== false) {
  505. $count = (int)$count;
  506. } else {
  507. $count = 0;
  508. }
  509. return $count;
  510. }
  511. /**
  512. * returns how many users are disabled in the requested groups
  513. *
  514. * @param array $groups groupids to search
  515. * @return int
  516. * @since 14.0.0
  517. */
  518. public function countDisabledUsersOfGroups(array $groups): int {
  519. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  520. $queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
  521. ->from('preferences', 'p')
  522. ->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
  523. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
  524. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
  525. ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
  526. ->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
  527. $result = $queryBuilder->execute();
  528. $count = $result->fetchOne();
  529. $result->closeCursor();
  530. if ($count !== false) {
  531. $count = (int)$count;
  532. } else {
  533. $count = 0;
  534. }
  535. return $count;
  536. }
  537. /**
  538. * returns how many users have logged in once
  539. *
  540. * @return int
  541. * @since 11.0.0
  542. */
  543. public function countSeenUsers() {
  544. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  545. $queryBuilder->select($queryBuilder->func()->count('*'))
  546. ->from('preferences')
  547. ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
  548. ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')));
  549. $query = $queryBuilder->execute();
  550. $result = (int)$query->fetchOne();
  551. $query->closeCursor();
  552. return $result;
  553. }
  554. /**
  555. * @param \Closure $callback
  556. * @psalm-param \Closure(\OCP\IUser):?bool $callback
  557. * @since 11.0.0
  558. */
  559. public function callForSeenUsers(\Closure $callback) {
  560. $limit = 1000;
  561. $offset = 0;
  562. do {
  563. $userIds = $this->getSeenUserIds($limit, $offset);
  564. $offset += $limit;
  565. foreach ($userIds as $userId) {
  566. foreach ($this->backends as $backend) {
  567. if ($backend->userExists($userId)) {
  568. $user = $this->getUserObject($userId, $backend, false);
  569. $return = $callback($user);
  570. if ($return === false) {
  571. return;
  572. }
  573. break;
  574. }
  575. }
  576. }
  577. } while (count($userIds) >= $limit);
  578. }
  579. /**
  580. * Getting all userIds that have a listLogin value requires checking the
  581. * value in php because on oracle you cannot use a clob in a where clause,
  582. * preventing us from doing a not null or length(value) > 0 check.
  583. *
  584. * @param int $limit
  585. * @param int $offset
  586. * @return string[] with user ids
  587. */
  588. private function getSeenUserIds($limit = null, $offset = null) {
  589. $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  590. $queryBuilder->select(['userid'])
  591. ->from('preferences')
  592. ->where($queryBuilder->expr()->eq(
  593. 'appid', $queryBuilder->createNamedParameter('login'))
  594. )
  595. ->andWhere($queryBuilder->expr()->eq(
  596. 'configkey', $queryBuilder->createNamedParameter('lastLogin'))
  597. )
  598. ->andWhere($queryBuilder->expr()->isNotNull('configvalue')
  599. );
  600. if ($limit !== null) {
  601. $queryBuilder->setMaxResults($limit);
  602. }
  603. if ($offset !== null) {
  604. $queryBuilder->setFirstResult($offset);
  605. }
  606. $query = $queryBuilder->execute();
  607. $result = [];
  608. while ($row = $query->fetch()) {
  609. $result[] = $row['userid'];
  610. }
  611. $query->closeCursor();
  612. return $result;
  613. }
  614. /**
  615. * @param string $email
  616. * @return IUser[]
  617. * @since 9.1.0
  618. */
  619. public function getByEmail($email) {
  620. // looking for 'email' only (and not primary_mail) is intentional
  621. $userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
  622. $users = array_map(function ($uid) {
  623. return $this->get($uid);
  624. }, $userIds);
  625. return array_values(array_filter($users, function ($u) {
  626. return ($u instanceof IUser);
  627. }));
  628. }
  629. /**
  630. * @param string $uid
  631. * @param bool $checkDataDirectory
  632. * @throws \InvalidArgumentException Message is an already translated string with a reason why the id is not valid
  633. * @since 26.0.0
  634. */
  635. public function validateUserId(string $uid, bool $checkDataDirectory = false): void {
  636. $l = Server::get(IFactory::class)->get('lib');
  637. // Check the name for bad characters
  638. // Allowed are: "a-z", "A-Z", "0-9", spaces and "_.@-'"
  639. if (preg_match('/[^a-zA-Z0-9 _.@\-\']/', $uid)) {
  640. throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
  641. . ' "a-z", "A-Z", "0-9", spaces and "_.@-\'"'));
  642. }
  643. // No empty username
  644. if (trim($uid) === '') {
  645. throw new \InvalidArgumentException($l->t('A valid username must be provided'));
  646. }
  647. // No whitespace at the beginning or at the end
  648. if (trim($uid) !== $uid) {
  649. throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
  650. }
  651. // Username only consists of 1 or 2 dots (directory traversal)
  652. if ($uid === '.' || $uid === '..') {
  653. throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
  654. }
  655. if (!$this->verifyUid($uid, $checkDataDirectory)) {
  656. throw new \InvalidArgumentException($l->t('Username is invalid because files already exist for this user'));
  657. }
  658. }
  659. private function verifyUid(string $uid, bool $checkDataDirectory = false): bool {
  660. $appdata = 'appdata_' . $this->config->getSystemValueString('instanceid');
  661. if (\in_array($uid, [
  662. '.htaccess',
  663. 'files_external',
  664. '__groupfolders',
  665. '.ocdata',
  666. 'owncloud.log',
  667. 'nextcloud.log',
  668. $appdata], true)) {
  669. return false;
  670. }
  671. if (!$checkDataDirectory) {
  672. return true;
  673. }
  674. $dataDirectory = $this->config->getSystemValueString('datadirectory', \OC::$SERVERROOT . '/data');
  675. return !file_exists(rtrim($dataDirectory, '/') . '/' . $uid);
  676. }
  677. public function getDisplayNameCache(): DisplayNameCache {
  678. return $this->displayNameCache;
  679. }
  680. }