3 require_once "SQL/sql.php";
4 require_once "SQL/settings.php";
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";
14 function __construct()
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 Hook
::func(HOOKTYPE_USER_ROLE_LIST
, 'sql_db::roles_list');
27 AuthModLoaded
::$status = 1;
30 public static function roles_list(&$list)
32 $settings = DbSettings
::get();
33 if (isset($settings['user_roles']))
34 foreach($settings['user_roles'] as $r => $role)
38 public static function add_pre_overview_card($empty)
40 if (defined('SQL_DEFAULT_USER'))
41 Message
::Fail("Warning: SQL_DEFAULT_USER is set in config.php. You should remove that item now, as it is only used during installation.");
42 if (defined('DEFAULT_USER'))
43 Message
::Fail("Warning: DEFAULT_USER is set in config.php. You should remove that item now, as it is only used during installation.");
47 * Delete all the tables (of us) in the SQLdb
50 public static function delete_tables()
53 foreach(["users","user_meta", "settings", "fail2ban"] as $table_name)
54 $conn->query("DROP TABLE IF EXISTS " . get_config("mysql::table_prefix") . $table_name);
58 * Create the tables we'll be using in the SQLdb
61 public static function create_tables()
64 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "users (
65 user_id int AUTO_INCREMENT NOT NULL,
66 user_name VARCHAR(255) NOT NULL,
67 user_pass VARCHAR(255) NOT NULL,
68 user_email VARCHAR(255),
69 user_fname VARCHAR(255),
70 user_lname VARCHAR(255),
71 user_bio VARCHAR(255),
77 * Patch for beta users
78 * This adds the email column to existing tables without it
80 $columns = $conn->query("SHOW COLUMNS FROM " . get_config("mysql::table_prefix") . "users");
81 $column_names = array();
82 $c = $columns->fetchAll();
84 foreach($c as $column) {
85 $column_names[] = $column['Field'];
87 $column_exists = in_array("user_email", $column_names);
88 if (!$column_exists) {
89 $conn->query("ALTER TABLE " . get_config("mysql::table_prefix") . "users ADD COLUMN user_email varchar(255)");
93 * Another patch for beta users
94 * This changes the size of the meta_value so we can store more
97 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "user_meta (
98 meta_id int AUTO_INCREMENT NOT NULL,
100 meta_key VARCHAR(255) NOT NULL,
101 meta_value VARCHAR(255),
102 PRIMARY KEY (meta_id),
103 CONSTRAINT meta_key_user_id UNIQUE(meta_key,user_id)
105 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "settings (
106 id int AUTO_INCREMENT NOT NULL,
107 setting_key VARCHAR(255) NOT NULL,
108 setting_value VARCHAR(5000),
112 $conn->query("CREATE TABLE IF NOT EXISTS " . get_config("mysql::table_prefix") . "fail2ban (
113 id int AUTO_INCREMENT NOT NULL,
114 ip VARCHAR(255) NOT NULL,
120 /* - user_meta: set charset and size */
122 if (($columns = $conn->query("SHOW COLUMNS FROM ".get_config("mysql::table_prefix")."user_meta")))
123 $c = $columns->fetchAll();
125 $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");
127 /* - settings: add UNIQUE(setting_key) */
129 if (($columns = $conn->query("SHOW INDEXES FROM ".get_config("mysql::table_prefix")."settings WHERE Key_name='setting_key'")))
130 $c = $columns->fetchAll();
133 $conn->query("ALTER TABLE " . get_config("mysql::table_prefix") . "settings ADD CONSTRAINT setting_key UNIQUE(setting_key)");
136 $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");
138 /* - user_meta: add UNIQUE(meta_key,user_id) */
140 if (($columns = $conn->query("SHOW INDEXES FROM ".get_config("mysql::table_prefix")."user_meta WHERE Key_name='meta_key_user_id'")))
141 $c = $columns->fetchAll();
143 $conn->query("ALTER TABLE " . get_config("mysql::table_prefix") . "user_meta ADD CONSTRAINT meta_key_user_id UNIQUE(meta_key,user_id)");
145 /* make sure everything went well */
146 $tables = ["users", "user_meta", "fail2ban", "settings"];
147 $errors = 0; // counter
148 $error_messages = "";
149 foreach($tables as $table)
151 $prefix = get_config("sql::table_prefix");
152 $sql = "SHOW TABLES LIKE '$prefix%'"; // SQL query to check if table exists
154 $result = $conn->query($sql);
155 if ($result->rowCount())
160 strcat($error_messages,"Table '$prefix$table' was not created successfully.<br>");
165 if (defined('DEFAULT_USER')) // we've got a default account
167 $lkup = new PanelUser(DEFAULT_USER
['username']);
169 if (!$lkup->id
) // doesn't exist, add it with full privileges
172 $user['user_name'] = DEFAULT_USER
['username'];
173 $user['user_pass'] = DEFAULT_USER
['password'];
175 create_new_user($user);
177 $lkup = new PanelUser(DEFAULT_USER
['username']);
178 if (!user_can($lkup, PERMISSION_MANAGE_USERS
))
179 $lkup->add_permission(PERMISSION_MANAGE_USERS
);
188 /* We convert $u with a full user as an object ;D*/
189 public static function get_user(&$u)
197 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id LIMIT 1");
198 $prep->execute(["id" => strtolower($id)]);
202 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "users WHERE LOWER(user_name) = :name LIMIT 1");
203 $prep->execute(["name" => strtolower($name)]);
208 $data = $prep->fetchAll();
209 if (isset($data[0]) && $data = $data[0])
211 $obj->id
= $data['user_id'];
212 $obj->username
= $data['user_name'];
213 $obj->passhash
= $data['user_pass'];
214 $obj->first_name
= $data['user_fname'] ?? NULL;
215 $obj->last_name
= $data['user_lname'] ?? NULL;
216 $obj->created
= $data['created'];
217 $obj->bio
= $data['user_bio'];
218 $obj->email
= $data['user_email'];
219 $obj->user_meta
= (new PanelUser_Meta($obj->id
))->list;
224 public static function get_usermeta(&$u)
231 $prep = $conn->prepare("SELECT * FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id");
232 $prep->execute(["id" => $id]);
234 foreach ($prep->fetchAll() as $row)
236 $list[$row['meta_key']] = $row['meta_value'];
240 public static function add_usermeta(&$meta)
242 $meta = $meta['meta'];
244 /* check if it exists first, update it if it does */
245 $query = "SELECT * FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id AND meta_key = :key";
246 $stmt = $conn->prepare($query);
247 $stmt->execute(["id" => $meta['id'], "key" => $meta['key']]);
248 if ($stmt->rowCount()) // it exists, update instead of insert
250 $query = "UPDATE " . get_config("mysql::table_prefix") . "user_meta SET meta_value = :value WHERE user_id = :id AND meta_key = :key";
251 $stmt = $conn->prepare($query);
252 $stmt->execute($meta);
253 if ($stmt->rowCount())
260 $query = "INSERT INTO " . get_config("mysql::table_prefix") . "user_meta (user_id, meta_key, meta_value) VALUES (:id, :key, :value)";
261 $stmt = $conn->prepare($query);
262 $stmt->execute($meta);
263 if ($stmt->rowCount())
268 public static function del_usermeta(&$u)
271 $query = "DELETE FROM " . get_config("mysql::table_prefix") . "user_meta WHERE user_id = :id AND meta_key = :key";
272 $stmt = $conn->prepare($query);
273 $stmt->execute($u['meta']);
274 if ($stmt->rowCount())
278 public static function user_create(&$u)
280 $username = $u['user_name'];
281 $first_name = $u['fname'] ?? NULL;
282 $last_name = $u['lname'] ?? NULL;
283 $password = $u['user_pass'] ?? NULL;
284 $user_bio = $u['user_bio'] ?? NULL;
285 $user_email = $u['user_email'] ?? NULL;
287 $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)");
288 $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")]);
289 if ($prep->rowCount())
290 $u['success'] = true;
292 $u['errmsg'][] = "Could not add user";
295 public static function get_user_list(&$list)
298 $result = $conn->query("SELECT user_id FROM " . get_config("mysql::table_prefix") . "users");
299 if (!$result) // impossible
301 die("Something went wrong.");
304 while($row = $result->fetch())
306 $userlist[] = new PanelUser(NULL, $row['user_id']);
308 if (!empty($userlist))
312 public static function user_delete(&$u)
315 $query = "DELETE FROM " . get_config("mysql::table_prefix") . "users WHERE user_id = :id";
317 $stmt = $conn->prepare($query);
318 $stmt->execute(["id" => $user->id
]);
319 $deleted = $stmt->rowCount();
322 $u['info'][] = "Successfully deleted user \"$user->username\"";
325 $u['info'][] = "Unknown error";
330 public static function edit_core($arr)
333 $user = $arr['user'];
334 $info = $arr['info'];
335 foreach($info as $key => $val)
338 if (!$val || !strlen($val) || BadPtr($val))
340 if (!strcmp($key,"update_fname") && $val != $user->first_name
)
342 $value = "user_fname";
343 $valuestr = "first name";
345 elseif (!strcmp($key,"update_lname") && $val != $user->last_name
)
347 $value = "user_lname";
348 $valuestr = "last name";
350 elseif (!strcmp($key,"update_bio") && $val != $user->bio
)
355 elseif (!strcmp($key,"update_pass") || !strcmp($key,"update_pass_conf"))
357 $value = "user_pass";
358 $valuestr = "password";
360 elseif(!strcmp($key,"update_email") && $val != $user->email
)
362 $value = "user_email";
363 $valuestr = "email address";
368 $query = "UPDATE " . get_config("mysql::table_prefix") . "users SET $value=:value WHERE user_id = :id";
369 $stmt = $conn->prepare($query);
370 $stmt->execute(["value" => $val, "id" => $user->id
]);
372 if (!$stmt->rowCount() && $stmt->errorInfo()[0] != "00000")
373 Message
::Fail("Could not update $valuestr for $user->username: ".$stmt->errorInfo()[0]." (CODE: ".$stmt->errorCode().")");
376 Message
::Success("Successfully updated the $valuestr for $user->username");
382 function security_check()
384 $ip = $_SERVER['REMOTE_ADDR'];
385 if (dnsbl_check($ip))
388 else if (fail2ban_check($ip))
394 function dnsbl_check($ip)
396 $dnsbl_lookup = get_config("dnsbl");
400 // clear variable just in case
403 // if the IP was not given because you're an idiot, stop processing
404 if (!$ip) { return; }
406 // get the first two segments of the IPv4
407 $because = split($ip, "."); // why you
408 $you = $because[1]; // gotta play
409 $want = $because[2]; // that song
410 $to = $you.".".$want."."; // so loud?
412 // exempt local connections because sometimes they get a false positive
413 if ($to == "192.168." || $to == "127.0.") { return NULL; }
415 // you spin my IP right round, right round, to check the records baby, right round-round-round
416 $reverse_ip = glue(array_reverse(split($ip, ".")), ".");
419 foreach ($dnsbl_lookup as $host) {
422 if (checkdnsrr($reverse_ip . "." . $host . ".", "A")) {
429 // if it was safe, return NOTHING
434 // else, you guessed it, return where it was listed
440 function fail2ban_check($ip)