]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blob - plugins/sql_db/sql_db.php
Add able to change background on overview
[irc/unrealircd/unrealircd-webpanel.git] / plugins / sql_db / sql_db.php
1 <?php
2
3 require_once "SQL/sql.php";
4 require_once "SQL/settings.php";
5
6 class sql_db
7 {
8 public $name = "SQLDB";
9 public $author = "Valware";
10 public $version = "1.0";
11 public $description = "SQL database backend";
12 public $email = "v.a.pond@outlook.com";
13
14 function __construct()
15 {
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 ;)
26 AuthModLoaded::$status = 1;
27 }
28
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.");
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.");
35 }
36
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
48 /**
49 * Create the tables we'll be using in the SQLdb
50 * @return void
51 */
52 public static function create_tables()
53 {
54 $conn = sqlnew();
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),
93 PRIMARY KEY (meta_id),
94 CONSTRAINT meta_key_user_id UNIQUE(meta_key,user_id)
95 )");
96 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "settings (
97 id int AUTO_INCREMENT NOT NULL,
98 setting_key VARCHAR(255) NOT NULL,
99 setting_value VARCHAR(5000),
100 PRIMARY KEY (id),
101 UNIQUE(setting_key)
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 )");
109
110 /* Upgrades: */
111 /* - user_meta: set charset and size */
112 $c = [];
113 if (($columns = $conn->query("SHOW COLUMNS FROM ".get_config("mysql::table_prefix")."user_meta")))
114 $c = $columns->fetchAll();
115 if (!empty($c))
116 $conn->query("ALTER TABLE ".get_config("mysql::table_prefix")."user_meta CHANGE `meta_value` `meta_value` VARCHAR(5000) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NULL DEFAULT NULL");
117
118 /* - settings: add UNIQUE(setting_key) */
119 $c = [];
120 if (($columns = $conn->query("SHOW INDEXES FROM ".get_config("mysql::table_prefix")."settings WHERE Key_name='setting_key'")))
121 $c = $columns->fetchAll();
122 if (empty($c))
123 {
124 $conn->query("ALTER TABLE " . get_config("mysql::table_prefix") . "settings ADD CONSTRAINT setting_key UNIQUE(setting_key)");
125 }
126 else
127 $conn->query("ALTER TABLE ".get_config("mysql::table_prefix")."settings CHANGE setting_value setting_value VARCHAR(5000) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NULL DEFAULT NULL");
128
129 /* - user_meta: add UNIQUE(meta_key,user_id) */
130 $c = [];
131 if (($columns = $conn->query("SHOW INDEXES FROM ".get_config("mysql::table_prefix")."user_meta WHERE Key_name='meta_key_user_id'")))
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
136 /* make sure everything went well */
137 $tables = ["users", "user_meta", "fail2ban", "settings"];
138 $errors = 0; // counter
139 $error_messages = "";
140 foreach($tables as $table)
141 {
142 $prefix = get_config("sql::table_prefix");
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 }
153 }
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
177 }
178
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 {
188 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id LIMIT 1");
189 $prep->execute(["id" => strtolower($id)]);
190 }
191 elseif ($name)
192 {
193 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "users WHERE LOWER(user_name) = :name LIMIT 1");
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'];
209 $obj->email = $data['user_email'];
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 {
217 $list = &$u['meta'];
218 $id = $u['id'];
219 $conn = sqlnew();
220 if (isset($id))
221 {
222 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id");
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 {
233 $meta = $meta['meta'];
234 $conn = sqlnew();
235 /* check if it exists first, update it if it does */
236 $query = "SELECT * FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id AND meta_key = :key";
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 {
241 $query = "UPDATE " . get_config("mysql::table_prefix") . "user_meta SET meta_value = :value WHERE user_id = :id AND meta_key = :key";
242 $stmt = $conn->prepare($query);
243 $stmt->execute($meta);
244 if ($stmt->rowCount())
245 return true;
246 return false;
247 }
248
249 else
250 {
251 $query = "INSERT INTO " . get_config("mysql::table_prefix") . "user_meta (user_id, meta_key, meta_value) VALUES (:id, :key, :value)";
252 $stmt = $conn->prepare($query);
253 $stmt->execute($meta);
254 if ($stmt->rowCount())
255 return true;
256 return false;
257 }
258 }
259 public static function del_usermeta(&$meta)
260 {
261 $conn = sqlnew();
262 $query = "DELETE FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id AND meta_key = :key";
263 $stmt = $conn->prepare($query);
264 $stmt->execute($meta['meta']);
265 if ($stmt->rowCount())
266 return true;
267 return false;
268 }
269 public static function user_create(&$u)
270 {
271 $username = $u['user_name'];
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;
277 $conn = sqlnew();
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)");
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")]);
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();
289 $result = $conn->query("SELECT user_id FROM " . get_config("mysql::table_prefix") . "users");
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'];
306 $query = "DELETE FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id";
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 }
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 {
328 $value = NULL;
329 if (!$val || !strlen($val) || BadPtr($val))
330 continue;
331 if (!strcmp($key,"update_fname") && $val != $user->first_name)
332 {
333 $value = "user_fname";
334 $valuestr = "first name";
335 }
336 elseif (!strcmp($key,"update_lname") && $val != $user->last_name)
337 {
338 $value = "user_lname";
339 $valuestr = "last name";
340 }
341 elseif (!strcmp($key,"update_bio") && $val != $user->bio)
342 {
343 $value = "user_bio";
344 $valuestr = "bio";
345 }
346 elseif (!strcmp($key,"update_pass") || !strcmp($key,"update_pass_conf"))
347 {
348 $value = "user_pass";
349 $valuestr = "password";
350 }
351 elseif(!strcmp($key,"update_email") && $val != $user->email)
352 {
353 $value = "user_email";
354 $valuestr = "email address";
355 }
356
357 if (!$value)
358 continue;
359 $query = "UPDATE " . get_config("mysql::table_prefix") . "users SET $value=:value WHERE user_id = :id";
360 $stmt = $conn->prepare($query);
361 $stmt->execute(["value" => $val, "id" => $user->id]);
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");
368 }
369 }
370 }
371
372
373 function 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
385 function dnsbl_check($ip)
386 {
387 $dnsbl_lookup = get_config("dnsbl");
388 if (!$dnsbl_lookup)
389 return;
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
431 function fail2ban_check($ip)
432 {
433
434 }