summaryrefslogtreecommitdiff
path: root/app/User.php
blob: fb36eafa4b597ad03592922e6cd1230263c939a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
<?php
/**
 * webtrees: online genealogy
 * Copyright (C) 2017 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
namespace Fisharebest\Webtrees;

use stdclass;

/**
 * Provide an interface to the wt_user table.
 */
class User {
	/** @var  string The primary key of this user. */
	private $user_id;

	/** @var  string The login name of this user. */
	private $user_name;

	/** @var  string The real (display) name of this user. */
	private $real_name;

	/** @var  string The email address of this user. */
	private $email;

	/** @var string[] Cached copy of the wt_user_setting table. */
	private $preferences = [];

	/** @var  User[] Only fetch users from the database once. */
	private static $cache = [];

	/**
	 * Find the user with a specified user_id.
	 *
	 * @param int|null $user_id
	 *
	 * @return User|null
	 */
	public static function find($user_id) {
		if (!array_key_exists($user_id, self::$cache)) {
			$row = Database::prepare(
				"SELECT SQL_CACHE user_id, user_name, real_name, email FROM `##user` WHERE user_id = ?"
			)->execute([$user_id])->fetchOneRow();
			if ($row) {
				self::$cache[$user_id] = new self($row);
			} else {
				self::$cache[$user_id] = null;
			}
		}

		return self::$cache[$user_id];
	}

	/**
	 * Find the user with a specified user_name.
	 *
	 * @param string $user_name
	 *
	 * @return User|null
	 */
	public static function findByUserName($user_name) {
		$user_id = Database::prepare(
			"SELECT SQL_CACHE user_id FROM `##user` WHERE user_name = :user_name"
		)->execute([
			'user_name' => $user_name,
		])->fetchOne();

		return self::find($user_id);
	}

	/**
	 * Find the user with a specified email address.
	 *
	 * @param string $email
	 *
	 * @return User|null
	 */
	public static function findByEmail($email) {
		$user_id = Database::prepare(
			"SELECT SQL_CACHE user_id FROM `##user` WHERE email = :email"
		)->execute([
			'email' => $email,
		])->fetchOne();

		return self::find($user_id);
	}

	/**
	 * Find the user with a specified user_name or email address.
	 *
	 * @param string $identifier
	 *
	 * @return User|null
	 */
	public static function findByIdentifier($identifier) {
		$user_id = Database::prepare(
			"SELECT SQL_CACHE user_id FROM `##user` WHERE ? IN (user_name, email)"
		)->execute([$identifier])->fetchOne();

		return self::find($user_id);
	}

	/**
	 * Find the user with a specified genealogy record.
	 *
	 * @param Individual $individual
	 *
	 * @return User|null
	 */
	public static function findByGenealogyRecord(Individual $individual) {
		$user_id = Database::prepare(
			"SELECT SQL_CACHE user_id" .
			" FROM `##user_gedcom_setting`" .
			" WHERE gedcom_id = :tree_id AND setting_name = 'gedcomid' AND setting_value = :xref"
		)->execute([
			'tree_id' => $individual->getTree()->getTreeId(),
			'xref'    => $individual->getXref(),
		])->fetchOne();

		return self::find($user_id);
	}

	/**
	 * Find the latest user to register.
	 *
	 * @return User|null
	 */
	public static function findLatestToRegister() {
		$user_id = Database::prepare(
			"SELECT SQL_CACHE u.user_id" .
			" FROM `##user` u" .
			" LEFT JOIN `##user_setting` us ON (u.user_id=us.user_id AND us.setting_name='reg_timestamp') " .
			" ORDER BY us.setting_value DESC LIMIT 1"
		)->execute()->fetchOne();

		return self::find($user_id);
	}

	/**
	 * Create a new user.
	 *
	 * The calling code needs to check for duplicates identifiers before calling
	 * this function.
	 *
	 * @param string $user_name
	 * @param string $real_name
	 * @param string $email
	 * @param string $password
	 *
	 * @return User
	 */
	public static function create($user_name, $real_name, $email, $password) {
		Database::prepare(
			"INSERT INTO `##user` (user_name, real_name, email, password) VALUES (:user_name, :real_name, :email, :password)"
		)->execute([
			'user_name' => $user_name,
			'real_name' => $real_name,
			'email'     => $email,
			'password'  => password_hash($password, PASSWORD_DEFAULT),
		]);

		// Set default blocks for this user
		$user = self::findByIdentifier($user_name);
		Database::prepare(
			"INSERT INTO `##block` (`user_id`, `location`, `block_order`, `module_name`)" .
			" SELECT :user_id , `location`, `block_order`, `module_name` FROM `##block` WHERE `user_id` = -1"
		)->execute(['user_id' => $user->getUserId()]);

		return $user;
	}

	/**
	 * Get a count of all users.
	 *
	 * @return int
	 */
	public static function count() {
		return (int) Database::prepare(
			"SELECT SQL_CACHE COUNT(*)" .
			" FROM `##user`" .
			" WHERE user_id > 0"
		)->fetchOne();
	}

	/**
	 * Get a list of all users.
	 *
	 * @return User[]
	 */
	public static function all() {
		$users = [];

		$rows = Database::prepare(
			"SELECT SQL_CACHE user_id, user_name, real_name, email" .
			" FROM `##user`" .
			" WHERE user_id > 0" .
			" ORDER BY user_name"
		)->fetchAll();

		foreach ($rows as $row) {
			$users[] = new self($row);
		}

		return $users;
	}

	/**
	 * Get a list of all administrators.
	 *
	 * @return User[]
	 */
	public static function allAdmins() {
		$rows = Database::prepare(
			"SELECT SQL_CACHE user_id, user_name, real_name, email" .
			" FROM `##user`" .
			" JOIN `##user_setting` USING (user_id)" .
			" WHERE user_id > 0" .
			"   AND setting_name = 'canadmin'" .
			"   AND setting_value = '1'"
		)->fetchAll();

		$users = [];
		foreach ($rows as $row) {
			$users[] = new self($row);
		}

		return $users;
	}

	/**
	 * Get a list of all verified uses.
	 *
	 * @return User[]
	 */
	public static function allVerified() {
		$rows = Database::prepare(
			"SELECT SQL_CACHE user_id, user_name, real_name, email" .
			" FROM `##user`" .
			" JOIN `##user_setting` USING (user_id)" .
			" WHERE user_id > 0" .
			"   AND setting_name = 'verified'" .
			"   AND setting_value = '1'"
		)->fetchAll();

		$users = [];
		foreach ($rows as $row) {
			$users[] = new self($row);
		}

		return $users;
	}

	/**
	 * Get a list of all users who are currently logged in.
	 *
	 * @return User[]
	 */
	public static function allLoggedIn() {
		$rows = Database::prepare(
			"SELECT SQL_NO_CACHE DISTINCT user_id, user_name, real_name, email" .
			" FROM `##user`" .
			" JOIN `##session` USING (user_id)"
		)->fetchAll();

		$users = [];
		foreach ($rows as $row) {
			$users[] = new self($row);
		}

		return $users;
	}

	/**
	 * Create a new user object from a row in the database.
	 *
	 * @param stdclass $user A row from the wt_user table
	 */
	public function __construct(stdClass $user) {
		$this->user_id   = $user->user_id;
		$this->user_name = $user->user_name;
		$this->real_name = $user->real_name;
		$this->email     = $user->email;
	}

	/**
	 * Delete a user
	 */
	public function delete() {
		// Don't delete the logs.
		Database::prepare("UPDATE `##log` SET user_id=NULL WHERE user_id =?")->execute([$this->user_id]);
		// Take over the user’s pending changes. (What else could we do with them?)
		Database::prepare("DELETE FROM `##change` WHERE user_id=? AND status='rejected'")->execute([$this->user_id]);
		Database::prepare("UPDATE `##change` SET user_id=? WHERE user_id=?")->execute([Auth::id(), $this->user_id]);
		Database::prepare("DELETE `##block_setting` FROM `##block_setting` JOIN `##block` USING (block_id) WHERE user_id=?")->execute([$this->user_id]);
		Database::prepare("DELETE FROM `##block` WHERE user_id=?")->execute([$this->user_id]);
		Database::prepare("DELETE FROM `##user_gedcom_setting` WHERE user_id=?")->execute([$this->user_id]);
		Database::prepare("DELETE FROM `##gedcom_setting` WHERE setting_value=? AND setting_name IN ('CONTACT_USER_ID', 'WEBMASTER_USER_ID')")->execute([$this->user_id]);
		Database::prepare("DELETE FROM `##user_setting` WHERE user_id=?")->execute([$this->user_id]);
		Database::prepare("DELETE FROM `##message` WHERE user_id=?")->execute([$this->user_id]);
		Database::prepare("DELETE FROM `##user` WHERE user_id=?")->execute([$this->user_id]);
	}

	/** Validate a supplied password
	 * @param string $password
	 *
	 * @return bool
	 */
	public function checkPassword($password) {
		$password_hash = Database::prepare(
			"SELECT password FROM `##user` WHERE user_id = ?"
		)->execute([$this->user_id])->fetchOne();

		if (password_verify($password, $password_hash)) {
			if (password_needs_rehash($password_hash, PASSWORD_DEFAULT)) {
				$this->setPassword($password);
			}

			return true;
		} else {
			return false;
		}
	}

	/**
	 * Get the numeric ID for this user.
	 *
	 * @return string
	 */
	public function getUserId() {
		return $this->user_id;
	}

	/**
	 * Get the login name for this user.
	 *
	 * @return string
	 */
	public function getUserName() {
		return $this->user_name;
	}

	/**
	 * Set the login name for this user.
	 *
	 * @param string $user_name
	 *
	 * @return $this
	 */
	public function setUserName($user_name) {
		if ($this->user_name !== $user_name) {
			$this->user_name = $user_name;
			Database::prepare(
				"UPDATE `##user` SET user_name = ? WHERE user_id = ?"
			)->execute([$user_name, $this->user_id]);
		}

		return $this;
	}

	/**
	 * Get the real name of this user.
	 *
	 * @return string
	 */
	public function getRealName() {
		return $this->real_name;
	}

	/**
	 * Get the real name of this user, for display on screen.
	 *
	 * @return string
	 */
	public function getRealNameHtml() {
		return '<span dir="auto">' . Filter::escapeHtml($this->real_name) . '</span>';
	}

	/**
	 * Set the real name of this user.
	 *
	 * @param string $real_name
	 *
	 * @return User
	 */
	public function setRealName($real_name) {
		if ($this->real_name !== $real_name) {
			$this->real_name = $real_name;
			Database::prepare(
				"UPDATE `##user` SET real_name = ? WHERE user_id = ?"
			)->execute([$real_name, $this->user_id]);
		}

		return $this;
	}

	/**
	 * Get the email address of this user.
	 *
	 * @return string
	 */
	public function getEmail() {
		return $this->email;
	}

	/**
	 * Set the email address of this user.
	 *
	 * @param string $email
	 *
	 * @return User
	 */
	public function setEmail($email) {
		if ($this->email !== $email) {
			$this->email = $email;
			Database::prepare(
				"UPDATE `##user` SET email = ? WHERE user_id = ?"
			)->execute([$email, $this->user_id]);
		}

		return $this;
	}

	/**
	 * Set the password of this user.
	 *
	 * @param string $password
	 *
	 * @return User
	 */
	public function setPassword($password) {
		Database::prepare(
			"UPDATE `##user` SET password = :password WHERE user_id = :user_id"
		)->execute([
			'password' => password_hash($password, PASSWORD_DEFAULT),
			'user_id'  => $this->user_id,
		]);

		return $this;
	}

	/**
	 * Fetch a user option/setting from the wt_user_setting table.
	 *
	 * Since we'll fetch several settings for each user, and since there aren’t
	 * that many of them, fetch them all in one database query
	 *
	 * @param string $setting_name
	 * @param string $default
	 *
	 * @return string
	 */
	public function getPreference($setting_name, $default = '') {
		if (empty($this->preferences) && $this->user_id !== null) {
			$this->preferences = Database::prepare(
				"SELECT SQL_CACHE setting_name, setting_value" .
				" FROM `##user_setting`" .
				" WHERE user_id = :user_id"
			)->execute([
				'user_id' => $this->user_id,
			])->fetchAssoc();
		}

		if (!array_key_exists($setting_name, $this->preferences)) {
			$this->preferences[$setting_name] = $default;
		}

		return $this->preferences[$setting_name];
	}

	/**
	 * Update a setting for the user.
	 *
	 * @param string $setting_name
	 * @param string $setting_value
	 *
	 * @return User
	 */
	public function setPreference($setting_name, $setting_value) {
		if ($this->user_id && $this->getPreference($setting_name) !== $setting_value) {
			Database::prepare("REPLACE INTO `##user_setting` (user_id, setting_name, setting_value) VALUES (?, ?, LEFT(?, 255))")
				->execute([$this->user_id, $setting_name, $setting_value]);

			$this->preferences[$setting_name] = $setting_value;
		}

		return $this;
	}
}