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 = [ <<