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
|
<?php
include_once './includes/Database.php';
const USER_LEVEL_MODERATOR = 1;
class User
{
public $id;
public $name;
public $password;
public $date;
public $level = 0;
private $has_value = false;
// Can't use a constructor here because we have two possible ways to get the user from the database
// and PHP does not allow function overloading.
public function get_by_id($id)
{
$sql = "SELECT user_name, user_date, user_level, user_pass FROM users WHERE user_id = ?;";
$result = Database::get()->query($sql, "i", $id);
if (empty($result)) {
return;
}
$this->id = $id;
$this->name = $result[0]['user_name'];
$this->password = $result[0]['user_pass'];
$this->date = $result[0]['user_date'];
$this->level = $result[0]['user_level'];
$this->has_value = true;
}
public function get_by_name($name)
{
$sql = "SELECT user_id, user_date, user_level, user_pass FROM users WHERE user_name = ?";
$result = Database::get()->query($sql, "s", $name);
if (empty($result)) {
return;
}
$this->id = $result[0]['user_id'];
$this->name = $name;
$this->password = $result[0]['user_pass'];
$this->date = $result[0]['user_date'];
$this->level = $result[0]['user_level'];
$this->has_value = true;
}
public function has_value(): bool
{
return $this->has_value;
}
public static function register(string $username, string $password)
{
$sql = "INSERT INTO users(user_name, user_pass, user_date, user_level) VALUES(?, ?, NOW(), 0);";
$pass_hash = password_hash($password, PASSWORD_DEFAULT);
Database::get()->query($sql, "ss", $username, $pass_hash);
}
public function change_password(string $pass_hash)
{
if (!Session::get()->is_signed_in()) {
trigger_error('You are not signed in.');
return;
}
if (Session::get()->get_current_user()->id != $this->id) {
trigger_error("You can't change another user's password.");
return;
}
$sql = "UPDATE users SET user_pass = ? WHERE user_id = ?;";
Database::get()->query($sql, "si", $pass_hash, $this->id);
}
public function get_threads(): array
{
$sql = "SELECT thread_id FROM threads WHERE thread_author = ? ORDER BY thread_date_lastpost DESC";
$result = Database::get()->query($sql, "i", $this->id);
$threads = array();
foreach ($result as $row) {
$thread = new Thread($row['thread_id']);
if ($thread->has_value())
array_push($threads, $thread);
}
return $threads;
}
public static function username_exists(string $username): bool
{
$sql = "SELECT * FROM users WHERE user_name = ?;";
$result = Database::get()->query($sql, "s", $username);
return !empty($result);
}
}
|