]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blame - plugins/sql_db/sql_db.php
Shut up some errors
[irc/unrealircd/unrealircd-webpanel.git] / plugins / sql_db / sql_db.php
CommitLineData
ea27475b
VP
1<?php
2
3require_once "SQL/sql.php";
ce9cf366 4require_once "SQL/settings.php";
4d634d0a 5
ce25dde2 6class sql_db
ea27475b 7{
ce25dde2 8 public $name = "SQLDB";
ea27475b
VP
9 public $author = "Valware";
10 public $version = "1.0";
ce25dde2 11 public $description = "SQL database backend";
b65f0496 12 public $email = "v.a.pond@outlook.com";
ea27475b
VP
13
14 function __construct()
15 {
ce25dde2
BM
16 Hook::func(HOOKTYPE_USER_LOOKUP, 'sql_db::get_user');
17 Hook::func(HOOKTYPE_USERMETA_ADD, 'sql_db::add_usermeta');
18 Hook::func(HOOKTYPE_USERMETA_DEL, 'sql_db::del_usermeta');
19 Hook::func(HOOKTYPE_USERMETA_GET, 'sql_db::get_usermeta');
20 Hook::func(HOOKTYPE_USER_CREATE, 'sql_db::user_create');
21 Hook::func(HOOKTYPE_GET_USER_LIST, 'sql_db::get_user_list');
22 Hook::func(HOOKTYPE_USER_DELETE, 'sql_db::user_delete');
23 Hook::func(HOOKTYPE_EDIT_USER, 'sql_db::edit_core');
24 Hook::func(HOOKTYPE_PRE_OVERVIEW_CARD, 'sql_db::add_pre_overview_card');
25 Hook::func(HOOKTYPE_UPGRADE, 'sql_db::create_tables'); // handles upgrades too ;)
c00c34d2 26 AuthModLoaded::$status = 1;
ea27475b
VP
27 }
28
b6a7129b
BM
29 public static function add_pre_overview_card($empty)
30 {
31 if (defined('SQL_DEFAULT_USER'))
32 Message::Fail("Warning: SQL_DEFAULT_USER is set in config.php. You should remove that item now, as it is only used during installation.");
5611f966
BM
33 if (defined('DEFAULT_USER'))
34 Message::Fail("Warning: DEFAULT_USER is set in config.php. You should remove that item now, as it is only used during installation.");
b6a7129b
BM
35 }
36
1bbc51fb
BM
37 /**
38 * Delete all the tables (of us) in the SQLdb
39 * @return void
40 */
41 public static function delete_tables()
42 {
43 $conn = sqlnew();
44 foreach(["users","user_meta", "settings", "fail2ban"] as $table_name)
45 $conn->query("DROP TABLE IF EXISTS " . get_config("mysql::table_prefix") . $table_name);
46 }
47
ce9cf366
VP
48 /**
49 * Create the tables we'll be using in the SQLdb
50 * @return void
51 */
5015c85c
VP
52 public static function create_tables()
53 {
54 $conn = sqlnew();
2dbe2544
VP
55 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "users (
56 user_id int AUTO_INCREMENT NOT NULL,
57 user_name VARCHAR(255) NOT NULL,
58 user_pass VARCHAR(255) NOT NULL,
59 user_email VARCHAR(255),
60 user_fname VARCHAR(255),
61 user_lname VARCHAR(255),
62 user_bio VARCHAR(255),
63 created VARCHAR(255),
64 PRIMARY KEY (user_id)
65 )");
66
67 /**
68 * Patch for beta users
69 * This adds the email column to existing tables without it
70 */
71 $columns = $conn->query("SHOW COLUMNS FROM " . get_config("mysql::table_prefix") . "users");
72 $column_names = array();
73 $c = $columns->fetchAll();
74
75 foreach($c as $column) {
76 $column_names[] = $column['Field'];
77 }
78 $column_exists = in_array("user_email", $column_names);
79 if (!$column_exists) {
80 $conn->query("ALTER TABLE " . get_config("mysql::table_prefix") . "users ADD COLUMN user_email varchar(255)");
81 }
82
83 /**
84 * Another patch for beta users
85 * This changes the size of the meta_value so we can store more
86 */
87
88 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "user_meta (
89 meta_id int AUTO_INCREMENT NOT NULL,
90 user_id int NOT NULL,
91 meta_key VARCHAR(255) NOT NULL,
92 meta_value VARCHAR(255),
7058d6d1
BM
93 PRIMARY KEY (meta_id),
94 CONSTRAINT meta_key_user_id UNIQUE(meta_key,user_id)
2dbe2544 95 )");
b41fa16f 96 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "settings (
2dbe2544
VP
97 id int AUTO_INCREMENT NOT NULL,
98 setting_key VARCHAR(255) NOT NULL,
0356d3b1 99 setting_value LONGTEXT,
a20d0d39
BM
100 PRIMARY KEY (id),
101 UNIQUE(setting_key)
2dbe2544
VP
102 )");
103 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "fail2ban (
104 id int AUTO_INCREMENT NOT NULL,
105 ip VARCHAR(255) NOT NULL,
106 count VARCHAR(255),
107 PRIMARY KEY (id)
108 )");
e1461204
BM
109
110 /* Upgrades: */
7058d6d1 111 /* - user_meta: set charset and size */
2dbe2544 112 $c = [];
088733d4 113 if (($columns = $conn->query("SHOW COLUMNS FROM ".get_config("mysql::table_prefix")."user_meta")))
2dbe2544
VP
114 $c = $columns->fetchAll();
115 if (!empty($c))
0356d3b1 116 $conn->query("ALTER TABLE ".get_config("mysql::table_prefix")."user_meta CHANGE `meta_value` `meta_value` LONGTEXT CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NULL DEFAULT NULL");
2dbe2544 117
7058d6d1 118 /* - settings: add UNIQUE(setting_key) */
e1461204 119 $c = [];
088733d4 120 if (($columns = $conn->query("SHOW INDEXES FROM ".get_config("mysql::table_prefix")."settings WHERE Key_name='setting_key'")))
e1461204
BM
121 $c = $columns->fetchAll();
122 if (empty($c))
088733d4 123 {
7058d6d1 124 $conn->query("ALTER TABLE " . get_config("mysql::table_prefix") . "settings ADD CONSTRAINT setting_key UNIQUE(setting_key)");
088733d4
VP
125 }
126 else
0356d3b1 127 $conn->query("ALTER TABLE ".get_config("mysql::table_prefix")."settings CHANGE setting_value setting_value LONGTEXT CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NULL DEFAULT NULL");
088733d4 128
7058d6d1
BM
129 /* - user_meta: add UNIQUE(meta_key,user_id) */
130 $c = [];
088733d4 131 if (($columns = $conn->query("SHOW INDEXES FROM ".get_config("mysql::table_prefix")."user_meta WHERE Key_name='meta_key_user_id'")))
7058d6d1
BM
132 $c = $columns->fetchAll();
133 if (empty($c))
134 $conn->query("ALTER TABLE " . get_config("mysql::table_prefix") . "user_meta ADD CONSTRAINT meta_key_user_id UNIQUE(meta_key,user_id)");
135
2dbe2544 136 /* make sure everything went well */
b41fa16f 137 $tables = ["users", "user_meta", "fail2ban", "settings"];
2dbe2544
VP
138 $errors = 0; // counter
139 $error_messages = "";
140 foreach($tables as $table)
f2c7ac01 141 {
ca3c76f7 142 $prefix = get_config("sql::table_prefix");
2dbe2544
VP
143 $sql = "SHOW TABLES LIKE '$prefix%'"; // SQL query to check if table exists
144
145 $result = $conn->query($sql);
146 if ($result->rowCount())
147 { /* great! */ }
148
149 else {
150 $errors++;
151 strcat($error_messages,"Table '$prefix$table' was not created successfully.<br>");
152 }
f2c7ac01 153 }
2dbe2544
VP
154 if (!$errors)
155 {
156 if (defined('DEFAULT_USER')) // we've got a default account
157 {
158 $lkup = new PanelUser(DEFAULT_USER['username']);
159
160 if (!$lkup->id) // doesn't exist, add it with full privileges
161 {
162 $user = [];
163 $user['user_name'] = DEFAULT_USER['username'];
164 $user['user_pass'] = DEFAULT_USER['password'];
165 $user['err'] = "";
166 create_new_user($user);
167 }
168 $lkup = new PanelUser(DEFAULT_USER['username']);
169 if (!user_can($lkup, PERMISSION_MANAGE_USERS))
170 $lkup->add_permission(PERMISSION_MANAGE_USERS);
171 }
172 return true;
173 }
174 else
175 return false;
176
5015c85c
VP
177 }
178
6930484c
VP
179 /* We convert $u with a full user as an object ;D*/
180 public static function get_user(&$u)
181 {
182 $id = $u['id'];
183 $name = $u['name'];
184 $conn = sqlnew();
185
186 if ($id)
187 {
ea90b321 188 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id LIMIT 1");
6930484c
VP
189 $prep->execute(["id" => strtolower($id)]);
190 }
191 elseif ($name)
192 {
ea90b321 193 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "users WHERE LOWER(user_name) = :name LIMIT 1");
6930484c
VP
194 $prep->execute(["name" => strtolower($name)]);
195 }
196 $data = NULL;
197 $obj = (object) [];
198 if ($prep)
199 $data = $prep->fetchAll();
200 if (isset($data[0]) && $data = $data[0])
201 {
202 $obj->id = $data['user_id'];
203 $obj->username = $data['user_name'];
204 $obj->passhash = $data['user_pass'];
205 $obj->first_name = $data['user_fname'] ?? NULL;
206 $obj->last_name = $data['user_lname'] ?? NULL;
207 $obj->created = $data['created'];
208 $obj->bio = $data['user_bio'];
9a674833 209 $obj->email = $data['user_email'];
6930484c
VP
210 $obj->user_meta = (new PanelUser_Meta($obj->id))->list;
211 }
212 $u['object'] = $obj;
213 }
214
215 public static function get_usermeta(&$u)
216 {
6930484c
VP
217 $list = &$u['meta'];
218 $id = $u['id'];
219 $conn = sqlnew();
220 if (isset($id))
221 {
ea90b321 222 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id");
6930484c
VP
223 $prep->execute(["id" => $id]);
224 }
225 foreach ($prep->fetchAll() as $row)
226 {
227 $list[$row['meta_key']] = $row['meta_value'];
228 }
229 }
230
231 public static function add_usermeta(&$meta)
232 {
da6fa2d1 233 $meta = $meta['meta'];
6930484c
VP
234 $conn = sqlnew();
235 /* check if it exists first, update it if it does */
ea90b321 236 $query = "SELECT * FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id AND meta_key = :key";
6930484c
VP
237 $stmt = $conn->prepare($query);
238 $stmt->execute(["id" => $meta['id'], "key" => $meta['key']]);
239 if ($stmt->rowCount()) // it exists, update instead of insert
240 {
ea90b321 241 $query = "UPDATE " . get_config("mysql::table_prefix") . "user_meta SET meta_value = :value WHERE user_id = :id AND meta_key = :key";
6930484c
VP
242 $stmt = $conn->prepare($query);
243 $stmt->execute($meta);
244 if ($stmt->rowCount())
245 return true;
246 return false;
247 }
248
249 else
250 {
ea90b321 251 $query = "INSERT INTO " . get_config("mysql::table_prefix") . "user_meta (user_id, meta_key, meta_value) VALUES (:id, :key, :value)";
6930484c
VP
252 $stmt = $conn->prepare($query);
253 $stmt->execute($meta);
254 if ($stmt->rowCount())
255 return true;
256 return false;
257 }
258 }
c53841fe 259 public static function del_usermeta(&$meta)
6930484c
VP
260 {
261 $conn = sqlnew();
ea90b321 262 $query = "DELETE FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id AND meta_key = :key";
6930484c 263 $stmt = $conn->prepare($query);
c53841fe 264 $stmt->execute($meta['meta']);
6930484c
VP
265 if ($stmt->rowCount())
266 return true;
267 return false;
268 }
180b8ec1
VP
269 public static function user_create(&$u)
270 {
271 $username = $u['user_name'];
9f9d16d5
VP
272 $first_name = $u['fname'] ?? NULL;
273 $last_name = $u['lname'] ?? NULL;
274 $password = $u['user_pass'] ?? NULL;
275 $user_bio = $u['user_bio'] ?? NULL;
276 $user_email = $u['user_email'] ?? NULL;
180b8ec1 277 $conn = sqlnew();
ea90b321 278 $prep = $conn->prepare("INSERT INTO " . get_config("mysql::table_prefix") . "users (user_name, user_pass, user_fname, user_lname, user_bio, user_email, created) VALUES (:name, :pass, :fname, :lname, :user_bio, :user_email, :created)");
9a674833 279 $prep->execute(["name" => $username, "pass" => $password, "fname" => $first_name, "lname" => $last_name, "user_bio" => $user_bio, "user_email" => $user_email, "created" => date("Y-m-d H:i:s")]);
180b8ec1
VP
280 if ($prep->rowCount())
281 $u['success'] = true;
282 else
283 $u['errmsg'][] = "Could not add user";
284 }
285
286 public static function get_user_list(&$list)
287 {
288 $conn = sqlnew();
ea90b321 289 $result = $conn->query("SELECT user_id FROM " . get_config("mysql::table_prefix") . "users");
180b8ec1
VP
290 if (!$result) // impossible
291 {
292 die("Something went wrong.");
293 }
294 $userlist = [];
295 while($row = $result->fetch())
296 {
297 $userlist[] = new PanelUser(NULL, $row['user_id']);
298 }
299 if (!empty($userlist))
300 $list = $userlist;
301
302 }
303 public static function user_delete(&$u)
304 {
305 $user = $u['user'];
ea90b321 306 $query = "DELETE FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id";
180b8ec1
VP
307 $conn = sqlnew();
308 $stmt = $conn->prepare($query);
309 $stmt->execute(["id" => $user->id]);
310 $deleted = $stmt->rowCount();
311 if ($deleted)
312 {
313 $u['info'][] = "Successfully deleted user \"$user->username\"";
314 $u['boolint'] = 1;
315 } else {
316 $u['info'][] = "Unknown error";
317 $u['boolint'] = 0;
318 }
319 }
5a7f0cde
VP
320
321 public static function edit_core($arr)
322 {
323 $conn = sqlnew();
324 $user = $arr['user'];
325 $info = $arr['info'];
326 foreach($info as $key => $val)
327 {
e9c858fd 328 $value = NULL;
8a73256b 329 if (!$val || !strlen($val) || BadPtr($val))
5a7f0cde 330 continue;
e9c858fd
VP
331 if (!strcmp($key,"update_fname") && $val != $user->first_name)
332 {
5a7f0cde 333 $value = "user_fname";
e9c858fd
VP
334 $valuestr = "first name";
335 }
336 elseif (!strcmp($key,"update_lname") && $val != $user->last_name)
337 {
5a7f0cde 338 $value = "user_lname";
e9c858fd
VP
339 $valuestr = "last name";
340 }
341 elseif (!strcmp($key,"update_bio") && $val != $user->bio)
342 {
5a7f0cde 343 $value = "user_bio";
e9c858fd
VP
344 $valuestr = "bio";
345 }
5a7f0cde 346 elseif (!strcmp($key,"update_pass") || !strcmp($key,"update_pass_conf"))
e9c858fd 347 {
5a7f0cde 348 $value = "user_pass";
e9c858fd
VP
349 $valuestr = "password";
350 }
351 elseif(!strcmp($key,"update_email") && $val != $user->email)
352 {
5a7f0cde 353 $value = "user_email";
e9c858fd
VP
354 $valuestr = "email address";
355 }
356
357 if (!$value)
358 continue;
ea90b321 359 $query = "UPDATE " . get_config("mysql::table_prefix") . "users SET $value=:value WHERE user_id = :id";
5a7f0cde
VP
360 $stmt = $conn->prepare($query);
361 $stmt->execute(["value" => $val, "id" => $user->id]);
e9c858fd
VP
362
363 if (!$stmt->rowCount() && $stmt->errorInfo()[0] != "00000")
364 Message::Fail("Could not update $valuestr for $user->username: ".$stmt->errorInfo()[0]." (CODE: ".$stmt->errorCode().")");
365
366 else
367 Message::Success("Successfully updated the $valuestr for $user->username");
5a7f0cde
VP
368 }
369 }
ce9cf366
VP
370}
371
372
373function security_check()
374{
375 $ip = $_SERVER['REMOTE_ADDR'];
376 if (dnsbl_check($ip))
377 return true;
378
379 else if (fail2ban_check($ip))
380 {
381
382 }
383}
384
385function dnsbl_check($ip)
386{
bb2ee92b 387 $dnsbl_lookup = get_config("dnsbl");
c51d17f4 388 if (!$dnsbl_lookup)
5a7f0cde 389 return;
ce9cf366
VP
390
391 // clear variable just in case
392 $listed = NULL;
393
394 // if the IP was not given because you're an idiot, stop processing
395 if (!$ip) { return; }
396
397 // get the first two segments of the IPv4
398 $because = split($ip, "."); // why you
399 $you = $because[1]; // gotta play
400 $want = $because[2]; // that song
401 $to = $you.".".$want."."; // so loud?
402
403 // exempt local connections because sometimes they get a false positive
404 if ($to == "192.168." || $to == "127.0.") { return NULL; }
405
406 // you spin my IP right round, right round, to check the records baby, right round-round-round
407 $reverse_ip = glue(array_reverse(split($ip, ".")), ".");
408
409 // checkem
410 foreach ($dnsbl_lookup as $host) {
411
412 //if it was listed
413 if (checkdnsrr($reverse_ip . "." . $host . ".", "A")) {
414
415 //take note
416 $listed = $host;
417 }
418 }
419
420 // if it was safe, return NOTHING
421 if (!$listed) {
422 return NULL;
423 }
424
425 // else, you guessed it, return where it was listed
426 else {
427 return $listed;
428 }
429}
430
431function fail2ban_check($ip)
33f512fa
VP
432{
433
434}