You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Database.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author adrien <adrien.waksberg@believedigital.com>
  7. * @author Aldo "xoen" Giambelluca <xoen@xoen.org>
  8. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  9. * @author Bart Visscher <bartv@thisnet.nl>
  10. * @author Bjoern Schiessle <bjoern@schiessle.org>
  11. * @author Björn Schießle <bjoern@schiessle.org>
  12. * @author fabian <fabian@web2.0-apps.de>
  13. * @author Georg Ehrke <oc.list@georgehrke.com>
  14. * @author Jakob Sack <mail@jakobsack.de>
  15. * @author Joas Schilling <coding@schilljs.com>
  16. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  17. * @author Loki3000 <github@labcms.ru>
  18. * @author Lukas Reschke <lukas@statuscode.ch>
  19. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  20. * @author michag86 <micha_g@arcor.de>
  21. * @author Morris Jobke <hey@morrisjobke.de>
  22. * @author nishiki <nishiki@yaegashi.fr>
  23. * @author Robin Appelman <robin@icewind.nl>
  24. * @author Robin McCorkell <robin@mccorkell.me.uk>
  25. * @author Roeland Jago Douma <roeland@famdouma.nl>
  26. * @author Thomas Müller <thomas.mueller@tmit.eu>
  27. * @author Vincent Petry <pvince81@owncloud.com>
  28. *
  29. * @license AGPL-3.0
  30. *
  31. * This code is free software: you can redistribute it and/or modify
  32. * it under the terms of the GNU Affero General Public License, version 3,
  33. * as published by the Free Software Foundation.
  34. *
  35. * This program is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. * GNU Affero General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU Affero General Public License, version 3,
  41. * along with this program. If not, see <http://www.gnu.org/licenses/>
  42. *
  43. */
  44. /*
  45. *
  46. * The following SQL statement is just a help for developers and will not be
  47. * executed!
  48. *
  49. * CREATE TABLE `users` (
  50. * `uid` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  51. * `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  52. * PRIMARY KEY (`uid`)
  53. * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  54. *
  55. */
  56. namespace OC\User;
  57. use OC\Cache\CappedMemoryCache;
  58. use OCP\IDBConnection;
  59. use OCP\User\Backend\ABackend;
  60. use OCP\User\Backend\ICheckPasswordBackend;
  61. use OCP\User\Backend\ICountUsersBackend;
  62. use OCP\User\Backend\ICreateUserBackend;
  63. use OCP\User\Backend\IGetDisplayNameBackend;
  64. use OCP\User\Backend\IGetHomeBackend;
  65. use OCP\User\Backend\ISetDisplayNameBackend;
  66. use OCP\User\Backend\ISetPasswordBackend;
  67. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  68. use Symfony\Component\EventDispatcher\GenericEvent;
  69. /**
  70. * Class for user management in a SQL Database (e.g. MySQL, SQLite)
  71. */
  72. class Database extends ABackend
  73. implements ICreateUserBackend,
  74. ISetPasswordBackend,
  75. ISetDisplayNameBackend,
  76. IGetDisplayNameBackend,
  77. ICheckPasswordBackend,
  78. IGetHomeBackend,
  79. ICountUsersBackend {
  80. /** @var CappedMemoryCache */
  81. private $cache;
  82. /** @var EventDispatcherInterface */
  83. private $eventDispatcher;
  84. /** @var IDBConnection */
  85. private $dbConn;
  86. /** @var string */
  87. private $table;
  88. /**
  89. * \OC\User\Database constructor.
  90. *
  91. * @param EventDispatcherInterface $eventDispatcher
  92. * @param string $table
  93. */
  94. public function __construct($eventDispatcher = null, $table = 'users') {
  95. $this->cache = new CappedMemoryCache();
  96. $this->table = $table;
  97. $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->getEventDispatcher();
  98. }
  99. /**
  100. * FIXME: This function should not be required!
  101. */
  102. private function fixDI() {
  103. if ($this->dbConn === null) {
  104. $this->dbConn = \OC::$server->getDatabaseConnection();
  105. }
  106. }
  107. /**
  108. * Create a new user
  109. *
  110. * @param string $uid The username of the user to create
  111. * @param string $password The password of the new user
  112. * @return bool
  113. *
  114. * Creates a new user. Basic checking of username is done in OC_User
  115. * itself, not in its subclasses.
  116. */
  117. public function createUser(string $uid, string $password): bool {
  118. $this->fixDI();
  119. if (!$this->userExists($uid)) {
  120. $event = new GenericEvent($password);
  121. $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
  122. $qb = $this->dbConn->getQueryBuilder();
  123. $qb->insert($this->table)
  124. ->values([
  125. 'uid' => $qb->createNamedParameter($uid),
  126. 'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
  127. 'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
  128. ]);
  129. $result = $qb->execute();
  130. // Clear cache
  131. unset($this->cache[$uid]);
  132. return $result ? true : false;
  133. }
  134. return false;
  135. }
  136. /**
  137. * delete a user
  138. *
  139. * @param string $uid The username of the user to delete
  140. * @return bool
  141. *
  142. * Deletes a user
  143. */
  144. public function deleteUser($uid) {
  145. $this->fixDI();
  146. // Delete user-group-relation
  147. $query = $this->dbConn->getQueryBuilder();
  148. $query->delete($this->table)
  149. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  150. $result = $query->execute();
  151. if (isset($this->cache[$uid])) {
  152. unset($this->cache[$uid]);
  153. }
  154. return $result ? true : false;
  155. }
  156. private function updatePassword(string $uid, string $passwordHash): bool {
  157. $query = $this->dbConn->getQueryBuilder();
  158. $query->update($this->table)
  159. ->set('password', $query->createNamedParameter($passwordHash))
  160. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  161. $result = $query->execute();
  162. return $result ? true : false;
  163. }
  164. /**
  165. * Set password
  166. *
  167. * @param string $uid The username
  168. * @param string $password The new password
  169. * @return bool
  170. *
  171. * Change the password of a user
  172. */
  173. public function setPassword(string $uid, string $password): bool {
  174. $this->fixDI();
  175. if ($this->userExists($uid)) {
  176. $event = new GenericEvent($password);
  177. $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
  178. $hasher = \OC::$server->getHasher();
  179. $hashedPassword = $hasher->hash($password);
  180. return $this->updatePassword($uid, $hashedPassword);
  181. }
  182. return false;
  183. }
  184. /**
  185. * Set display name
  186. *
  187. * @param string $uid The username
  188. * @param string $displayName The new display name
  189. * @return bool
  190. *
  191. * Change the display name of a user
  192. */
  193. public function setDisplayName(string $uid, string $displayName): bool {
  194. $this->fixDI();
  195. if ($this->userExists($uid)) {
  196. $query = $this->dbConn->getQueryBuilder();
  197. $query->update($this->table)
  198. ->set('displayname', $query->createNamedParameter($displayName))
  199. ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
  200. $query->execute();
  201. $this->cache[$uid]['displayname'] = $displayName;
  202. return true;
  203. }
  204. return false;
  205. }
  206. /**
  207. * get display name of the user
  208. *
  209. * @param string $uid user ID of the user
  210. * @return string display name
  211. */
  212. public function getDisplayName($uid): string {
  213. $uid = (string)$uid;
  214. $this->loadUser($uid);
  215. return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
  216. }
  217. /**
  218. * Get a list of all display names and user ids.
  219. *
  220. * @param string $search
  221. * @param string|null $limit
  222. * @param string|null $offset
  223. * @return array an array of all displayNames (value) and the corresponding uids (key)
  224. */
  225. public function getDisplayNames($search = '', $limit = null, $offset = null) {
  226. $this->fixDI();
  227. $query = $this->dbConn->getQueryBuilder();
  228. $query->select('uid', 'displayname')
  229. ->from($this->table, 'u')
  230. ->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
  231. $query->expr()->eq('userid', 'uid'),
  232. $query->expr()->eq('appid', $query->expr()->literal('settings')),
  233. $query->expr()->eq('configkey', $query->expr()->literal('email')))
  234. )
  235. // sqlite doesn't like re-using a single named parameter here
  236. ->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  237. ->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  238. ->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
  239. ->orderBy($query->func()->lower('displayname'), 'ASC')
  240. ->orderBy('uid_lower', 'ASC')
  241. ->setMaxResults($limit)
  242. ->setFirstResult($offset);
  243. $result = $query->execute();
  244. $displayNames = [];
  245. while ($row = $result->fetch()) {
  246. $displayNames[(string)$row['uid']] = (string)$row['displayname'];
  247. }
  248. return $displayNames;
  249. }
  250. /**
  251. * Check if the password is correct
  252. *
  253. * @param string $uid The username
  254. * @param string $password The password
  255. * @return string
  256. *
  257. * Check if the password is correct without logging in the user
  258. * returns the user id or false
  259. */
  260. public function checkPassword(string $uid, string $password) {
  261. $this->fixDI();
  262. $qb = $this->dbConn->getQueryBuilder();
  263. $qb->select('uid', 'password')
  264. ->from($this->table)
  265. ->where(
  266. $qb->expr()->eq(
  267. 'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
  268. )
  269. );
  270. $result = $qb->execute();
  271. $row = $result->fetch();
  272. $result->closeCursor();
  273. if ($row) {
  274. $storedHash = $row['password'];
  275. $newHash = '';
  276. if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
  277. if (!empty($newHash)) {
  278. $this->updatePassword($uid, $newHash);
  279. }
  280. return (string)$row['uid'];
  281. }
  282. }
  283. return false;
  284. }
  285. /**
  286. * Load an user in the cache
  287. *
  288. * @param string $uid the username
  289. * @return boolean true if user was found, false otherwise
  290. */
  291. private function loadUser($uid) {
  292. $this->fixDI();
  293. $uid = (string)$uid;
  294. if (!isset($this->cache[$uid])) {
  295. //guests $uid could be NULL or ''
  296. if ($uid === '') {
  297. $this->cache[$uid] = false;
  298. return true;
  299. }
  300. $qb = $this->dbConn->getQueryBuilder();
  301. $qb->select('uid', 'displayname')
  302. ->from($this->table)
  303. ->where(
  304. $qb->expr()->eq(
  305. 'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
  306. )
  307. );
  308. $result = $qb->execute();
  309. $row = $result->fetch();
  310. $result->closeCursor();
  311. $this->cache[$uid] = false;
  312. // "uid" is primary key, so there can only be a single result
  313. if ($row !== false) {
  314. $this->cache[$uid]['uid'] = (string)$row['uid'];
  315. $this->cache[$uid]['displayname'] = (string)$row['displayname'];
  316. } else {
  317. return false;
  318. }
  319. }
  320. return true;
  321. }
  322. /**
  323. * Get a list of all users
  324. *
  325. * @param string $search
  326. * @param null|int $limit
  327. * @param null|int $offset
  328. * @return string[] an array of all uids
  329. */
  330. public function getUsers($search = '', $limit = null, $offset = null) {
  331. $users = $this->getDisplayNames($search, $limit, $offset);
  332. $userIds = array_map(function ($uid) {
  333. return (string)$uid;
  334. }, array_keys($users));
  335. sort($userIds, SORT_STRING | SORT_FLAG_CASE);
  336. return $userIds;
  337. }
  338. /**
  339. * check if a user exists
  340. *
  341. * @param string $uid the username
  342. * @return boolean
  343. */
  344. public function userExists($uid) {
  345. $this->loadUser($uid);
  346. return $this->cache[$uid] !== false;
  347. }
  348. /**
  349. * get the user's home directory
  350. *
  351. * @param string $uid the username
  352. * @return string|false
  353. */
  354. public function getHome(string $uid) {
  355. if ($this->userExists($uid)) {
  356. return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
  357. }
  358. return false;
  359. }
  360. /**
  361. * @return bool
  362. */
  363. public function hasUserListings() {
  364. return true;
  365. }
  366. /**
  367. * counts the users in the database
  368. *
  369. * @return int|bool
  370. */
  371. public function countUsers() {
  372. $this->fixDI();
  373. $query = $this->dbConn->getQueryBuilder();
  374. $query->select($query->func()->count('uid'))
  375. ->from($this->table);
  376. $result = $query->execute();
  377. return $result->fetchColumn();
  378. }
  379. /**
  380. * returns the username for the given login name in the correct casing
  381. *
  382. * @param string $loginName
  383. * @return string|false
  384. */
  385. public function loginName2UserName($loginName) {
  386. if ($this->userExists($loginName)) {
  387. return $this->cache[$loginName]['uid'];
  388. }
  389. return false;
  390. }
  391. /**
  392. * Backend name to be shown in user management
  393. *
  394. * @return string the name of the backend to be shown
  395. */
  396. public function getBackendName() {
  397. return 'Database';
  398. }
  399. public static function preLoginNameUsedAsUserName($param) {
  400. if (!isset($param['uid'])) {
  401. throw new \Exception('key uid is expected to be set in $param');
  402. }
  403. $backends = \OC::$server->getUserManager()->getBackends();
  404. foreach ($backends as $backend) {
  405. if ($backend instanceof Database) {
  406. /** @var \OC\User\Database $backend */
  407. $uid = $backend->loginName2UserName($param['uid']);
  408. if ($uid !== false) {
  409. $param['uid'] = $uid;
  410. return;
  411. }
  412. }
  413. }
  414. }
  415. }