database.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author adrien <adrien.waksberg@believedigital.com>
  6. * @author Aldo "xoen" Giambelluca <xoen@xoen.org>
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Bart Visscher <bartv@thisnet.nl>
  9. * @author Bjoern Schiessle <bjoern@schiessle.org>
  10. * @author Björn Schießle <bjoern@schiessle.org>
  11. * @author fabian <fabian@web2.0-apps.de>
  12. * @author Georg Ehrke <georg@owncloud.com>
  13. * @author Jakob Sack <mail@jakobsack.de>
  14. * @author Joas Schilling <coding@schilljs.com>
  15. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author nishiki <nishiki@yaegashi.fr>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Robin McCorkell <robin@mccorkell.me.uk>
  22. * @author Roeland Jago Douma <roeland@famdouma.nl>
  23. * @author Thomas Müller <thomas.mueller@tmit.eu>
  24. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  25. *
  26. * @license AGPL-3.0
  27. *
  28. * This code is free software: you can redistribute it and/or modify
  29. * it under the terms of the GNU Affero General Public License, version 3,
  30. * as published by the Free Software Foundation.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU Affero General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU Affero General Public License, version 3,
  38. * along with this program. If not, see <http://www.gnu.org/licenses/>
  39. *
  40. */
  41. /*
  42. *
  43. * The following SQL statement is just a help for developers and will not be
  44. * executed!
  45. *
  46. * CREATE TABLE `users` (
  47. * `uid` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  48. * `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  49. * PRIMARY KEY (`uid`)
  50. * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  51. *
  52. */
  53. use OC\Cache\CappedMemoryCache;
  54. use Symfony\Component\EventDispatcher\EventDispatcher;
  55. use Symfony\Component\EventDispatcher\GenericEvent;
  56. /**
  57. * Class for user management in a SQL Database (e.g. MySQL, SQLite)
  58. */
  59. class OC_User_Database extends OC_User_Backend implements \OCP\IUserBackend {
  60. /** @var CappedMemoryCache */
  61. private $cache;
  62. /**
  63. * OC_User_Database constructor.
  64. *
  65. * @param EventDispatcher $eventDispatcher
  66. */
  67. public function __construct(EventDispatcher $eventDispatcher = null) {
  68. $this->cache = new CappedMemoryCache();
  69. $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->getEventDispatcher();
  70. }
  71. /**
  72. * Create a new user
  73. * @param string $uid The username of the user to create
  74. * @param string $password The password of the new user
  75. * @return bool
  76. *
  77. * Creates a new user. Basic checking of username is done in OC_User
  78. * itself, not in its subclasses.
  79. */
  80. public function createUser($uid, $password) {
  81. if (!$this->userExists($uid)) {
  82. $query = OC_DB::prepare('INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )');
  83. $result = $query->execute(array($uid, \OC::$server->getHasher()->hash($password)));
  84. return $result ? true : false;
  85. }
  86. return false;
  87. }
  88. /**
  89. * delete a user
  90. * @param string $uid The username of the user to delete
  91. * @return bool
  92. *
  93. * Deletes a user
  94. */
  95. public function deleteUser($uid) {
  96. // Delete user-group-relation
  97. $query = OC_DB::prepare('DELETE FROM `*PREFIX*users` WHERE `uid` = ?');
  98. $result = $query->execute(array($uid));
  99. if (isset($this->cache[$uid])) {
  100. unset($this->cache[$uid]);
  101. }
  102. return $result ? true : false;
  103. }
  104. /**
  105. * Set password
  106. * @param string $uid The username
  107. * @param string $password The new password
  108. * @return bool
  109. *
  110. * Change the password of a user
  111. */
  112. public function setPassword($uid, $password) {
  113. if ($this->userExists($uid)) {
  114. $event = new GenericEvent($password);
  115. $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
  116. $query = OC_DB::prepare('UPDATE `*PREFIX*users` SET `password` = ? WHERE `uid` = ?');
  117. $result = $query->execute(array(\OC::$server->getHasher()->hash($password), $uid));
  118. return $result ? true : false;
  119. }
  120. return false;
  121. }
  122. /**
  123. * Set display name
  124. * @param string $uid The username
  125. * @param string $displayName The new display name
  126. * @return bool
  127. *
  128. * Change the display name of a user
  129. */
  130. public function setDisplayName($uid, $displayName) {
  131. if ($this->userExists($uid)) {
  132. $query = OC_DB::prepare('UPDATE `*PREFIX*users` SET `displayname` = ? WHERE LOWER(`uid`) = LOWER(?)');
  133. $query->execute(array($displayName, $uid));
  134. $this->cache[$uid]['displayname'] = $displayName;
  135. return true;
  136. }
  137. return false;
  138. }
  139. /**
  140. * get display name of the user
  141. * @param string $uid user ID of the user
  142. * @return string display name
  143. */
  144. public function getDisplayName($uid) {
  145. $this->loadUser($uid);
  146. return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
  147. }
  148. /**
  149. * Get a list of all display names and user ids.
  150. *
  151. * @param string $search
  152. * @param string|null $limit
  153. * @param string|null $offset
  154. * @return array an array of all displayNames (value) and the corresponding uids (key)
  155. */
  156. public function getDisplayNames($search = '', $limit = null, $offset = null) {
  157. $parameters = [];
  158. $searchLike = '';
  159. if ($search !== '') {
  160. $parameters[] = '%' . $search . '%';
  161. $parameters[] = '%' . $search . '%';
  162. $searchLike = ' WHERE LOWER(`displayname`) LIKE LOWER(?) OR '
  163. . 'LOWER(`uid`) LIKE LOWER(?)';
  164. }
  165. $displayNames = array();
  166. $query = OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users`'
  167. . $searchLike .' ORDER BY `uid` ASC', $limit, $offset);
  168. $result = $query->execute($parameters);
  169. while ($row = $result->fetchRow()) {
  170. $displayNames[$row['uid']] = $row['displayname'];
  171. }
  172. return $displayNames;
  173. }
  174. /**
  175. * Check if the password is correct
  176. * @param string $uid The username
  177. * @param string $password The password
  178. * @return string
  179. *
  180. * Check if the password is correct without logging in the user
  181. * returns the user id or false
  182. */
  183. public function checkPassword($uid, $password) {
  184. $query = OC_DB::prepare('SELECT `uid`, `password` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
  185. $result = $query->execute(array($uid));
  186. $row = $result->fetchRow();
  187. if ($row) {
  188. $storedHash = $row['password'];
  189. $newHash = '';
  190. if(\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
  191. if(!empty($newHash)) {
  192. $this->setPassword($uid, $password);
  193. }
  194. return $row['uid'];
  195. }
  196. }
  197. return false;
  198. }
  199. /**
  200. * Load an user in the cache
  201. * @param string $uid the username
  202. * @return boolean
  203. */
  204. private function loadUser($uid) {
  205. if (empty($this->cache[$uid])) {
  206. $query = OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
  207. $result = $query->execute(array($uid));
  208. if ($result === false) {
  209. \OCP\Util::writeLog('core', OC_DB::getErrorMessage(), \OCP\Util::ERROR);
  210. return false;
  211. }
  212. while ($row = $result->fetchRow()) {
  213. $this->cache[$uid]['uid'] = $row['uid'];
  214. $this->cache[$uid]['displayname'] = $row['displayname'];
  215. }
  216. }
  217. return true;
  218. }
  219. /**
  220. * Get a list of all users
  221. *
  222. * @param string $search
  223. * @param null|int $limit
  224. * @param null|int $offset
  225. * @return string[] an array of all uids
  226. */
  227. public function getUsers($search = '', $limit = null, $offset = null) {
  228. $parameters = [];
  229. $searchLike = '';
  230. if ($search !== '') {
  231. $parameters[] = '%' . $search . '%';
  232. $searchLike = ' WHERE LOWER(`uid`) LIKE LOWER(?)';
  233. }
  234. $query = OC_DB::prepare('SELECT `uid` FROM `*PREFIX*users`' . $searchLike . ' ORDER BY `uid` ASC', $limit, $offset);
  235. $result = $query->execute($parameters);
  236. $users = array();
  237. while ($row = $result->fetchRow()) {
  238. $users[] = $row['uid'];
  239. }
  240. return $users;
  241. }
  242. /**
  243. * check if a user exists
  244. * @param string $uid the username
  245. * @return boolean
  246. */
  247. public function userExists($uid) {
  248. $this->loadUser($uid);
  249. return !empty($this->cache[$uid]);
  250. }
  251. /**
  252. * get the user's home directory
  253. * @param string $uid the username
  254. * @return string|false
  255. */
  256. public function getHome($uid) {
  257. if ($this->userExists($uid)) {
  258. return \OC::$server->getConfig()->getSystemValue("datadirectory", OC::$SERVERROOT . "/data") . '/' . $uid;
  259. }
  260. return false;
  261. }
  262. /**
  263. * @return bool
  264. */
  265. public function hasUserListings() {
  266. return true;
  267. }
  268. /**
  269. * counts the users in the database
  270. *
  271. * @return int|bool
  272. */
  273. public function countUsers() {
  274. $query = OC_DB::prepare('SELECT COUNT(*) FROM `*PREFIX*users`');
  275. $result = $query->execute();
  276. if ($result === false) {
  277. \OCP\Util::writeLog('core', OC_DB::getErrorMessage(), \OCP\Util::ERROR);
  278. return false;
  279. }
  280. return $result->fetchOne();
  281. }
  282. /**
  283. * returns the username for the given login name in the correct casing
  284. *
  285. * @param string $loginName
  286. * @return string|false
  287. */
  288. public function loginName2UserName($loginName) {
  289. if ($this->userExists($loginName)) {
  290. return $this->cache[$loginName]['uid'];
  291. }
  292. return false;
  293. }
  294. /**
  295. * Backend name to be shown in user management
  296. * @return string the name of the backend to be shown
  297. */
  298. public function getBackendName(){
  299. return 'Database';
  300. }
  301. public static function preLoginNameUsedAsUserName($param) {
  302. if(!isset($param['uid'])) {
  303. throw new \Exception('key uid is expected to be set in $param');
  304. }
  305. $backends = \OC::$server->getUserManager()->getBackends();
  306. foreach ($backends as $backend) {
  307. if ($backend instanceof \OC_User_Database) {
  308. /** @var \OC_User_Database $backend */
  309. $uid = $backend->loginName2UserName($param['uid']);
  310. if ($uid !== false) {
  311. $param['uid'] = $uid;
  312. return;
  313. }
  314. }
  315. }
  316. }
  317. }