diff --git a/404.php b/404.php index 1f01ea7..4da48e2 100644 --- a/404.php +++ b/404.php @@ -1,17 +1,16 @@ -
-

-

+

+

-render_incidents(false,$_GET['offset'],5); +if (isset($_GET['ajax'])) { + $constellation->render_incidents(false, $_GET['offset'], 5); exit(); -}else if (isset($_GET['offset'])) -{ +} else if (isset($_GET['offset'])) { $offset = $_GET['offset']; } -if (isset($_GET['new']) && $_GET['new']=="incident") -{ +if (isset($_GET['new']) && $_GET['new'] == "incident") { Incident::add(); } -if (isset($_GET['delete'])) -{ +if (isset($_GET['delete'])) { Incident::delete($_GET['delete']); } if (isset($_GET['tasks'])) { - Queue::process_queue(); + Queue::process_queue(); } Template::render_header(_("Dashboard"), true); ?> -
-

-

get_name();?>

-
+
+

+

get_name(); ?>

+
-
- render_status(true); - ?> -
-
-
-
-
-

-
+
+ render_status(true); + ?> +
+
+
+
+
+

+
- -

+ +

- -
- get_status()!=-1){?> -
- get_id(), $post_services))?"checked":'';?> id="service-get_id(); ?>"> -
- - - -
- + foreach ($services as $service) { + ?> +
+ get_status() != -1) { ?> +
+ get_id(), $post_services)) ? "checked" : ''; ?> id="service-get_id(); ?>"> +
+ + + +
+
- " value="" required> + " value="" required> - "> + ">
-

+

@@ -95,26 +91,24 @@ Template::render_header(_("Dashboard"), true);
- +
- - render_incidents(true,$offset,5,true); - $constellation->render_incidents(false,$offset,5,true); - ?> -
+ + render_incidents(true, $offset, 5, true); + $constellation->render_incidents(false, $offset, 5, true); + ?>
+
\ No newline at end of file diff --git a/admin/index.php b/admin/index.php index 345f89c..2184858 100644 --- a/admin/index.php +++ b/admin/index.php @@ -1,10 +1,8 @@ getSetting($mysqli,"name")); - define("TITLE", $db->getSetting($mysqli,"title")); - define("WEB_URL", $db->getSetting($mysqli,"url")); - define("MAILER_NAME", $db->getSetting($mysqli,"mailer")); - define("MAILER_ADDRESS", $db->getSetting($mysqli,"mailer_email")); + define("NAME", $db->getSetting($mysqli, "name")); + define("TITLE", $db->getSetting($mysqli, "title")); + define("WEB_URL", $db->getSetting($mysqli, "url")); + define("MAILER_NAME", $db->getSetting($mysqli, "mailer")); + define("MAILER_ADDRESS", $db->getSetting($mysqli, "mailer_email")); define("GOOGLE_RECAPTCHA", $db->getBooleanSetting($mysqli, "google_recaptcha")); define("GOOGLE_RECAPTCHA_SECRET", $db->getSetting($mysqli, "google_recaptcha_secret")); @@ -39,58 +37,45 @@ else{ // Process the subscriber notification queue // If CRON_SERVER_IP is not set, call notification once incident has been saved - if ( empty(CRON_SERVER_IP) ) - { - if ( isset($_GET['sent']) && $_GET['sent'] == true ) - { + if (empty(CRON_SERVER_IP)) { + if (isset($_GET['sent']) && $_GET['sent'] == true) { Queue::process_queue(); } - } - else if ( isset($_GET['task']) && $_GET['task'] == 'cron' ) - { + } else if (isset($_GET['task']) && $_GET['task'] == 'cron') { // Else, base it on call to /admin?task=cron being called from IP defined by CRON_SERVER_IP - if (! empty(CRON_SERVER_IP) && $_SERVER['REMOTE_ADDR'] == CRON_SERVER_IP ) - { - Queue::process_queue(); - syslog(1, "CRON server processed"); - } - else { - syslog(1, "CRON called from unauthorised server"); + if (!empty(CRON_SERVER_IP) && $_SERVER['REMOTE_ADDR'] == CRON_SERVER_IP) { + Queue::process_queue(); + syslog(1, "CRON server processed"); + } else { + syslog(1, "CRON called from unauthorised server"); } } - if(isset($_COOKIE['user'])&&!isset($_SESSION['user'])) - { + if (isset($_COOKIE['user']) && !isset($_SESSION['user'])) { User::restore_session(); } - if (!isset($_SESSION['user'])) - { - if (isset($_GET['do']) && $_GET['do']=="lost-password") - { + if (!isset($_SESSION['user'])) { + if (isset($_GET['do']) && $_GET['do'] == "lost-password") { require_once("lost-password.php"); - }else if (isset($_GET['do']) && $_GET['do']=="change-email"){ + } else if (isset($_GET['do']) && $_GET['do'] == "change-email") { $user_pwd = new User($_GET['id']); $user_pwd->change_email(); require_once("login-form.php"); - } - else{ + } else { User::login(); require_once("login-form.php"); } - } - else - { + } else { $user = new User($_SESSION['user']); - if (!$user->is_active()) - { + if (!$user->is_active()) { User::logout(); } - if (!isset($_GET['do'])){ + if (!isset($_GET['do'])) { $do = ""; - }else{ + } else { $do = $_GET['do']; } @@ -98,17 +83,17 @@ else{ case 'change-email': $user = new User($_GET['id']); $user->change_email(); - case 'user': - require_once("user.php"); - break; + case 'user': + require_once("user.php"); + break; - case 'settings': - require_once("settings.php"); - break; + case 'settings': + require_once("settings.php"); + break; - case 'new-user': - require_once("new-user.php"); - break; + case 'new-user': + require_once("new-user.php"); + break; case 'new-service': case 'edit-service': @@ -128,9 +113,9 @@ else{ User::logout(); break; - default: - require_once("dashboard.php"); - break; + default: + require_once("dashboard.php"); + break; } Template::render_footer(true); diff --git a/admin/login-form.php b/admin/login-form.php index f4ef6f9..0521f93 100644 --- a/admin/login-form.php +++ b/admin/login-form.php @@ -1,32 +1,32 @@ -
-

-
-
- -

- -

- -
-
- - " class="form-control" name="email" id="email" type="email" tabindex="1" value="" required> -
-
- - " class="form-control" name="pass" id="pass" type="password" tabindex="2" required> -
- - -
-
-
- -
-
+
+

+
+
+ +

+ +

+ +
+
+ + " class="form-control" name="email" id="email" type="email" tabindex="1" value="" required>
+
+ + " class="form-control" name="pass" id="pass" type="password" tabindex="2" required> +
+ + +
+
+
+ +
+
+
-
-

-
-
- - change_password($_POST['token']); - if (isset($message)){?> -

- - -

- - -

- - -

- - +

+
+
- if (isset($message)){?> -

- -
- - -
- " type="email" required> - - - -
- -

get_name(), $user->get_username());?>

- - - - " type="password" class="form-control" name="password"> - - " type="password" class="form-control" name="password_repeat"> - - -
- -
-change_password($_POST['token']); + if (isset($message)) { ?> +

+ + +

+ + +

+ + +

+ + +

+ +
+ + +
+ " type="email" required> + + + +
+ +

get_name(), $user->get_username()); ?>

+ + + + " type="password" class="form-control" name="password"> + + " type="password" class="form-control" name="password_repeat"> + + +
+ +
+
-

Add new user

+

Add new user

-
- -

- + + +

+
-
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
+
" class="form-control" required>
-
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
+
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
- +
- -
+ + \ No newline at end of file diff --git a/admin/options.php b/admin/options.php index 3ebdb16..ac7ed0f 100644 --- a/admin/options.php +++ b/admin/options.php @@ -1,15 +1,14 @@ getBooleanSetting($mysqli, "notifyUpdates"); - $emailSubscription_status = $db->getBooleanSetting($mysqli, "subscribe_email"); - $telegramSubscription_status = $db->getBooleanSetting($mysqli, "subscribe_telegram"); - $tg_bot_api_token = $db->getSetting($mysqli, "tg_bot_api_token"); - $tg_bot_username = $db->getSetting($mysqli, "tg_bot_username"); - $php_mailer_status = $db->getBooleanSetting($mysqli, "php_mailer"); - $php_mailer_smtp_status = $db->getBooleanSetting($mysqli, "php_mailer_smtp"); - $php_mailer_secure_status = $db->getBooleanSetting($mysqli, "php_mailer_secure"); - $php_mailer_path = $db->getSetting($mysqli, "php_mailer_path"); - $php_mailer_host = $db->getSetting($mysqli, "php_mailer_host"); - $php_mailer_port = $db->getSetting($mysqli, "php_mailer_port"); - $php_mailer_user = $db->getSetting($mysqli, "php_mailer_user"); - $php_mailer_pass = $db->getSetting($mysqli, "php_mailer_pass"); - $cron_server_ip = $db->getSetting($mysqli, "cron_server_ip"); - $google_rechaptcha_status = $db->getBooleanSetting($mysqli, "google_recaptcha"); - $google_recaptcha_sitekey = $db->getSetting($mysqli, "google_recaptcha_sitekey"); - $google_recaptcha_secret = $db->getSetting($mysqli, "google_recaptcha_secret"); +$db = new SSDB(); +$notifyUpdates_status = $db->getBooleanSetting($mysqli, "notifyUpdates"); +$emailSubscription_status = $db->getBooleanSetting($mysqli, "subscribe_email"); +$telegramSubscription_status = $db->getBooleanSetting($mysqli, "subscribe_telegram"); +$tg_bot_api_token = $db->getSetting($mysqli, "tg_bot_api_token"); +$tg_bot_username = $db->getSetting($mysqli, "tg_bot_username"); +$php_mailer_status = $db->getBooleanSetting($mysqli, "php_mailer"); +$php_mailer_smtp_status = $db->getBooleanSetting($mysqli, "php_mailer_smtp"); +$php_mailer_secure_status = $db->getBooleanSetting($mysqli, "php_mailer_secure"); +$php_mailer_path = $db->getSetting($mysqli, "php_mailer_path"); +$php_mailer_host = $db->getSetting($mysqli, "php_mailer_host"); +$php_mailer_port = $db->getSetting($mysqli, "php_mailer_port"); +$php_mailer_user = $db->getSetting($mysqli, "php_mailer_user"); +$php_mailer_pass = $db->getSetting($mysqli, "php_mailer_pass"); +$cron_server_ip = $db->getSetting($mysqli, "cron_server_ip"); +$google_rechaptcha_status = $db->getBooleanSetting($mysqli, "google_recaptcha"); +$google_recaptcha_sitekey = $db->getSetting($mysqli, "google_recaptcha_sitekey"); +$google_recaptcha_secret = $db->getSetting($mysqli, "google_recaptcha_secret"); - $db->getSetting($mysqli, ""); - $set_post = false; - if(!empty($_POST)){ - $db->updateSetting($mysqli, "notifyUpdates", getToggle($_POST["nu_toggle"])); - $db->updateSetting($mysqli, "name",htmlspecialchars($_POST["sitename"], ENT_QUOTES)); - $db->updateSetting($mysqli, "subscribe_email", getToggle($_POST["email_subscription_toggle"])); - $db->updateSetting($mysqli, "subscribe_telegram", getToggle($_POST["telegram_subscription_toggle"])); - $db->updateSetting($mysqli, "tg_bot_api_token", htmlspecialchars($_POST["tg_bot_api_token"], ENT_QUOTES)); - $db->updateSetting($mysqli, "tg_bot_username", htmlspecialchars($_POST["tg_bot_username"], ENT_QUOTES)); - $db->updateSetting($mysqli, "php_mailer", getToggle($_POST["php_mailer_toggle"])); - $db->updateSetting($mysqli, "php_mailer_smtp", getToggle($_POST["php_mailer_smtp_toggle"])); - $db->updateSetting($mysqli, "php_mailer_secure", getToggle($_POST["php_mailer_secure_toggle"])); - $db->updateSetting($mysqli, "php_mailer_path", htmlspecialchars($_POST["php_mailer_path"], ENT_QUOTES)); - $db->updateSetting($mysqli, "php_mailer_host", htmlspecialchars($_POST["php_mailer_host"], ENT_QUOTES)); - $db->updateSetting($mysqli, "php_mailer_port", htmlspecialchars($_POST["php_mailer_port"], ENT_QUOTES)); - $db->updateSetting($mysqli, "php_mailer_user", htmlspecialchars($_POST["php_mailer_user"], ENT_QUOTES)); - $db->updateSetting($mysqli, "php_mailer_pass", htmlspecialchars($_POST["php_mailer_pass"], ENT_QUOTES)); - $db->updateSetting($mysqli, "cron_server_ip", htmlspecialchars($_POST["cron_server_ip"], ENT_QUOTES)); - $db->updateSetting($mysqli, "google_recaptcha", getToggle($_POST["google_rechaptcha_toggle"])); - $db->updateSetting($mysqli, "google_recaptcha_sitekey", htmlspecialchars($_POST["google_recaptcha_sitekey"], ENT_QUOTES)); - $db->updateSetting($mysqli, "google_recaptcha_secret", htmlspecialchars($_POST["google_recaptcha_secret"], ENT_QUOTES)); +$db->getSetting($mysqli, ""); +$set_post = false; +if (!empty($_POST)) { + $db->updateSetting($mysqli, "notifyUpdates", getToggle($_POST["nu_toggle"])); + $db->updateSetting($mysqli, "name", htmlspecialchars($_POST["sitename"], ENT_QUOTES)); + $db->updateSetting($mysqli, "subscribe_email", getToggle($_POST["email_subscription_toggle"])); + $db->updateSetting($mysqli, "subscribe_telegram", getToggle($_POST["telegram_subscription_toggle"])); + $db->updateSetting($mysqli, "tg_bot_api_token", htmlspecialchars($_POST["tg_bot_api_token"], ENT_QUOTES)); + $db->updateSetting($mysqli, "tg_bot_username", htmlspecialchars($_POST["tg_bot_username"], ENT_QUOTES)); + $db->updateSetting($mysqli, "php_mailer", getToggle($_POST["php_mailer_toggle"])); + $db->updateSetting($mysqli, "php_mailer_smtp", getToggle($_POST["php_mailer_smtp_toggle"])); + $db->updateSetting($mysqli, "php_mailer_secure", getToggle($_POST["php_mailer_secure_toggle"])); + $db->updateSetting($mysqli, "php_mailer_path", htmlspecialchars($_POST["php_mailer_path"], ENT_QUOTES)); + $db->updateSetting($mysqli, "php_mailer_host", htmlspecialchars($_POST["php_mailer_host"], ENT_QUOTES)); + $db->updateSetting($mysqli, "php_mailer_port", htmlspecialchars($_POST["php_mailer_port"], ENT_QUOTES)); + $db->updateSetting($mysqli, "php_mailer_user", htmlspecialchars($_POST["php_mailer_user"], ENT_QUOTES)); + $db->updateSetting($mysqli, "php_mailer_pass", htmlspecialchars($_POST["php_mailer_pass"], ENT_QUOTES)); + $db->updateSetting($mysqli, "cron_server_ip", htmlspecialchars($_POST["cron_server_ip"], ENT_QUOTES)); + $db->updateSetting($mysqli, "google_recaptcha", getToggle($_POST["google_rechaptcha_toggle"])); + $db->updateSetting($mysqli, "google_recaptcha_sitekey", htmlspecialchars($_POST["google_recaptcha_sitekey"], ENT_QUOTES)); + $db->updateSetting($mysqli, "google_recaptcha_secret", htmlspecialchars($_POST["google_recaptcha_secret"], ENT_QUOTES)); - $set_post = true; - /*if($nu_toggle == "yes"){ + $set_post = true; + /*if($nu_toggle == "yes"){ $notifyUpdates_status = true; } else { $notifyUpdates_status = false; }*/ - // TODO - Reload page to prevent showing old values! or update variables being displayed - header("Location: " .$uri = $_SERVER['REQUEST_URI']); - // TODO - The code below will not happen ... + // TODO - Reload page to prevent showing old values! or update variables being displayed + header("Location: " . $uri = $_SERVER['REQUEST_URI']); + // TODO - The code below will not happen ... - /*define("NAME", $db->getSetting($mysqli,"name")); + /*define("NAME", $db->getSetting($mysqli,"name")); define("TITLE", $db->getSetting($mysqli,"title")); define("WEB_URL", $db->getSetting($mysqli,"url")); define("MAILER_NAME", $db->getSetting($mysqli,"mailer")); @@ -92,92 +91,96 @@ else{ define("PHP_MAILER_PASS", $db->getSetting($mysqli,"php_mailer_pass")); define("CRON_SERVER_IP", $db->getSetting($mysqli,"cron_server_ip")); */ - } - Template::render_header(_("Options"), true); +} +Template::render_header(_("Options"), true); ?>
-

+

- -
-
- Site Name -
- + +
+
+ Site Name
+ +
- - + + -
-
- Telegram BOT API Token -
- +
+
+ Telegram BOT API Token
-
-
- Telegram BOT Username -
- + +
+
+
+ Telegram BOT Username
+ +
- - - -
-
- PHPMailer Path -
- + + + +
+
+ PHPMailer Path
-
-
- PHPMailer SMTP Host -
- + +
+
+
+ PHPMailer SMTP Host
-
-
- PHPMailer SMTP Port -
- + +
+
+
+ PHPMailer SMTP Port
-
-
- PHPMailer Username -
- + +
+
+
+ PHPMailer Username
-
-
- PHPMailer Password -
- + +
+
+
+ PHPMailer Password
-
-
- Cron Server IP -
- + +
+
+
+ Cron Server IP
+ +
- -
-
- Google reChaptcha Sitekey -
- + +
+
+ Google reChaptcha Sitekey
-
-
- Google reChaptcha Secret -
- + +
+
+
+ Google reChaptcha Secret
+ +
- - + + \ No newline at end of file diff --git a/admin/service-group.php b/admin/service-group.php index 23f3293..6bc4261 100644 --- a/admin/service-group.php +++ b/admin/service-group.php @@ -1,16 +1,13 @@ prepare("SELECT * FROM services_groups WHERE id LIKE ?"); @@ -27,7 +24,7 @@ if ( isset($_GET['id']) && !isset($_POST['id']) ) { $stmt->execute(); $query = $stmt->get_result(); $data = $query->fetch_assoc(); - $group_value = $data['name']; + $group_value = $data['name']; $description_value = $data['description']; $visibility_id_value = $data['visibility']; } @@ -35,55 +32,47 @@ if ( isset($_GET['id']) && !isset($_POST['id']) ) { if (!$boolEdit) { -Template::render_header(_("New service group"), true); ?> -
-

-
+ Template::render_header(_("New service group"), true); ?> +
+

+
-

+

- -
- -

- + + +

+
-
" class="form-control" required>
-
" class="form-control">
+
" class="form-control" required>
+
" class="form-control">
- + '; + } + ?> + + \ No newline at end of file diff --git a/admin/service.php b/admin/service.php index 1f51d70..0a7a543 100644 --- a/admin/service.php +++ b/admin/service.php @@ -1,11 +1,9 @@ prepare("SELECT * FROM services WHERE id LIKE ?"); @@ -28,7 +26,7 @@ if ( isset($_GET['id']) && !isset($_POST['id']) ) { $query = $stmt->get_result(); $data = $query->fetch_assoc(); //print_r($data); - $service_value = $data['name']; + $service_value = $data['name']; $description_value = $data['description']; $group_id_value = $data['group_id']; } @@ -36,52 +34,46 @@ if ( isset($_GET['id']) && !isset($_POST['id']) ) { if (!$boolEdit) { -Template::render_header(_("New service"), true); ?> -
-

-
+ Template::render_header(_("New service"), true); ?> +
+

+
-

+

- -
- -

- + + +

+
-
" class="form-control" required>
-
" class="form-control">
+
" class="form-control" required>
+
" class="form-control">
- + '; + } + ?> + + \ No newline at end of file diff --git a/admin/settings.php b/admin/settings.php index bd93f10..309b32f 100644 --- a/admin/settings.php +++ b/admin/settings.php @@ -1,10 +1,8 @@ Settings
-

- +if (isset($message)) { +?> +

+
-

- get_rank() <= 1){?> -
-
- -
-
- +

+ get_rank() <= 1) { ?> +
+
+ +
+
+
- - - - - - get_rank()<=1) - {?> - + + + + + + + get_rank() <= 1) { ?> + query("SELECT services.*, services_groups.name AS group_name FROM `services` LEFT JOIN services_groups ON services.group_id = services_groups.id ORDER BY services.name ASC"); - while($result = $query->fetch_assoc()) - { + while ($result = $query->fetch_assoc()) { echo ""; //echo ""; - echo '"; - echo ""; + echo '"; + echo ""; - if ($user->get_rank()<=1) - { - echo ''; + if ($user->get_rank() <= 1) { + echo ''; } echo ""; - }?> + } ?>
".$result['id']."'.$result['name'].''; - echo "".$result['description']."".$result['group_name']."' . $result['name'] . ''; + echo "" . $result['description'] . "" . $result['group_name'] . "
-

- get_rank() <= 1){?> -
-
- -
-
- +

+ get_rank() <= 1) { ?> +
+
+ +
+
+
- - - - - - - get_rank()<=1) - {?> - + + + + + + + + get_rank() <= 1) { ?> + query("SELECT sg.* , (SELECT COUNT(*) FROM services WHERE services.group_id = sg.id) AS counter FROM services_groups AS sg ORDER BY sg.id ASC"); - while($result = $query->fetch_assoc()) - { + while ($result = $query->fetch_assoc()) { echo ""; //echo ""; - echo '"; - echo ""; + echo '"; + echo ""; - if ($user->get_rank()<=1) - { - echo ''; + if ($user->get_rank() <= 1) { + echo ''; } echo ""; - }?> + } ?>
".$result['id']."'.$result['name'].''; - echo ' '.$result['counter'].''; - echo "".$result['description']."".$visibility[$result['visibility']]."' . $result['name'] . ''; + echo ' ' . $result['counter'] . ''; + echo "" . $result['description'] . "" . $visibility[$result['visibility']] . "
@@ -113,29 +107,38 @@ if (isset($message)){
-

- get_rank() == 0){?> +

+ get_rank() == 0) { ?>
- + + + + + + + + + + + query("SELECT * FROM users"); - while($result = $query->fetch_assoc()) - { + while ($result = $query->fetch_assoc()) { echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; + echo ""; + echo ""; + echo ""; + echo ""; + echo ""; echo ""; - }?> + } ?>
Active
Active
".$result['id']."".$result['username']."".$result['name']."".$result['surname']."".$result['email']."".$permissions[$result['permission']].""; - echo ""; + echo "" . $result['id'] . "" . $result['username'] . "" . $result['name'] . "" . $result['surname'] . "" . $result['email'] . "" . $permissions[$result['permission']] . ""; + echo ""; echo "
-
+
\ No newline at end of file diff --git a/admin/user.php b/admin/user.php index 04c7ca4..218d2e5 100644 --- a/admin/user.php +++ b/admin/user.php @@ -1,44 +1,37 @@ change_password(); } -if (isset($_POST['username'])) -{ +if (isset($_POST['username'])) { $displayed_user->change_username(); } -if (isset($_POST['name'])) -{ +if (isset($_POST['name'])) { $displayed_user->change_name(); } -if (isset($_POST['email'])) -{ +if (isset($_POST['email'])) { $success = $displayed_user->email_link(); } -if (isset($_POST['permission'])) -{ +if (isset($_POST['permission'])) { $displayed_user->change_permission(); } -if (isset($_GET['what']) && $_GET['what']=='toggle') -{ +if (isset($_GET['what']) && $_GET['what'] == 'toggle') { $displayed_user->toggle(); } @@ -46,19 +39,18 @@ Template::render_header(_("User"), true); ?>
-

+

- -

+ +

-

+if (isset($success)) { ?> +

render_user_settings(); \ No newline at end of file +$displayed_user->render_user_settings(); diff --git a/api/incidents.php b/api/incidents.php index 105509f..06169a4 100644 --- a/api/incidents.php +++ b/api/incidents.php @@ -1,19 +1,17 @@ get_incidents((isset($_GET['future'])?$_GET['future']:false), $offset, $limit, $timestamp); + $result = $constellation->get_incidents((isset($_GET['future']) ? $_GET['future'] : false), $offset, $limit, $timestamp); header('Cache-Control: no-cache'); header('Content-type: application/json'); echo json_encode($result); -} \ No newline at end of file +} diff --git a/api/status.php b/api/status.php index 5ace02d..6a6c7dc 100644 --- a/api/status.php +++ b/api/status.php @@ -1,42 +1,36 @@ render_status(true, false); - echo json_encode($array); - }else{ - $query = $mysqli->prepare("SELECT name FROM services WHERE id=?"); - $query->bind_param("i", $_GET['id']); - $query->execute(); + if (!isset($_GET['id'])) { + $array = $constellation->render_status(true, false); + echo json_encode($array); + } else { + $query = $mysqli->prepare("SELECT name FROM services WHERE id=?"); + $query->bind_param("i", $_GET['id']); + $query->execute(); $result = $query->get_result()->fetch_assoc(); - if (!count($result)) - { - die(json_encode(["error" => _("Service does not exist!")])); + if (!count($result)) { + die(json_encode(["error" => _("Service does not exist!")])); } - $sql = $mysqli->prepare("SELECT type FROM services_status INNER JOIN status ON services_status.status_id = status.id WHERE service_id = ? AND `time` <= ? AND (`end_time` >= ? OR `end_time`=0) ORDER BY `time` DESC LIMIT 1"); + $sql = $mysqli->prepare("SELECT type FROM services_status INNER JOIN status ON services_status.status_id = status.id WHERE service_id = ? AND `time` <= ? AND (`end_time` >= ? OR `end_time`=0) ORDER BY `time` DESC LIMIT 1"); $sql->bind_param("iii", $id, $timestamp, $timestamp); $sql->execute(); $tmp = $sql->get_result(); - if ($tmp->num_rows) - { + if ($tmp->num_rows) { $service = new Service($_GET['id'], $result['name'], $tmp->fetch_assoc()['type']); - } - else{ + } else { $service = new Service($_GET['id'], $result['name']); } echo json_encode($service); } -} \ No newline at end of file +} diff --git a/classes/constellation.php b/classes/constellation.php index f7ab8d0..245bf21 100644 --- a/classes/constellation.php +++ b/classes/constellation.php @@ -6,8 +6,8 @@ require_once(__DIR__ . "/service-group.php"); require_once(__DIR__ . "/user.php"); require_once(__DIR__ . "/token.php"); /** -* Facade class -*/ + * Facade class + */ class Constellation { @@ -18,48 +18,41 @@ class Constellation * @param int $limit - limits the number of incidents rendered * @param Boolean $admin - specifies whether to render admin controls */ - public function render_incidents($future=false, $offset=0, $limit = 5, $admin = 0){ - if ($offset<0) - { + public function render_incidents($future = false, $offset = 0, $limit = 5, $admin = 0) + { + if ($offset < 0) { $offset = 0; } - $limit = (isset($_GET['limit'])?$_GET['limit']:5); - $offset = (isset($_GET['offset'])?$_GET['offset']:0); - $timestamp = (isset($_GET['timestamp']))?$_GET['timestamp']:time(); + $limit = (isset($_GET['limit']) ? $_GET['limit'] : 5); + $offset = (isset($_GET['offset']) ? $_GET['offset'] : 0); + $timestamp = (isset($_GET['timestamp'])) ? $_GET['timestamp'] : time(); $incidents = $this->get_incidents($future, $offset, $limit, $timestamp); $ajax = isset($_GET['ajax']); - if ($future && count($incidents["incidents"]) && !$ajax) - { - echo "

"._("Planned maintenance")."

"; - } - else if (count($incidents["incidents"]) &&!$ajax) - { - if ($offset) - { - echo ''; + if ($future && count($incidents["incidents"]) && !$ajax) { + echo "

" . _("Planned maintenance") . "

"; + } else if (count($incidents["incidents"]) && !$ajax) { + if ($offset) { + echo ''; } - echo "

"._("Past incidents")."

"; - } - else if (!$future &&!$ajax) - { - echo "

"._("No incidents")."

"; + echo "

" . _("Past incidents") . "

"; + } else if (!$future && !$ajax) { + echo "

" . _("No incidents") . "

"; } $show = !$future && $incidents["more"]; $offset += $limit; - if (count($incidents["incidents"])){ + if (count($incidents["incidents"])) { foreach ($incidents['incidents'] as $incident) { $incident->render($admin); } - if ($show) - { - echo ''; + if ($show) { + echo ''; } } } @@ -69,54 +62,49 @@ class Constellation * @param boolean $admin * @return array of services */ - public function render_status($admin = false, $heading = true){ + public function render_status($admin = false, $heading = true) + { global $mysqli; //$query = $mysqli->query("SELECT id, name, description FROM services"); $query = $mysqli->query("SELECT services.id, services.name, services.description, services_groups.name as group_name FROM services LEFT JOIN services_groups ON services.group_id=services_groups.id ORDER BY services_groups.name "); $array = array(); - if ($query->num_rows){ + if ($query->num_rows) { $timestamp = time(); - while($result = $query->fetch_assoc()) - { + while ($result = $query->fetch_assoc()) { $id = $result['id']; $sql = $mysqli->prepare("SELECT type FROM services_status INNER JOIN status ON services_status.status_id = status.id WHERE service_id = ? AND `time` <= ? AND (`end_time` >= ? OR `end_time`=0) ORDER BY `time` DESC LIMIT 1"); $sql->bind_param("iii", $id, $timestamp, $timestamp); $sql->execute(); $tmp = $sql->get_result(); - if ($tmp->num_rows) - { + if ($tmp->num_rows) { $array[] = new Service($result['id'], $result['name'], $result['description'], $result['group_name'], $tmp->fetch_assoc()['type']); - } - else{ + } else { $array[] = new Service($result['id'], $result['name'], $result['description'], $result['group_name']); } } - if ($heading) - { + if ($heading) { echo Service::current_status($array); } - } - else{ + } else { $array[] = new Service(0, _("No services"), -1); } - if (!$admin) - { - ?> + if (!$admin) { +?> - '; //$arrCompletedGroups = array(); - foreach($array as $service){ + foreach ($array as $service) { //print_r($service); //if ( !empty($service->group_name) && !in_array($service->group_name, $arrCompletedGroups)) { -//print $service->name; + //print $service->name; // $arrCompletedGroups[] = $service['group_name']; // $service->render(true); //} else { @@ -125,35 +113,33 @@ class Constellation } echo ''; //echo '
'; - } - else{ + } else { return $array; } } - function get_incidents($future = false, $offset = 0, $limit = 5, $timestamp = 0){ + function get_incidents($future = false, $offset = 0, $limit = 5, $timestamp = 0) + { global $mysqli; - if ($timestamp == 0) - { + if ($timestamp == 0) { $timestamp = time(); } - $operator = ($future)?">=":"<="; + $operator = ($future) ? ">=" : "<="; $limit++; $sql = $mysqli->prepare("SELECT users.id, status.type, status.title, status.text, status.time, status.end_time, users.username, status.id as status_id FROM status INNER JOIN users ON user_id=users.id WHERE `time` $operator ? AND `end_time` $operator ? OR (`time`<=? AND `end_time` $operator ? ) ORDER BY `time` DESC LIMIT ? OFFSET ?"); - $sql->bind_param("iiiiii",$timestamp, $timestamp, $timestamp, $timestamp, $limit, $offset); + $sql->bind_param("iiiiii", $timestamp, $timestamp, $timestamp, $timestamp, $limit, $offset); $sql->execute(); $query = $sql->get_result(); $array = []; $limit--; $more = false; - if ($query->num_rows>$limit){ + if ($query->num_rows > $limit) { $more = true; } - if ($query->num_rows){ - while(($result = $query->fetch_assoc()) && $limit-- > 0) - { + if ($query->num_rows) { + while (($result = $query->fetch_assoc()) && $limit-- > 0) { // Add service id and service names to an array in the Incident class $stmt_service = $mysqli->prepare("SELECT services.id,services.name FROM services INNER JOIN services_status ON services.id = services_status.service_id @@ -161,7 +147,7 @@ class Constellation $stmt_service->bind_param("i", $result['status_id']); $stmt_service->execute(); $query_service = $stmt_service->get_result(); - while($result_service = $query_service->fetch_assoc()) { + while ($result_service = $query_service->fetch_assoc()) { $result['service_id'][] = $result_service['id']; $result['service_name'][] = $result_service['name']; } @@ -198,15 +184,14 @@ class Constellation function render_alert($alert_type, $header, $message, $show_link = false, $url = null, $link_text = null) { echo '

- '; - if ( $show_link ) { - echo ''; + if ($show_link) { + echo ''; } - } } diff --git a/classes/db-class.php b/classes/db-class.php index b9fe130..c104916 100644 --- a/classes/db-class.php +++ b/classes/db-class.php @@ -3,53 +3,57 @@ class SSDB { - function execute($conn,$sql){ + function execute($conn, $sql) + { if ($conn->query($sql) === TRUE) { - return true; + return true; } else { - return $conn->error; + return $conn->error; } } - function getSetting($conn,$setting){ - $sql = "SELECT value FROM settings WHERE setting='".$setting."'"; + function getSetting($conn, $setting) + { + $sql = "SELECT value FROM settings WHERE setting='" . $setting . "'"; $result = $conn->query($sql); if ($result->num_rows == 1) { - while($row = $result->fetch_assoc()) { + while ($row = $result->fetch_assoc()) { return $row["value"]; } } else { return "null"; } } - function setSetting($conn,$settingname,$settingvalue){ - $sql = "INSERT INTO settings (setting,value) VALUES ('".$settingname."','".$settingvalue."');"; - if ($conn->query($sql) === TRUE) { - return true; - } else { - return $conn->error; - } - - } - function deleteSetting($conn,$settingname){ - $sql = "DELETE FROM settings WHERE setting=\"".$settingname."\";"; + function setSetting($conn, $settingname, $settingvalue) + { + $sql = "INSERT INTO settings (setting,value) VALUES ('" . $settingname . "','" . $settingvalue . "');"; if ($conn->query($sql) === TRUE) { - return true; - } else { - return $conn->error; - } - + return true; + } else { + return $conn->error; + } } - function updateSetting($conn, $settingname, $settingvalue){ + function deleteSetting($conn, $settingname) + { + $sql = "DELETE FROM settings WHERE setting=\"" . $settingname . "\";"; + if ($conn->query($sql) === TRUE) { + return true; + } else { + return $conn->error; + } + } + function updateSetting($conn, $settingname, $settingvalue) + { $this->deleteSetting($conn, $settingname); $this->setSetting($conn, $settingname, $settingvalue); return true; } - function getBooleanSetting($conn, $setting) { - if (trim($this->getSetting($conn, $setting)) == "yes"){ - return true; - } - return false; + function getBooleanSetting($conn, $setting) + { + if (trim($this->getSetting($conn, $setting)) == "yes") { + return true; + } + return false; } } diff --git a/classes/incident.php b/classes/incident.php index 8f48b3b..503d827 100644 --- a/classes/incident.php +++ b/classes/incident.php @@ -2,8 +2,8 @@ require_once(__DIR__ . "/notification.php"); /** -* Class for creating and rendering an incident -*/ + * Class for creating and rendering an incident + */ class Incident implements JsonSerializable { private $id; @@ -24,14 +24,14 @@ class Incident implements JsonSerializable */ function __construct($data) { - //TODO: Maybe get data from id? + //TODO: Maybe get data from id? $this->id = $data['status_id']; $this->timestamp = $data['time']; $this->end_timestamp = $data['end_time']; - $this->date = new DateTime("@".$data['time']); + $this->date = new DateTime("@" . $data['time']); $this->date = $this->date->format('Y-m-d H:i:sP'); - if ($data['end_time']>0){ - $this->end_date = new DateTime("@".$data['end_time']); + if ($data['end_time'] > 0) { + $this->end_date = new DateTime("@" . $data['end_time']); $this->end_date = $this->end_date->format('Y-m-d H:i:sP'); } $this->type = $data['type']; @@ -46,17 +46,16 @@ class Incident implements JsonSerializable * Deletes incident by ID. * @param int ID */ - public static function delete($id){ + public static function delete($id) + { global $mysqli, $message, $user; - if ($user->get_rank() > 1) - { + if ($user->get_rank() > 1) { $stmt = $mysqli->prepare("SELECT count(*) as count FROM status WHERE id= ? AND user_id = ?"); $stmt->bind_param("ii", $id, $_SESSION['user']); $stmt->execute(); $query = $stmt->get_result(); - if (!$query->fetch_assoc()['count']) - { + if (!$query->fetch_assoc()['count']) { $message = _("You don't have permission to do that!"); return; } @@ -71,7 +70,7 @@ class Incident implements JsonSerializable $stmt->bind_param("i", $id); $stmt->execute(); $query = $stmt->get_result(); - header("Location: ".WEB_URL."/admin"); + header("Location: " . WEB_URL . "/admin"); } /** @@ -84,77 +83,66 @@ class Incident implements JsonSerializable { global $mysqli, $message; //Sould be a better way to get this array... - $statuses = array(_("Major outage"), _("Minor outage"), _("Planned maintenance"), _("Operational") ); + $statuses = array(_("Major outage"), _("Minor outage"), _("Planned maintenance"), _("Operational")); $user_id = $_SESSION['user']; $type = $_POST['type']; $title = strip_tags($_POST['title']); $text = strip_tags($_POST['text'], '
'); - if (strlen($title)==0) - { + if (strlen($title) == 0) { $message = _("Please enter title"); return; - }else if(strlen($title)>50){ + } else if (strlen($title) > 50) { $message = _("Title too long! Character limit is 50"); return; } - if (strlen($title)==0) - { + if (strlen($title) == 0) { $message = _("Please enter text"); return; } - if ($type == 2 && (!strlen(trim($_POST['time'])) || !strlen(trim($_POST['end_time'])))) - { + if ($type == 2 && (!strlen(trim($_POST['time'])) || !strlen(trim($_POST['end_time'])))) { $message = _("Please set start and end time! Use ISO 8601 format."); return; } - if (empty($_POST['services'])){ + if (empty($_POST['services'])) { $message = _("Please select at least one service"); - } - else - { - if (!is_array($_POST['services'])) - { + } else { + if (!is_array($_POST['services'])) { $services = array($_POST['services']); - } - else - { + } else { $services = $_POST['services']; } - if (!empty($_POST['time']) && $type == 2){ - $input_time = (!empty($_POST['time_js'])?$_POST['time_js']: $_POST['time']); - $input_end_time = (!empty($_POST['end_time_js'])?$_POST['end_time_js']: $_POST['end_time']); + if (!empty($_POST['time']) && $type == 2) { + $input_time = (!empty($_POST['time_js']) ? $_POST['time_js'] : $_POST['time']); + $input_end_time = (!empty($_POST['end_time_js']) ? $_POST['end_time_js'] : $_POST['end_time']); $time = strtotime($input_time); $end_time = strtotime($input_end_time); - if (!$time) - { + if (!$time) { $message = _("Start date format is not recognized. Please use ISO 8601 format."); return; } - if (!$end_time) - { + if (!$end_time) { $message = _("End date format is not recognized. Please use ISO 8601 format."); return; } - if ($time >= $end_time) - { + if ($time >= $end_time) { $message = _("End time is either the same or earlier than start time!"); return; } - }else{ + } else { $time = time(); $end_time = ''; } $stmt = $mysqli->prepare("INSERT INTO status VALUES (NULL,?, ?, ?, ?, ?, ?)"); - $stmt->bind_param("issiii", $type, $title, $text, $time ,$end_time ,$user_id); + $stmt->bind_param("issiii", $type, $title, $text, $time, $end_time, $user_id); $stmt->execute(); $query = $stmt->get_result(); $status_id = $mysqli->insert_id; @@ -178,7 +166,7 @@ class Incident implements JsonSerializable $notify->notify_subscribers(); - header("Location: ".WEB_URL."/admin?sent=true"); + header("Location: " . WEB_URL . "/admin?sent=true"); } } @@ -187,40 +175,42 @@ class Incident implements JsonSerializable * @param Boolean $admin - decides whether admin controls should be rendered * @return void */ - public function render($admin=0){ + public function render($admin = 0) + { global $icons; global $classes, $user; - $admin = $admin && (($user->get_rank()<=1) || ($user->get_username() == $this->username)); + $admin = $admin && (($user->get_rank() <= 1) || ($user->get_username() == $this->username)); $Parsedown = new Parsedown(); - ?> -
-
-
- title; ?> - -
- id.'" class="pull-right delete">'; - }?> -
+?> +
+
+
+ title; ?> + +
+ id . '" class="pull-right delete">'; + } ?> +
-
- setBreaksEnabled(true)->text($this->text); ?> -
- -
- + setBreaksEnabled(true)->text($this->text); ?> +
+ +
+ $this->id, "date" => $this->timestamp, diff --git a/classes/locale-negotiator.php b/classes/locale-negotiator.php index b13ee23..e234cd2 100644 --- a/classes/locale-negotiator.php +++ b/classes/locale-negotiator.php @@ -1,10 +1,11 @@ '中文', 'zh_TW' => '中文', 'zu_ZA' => 'Isizulu', - ); + ); /** - * This method scans for languages and creates a list of language and its name (localized ofc.) - * @param String $default_language language displayed to user in case no suitable lang is found - */ + * This method scans for languages and creates a list of language and its name (localized ofc.) + * @param String $default_language language displayed to user in case no suitable lang is found + */ function __construct($default_language) { - $tmp = glob(__DIR__ . '/../locale/*' , GLOB_ONLYDIR); + $tmp = glob(__DIR__ . '/../locale/*', GLOB_ONLYDIR); $this->default_language = $default_language; //Works only if the server supports the locale //This basically means $accepted_langs[] = ""; @@ -239,41 +240,42 @@ class LocaleNegotiator } /** - * Returns list of accepted langs so it can be reused for rendering language list for switching... - */ - public function get_accepted_langs(){ + * Returns list of accepted langs so it can be reused for rendering language list for switching... + */ + public function get_accepted_langs() + { return $this->accepted_langs; } /** - * This method does the actual negotiation. It has override parameter in case user wants to switch - * languages. - * @param String $override adds language to list of preffered languages with highest priority - * @return String language code that matched best with browser preferences - */ - public function negotiate($override = null){ + * This method does the actual negotiation. It has override parameter in case user wants to switch + * languages. + * @param String $override adds language to list of preffered languages with highest priority + * @return String language code that matched best with browser preferences + */ + public function negotiate($override = null) + { $langs = []; if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $http_accept_language = str_replace("-", "_", $_SERVER['HTTP_ACCEPT_LANGUAGE']); - preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $http_accept_language, $lang_parse); + preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $http_accept_language, $lang_parse); - if (count($lang_parse[1])) { - $langs = array_combine($lang_parse[1], $lang_parse[4]); - - foreach ($langs as $lang => $val) { - //If browser didn't send quality of language, it is 1 by default - if ($val === '') $langs[$lang] = 1; - } + if (count($lang_parse[1])) { + $langs = array_combine($lang_parse[1], $lang_parse[4]); - if (isset($override)) - { - //More important than the best lang of browser - $langs[$override] = 2; - } + foreach ($langs as $lang => $val) { + //If browser didn't send quality of language, it is 1 by default + if ($val === '') $langs[$lang] = 1; + } - arsort($langs, SORT_NUMERIC); - } + if (isset($override)) { + //More important than the best lang of browser + $langs[$override] = 2; + } + + arsort($langs, SORT_NUMERIC); + } } //So we have lang code as value @@ -285,18 +287,18 @@ class LocaleNegotiator global $lang; foreach ($langs as $lang) { - if (strlen($lang)>2){ - if (in_array($lang, $accepted_langs)){ + if (strlen($lang) > 2) { + if (in_array($lang, $accepted_langs)) { $best_match = $lang; break; } - }else{ - $possible = array_filter($accepted_langs, function($key) { + } else { + $possible = array_filter($accepted_langs, function ($key) { global $lang; - return strpos($key, $lang) === 0; + return strpos($key, $lang) === 0; }); - if (count($possible)){ + if (count($possible)) { foreach ($possible as $value) { $best_match = $value; } @@ -305,11 +307,10 @@ class LocaleNegotiator } } - if ($best_match === false){ + if ($best_match === false) { $best_match = $this->default_language; } return $best_match; } } - diff --git a/classes/mailer.php b/classes/mailer.php index 4a716b6..9edf1b1 100644 --- a/classes/mailer.php +++ b/classes/mailer.php @@ -15,10 +15,11 @@ if (file_exists("libs/php_idn/idna.php")) { require_once("../libs/php_idn/idna.php"); } -class Mailer { - - public function __construct(){ +class Mailer +{ + public function __construct() + { } /** @@ -28,7 +29,8 @@ class Mailer { * @param boolean $html Set to true if we are sending HTML Mailer * @return boolean True if success */ - public function send_mail($to, $subject, $message, $html = true) { + public function send_mail($to, $subject, $message, $html = true) + { // TODO -Handle $to as an array in order to send to muliple recipients without having // to call the entire send_mail function over and over.. @@ -36,19 +38,19 @@ class Mailer { // Convert IDN/punycode domain to ascii // TODO Handle IDN in left hand side of email address - if ( $this->is_utf8($to) ) { + if ($this->is_utf8($to)) { $elements = explode('@', $to); $domainpart = EncodePunycodeIDN(array_pop($elements)); // Convert domain part to ascii $to = $elements[0] . '@' . $domainpart; // Reassemble tge full email address } // Send using PHP mailer if it is enabled - if ( PHP_MAILER ) { - require_once(PHP_MAILER_PATH .'/Exception.php'); /* Exception class. */ - require_once(PHP_MAILER_PATH .'/PHPMailer.php'); /* The main PHPMailer class. */ + if (PHP_MAILER) { + require_once(PHP_MAILER_PATH . '/Exception.php'); /* Exception class. */ + require_once(PHP_MAILER_PATH . '/PHPMailer.php'); /* The main PHPMailer class. */ - if ( PHP_MAILER_SMTP ) { - require_once(PHP_MAILER_PATH .'/SMTP.php'); /* SMTP class, needed if you want to use SMTP. */ + if (PHP_MAILER_SMTP) { + require_once(PHP_MAILER_PATH . '/SMTP.php'); /* SMTP class, needed if you want to use SMTP. */ } $phpmail = new PHPMailer(false); @@ -58,7 +60,7 @@ class Mailer { //$phpmail->Debugoutput = error_log; // Define SMTP parameters if enabled - if ( PHP_MAILER_SMTP ) { + if (PHP_MAILER_SMTP) { $phpmail->isSMTP(); $phpmail->Host = PHP_MAILER_HOST; @@ -67,7 +69,7 @@ class Mailer { //$phpmail->SMTPDebug = 2; // Enable for debugging // Handle authentication for SMTP if enabled - if ( !empty(PHP_MAILER_USER) ) { + if (!empty(PHP_MAILER_USER)) { $phpmail->SMTPAuth = true; $phpmail->Username = PHP_MAILER_USER; $phpmail->Password = PHP_MAILER_PASS; @@ -77,7 +79,7 @@ class Mailer { $phpmail->addAddress($to); $phpmail->Subject = $subject; // Send HMTL mail - if ( $html ) { + if ($html) { $phpmail->msgHtml($message); $phpmail->AltBody = $this->convert_html_to_plain_txt($message, false); } else { @@ -85,24 +87,22 @@ class Mailer { } $phpmail->isHtml($html); // use htmlmail if enabled - if ( ! $phpmail->send() ) { + if (!$phpmail->send()) { // TODO Log error message $phpmail->ErrorInfo; return false; } return true; - } else { // Use standard PHP mail() function - $headers = "Content-Type: $content_type; \"charset=utf-8\" ".PHP_EOL; - $headers .= "MIME-Version: 1.0 ".PHP_EOL; - $headers .= "From: ".MAILER_NAME.' <'.MAILER_ADDRESS.'>'.PHP_EOL; - $headers .= "Reply-To: ".MAILER_NAME.' <'.MAILER_ADDRESS.'>'.PHP_EOL; + $headers = "Content-Type: $content_type; \"charset=utf-8\" " . PHP_EOL; + $headers .= "MIME-Version: 1.0 " . PHP_EOL; + $headers .= "From: " . MAILER_NAME . ' <' . MAILER_ADDRESS . '>' . PHP_EOL; + $headers .= "Reply-To: " . MAILER_NAME . ' <' . MAILER_ADDRESS . '>' . PHP_EOL; mail($to, $subject, $message, $headers); // TODO log error message if mail fails return true; } - } /** * Tries to verify the domain using dns request against an MX record of the domain part @@ -112,11 +112,12 @@ class Mailer { * @param String $email Email address to check * @return boolean True if MX record exits, false if otherwise */ - public function verify_domain($email){ + public function verify_domain($email) + { // TODO - Handle idn/punycode domain names without being dependent on PHP native libs. $domain = explode('@', $email); - $domain = EncodePunycodeIDN(array_pop($domain).'.'); // Add dot at end of domain to avoid local domain lookups - syslog(1,$domain); + $domain = EncodePunycodeIDN(array_pop($domain) . '.'); // Add dot at end of domain to avoid local domain lookups + syslog(1, $domain); return checkdnsrr($domain, 'MX'); } @@ -145,20 +146,22 @@ class Mailer { * @param boolean $remove_links Set to true if links should be removed from email * @return String pain text version */ - public function convert_html_to_plain_txt($content, $remove_links=false){ + public function convert_html_to_plain_txt($content, $remove_links = false) + { // TODO does not handle unsubscribe/manage subscription text very well. // Replace HTML line breaks with text line breaks - $plain_text = str_ireplace(array("
","
"), "\n\r", $content); + $plain_text = str_ireplace(array("
", "
"), "\n\r", $content); // Remove the content between the tags that wouldn't normally get removed with the strip_tags function - $plain_text = preg_replace(array('@]*?>.*?@siu', + $plain_text = preg_replace(array( + '@]*?>.*?@siu', '@]*?>.*?@siu', '@]*?.*?@siu', '@]*?.*?@siu', ), "", $plain_text); // Remove everything from between the tags that doesn't get removed with strip_tags function // If the user has chosen to preserve the addresses from links - if(!$remove_links){ + if (!$remove_links) { $plain_text = strip_tags(preg_replace('//', ' $1 ', $plain_text)); } @@ -166,9 +169,8 @@ class Mailer { $plain_text = str_replace(" ", "", $plain_text); // Replace multiple line breaks with a single line break - $plain_text = preg_replace("/(\s){3,}/","\r\n\r\n",trim($plain_text)); + $plain_text = preg_replace("/(\s){3,}/", "\r\n\r\n", trim($plain_text)); return $plain_text; } - } diff --git a/classes/notification.php b/classes/notification.php index 762bbd7..8ce257a 100644 --- a/classes/notification.php +++ b/classes/notification.php @@ -25,7 +25,7 @@ class Notification public function populate_impacted_services($status_id) { global $mysqli; - if (! empty($status_id)) { + if (!empty($status_id)) { // Fetch services names for use in email $stmt = $mysqli->prepare("SELECT services.id, services.name FROM services INNER JOIN services_status on services.id = services_status.service_id WHERE services_status.status_id = ?"); $stmt->bind_param("i", $status_id); @@ -66,7 +66,7 @@ class Notification $queue->user_id = $_SESSION['user']; $arr_data = array(); - if ( SUBSCRIBE_EMAIL ) { + if (SUBSCRIBE_EMAIL) { $arr_data = $this->prepare_email(); // Make up the base message and subject for email $queue->type_id = $queue->all_type_id['notify_email']; $queue->template_data1 = $arr_data['subject']; @@ -75,7 +75,7 @@ class Notification //syslog(1, "queue email: ". $task_id_email); $arr_email = array(); } - if ( SUBSCRIBE_TELEGRAM ) { + if (SUBSCRIBE_TELEGRAM) { $arr_data = $this->prepare_telegram(); $queue->type_id = $queue->all_type_id['notify_telegram']; $queue->template_data1 = null; @@ -103,16 +103,14 @@ class Notification if ($typeID == 2 && SUBSCRIBE_EMAIL) { $arr_email[] = $subscriber['subscriberIDFK']; } - } - } - if ( SUBSCRIBE_TELEGRAM) { + if (SUBSCRIBE_TELEGRAM) { $queue->task_id = $task_id_telegram; $queue->add_notification($arr_telegram); // Add array of Telegram users to the notification queue list } - if ( SUBSCRIBE_EMAIL ) { + if (SUBSCRIBE_EMAIL) { $queue->task_id = $task_id_email; $queue->add_notification($arr_email); // Add array of Email users to the notification queue list } @@ -132,13 +130,12 @@ class Notification $msg = sprintf($msg, $firstname); $tg_message = array('text' => $msg, 'chat_id' => $userID, 'parse_mode' => 'HTML'); - $json = @file_get_contents("https://api.telegram.org/bot" . TG_BOT_API_TOKEN . "/sendMessage?" . http_build_query($tg_message) ); + $json = @file_get_contents("https://api.telegram.org/bot" . TG_BOT_API_TOKEN . "/sendMessage?" . http_build_query($tg_message)); $response = json_decode($json, true); - if (!is_array($response) || ! array_key_exists("ok", $response) || $response['ok'] != 1 ) { + if (!is_array($response) || !array_key_exists("ok", $response) || $response['ok'] != 1) { return false; - } return true; } @@ -154,13 +151,14 @@ class Notification { // TODO Error handling $mailer = new Mailer(); - if ( ! $mailer->send_mail($subscriber, $subject, $msg, true) ) { - return false; + if (!$mailer->send_mail($subscriber, $subject, $msg, true)) { + return false; } return true; } - public function prepare_email(){ + public function prepare_email() + { $Parsedown = new Parsedown(); $str_mail = file_get_contents("../libs/templates/email_status_update.html"); @@ -189,7 +187,8 @@ class Notification return $val; } - public function prepare_telegram(){ + public function prepare_telegram() + { $msg = _("Hi #s!\nThere is a status update for service(s): %s\nThe new status is: %s\nTitle: %s\n\n%s\n\nView online"); $val['body'] = sprintf($msg, $this->servicenames, $this->status, $this->title, $this->text, WEB_URL); return $val; diff --git a/classes/queue.php b/classes/queue.php index dd8187c..f989c56 100644 --- a/classes/queue.php +++ b/classes/queue.php @@ -5,157 +5,167 @@ */ class Queue { - public $task_id; - public $type_id; - public $status; - public $template_data1; // i.e. Subject for email - public $template_data2; // i.e. HTML email body - public $create_time; - public $completed_time; - public $num_errors; - public $user_id; - public $all_type_id = array('notify_telegram' => 1, - 'notify_email' => 2); + public $task_id; + public $type_id; + public $status; + public $template_data1; // i.e. Subject for email + public $template_data2; // i.e. HTML email body + public $create_time; + public $completed_time; + public $num_errors; + public $user_id; + public $all_type_id = array( + 'notify_telegram' => 1, + 'notify_email' => 2 + ); - public $all_status = array('populating' => 1, - 'ready' => 2, - 'processing' => 3, - 'completed' => 4, - 'failed' => 5); + public $all_status = array( + 'populating' => 1, + 'ready' => 2, + 'processing' => 3, + 'completed' => 4, + 'failed' => 5 + ); - public function add_task() { - global $mysqli; - $stmt = $mysqli->prepare("INSERT INTO queue_task (type_id, status, template_data1, template_data2, created_time, user_id) VALUES (?,?,?,?,?,?)"); - if ( false===$stmt ) { - //die('prepare() failed: ' . htmlspecialchars($mysqli->error)); - echo $mysqli->errno(); - - } - #if ( false === $stmt ) { syslog(1, "Error :". $mysqli->error); } - $now = time(); - $res = $stmt->bind_param("iissii", $this->type_id, $this->status, $this->template_data1, $this->template_data2, $now, $this->user_id); - if ( false === $res ) { - echo "error"; - die(); - } - $stmt->execute(); - $query = $stmt->get_result(); - print $query; - $this->task_id = $mysqli->insert_id; - return $this->task_id; + public function add_task() + { + global $mysqli; + $stmt = $mysqli->prepare("INSERT INTO queue_task (type_id, status, template_data1, template_data2, created_time, user_id) VALUES (?,?,?,?,?,?)"); + if (false === $stmt) { + //die('prepare() failed: ' . htmlspecialchars($mysqli->error)); + echo $mysqli->errno(); } - - /** - * Remove task from the queue - * @return void - */ - public function delete_task($task_id){ - global $mysqli; - $stmt = $mysqli->prepare("DELETE FROM queue_task WHERE id = ?"); - $stmt->bind_param("i", $task_id); - $stmt->execute(); + #if ( false === $stmt ) { syslog(1, "Error :". $mysqli->error); } + $now = time(); + $res = $stmt->bind_param("iissii", $this->type_id, $this->status, $this->template_data1, $this->template_data2, $now, $this->user_id); + if (false === $res) { + echo "error"; + die(); } + $stmt->execute(); + $query = $stmt->get_result(); + print $query; + $this->task_id = $mysqli->insert_id; + return $this->task_id; + } - /** - * Update status for given task - * @param int $new_status The new current status of the task. Must be selected from the $all_status array. - * @return void - */ - public function set_task_status($new_status) { - global $mysqli; - $stmt = $mysqli->prepare("UPDATE queue_task SET status = ? WHERE id = ?"); - $stmt->bind_param("ii", $new_status, $this->task_id); - $stmt->execute(); - $this->status = $new_status; + /** + * Remove task from the queue + * @return void + */ + public function delete_task($task_id) + { + global $mysqli; + $stmt = $mysqli->prepare("DELETE FROM queue_task WHERE id = ?"); + $stmt->bind_param("i", $task_id); + $stmt->execute(); + } + + /** + * Update status for given task + * @param int $new_status The new current status of the task. Must be selected from the $all_status array. + * @return void + */ + public function set_task_status($new_status) + { + global $mysqli; + $stmt = $mysqli->prepare("UPDATE queue_task SET status = ? WHERE id = ?"); + $stmt->bind_param("ii", $new_status, $this->task_id); + $stmt->execute(); + $this->status = $new_status; + } + + /** + * Add notification queue data for given task + * @param array $arr_data Array filled with subscriber_id + * @return void + */ + public function add_notification($arr_data) + { + global $mysqli; + + //Default status = 1, retres = 0, task_id = $this->task_id + + // Build query manually since mysqli doesn't cater well for multi insert.. + $count = count($arr_data); // Let's find number of elements + $counter = 0; + $query = ''; + $seperator = ','; + $sub_query = '(%d, %d, %d ,%d)%s'; + + foreach ($arr_data as $value) { + $counter++; + if ($counter == $count) { + $seperator = ''; + } // Make sure last character for SQL query is correct + $query .= sprintf($sub_query, $this->task_id, 1, $value, 0, $seperator); } + $sql = "INSERT INTO queue_notify (task_id, status, subscriber_id, retries) VALUES " . $query; - /** - * Add notification queue data for given task - * @param array $arr_data Array filled with subscriber_id - * @return void - */ - public function add_notification($arr_data) { - global $mysqli; + $mysqli->query($sql); - //Default status = 1, retres = 0, task_id = $this->task_id + $this->set_task_status($this->all_status['ready']); // Make task available for release + } - // Build query manually since mysqli doesn't cater well for multi insert.. - $count = count($arr_data); // Let's find number of elements - $counter = 0; - $query = ''; - $seperator = ','; - $sub_query = '(%d, %d, %d ,%d)%s'; + public function update_notification_retries($task_id, $subscriber_id) + { + global $mysqli; + $stmt = $mysqli->prepare("UPDATE queue_notify SET retries = retries+1 WHERE task_id = ? AND subscriber_id = ?"); + $stmt->bind_param("ii", $task_id, $subscriber_id); + $stmt->execute(); + } - foreach ($arr_data as $value) { - $counter++; - if ($counter == $count) { $seperator = ''; } // Make sure last character for SQL query is correct - $query .= sprintf($sub_query, $this->task_id, 1, $value, 0, $seperator); - } - $sql = "INSERT INTO queue_notify (task_id, status, subscriber_id, retries) VALUES ". $query; + public function delete_notification($task_id, $subscriber_id) + { + global $mysqli; + $stmt = $mysqli->prepare("DELETE FROM queue_notify WHERE task_id = ? AND subscriber_id = ?"); + $stmt->bind_param("ii", $task_id, $subscriber_id); + $stmt->execute(); + } - $mysqli->query($sql); + // TODO: Fix max attempts for notifications + public function process_queue() + { + global $mysqli; + $stmt = $mysqli->query("SELECT qn.id, qn.task_id, qn.status, qn.subscriber_id, qn.retries, sub.firstname, sub.userID, sub.token FROM queue_notify AS qn INNER JOIN subscribers AS sub ON qn.subscriber_id = sub.subscriberID WHERE qn.status NOT LIKE 2 AND sub.active=1"); + while ($result = $stmt->fetch_assoc()) { - $this->set_task_status($this->all_status['ready']); // Make task available for release - } + $i = 2; + $stmt2 = $mysqli->prepare("SELECT * FROM queue_task WHERE id = ? AND status = ?"); + $stmt2->bind_param("ii", $result['task_id'], $i); + $stmt2->execute(); + $tmp = $stmt2->get_result(); + $result2 = $tmp->fetch_assoc(); + $typeID = $result2['type_id']; - public function update_notification_retries($task_id, $subscriber_id) { - global $mysqli; - $stmt = $mysqli->prepare("UPDATE queue_notify SET retries = retries+1 WHERE task_id = ? AND subscriber_id = ?"); - $stmt->bind_param("ii", $task_id, $subscriber_id); - $stmt->execute(); - } - - public function delete_notification($task_id, $subscriber_id) { - global $mysqli; - $stmt = $mysqli->prepare("DELETE FROM queue_notify WHERE task_id = ? AND subscriber_id = ?"); - $stmt->bind_param("ii", $task_id, $subscriber_id); - $stmt->execute(); - - } - - // TODO: Fix max attempts for notifications - public function process_queue(){ - global $mysqli; - $stmt = $mysqli->query("SELECT qn.id, qn.task_id, qn.status, qn.subscriber_id, qn.retries, sub.firstname, sub.userID, sub.token FROM queue_notify AS qn INNER JOIN subscribers AS sub ON qn.subscriber_id = sub.subscriberID WHERE qn.status NOT LIKE 2 AND sub.active=1"); - while ( $result = $stmt->fetch_assoc() ) { - - $i = 2; - $stmt2 = $mysqli->prepare("SELECT * FROM queue_task WHERE id = ? AND status = ?"); - $stmt2->bind_param("ii", $result['task_id'], $i); - $stmt2->execute(); - $tmp = $stmt2->get_result(); - $result2 = $tmp->fetch_assoc(); - $typeID = $result2['type_id']; - - // Handle telegram - if ($typeID == 1) { - $msg = str_replace("#s", $result['firstname'], $result2['template_data2']); - if ( ! Notification::submit_queue_telegram($result['userID'], $result['firstname'], $msg) ) { - Queue::update_notification_retries($result['task_id'], $result['subscriber_id']); // Sent - } else { - Queue::delete_notification($result['task_id'], $result['subscriber_id']); // Failed - } - } - - // Handle email - if ($typeID == 2) { - $msg = str_replace("%token%", $result['token'], $result2['template_data2']); - if ( ! Notification::submit_queue_email($result['userID'], $result2['template_data1'], $msg) ) { - Queue::update_notification_retries($result['task_id'], $result['subscriber_id']); // Sent - - } else { - Queue::delete_notification($result['task_id'], $result['subscriber_id']); // Failed - } - } - } - - // Check if queue log is empty and if so delete the queue_task - $stmt = $mysqli->query("SELECT id, (SELECT COUNT(*) FROM queue_notify AS qn WHERE qn.task_id = queue_task.id) AS count FROM queue_task"); - while ( $result = $stmt->fetch_assoc() ) { - if ( $result['count'] == 0 ) { - Queue::delete_task($result['id']); + // Handle telegram + if ($typeID == 1) { + $msg = str_replace("#s", $result['firstname'], $result2['template_data2']); + if (!Notification::submit_queue_telegram($result['userID'], $result['firstname'], $msg)) { + Queue::update_notification_retries($result['task_id'], $result['subscriber_id']); // Sent + } else { + Queue::delete_notification($result['task_id'], $result['subscriber_id']); // Failed } } + // Handle email + if ($typeID == 2) { + $msg = str_replace("%token%", $result['token'], $result2['template_data2']); + if (!Notification::submit_queue_email($result['userID'], $result2['template_data1'], $msg)) { + Queue::update_notification_retries($result['task_id'], $result['subscriber_id']); // Sent + + } else { + Queue::delete_notification($result['task_id'], $result['subscriber_id']); // Failed + } + } } + + // Check if queue log is empty and if so delete the queue_task + $stmt = $mysqli->query("SELECT id, (SELECT COUNT(*) FROM queue_notify AS qn WHERE qn.task_id = queue_task.id) AS count FROM queue_task"); + while ($result = $stmt->fetch_assoc()) { + if ($result['count'] == 0) { + Queue::delete_task($result['id']); + } + } + } } diff --git a/classes/service-group.php b/classes/service-group.php index 933571a..a22a6f4 100644 --- a/classes/service-group.php +++ b/classes/service-group.php @@ -1,7 +1,8 @@ 50) - { + if (strlen($_POST['group']) > 50) { $message = _("Service group name is too long! Character limit is 50"); return; - }else if (strlen(trim($_POST['group']))==0){ + } else if (strlen(trim($_POST['group'])) == 0) { $message = _("Please enter name!"); return; } - if ($user->get_rank()<=1) - { + if ($user->get_rank() <= 1) { global $mysqli; $name = $_POST["group"]; $description = $_POST["description"]; @@ -82,9 +81,8 @@ class ServiceGroup $stmt->bind_param("ssi", $name, $description, $visibility_id); $stmt->execute(); $stmt->get_result(); - header("Location: ".WEB_URL."/admin/?do=settings"); - }else - { + header("Location: " . WEB_URL . "/admin/?do=settings"); + } else { $message = _("You don't have the permission to do that!"); } } @@ -92,17 +90,15 @@ class ServiceGroup public static function edit() { global $user, $message; - if (strlen($_POST['group'])>50) - { + if (strlen($_POST['group']) > 50) { $message = _("Service group name is too long! Character limit is 50"); return; - }else if (strlen(trim($_POST['group']))==0){ + } else if (strlen(trim($_POST['group'])) == 0) { $message = _("Please enter name!"); return; } - if ($user->get_rank()<=1) - { + if ($user->get_rank() <= 1) { global $mysqli; $name = $_POST["group"]; $description = $_POST["description"]; @@ -112,9 +108,8 @@ class ServiceGroup $stmt->bind_param("ssii", $name, $description, $visibility_id, $group_id); $stmt->execute(); $stmt->get_result(); - header("Location: ".WEB_URL."/admin/?do=settings"); - }else - { + header("Location: " . WEB_URL . "/admin/?do=settings"); + } else { $message = _("You don't have the permission to do that!"); } } @@ -125,8 +120,7 @@ class ServiceGroup public static function delete() { global $user, $message; - if ($user->get_rank()<=1) - { + if ($user->get_rank() <= 1) { global $mysqli; $id = $_GET['delete']; @@ -140,10 +134,8 @@ class ServiceGroup $stmt->execute(); $query = $stmt->get_result(); - header("Location: ".WEB_URL."/admin/?do=settings"); - } - else - { + header("Location: " . WEB_URL . "/admin/?do=settings"); + } else { $message = _("You don't have the permission to do that!"); } } @@ -153,7 +145,8 @@ class ServiceGroup * Get list of services groups. * @return array $groups */ - public function get_groups() { + public function get_groups() + { global $mysqli; $stmt = $mysqli->query("SELECT id, name FROM services_groups ORDER by name ASC"); diff --git a/classes/service.php b/classes/service.php index bdb650e..eb014d2 100644 --- a/classes/service.php +++ b/classes/service.php @@ -1,7 +1,8 @@ id = $id; @@ -72,17 +73,15 @@ class Service implements JsonSerializable public static function add() { global $user, $message; - if (strlen($_POST['service'])>50) - { + if (strlen($_POST['service']) > 50) { $message = _("Service name is too long! Character limit is 50"); return; - }else if (strlen(trim($_POST['service']))==0){ + } else if (strlen(trim($_POST['service'])) == 0) { $message = _("Please enter name!"); return; } - if ($user->get_rank()<=1) - { + if ($user->get_rank() <= 1) { global $mysqli; $name = htmlspecialchars($_POST['service']); $description = htmlspecialchars($_POST['description']); @@ -91,48 +90,44 @@ class Service implements JsonSerializable $stmt->bind_param("ssi", $name, $description, $group_id); $stmt->execute(); $stmt->get_result(); - header("Location: ".WEB_URL."/admin/?do=settings"); - }else - { + header("Location: " . WEB_URL . "/admin/?do=settings"); + } else { $message = _("You don't have the permission to do that!"); } } /** - * Processes submitted form and adds service unless problem is encountered, - * calling this is possible only for admin or higher rank. Also checks requirements - * for char limits. - * @return void - */ - public static function edit() - { - global $user, $message; - if (strlen($_POST['service'])>50) - { - $message = _("Service name is too long! Character limit is 50"); - return; - }else if (strlen(trim($_POST['service']))==0){ - $message = _("Please enter name!"); - return; - } - - if ($user->get_rank()<=1) - { - global $mysqli; - $service_id = $_POST["id"]; - $name = htmlspecialchars($_POST['service']); - $description = htmlspecialchars($_POST["description"]); - $group_id = $_POST["group_id"]; - $stmt = $mysqli->prepare("UPDATE services SET name=?, description=?, group_id=? WHERE id = ?"); - $stmt->bind_param("ssii", $name, $description, $group_id, $service_id); - $stmt->execute(); - $stmt->get_result(); - header("Location: ".WEB_URL."/admin/?do=settings"); - }else - { - $message = _("You don't have the permission to do that!"); - } + * Processes submitted form and adds service unless problem is encountered, + * calling this is possible only for admin or higher rank. Also checks requirements + * for char limits. + * @return void + */ + public static function edit() + { + global $user, $message; + if (strlen($_POST['service']) > 50) { + $message = _("Service name is too long! Character limit is 50"); + return; + } else if (strlen(trim($_POST['service'])) == 0) { + $message = _("Please enter name!"); + return; } + if ($user->get_rank() <= 1) { + global $mysqli; + $service_id = $_POST["id"]; + $name = htmlspecialchars($_POST['service']); + $description = htmlspecialchars($_POST["description"]); + $group_id = $_POST["group_id"]; + $stmt = $mysqli->prepare("UPDATE services SET name=?, description=?, group_id=? WHERE id = ?"); + $stmt->bind_param("ssii", $name, $description, $group_id, $service_id); + $stmt->execute(); + $stmt->get_result(); + header("Location: " . WEB_URL . "/admin/?do=settings"); + } else { + $message = _("You don't have the permission to do that!"); + } + } + /** * Deletes this service - first checks if user has permission to do that. * @return void @@ -140,8 +135,7 @@ class Service implements JsonSerializable public static function delete() { global $user, $message; - if ($user->get_rank()<=1) - { + if ($user->get_rank() <= 1) { global $mysqli; $id = $_GET['delete']; @@ -151,8 +145,7 @@ class Service implements JsonSerializable $query = $stmt->get_result(); while ($res = $query->fetch_assoc()) { - if ($res['count']==1) - { + if ($res['count'] == 1) { Incident::delete($res['status']); } } @@ -167,10 +160,8 @@ class Service implements JsonSerializable $stmt->execute(); $query = $stmt->get_result(); - header("Location: ".WEB_URL."/admin/?do=settings"); - } - else - { + header("Location: " . WEB_URL . "/admin/?do=settings"); + } else { $message = _("You don't have the permission to do that!"); } } @@ -180,25 +171,24 @@ class Service implements JsonSerializable * @param Service[] $array array of services * @return void */ - public static function current_status($array){ + public static function current_status($array) + { global $all, $some, $classes; - $statuses = array(0,0,0,0); + $statuses = array(0, 0, 0, 0); $worst = 5; foreach ($array as $service) { - if ($service->status<$worst) - { + if ($service->status < $worst) { $worst = $service->get_status(); } $statuses[$service->get_status()]++; } - echo '
'; + echo '
'; - if ($statuses[$worst] == count($array)) - { + if ($statuses[$worst] == count($array)) { echo $all[$worst]; - }else{ + } else { echo $some[$worst]; } echo '
'; @@ -209,7 +199,8 @@ class Service implements JsonSerializable * @param $boolGroup set to true if the groups name is to be rendered * @return void */ - public function render(){ + public function render() + { global $statuses; global $classes; static $arrCompletedGroups = array(); @@ -218,49 +209,50 @@ class Service implements JsonSerializable // Check if previous ul has been opened, and if a empty/new group is being // render_header, close the UL first. - if ( $boolOpened ) { - if ( empty($this->group_name) || !in_array($this->group_name, $arrCompletedGroups) ) { + if ($boolOpened) { + if (empty($this->group_name) || !in_array($this->group_name, $arrCompletedGroups)) { echo ''; $boolOpened = false; } } // If no group exist or group is new, start a new UL - if ( !empty($this->group_name) && !in_array($this->group_name, $arrCompletedGroups)) { + if (!empty($this->group_name) && !in_array($this->group_name, $arrCompletedGroups)) { echo '
    '; //echo '
      '; // Render the group status if it exists - echo '
    •  ' . $this->group_name .'
      '. _($statuses[$this->status]).'
    • '; + echo '
    •  ' . $this->group_name . '
      ' . _($statuses[$this->status]) . '
    • '; //echo '
    • ' . $this->group_name .'
      status]).'
    • '; $arrCompletedGroups[] = $this->group_name; $boolOpened = true; } - if ( empty($this->group_name)) { + if (empty($this->group_name)) { echo '
        '; -// echo '
          '; + // echo '
            '; $boolFinish = true; } // Render the service status echo '
            '; - echo '
          • ' . $this->name .''; + echo '
          • ' . $this->name . ''; //echo '
          • ' . $this->name . ''; - if(!empty($this->description)) { - echo ' '; + if (!empty($this->description)) { + echo ' '; } - if ($this->status!=-1){?>
            status]);?>
            - status != -1) { ?>
            status]); ?>
            +'; - if ( isset($boolFinish) && $boolFinish) { + if (isset($boolFinish) && $boolFinish) { echo '
          '; } echo '
'; } - public function jsonSerialize() { + public function jsonSerialize() + { global $statuses; return [ "id" => $this->id, @@ -270,5 +262,4 @@ class Service implements JsonSerializable "status_string" => $statuses[$this->status] ]; } - } diff --git a/classes/subscriber.php b/classes/subscriber.php index 0fef6fd..151e5bd 100644 --- a/classes/subscriber.php +++ b/classes/subscriber.php @@ -4,7 +4,7 @@ * Subscriber class * */ -Class Subscriber +class Subscriber { public $id = null; public $firstname = null; @@ -15,7 +15,8 @@ Class Subscriber public $typeID = null; // Holds subscription type ID - function __construct() { + function __construct() + { $this->firstname = null; $this->lastname = null; $this->userID = ""; @@ -44,7 +45,6 @@ Class Subscriber return $row['token']; } return false; - } public function get_subscriber_by_token($token) { @@ -66,7 +66,7 @@ Class Subscriber { global $mysqli; $stmt = $mysqli->prepare("SELECT subscriberID FROM subscribers WHERE userID LIKE ? AND typeID = ? LIMIT 1"); - $stmt->bind_param("si", $this->userID, $this->typeID ); + $stmt->bind_param("si", $this->userID, $this->typeID); $stmt->execute(); $result = $stmt->get_result(); @@ -77,7 +77,7 @@ Class Subscriber return $row['subscriberID']; } else { // User is not registered in DB, so add if $create = true - if ( $create ) { + if ($create) { $subscriber_id = $this->add($this->typeID, $this->userID, $this->active, $this->firstname, $this->lastname); return $subscriber_id; } @@ -111,7 +111,7 @@ Class Subscriber $expireTime = strtotime("+2 hours"); $updateTime = strtotime("now"); $token = $this->generate_token(); - + $stmt = $mysqli->prepare("INSERT INTO subscribers (typeID, userID, firstname, lastname, token, active, expires, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); $stmt->bind_param("issssiii", $typeID, $userID, $firstname, $lastname, $token, $active, $expireTime, $updateTime); $stmt->execute(); @@ -135,7 +135,6 @@ Class Subscriber $stmt->bind_param("ii", $updateTime, $subscriberID); $stmt->execute(); return true; - } public function activate($subscriberID) @@ -164,7 +163,6 @@ Class Subscriber $stmt->execute(); //$query = $stmt->get_result(); return true; - } public function check_userid_exist() @@ -177,7 +175,7 @@ Class Subscriber $stmt->execute(); $result = $stmt->get_result(); - if($result->num_rows > 0) { + if ($result->num_rows > 0) { $row = $result->fetch_assoc(); $this->id = $row['subscriberID']; $this->populate(); @@ -192,7 +190,7 @@ Class Subscriber $stmt = $mysqli->prepare("SELECT subscriberID, token, userID, active, expires FROM subscribers WHERE token LIKE ? LIMIT 1"); - $stmt->bind_param("s", $token ); + $stmt->bind_param("s", $token); $stmt->execute(); $result = $stmt->get_result(); @@ -205,14 +203,14 @@ Class Subscriber // If account is not already active, check if we are within timeframe of exipre +2h // and active if so, otherwise,delete account and return falsev - if ( $row['active'] <> 1 ) { + if ($row['active'] <> 1) { // Calculate time range for when subscription need to be validated $time_end = $row['expires']; - $time_start = $time_end - (3600*2); // TODO - make this interval configurable via a config option + $time_start = $time_end - (3600 * 2); // TODO - make this interval configurable via a config option $time_now = time(); - if ( ($time_now > $time_start) && ($time_now < $time_end) ) { + if (($time_now > $time_start) && ($time_now < $time_end)) { // Timefram is within range, active user.. $stmt2 = $mysqli->prepare("UPDATE subscribers SET active=1, expires=null WHERE subscriberID = ?"); $stmt2->bind_param("i", $row['subscriberID']); @@ -223,7 +221,6 @@ Class Subscriber $this->userID = $row['userID']; $this->token = $row['token']; return true; - } else { // Timeframe outside of given scope -> delete account $stmt2 = $mysqli->prepare("DELETE FROM subscribers WHERE subscriberID = ?"); @@ -251,7 +248,7 @@ Class Subscriber { global $mysqli; - if ( function_exists('openssl_random_pseudo_bytes') ) { + if (function_exists('openssl_random_pseudo_bytes')) { $token = openssl_random_pseudo_bytes(32); //Generate a random string. $token = bin2hex($token); //Convert the binary data into hexadecimal representation. } else { @@ -265,7 +262,7 @@ Class Subscriber $stmt->bind_param("s", $token); $stmt->execute(); $result = $stmt->get_result(); - if ($result->num_rows > 0 ) { + if ($result->num_rows > 0) { // token already exists, call self again $token = $this->generate_token(); } @@ -285,18 +282,18 @@ Class Subscriber $key = ''; // build range and shuffle range using ASCII table - for ($i=0; $i<=255; $i++) { + for ($i = 0; $i <= 255; $i++) { $range[] = chr($i); } // shuffle our range 3 times - for ($i=0; $i<=3; $i++) { + for ($i = 0; $i <= 3; $i++) { shuffle($range); } // loop for random number generation for ($i = 0; $i < mt_rand($min_length, $max_length); $i++) { - $key .= $range[mt_rand(0, count($range)-1)]; + $key .= $range[mt_rand(0, count($range) - 1)]; } $return = bin2hex($key); @@ -325,5 +322,4 @@ Class Subscriber unset($_SESSION['subscriber_id']); unset($_SESSION['subscriber_token']); } - } diff --git a/classes/subscriptions.php b/classes/subscriptions.php index 43f731f..0eb9f95 100644 --- a/classes/subscriptions.php +++ b/classes/subscriptions.php @@ -4,30 +4,30 @@ * Subscriptions class * */ -Class Subscriptions +class Subscriptions { public function add($userID, $service) { global $mysqli; - + $stmt = $mysqli->prepare("INSERT INTO services_subscriber (subscriberIDFK, serviceIDFK) VALUES (?, ?)"); $stmt->bind_param("ii", $userID, $service); $stmt->execute(); //$query = $stmt->get_result(); return true; } - + public function remove($userID, $service) { global $mysqli; - + $stmt = $mysqli->prepare("DELETE FROM services_subscriber WHERE subscriberIDFK = ? AND serviceIDFK = ?"); $stmt->bind_param("ii", $userID, $service); $stmt->execute(); //$query = $stmt->get_result(); return true; } - + function render_subscribed_services($typeID, $subscriberID, $userID, $token) { global $mysqli; @@ -41,54 +41,54 @@ Class Subscriptions $query = $stmt->get_result(); $strNotifyType = _('E-mail Notification subscription'); - if ( $typeID == 1 ) { $strNotifyType = _('Telegram Notification subscription'); } + if ($typeID == 1) { + $strNotifyType = _('Telegram Notification subscription'); + } - ?> +?>
- - ' . _("Your subscriptions") . ""; echo '
'; $subs = array(); // Will be used to hold IDs of services already selected - - if ($query->num_rows){ - while($result = $query->fetch_assoc()) - { - echo ' ' . $result['name'] . ''; + + if ($query->num_rows) { + while ($result = $query->fetch_assoc()) { + echo ' ' . $result['name'] . ''; $subs[] = $result['id']; } - } else { - echo '
'._("You do not currently subscribe to any services. Please add services from the list below.").'
'; + echo '
' . _("You do not currently subscribe to any services. Please add services from the list below.") . '
'; } echo "
"; - + echo '

' . _("Add new subscription") . '

'; // Prepare to query for unselect services. If none are selected, query for all $subsExp = null; - if (count($subs) > 0 ) { - $subsExp = 'NOT IN ('. implode(",", $subs) .')'; + if (count($subs) > 0) { + $subsExp = 'NOT IN (' . implode(",", $subs) . ')'; } $query = $mysqli->query("SELECT services.id, services.name from services WHERE services.id $subsExp"); echo '
'; - if ($query->num_rows){ - while($result = $query->fetch_assoc()){ - echo ' ' . $result['name'] . ''; + if ($query->num_rows) { + while ($result = $query->fetch_assoc()) { + echo ' ' . $result['name'] . ''; } } else { - echo '
'._("No further services available for subscriptions.").'
'; + echo '
' . _("No further services available for subscriptions.") . '
'; } echo '
'; } - -} \ No newline at end of file +} diff --git a/classes/telegram.php b/classes/telegram.php index 5d506c7..ddaf893 100644 --- a/classes/telegram.php +++ b/classes/telegram.php @@ -1,82 +1,85 @@ $value) { - // $data_check_arr[] = $key . '=' . $value; - $data_check_arr[] = $key . '=' . str_replace('https:/t', 'https://t', $value); - } - sort($data_check_arr); - $data_check_string = implode("\n", $data_check_arr); - $secret_key = hash('sha256', TG_BOT_API_TOKEN, true); - $hash = hash_hmac('sha256', $data_check_string, $secret_key); - if (strcmp($hash, $check_hash) !== 0) { - throw new Exception('Data is NOT from Telegram'); - } - if ((time() - $auth_data['auth_date']) > 86400) { - throw new Exception('Data is outdated'); - } - return $auth_data; + return false; + } + /** + * Check if data is from telegram + * + * This checks if the data provides is from telegram. It includes a Fix for firefox + * + * @param mixed $auth_data The Authentication Data + * + * @return $auth_data + * + */ + function checkTelegramAuthorization($auth_data) + { + $check_hash = $auth_data['hash']; + unset($auth_data['hash']); + $data_check_arr = []; + foreach ($auth_data as $key => $value) { + // $data_check_arr[] = $key . '=' . $value; + $data_check_arr[] = $key . '=' . str_replace('https:/t', 'https://t', $value); } - - - /** - * Save telegram userdata - * - * Save the telegram user data in a cookie - * @return void - */ - function saveTelegramUserData($auth_data) { - $auth_data_json = json_encode($auth_data); - setcookie('tg_user', $auth_data_json); + sort($data_check_arr); + $data_check_string = implode("\n", $data_check_arr); + $secret_key = hash('sha256', TG_BOT_API_TOKEN, true); + $hash = hash_hmac('sha256', $data_check_string, $secret_key); + if (strcmp($hash, $check_hash) !== 0) { + throw new Exception('Data is NOT from Telegram'); } - - function get_telegram_subscriberid($user) - { - global $mysqli; - $stmt = $mysqli->prepare("SELECT subscriberID FROM subscribers WHERE typeID=1 AND userID LIKE ? LIMIT 1"); - $stmt->bind_param("s", $user); - $stmt->execute(); - $result = $stmt->get_result(); - if ( $result->num_rows) { - $row = $result->fetch_assoc(); - $subscriberID = $row['subscriberID']; - return $subscriberID; - } - return null; // Return null on false + if ((time() - $auth_data['auth_date']) > 86400) { + throw new Exception('Data is outdated'); } -} \ No newline at end of file + return $auth_data; + } + + + /** + * Save telegram userdata + * + * Save the telegram user data in a cookie + * @return void + */ + function saveTelegramUserData($auth_data) + { + $auth_data_json = json_encode($auth_data); + setcookie('tg_user', $auth_data_json); + } + + function get_telegram_subscriberid($user) + { + global $mysqli; + $stmt = $mysqli->prepare("SELECT subscriberID FROM subscribers WHERE typeID=1 AND userID LIKE ? LIMIT 1"); + $stmt->bind_param("s", $user); + $stmt->execute(); + $result = $stmt->get_result(); + if ($result->num_rows) { + $row = $result->fetch_assoc(); + $subscriberID = $row['subscriberID']; + return $subscriberID; + } + return null; // Return null on false + } +} diff --git a/classes/token.php b/classes/token.php index 1771367..e1233cb 100644 --- a/classes/token.php +++ b/classes/token.php @@ -1,7 +1,8 @@ prepare("INSERT INTO tokens VALUES(?, ?, ?, ?)"); $stmt->bind_param("siis", $token, $id, $expire, $data); $stmt->execute(); @@ -67,8 +68,8 @@ class Token global $mysqli; $time = time(); $stmt = $mysqli->prepare("DELETE FROM tokens WHERE token = ? OR expirebind_param("sd", $token,$time); + $stmt->bind_param("sd", $token, $time); $stmt->execute(); $stmt->get_result(); } -} \ No newline at end of file +} diff --git a/classes/user.php b/classes/user.php index f613373..a1f3c6d 100644 --- a/classes/user.php +++ b/classes/user.php @@ -1,7 +1,8 @@ execute(); $query = $stmt->get_result(); - if (!$query->num_rows) - { + if (!$query->num_rows) { throw new Exception("User doesn't exist."); return; } @@ -48,7 +48,7 @@ class User { return $this->username; } - + /** * Returns whether this user is active * @return Boolean user active status @@ -57,7 +57,7 @@ class User { return $this->active; } - + /** * Returns rank of this user * @return int rank @@ -66,7 +66,7 @@ class User { return $this->rank; } - + /** * Returns full name of this user * @return String name in "Name Surname" format @@ -86,14 +86,13 @@ class User global $mysqli, $message, $user; $id = $_GET['id']; - if ($this->id!=$_SESSION['user'] && $user->get_rank()<=1 && ($user->get_rank()<$this->rank)) - { + if ($this->id != $_SESSION['user'] && $user->get_rank() <= 1 && ($user->get_rank() < $this->rank)) { $stmt = $mysqli->prepare("UPDATE users SET active = !active WHERE id=?"); $stmt->bind_param("i", $this->id); $stmt->execute(); $stmt->close(); - header("Location: ".WEB_URL."/admin/?do=user&id=".$id); - }else{ + header("Location: " . WEB_URL . "/admin/?do=user&id=" . $id); + } else { $message = _("You don't have the permission to do that!"); } } @@ -108,94 +107,87 @@ class User public static function add() { global $user, $message, $mysqli; - if (INSTALL_OVERRIDE || $user->get_rank()==0) - { - if (strlen(trim($_POST['name']))==0) { + if (INSTALL_OVERRIDE || $user->get_rank() == 0) { + if (strlen(trim($_POST['name'])) == 0) { $messages[] = _("Name"); } - if(strlen(trim($_POST['surname']))==0) { + if (strlen(trim($_POST['surname'])) == 0) { $messages[] = _("Surname"); } - if(strlen(trim($_POST['email']))==0) { + if (strlen(trim($_POST['email'])) == 0) { $messages[] = _("Email"); } - if(strlen(trim($_POST['password']))==0) { + if (strlen(trim($_POST['password'])) == 0) { $messages[] = _("Password"); } - if(!isset($_POST['permission'])) - { + if (!isset($_POST['permission'])) { $messages[] = _("Rank"); } - if (isset($messages)){ - $message = "Please enter ".implode(", ", $messages); + if (isset($messages)) { + $message = "Please enter " . implode(", ", $messages); return; } - + $name = $_POST['name']; $surname = $_POST['surname']; $username = $_POST['username']; $email = $_POST['email']; $pass = $_POST['password']; - - if (!filter_var($email, FILTER_VALIDATE_EMAIL)) - { + + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $message = "Invalid email!"; return; } $variables = array(); - if (strlen($name)>50){ + if (strlen($name) > 50) { $variables[] = 'name: 50'; } - if (strlen($surname)>50){ + if (strlen($surname) > 50) { $variables[] = 'surname: 50'; } - if (strlen($username)>50){ + if (strlen($username) > 50) { $variables[] = 'username: 50'; } - if (strlen($email)>60){ + if (strlen($email) > 60) { $variables[] = 'email: 60'; } - if (!empty($variables)) - { + if (!empty($variables)) { $message = _("Please mind the following character limits: "); $message .= implode(", ", $variables); return; } $salt = uniqid(mt_rand(), true); - $hash = hash('sha256', $pass.$salt); + $hash = hash('sha256', $pass . $salt); $permission = $_POST['permission']; - + $stmt = $mysqli->prepare("INSERT INTO users values (NULL, ?, ?, ?, ?, ?, ?, ?, 1)"); $stmt->bind_param("ssssssi", $email, $username, $name, $surname, $hash, $salt, $permission); $stmt->execute(); - if ($stmt->affected_rows==0) - { + if ($stmt->affected_rows == 0) { $message = _("Username or email already used"); return; } $to = $email; - $subject = _('User account created').' - '.NAME; - $msg = sprintf(_("Hi %s!
"."Your account has been created. You can login with your email address at %s with password %s - please change it as soon as possible."), $name." ".$surname,WEB_URL."/admin", WEB_URL."/admin", $pass); - $headers = "Content-Type: text/html; charset=utf-8 ".PHP_EOL; - $headers .= "MIME-Version: 1.0 ".PHP_EOL; - $headers .= "From: ".MAILER_NAME.' <'.MAILER_ADDRESS.'>'.PHP_EOL; - $headers .= "Reply-To: ".MAILER_NAME.' <'.MAILER_ADDRESS.'>'.PHP_EOL; + $subject = _('User account created') . ' - ' . NAME; + $msg = sprintf(_("Hi %s!
" . "Your account has been created. You can login with your email address at %s with password %s - please change it as soon as possible."), $name . " " . $surname, WEB_URL . "/admin", WEB_URL . "/admin", $pass); + $headers = "Content-Type: text/html; charset=utf-8 " . PHP_EOL; + $headers .= "MIME-Version: 1.0 " . PHP_EOL; + $headers .= "From: " . MAILER_NAME . ' <' . MAILER_ADDRESS . '>' . PHP_EOL; + $headers .= "Reply-To: " . MAILER_NAME . ' <' . MAILER_ADDRESS . '>' . PHP_EOL; mail($to, $subject, $msg, $headers); - if (!INSTALL_OVERRIDE) - { - header("Location: ".WEB_URL."/admin/?do=settings"); + if (!INSTALL_OVERRIDE) { + header("Location: " . WEB_URL . "/admin/?do=settings"); } - } - else { + } else { $message = _("You don't have the permission to do that!"); } } @@ -210,13 +202,11 @@ class User public static function login() { global $message, $mysqli; - if (!isset($_POST['email']) && !isset($_POST['email'])) - { + if (!isset($_POST['email']) && !isset($_POST['email'])) { return; } - if ((!isset($_POST['email']) || !isset($_POST['email']))) - { + if ((!isset($_POST['email']) || !isset($_POST['email']))) { $message = _("Please fill in your email and password!"); return; } @@ -228,37 +218,33 @@ class User $stmt->execute(); $query = $stmt->get_result(); - if ($query->num_rows<1) - { + if ($query->num_rows < 1) { $message = _("Wrong email or password"); return; } - + $result = $query->fetch_assoc(); $salt = $result["salt"]; $id = $result["id"]; $active = $result["active"]; - if (!$active) - { + if (!$active) { $message = _("Your account has been disabled. Please contact administrator."); return; } - $hash = hash('sha256', $pass.$salt); + $hash = hash('sha256', $pass . $salt); $stmt = $mysqli->prepare("SELECT count(*) as count FROM users WHERE id=? AND password_hash=?"); $stmt->bind_param("is", $id, $hash); $stmt->execute(); $query = $stmt->get_result(); - if (!$query->fetch_assoc()['count']) - { + if (!$query->fetch_assoc()['count']) { $message = _("Wrong email or password"); return; } - if (isset($_POST['remember'])&&$_POST['remember']) - { + if (isset($_POST['remember']) && $_POST['remember']) { $year = strtotime('+356 days', time()); $token = Token::add($id, 'remember', $year); setcookie('token', $token, $year, "/"); @@ -266,7 +252,7 @@ class User } $_SESSION['user'] = $id; - header("Location: ".WEB_URL."/admin"); + header("Location: " . WEB_URL . "/admin"); } /** @@ -281,24 +267,21 @@ class User $id = $_COOKIE['user']; $token = $_COOKIE['token']; - if (Token::validate($token, $id, "remember")) - { + if (Token::validate($token, $id, "remember")) { $year = strtotime('+356 days', time()); unset($_COOKIE['token']); $_SESSION['user'] = $id; $new_token = Token::add($id, 'remember', $year); setcookie('token', $new_token, $year, "/"); setcookie('user', $id, $year, "/"); - } - else - { + } else { unset($_COOKIE['user']); unset($_COOKIE['token']); setcookie('user', null, -1, '/'); setcookie('token', null, -1, '/'); $message = _("Invalid token detected, please login again!"); } - + Token::delete($token); } /** @@ -308,142 +291,137 @@ class User public function render_user_settings() { global $permissions, $user; - ?> +?>
-
<?php echo _(">
+
<?php echo _(">
- id==$_SESSION['user']||$user->get_rank()<1){ - ?> -
-
-
-
- - -
-
- " - title="" class="form-control form-name" - value=name, ENT_QUOTES);?>> - " - title="" class="form-control form-name" - value=surname, ENT_QUOTES);?>> + id == $_SESSION['user'] || $user->get_rank() < 1) { + ?> + +
+
+
+ + +
+
+ " title="" class="form-control form-name" value=name, ENT_QUOTES); ?>> + " title="" class="form-control form-name" value=surname, ENT_QUOTES); ?>> +
-
-
- -
- +
+ +
+ -

name." ".$this->surname;?>

+

name . " " . $this->surname; ?>

+ } ?>
-
+
-
+
id==$_SESSION['user'] || $user->get_rank()<1){?> -
- - - - -
- username." "; - if ($user->get_rank()>=1){ - echo ""; - } - } - ?> + if ($this->id == $_SESSION['user'] || $user->get_rank() < 1) { ?> +
+ + + + +
+ username . " "; + if ($user->get_rank() >= 1) { + echo ""; + } + } + ?>
-
+
-
-
get_rank() == 0 && $this->id != $_SESSION['user']){?> -
- - -
rank];}?>
-
-
- - id==$_SESSION['user']||$user->get_rank()<1) - {?> -
-
-
Email
-
-
- - - - -
+
+
get_rank() == 0 && $this->id != $_SESSION['user']) { ?> +
+ + +
rank]; + } ?>
- id == $_SESSION['user'] || $user->get_rank() < 1) { ?> +
+
+
Email
+
+
+ + + + +
+
+
+
+ -
-
-
- email; ?> -
-
- id==$_SESSION['user']){ - ?> - -
-
-
+
+
- - " type="password" class="form-control" name="old_password"> - - " type="password" class="form-control" name="password"> - - " type="password" class="form-control" name="password_repeat"> - + email; ?>
- id!=$_SESSION['user'] && $user->get_rank()<=1 && ($user->get_rank()<$this->rank)) - {?> -
-
-
- active){ - echo ''._("Deactivate user").""; - }else{ - echo ''._("Activate user").""; - } - ?> + } + + if ($this->id == $_SESSION['user']) { + ?> + +
+
+
+
+ + " type="password" class="form-control" name="old_password"> + + " type="password" class="form-control" name="password"> + + " type="password" class="form-control" name="password_repeat"> + +
+
+
+ id != $_SESSION['user'] && $user->get_rank() <= 1 && ($user->get_rank() < $this->rank)) { ?> +
+
+
+ active) { + echo '' . _("Deactivate user") . ""; + } else { + echo '' . _("Activate user") . ""; + } + ?> +
-
- id; $stmt = $mysqli->prepare("SELECT count(*) FROM users WHERE username LIKE ?"); - $stmt->bind_param("s",$_POST["username"]); + $stmt->bind_param("s", $_POST["username"]); $stmt->execute(); - if ($stmt->num_rows > 0) - { + if ($stmt->num_rows > 0) { $message = _("This username is already taken."); return; } $stmt->close(); - if ($_SESSION['user'] != $id && $user->get_rank()>0) - { + if ($_SESSION['user'] != $id && $user->get_rank() > 0) { $message = _("Cannot change username of other users!"); - }else{ + } else { $stmt = $mysqli->prepare("UPDATE users SET username = ? WHERE id=?"); - $stmt->bind_param("si",$_POST["username"],$id); + $stmt->bind_param("si", $_POST["username"], $id); $stmt->execute(); $stmt->close(); - header("Location: ".WEB_URL."/admin/?do=user&id=".$id); + header("Location: " . WEB_URL . "/admin/?do=user&id=" . $id); } } @@ -484,30 +460,28 @@ class User public function change_name() { global $mysqli, $message, $user; - if (strlen(trim($_POST['name']))==0) { + if (strlen(trim($_POST['name'])) == 0) { $messages[] = _("Name"); } - if(strlen(trim($_POST['surname']))==0) { + if (strlen(trim($_POST['surname'])) == 0) { $messages[] = _("Surname"); } - if (!empty($messages)) - { - $message = "Please enter ".implode(", ", $messages); + if (!empty($messages)) { + $message = "Please enter " . implode(", ", $messages); return; } $id = $this->id; - if ($_SESSION['user'] != $id && $user->get_rank()>0) - { + if ($_SESSION['user'] != $id && $user->get_rank() > 0) { $message = _("Cannot change names of other users!"); - }else{ + } else { $stmt = $mysqli->prepare("UPDATE users SET `name` = ?, `surname` = ? WHERE id=?"); - $stmt->bind_param("ssi",$_POST["name"],$_POST["surname"],$id); + $stmt->bind_param("ssi", $_POST["name"], $_POST["surname"], $id); $stmt->execute(); $stmt->close(); - header("Location: ".WEB_URL."/admin/?do=user&id=".$id); + header("Location: " . WEB_URL . "/admin/?do=user&id=" . $id); } } @@ -521,18 +495,15 @@ class User { global $mysqli, $message; $id = $this->id; - if ($_POST['password']!=$_POST['password_repeat']) - { + if ($_POST['password'] != $_POST['password_repeat']) { $message = _("Passwords do not match!"); return; } - if (!$token) - { - if ($_SESSION['user']!=$id) - { + if (!$token) { + if ($_SESSION['user'] != $id) { $message = _("Cannot change password of other users!"); - }else{ + } else { $stmt = $mysqli->prepare("SELECT password_salt as salt FROM users WHERE id=?"); $stmt->bind_param("i", $id); $stmt->execute(); @@ -541,35 +512,32 @@ class User $salt = $result['salt']; $pass = $_POST['old_password']; - $hash = hash('sha256', $pass.$salt); + $hash = hash('sha256', $pass . $salt); $stmt = $mysqli->prepare("SELECT count(*) as count FROM users WHERE id=? AND password_hash = ?"); $stmt->bind_param("is", $id, $hash); $stmt->execute(); - if ($stmt->get_result()->fetch_assoc()['count']) - { + if ($stmt->get_result()->fetch_assoc()['count']) { $pass = $_POST['password']; - $hash = hash('sha256', $pass.$salt); + $hash = hash('sha256', $pass . $salt); $stmt = $mysqli->prepare("UPDATE users SET password_hash = ? WHERE id=?"); $stmt->bind_param("si", $hash, $id); $stmt->execute(); $stmt->close(); $stmt = $mysqli->prepare("DELETE FROM tokens WHERE user = ? AND data = 'remember'"); - $stmt->bind_param("d", $id); - $stmt->execute(); + $stmt->bind_param("d", $id); + $stmt->execute(); $stmt->get_result(); - + User::logout(); - } - else{ + } else { $message = _("Wrong password!"); } } - }else{ - if (Token::validate($token, $id, "passwd")) - { + } else { + if (Token::validate($token, $id, "passwd")) { $stmt = $mysqli->prepare("SELECT password_salt as salt FROM users WHERE id=?"); $stmt->bind_param("i", $id); $stmt->execute(); @@ -578,20 +546,18 @@ class User $salt = $result['salt']; $pass = $_POST['password']; - $hash = hash('sha256', $pass.$salt); + $hash = hash('sha256', $pass . $salt); $stmt = $mysqli->prepare("UPDATE users SET password_hash = ? WHERE id=?"); - $stmt->bind_param("si", $hash,$id); + $stmt->bind_param("si", $hash, $id); $stmt->execute(); $stmt->close(); $stmt = $mysqli->prepare("DELETE FROM tokens WHERE user = ? AND data = 'remember'"); - $stmt->bind_param("d", $id); - $stmt->execute(); - $stmt->get_result(); - } - else - { + $stmt->bind_param("d", $id); + $stmt->execute(); + $stmt->get_result(); + } else { $message = _("Invalid token detected, please retry your request from start!"); } Token::delete($token); @@ -612,41 +578,41 @@ class User $stmt->execute(); $query = $stmt->get_result(); - $id = $query->fetch_assoc()['id']; + $id = $query->fetch_assoc()['id']; $time = strtotime('+1 day', time()); $token = Token::add($id, 'passwd', $time); - $link = WEB_URL."/admin/?do=lost-password&id=$id&token=$token"; + $link = WEB_URL . "/admin/?do=lost-password&id=$id&token=$token"; $to = $email; $user = new User($id); - $subject = _('Reset password') . ' - '.NAME; - $msg = sprintf(_( "Hi %s!
Below you will find link to change your password. The link is valid for 24hrs. If you didn't request this, feel free to ignore it.

RESET PASSWORD

If the link doesn't work, copy & paste it into your browser:
%s"), $user->get_name(), $link, $link); - $headers = "Content-Type: text/html; charset=utf-8 ".PHP_EOL; - $headers .= "MIME-Version: 1.0 ".PHP_EOL; - $headers .= "From: ".MAILER_NAME.' <'.MAILER_ADDRESS.'>'.PHP_EOL; - $headers .= "Reply-To: ".MAILER_NAME.' <'.MAILER_ADDRESS.'>'.PHP_EOL; + $subject = _('Reset password') . ' - ' . NAME; + $msg = sprintf(_("Hi %s!
Below you will find link to change your password. The link is valid for 24hrs. If you didn't request this, feel free to ignore it.

RESET PASSWORD

If the link doesn't work, copy & paste it into your browser:
%s"), $user->get_name(), $link, $link); + $headers = "Content-Type: text/html; charset=utf-8 " . PHP_EOL; + $headers .= "MIME-Version: 1.0 " . PHP_EOL; + $headers .= "From: " . MAILER_NAME . ' <' . MAILER_ADDRESS . '>' . PHP_EOL; + $headers .= "Reply-To: " . MAILER_NAME . ' <' . MAILER_ADDRESS . '>' . PHP_EOL; mail($to, $subject, $msg, $headers); - } + } /** * Sends email with link for email change confirmation (security reasons), link is token protected and valid only once. * @return void */ - public function email_link(){ + public function email_link() + { global $user, $mysqli; - + $email = $_POST['email']; $id = $this->id; - if ($user->get_rank()<1 && $id!=$_SESSION['user']) - { + if ($user->get_rank() < 1 && $id != $_SESSION['user']) { $stmt = $mysqli->prepare("UPDATE users SET email = ? WHERE id=?"); $stmt->bind_param("sd", $email, $id); $stmt->execute(); $stmt->get_result(); - header("Location: ".WEB_URL."/admin/?do=user&id=".$id); + header("Location: " . WEB_URL . "/admin/?do=user&id=" . $id); return; } @@ -654,14 +620,14 @@ class User $token = Token::add($id, 'email;$email', $time); - $link = WEB_URL."/admin/?do=change-email&id=$id&token=$token"; + $link = WEB_URL . "/admin/?do=change-email&id=$id&token=$token"; $to = $email; - $subject = _('Email change').' - '.NAME; - $msg = sprintf(_( "Hi %s!
Below you will find link to change your email. The link is valid for 24hrs. If you didn't request this, feel free to ignore it.

CHANGE EMAIL

If the link doesn't work, copy & paste it into your browser:
%s"), $user->get_name(), $link, $link); - $headers = "Content-Type: text/html; charset=utf-8 ".PHP_EOL; - $headers .= "MIME-Version: 1.0 ".PHP_EOL; - $headers .= "From: ".MAILER_NAME.' <'.MAILER_ADDRESS.'>'.PHP_EOL; - $headers .= "Reply-To: ".MAILER_NAME.' <'.MAILER_ADDRESS.'>'.PHP_EOL; + $subject = _('Email change') . ' - ' . NAME; + $msg = sprintf(_("Hi %s!
Below you will find link to change your email. The link is valid for 24hrs. If you didn't request this, feel free to ignore it.

CHANGE EMAIL

If the link doesn't work, copy & paste it into your browser:
%s"), $user->get_name(), $link, $link); + $headers = "Content-Type: text/html; charset=utf-8 " . PHP_EOL; + $headers .= "MIME-Version: 1.0 " . PHP_EOL; + $headers .= "From: " . MAILER_NAME . ' <' . MAILER_ADDRESS . '>' . PHP_EOL; + $headers .= "Reply-To: " . MAILER_NAME . ' <' . MAILER_ADDRESS . '>' . PHP_EOL; mail($to, $subject, $msg, $headers); return _('Confirmation email sent!'); @@ -677,8 +643,7 @@ class User $token = $_GET['token']; $id = $_GET['id']; - if (Token::validate($token, $id, "email;%")) - { + if (Token::validate($token, $id, "email;%")) { $data = explode(";", Token::get_data($token, $id)); $email = $data[1]; @@ -688,25 +653,22 @@ class User $stmt->execute(); $stmt->get_result(); Token::delete($token); - header("Location: ".WEB_URL."/admin/"); - } - else - { + header("Location: " . WEB_URL . "/admin/"); + } else { $message = _("Invalid token detected, please retry your request from start!"); } Token::delete($token); - } /** * Logs current user out. * @return void */ - public static function logout(){ + public static function logout() + { session_unset(); - if (isset($_COOKIE['token'])) - { + if (isset($_COOKIE['token'])) { $token = $_COOKIE['token']; Token::delete($token); unset($_COOKIE['user']); @@ -714,26 +676,25 @@ class User setcookie('user', null, -1, '/'); setcookie('token', null, -1, '/'); } - header("Location: ".WEB_URL."/admin"); + header("Location: " . WEB_URL . "/admin"); } /** * Changes permissions of current user - only super admin can do this, so it checks permission first. * @return void */ - public function change_permission(){ + public function change_permission() + { global $mysqli, $message, $user; - if ($user->get_rank()==0) - { + if ($user->get_rank() == 0) { $permission = $_POST['permission']; $id = $_GET['id']; $stmt = $mysqli->prepare("UPDATE users SET permission=? WHERE id=?"); $stmt->bind_param("si", $permission, $id); - $stmt->execute(); - header("Location: ".WEB_URL."/admin/?do=user&id=".$id); - } - else{ + $stmt->execute(); + header("Location: " . WEB_URL . "/admin/?do=user&id=" . $id); + } else { $message = _("You don't have permission to do that!"); } } -} +} diff --git a/create-server-config.php b/create-server-config.php index c3130da..96a026a 100644 --- a/create-server-config.php +++ b/create-server-config.php @@ -20,4 +20,3 @@ fwrite($f, fread($f2, filesize("IISWebConfig"))); fclose($f); fclose($f2); } -?> diff --git a/css/main.css b/css/main.css index 2909dfe..a825a60 100644 --- a/css/main.css +++ b/css/main.css @@ -183,9 +183,9 @@ a:focus { } article.card input { -background: transparent; -border: none; -border-bottom: 1px white outset; + background: transparent; + border: none; + border-bottom: 1px white outset; } article.card textarea { diff --git a/css/print.css b/css/print.css index d688d07..1971e74 100644 --- a/css/print.css +++ b/css/print.css @@ -1,140 +1,137 @@ @import url(https://fonts.googleapis.com/css?family=Open+Sans:400); @import url(https://fonts.googleapis.com/css?family=Fira+Sans:400,700); -body { - background: #ffffff; - margin: 0; - height: 100%; - line-height: 24px; - font-family: 'Open Sans', sans-serif; +body { + background: #ffffff; + margin: 0; + height: 100%; + line-height: 24px; + font-family: "Open Sans", sans-serif; } -#status-container -{ - border-radius: 0; - border-top: 1px solid #e0e0e0; - border-bottom: 1px solid #e0e0e0; +#status-container { + border-radius: 0; + border-top: 1px solid #e0e0e0; + border-bottom: 1px solid #e0e0e0; } -#status-container .item:last-child -{ - border: none; +#status-container .item:last-child { + border: none; } -#status-container .item{ - border-bottom: 1px solid #e0e0e0; +#status-container .item { + border-bottom: 1px solid #e0e0e0; } -#status-big -{ - float: none; - width: 100%; - text-align: center; - font-family: 'Fira Sans', sans-serif; - font-size: 1.5em +#status-big { + float: none; + width: 100%; + text-align: center; + font-family: "Fira Sans", sans-serif; + font-size: 1.5em; } -#wrapper{ - padding-left: 20%; - padding-right: 20%; +#wrapper { + padding-left: 20%; + padding-right: 20%; } -.service{ - float: left; - box-sizing: border-box; - width:60%; - min-width: 200px; - padding: 15px 35px; - font-weight: bold; - font-size: 1em; - font-family: 'Fira Sans', sans-serif; +.service { + float: left; + box-sizing: border-box; + width: 60%; + min-width: 200px; + padding: 15px 35px; + font-weight: bold; + font-size: 1em; + font-family: "Fira Sans", sans-serif; } -.status{ - float: left; - box-sizing: border-box; - width:40%; - min-width: 150px; - padding: 15px 35px; - text-align: right; - font-size: 0.8em; - font-family: 'Fira Sans', sans-serif; +.status { + float: left; + box-sizing: border-box; + width: 40%; + min-width: 150px; + padding: 15px 35px; + text-align: right; + font-size: 0.8em; + font-family: "Fira Sans", sans-serif; } - -#status-container .status.success{ - color:#2fcc66!important; - font-weight: bolder; +#status-container .status.success { + color: #2fcc66 !important; + font-weight: bolder; } -#status-container .status.warning{ - color:#edaa16!important; - font-weight: bolder; +#status-container .status.warning { + color: #edaa16 !important; + font-weight: bolder; } -#status-container .status.danger{ - color:#e74c3c!important; - font-weight: bolder; +#status-container .status.danger { + color: #e74c3c !important; + font-weight: bolder; } -#status-container .status.primary{ - color:#3A72BD!important; - font-weight: bolder; +#status-container .status.primary { + color: #3a72bd !important; + font-weight: bolder; } -.panel-success{ - border-color:#2fcc66; +.panel-success { + border-color: #2fcc66; } -#footerwrap{ - display: none +#footerwrap { + display: none; } -.btn -{ - display: none +.btn { + display: none; } -h3{ - text-align: center; +h3 { + text-align: center; } -.panel-heading.icon{ - width: 50px; - float: left; - border: none; +.panel-heading.icon { + width: 50px; + float: left; + border: none; } -h2.panel-title{ - float: left; +h2.panel-title { + float: left; } -.panel,.panel-heading,.panel-footer{ - border-width: 3px +.panel, +.panel-heading, +.panel-footer { + border-width: 3px; } body .panel-danger, .panel-danger > .panel-body, .panel-danger > .panel-heading, -.panel-danger > .panel-footer{ - border-color: #a94442 +.panel-danger > .panel-footer { + border-color: #a94442; } body .panel-success, .panel-success > .panel-body, .panel-success > .panel-heading, -.panel-success > .panel-footer{ - border-color: #2fcc66 +.panel-success > .panel-footer { + border-color: #2fcc66; } body .panel-warning, .panel-warning > .panel-body, .panel-warning > .panel-heading, -.panel-warning > .panel-footer{ - border-color: #edaa16 +.panel-warning > .panel-footer { + border-color: #edaa16; } body .panel-primary, .panel-primary > .panel-body, .panel-primary > .panel-heading, -.panel-primary > .panel-footer{ - border-color: #337ab7 -} \ No newline at end of file +.panel-primary > .panel-footer { + border-color: #337ab7; +} diff --git a/email_subscriptions.php b/email_subscriptions.php index 366c2be..a06a29d 100644 --- a/email_subscriptions.php +++ b/email_subscriptions.php @@ -8,11 +8,11 @@ require_once("classes/mailer.php"); //require_once("libs/php_idn/idna.php"); require_once("classes/db-class.php"); $db = new SSDB(); -define("NAME", $db->getSetting($mysqli,"name")); -define("TITLE", $db->getSetting($mysqli,"title")); -define("WEB_URL", $db->getSetting($mysqli,"url")); -define("MAILER_NAME", $db->getSetting($mysqli,"mailer")); -define("MAILER_ADDRESS", $db->getSetting($mysqli,"mailer_email")); +define("NAME", $db->getSetting($mysqli, "name")); +define("TITLE", $db->getSetting($mysqli, "title")); +define("WEB_URL", $db->getSetting($mysqli, "url")); +define("MAILER_NAME", $db->getSetting($mysqli, "mailer")); +define("MAILER_ADDRESS", $db->getSetting($mysqli, "mailer_email")); define("GOOGLE_RECAPTCHA", $db->getBooleanSetting($mysqli, "google_recaptcha")); //define("", $db->getSettings($mysqli, "")); define("GOOGLE_RECAPTCHA_SECRET", $db->getSetting($mysqli, "google_recaptcha_secret")); @@ -37,20 +37,20 @@ $subscription = new Subscriptions(); $boolRegistered = false; -if ( isset($_GET['new']) ) { +if (isset($_GET['new'])) { // Form validation for subscribers signing up $message = ""; - Template :: render_header(_("Email Subscription")); + Template::render_header(_("Email Subscription")); if (isset($_POST['emailaddress'])) { - if (0 == strlen(trim($_POST['emailaddress']))){ + if (0 == strlen(trim($_POST['emailaddress']))) { $messages[] = _("Email address"); } // Perform DNS domain validation on - if ( ! $mailer->verify_domain($_POST['emailaddress']) ) { + if (!$mailer->verify_domain($_POST['emailaddress'])) { $messages[] = _("Domain does not apper to be a valid email domain. (Check MX record)"); } @@ -63,7 +63,7 @@ if ( isset($_GET['new']) ) { 'response' => $_POST["g-recaptcha-response"] ); $options = array( - 'http' => array ( + 'http' => array( 'header' => 'Content-Type: application/x-www-form-urlencoded\r\n', 'method' => 'POST', 'content' => http_build_query($data) @@ -73,19 +73,17 @@ if ( isset($_GET['new']) ) { $verify = file_get_contents($url, false, $context); $captcha_success = json_decode($verify); - if ( $captcha_success->success==false ) { + if ($captcha_success->success == false) { $messages[] = _("reChaptcha validation failed"); } } - if ( isset($messages) ) { + if (isset($messages)) { $message = _("Please check
"); $message .= implode("
", $messages); } - } - if(isset($_POST['emailaddress']) && empty($message)) - { + if (isset($_POST['emailaddress']) && empty($message)) { // Check if email is already registered $boolUserExist = false; @@ -93,23 +91,21 @@ if ( isset($_GET['new']) ) { $subscriber->typeID = 2; // Email $boolUserExist = $subscriber->check_userid_exist(); - $url = WEB_URL."/index.php?do=manage&token=".$subscriber->token; + $url = WEB_URL . "/index.php?do=manage&token=" . $subscriber->token; - if ( ! $boolUserExist ) { + if (!$boolUserExist) { // Create a new subscriber as it does not exist $subscriber->add($subscriber->typeID, $_POST['emailaddress']); - $url = WEB_URL."/index.php?do=manage&token=".$subscriber->token; // Needed again after adding subscriber since token did not exist before add - $msg = sprintf(_("Thank you for registering to receive status updates via email.

Click on the following link to confirm and manage your subcription: %s. New subscriptions must be confirmed within 2 hours"), $url, NAME .' - ' . _("Validate subscription")); - + $url = WEB_URL . "/index.php?do=manage&token=" . $subscriber->token; // Needed again after adding subscriber since token did not exist before add + $msg = sprintf(_("Thank you for registering to receive status updates via email.

Click on the following link to confirm and manage your subcription: %s. New subscriptions must be confirmed within 2 hours"), $url, NAME . ' - ' . _("Validate subscription")); } else { - if ( ! $subscriber->active ) { + if (!$subscriber->active) { // Subscriber is registered, but has not been activated yet... - $msg = sprintf(_("Thank you for registering to receive status updates via email.

Click on the following link to confirm and manage your subcription: %s. New subscriptions must be confirmed within 2 hours"), $url, NAME .' - ' . _("Validate subscription")); + $msg = sprintf(_("Thank you for registering to receive status updates via email.

Click on the following link to confirm and manage your subcription: %s. New subscriptions must be confirmed within 2 hours"), $url, NAME . ' - ' . _("Validate subscription")); $subscriber->activate($subscriber->id); - } else { // subscriber is registered and active - $msg = sprintf(_("Click on the following link to update your existing subscription: %s"), $url, NAME .' - ' . _("Manage subscription")); + $msg = sprintf(_("Click on the following link to update your existing subscription: %s"), $url, NAME . ' - ' . _("Manage subscription")); $subscriber->update($subscriber->id); } } @@ -119,90 +115,87 @@ if ( isset($_GET['new']) ) { $constellation->render_success($header, $message, true, WEB_URL, _('Go back')); // Send email about new registration - $subject = _('Email subscription registered').' - '.NAME; + $subject = _('Email subscription registered') . ' - ' . NAME; $mailer->send_mail($_POST['emailaddress'], $subject, $msg); $boolRegistered = true; } // Add a new email subscriber - display form - if ( isset($_GET['new']) && (! $boolRegistered) ) { + if (isset($_GET['new']) && (!$boolRegistered)) { if (!empty($message)) { - echo '

'.$message.'

'; + echo '

' . $message . '

'; } $strPostedEmail = (isset($_POST['emailaddress'])) ? $_POST['emailaddress'] : ""; - ?> +?> -
-

-
- - -
- -
-
-
-
-
+ +

+
+ +
-
- - - Privacy Policy'), POLICY_URL); - echo $msg; - ?> - -
-
- - - - +
+
+
+
+
+
+
+ + + Privacy Policy'), POLICY_URL); + echo $msg; + ?> + +
+
+ + + +typeID = 2; //EMAIL - if ( $subscriber->is_active_subscriber($_GET['token']) ) { + if ($subscriber->is_active_subscriber($_GET['token'])) { // forward user to subscriber list.... $subscriber->set_logged_in(); header('Location: subscriptions.php'); exit; } else { - Template :: render_header(_("Email Subscription")); + Template::render_header(_("Email Subscription")); $header = _("We cannot find a valid subscriber account matching those details"); $message = _("If you have recently subscribed, please make sure you activate the account within two hours of doing so. You are welcome to try and re-subscribe."); $constellation->render_warning($header, $message, true, WEB_URL, _('Go back')); } - - } else if (isset($_GET['do']) && $_GET['do'] == 'unsubscribe') { // Handle unsubscriptions // TODO This function is universal and should probably live elsewhere?? if (isset($_GET['token'])) { $subscriber->typeID = (int) $_GET['type']; - if ( $subscriber->get_subscriber_by_token($_GET['token'])) { + if ($subscriber->get_subscriber_by_token($_GET['token'])) { $subscriber->delete($subscriber->id); $subscriber->set_logged_off(); - Template :: render_header(_("Email Subscription")); + Template::render_header(_("Email Subscription")); $header = _("You have been unsubscribed from our system"); $message = _("We are sorry to see you go. If you want to subscribe again at a later date please feel free to re-subscribe."); - $constellation->render_success($header, $message, true, WEB_URL, _('Go back')); - + $constellation->render_success($header, $message, true, WEB_URL, _('Go back')); } else { // TODO Log token for troubleshooting ? // Cannot find subscriber - show alert - Template :: render_header(_("Email Subscription")); + Template::render_header(_("Email Subscription")); $header = _("We are unable to find any valid subscriber detail matching your submitted data!"); $message = _("If you believe this to be an error, please contact the system admininistrator."); $constellation->render_warning($header, $message, true, WEB_URL, _('Go back')); @@ -216,4 +209,4 @@ if ( isset($_GET['new']) ) { $constellation->render_warning($header, $message, true, WEB_URL, _('Go back')); } } -Template :: render_footer(); +Template::render_footer(); diff --git a/index.php b/index.php index c05380e..18126a1 100644 --- a/index.php +++ b/index.php @@ -1,74 +1,70 @@ getSetting($mysqli,"name")); -define("TITLE", $db->getSetting($mysqli,"title")); -define("WEB_URL", $db->getSetting($mysqli,"url")); -define("MAILER_NAME", $db->getSetting($mysqli,"mailer")); -define("MAILER_ADDRESS", $db->getSetting($mysqli,"mailer_email")); + require_once("config.php"); + require_once("template.php"); + require_once("classes/constellation.php"); + require_once("classes/db-class.php"); + $db = new SSDB(); + define("NAME", $db->getSetting($mysqli, "name")); + define("TITLE", $db->getSetting($mysqli, "title")); + define("WEB_URL", $db->getSetting($mysqli, "url")); + define("MAILER_NAME", $db->getSetting($mysqli, "mailer")); + define("MAILER_ADDRESS", $db->getSetting($mysqli, "mailer_email")); -define("SUBSCRIBE_EMAIL", $db->getBooleanSetting($mysqli,"subscribe_email")); -define("SUBSCRIBE_TELEGRAM", $db->getBooleanSetting($mysqli,"subscribe_telegram")); -define("TG_BOT_USERNAME", $db->getSetting($mysqli,"tg_bot_username")); -define("TG_BOT_API_TOKEN", $db->getSetting($mysqli,"tg_bot_api_token")); -define("GOOGLE_RECAPTCHA", $db->getBooleanSetting($mysqli,"google_recaptcha")); -define("GOOGLE_RECAPTCHA_SITEKEY", $db->getSetting($mysqli,"google_recaptcha_sitekey")); -define("GOOGLE_RECAPTCHA_SECRET", $db->getSetting($mysqli,"google_recaptcha_secret")); -$offset = 0; + define("SUBSCRIBE_EMAIL", $db->getBooleanSetting($mysqli, "subscribe_email")); + define("SUBSCRIBE_TELEGRAM", $db->getBooleanSetting($mysqli, "subscribe_telegram")); + define("TG_BOT_USERNAME", $db->getSetting($mysqli, "tg_bot_username")); + define("TG_BOT_API_TOKEN", $db->getSetting($mysqli, "tg_bot_api_token")); + define("GOOGLE_RECAPTCHA", $db->getBooleanSetting($mysqli, "google_recaptcha")); + define("GOOGLE_RECAPTCHA_SITEKEY", $db->getSetting($mysqli, "google_recaptcha_sitekey")); + define("GOOGLE_RECAPTCHA_SECRET", $db->getSetting($mysqli, "google_recaptcha_secret")); + $offset = 0; -if (isset($_GET['ajax'])) -{ - $constellation->render_incidents(false,$_GET['offset'],5); - exit(); -}else if (isset($_GET['offset'])) -{ - $offset = $_GET['offset']; -} + if (isset($_GET['ajax'])) { + $constellation->render_incidents(false, $_GET['offset'], 5); + exit(); + } else if (isset($_GET['offset'])) { + $offset = $_GET['offset']; + } -if (isset($_GET['subscriber_logout'])){ - setcookie('tg_user', ''); - setcookie('referer', '', time() - 3600); - $_SESSION['subscriber_valid'] = false; - unset($_SESSION['subscriber_userid']); - unset($_SESSION['subscriber_typeid']); - unset($_SESSION['subscriber_id']); - header('Location: index.php'); -} -/* + if (isset($_GET['subscriber_logout'])) { + setcookie('tg_user', ''); + setcookie('referer', '', time() - 3600); + $_SESSION['subscriber_valid'] = false; + unset($_SESSION['subscriber_userid']); + unset($_SESSION['subscriber_typeid']); + unset($_SESSION['subscriber_id']); + header('Location: index.php'); + } + /* $versionfile = fopen("versionfile", "r") or die("Unable to open version file!"); $appversion = fread($versionfile,filesize("versionfile")); fclose($versionfile); @@ -92,30 +88,29 @@ if($db->getSetting($mysqli,"notifyUpdates") == "yes"){ } } */ -Template::render_header("Status"); + Template::render_header("Status"); ?> -
-

-
-
- render_status();?> -
+
+

+
+
+ render_status(); ?> +
-query("SELECT count(*) FROM status")->num_rows) -{ + query("SELECT count(*) FROM status")->num_rows) { ?> -
-
-
-
- render_incidents(true,$offset); - $constellation->render_incidents(false,$offset); - ?> -
+
+
+
+
+ render_incidents(true, $offset); + $constellation->render_incidents(false, $offset); + ?>
+
negotiate($override); $_SESSION['locale'] = $best_match; - setlocale(LC_ALL, $_SESSION['locale'].".UTF-8"); + setlocale(LC_ALL, $_SESSION['locale'] . ".UTF-8"); bindtextdomain("server-status", __DIR__ . "/locale/"); bind_textdomain_codeset($_SESSION['locale'], "utf-8"); textdomain("server-status"); } -if (isset($_POST['server'])) -{ - $mysqli = new mysqli($_POST['server'],$_POST['dbuser'],$_POST['dbpassword'],$_POST['database']); +if (isset($_POST['server'])) { + $mysqli = new mysqli($_POST['server'], $_POST['dbuser'], $_POST['dbpassword'], $_POST['database']); if ($mysqli->connect_errno) { $message .= sprintf(_("Connection failed: %s\n"), $mysqli->connect_error); } - if (isset($_POST['url']) && filter_var($_POST['url'], FILTER_VALIDATE_URL) === false) - { + if (isset($_POST['url']) && filter_var($_POST['url'], FILTER_VALIDATE_URL) === false) { $message .= _("Please set valid url!"); } //Ostatní má checky existence ve funkci pro pridani - if (0 == strlen(trim($_POST['servername']))){ + if (0 == strlen(trim($_POST['servername']))) { $messages[] = _("Server name"); } - if (0 == strlen(trim($_POST['url']))){ + if (0 == strlen(trim($_POST['url']))) { $messages[] = _("Url"); } - if (0 == strlen(trim($_POST['mailer']))){ + if (0 == strlen(trim($_POST['mailer']))) { $messages[] = _("Mailer name"); } - if (0 == strlen(trim($_POST['title']))){ + if (0 == strlen(trim($_POST['title']))) { $messages[] = _("Title"); } - if (0 == strlen(trim($_POST['mailer_email']))){ + if (0 == strlen(trim($_POST['mailer_email']))) { $messages[] = _("Mailer email"); } - if (0 == strlen(trim($_POST['server']))){ + if (0 == strlen(trim($_POST['server']))) { $messages[] = _("Database server"); } - if (0 == strlen(trim($_POST['database']))){ + if (0 == strlen(trim($_POST['database']))) { $messages[] = _("Database name"); } - if (0 == strlen(trim($_POST['dbuser']))){ + if (0 == strlen(trim($_POST['dbuser']))) { $messages[] = _("Database user"); } - if (0 == strlen(trim($_POST['dbpassword']))) - { + if (0 == strlen(trim($_POST['dbpassword']))) { $messages[] = _("Database password"); } - if (isset($messages)) - { + if (isset($messages)) { $message .= _("Please enter"); $message .= implode(", ", $messages); } } -if(isset($_POST['server']) && empty($message)) -{ +if (isset($_POST['server']) && empty($message)) { define("MAILER_NAME", $_POST['mailer']); define("MAILER_ADDRESS", $_POST['mailer_email']); define("INSTALL_OVERRIDE", true); @@ -102,39 +96,35 @@ if(isset($_POST['server']) && empty($message)) foreach ($array as $value) { $val = trim($value); - if (empty($val)) - { + if (empty($val)) { continue; } $q_res = $mysqli->query($value); - if ($q_res === false) - { + if ($q_res === false) { $message = sprintf(_("Error while creating database. Please check permission for your account or MYSQL version.
Error: %s"), $mysqli->error); break; } } - if (empty($message)) - { + if (empty($message)) { require_once("classes/constellation.php"); User::add(); } - if (empty($message)) - { + if (empty($message)) { //Create config $config = file_get_contents("config.php.template"); //$config = str_replace("##name##", htmlspecialchars($_POST['servername'], ENT_QUOTES), $config); - $db->setSetting($mysqli,"name",htmlspecialchars($_POST['servername'], ENT_QUOTES)); + $db->setSetting($mysqli, "name", htmlspecialchars($_POST['servername'], ENT_QUOTES)); //$config = str_replace("##title##", htmlspecialchars($_POST['title'], ENT_QUOTES), $config); - $db->setSetting($mysqli,"title",htmlspecialchars($_POST['title'], ENT_QUOTES)); + $db->setSetting($mysqli, "title", htmlspecialchars($_POST['title'], ENT_QUOTES)); //$config = str_replace("##url##", $_POST['url'], $config); - $db->setSetting($mysqli,"url",$_POST['url']); + $db->setSetting($mysqli, "url", $_POST['url']); //$config = str_replace("##mailer##", htmlspecialchars($_POST['mailer'], ENT_QUOTES), $config); - $db->setSetting($mysqli,"mailer",htmlspecialchars($_POST['mailer'], ENT_QUOTES)); + $db->setSetting($mysqli, "mailer", htmlspecialchars($_POST['mailer'], ENT_QUOTES)); //$config = str_replace("##mailer_email##", htmlspecialchars($_POST['mailer_email'], ENT_QUOTES), $config); - $db->setSetting($mysqli,"mailer_email",htmlspecialchars($_POST['mailer_email'], ENT_QUOTES)); + $db->setSetting($mysqli, "mailer_email", htmlspecialchars($_POST['mailer_email'], ENT_QUOTES)); $config = str_replace("##server##", htmlspecialchars($_POST['server'], ENT_QUOTES), $config); $config = str_replace("##database##", htmlspecialchars($_POST['database'], ENT_QUOTES), $config); $config = str_replace("##user##", htmlspecialchars($_POST['dbuser'], ENT_QUOTES), $config); @@ -143,169 +133,174 @@ if(isset($_POST['server']) && empty($message)) $config = str_replace("##policy_name##", htmlspecialchars($_POST['policy_name'], ENT_QUOTES), $config); $config = str_replace("##address##", htmlspecialchars($_POST['address'], ENT_QUOTES), $config); $config = str_replace("##policy_mail##", htmlspecialchars($_POST['policy_mail'], ENT_QUOTES), $config); - $config = str_replace("##policy_phone##", htmlspecialchars($_POST['policy_phone'], ENT_QUOTES),$config); + $config = str_replace("##policy_phone##", htmlspecialchars($_POST['policy_phone'], ENT_QUOTES), $config); $config = str_replace("##who_we_are##", htmlspecialchars($_POST['who_we_are'], ENT_QUOTES), $config); - $policy_url_conf = ( ! empty($_POST['policy_url']) ) ? htmlspecialchars($_POST['policy_url'], ENT_QUOTES) : $_POST['url']."/policy.php"; + $policy_url_conf = (!empty($_POST['policy_url'])) ? htmlspecialchars($_POST['policy_url'], ENT_QUOTES) : $_POST['url'] . "/policy.php"; $config = str_replace("##policy_url##", $policy_url_conf, $config); file_put_contents("config.php", $config); include_once "create-server-config.php"; - $db->setSetting($mysqli,"dbConfigVersion","Version2Beta7"); - $db->setSetting($mysqli,"notifyUpdates","yes"); - $db->setSetting($mysqli,"subscribe_email","no"); - $db->setSetting($mysqli,"subscribe_telegram","no"); - $db->setSetting($mysqli,"tg_bot_api_token",""); - $db->setSetting($mysqli,"tg_bot_username",""); - $db->setSetting($mysqli,"php_mailer","no"); - $db->setSetting($mysqli,"php_mailer_host",""); - $db->setSetting($mysqli,"php_mailer_smtp","no"); - $db->setSetting($mysqli,"php_mailer_path",""); - $db->setSetting($mysqli,"php_mailer_port",""); - $db->setSetting($mysqli,"php_mailer_secure","no"); - $db->setSetting($mysqli,"php_mailer_user",""); - $db->setSetting($mysqli,"php_mailer_pass",""); - $db->setSetting($mysqli,"google_recaptcha","no"); - $db->setSetting($mysqli,"google_recaptcha_secret",""); - $db->setSetting($mysqli,"google_recaptcha_sitekey",""); - $db->setSetting($mysqli,"cron_server_ip",""); - if(!$isDeveleoperEnvironement) { - unlink("create-server-config.php"); - unlink("config.php.template"); - unlink("install.sql"); - unlink(__FILE__); - } - header("Location: ".WEB_URL); + $db->setSetting($mysqli, "dbConfigVersion", "Version2Beta7"); + $db->setSetting($mysqli, "notifyUpdates", "yes"); + $db->setSetting($mysqli, "subscribe_email", "no"); + $db->setSetting($mysqli, "subscribe_telegram", "no"); + $db->setSetting($mysqli, "tg_bot_api_token", ""); + $db->setSetting($mysqli, "tg_bot_username", ""); + $db->setSetting($mysqli, "php_mailer", "no"); + $db->setSetting($mysqli, "php_mailer_host", ""); + $db->setSetting($mysqli, "php_mailer_smtp", "no"); + $db->setSetting($mysqli, "php_mailer_path", ""); + $db->setSetting($mysqli, "php_mailer_port", ""); + $db->setSetting($mysqli, "php_mailer_secure", "no"); + $db->setSetting($mysqli, "php_mailer_user", ""); + $db->setSetting($mysqli, "php_mailer_pass", ""); + $db->setSetting($mysqli, "google_recaptcha", "no"); + $db->setSetting($mysqli, "google_recaptcha_secret", ""); + $db->setSetting($mysqli, "google_recaptcha_sitekey", ""); + $db->setSetting($mysqli, "cron_server_ip", ""); + if (!$isDeveleoperEnvironement) { + unlink("create-server-config.php"); + unlink("config.php.template"); + unlink("install.sql"); + unlink(__FILE__); + } + header("Location: " . WEB_URL); } } Template::render_header(_("Install")); ?> -

- +

+ MINIMUM_PHP_VERSION - if (strnatcmp(phpversion(), MINIMUM_PHP_VERSION) >= 0) { $preq_phpver = $preq_ok; } +// Check if PHP version if > MINIMUM_PHP_VERSION +if (strnatcmp(phpversion(), MINIMUM_PHP_VERSION) >= 0) { + $preq_phpver = $preq_ok; +} - // Test for mysqlnd precense. The mysqlnd driver provides some extra functions that is not available - // if the plain mysql package is installed, and mysqli_get_client_stats is one of them. This is documented - // on the PHP site at http://www.php.net/manual/en/mysqlnd.stats.php - // This test is also discussed at https://stackoverflow.com/questions/1475701/how-to-know-if-mysqlnd-is-the-active-driver - if ( function_exists('mysqli_get_client_stats') ) { $preq_mysqlnd = $preq_ok; } +// Test for mysqlnd precense. The mysqlnd driver provides some extra functions that is not available +// if the plain mysql package is installed, and mysqli_get_client_stats is one of them. This is documented +// on the PHP site at http://www.php.net/manual/en/mysqlnd.stats.php +// This test is also discussed at https://stackoverflow.com/questions/1475701/how-to-know-if-mysqlnd-is-the-active-driver +if (function_exists('mysqli_get_client_stats')) { + $preq_mysqlnd = $preq_ok; +} - // Check if we have access to write to location - if ( is_writable(__DIR__) ) { $preq_writedir = $preq_ok; } +// Check if we have access to write to location +if (is_writable(__DIR__)) { + $preq_writedir = $preq_ok; +} ?> -
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-

+

+if (!empty($message)) { +?>

- - +
-

- https://example.com/status - without the trailing slash), so we can mail users link for forgotten password etc...");?> +

+ https://example.com/status - without the trailing slash), so we can mail users link for forgotten password etc..."); ?>
-
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
+
" class="form-control" required>
- +
-
" class="form-control" required>
+
" class="form-control" required>
- +
-
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
+
" class="form-control" required>
-

- +

+
-
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
+
" class="form-control" required>
-
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
+
" class="form-control" required>
-

- +

+
-
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
+
" class="form-control" required>
-
" class="form-control" required>
-
" class="form-control">
+
" class="form-control" required>
+
" class="form-control">
-
+
-
- - " class="form-control"> +
+ + " class="form-control">
-

- +

+
-
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
+
" class="form-control" required>
-
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
+
" class="form-control" required>
-
" class="form-control" required>
+
" class="form-control" required>
- +
diff --git a/install.sql b/install.sql index cd3b013..0885546 100644 --- a/install.sql +++ b/install.sql @@ -1,16 +1,16 @@ CREATE TABLE `settings` ( `setting` varchar(255) NOT NULL UNIQUE, `value` varchar(255) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; +) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci; CREATE TABLE `services` ( `id` int(11) NOT NULL, `name` varchar(50) COLLATE utf8_czech_ci NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; +) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci; CREATE TABLE `services_status` ( `id` int(11) NOT NULL, `service_id` int(11) NOT NULL, `status_id` int(11) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; +) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci; CREATE TABLE `status` ( `id` int(11) NOT NULL, `type` int(11) NOT NULL, @@ -19,13 +19,13 @@ CREATE TABLE `status` ( `time` int(11) NOT NULL, `end_time` int(11) NOT NULL, `user_id` int(11) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; +) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci; CREATE TABLE `tokens` ( `token` varchar(64) COLLATE utf8_czech_ci NOT NULL, `user` int(11) NOT NULL, `expire` int(11) NOT NULL, `data` varchar(80) COLLATE utf8_czech_ci NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; +) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci; CREATE TABLE `users` ( `id` int(11) NOT NULL, `email` varchar(60) COLLATE utf8_czech_ci NOT NULL, @@ -36,18 +36,18 @@ CREATE TABLE `users` ( `password_salt` char(64) COLLATE utf8_czech_ci NOT NULL, `permission` int(11) NOT NULL DEFAULT '0', `active` tinyint(1) NOT NULL DEFAULT '1' -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; +) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci; CREATE TABLE `subscribers` ( `subscriberID` int(11) NOT NULL, `telegramID` int(50) NOT NULL, `firstname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `lastname` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; CREATE TABLE `services_subscriber` ( `comboID` int(11) NOT NULL, `subscriberIDFK` int(11) NOT NULL, `serviceIDFK` int(11) NOT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; CREATE TABLE queue_notify ( id int(11) NOT NULL AUTO_INCREMENT, task_id int(11) NOT NULL, @@ -55,16 +55,14 @@ CREATE TABLE queue_notify ( subscriber_id int(11) NOT NULL, retries tinyint(1) DEFAULT NULL, PRIMARY KEY (id) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; - +) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci; CREATE TABLE services_groups ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, description varchar(50) DEFAULT NULL, visibility tinyint(4) NOT NULL, PRIMARY KEY (id) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - +) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci; CREATE TABLE queue_task ( id int(11) NOT NULL AUTO_INCREMENT, type_id int(11) NOT NULL, @@ -76,67 +74,79 @@ CREATE TABLE queue_task ( num_errors int(11) DEFAULT NULL, user_id int(11) NOT NULL, PRIMARY KEY (id) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci; +) ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_czech_ci; ALTER TABLE `services` - ADD PRIMARY KEY (`id`); +ADD PRIMARY KEY (`id`); ALTER TABLE `services_status` - ADD PRIMARY KEY (`id`), +ADD PRIMARY KEY (`id`), ADD KEY `service_id` (`service_id`), ADD KEY `status_id` (`status_id`); ALTER TABLE `status` - ADD PRIMARY KEY (`id`), +ADD PRIMARY KEY (`id`), ADD KEY `user_id` (`user_id`); ALTER TABLE `tokens` - ADD PRIMARY KEY (`token`), +ADD PRIMARY KEY (`token`), ADD KEY `user` (`user`); ALTER TABLE `users` - ADD PRIMARY KEY (`id`), +ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `email` (`email`), ADD UNIQUE KEY `username` (`username`); ALTER TABLE `services` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; +MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `services_status` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; +MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `status` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; +MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `users` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; +MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `services_subscriber` - ADD PRIMARY KEY (`comboID`), - ADD UNIQUE KEY `unique_subscription` (`subscriberIDFK`,`serviceIDFK`), +ADD PRIMARY KEY (`comboID`), + ADD UNIQUE KEY `unique_subscription` (`subscriberIDFK`, `serviceIDFK`), ADD KEY `serviceIDFK` (`serviceIDFK`); ALTER TABLE `subscribers` - ADD PRIMARY KEY (`subscriberID`), +ADD PRIMARY KEY (`subscriberID`), ADD UNIQUE KEY `telegramID` (`telegramID`); ALTER TABLE `services_subscriber` - MODIFY `comboID` int(11) NOT NULL AUTO_INCREMENT; +MODIFY `comboID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `subscribers` - MODIFY `subscriberID` int(11) NOT NULL AUTO_INCREMENT; +MODIFY `subscriberID` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `services_status` - ADD CONSTRAINT `service_id` FOREIGN KEY (`service_id`) REFERENCES `services` (`id`), +ADD CONSTRAINT `service_id` FOREIGN KEY (`service_id`) REFERENCES `services` (`id`), ADD CONSTRAINT `status_id` FOREIGN KEY (`status_id`) REFERENCES `status` (`id`); ALTER TABLE `status` - ADD CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); +ADD CONSTRAINT `user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); ALTER TABLE `tokens` - ADD CONSTRAINT `user` FOREIGN KEY (`user`) REFERENCES `users` (`id`); +ADD CONSTRAINT `user` FOREIGN KEY (`user`) REFERENCES `users` (`id`); ALTER TABLE `services_subscriber` - ADD CONSTRAINT `services_subscriber_ibfk_1` FOREIGN KEY (`subscriberIDFK`) REFERENCES `subscribers` (`subscriberID`) ON DELETE CASCADE ON UPDATE CASCADE, +ADD CONSTRAINT `services_subscriber_ibfk_1` FOREIGN KEY (`subscriberIDFK`) REFERENCES `subscribers` (`subscriberID`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `services_subscriber_ibfk_2` FOREIGN KEY (`serviceIDFK`) REFERENCES `services` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; COMMIT; - -ALTER TABLE `subscribers` CHANGE COLUMN lastname lastname varchar(255) DEFAULT NULL; # was varchar(255) NOT NULL -ALTER TABLE `subscribers` CHANGE COLUMN firstname firstname varchar(255) DEFAULT NULL; # was varchar(255) NOT NULL +ALTER TABLE `subscribers` CHANGE COLUMN lastname lastname varchar(255) DEFAULT NULL; +# was varchar(255) NOT NULL +ALTER TABLE `subscribers` CHANGE COLUMN firstname firstname varchar(255) DEFAULT NULL; +# was varchar(255) NOT NULL ALTER TABLE `subscribers` CHANGE COLUMN telegramID userID varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL; -ALTER TABLE `subscribers` ADD COLUMN typeID tinyint(1) NOT NULL AFTER subscriberID; -ALTER TABLE `subscribers` ADD COLUMN token varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL AFTER lastname; -ALTER TABLE `subscribers` ADD COLUMN expires int(11) DEFAULT NULL; -ALTER TABLE `subscribers` ADD COLUMN active tinyint(1) DEFAULT NULL; -ALTER TABLE `subscribers` ADD COLUMN create_time int(11) DEFAULT NULL; -ALTER TABLE `subscribers` ADD COLUMN update_time int(11) DEFAULT NULL; -ALTER TABLE `subscribers` DROP INDEX telegramID; # was UNIQUE (telegramID) -ALTER TABLE `subscribers` ADD UNIQUE userID (userID); -COMMIT; - -ALTER TABLE services ADD COLUMN description varchar(200) COLLATE utf8_czech_ci NOT NULL; -ALTER TABLE services ADD COLUMN group_id int(11) DEFAULT NULL; +ALTER TABLE `subscribers` +ADD COLUMN typeID tinyint(1) NOT NULL +AFTER subscriberID; +ALTER TABLE `subscribers` +ADD COLUMN token varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL +AFTER lastname; +ALTER TABLE `subscribers` +ADD COLUMN expires int(11) DEFAULT NULL; +ALTER TABLE `subscribers` +ADD COLUMN active tinyint(1) DEFAULT NULL; +ALTER TABLE `subscribers` +ADD COLUMN create_time int(11) DEFAULT NULL; +ALTER TABLE `subscribers` +ADD COLUMN update_time int(11) DEFAULT NULL; +ALTER TABLE `subscribers` DROP INDEX telegramID; +# was UNIQUE (telegramID) +ALTER TABLE `subscribers` +ADD UNIQUE userID (userID); COMMIT; +ALTER TABLE services +ADD COLUMN description varchar(200) COLLATE utf8_czech_ci NOT NULL; +ALTER TABLE services +ADD COLUMN group_id int(11) DEFAULT NULL; +COMMIT; \ No newline at end of file diff --git a/js/admin.js b/js/admin.js index f07ef1a..78e5416 100644 --- a/js/admin.js +++ b/js/admin.js @@ -1,63 +1,65 @@ -(function(){ - $("#time_input").flatpickr({enableTime:true, minDate: "today",time_24hr:true, onChange: function(date, dateStr, instance) { - $("#time_input_js").val(date[0].toISOString()); - }}); - $("#end_time").flatpickr({enableTime:true, minDate: "today",time_24hr:true, onChange: function(date, dateStr, instance) { - $("#end_time_js").val(date[0].toISOString()); // iso date str - }}); +(function () { + $("#time_input").flatpickr({ + enableTime: true, + minDate: "today", + time_24hr: true, + onChange: function (date, dateStr, instance) { + $("#time_input_js").val(date[0].toISOString()); + }, + }); + $("#end_time").flatpickr({ + enableTime: true, + minDate: "today", + time_24hr: true, + onChange: function (date, dateStr, instance) { + $("#end_time_js").val(date[0].toISOString()); // iso date str + }, + }); + var bgcolore = ["bg-danger", "bg-warning", "bg-primary", "bg-success"]; + var bordercolore = ["border-danger", "border-warning", "border-primary", "border-success"]; + var icons = ["fa fa-times", "fa fa-exclamation", "fa fa-info", "fa fa-check"]; - var bgcolore = ["bg-danger", "bg-warning", "bg-primary", "bg-success"]; - var bordercolore = ["border-danger", "border-warning", "border-primary", "border-success"]; - var icons = ["fa fa-times", "fa fa-exclamation", "fa fa-info", "fa fa-check"]; + $("body").on("change", "#new-incident select", function () { + var val = parseInt($(this).val()); //this should make exploitation harder - $("body").on("change","#new-incident select", function(){ - var val = parseInt($(this).val()); //this should make exploitation harder + $("#new-incident .card.new .card-colore i").get(0).className = icons[val]; + $("#new-incident .card.new .icon").get(0).className = "card-colore icon " + bgcolore[val]; + $("#new-incident .card.new").get(0).className = "card " + bordercolore[val] + " new"; + $("#new-incident .card.new .card-header").get(0).className = "card-colore card-header " + bgcolore[val] + " " + bordercolore[val]; + $("#time_input").val(""); + $("#end_time").val(""); + }); - $("#new-incident .card.new .card-colore i").get(0).className = icons[val]; - $("#new-incident .card.new .icon").get(0).className = "card-colore icon " + bgcolore[val]; - $("#new-incident .card.new").get(0).className = "card " + bordercolore[val] + " new"; - $("#new-incident .card.new .card-header").get(0).className = "card-colore card-header " + bgcolore[val] + " " + bordercolore[val] ; - $("#time_input").val(""); - $("#end_time").val(""); - }); + $("#new-incident select").trigger("change"); - $("#new-incident select").trigger("change"); + $("body").on("submit", "#new-incident", function () { + var time = Date.parse($("#time_input").val()); + var end_time = Date.parse($("#end_time").val()); + var type = $("#type").val() || 0; - $("body").on("submit","#new-incident",function(){ - var time = Date.parse($("#time_input").val()); - var end_time = Date.parse($("#end_time").val()); - var type = $("#type").val() || 0; + if (parseInt(type) === 2 && (isNaN(time) || isNaN(end_time))) { + if (isNaN(end_time)) { + $("#time_input").addClass("error"); + $.growl.error({ message: "Start time is invalid!" }); + } - if (parseInt(type) === 2 &&(isNaN(time) || isNaN(end_time))) - { - if (isNaN(end_time)) - { - $("#time_input").addClass("error"); - $.growl.error({ message: "Start time is invalid!" }); - } - - if (isNaN(end_time)) - { - $("#end_time").addClass("error"); - $.growl.error({ message: "End time is invalid!" }); - } - return false; - } - else if (parseInt(type) === 2 && time >= end_time) - { - $.growl.error({ message: "End time is either the same or earlier than start time!" }); - $("#time").addClass("error"); - $("#end_time").addClass("error"); - return false; - } + if (isNaN(end_time)) { + $("#end_time").addClass("error"); + $.growl.error({ message: "End time is invalid!" }); + } + return false; + } else if (parseInt(type) === 2 && time >= end_time) { + $.growl.error({ message: "End time is either the same or earlier than start time!" }); + $("#time").addClass("error"); + $("#end_time").addClass("error"); + return false; + } - if($("#status-container :checkbox:checked").length === 0) - { - $.growl.error({ message: "Please check at least one service!" }); - $("#status-container").addClass("error"); - return false; - } - }); + if ($("#status-container :checkbox:checked").length === 0) { + $.growl.error({ message: "Please check at least one service!" }); + $("#status-container").addClass("error"); + return false; + } + }); })(); - diff --git a/js/main.js b/js/main.js index 063b261..68f4a70 100644 --- a/js/main.js +++ b/js/main.js @@ -1,32 +1,29 @@ -function timeago() -{ - $("time.timeago").timeago(); - $("time.timeago").each(function(){ - var date = new Date($(this).attr("datetime")); - $(this).attr("title",date.toLocaleString()); - }); +function timeago() { + $("time.timeago").timeago(); + $("time.timeago").each(function () { + var date = new Date($(this).attr("datetime")); + $(this).attr("title", date.toLocaleString()); + }); } -(function(){ - jQuery.timeago.settings.allowFuture = true; +(function () { + jQuery.timeago.settings.allowFuture = true; - timeago(); - - $("body").on("click", ".navbar-toggle", function(){ - $($(this).data("target")).toggleClass("collapse"); - }); - - var incidents = $('.timeline'); - $("body").on("click", "#loadmore", function(e){ - e.preventDefault(); - var url = $("#loadmore").attr("href") + "&ajax=true"; - $("#loadmore").remove(); - - $.get(url, - function(data){ - incidents.append(data); - timeago(); - }); - }); - })(); - + timeago(); + + $("body").on("click", ".navbar-toggle", function () { + $($(this).data("target")).toggleClass("collapse"); + }); + + var incidents = $(".timeline"); + $("body").on("click", "#loadmore", function (e) { + e.preventDefault(); + var url = $("#loadmore").attr("href") + "&ajax=true"; + $("#loadmore").remove(); + + $.get(url, function (data) { + incidents.append(data); + timeago(); + }); + }); +})(); diff --git a/policy.php b/policy.php index 9379583..43dfd01 100644 --- a/policy.php +++ b/policy.php @@ -1,48 +1,48 @@ " . _("Privacy Policy") . ""; - echo "

" . _("Who we are") . "

"; - echo WHO_WE_ARE; - echo "

" . _("Contact") . "

"; - echo POLICY_NAME . "
"; - echo ADDRESS . "
"; - echo POLICY_MAIL . "
"; - if(defined('POLICY_PHONE') && POLICY_PHONE != ""){ - echo POLICY_PHONE . "
"; - } +echo "

" . _("Privacy Policy") . "

"; +echo "

" . _("Who we are") . "

"; +echo WHO_WE_ARE; +echo "

" . _("Contact") . "

"; +echo POLICY_NAME . "
"; +echo ADDRESS . "
"; +echo POLICY_MAIL . "
"; +if (defined('POLICY_PHONE') && POLICY_PHONE != "") { + echo POLICY_PHONE . "
"; +} - echo '

' . _("What personal data we collect and why") . '

'; - echo '

' . _("General") . "

"; - echo _("If you access our websites, the following information will be saved: IP-address, Date, Time, Browser queries, +echo '

' . _("What personal data we collect and why") . '

'; +echo '

' . _("General") . "

"; +echo _("If you access our websites, the following information will be saved: IP-address, Date, Time, Browser queries, General information about your browser, operating system and all search queries on the sites. This user data will be used for anonym user statistics to recognize trends and improve our content. ") . "
"; - echo '

' . _("Telegram") . "

"; - echo _("If you use the Telegram Login Widget (The blue \"Login with Telegram\" button), we recive the following data from the service \"Telegram\" (telegram.org):"); - echo '
    +echo '

    ' . _("Telegram") . "

    "; +echo _("If you use the Telegram Login Widget (The blue \"Login with Telegram\" button), we recive the following data from the service \"Telegram\" (telegram.org):"); +echo '
    • ' . _("Your Telegram-User-ID") . "
    • " . _("Your Telegram username") . '
    • ' . _("The name you provided when registering with Telegram.") . '
    • ' . _("Your telegram profile picture") . '
    '; - echo _("Although we are receiving this data, we only save your telegram ID, your telegram username and the first and last name you provided telegram when registred for their service."); - echo _("We are saving this data, to provide a subscription service which alerts you about status update via our telegram bot. With this data we know who we need to send the alert to. Also we know your name, so we can say hi to you."); - echo _("Because of this, we also save who has subscribed which service."); - echo "

    " . _("How we protect your data") . "

    "; - echo _("In collaboration with our hosting provider we try our best to protect our +echo _("Although we are receiving this data, we only save your telegram ID, your telegram username and the first and last name you provided telegram when registred for their service."); +echo _("We are saving this data, to provide a subscription service which alerts you about status update via our telegram bot. With this data we know who we need to send the alert to. Also we know your name, so we can say hi to you."); +echo _("Because of this, we also save who has subscribed which service."); +echo "

    " . _("How we protect your data") . "

    "; +echo _("In collaboration with our hosting provider we try our best to protect our databases against access from third parties, losses, misuse or forgery. ") . "

    "; - echo "

    " . _("Third party that receive your personal data") . "

    "; - echo "Our hosting provider can access the date we store on their server. We have a data processing agreement with them."; - echo "

    " . _("Cookies") . "

    "; - echo _("This site uses cookies – small text files that are placed on your machine to help the site provide a better user experience. +echo "

    " . _("Third party that receive your personal data") . "

    "; +echo "Our hosting provider can access the date we store on their server. We have a data processing agreement with them."; +echo "

    " . _("Cookies") . "

    "; +echo _("This site uses cookies – small text files that are placed on your machine to help the site provide a better user experience. In general, cookies are used to retain user preferences, store information for things like shopping carts, and provide anonymised tracking data to third party applications like Google Analytics. As a rule, cookies will make your browsing experience better. However, you may prefer to disable cookies on this site and on others. The most effective way to do this is to disable cookies in your browser. We suggest consulting the Help section of your browser or taking a look at the About Cookies website which offers guidance for all modern browsers"); - Template::render_footer(); +Template::render_footer(); diff --git a/subscriptions.php b/subscriptions.php index ad9435b..fea6dbf 100644 --- a/subscriptions.php +++ b/subscriptions.php @@ -6,11 +6,11 @@ require_once("classes/subscriptions.php"); require_once("classes/telegram.php"); require_once("classes/db-class.php"); $db = new SSDB(); -define("NAME", $db->getSetting($mysqli,"name")); -define("TITLE", $db->getSetting($mysqli,"title")); -define("WEB_URL", $db->getSetting($mysqli,"url")); -define("MAILER_NAME", $db->getSetting($mysqli,"mailer")); -define("MAILER_ADDRESS", $db->getSetting($mysqli,"mailer_email")); +define("NAME", $db->getSetting($mysqli, "name")); +define("TITLE", $db->getSetting($mysqli, "title")); +define("WEB_URL", $db->getSetting($mysqli, "url")); +define("MAILER_NAME", $db->getSetting($mysqli, "mailer")); +define("MAILER_ADDRESS", $db->getSetting($mysqli, "mailer_email")); define("SUBSCRIBE_EMAIL", $db->getBooleanSetting($mysqli, "subscribe_email")); define("SUBSCRIBE_TELEGRAM", $db->getBooleanSetting($mysqli, "subscribe_telegram")); define("GOOGLE_RECAPTCHA", $db->getSetting($mysqli, "google_recaptcha")); @@ -24,34 +24,33 @@ $telegram = new Telegram(); Template::render_header("Subscriptions"); -if ( SUBSCRIBE_TELEGRAM && $_SESSION['subscriber_typeid'] == 2 ) { +if (SUBSCRIBE_TELEGRAM && $_SESSION['subscriber_typeid'] == 2) { $tg_user = $telegram->getTelegramUserData(); // TODO: Do we need this any longer? } -if( $_SESSION['subscriber_valid'] ){ +if ($_SESSION['subscriber_valid']) { $typeID = $_SESSION['subscriber_typeid']; $subscriberID = $_SESSION['subscriber_id']; $userID = $_SESSION['subscriber_userid']; $token = $_SESSION['subscriber_token']; - if(isset($_GET['add'])){ + if (isset($_GET['add'])) { $subscription->add($subscriberID, $_GET['add']); } - if(isset($_GET['remove'])){ + if (isset($_GET['remove'])) { $subscription->remove($subscriberID, $_GET['remove']); } $subscription->render_subscribed_services($typeID, $subscriberID, $userID, $token); - } else { $header = _("Your session has expired or you tried something we don't suppprt"); $message = _('If your session expired, retry your link or in case of Telegram use the login button in the top menu.'); $constellation->render_warning($header, $message); - header('Location: index.php'); + header('Location: index.php'); } Template::render_footer(); diff --git a/telegram_check.php b/telegram_check.php index 595670f..0602a70 100644 --- a/telegram_check.php +++ b/telegram_check.php @@ -1,15 +1,14 @@ getSetting($mysqli,"name")); -define("TITLE", $db->getSetting($mysqli,"title")); -define("WEB_URL", $db->getSetting($mysqli,"url")); -define("MAILER_NAME", $db->getSetting($mysqli,"mailer")); -define("MAILER_ADDRESS", $db->getSetting($mysqli,"mailer_email")); -define("SUBSCRIBE_TELEGRAM", $db->getBooleanSetting($mysqli, "subscribe_telegram")); +define("NAME", $db->getSetting($mysqli, "name")); +define("TITLE", $db->getSetting($mysqli, "title")); +define("WEB_URL", $db->getSetting($mysqli, "url")); +define("MAILER_NAME", $db->getSetting($mysqli, "mailer")); +define("MAILER_ADDRESS", $db->getSetting($mysqli, "mailer_email")); define("SUBSCRIBE_TELEGRAM", $db->getBooleanSetting($mysqli, "subscribe_telegram")); define("TG_BOT_API_TOKEN", $db->getSetting($mysqli, "tg_bot_api_token")); define("TG_BOT_USERNAME", $db->getSetting($mysqli, "tg_bot_username")); diff --git a/template.php b/template.php index 715c100..09706cf 100644 --- a/template.php +++ b/template.php @@ -1,224 +1,241 @@ '; - // If subscriber is not logged on, display subscriber menus - if ( (!isset($_SESSION['subscriber_valid'])) || false == $_SESSION['subscriber_valid'] ) { - $strSubsMenu .= '
  •  ' . _('Subscribe via email') . '
  • '; + } + if ($SUBSCRIBE_TELEGRAM) { + $strSubsMenu .= '
  • '; + } + $strSubsMenu .= '
'; + } + } + // If subscriber is logged on, display unsub and logoff menu points + if ((isset($_SESSION['subscriber_valid'])) && $_SESSION['subscriber_valid']) { + $strSubsMenu .= '
  • ' . _('Subscriptions') . '
  • '; + $strSubsMenu .= '
  • ' . _('Logout') . '
  • '; + } + $strSubsMenu .= ''; + } + } +?> + + + + + + <?php echo $page_name . " - " . NAME ?> + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - <?php echo $page_name." - ".NAME ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
    + -
    + if (!$admin) { + ?> +
    + - + /** + * Renders a toggle switch + * Created by Yigit Kerem Oktay + * @param String $toggletext will decide what the description text next to the toggle will be + * @param String $input_name will decide what the HTML Name attribute of the toggle will be + * @param Boolean $checked will decide if the toggle will initially be on or off + */ + public static function render_toggle($toggletext, $input_name, $checked) + { + ?>
    -

    -
    - get_accepted_langs(); - ?> -
    -
    -
    -
    -
    Copyright © Server Status Project Contributors 1){ echo " and ".COPYRIGHT_TEXT; } ?>
    -
    -
    - - - + get_accepted_langs(); + ?> +
    +
    +
    +
    +
    Copyright © Server Status Project Contributors 1) { + echo " and " . COPYRIGHT_TEXT; + } ?>
    +
    +
    + + + +
    +
    +
    +
    +
    +
    -
    -
    -
    -
    - - - - - - - - - - - - - + + + + + + + + + + + + + +