Completed
Push — master ( 35f6b8...257fbd )
by Joas
371:46 queued 360:05
created
lib/private/User/Database.php 1 patch
Indentation   +316 added lines, -316 removed lines patch added patch discarded remove patch
@@ -62,320 +62,320 @@
 block discarded – undo
62 62
  * Class for user management in a SQL Database (e.g. MySQL, SQLite)
63 63
  */
64 64
 class Database extends Backend implements IUserBackend {
65
-	/** @var CappedMemoryCache */
66
-	private $cache;
67
-
68
-	/** @var EventDispatcher */
69
-	private $eventDispatcher;
70
-
71
-	/**
72
-	 * \OC\User\Database constructor.
73
-	 *
74
-	 * @param EventDispatcher $eventDispatcher
75
-	 */
76
-	public function __construct($eventDispatcher = null) {
77
-		$this->cache = new CappedMemoryCache();
78
-		$this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->getEventDispatcher();
79
-	}
80
-
81
-	/**
82
-	 * Create a new user
83
-	 * @param string $uid The username of the user to create
84
-	 * @param string $password The password of the new user
85
-	 * @return bool
86
-	 *
87
-	 * Creates a new user. Basic checking of username is done in OC_User
88
-	 * itself, not in its subclasses.
89
-	 */
90
-	public function createUser($uid, $password) {
91
-		if (!$this->userExists($uid)) {
92
-			$event = new GenericEvent($password);
93
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
94
-			$query = \OC_DB::prepare('INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )');
95
-			$result = $query->execute(array($uid, \OC::$server->getHasher()->hash($password)));
96
-
97
-			// Clear cache
98
-			unset($this->cache[$uid]);
99
-
100
-			return $result ? true : false;
101
-		}
102
-
103
-		return false;
104
-	}
105
-
106
-	/**
107
-	 * delete a user
108
-	 * @param string $uid The username of the user to delete
109
-	 * @return bool
110
-	 *
111
-	 * Deletes a user
112
-	 */
113
-	public function deleteUser($uid) {
114
-		// Delete user-group-relation
115
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*users` WHERE `uid` = ?');
116
-		$result = $query->execute(array($uid));
117
-
118
-		if (isset($this->cache[$uid])) {
119
-			unset($this->cache[$uid]);
120
-		}
121
-
122
-		return $result ? true : false;
123
-	}
124
-
125
-	/**
126
-	 * Set password
127
-	 * @param string $uid The username
128
-	 * @param string $password The new password
129
-	 * @return bool
130
-	 *
131
-	 * Change the password of a user
132
-	 */
133
-	public function setPassword($uid, $password) {
134
-		if ($this->userExists($uid)) {
135
-			$event = new GenericEvent($password);
136
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
137
-			$query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `password` = ? WHERE `uid` = ?');
138
-			$result = $query->execute(array(\OC::$server->getHasher()->hash($password), $uid));
139
-
140
-			return $result ? true : false;
141
-		}
142
-
143
-		return false;
144
-	}
145
-
146
-	/**
147
-	 * Set display name
148
-	 * @param string $uid The username
149
-	 * @param string $displayName The new display name
150
-	 * @return bool
151
-	 *
152
-	 * Change the display name of a user
153
-	 */
154
-	public function setDisplayName($uid, $displayName) {
155
-		if ($this->userExists($uid)) {
156
-			$query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `displayname` = ? WHERE LOWER(`uid`) = LOWER(?)');
157
-			$query->execute(array($displayName, $uid));
158
-			$this->cache[$uid]['displayname'] = $displayName;
159
-
160
-			return true;
161
-		}
162
-
163
-		return false;
164
-	}
165
-
166
-	/**
167
-	 * get display name of the user
168
-	 * @param string $uid user ID of the user
169
-	 * @return string display name
170
-	 */
171
-	public function getDisplayName($uid) {
172
-		$this->loadUser($uid);
173
-		return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
174
-	}
175
-
176
-	/**
177
-	 * Get a list of all display names and user ids.
178
-	 *
179
-	 * @param string $search
180
-	 * @param string|null $limit
181
-	 * @param string|null $offset
182
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
183
-	 */
184
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
185
-		$parameters = [];
186
-		$searchLike = '';
187
-		if ($search !== '') {
188
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
189
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
190
-			$searchLike = ' WHERE LOWER(`displayname`) LIKE LOWER(?) OR '
191
-				. 'LOWER(`uid`) LIKE LOWER(?)';
192
-		}
193
-
194
-		$displayNames = array();
195
-		$query = \OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users`'
196
-			. $searchLike .' ORDER BY `uid` ASC', $limit, $offset);
197
-		$result = $query->execute($parameters);
198
-		while ($row = $result->fetchRow()) {
199
-			$displayNames[$row['uid']] = $row['displayname'];
200
-		}
201
-
202
-		return $displayNames;
203
-	}
204
-
205
-	/**
206
-	 * Check if the password is correct
207
-	 * @param string $uid The username
208
-	 * @param string $password The password
209
-	 * @return string
210
-	 *
211
-	 * Check if the password is correct without logging in the user
212
-	 * returns the user id or false
213
-	 */
214
-	public function checkPassword($uid, $password) {
215
-		$query = \OC_DB::prepare('SELECT `uid`, `password` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
216
-		$result = $query->execute(array($uid));
217
-
218
-		$row = $result->fetchRow();
219
-		if ($row) {
220
-			$storedHash = $row['password'];
221
-			$newHash = '';
222
-			if(\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
223
-				if(!empty($newHash)) {
224
-					$this->setPassword($uid, $password);
225
-				}
226
-				return $row['uid'];
227
-			}
228
-
229
-		}
230
-
231
-		return false;
232
-	}
233
-
234
-	/**
235
-	 * Load an user in the cache
236
-	 * @param string $uid the username
237
-	 * @return boolean true if user was found, false otherwise
238
-	 */
239
-	private function loadUser($uid) {
240
-		if (!isset($this->cache[$uid])) {
241
-			//guests $uid could be NULL or ''
242
-			if ($uid === null || $uid === '') {
243
-				$this->cache[$uid]=false;
244
-				return true;
245
-			}
246
-
247
-			$query = \OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
248
-			$result = $query->execute(array($uid));
249
-
250
-			if ($result === false) {
251
-				Util::writeLog('core', \OC_DB::getErrorMessage(), Util::ERROR);
252
-				return false;
253
-			}
254
-
255
-			$this->cache[$uid] = false;
256
-
257
-			// "uid" is primary key, so there can only be a single result
258
-			if ($row = $result->fetchRow()) {
259
-				$this->cache[$uid]['uid'] = $row['uid'];
260
-				$this->cache[$uid]['displayname'] = $row['displayname'];
261
-				$result->closeCursor();
262
-			} else {
263
-				$result->closeCursor();
264
-				return false;
265
-			}
266
-		}
267
-
268
-		return true;
269
-	}
270
-
271
-	/**
272
-	 * Get a list of all users
273
-	 *
274
-	 * @param string $search
275
-	 * @param null|int $limit
276
-	 * @param null|int $offset
277
-	 * @return string[] an array of all uids
278
-	 */
279
-	public function getUsers($search = '', $limit = null, $offset = null) {
280
-		$parameters = [];
281
-		$searchLike = '';
282
-		if ($search !== '') {
283
-			$parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
284
-			$searchLike = ' WHERE LOWER(`uid`) LIKE LOWER(?)';
285
-		}
286
-
287
-		$query = \OC_DB::prepare('SELECT `uid` FROM `*PREFIX*users`' . $searchLike . ' ORDER BY `uid` ASC', $limit, $offset);
288
-		$result = $query->execute($parameters);
289
-		$users = array();
290
-		while ($row = $result->fetchRow()) {
291
-			$users[] = $row['uid'];
292
-		}
293
-		return $users;
294
-	}
295
-
296
-	/**
297
-	 * check if a user exists
298
-	 * @param string $uid the username
299
-	 * @return boolean
300
-	 */
301
-	public function userExists($uid) {
302
-		$this->loadUser($uid);
303
-		return $this->cache[$uid] !== false;
304
-	}
305
-
306
-	/**
307
-	 * get the user's home directory
308
-	 * @param string $uid the username
309
-	 * @return string|false
310
-	 */
311
-	public function getHome($uid) {
312
-		if ($this->userExists($uid)) {
313
-			return \OC::$server->getConfig()->getSystemValue("datadirectory", \OC::$SERVERROOT . "/data") . '/' . $uid;
314
-		}
315
-
316
-		return false;
317
-	}
318
-
319
-	/**
320
-	 * @return bool
321
-	 */
322
-	public function hasUserListings() {
323
-		return true;
324
-	}
325
-
326
-	/**
327
-	 * counts the users in the database
328
-	 *
329
-	 * @return int|bool
330
-	 */
331
-	public function countUsers() {
332
-		$query = \OC_DB::prepare('SELECT COUNT(*) FROM `*PREFIX*users`');
333
-		$result = $query->execute();
334
-		if ($result === false) {
335
-			Util::writeLog('core', \OC_DB::getErrorMessage(), Util::ERROR);
336
-			return false;
337
-		}
338
-		return $result->fetchOne();
339
-	}
340
-
341
-	/**
342
-	 * returns the username for the given login name in the correct casing
343
-	 *
344
-	 * @param string $loginName
345
-	 * @return string|false
346
-	 */
347
-	public function loginName2UserName($loginName) {
348
-		if ($this->userExists($loginName)) {
349
-			return $this->cache[$loginName]['uid'];
350
-		}
351
-
352
-		return false;
353
-	}
354
-
355
-	/**
356
-	 * Backend name to be shown in user management
357
-	 * @return string the name of the backend to be shown
358
-	 */
359
-	public function getBackendName(){
360
-		return 'Database';
361
-	}
362
-
363
-	public static function preLoginNameUsedAsUserName($param) {
364
-		if(!isset($param['uid'])) {
365
-			throw new \Exception('key uid is expected to be set in $param');
366
-		}
367
-
368
-		$backends = \OC::$server->getUserManager()->getBackends();
369
-		foreach ($backends as $backend) {
370
-			if ($backend instanceof Database) {
371
-				/** @var \OC\User\Database $backend */
372
-				$uid = $backend->loginName2UserName($param['uid']);
373
-				if ($uid !== false) {
374
-					$param['uid'] = $uid;
375
-					return;
376
-				}
377
-			}
378
-		}
379
-
380
-	}
65
+    /** @var CappedMemoryCache */
66
+    private $cache;
67
+
68
+    /** @var EventDispatcher */
69
+    private $eventDispatcher;
70
+
71
+    /**
72
+     * \OC\User\Database constructor.
73
+     *
74
+     * @param EventDispatcher $eventDispatcher
75
+     */
76
+    public function __construct($eventDispatcher = null) {
77
+        $this->cache = new CappedMemoryCache();
78
+        $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->getEventDispatcher();
79
+    }
80
+
81
+    /**
82
+     * Create a new user
83
+     * @param string $uid The username of the user to create
84
+     * @param string $password The password of the new user
85
+     * @return bool
86
+     *
87
+     * Creates a new user. Basic checking of username is done in OC_User
88
+     * itself, not in its subclasses.
89
+     */
90
+    public function createUser($uid, $password) {
91
+        if (!$this->userExists($uid)) {
92
+            $event = new GenericEvent($password);
93
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
94
+            $query = \OC_DB::prepare('INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )');
95
+            $result = $query->execute(array($uid, \OC::$server->getHasher()->hash($password)));
96
+
97
+            // Clear cache
98
+            unset($this->cache[$uid]);
99
+
100
+            return $result ? true : false;
101
+        }
102
+
103
+        return false;
104
+    }
105
+
106
+    /**
107
+     * delete a user
108
+     * @param string $uid The username of the user to delete
109
+     * @return bool
110
+     *
111
+     * Deletes a user
112
+     */
113
+    public function deleteUser($uid) {
114
+        // Delete user-group-relation
115
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*users` WHERE `uid` = ?');
116
+        $result = $query->execute(array($uid));
117
+
118
+        if (isset($this->cache[$uid])) {
119
+            unset($this->cache[$uid]);
120
+        }
121
+
122
+        return $result ? true : false;
123
+    }
124
+
125
+    /**
126
+     * Set password
127
+     * @param string $uid The username
128
+     * @param string $password The new password
129
+     * @return bool
130
+     *
131
+     * Change the password of a user
132
+     */
133
+    public function setPassword($uid, $password) {
134
+        if ($this->userExists($uid)) {
135
+            $event = new GenericEvent($password);
136
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
137
+            $query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `password` = ? WHERE `uid` = ?');
138
+            $result = $query->execute(array(\OC::$server->getHasher()->hash($password), $uid));
139
+
140
+            return $result ? true : false;
141
+        }
142
+
143
+        return false;
144
+    }
145
+
146
+    /**
147
+     * Set display name
148
+     * @param string $uid The username
149
+     * @param string $displayName The new display name
150
+     * @return bool
151
+     *
152
+     * Change the display name of a user
153
+     */
154
+    public function setDisplayName($uid, $displayName) {
155
+        if ($this->userExists($uid)) {
156
+            $query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `displayname` = ? WHERE LOWER(`uid`) = LOWER(?)');
157
+            $query->execute(array($displayName, $uid));
158
+            $this->cache[$uid]['displayname'] = $displayName;
159
+
160
+            return true;
161
+        }
162
+
163
+        return false;
164
+    }
165
+
166
+    /**
167
+     * get display name of the user
168
+     * @param string $uid user ID of the user
169
+     * @return string display name
170
+     */
171
+    public function getDisplayName($uid) {
172
+        $this->loadUser($uid);
173
+        return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
174
+    }
175
+
176
+    /**
177
+     * Get a list of all display names and user ids.
178
+     *
179
+     * @param string $search
180
+     * @param string|null $limit
181
+     * @param string|null $offset
182
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
183
+     */
184
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
185
+        $parameters = [];
186
+        $searchLike = '';
187
+        if ($search !== '') {
188
+            $parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
189
+            $parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
190
+            $searchLike = ' WHERE LOWER(`displayname`) LIKE LOWER(?) OR '
191
+                . 'LOWER(`uid`) LIKE LOWER(?)';
192
+        }
193
+
194
+        $displayNames = array();
195
+        $query = \OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users`'
196
+            . $searchLike .' ORDER BY `uid` ASC', $limit, $offset);
197
+        $result = $query->execute($parameters);
198
+        while ($row = $result->fetchRow()) {
199
+            $displayNames[$row['uid']] = $row['displayname'];
200
+        }
201
+
202
+        return $displayNames;
203
+    }
204
+
205
+    /**
206
+     * Check if the password is correct
207
+     * @param string $uid The username
208
+     * @param string $password The password
209
+     * @return string
210
+     *
211
+     * Check if the password is correct without logging in the user
212
+     * returns the user id or false
213
+     */
214
+    public function checkPassword($uid, $password) {
215
+        $query = \OC_DB::prepare('SELECT `uid`, `password` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
216
+        $result = $query->execute(array($uid));
217
+
218
+        $row = $result->fetchRow();
219
+        if ($row) {
220
+            $storedHash = $row['password'];
221
+            $newHash = '';
222
+            if(\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
223
+                if(!empty($newHash)) {
224
+                    $this->setPassword($uid, $password);
225
+                }
226
+                return $row['uid'];
227
+            }
228
+
229
+        }
230
+
231
+        return false;
232
+    }
233
+
234
+    /**
235
+     * Load an user in the cache
236
+     * @param string $uid the username
237
+     * @return boolean true if user was found, false otherwise
238
+     */
239
+    private function loadUser($uid) {
240
+        if (!isset($this->cache[$uid])) {
241
+            //guests $uid could be NULL or ''
242
+            if ($uid === null || $uid === '') {
243
+                $this->cache[$uid]=false;
244
+                return true;
245
+            }
246
+
247
+            $query = \OC_DB::prepare('SELECT `uid`, `displayname` FROM `*PREFIX*users` WHERE LOWER(`uid`) = LOWER(?)');
248
+            $result = $query->execute(array($uid));
249
+
250
+            if ($result === false) {
251
+                Util::writeLog('core', \OC_DB::getErrorMessage(), Util::ERROR);
252
+                return false;
253
+            }
254
+
255
+            $this->cache[$uid] = false;
256
+
257
+            // "uid" is primary key, so there can only be a single result
258
+            if ($row = $result->fetchRow()) {
259
+                $this->cache[$uid]['uid'] = $row['uid'];
260
+                $this->cache[$uid]['displayname'] = $row['displayname'];
261
+                $result->closeCursor();
262
+            } else {
263
+                $result->closeCursor();
264
+                return false;
265
+            }
266
+        }
267
+
268
+        return true;
269
+    }
270
+
271
+    /**
272
+     * Get a list of all users
273
+     *
274
+     * @param string $search
275
+     * @param null|int $limit
276
+     * @param null|int $offset
277
+     * @return string[] an array of all uids
278
+     */
279
+    public function getUsers($search = '', $limit = null, $offset = null) {
280
+        $parameters = [];
281
+        $searchLike = '';
282
+        if ($search !== '') {
283
+            $parameters[] = '%' . \OC::$server->getDatabaseConnection()->escapeLikeParameter($search) . '%';
284
+            $searchLike = ' WHERE LOWER(`uid`) LIKE LOWER(?)';
285
+        }
286
+
287
+        $query = \OC_DB::prepare('SELECT `uid` FROM `*PREFIX*users`' . $searchLike . ' ORDER BY `uid` ASC', $limit, $offset);
288
+        $result = $query->execute($parameters);
289
+        $users = array();
290
+        while ($row = $result->fetchRow()) {
291
+            $users[] = $row['uid'];
292
+        }
293
+        return $users;
294
+    }
295
+
296
+    /**
297
+     * check if a user exists
298
+     * @param string $uid the username
299
+     * @return boolean
300
+     */
301
+    public function userExists($uid) {
302
+        $this->loadUser($uid);
303
+        return $this->cache[$uid] !== false;
304
+    }
305
+
306
+    /**
307
+     * get the user's home directory
308
+     * @param string $uid the username
309
+     * @return string|false
310
+     */
311
+    public function getHome($uid) {
312
+        if ($this->userExists($uid)) {
313
+            return \OC::$server->getConfig()->getSystemValue("datadirectory", \OC::$SERVERROOT . "/data") . '/' . $uid;
314
+        }
315
+
316
+        return false;
317
+    }
318
+
319
+    /**
320
+     * @return bool
321
+     */
322
+    public function hasUserListings() {
323
+        return true;
324
+    }
325
+
326
+    /**
327
+     * counts the users in the database
328
+     *
329
+     * @return int|bool
330
+     */
331
+    public function countUsers() {
332
+        $query = \OC_DB::prepare('SELECT COUNT(*) FROM `*PREFIX*users`');
333
+        $result = $query->execute();
334
+        if ($result === false) {
335
+            Util::writeLog('core', \OC_DB::getErrorMessage(), Util::ERROR);
336
+            return false;
337
+        }
338
+        return $result->fetchOne();
339
+    }
340
+
341
+    /**
342
+     * returns the username for the given login name in the correct casing
343
+     *
344
+     * @param string $loginName
345
+     * @return string|false
346
+     */
347
+    public function loginName2UserName($loginName) {
348
+        if ($this->userExists($loginName)) {
349
+            return $this->cache[$loginName]['uid'];
350
+        }
351
+
352
+        return false;
353
+    }
354
+
355
+    /**
356
+     * Backend name to be shown in user management
357
+     * @return string the name of the backend to be shown
358
+     */
359
+    public function getBackendName(){
360
+        return 'Database';
361
+    }
362
+
363
+    public static function preLoginNameUsedAsUserName($param) {
364
+        if(!isset($param['uid'])) {
365
+            throw new \Exception('key uid is expected to be set in $param');
366
+        }
367
+
368
+        $backends = \OC::$server->getUserManager()->getBackends();
369
+        foreach ($backends as $backend) {
370
+            if ($backend instanceof Database) {
371
+                /** @var \OC\User\Database $backend */
372
+                $uid = $backend->loginName2UserName($param['uid']);
373
+                if ($uid !== false) {
374
+                    $param['uid'] = $uid;
375
+                    return;
376
+                }
377
+            }
378
+        }
379
+
380
+    }
381 381
 }
Please login to merge, or discard this patch.