From 0ad5e542c1458842f638ec99d5cb98850e062d4c Mon Sep 17 00:00:00 2001 From: Matteo Gheza Date: Mon, 3 May 2021 23:29:27 +0200 Subject: [PATCH] Migrated db to PHP-DB and lots of fixes --- server/api.php | 47 +-- server/composer.json | 3 +- server/composer.lock | 16 +- server/core.php | 309 +++++++++--------- server/cron.php | 50 ++- server/edit_service.php | 10 +- server/edit_training.php | 8 +- server/edit_user.php | 6 +- server/error_page.php | 24 +- server/install/install.php | 26 +- server/install/installHelper.php | 132 +++++--- server/modal_availability_schedule.php | 2 +- server/online_check.php | 7 +- server/resources/ajax/ajax_add_type.php | 5 +- .../ajax/ajax_availability_schedule.php | 15 +- .../ajax/ajax_change_availability.php | 12 +- server/resources/ajax/ajax_list.php | 4 +- server/resources/ajax/ajax_log.php | 4 +- server/resources/ajax/ajax_services.php | 8 +- server/resources/ajax/ajax_trainings.php | 8 +- server/ui.php | 17 +- server/user_details.php | 2 +- 22 files changed, 401 insertions(+), 314 deletions(-) diff --git a/server/api.php b/server/api.php index 20b096e..6392a7a 100644 --- a/server/api.php +++ b/server/api.php @@ -22,11 +22,14 @@ $dispatcher = FastRoute\simpleDispatcher( ); $r->addRoute( 'POST', '/login', function ($vars) { - global $tools, $database, $user; + global $tools, $db, $user; try { $user->auth->loginWithUsername($_POST['username'], $_POST['password']); $apiKey = $tools->createKey(); - $database->exec("INSERT INTO `%PREFIX%_api_keys` (`apikey`, `user`, `permissions`) VALUES (:apiKey, :userId, 'ALL');", true, [":apiKey" => $apiKey, ":userId" => $user->auth->getUserId()]); + $db->insert( + DB_PREFIX."_api_keys", + ["apikey" => $apiKey, "user" => $user->auth->getUserId(), "permissions" => "all"] + ); return ["status" => "ok", "apiKey" => $apiKey]; } catch (\Delight\Auth\UnknownUsernameException $e) { @@ -54,9 +57,9 @@ $dispatcher = FastRoute\simpleDispatcher( $r->addRoute( 'GET', '/users', function ($vars) { requireToken(); - global $database; - $users = $database->exec("SELECT * FROM `%PREFIX%_users`;", true); - $users_profiles = $database->exec("SELECT * FROM `%PREFIX%_profiles`;", true); + global $db; + $users = $db->select("SELECT * FROM `".DB_PREFIX."_users`"); + $users_profiles = $db->select("SELECT * FROM `".DB_PREFIX."_profiles`"); foreach ($users_profiles as $key=>$value){ if(is_null($users_profiles[$key]["name"])) { $users_profiles[$key]["name"] = $users[$key]["username"]; @@ -69,9 +72,9 @@ $dispatcher = FastRoute\simpleDispatcher( $r->addRoute( 'GET', '/user', function ($vars) { requireToken(); - global $database, $user_info; - $users = $database->exec("SELECT * FROM `%PREFIX%_users` WHERE id = :id;", true, [":id" => $user_info["id"]])[0]; - $users_profiles = $database->exec("SELECT * FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $user_info["id"]])[0]; + global $db, $user_info; + $users = $db->select("SELECT * FROM `".DB_PREFIX."_users` WHERE id = :id", ["id" => $user_info["id"]])[0]; + $users_profiles = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE id = :id", ["id" => $user_info["id"]])[0]; if(is_null($users_profiles["name"])) { $users_profiles["name"] = $users["username"]; } @@ -82,9 +85,9 @@ $dispatcher = FastRoute\simpleDispatcher( $r->addRoute( 'GET', '/user/{id:\d+}', function ($vars) { requireToken(); - global $database; - $users = $database->exec("SELECT * FROM `%PREFIX%_users` WHERE id = :id;", true, [":id" => $vars["id"]])[0]; - $users_profiles = $database->exec("SELECT * FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $vars["id"]])[0]; + global $db; + $users = $db->select("SELECT * FROM `".DB_PREFIX."_users` WHERE id = :id", ["id" => $vars["id"]])[0]; + $users_profiles = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE id = :id", ["id" => $vars["id"]])[0]; if(is_null($users_profiles["name"])) { $users_profiles["name"] = $users["username"]; } @@ -133,40 +136,40 @@ $dispatcher = FastRoute\simpleDispatcher( $r->addRoute( 'GET', '/availability', function ($vars) { requireToken(); - global $database, $user_info; - return $database->exec("SELECT * FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $user_info["id"]])[0]["available"]; + global $db, $user_info; + return $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE id = :id", ["id" => $user_info["id"]])[0]["available"]; } ); $r->addRoute( 'GET', '/availability/{id:\d+}', function ($vars) { requireToken(); - global $database; - return $database->exec("SELECT * FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $vars["id"]])[0]["available"]; + global $db; + return $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE id = :id", ["id" => $vars["id"]])[0]["available"]; } ); $r->addRoute( 'GET', '/changeAvailability/{available:\d+}', function ($vars) { requireToken(); - global $user, $database, $user_info; + global $user, $db, $user_info; $vars["available"] = (int) $vars["available"]; if($vars["available"] !== 0 && $vars["available"] !== 1) { return ["status" => "error", "message" => "Availability code not allowed"]; } $log_message = $vars["available"] ? "Status changed to 'available'" : "Status changed to 'not available'"; - $database->exec("UPDATE `%PREFIX%_profiles` SET `available` = :available WHERE `id` = :id;", true, [":id" => $user_info["id"], ":available" => $vars["available"]]); + $db->select("UPDATE `".DB_PREFIX."_profiles` SET `available` = :available WHERE `id` = :id", ["id" => $user_info["id"], "available" => $vars["available"]]); $user->log($log_message); } ); $r->addRoute( 'GET', '/changeAvailability/{id:\d+}/{available:\d+}', function ($vars) { requireToken(); - global $user, $database, $user_info; + global $user, $db, $user_info; $vars["available"] = (int) $vars["available"]; if($vars["available"] !== 0 && $vars["available"] !== 1) { return ["status" => "error", "message" => "Availability code not allowed"]; } $log_message = $vars["available"] ? "Status changed to 'available'" : "Status changed to 'not available'"; - $database->exec("UPDATE `%PREFIX%_profiles` SET `available` = :available WHERE `id` = :id;", true, [":id" => $vars["id"], ":available" => $vars["available"]]); + $db->select("UPDATE `".DB_PREFIX."_profiles` SET `available` = :available WHERE `id` = :id", ["id" => $vars["id"], "available" => $vars["available"]]); $user->log($log_message, $vars["id"], $user_info["id"]); } ); @@ -230,13 +233,13 @@ function responseApi($content, $status_code=200) function validToken() { - global $database, $user_info; + global $db, $user_info; $token = isset($_REQUEST['apiKey']) ? $_REQUEST['apiKey'] : (isset($_REQUEST['apikey']) ? $_REQUEST['apikey'] : (isset($_SERVER['HTTP_APIKEY']) ? $_SERVER['HTTP_APIKEY'] : false)); if($token == false) { return false; } - if(!empty($api_key_row = $database->exec("SELECT * FROM `%PREFIX%_api_keys` WHERE apikey = :apikey;", true, [":apikey" => $token]))) { - $user_info["id"] = $database->exec("SELECT * FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $api_key_row[0]["user"]])[0]["id"]; + if(!empty($api_key_row = $db->select("SELECT * FROM `".DB_PREFIX."_api_keys` WHERE apikey = :apikey", ["apikey" => $token]))) { + $user_info["id"] = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE id = :id", ["id" => $api_key_row[0]["user"]])[0]["id"]; return true; } else { return false; diff --git a/server/composer.json b/server/composer.json index 6cd4dee..4ecb6e4 100644 --- a/server/composer.json +++ b/server/composer.json @@ -20,7 +20,8 @@ "maximebf/debugbar": "^1.16", "azuyalabs/yasumi": "^2.3", "ministryofweb/php-osm-tiles": "^2.0", - "jenstornell/tiny-html-minifier": "dev-master" + "jenstornell/tiny-html-minifier": "dev-master", + "delight-im/db": "^1.3" }, "license": "GPL-3.0-or-later", "authors": [ diff --git a/server/composer.lock b/server/composer.lock index 59882ef..c268d33 100644 --- a/server/composer.lock +++ b/server/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "ae7c144f55a8641ac68db46c3943d7ec", + "content-hash": "492606c03730f891878c2eddc0bffee0", "packages": [ { "name": "azuyalabs/yasumi", @@ -1653,16 +1653,16 @@ }, { "name": "psr/log", - "version": "1.1.3", + "version": "1.1.4", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc" + "reference": "d49695b909c3b7628b6289db5479a1c204601f11" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/0f73288fd15629204f9d42b7055f72dacbe811fc", - "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc", + "url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11", + "reference": "d49695b909c3b7628b6289db5479a1c204601f11", "shasum": "" }, "require": { @@ -1686,7 +1686,7 @@ "authors": [ { "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" + "homepage": "https://www.php-fig.org/" } ], "description": "Common interface for logging libraries", @@ -1697,9 +1697,9 @@ "psr-3" ], "support": { - "source": "https://github.com/php-fig/log/tree/1.1.3" + "source": "https://github.com/php-fig/log/tree/1.1.4" }, - "time": "2020-03-23T09:12:05+00:00" + "time": "2021-05-03T11:20:27+00:00" }, { "name": "ralouphie/getallheaders", diff --git a/server/core.php b/server/core.php index 6a79236..c2eeda6 100644 --- a/server/core.php +++ b/server/core.php @@ -31,13 +31,13 @@ function bdump($message){ class tools { - public $database; + public $db; public $profiler_enabled; public $profiler_last_name = ""; - public function __construct($database, $profiler_enabled) + public function __construct($db, $profiler_enabled) { - $this->database = $database; + $this->db = $db; $this->profiler_enabled = $profiler_enabled; } @@ -65,7 +65,7 @@ class tools }else{ $ip = $_SERVER['REMOTE_ADDR']; } - if($this->database->get_option("check_cf_ip")) { + if(get_option("check_cf_ip")) { if(!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) { $ip = $_SERVER['HTTP_CF_CONNECTING_IP']; } @@ -203,7 +203,7 @@ class tools } public function convertMapAddressToUrl($lat, $lng, $zoom){ - switch ($this->database->get_option("map_preview_generator")) { + switch (get_option("map_preview_generator")) { case 'osm': $converter = new Converter(); $point = new LatLng($lat, $lng); @@ -214,10 +214,10 @@ class tools case 'custom': default: - if($this->database->get_option("map_preview_generator_add_marker") && $this->database->get_option("map_preview_generator_url_marker") && $this->database->get_option("map_preview_generator_url_marker") !== ""){ - $url = $this->database->get_option("map_preview_generator_url_marker"); + if(get_option("map_preview_generator_add_marker") && get_option("map_preview_generator_url_marker") && get_option("map_preview_generator_url_marker") !== ""){ + $url = get_option("map_preview_generator_url_marker"); } else { - $url = $this->database->get_option("map_preview_generator_url"); + $url = get_option("map_preview_generator_url"); } $url = str_replace("{{LAT}}", $lat, $url); $url = str_replace("{{LNG}}", $lng, $url); @@ -241,12 +241,12 @@ class tools $filePath = "resources/images/map_cache/".$filename.".png"; file_put_contents($filePath, $data); if(extension_loaded('gd')){ - $img = imagecreatefrompng($filePath); - if($this->database->get_option("map_preview_generator_add_marker") && (!$this->database->get_option("map_preview_generator_url_marker") || $this->database->get_option("map_preview_generator_url_marker") == "")){ + $img = imagecreatefromstring(file_get_contents($filePath)); + if(get_option("map_preview_generator_add_marker") && (!get_option("map_preview_generator_url_marker") || get_option("map_preview_generator_url_marker") == "")){ $marker = imagecreatefromgif("resources/images/marker.gif"); imagecopy($img, $marker, 120, 87, 0, 0, 25, 41); } - if($this->database->get_option("map_preview_generator") == "osm"){ + if(get_option("map_preview_generator") == "osm"){ $textcolor = imagecolorallocate($img, 0, 0, 0); imagestring($img, 5, 0, 236, ' OpenStreetMap contributors', $textcolor); } @@ -259,7 +259,7 @@ class tools } public function checkPlaceParam($place){ - if($this->database->get_option("generate_map_preview")){ + if(get_option("generate_map_preview")){ if(preg_match('/[+-]?\d+([.]\d+)?[;][+-]?\d+([.]\d+)?/', $place)){ $lat = explode(";", $place)[0]; $lng = explode(";", $place)[1]; @@ -272,43 +272,15 @@ class tools } } -class database +class options { - protected $db_host = DB_HOST; - protected $db_dbname = DB_NAME; - protected $db_username = DB_USER; - protected $db_password = DB_PASSWORD; - public $connection = null; - public $query = null; - public $stmt = null; + protected $db; public $load_from_file = true; public $options = []; public $options_cache_file = null; - public function connect() - { - try { - $this->connection = new DebugBar\DataCollector\PDO\TraceablePDO(new PDO("mysql:host=" . $this->db_host . ";dbname=" . $this->db_dbname, $this->db_username, $this->db_password)); - $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); - $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - } - catch(PDOException $e) - { - exit($e->getMessage()); - } - } - - public function isOptionsEmpty() - { - return empty($this->exec("SELECT * FROM `%PREFIX%_options`;", true)); - } - - public function __construct() - { - $this->connect(); - if($this->isOptionsEmpty()) { - header('Location: install/install.php'); - } + public function __construct($db){ + $this->db = $db; $file_infos = pathinfo(array_reverse(debug_backtrace())[0]['file']); if(strpos($file_infos['dirname'], 'resources') !== false) { $this->options_cache_file = "../../options.txt"; @@ -319,68 +291,20 @@ class database if(file_exists($this->options_cache_file)/* && time()-@filemtime($this->options_cache_file) < 604800*/) { $this->options = json_decode(file_get_contents($this->options_cache_file), true); } else { - $this->options = $this->exec("SELECT * FROM `%PREFIX%_options` WHERE `enabled` = 1", true); + $this->options = $db->select("SELECT * FROM `".DB_PREFIX."_options` WHERE `enabled` = 1"); file_put_contents($this->options_cache_file, json_encode($this->options)); } } else { - $this->options = $this->exec("SELECT * FROM `%PREFIX%_options` WHERE `enabled` = 1", true); + $this->options = $db->select("SELECT * FROM `".DB_PREFIX."_options` WHERE `enabled` = 1"); } + if(empty($this->options)) header('Location: install/install.php'); } - public function close() - { - $this->connection = null; - } - - public function exec($sql1, $fetch=false, $param=null, ...$others_params) - { - try{ - //$this->connection->beginTransaction(); - array_unshift($others_params, $sql1); - bdump($others_params); - $toReturn = []; - foreach($others_params as $sql){ - $sql = str_replace("%PREFIX%", DB_PREFIX, $sql); - bdump($sql); - $this->stmt = $this->connection->prepare($sql); - if(!is_null($param)) { - $this->query = $this->stmt->execute($param); - } else { - $this->query = $this->stmt->execute(); - } - bdump($this->query); - - if($fetch == true) { - if(count($others_params) > 1) { - $toReturn[] = $this->stmt->fetchAll(PDO::FETCH_ASSOC); - } else { - $toReturn = $this->stmt->fetchAll(PDO::FETCH_ASSOC); - } - } - } - //$this->connection->commit(); - //$this->stmt->closeCursor(); - return $toReturn; - } catch (PDOException $e) { - print "Error!: " . $e->getMessage() . "
"; - //$this->connection->rollBack(); - die(); - } - } - - public function exists($table, $id) - { - $result = $this->exec("SELECT :table FROM `%PREFIX%_services` WHERE id = :id;", true, [":table" => $table, ":id" => $id]); - return !empty($result); - } - - public function get_option($name) + public function get($name) { if(defined($name)) { return constant($name); } else { - //$option = $this->exec("SELECT `value` FROM `%PREFIX%_options` WHERE `name` = :name AND `enabled` = 1;", true, [":name" => $name]); - //return empty($option) ? "" : $option[0]["value"]; foreach($this->options as $option){ if($name == $option["name"]) { return empty($option["value"]) ? false : $option["value"]; @@ -413,23 +337,25 @@ final class Role class user { - private $database = null; + private $db = null; private $tools = null; private $profile_names = null; public $auth = null; public $authenticated = false; public $holidays = null; - public function __construct($database, $tools) + public function __construct($db, $tools) { - $this->database = $database; + $this->db = $db; $this->tools = $tools; - $this->auth = new \Delight\Auth\Auth($database->connection, $tools->get_ip(), DB_PREFIX."_", false); + $this->auth = new \Delight\Auth\Auth($this->db, $tools->get_ip(), DB_PREFIX."_", false); \header_remove('X-Frame-Options'); if(isset($_REQUEST["apiKey"]) && !is_null($_REQUEST["apiKey"])){ - $api_key_row = $this->database->exec("SELECT * FROM `%PREFIX%_api_keys` WHERE apikey = :apikey;", true, [":apikey" => $_REQUEST["apiKey"]]); + //var_dump("SELECT * FROM \`".DB_PREFIX."_api_keys\` WHERE apikey = :apikey"); + //exit(); + $api_key_row = $this->db->select("SELECT * FROM `".DB_PREFIX."_api_keys` WHERE apikey = :apikey", [":apikey" => $_REQUEST["apiKey"]]); if(!empty($api_key_row)){ - $user = $this->database->exec("SELECT * FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $api_key_row[0]["user"]]); + $user = $this->db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE id = :id", [":id" => $api_key_row[0]["user"]]); $user_id = $user[0]["id"]; $this->auth->admin()->logInAsUserById($user_id); if(!empty($user)) { @@ -446,9 +372,9 @@ class user } } $this->authenticated = $this->auth->isLoggedIn(); - $this->profile_names = $this->database->exec("SELECT `id`, `name` FROM `%PREFIX%_profiles`;", true); - $this->user_names = $this->database->exec("SELECT `id`, `username` FROM `%PREFIX%_users`;", true); - $this->holidays = Yasumi\Yasumi::create($this->database->get_option("holidays_provider") ?: "USA", date("Y"), $this->database->get_option("holidays_language") ?: "en_US"); + $this->profile_names = $this->db->select("SELECT `id`, `name` FROM `".DB_PREFIX."_profiles`"); + $this->user_names = $this->db->select("SELECT `id`, `username` FROM `".DB_PREFIX."_users`"); + $this->holidays = Yasumi\Yasumi::create(get_option("holidays_provider") ?: "USA", date("Y"), get_option("holidays_language") ?: "en_US"); } public function authenticated() @@ -460,17 +386,19 @@ class user { $this->tools->profiler_start("Require login"); if(!$this->authenticated()) { - if($this->database->get_option("intrusion_save")) { - if($this->database->get_option("intrusion_save_info")) { - $params = [":page" => $this->tools->get_page_url(), ":ip" => $this->tools->get_ip(), ":date" => date("d/m/Y"), ":hour" => date("H:i.s"), ":server_var" => json_encode($_SERVER)]; + if(get_option("intrusion_save")) { + if(get_option("intrusion_save_info")) { + $params = ["page" => $this->tools->get_page_url(), "ip" => $this->tools->get_ip(), "date" => date("d/m/Y"), "hour" => date("H:i.s"), "server_var" => json_encode($_SERVER)]; } else { - $params = [":page" => $this->tools->get_page_url(), ":ip" => "redacted", ":date" => date("d/m/Y"), ":hour" => date("H:i.s"), ":server_var" => json_encode(["redacted" => "true"])]; + $params = ["page" => $this->tools->get_page_url(), "ip" => "redacted", "date" => date("d/m/Y"), "hour" => date("H:i.s"), "server_var" => json_encode(["redacted" => "true"])]; } - $sql = "INSERT INTO `%PREFIX%_intrusions` (`id`, `page`, `date`, `hour`, `ip`, `server_var`) VALUES (NULL, :page, :date, :hour, :ip, :server_var)"; - $this->database->exec($sql, false, $params); + $this->db->insert( + "intrusions", + $params + ); } if($redirect) { - $this->tools->redirect($this->database->get_option("web_url")); + $this->tools->redirect(get_option("web_url")); } else { exit(); } @@ -526,16 +454,16 @@ class user if(is_null($user)){ $user = $this->auth->getUserId(); } - $result = $this->database->exec("SELECT `hidden` FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $user]); + $result = $this->db->select("SELECT `hidden` FROM `".DB_PREFIX."_profiles` WHERE id = :id", [":id" => $user]); if(isset($result[0]) && isset($result[0]["hidden"])){ return boolval($result[0]["hidden"]); } return false; } - public function available($name) + public function available($id) { - $user = $this->database->exec("SELECT available FROM `%PREFIX%_users` WHERE name = :name;", true, [":name" => $name]); + $user = $this->db->select("SELECT available FROM `".DB_PREFIX."_users` WHERE id = :id", [":id" => $id]); if(empty($user)) { return false; } else { @@ -585,7 +513,7 @@ class user } if($this->auth->isLoggedIn()) { $this->log("Login", $this->auth->getUserId()); - $user = $this->database->exec("SELECT * FROM `%PREFIX%_profiles` WHERE id = :id;", true, [":id" => $this->auth->getUserId()]); + $user = $this->db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE id = :id", [":id" => $this->auth->getUserId()]); if(!empty($user)) { if(is_null($user[0]["name"])) { $_SESSION['_user_name'] = $this->auth->getUsername(); @@ -623,16 +551,17 @@ class user $editor = $changed; } if(!$this->hidden($editor)){ - if($this->database->get_option("log_save_ip")){ + if(get_option("log_save_ip")){ $ip = $this->tools->get_ip(); } else { $ip = null; } $source_type = defined("REQUEST_USING_API") ? "api" : "web"; $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? mb_strimwidth($_SERVER['HTTP_USER_AGENT'], 0, 200, "...") : null; - $params = [":action" => $action, ":changed" => $changed, ":editor" => $editor, ":timestamp" => $timestamp, ":ip" => $ip, "source_type" => $source_type, "user_agent" => $user_agent]; - $sql = "INSERT INTO `%PREFIX%_log` (`id`, `action`, `changed`, `editor`, `timestamp`, `ip`, `source_type`, `user_agent`) VALUES (NULL, :action, :changed, :editor, :timestamp, :ip, :source_type, :user_agent)"; - $this->database->exec($sql, false, $params); + $this->db->insert( + DB_PREFIX."_log", + ["action" => $action, "changed" => $changed, "editor" => $editor, "timestamp" => $timestamp, "ip" => $ip, "source_type" => $source_type, "user_agent" => $user_agent] + ); } $this->tools->profiler_stop(); } @@ -661,8 +590,10 @@ class user $disabled = $disabled ? 1 : 0; $chief = $chief ? 1 : 0; $driver = $driver ? 1 : 0; - $sql = "INSERT INTO `%PREFIX%_profiles` (`hidden`, `disabled`, `name`, `phone_number`, `chief`, `driver`) VALUES (:hidden, :disabled, :name, :phone_number, :chief, :driver)"; - $this->database->exec($sql, false, [":hidden" => $hidden, ":disabled" => $disabled, ":name" => $name, ":phone_number" => $phone_number, ":chief" => $chief, ":driver" => $driver]); + $this->db->insert( + DB_PREFIX."_profiles", + ["hidden" => $hidden, "disabled" => $disabled, "name" => $name, "phone_number" => $phone_number, "chief" => $chief, "driver" => $driver] + ); if($chief == 1) { $this->auth->admin()->addRoleForUserById($userId, Role::FULL_VIEWER); } @@ -678,7 +609,14 @@ class user public function remove_user($id, $removed_by) { $this->tools->profiler_start("Remove user"); - $this->database->exec("DELETE FROM `%PREFIX%_users` WHERE `id` = :id", true, [":id" => $id], "DELETE FROM `%PREFIX%_profiles` WHERE `id` = :id"); + $this->db->delete( + DB_PREFIX."_users", + ["id" => $id] + ); + $this->db->delete( + DB_PREFIX."_profiles", + ["id" => $id] + ); $this->log("User removed", null, $removed_by); $this->tools->profiler_stop(); } @@ -687,8 +625,11 @@ class user $this->tools->profiler_start("Update online timestamp"); if(is_null($id)) $id = $this->auth->getUserId(); $time = time(); - $sql = "UPDATE `%PREFIX%_profiles` SET online_time = '$time' WHERE id = '" . $id ."'"; - $this->database->exec($sql, true); + $this->db->update( + DB_PREFIX."_profiles", + ["online_time" => $time], + ["id" => $id] + ); bdump(["id" => $id, "time" => $time]); $this->tools->profiler_stop(); } @@ -697,58 +638,68 @@ class user class crud { public $tools = null; - public $database = null; + public $db = null; public $user = null; - public function __construct($tools, $database, $user) + public function __construct($tools, $db, $user) { $this->tools = $tools; - $this->database = $database; + $this->db = $db; $this->user = $user; } - public function increment($increment) + public function increment_services($increment) { bdump($increment); - $sql = "UPDATE `%PREFIX%_profiles` SET `services`= services + 1 WHERE id IN ($increment);"; - $this->database->exec($sql, false); + $this->db->exec( + "UPDATE `".DB_PREFIX."_profiles` SET `services`= services + 1 WHERE id IN ($increment)" + ); } - public function getIncrement($id) + public function getIncrement_services($id) { bdump($id); - $sql = "SELECT `increment` FROM `%PREFIX%_services` WHERE `id` = :id"; - $increment = $this->database->exec($sql, true, [":id" => $id])[0]['increment']; + $increment = $this->db->selectValue( + "SELECT `increment` FROM `".DB_PREFIX."_services` WHERE `id` = :id LIMIT 0, 1", + ["id" => $id] + ); bdump($increment); return $increment; } - public function decrease($id) + public function decrease_services($id) { - $sql = "UPDATE `%PREFIX%_profiles` SET `services`= services - 1 WHERE id IN ({$this->getIncrement($id)});"; - $this->database->exec($sql, false); + $increment = $this->getIncrement_services($id); + $this->db->exec( + "UPDATE `".DB_PREFIX."_profiles` SET `services`= services - 1 WHERE id IN ($increment)" + ); } public function increment_trainings($increment) { bdump($increment); - $sql = "UPDATE `%PREFIX%_profiles` SET `trainings`= trainings + 1 WHERE id IN ($increment);"; - $this->database->exec($sql, false); + $this->db->exec( + "UPDATE `".DB_PREFIX."_profiles` SET `trainings`= trainings + 1 WHERE id IN ($increment)" + ); } public function getIncrement_trainings($id) { bdump($id); - $sql = "SELECT `increment` FROM `%PREFIX%_trainings` WHERE `id` = :id"; - $increment = $this->database->exec($sql, true, [":id" => $id])[0]['increment']; + $increment = $this->db->selectValue( + "SELECT `increment` FROM `".DB_PREFIX."_trainings` WHERE `id` = :id LIMIT 0, 1", + ["id" => $id] + ); bdump($increment); return $increment; } public function decrease_trainings($id) { - $sql = "UPDATE `%PREFIX%_profiles` SET `trainings`= trainings - 1 WHERE id IN ({$this->getIncrement_trainings($id)});"; - $this->database->exec($sql, false); + $increment = $this->getIncrement_trainings($id); + $this->db->exec( + "UPDATE `".DB_PREFIX."_profiles` SET `trainings`= trainings - 1 WHERE id IN ($increment)" + ); } public function add_service($date, $code, $beginning, $end, $chief, $drivers, $crew, $place, $notes, $type, $increment, $inserted_by) @@ -760,16 +711,21 @@ class crud $increment = implode(",", $increment); bdump($increment); $date = date('Y-m-d H:i:s', strtotime($date)); - $sql = "INSERT INTO `%PREFIX%_services` (`id`, `date`, `code`, `beginning`, `end`, `chief`, `drivers`, `crew`, `place`, `notes`, `type`, `increment`, `inserted_by`) VALUES (NULL, :date, :code, :beginning, :end, :chief, :drivers, :crew, :place, :notes, :type, :increment, :inserted_by);"; - $this->database->exec($sql, false, [":date" => $date, ":code" => $code, "beginning" => $beginning, ":end" => $end, ":chief" => $chief, ":drivers" => $drivers, ":crew" => $crew, ":place" => $place, ":notes" => $notes, ":type" => $type, ":increment" => $increment, ":inserted_by" => $inserted_by]); - $this->increment($increment); + $this->db->insert( + DB_PREFIX."_services", + ["date" => $date, "code" => $code, "beginning" => $beginning, "end" => $end, "chief" => $chief, "drivers" => $drivers, "crew" => $crew, "place" => $place, "notes" => $notes, "type" => $type, "increment" => $increment, "inserted_by" => $inserted_by] + ); + $this->increment_services($increment); $this->user->log("Service added"); } public function remove_service($id) { - $this->decrease($id); - $this->database->exec("DELETE FROM `%PREFIX%_services` WHERE `id` = :id", true, [":id" => $id]); + $this->decrease_services($id); + $this->db->delete( + DB_PREFIX."_services", + ["id" => $id] + ); $this->user->log("Service removed"); } @@ -788,8 +744,10 @@ class crud $increment = implode(",", $increment); bdump($increment); $date = date('Y-m-d H:i:s', strtotime($date)); - $sql = "INSERT INTO `%PREFIX%_trainings` (`id`, `date`, `name`, `beginning`, `end`, `chief`, `crew`, `place`, `notes`, `increment`, `inserted_by`) VALUES (NULL, :date, :name, :start_time, :end_time, :chief, :crew, :place, :notes, :increment, :inserted_by);"; - $this->database->exec($sql, false, [":date" => $date, ":name" => $name, "start_time" => $start_time, ":end_time" => $end_time, ":chief" => $chief, ":crew" => $crew, ":place" => $place, ":notes" => $notes, ":increment" => $increment, ":inserted_by" => $inserted_by]); + $this->db->insert( + DB_PREFIX."_trainings", + ["date" => $date, "name" => $name, "beginning" => $start_time, "end" => $end_time, "chief" => $chief, "crew" => $crew, "place" => $place, "notes" => $notes, "increment" => $increment, "inserted_by" => $inserted_by] + ); $this->increment_trainings($increment); $this->user->log("Training added"); } @@ -798,7 +756,10 @@ class crud { $this->decrease_trainings($id); bdump($id); - $this->database->exec("DELETE FROM `%PREFIX%_trainings` WHERE `id` = :id", true, [":id" => $id]); + $this->db->delete( + DB_PREFIX."_trainings", + ["id" => $id] + ); $this->user->log("Training removed"); } @@ -809,6 +770,12 @@ class crud $this->add_training($date, $name, $start_time, $end_time, $chief, $crew, $place, $notes, $increment, $inserted_by); $this->user->log("Training edited"); } + + public function exists($table, $id) + { + $result = $this->db->select("SELECT id FROM `".DB_PREFIX."_{$table}` WHERE id = :id", [":id" => $id]); + return !empty($result); + } } class translations @@ -897,17 +864,31 @@ class translations } } } + +function init_db(){ + global $db; + + $dataSource = new \Delight\Db\PdoDataSource('mysql'); + $dataSource->setHostname(DB_HOST); + $dataSource->setPort(3306); + $dataSource->setDatabaseName(DB_NAME); + $dataSource->setCharset('utf8mb4'); + $dataSource->setUsername(DB_USER); + $dataSource->setPassword(DB_PASSWORD); + $db = \Delight\Db\PdoDatabase::fromDataSource($dataSource); +} + $webpack_manifest_path = realpath("resources/dist/manifest.json"); function init_class($enableDebugger=true, $headers=true) { - global $tools, $database, $user, $crud, $translations, $debugbar; - if(!isset($tools) && !isset($database) && !isset($translations)) { - $database = new database(); - $tools = new tools($database, $enableDebugger); - $user = new user($database, $tools); - $crud = new crud($tools, $database, $user); - $translations = new translations($database->get_option("force_language")); - } + global $tools, $options, $db, $user, $crud, $translations, $debugbar; + init_db(); + $options = new options($db); + $tools = new tools($db, $enableDebugger); + $user = new user($db, $tools); + $crud = new crud($tools, $db, $user); + $translations = new translations(get_option("force_language")); + if($headers) { //TODO adding require-trusted-types-for 'script'; $csp = "default-src 'self' data: *.tile.openstreetmap.org nominatim.openstreetmap.org; connect-src 'self' *.sentry.io nominatim.openstreetmap.org; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: *.tile.openstreetmap.org; object-src; style-src 'self' 'unsafe-inline';"; @@ -948,8 +929,9 @@ function init_class($enableDebugger=true, $headers=true) bdump(__DIR__); $dir = str_replace("resources\ajax\\", "", __DIR__).DIRECTORY_SEPARATOR.'debug_storage'; $debugbar->setStorage(new DebugBar\Storage\FileStorage($dir)); - $debugbar->addCollector(new DebugBar\DataCollector\PDO\PDOCollector($database->connection)); - $debugbar->addCollector(new DebugBar\DataCollector\ConfigCollector($database->options)); + //TODO: debug PDO + //$debugbar->addCollector(new DebugBar\DataCollector\PDO\PDOCollector($database->connection)); + $debugbar->addCollector(new DebugBar\DataCollector\ConfigCollector($options->options)); } else { $debugbar = null; } @@ -999,6 +981,11 @@ function s($string, $echo=true, $htmlAllowed=false, $htmlPurifierOptions=[]) } } +function get_option($option){ + global $options; + return $options->get($option); +} + function p_start($name=null) { global $tools; diff --git a/server/cron.php b/server/cron.php index fc08689..9a28fe8 100644 --- a/server/cron.php +++ b/server/cron.php @@ -5,7 +5,7 @@ init_class(false); header('Content-Type: application/json'); error_reporting(-1); -list($cronJobDay, $cronJobTime) = explode(";", $database->get_option("cron_job_time")); +list($cronJobDay, $cronJobTime) = explode(";", get_option("cron_job_time")); $execDateTime = [ "day" => date("d"), @@ -23,7 +23,7 @@ $cronJobDateTime = [ "minutes" => explode(":", $cronJobTime)[1] ]; -$start = $database->get_option("cron_job_enabled") && ((isset($_POST['cron']) && $_POST['cron'] == "cron_job-".$database->get_option("cron_job_code")) || (isset($_SERVER['HTTP_CRON']) && $_SERVER['HTTP_CRON'] == "cron_job-".$database->get_option("cron_job_code"))); +$start = get_option("cron_job_enabled") && ((isset($_POST['cron']) && $_POST['cron'] == "cron_job-".get_option("cron_job_code")) || (isset($_SERVER['HTTP_CRON']) && $_SERVER['HTTP_CRON'] == "cron_job-".get_option("cron_job_code"))); $start_reset = ( $execDateTime["day"] == $cronJobDateTime["day"] && $execDateTime["day"] == $cronJobDateTime["day"] && $execDateTime["month"] == $cronJobDateTime["month"] && @@ -35,21 +35,25 @@ $action = "Availability Minutes "; if($start) { if($start_reset) { $action .= "reset and "; - $sql = "SELECT * FROM `%PREFIX%_profiles` WHERE `available` = 1 "; - $profiles = $database->exec($sql, true); + $profiles = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `available` = 1 "); if(count($profiles) > 0) { $list = []; foreach($profiles as $profile){ $list[] = [$profile["id"] => $profile["availability_minutes"]]; } - $database->exec("INSERT INTO `%PREFIX%_minutes` (`id`, `month`, `year`, `list`) VALUES (NULL, :month, :year, :list)", false, [":month" => $execDateTime["month"],":year" => $execDateTime["year"],":list"=>json_encode($list)]); - $database->exec("UPDATE %PREFIX%_profiles SET availability_minutes = 0"); + $db->insert( + DB_PREFIX."_minutes", + ["month" => $execDateTime["month"], "year" => $execDateTime["year"], "list"=>json_encode($list)] + ); + $db->update( + DB_PREFIX."_profiles", + ["availability_minutes" => 0] + ); } } $action .= "update"; - $sql = "SELECT * FROM `%PREFIX%_profiles` WHERE `available` = 1 "; - $profiles = $database->exec($sql, true); + $profiles = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `available` = 1"); if(count($profiles) > 0) { $output = []; $output[] = $profiles; @@ -59,9 +63,13 @@ if($start) { $value = (int)$row["availability_minutes"]+5; $id = $row["id"]; $increment[$id] = $value; - $database->exec("UPDATE %PREFIX%_profiles SET availability_minutes = :value WHERE id = :id", true, [":value" => $value, ":id" => $id]); + $count = $db->update( + DB_PREFIX."_profiles", + ["availability_minutes" => $value], + ["id" => $id] + ); $tmp = $id . " - " . $value . " "; - $tmp .= $database->stmt->rowCount() == 1 ? "success" : "fail"; + $tmp .= $count == 1 ? "success" : "fail"; $queries[] = $tmp; } $output[] = $queries; @@ -70,7 +78,7 @@ if($start) { $output_status = "ok"; } - $result = $database->exec("SELECT * FROM `%PREFIX%_schedules`;", true); + $result = $db->select("SELECT * FROM `".DB_PREFIX."_schedules`;"); $schedules_check = []; $schedules_users = []; $schedules_check["schedules"] = []; @@ -115,8 +123,16 @@ if($start) { if(!in_array($user_id,$schedules_users)) $schedules_users[] = $user_id; if($schedule["hour"] == $last_exec["hour"] ? $schedule["minutes"] !== $last_exec["minutes"] : true && !in_array(date('Y-m-d'), $selected_holidays_dates)){ $last_exec_new = $schedule["day"].";".sprintf("%02d", $schedule["hour"]).":".sprintf("%02d", $schedule["minutes"]); - $database->exec("UPDATE `%PREFIX%_schedules` SET `last_exec` = :last_exec WHERE `id` = :id;", false, [":id" => $id, ":last_exec" => $last_exec_new]); - $database->exec("UPDATE `%PREFIX%_profiles` SET available = '1', availability_last_change = 'cron' WHERE `id` = :user_id;", false, [":user_id" => $user_id]); + $db->update( + DB_PREFIX."_schedules", + ["last_exec" => $last_exec_new], + ["id" => $id] + ); + $db->update( + DB_PREFIX."_profiles", + ["available" => '1', "availability_last_change" => "cron"], + ["id" => $user_id] + ); $schedules_check["schedules"][] = [ "schedule" => $schedule, "now" => $now, @@ -129,10 +145,14 @@ if($start) { } } $schedules_check["users"] = $schedules_users; - $profiles = $database->exec("SELECT id FROM `%PREFIX%_profiles`", true); + $profiles = $db->select("SELECT id FROM `".DB_PREFIX."_profiles`"); foreach ($profiles as $profile) { if(!in_array($profile["id"],$schedules_users)){ - $database->exec("UPDATE `%PREFIX%_profiles` SET available = '0' WHERE availability_last_change = 'cron' AND id = :id;", false, [":id" => $profile["id"]]); + $db->update( + DB_PREFIX."_profiles", + ["available" => 0], + ["availability_last_change" => "cron", "id" => $profile["id"]] + ); } } } diff --git a/server/edit_service.php b/server/edit_service.php index 276efab..b44653f 100644 --- a/server/edit_service.php +++ b/server/edit_service.php @@ -49,8 +49,8 @@ if($tools->validate_form("mod", "add")) { if(isset($_GET["add"])||isset($_GET["edit"])||isset($_GET["delete"])||isset($_GET["mod"])) { $_SESSION["token"] = bin2hex(random_bytes(64)); } - $crew = $database->exec("SELECT * FROM `%PREFIX%_profiles` ORDER BY name ASC;", true); - $types = $database->exec("SELECT `name` FROM `%PREFIX%_type` ORDER BY name ASC", true); + $crew = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` ORDER BY name ASC"); + $types = $db->select("SELECT `name` FROM `".DB_PREFIX."_type` ORDER BY name ASC"); $modalità = (isset($_GET["add"])) ? "add" : ((isset($_GET["edit"])) ? "edit" : ((isset($_GET["delete"])) ? "delete" : "add")); bdump($modalità, "modalità"); bdump($types, "types"); @@ -58,8 +58,8 @@ if($tools->validate_form("mod", "add")) { $id = ""; if(isset($_GET["id"])) { $id = $_GET["id"]; - bdump($database->exists("services", $id)); - $values = $database->exec("SELECT * FROM `%PREFIX%_services` WHERE `id` = :id", true, [":id" => $id])[0]; + bdump($crud->exists("services", $id)); + $values = $db->select("SELECT * FROM `".DB_PREFIX."_services` WHERE `id` = :id", [":id" => $id])[0]; bdump($values); } else { $values = []; @@ -67,7 +67,7 @@ if($tools->validate_form("mod", "add")) { if($modalità=="edit" || $modalità=="delete") { if(empty($id)) { echo("
"); var_dump($_POST); echo("
"); - } elseif (!$database->exists("services", $id)) { + } elseif (!$crud->exists("services", $id)) { echo("
"); var_dump($_POST); echo("
"); } } diff --git a/server/edit_training.php b/server/edit_training.php index 7fa6bf4..2f63b78 100644 --- a/server/edit_training.php +++ b/server/edit_training.php @@ -47,15 +47,15 @@ if($tools->validate_form("mod", "add")) { if(isset($_GET["add"])||isset($_GET["edit"])||isset($_GET["delete"])||isset($_GET["mod"])) { $_SESSION["token"] = bin2hex(random_bytes(64)); } - $crew = $database->exec("SELECT * FROM `%PREFIX%_profiles` ORDER BY name ASC;", true); + $crew = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` ORDER BY name ASC"); $modalità = (isset($_GET["add"])) ? "add" : ((isset($_GET["edit"])) ? "edit" : ((isset($_GET["delete"])) ? "delete" : "add")); bdump($modalità, "modalità"); bdump($crew, "crew"); $id = ""; if(isset($_GET["id"])) { $id = $_GET["id"]; - bdump($database->exists("trainings", $id)); - $values = $database->exec("SELECT * FROM `%PREFIX%_trainings` WHERE `id` = :id", true, [":id" => $id])[0]; + bdump($crud->exists("trainings", $id)); + $values = $db->select("SELECT * FROM `".DB_PREFIX."_trainings` WHERE `id` = :id", [":id" => $id])[0]; bdump($values); } else { $values = []; @@ -63,7 +63,7 @@ if($tools->validate_form("mod", "add")) { if($modalità=="edit" || $modalità=="delete") { if(empty($id)) { $tools->redirect("accessdenied.php"); - } elseif (!$database->exists("trainings", $id)) { + } elseif (!$crud->exists("trainings", $id)) { //$tools->redirect("accessdenied.php"); } } diff --git a/server/edit_user.php b/server/edit_user.php index 2b1bd34..d85d621 100644 --- a/server/edit_user.php +++ b/server/edit_user.php @@ -69,8 +69,8 @@ if($tools->validate_form("mod", "add")) { $id = ""; if(isset($_GET["id"])) { $id = $_GET["id"]; - bdump($database->exists("profiles", $id)); - $values = $database->exec("SELECT * FROM `%PREFIX%_profiles` WHERE `id` = :id", true, [":id" => $id])[0]; + bdump($crud->exists("profiles", $id)); + $values = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` WHERE `id` = :id", [":id" => $id])[0]; bdump($values); } else { $values = []; @@ -78,7 +78,7 @@ if($tools->validate_form("mod", "add")) { if($modalità=="edit" || $modalità=="delete") { if(empty($id)) { $tools->redirect("accessdenied.php"); - } elseif (!$database->exists("profiles", $id)) { + } elseif (!$crud->exists("profiles", $id)) { $tools->redirect("accessdenied.php"); } } diff --git a/server/error_page.php b/server/error_page.php index 80f67ad..973e59f 100644 --- a/server/error_page.php +++ b/server/error_page.php @@ -15,12 +15,20 @@ function show_error_page($error=null, $error_message=null, $error_message_advanc break; } } - $webpack_manifest = json_decode( - file_get_contents(isset($webpack_manifest_path) ? $webpack_manifest_path : realpath("resources/dist/manifest.json")), - true - ); - $main_script_url = "resources/dist/".$webpack_manifest["main.js"]; - $game_script_url = "resources/dist/".$webpack_manifest["games.js"]; + $main_script_url = null; + $game_script_url = null; + try{ + $webpack_manifest_path = isset($webpack_manifest_path) ? $webpack_manifest_path : realpath("resources/dist/manifest.json"); + if(!empty($webpack_manifest_path)){ + $webpack_manifest = json_decode( + file_get_contents($webpack_manifest_path), + true + ); + $main_script_url = "resources/dist/".$webpack_manifest["main.js"]; + $game_script_url = "resources/dist/".$webpack_manifest["games.js"]; + } + } catch(\Exception $e) { + } $error_templates = [ <<

+
While you are waiting, you can play some games:
    @@ -73,6 +84,7 @@ function show_error_page($error=null, $error_message=null, $error_message_advanc PDO::ERRMODE_EXCEPTION]); - $stmt = $connection->prepare(str_replace("%PREFIX%", DB_PREFIX, "SELECT * FROM `%PREFIX%_dbversion`;")); - $query = $stmt->execute(); - $populated = !empty($stmt->fetchAll(PDO::FETCH_ASSOC)); - $stmt2 = $connection->prepare(str_replace("%PREFIX%", DB_PREFIX, "SELECT * FROM `%PREFIX%_users`;")); - $query2 = $stmt2->execute(); - $userPopulated = !empty($stmt2->fetchAll(PDO::FETCH_ASSOC)); - } catch (PDOException $e){ + $db = \Delight\Db\PdoDatabase::fromDsn( + new \Delight\Db\PdoDsn( + "mysql:host=$dbhostValue;dbname=$dbnameValue", + $unameValue, + $pwdValue + ) + ); + try{ + $populated = !is_null($db->select("SELECT * FROM `".DB_PREFIX."_dbversion`")); + } catch (Delight\Db\Throwable\TableNotFoundError $e){ + $populated = false; + } + try{ + $userPopulated = !is_null($db->select("SELECT * FROM `".DB_PREFIX."_users`")); + } catch (Delight\Db\Throwable\TableNotFoundError $e){ + $userPopulated = false; + } + } catch (Exception $e){ $populated = false; $userPopulated = false; } diff --git a/server/install/installHelper.php b/server/install/installHelper.php index 4d94299..55b1215 100644 --- a/server/install/installHelper.php +++ b/server/install/installHelper.php @@ -252,11 +252,16 @@ define('SENTRY_ENV', 'prod');
    function initDB() { try{ - $connection = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); + $db = \Delight\Db\PdoDatabase::fromDsn( + new \Delight\Db\PdoDsn( + "mysql:host=".DB_HOST.";dbname=".DB_NAME, + DB_USER, + DB_PASSWORD + ) + ); $prefix = DB_PREFIX; - $connection->exec( - " -CREATE TABLE IF NOT EXISTS `".$prefix."_trainings` ( +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_trainings` ( `id` int(11) NOT NULL AUTO_INCREMENT, `date` date NOT NULL, `name` varchar(999) NOT NULL, @@ -270,7 +275,9 @@ CREATE TABLE IF NOT EXISTS `".$prefix."_trainings` ( `inserted_by` varchar(200) NOT NULL, PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE IF NOT EXISTS `".$prefix."_services` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_services` ( `id` int(11) NOT NULL AUTO_INCREMENT, `date` date NOT NULL, `code` text NOT NULL, @@ -286,7 +293,9 @@ CREATE TABLE IF NOT EXISTS `".$prefix."_services` ( `inserted_by` varchar(200) NOT NULL, PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE IF NOT EXISTS `".$prefix."_intrusions` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_intrusions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `page` varchar(999) COLLATE utf8mb4_unicode_ci NOT NULL, `date` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, @@ -295,7 +304,9 @@ CREATE TABLE IF NOT EXISTS `".$prefix."_intrusions` ( `server_var` varchar(9999) COLLATE utf8mb4_unicode_ci NOT NULL, PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE IF NOT EXISTS `".$prefix."_log` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `action` varchar(100) NOT NULL, `changed` varchar(100), @@ -306,20 +317,26 @@ CREATE TABLE IF NOT EXISTS `".$prefix."_log` ( `user_agent` varchar(500), PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE IF NOT EXISTS `".$prefix."_minutes` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_minutes` ( `id` int(11) NOT NULL AUTO_INCREMENT, `month` int(2) NOT NULL, `year` int(2) NOT NULL, `list` mediumtext NOT NULL, PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE IF NOT EXISTS `".$prefix."_type` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_type` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` text NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `type_name` (`name`(99)) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE IF NOT EXISTS `".$prefix."_users` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, @@ -334,7 +351,9 @@ CREATE TABLE IF NOT EXISTS `".$prefix."_users` ( PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE IF NOT EXISTS `".$prefix."_profiles` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_profiles` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `hidden` BOOLEAN NOT NULL DEFAULT FALSE, `disabled` BOOLEAN NOT NULL DEFAULT FALSE, @@ -351,7 +370,9 @@ CREATE TABLE IF NOT EXISTS `".$prefix."_profiles` ( `image` varchar(1000) DEFAULT NULL, PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE IF NOT EXISTS `".$prefix."_users_confirmations` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_users_confirmations` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `email` varchar(249) COLLATE utf8mb4_unicode_ci NOT NULL, @@ -363,7 +384,9 @@ UNIQUE KEY `selector` (`selector`), KEY `email_expires` (`email`,`expires`), KEY `user_id` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -CREATE TABLE IF NOT EXISTS `".$prefix."_users_remembered` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_users_remembered` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user` int(10) unsigned NOT NULL, `selector` varchar(24) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, @@ -373,7 +396,9 @@ PRIMARY KEY (`id`), UNIQUE KEY `selector` (`selector`), KEY `user` (`user`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -CREATE TABLE IF NOT EXISTS `".$prefix."_users_resets` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_users_resets` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user` int(10) unsigned NOT NULL, `selector` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, @@ -383,7 +408,9 @@ PRIMARY KEY (`id`), UNIQUE KEY `selector` (`selector`), KEY `user_expires` (`user`,`expires`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -CREATE TABLE IF NOT EXISTS `".$prefix."_users_throttling` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_users_throttling` ( `bucket` varchar(44) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL, `tokens` float unsigned NOT NULL, `replenished_at` int(10) unsigned NOT NULL, @@ -391,7 +418,9 @@ CREATE TABLE IF NOT EXISTS `".$prefix."_users_throttling` ( PRIMARY KEY (`bucket`), KEY `expires_at` (`expires_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -CREATE TABLE IF NOT EXISTS `".$prefix."_options` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE IF NOT EXISTS `{$prefix}_options` ( `id` INT NOT NULL AUTO_INCREMENT, `name` TEXT NOT NULL, `value` MEDIUMTEXT NOT NULL, `enabled` BOOLEAN NOT NULL DEFAULT TRUE, @@ -400,26 +429,34 @@ CREATE TABLE IF NOT EXISTS `".$prefix."_options` ( `user_id` INT NOT NULL, PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE `".$prefix."_dbversion` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE `{$prefix}_dbversion` ( `id` INT NOT NULL AUTO_INCREMENT, `version` INT NOT NULL, `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE `".$prefix."_api_keys` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE `{$prefix}_api_keys` ( `id` INT NOT NULL AUTO_INCREMENT, `apikey` VARCHAR(128) NOT NULL, `user` INT NOT NULL, `permissions` VARCHAR(128) NOT NULL DEFAULT 'ALL', PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE `".$prefix."_bot_telegram` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE `{$prefix}_bot_telegram` ( `id` INT NOT NULL AUTO_INCREMENT, `chat_id` VARCHAR(128) NOT NULL, `user` INT NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET=latin1; -CREATE TABLE `".$prefix."_schedules` ( +EOL); +$db->exec(<<<"EOL" +CREATE TABLE `{$prefix}_schedules` ( `id` INT NOT NULL AUTO_INCREMENT, `user` INT NOT NULL, `profile_name` VARCHAR(500) NOT NULL DEFAULT 'default', @@ -429,8 +466,8 @@ CREATE TABLE `".$prefix."_schedules` ( `last_update` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET=latin1; -INSERT INTO `".$prefix."_dbversion` (`version`, `timestamp`) VALUES('1', current_timestamp());" - ); +EOL); +$db->exec("INSERT INTO `{$prefix}_dbversion` (`version`, `timestamp`) VALUES('1', current_timestamp());"); } catch (Exception $e) { if(is_cli()) { echo($e); @@ -471,27 +508,36 @@ function initOptions($name, $visible, $developer, $password, $report_email, $own { try{ include_once "../config.php"; - $connection = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); + $db = \Delight\Db\PdoDatabase::fromDsn( + new \Delight\Db\PdoDsn( + "mysql:host=".DB_HOST.";dbname=".DB_NAME, + DB_USER, + DB_PASSWORD + ) + ); $prefix = DB_PREFIX; - $auth = new \Delight\Auth\Auth($connection, $_SERVER['REMOTE_ADDR'], $prefix."_"); + $auth = new \Delight\Auth\Auth($db, $_SERVER['REMOTE_ADDR'], $prefix."_"); $userId = $auth->register($report_email, $password, $name); $auth->admin()->addRoleForUserById($userId, \Delight\Auth\Role::SUPER_ADMIN); if($developer) { $auth->admin()->addRoleForUserById($userId, \Delight\Auth\Role::DEVELOPER); } + if(is_null($url)){ + $url = str_replace("install/install.php", "", full_path()); + } $options = [ - 'check_cf_ip' => ':check_cf_ip', - 'report_email' => ':report_email', - 'owner' => ':owner', - 'web_url' => ':web_url', + 'check_cf_ip' => empty($_SERVER['HTTP_CF_CONNECTING_IP']) ? 0 : 1, + 'report_email' => $report_email, + 'owner' => $owner, + 'web_url' => $url, 'use_custom_error_sound' => 0, 'use_custom_error_image' => 0, 'intrusion_save' => 1, 'intrusion_save_info' => 0, 'log_save_ip' => 1, - 'cron_job_code' => ':cron_job_code', + 'cron_job_code' => str_replace(".", "", bin2hex(random_bytes(10)).base64_encode(openssl_random_pseudo_bytes(30))), 'cron_job_enabled' => 1, - 'cron_job_time' => ':cron_job_time', + 'cron_job_time' => '01;00:00', 'service_edit' => 1, 'service_remove' => 1, 'training_edit' => 1, @@ -508,26 +554,16 @@ function initOptions($name, $visible, $developer, $password, $report_email, $own 'holidays_language' => 'en_US', 'messages' => '{}' ]; - $query = ""; foreach ($options as $key => $value) { - $query .= " -INSERT INTO `".$prefix."_options` (`id`, `name`, `value`, `enabled`, `created_time`, `last_edit`, `user_id`) VALUES (NULL, '".$key."', $value, 1, current_timestamp(), current_timestamp(), '1');"; + $db->insert( + $prefix."_options", + ["name" => $key, "value" => $value, "enabled" => 1, "user_id" => 1] + ); } - $query = " -INSERT INTO `".$prefix."_profiles` (`id`, `hidden`) VALUES (NULL, :hidden);".$query; - $prep = $connection->prepare($query); - mt_srand(10); - $prep->bindValue(':check_cf_ip', (empty($_SERVER['HTTP_CF_CONNECTING_IP']) ? 0 : 1), PDO::PARAM_INT); - $prep->bindValue(':hidden', ($visible ? 0 : 1), PDO::PARAM_INT); - $prep->bindValue(':report_email', $report_email, PDO::PARAM_STR); - $prep->bindValue(':owner', $owner, PDO::PARAM_STR); - if(is_null($url)){ - $url = str_replace("install/install.php", "", full_path()); - } - $prep->bindValue(':web_url', $url, PDO::PARAM_STR); - $prep->bindValue(':cron_job_code', str_replace(".", "", bin2hex(random_bytes(10)).base64_encode(openssl_random_pseudo_bytes(30))), PDO::PARAM_STR); - $prep->bindValue(':cron_job_time', "01;00:00", PDO::PARAM_STR); - $prep->execute(); + $db->insert( + $prefix."_profiles", + ["hidden" => $visible ? 0 : 1] + ); } catch (Exception $e) { if(is_cli()) { echo($e); diff --git a/server/modal_availability_schedule.php b/server/modal_availability_schedule.php index 650b27c..6924b08 100644 --- a/server/modal_availability_schedule.php +++ b/server/modal_availability_schedule.php @@ -44,7 +44,7 @@ $days = [ ]; $user_id = $user->auth->getUserId(); -$result = $database->exec("SELECT * FROM `%PREFIX%_schedules` WHERE `user`={$user_id};", true); +$result = $db->select("SELECT * FROM `".DB_PREFIX."_schedules` WHERE `user`={$user_id}"); if(!empty($result)){ $old_schedules_db = json_decode($result[0]["schedules"]); foreach ($old_schedules_db as $schedule) { diff --git a/server/online_check.php b/server/online_check.php index 6827a9c..477f46b 100644 --- a/server/online_check.php +++ b/server/online_check.php @@ -7,8 +7,11 @@ $id = $user->auth->getUserId(); $time = time(); if(!is_null($id)) { - $sql = "UPDATE `%PREFIX%_profiles` SET online_time = '$time' WHERE id = '" . $id ."'"; - $database->exec($sql, true); + $db->update( + DB_PREFIX."_profiles", + ["online_time" => $time], + ["id" => $id] + ); echo(json_encode(["id" => $id, "time" => $time, "sql" => $sql])); } ?> diff --git a/server/resources/ajax/ajax_add_type.php b/server/resources/ajax/ajax_add_type.php index 7cf7b46..717a8f2 100644 --- a/server/resources/ajax/ajax_add_type.php +++ b/server/resources/ajax/ajax_add_type.php @@ -5,6 +5,9 @@ $user->requirelogin(false); if(isset($_POST["type"])){ $type = $_POST["type"]; - $database->exec("INSERT INTO `%PREFIX%_type` (`name`) VALUES (:name);", false, [":name" => $type]); + $db->insert( + DB_PREFIX."_type", + ["name" => $type] + ); $user->log("Added service type"); } \ No newline at end of file diff --git a/server/resources/ajax/ajax_availability_schedule.php b/server/resources/ajax/ajax_availability_schedule.php index be81df9..1d92729 100644 --- a/server/resources/ajax/ajax_availability_schedule.php +++ b/server/resources/ajax/ajax_availability_schedule.php @@ -4,7 +4,7 @@ init_class(false); $user->requirelogin(false); $user_id = $user->auth->getUserId(); -$result = $database->exec("SELECT * FROM `%PREFIX%_schedules` WHERE `user`={$user_id};", true); +$result = $db->select("SELECT * FROM `".DB_PREFIX."_schedules` WHERE `user` = :id", ["id" => $user_id]); if(!empty($result)){ $result[0]["schedules"] = json_decode($result[0]["schedules"]); $result[0]["holidays"] = json_decode($result[0]["holidays"]); @@ -15,10 +15,17 @@ if(isset($_POST["hours"])){ $holidays = (string) json_encode($_POST["holidays"]); echo($hours."-".$holidays); if(!empty($result)){ - $database->exec("UPDATE `%PREFIX%_schedules` SET schedules = :schedules, holidays = :holidays WHERE `id` = :id;", false, [":id" => $result[0]["id"], ":schedules" => $hours, ":holidays" => $holidays]); + $db->update( + DB_PREFIX."_schedules", + ["schedules" => $hours, "holidays" => $holidays], + ["id" => $result[0]["id"]] + ); } else { - $database->exec("INSERT INTO `%PREFIX%_schedules` (`user`, `schedules`, `holidays`) VALUES (:user, :schedules, :holidays);", false, [":user" => $user_id, ":schedules" => $hours, ":holidays" => $holidays]); + $db->insert( + DB_PREFIX."_schedules", + ["schedules" => $hours, "holidays" => $holidays, "user" => $user_id] + ); } } else { - echo(json_encode(empty($result) ? [] : $result[0])); + echo(json_encode(empty($result)||is_null($result) ? [] : $result[0])); } \ No newline at end of file diff --git a/server/resources/ajax/ajax_change_availability.php b/server/resources/ajax/ajax_change_availability.php index 6080e51..2d41fab 100644 --- a/server/resources/ajax/ajax_change_availability.php +++ b/server/resources/ajax/ajax_change_availability.php @@ -5,10 +5,18 @@ $user->requirelogin(false); $user->online_time_update(); if(isset($_POST["change_id"]) && $_POST["dispo"] == 1 /* && $_POST["token_list"] == $_SESSION['token_list'] */){ - $database->exec("UPDATE `%PREFIX%_profiles` SET available = '1', availability_last_change = 'manual' WHERE id = :id;", false, [":id" => $_POST["change_id"]]); + $db->update( + DB_PREFIX."_profiles", + ["available" => 1, "availability_last_change" => "manual"], + ["id" => $_POST["change_id"]] + ); $user->log("Status changed to 'available'", $_POST["change_id"], $user->auth->getUserId()); } else if(isset($_POST["change_id"]) && $_POST["dispo"] == 0 /* && $_POST["token_list"] == $_SESSION['token_list'] */){ - $database->exec("UPDATE `%PREFIX%_profiles` SET available = '0', availability_last_change = 'manual' WHERE id = :id;", false, [":id" => $_POST["change_id"]]); + $db->update( + DB_PREFIX."_profiles", + ["available" => 0, "availability_last_change" => "manual"], + ["id" => $_POST["change_id"]] + ); $user->log("Status changed to 'not available'", $_POST["change_id"], $user->auth->getUserId()); } ?> diff --git a/server/resources/ajax/ajax_list.php b/server/resources/ajax/ajax_list.php index e39d988..9492d43 100644 --- a/server/resources/ajax/ajax_list.php +++ b/server/resources/ajax/ajax_list.php @@ -4,10 +4,10 @@ init_class(); $user->requirelogin(false); $user->online_time_update(); -$result = $database->exec("SELECT * FROM `%PREFIX%_profiles` ORDER BY available DESC, chief DESC, services ASC, availability_minutes ASC, name ASC;", true); +$result = $db->select("SELECT * FROM `".DB_PREFIX."_profiles` ORDER BY available DESC, chief DESC, services ASC, availability_minutes ASC, name ASC"); $response = []; -foreach($result as $row){ +foreach(!is_null($result) ? $result : [] as $row){ if(!$user->hidden($row["id"])){ if($user->requireRole(Role::FULL_VIEWER)){ $name = $user->nameById($row["id"]); diff --git a/server/resources/ajax/ajax_log.php b/server/resources/ajax/ajax_log.php index 4a6125d..7e697b1 100644 --- a/server/resources/ajax/ajax_log.php +++ b/server/resources/ajax/ajax_log.php @@ -4,7 +4,7 @@ init_class(); $user->requirelogin(false); $user->online_time_update(); -$result = $database->exec("SELECT * FROM `%PREFIX%_log` ORDER BY `timestamp` DESC", true); +$result = $db->select("SELECT * FROM `".DB_PREFIX."_log` ORDER BY `timestamp` DESC"); //https://stackoverflow.com/a/2524761 function isValidTimeStamp($timestamp) @@ -15,7 +15,7 @@ function isValidTimeStamp($timestamp) } $response = []; -foreach($result as $row){ +foreach(!is_null($result) ? $result : [] as $row){ if(isValidTimeStamp($row["timestamp"])){ $date = new DateTime(); $date->setTimestamp($row["timestamp"]); diff --git a/server/resources/ajax/ajax_services.php b/server/resources/ajax/ajax_services.php index 8e9e209..77b3162 100644 --- a/server/resources/ajax/ajax_services.php +++ b/server/resources/ajax/ajax_services.php @@ -4,10 +4,10 @@ init_class(); $user->requirelogin(false); $user->online_time_update(); -$result = $database->exec("SELECT * FROM `%PREFIX%_services` ORDER BY date DESC, beginning DESC", true); +$result = $db->select("SELECT * FROM `".DB_PREFIX."_services` ORDER BY date DESC, beginning DESC"); $response = []; -foreach($result as $row){ +foreach(!is_null($result) ? $result : [] as $row){ $chief = $user->nameById($row["chief"]); $drivers_array = explode(",", $row['drivers']); @@ -32,8 +32,8 @@ foreach($result as $row){ s($row['place'],false,true), s($row['notes'],false,true), s($row['type'],false,true), - $database->get_option("service_edit") ? "" : null, - $database->get_option("service_remove") ? "" : null + get_option("service_edit") ? "" : null, + get_option("service_remove") ? "" : null ]; } $tools->ajax_page_response($response); diff --git a/server/resources/ajax/ajax_trainings.php b/server/resources/ajax/ajax_trainings.php index c4feb24..ca126e0 100644 --- a/server/resources/ajax/ajax_trainings.php +++ b/server/resources/ajax/ajax_trainings.php @@ -4,10 +4,10 @@ init_class(); $user->requirelogin(false); $user->online_time_update(); -$result = $database->exec("SELECT * FROM `%PREFIX%_trainings` ORDER BY date DESC, beginning desc", true); +$result = $db->select("SELECT * FROM `".DB_PREFIX."_trainings` ORDER BY date DESC, beginning desc"); $response = []; -foreach($result as $row){ +foreach(!is_null($result) ? $result : [] as $row){ $chief = $user->nameById($row["chief"]); $others_crew_array = explode(",", $row['crew']); @@ -24,8 +24,8 @@ foreach($result as $row){ $others_crew, s($row['place'],false,true), s($row['notes'],false,true), - $database->get_option("training_edit") ? "" : null, - $database->get_option("training_remove") ? "" : null + get_option("training_edit") ? "" : null, + get_option("training_remove") ? "" : null ]; } $tools->ajax_page_response($response); diff --git a/server/ui.php b/server/ui.php index 7a9b1bb..8ddb895 100644 --- a/server/ui.php +++ b/server/ui.php @@ -37,10 +37,7 @@ $filter_translate = new \Twig\TwigFilter( $twig->addFilter($filter_translate); $function_option = new \Twig\TwigFunction( - 'option', function ($option) { - global $database; - return $database->get_option($option); - } + 'option', "get_option" ); $twig->addFunction($function_option); @@ -78,7 +75,7 @@ p_stop(); $template = null; function loadtemplate($templatename, $data, $requirelogin=true) { - global $database, $user, $twig, $template, $enable_debugbar, $debugbarRenderer; + global $user, $twig, $template, $enable_debugbar, $debugbarRenderer; p_start("Render Twig template"); if($requirelogin) { $user->requirelogin(); @@ -89,23 +86,23 @@ function loadtemplate($templatename, $data, $requirelogin=true) $data['enable_debug_bar'] = $enable_debugbar; $data['debug_bar_head'] = $enable_debugbar ? $debugbarRenderer->renderHead() : ""; $data['debug_bar'] = $enable_debugbar ? $debugbarRenderer->render() : ""; - $data['owner'] = $database->get_option("owner"); - $data['urlsoftware'] = $database->get_option("web_url"); + $data['owner'] = get_option("owner"); + $data['urlsoftware'] = get_option("web_url"); $data['user'] = $user->info(); $data['show_menu'] = !isset($_REQUEST["hide_menu"]); $data['show_footer'] = !isset($_REQUEST["hide_footer"]); - if($database->get_option("use_custom_error_sound")) { + if(get_option("use_custom_error_sound")) { $data['error_sound'] = "custom-error.mp3"; } else { $data['error_sound'] = "error.mp3"; } - if($database->get_option("use_custom_error_image")) { + if(get_option("use_custom_error_image")) { $data['error_image'] = "custom-error.gif"; } else { $data['error_image'] = "error.gif"; } //TODO: replace this - if($messages = $database->get_option("messages")){ + if($messages = get_option("messages")){ try { $messages = json_decode($messages, true); if(isset($messages[$templatename])){ diff --git a/server/user_details.php b/server/user_details.php index 810a132..941a916 100644 --- a/server/user_details.php +++ b/server/user_details.php @@ -1,5 +1,5 @@ exec('SELECT * FROM `%PREFIX%_profiles` WHERE id = :id', true, array(":id" => $_GET['user'])); +$row = $db->select('SELECT * FROM `".DB_PREFIX."_profiles` WHERE id = :id', [":id" => $_GET['user']]); loadtemplate('user_details.html', ['title' => t("Personal data", false), 'user' => $row[0]]); ?>