Skip to content

Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.

feat: enforce CSRF protection and POST-only policy across endpoints (#940)

Miguel Ribeiro3247ce2c8768
diff --git a/api/subscriptions/get_subscriptions.php b/api/subscriptions/get_subscriptions.php
index d9d61a4..0f9cb66 100644
--- a/api/subscriptions/get_subscriptions.php
+++ b/api/subscriptions/get_subscriptions.php
@@ -352,8 +352,4 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET
];
echo json_encode($response);
exit;
-}
-
-
-?>
-
+}
\ No newline at end of file
diff --git a/endpoints/admin/adduser.php b/endpoints/admin/adduser.php
index 7625405..4190edd 100644
--- a/endpoints/admin/adduser.php
+++ b/endpoints/admin/adduser.php
@@ -1,20 +1,6 @@
<?php
require_once '../../includes/connect_endpoint.php';
-
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-// Check that user is an admin
-if ($userId !== 1) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
-}
+require_once '../../includes/validate_endpoint_admin.php';
$currencies = [
['id' => 1, 'name' => 'Euro', 'symbol' => '€', 'code' => 'EUR'],
@@ -116,155 +102,142 @@ function validate($value)
return $value;
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
-
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
- $loggedInUserId = $userId;
+$loggedInUserId = $userId;
- $email = validate($data['email']);
- $username = validate($data['username']);
- $password = $data['password'];
+$email = validate($data['email']);
+$username = validate($data['username']);
+$password = $data['password'];
- if (empty($username) || empty($password) || empty($email)) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
- }
-
- $stmt = $db->prepare('SELECT COUNT(*) FROM user WHERE username = :username OR email = :email');
- $stmt->bindValue(':username', $username, SQLITE3_INTEGER);
- $stmt->bindValue(':email', $email, SQLITE3_TEXT);
- $result = $stmt->execute();
- $row = $result->fetchArray();
- // Error if user exist
- if ($row[0] > 0) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
- }
-
- // Get main currency and language from admin user
- $stmt = $db->prepare('SELECT main_currency, language FROM user WHERE id = :id');
- $stmt->bindValue(':id', $loggedInUserId, SQLITE3_TEXT);
- $result = $stmt->execute();
- $row = $result->fetchArray();
- $currency = $row['main_currency'] ?? 1;
- $language = $row['language'] ?? 'en';
- $avatar = "images/avatars/0.svg";
+if (empty($username) || empty($password) || empty($email)) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ]));
+}
- // Get code for main currency
- $stmt = $db->prepare('SELECT code FROM currencies WHERE id = :id');
- $stmt->bindValue(':id', $currency, SQLITE3_TEXT);
- $row = $stmt->execute();
- $main_currency = $row->fetchArray()['code'];
+$stmt = $db->prepare('SELECT COUNT(*) FROM user WHERE username = :username OR email = :email');
+$stmt->bindValue(':username', $username, SQLITE3_INTEGER);
+$stmt->bindValue(':email', $email, SQLITE3_TEXT);
+$result = $stmt->execute();
+$row = $result->fetchArray();
+// Error if user exist
+if ($row[0] > 0) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ]));
+}
- $query = "INSERT INTO user (username, email, password, main_currency, avatar, language, budget) VALUES (:username, :email, :password, :main_currency, :avatar, :language, :budget)";
+// Get main currency and language from admin user
+$stmt = $db->prepare('SELECT main_currency, language FROM user WHERE id = :id');
+$stmt->bindValue(':id', $loggedInUserId, SQLITE3_TEXT);
+$result = $stmt->execute();
+$row = $result->fetchArray();
+$currency = $row['main_currency'] ?? 1;
+$language = $row['language'] ?? 'en';
+$avatar = "images/avatars/0.svg";
+
+// Get code for main currency
+$stmt = $db->prepare('SELECT code FROM currencies WHERE id = :id');
+$stmt->bindValue(':id', $currency, SQLITE3_TEXT);
+$row = $stmt->execute();
+$main_currency = $row->fetchArray()['code'];
+
+$query = "INSERT INTO user (username, email, password, main_currency, avatar, language, budget) VALUES (:username, :email, :password, :main_currency, :avatar, :language, :budget)";
+$stmt = $db->prepare($query);
+$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
+$stmt->bindValue(':username', $username, SQLITE3_TEXT);
+$stmt->bindValue(':email', $email, SQLITE3_TEXT);
+$stmt->bindValue(':password', $hashedPassword, SQLITE3_TEXT);
+$stmt->bindValue(':main_currency', 1, SQLITE3_TEXT);
+$stmt->bindValue(':avatar', $avatar, SQLITE3_TEXT);
+$stmt->bindValue(':language', $language, SQLITE3_TEXT);
+$stmt->bindValue(':budget', 0, SQLITE3_INTEGER);
+$result = $stmt->execute();
+
+if ($result) {
+
+ // Get id of the newly created user
+ $newUserId = $db->lastInsertRowID();
+
+ // Add username as household member for that user
+ $query = "INSERT INTO household (name, user_id) VALUES (:name, :user_id)";
$stmt = $db->prepare($query);
- $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
- $stmt->bindValue(':username', $username, SQLITE3_TEXT);
- $stmt->bindValue(':email', $email, SQLITE3_TEXT);
- $stmt->bindValue(':password', $hashedPassword, SQLITE3_TEXT);
- $stmt->bindValue(':main_currency', 1, SQLITE3_TEXT);
- $stmt->bindValue(':avatar', $avatar, SQLITE3_TEXT);
- $stmt->bindValue(':language', $language, SQLITE3_TEXT);
- $stmt->bindValue(':budget', 0, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':name', $username, SQLITE3_TEXT);
+ $stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
+ $stmt->execute();
- if ($result) {
+ if ($newUserId > 1) {
- // Get id of the newly created user
- $newUserId = $db->lastInsertRowID();
-
- // Add username as household member for that user
- $query = "INSERT INTO household (name, user_id) VALUES (:name, :user_id)";
+ // Add categories for that user
+ $query = 'INSERT INTO categories (name, "order", user_id) VALUES (:name, :order, :user_id)';
$stmt = $db->prepare($query);
- $stmt->bindValue(':name', $username, SQLITE3_TEXT);
- $stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
- $stmt->execute();
-
- if ($newUserId > 1) {
-
- // Add categories for that user
- $query = 'INSERT INTO categories (name, "order", user_id) VALUES (:name, :order, :user_id)';
- $stmt = $db->prepare($query);
- foreach ($categories as $index => $category) {
- $stmt->bindValue(':name', $category['name'], SQLITE3_TEXT);
- $stmt->bindValue(':order', $index + 1, SQLITE3_INTEGER);
- $stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
- $stmt->execute();
- }
-
- // Add payment methods for that user
- $query = 'INSERT INTO payment_methods (name, icon, "order", user_id) VALUES (:name, :icon, :order, :user_id)';
- $stmt = $db->prepare($query);
- foreach ($payment_methods as $index => $payment_method) {
- $stmt->bindValue(':name', $payment_method['name'], SQLITE3_TEXT);
- $stmt->bindValue(':icon', $payment_method['icon'], SQLITE3_TEXT);
- $stmt->bindValue(':order', $index + 1, SQLITE3_INTEGER);
- $stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
- $stmt->execute();
- }
-
- // Add currencies for that user
- $query = "INSERT INTO currencies (name, symbol, code, rate, user_id) VALUES (:name, :symbol, :code, :rate, :user_id)";
- $stmt = $db->prepare($query);
- foreach ($currencies as $currency) {
- $stmt->bindValue(':name', $currency['name'], SQLITE3_TEXT);
- $stmt->bindValue(':symbol', $currency['symbol'], SQLITE3_TEXT);
- $stmt->bindValue(':code', $currency['code'], SQLITE3_TEXT);
- $stmt->bindValue(':rate', 1, SQLITE3_FLOAT);
- $stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
- $stmt->execute();
- }
-
- // Retrieve main currency id
- $query = "SELECT id FROM currencies WHERE code = :code AND user_id = :user_id";
- $stmt = $db->prepare($query);
- $stmt->bindValue(':code', $main_currency, SQLITE3_TEXT);
+ foreach ($categories as $index => $category) {
+ $stmt->bindValue(':name', $category['name'], SQLITE3_TEXT);
+ $stmt->bindValue(':order', $index + 1, SQLITE3_INTEGER);
$stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $currency = $result->fetchArray(SQLITE3_ASSOC);
+ $stmt->execute();
+ }
- // Update user main currency
- $query = "UPDATE user SET main_currency = :main_currency WHERE id = :user_id";
- $stmt = $db->prepare($query);
- $stmt->bindValue(':main_currency', $currency['id'], SQLITE3_INTEGER);
+ // Add payment methods for that user
+ $query = 'INSERT INTO payment_methods (name, icon, "order", user_id) VALUES (:name, :icon, :order, :user_id)';
+ $stmt = $db->prepare($query);
+ foreach ($payment_methods as $index => $payment_method) {
+ $stmt->bindValue(':name', $payment_method['name'], SQLITE3_TEXT);
+ $stmt->bindValue(':icon', $payment_method['icon'], SQLITE3_TEXT);
+ $stmt->bindValue(':order', $index + 1, SQLITE3_INTEGER);
$stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
$stmt->execute();
+ }
- // Add settings for that user
- $query = "INSERT INTO settings (dark_theme, monthly_price, convert_currency, remove_background, color_theme, hide_disabled, user_id, disabled_to_bottom, show_original_price, mobile_nav)
- VALUES (2, 0, 0, 0, 'blue', 0, :user_id, 0, 0, 0)";
- $stmt = $db->prepare($query);
+ // Add currencies for that user
+ $query = "INSERT INTO currencies (name, symbol, code, rate, user_id) VALUES (:name, :symbol, :code, :rate, :user_id)";
+ $stmt = $db->prepare($query);
+ foreach ($currencies as $currency) {
+ $stmt->bindValue(':name', $currency['name'], SQLITE3_TEXT);
+ $stmt->bindValue(':symbol', $currency['symbol'], SQLITE3_TEXT);
+ $stmt->bindValue(':code', $currency['code'], SQLITE3_TEXT);
+ $stmt->bindValue(':rate', 1, SQLITE3_FLOAT);
$stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
$stmt->execute();
-
- // If email verification is required add the user to the email_verification table
- $query = "SELECT * FROM admin";
- $stmt = $db->prepare($query);
- $result = $stmt->execute();
- $settings = $result->fetchArray(SQLITE3_ASSOC);
}
- $db->close();
+ // Retrieve main currency id
+ $query = "SELECT id FROM currencies WHERE code = :code AND user_id = :user_id";
+ $stmt = $db->prepare($query);
+ $stmt->bindValue(':code', $main_currency, SQLITE3_TEXT);
+ $stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $currency = $result->fetchArray(SQLITE3_ASSOC);
- die(json_encode([
- "success" => true,
- "message" => translate('success', $i18n)
- ]));
- }
+ // Update user main currency
+ $query = "UPDATE user SET main_currency = :main_currency WHERE id = :user_id";
+ $stmt = $db->prepare($query);
+ $stmt->bindValue(':main_currency', $currency['id'], SQLITE3_INTEGER);
+ $stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
+ $stmt->execute();
+
+ // Add settings for that user
+ $query = "INSERT INTO settings (dark_theme, monthly_price, convert_currency, remove_background, color_theme, hide_disabled, user_id, disabled_to_bottom, show_original_price, mobile_nav)
+ VALUES (2, 0, 0, 0, 'blue', 0, :user_id, 0, 0, 0)";
+ $stmt = $db->prepare($query);
+ $stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
+ $stmt->execute();
+ // If email verification is required add the user to the email_verification table
+ $query = "SELECT * FROM admin";
+ $stmt = $db->prepare($query);
+ $result = $stmt->execute();
+ $settings = $result->fetchArray(SQLITE3_ASSOC);
+ }
+ $db->close();
-} else {
die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
+ "success" => true,
+ "message" => translate('success', $i18n)
]));
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/admin/deleteunusedlogos.php b/endpoints/admin/deleteunusedlogos.php
index 2fba6eb..3a75709 100644
--- a/endpoints/admin/deleteunusedlogos.php
+++ b/endpoints/admin/deleteunusedlogos.php
@@ -1,21 +1,7 @@
<?php
require_once '../../includes/connect_endpoint.php';
-
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-// Check that user is an admin
-if ($userId !== 1) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
-}
+require_once '../../includes/validate_endpoint_admin.php';
$query = 'SELECT logo FROM subscriptions';
$stmt = $db->prepare($query);
diff --git a/endpoints/admin/deleteuser.php b/endpoints/admin/deleteuser.php
index b137f50..26641ca 100644
--- a/endpoints/admin/deleteuser.php
+++ b/endpoints/admin/deleteuser.php
@@ -1,142 +1,117 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint_admin.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$userId = $data['userId'];
-// Check that user is an admin
-if ($userId !== 1) {
+if ($userId == 1) {
die(json_encode([
"success" => false,
"message" => translate('error', $i18n)
]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
-
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $userId = $data['userId'];
-
- if ($userId == 1) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
- } else {
- // Delete user
- $stmt = $db->prepare('DELETE FROM user WHERE id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete subscriptions
- $stmt = $db->prepare('DELETE FROM subscriptions WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete settings
- $stmt = $db->prepare('DELETE FROM settings WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete fixer
- $stmt = $db->prepare('DELETE FROM fixer WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete custom colors
- $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete currencies
- $stmt = $db->prepare('DELETE FROM currencies WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete categories
- $stmt = $db->prepare('DELETE FROM categories WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete household
- $stmt = $db->prepare('DELETE FROM household WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete payment methods
- $stmt = $db->prepare('DELETE FROM payment_methods WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete email notifications
- $stmt = $db->prepare('DELETE FROM email_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete telegram notifications
- $stmt = $db->prepare('DELETE FROM telegram_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete webhook notifications
- $stmt = $db->prepare('DELETE FROM webhook_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete gotify notifications
- $stmt = $db->prepare('DELETE FROM gotify_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete pushover notifications
- $stmt = $db->prepare('DELETE FROM pushover_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Dele notification settings
- $stmt = $db->prepare('DELETE FROM notification_settings WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete last exchange update
- $stmt = $db->prepare('DELETE FROM last_exchange_update WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete email verification
- $stmt = $db->prepare('DELETE FROM email_verification WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete totp
- $stmt = $db->prepare('DELETE FROM totp WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete total yearly cost
- $stmt = $db->prepare('DELETE FROM total_yearly_cost WHERE user_id = :id');
- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- die(json_encode([
- "success" => true,
- "message" => translate('success', $i18n)
- ]));
-
- }
-
} else {
+ // Delete user
+ $stmt = $db->prepare('DELETE FROM user WHERE id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete subscriptions
+ $stmt = $db->prepare('DELETE FROM subscriptions WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete settings
+ $stmt = $db->prepare('DELETE FROM settings WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete fixer
+ $stmt = $db->prepare('DELETE FROM fixer WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete custom colors
+ $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete currencies
+ $stmt = $db->prepare('DELETE FROM currencies WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete categories
+ $stmt = $db->prepare('DELETE FROM categories WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete household
+ $stmt = $db->prepare('DELETE FROM household WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete payment methods
+ $stmt = $db->prepare('DELETE FROM payment_methods WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete email notifications
+ $stmt = $db->prepare('DELETE FROM email_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete telegram notifications
+ $stmt = $db->prepare('DELETE FROM telegram_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete webhook notifications
+ $stmt = $db->prepare('DELETE FROM webhook_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete gotify notifications
+ $stmt = $db->prepare('DELETE FROM gotify_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete pushover notifications
+ $stmt = $db->prepare('DELETE FROM pushover_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Dele notification settings
+ $stmt = $db->prepare('DELETE FROM notification_settings WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete last exchange update
+ $stmt = $db->prepare('DELETE FROM last_exchange_update WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete email verification
+ $stmt = $db->prepare('DELETE FROM email_verification WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete totp
+ $stmt = $db->prepare('DELETE FROM totp WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete total yearly cost
+ $stmt = $db->prepare('DELETE FROM total_yearly_cost WHERE user_id = :id');
+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
+ "success" => true,
+ "message" => translate('success', $i18n)
]));
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/admin/enableoidc.php b/endpoints/admin/enableoidc.php
index 327249d..79b4a33 100644
--- a/endpoints/admin/enableoidc.php
+++ b/endpoints/admin/enableoidc.php
@@ -1,45 +1,22 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint_admin.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
-// Check that user is an admin
-if ($userId !== 1) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
-}
+$oidcEnabled = isset($data['oidcEnabled']) ? $data['oidcEnabled'] : 0;
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
-
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $oidcEnabled = isset($data['oidcEnabled']) ? $data['oidcEnabled'] : 0;
-
- $stmt = $db->prepare('UPDATE admin SET oidc_oauth_enabled = :oidcEnabled WHERE id = 1');
- $stmt->bindParam(':oidcEnabled', $oidcEnabled, SQLITE3_INTEGER);
- $stmt->execute();
-
- if ($db->changes() > 0) {
- die(json_encode([
- "success" => true,
- "message" => translate('success', $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
- }
+$stmt = $db->prepare('UPDATE admin SET oidc_oauth_enabled = :oidcEnabled WHERE id = 1');
+$stmt->bindParam(':oidcEnabled', $oidcEnabled, SQLITE3_INTEGER);
+$stmt->execute();
+if ($db->changes() > 0) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('success', $i18n)
+ ]));
} else {
die(json_encode([
"success" => false,
diff --git a/endpoints/admin/saveoidcsettings.php b/endpoints/admin/saveoidcsettings.php
index 74746c8..c9c2ef1 100644
--- a/endpoints/admin/saveoidcsettings.php
+++ b/endpoints/admin/saveoidcsettings.php
@@ -1,48 +1,32 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint_admin.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
-// Check that user is an admin
-if ($userId !== 1) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
-}
+$oidcName = isset($data['oidcName']) ? trim($data['oidcName']) : '';
+$oidcClientId = isset($data['oidcClientId']) ? trim($data['oidcClientId']) : '';
+$oidcClientSecret = isset($data['oidcClientSecret']) ? trim($data['oidcClientSecret']) : '';
+$oidcAuthUrl = isset($data['oidcAuthUrl']) ? trim($data['oidcAuthUrl']) : '';
+$oidcTokenUrl = isset($data['oidcTokenUrl']) ? trim($data['oidcTokenUrl']) : '';
+$oidcUserInfoUrl = isset($data['oidcUserInfoUrl']) ? trim($data['oidcUserInfoUrl']) : '';
+$oidcRedirectUrl = isset($data['oidcRedirectUrl']) ? trim($data['oidcRedirectUrl']) : '';
+$oidcLogoutUrl = isset($data['oidcLogoutUrl']) ? trim($data['oidcLogoutUrl']) : '';
+$oidcUserIdentifierField = isset($data['oidcUserIdentifierField']) ? trim($data['oidcUserIdentifierField']) : '';
+$oidcScopes = isset($data['oidcScopes']) ? trim($data['oidcScopes']) : '';
+$oidcAuthStyle = isset($data['oidcAuthStyle']) ? trim($data['oidcAuthStyle']) : '';
+$oidcAutoCreateUser = isset($data['oidcAutoCreateUser']) ? (int) $data['oidcAutoCreateUser'] : 0;
+$oidcPasswordLoginDisabled = isset($data['oidcPasswordLoginDisabled']) ? (int) $data['oidcPasswordLoginDisabled'] : 0;
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
+$checkStmt = $db->prepare('SELECT COUNT(*) as count FROM oauth_settings WHERE id = 1');
+$result = $checkStmt->execute();
+$row = $result->fetchArray(SQLITE3_ASSOC);
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $oidcName = isset($data['oidcName']) ? trim($data['oidcName']) : '';
- $oidcClientId = isset($data['oidcClientId']) ? trim($data['oidcClientId']) : '';
- $oidcClientSecret = isset($data['oidcClientSecret']) ? trim($data['oidcClientSecret']) : '';
- $oidcAuthUrl = isset($data['oidcAuthUrl']) ? trim($data['oidcAuthUrl']) : '';
- $oidcTokenUrl = isset($data['oidcTokenUrl']) ? trim($data['oidcTokenUrl']) : '';
- $oidcUserInfoUrl = isset($data['oidcUserInfoUrl']) ? trim($data['oidcUserInfoUrl']) : '';
- $oidcRedirectUrl = isset($data['oidcRedirectUrl']) ? trim($data['oidcRedirectUrl']) : '';
- $oidcLogoutUrl = isset($data['oidcLogoutUrl']) ? trim($data['oidcLogoutUrl']) : '';
- $oidcUserIdentifierField = isset($data['oidcUserIdentifierField']) ? trim($data['oidcUserIdentifierField']) : '';
- $oidcScopes = isset($data['oidcScopes']) ? trim($data['oidcScopes']) : '';
- $oidcAuthStyle = isset($data['oidcAuthStyle']) ? trim($data['oidcAuthStyle']) : '';
- $oidcAutoCreateUser = isset($data['oidcAutoCreateUser']) ? (int)$data['oidcAutoCreateUser'] : 0;
- $oidcPasswordLoginDisabled = isset($data['oidcPasswordLoginDisabled']) ? (int)$data['oidcPasswordLoginDisabled'] : 0;
-
- $checkStmt = $db->prepare('SELECT COUNT(*) as count FROM oauth_settings WHERE id = 1');
- $result = $checkStmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
-
- if ($row['count'] > 0) {
- // Update existing row
- $stmt = $db->prepare('UPDATE oauth_settings SET
+if ($row['count'] > 0) {
+ // Update existing row
+ $stmt = $db->prepare('UPDATE oauth_settings SET
name = :oidcName,
client_id = :oidcClientId,
client_secret = :oidcClientSecret,
@@ -57,45 +41,38 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") {
auto_create_user = :oidcAutoCreateUser,
password_login_disabled = :oidcPasswordLoginDisabled
WHERE id = 1');
- } else {
- // Insert new row
- $stmt = $db->prepare('INSERT INTO oauth_settings (
+} else {
+ // Insert new row
+ $stmt = $db->prepare('INSERT INTO oauth_settings (
id, name, client_id, client_secret, authorization_url, token_url, user_info_url, redirect_url, logout_url, user_identifier_field, scopes, auth_style, auto_create_user, password_login_disabled
) VALUES (
1, :oidcName, :oidcClientId, :oidcClientSecret, :oidcAuthUrl, :oidcTokenUrl, :oidcUserInfoUrl, :oidcRedirectUrl, :oidcLogoutUrl, :oidcUserIdentifierField, :oidcScopes, :oidcAuthStyle, :oidcAutoCreateUser, :oidcPasswordLoginDisabled
)');
- }
-
- $stmt->bindParam(':oidcName', $oidcName, SQLITE3_TEXT);
- $stmt->bindParam(':oidcClientId', $oidcClientId, SQLITE3_TEXT);
- $stmt->bindParam(':oidcClientSecret', $oidcClientSecret, SQLITE3_TEXT);
- $stmt->bindParam(':oidcAuthUrl', $oidcAuthUrl, SQLITE3_TEXT);
- $stmt->bindParam(':oidcTokenUrl', $oidcTokenUrl, SQLITE3_TEXT);
- $stmt->bindParam(':oidcUserInfoUrl', $oidcUserInfoUrl, SQLITE3_TEXT);
- $stmt->bindParam(':oidcRedirectUrl', $oidcRedirectUrl, SQLITE3_TEXT);
- $stmt->bindParam(':oidcLogoutUrl', $oidcLogoutUrl, SQLITE3_TEXT);
- $stmt->bindParam(':oidcUserIdentifierField', $oidcUserIdentifierField, SQLITE3_TEXT);
- $stmt->bindParam(':oidcScopes', $oidcScopes, SQLITE3_TEXT);
- $stmt->bindParam(':oidcAuthStyle', $oidcAuthStyle, SQLITE3_TEXT);
- $stmt->bindParam(':oidcAutoCreateUser', $oidcAutoCreateUser, SQLITE3_INTEGER);
- $stmt->bindParam(':oidcPasswordLoginDisabled', $oidcPasswordLoginDisabled, SQLITE3_INTEGER);
- $stmt->execute();
+}
- if ($db->changes() > 0) {
- $db->close();
- die(json_encode([
- "success" => true,
- "message" => translate('success', $i18n)
- ]));
- } else {
- $db->close();
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
- }
+$stmt->bindParam(':oidcName', $oidcName, SQLITE3_TEXT);
+$stmt->bindParam(':oidcClientId', $oidcClientId, SQLITE3_TEXT);
+$stmt->bindParam(':oidcClientSecret', $oidcClientSecret, SQLITE3_TEXT);
+$stmt->bindParam(':oidcAuthUrl', $oidcAuthUrl, SQLITE3_TEXT);
+$stmt->bindParam(':oidcTokenUrl', $oidcTokenUrl, SQLITE3_TEXT);
+$stmt->bindParam(':oidcUserInfoUrl', $oidcUserInfoUrl, SQLITE3_TEXT);
+$stmt->bindParam(':oidcRedirectUrl', $oidcRedirectUrl, SQLITE3_TEXT);
+$stmt->bindParam(':oidcLogoutUrl', $oidcLogoutUrl, SQLITE3_TEXT);
+$stmt->bindParam(':oidcUserIdentifierField', $oidcUserIdentifierField, SQLITE3_TEXT);
+$stmt->bindParam(':oidcScopes', $oidcScopes, SQLITE3_TEXT);
+$stmt->bindParam(':oidcAuthStyle', $oidcAuthStyle, SQLITE3_TEXT);
+$stmt->bindParam(':oidcAutoCreateUser', $oidcAutoCreateUser, SQLITE3_INTEGER);
+$stmt->bindParam(':oidcPasswordLoginDisabled', $oidcPasswordLoginDisabled, SQLITE3_INTEGER);
+$stmt->execute();
+if ($db->changes() > 0) {
+ $db->close();
+ die(json_encode([
+ "success" => true,
+ "message" => translate('success', $i18n)
+ ]));
} else {
+ $db->close();
die(json_encode([
"success" => false,
"message" => translate('error', $i18n)
diff --git a/endpoints/admin/saveopenregistrations.php b/endpoints/admin/saveopenregistrations.php
index 6d3f4c8..7f07b86 100644
--- a/endpoints/admin/saveopenregistrations.php
+++ b/endpoints/admin/saveopenregistrations.php
@@ -1,85 +1,66 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint_admin.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-// Check that user is an admin
-if ($userId !== 1) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
-
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $openRegistrations = $data['open_registrations'];
- $maxUsers = $data['max_users'];
- $requireEmailVerification = $data['require_email_validation'];
- $serverUrl = $data['server_url'];
- $disableLogin = $data['disable_login'];
-
- if ($disableLogin == 1) {
- if ($openRegistrations == 1) {
- echo json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]);
- die();
- }
-
- $sql = "SELECT COUNT(*) as userCount FROM user";
- $stmt = $db->prepare($sql);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $userCount = $row['userCount'];
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
- if ($userCount > 1) {
- echo json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]);
- die();
- }
- }
+$openRegistrations = $data['open_registrations'];
+$maxUsers = $data['max_users'];
+$requireEmailVerification = $data['require_email_validation'];
+$serverUrl = $data['server_url'];
+$disableLogin = $data['disable_login'];
- if ($requireEmailVerification == 1 && $serverUrl == "") {
+if ($disableLogin == 1) {
+ if ($openRegistrations == 1) {
echo json_encode([
"success" => false,
- "message" => translate('fill_all_fields', $i18n)
+ "message" => translate('error', $i18n)
]);
die();
}
- $sql = "UPDATE admin SET registrations_open = :openRegistrations, max_users = :maxUsers, require_email_verification = :requireEmailVerification, server_url = :serverUrl, login_disabled = :disableLogin WHERE id = 1";
+ $sql = "SELECT COUNT(*) as userCount FROM user";
$stmt = $db->prepare($sql);
- $stmt->bindParam(':openRegistrations', $openRegistrations, SQLITE3_INTEGER);
- $stmt->bindParam(':maxUsers', $maxUsers, SQLITE3_INTEGER);
- $stmt->bindParam(':requireEmailVerification', $requireEmailVerification, SQLITE3_INTEGER);
- $stmt->bindParam(':serverUrl', $serverUrl, SQLITE3_TEXT);
- $stmt->bindParam(':disableLogin', $disableLogin, SQLITE3_INTEGER);
$result = $stmt->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $userCount = $row['userCount'];
- if ($result) {
- echo json_encode([
- "success" => true,
- "message" => translate('success', $i18n)
- ]);
- } else {
+ if ($userCount > 1) {
echo json_encode([
"success" => false,
"message" => translate('error', $i18n)
]);
+ die();
}
}
-?>
\ No newline at end of file
+if ($requireEmailVerification == 1 && $serverUrl == "") {
+ echo json_encode([
+ "success" => false,
+ "message" => translate('fill_all_fields', $i18n)
+ ]);
+ die();
+}
+
+$sql = "UPDATE admin SET registrations_open = :openRegistrations, max_users = :maxUsers, require_email_verification = :requireEmailVerification, server_url = :serverUrl, login_disabled = :disableLogin WHERE id = 1";
+$stmt = $db->prepare($sql);
+$stmt->bindParam(':openRegistrations', $openRegistrations, SQLITE3_INTEGER);
+$stmt->bindParam(':maxUsers', $maxUsers, SQLITE3_INTEGER);
+$stmt->bindParam(':requireEmailVerification', $requireEmailVerification, SQLITE3_INTEGER);
+$stmt->bindParam(':serverUrl', $serverUrl, SQLITE3_TEXT);
+$stmt->bindParam(':disableLogin', $disableLogin, SQLITE3_INTEGER);
+$result = $stmt->execute();
+
+if ($result) {
+ echo json_encode([
+ "success" => true,
+ "message" => translate('success', $i18n)
+ ]);
+} else {
+ echo json_encode([
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ]);
+}
\ No newline at end of file
diff --git a/endpoints/admin/savesmtpsettings.php b/endpoints/admin/savesmtpsettings.php
index 5b040c4..ff7f59f 100644
--- a/endpoints/admin/savesmtpsettings.php
+++ b/endpoints/admin/savesmtpsettings.php
@@ -1,64 +1,44 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint_admin.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$smtpAddress = $data['smtpaddress'];
+$smtpPort = $data['smtpport'];
+$encryption = $data['encryption'];
+$smtpUsername = $data['smtpusername'];
+$smtpPassword = $data['smtppassword'];
+$fromEmail = $data['fromemail'];
+
+if (empty($smtpAddress) || empty($smtpPort)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate('fill_all_fields', $i18n)
]));
}
-// Check that user is an admin
-if ($userId !== 1) {
+// Save settings
+$stmt = $db->prepare('UPDATE admin SET smtp_address = :smtp_address, smtp_port = :smtp_port, encryption = :encryption, smtp_username = :smtp_username, smtp_password = :smtp_password, from_email = :from_email');
+$stmt->bindValue(':smtp_address', $smtpAddress, SQLITE3_TEXT);
+$stmt->bindValue(':smtp_port', $smtpPort, SQLITE3_TEXT);
+$encryption = empty($data['encryption']) ? 'tls' : $data['encryption'];
+$stmt->bindValue(':encryption', $encryption, SQLITE3_TEXT);
+$stmt->bindValue(':smtp_username', $smtpUsername, SQLITE3_TEXT);
+$stmt->bindValue(':smtp_password', $smtpPassword, SQLITE3_TEXT);
+$stmt->bindValue(':from_email', $fromEmail, SQLITE3_TEXT);
+$result = $stmt->execute();
+
+if ($result) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('success', $i18n)
+ ]));
+} else {
die(json_encode([
"success" => false,
"message" => translate('error', $i18n)
]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
-
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $smtpAddress = $data['smtpaddress'];
- $smtpPort = $data['smtpport'];
- $encryption = $data['encryption'];
- $smtpUsername = $data['smtpusername'];
- $smtpPassword = $data['smtppassword'];
- $fromEmail = $data['fromemail'];
-
- if (empty($smtpAddress) || empty($smtpPort)) {
- die(json_encode([
- "success" => false,
- "message" => translate('fill_all_fields', $i18n)
- ]));
- }
-
- // Save settings
- $stmt = $db->prepare('UPDATE admin SET smtp_address = :smtp_address, smtp_port = :smtp_port, encryption = :encryption, smtp_username = :smtp_username, smtp_password = :smtp_password, from_email = :from_email');
- $stmt->bindValue(':smtp_address', $smtpAddress, SQLITE3_TEXT);
- $stmt->bindValue(':smtp_port', $smtpPort, SQLITE3_TEXT);
- $encryption = empty($data['encryption']) ? 'tls' : $data['encryption'];
- $stmt->bindValue(':encryption', $encryption, SQLITE3_TEXT);
- $stmt->bindValue(':smtp_username', $smtpUsername, SQLITE3_TEXT);
- $stmt->bindValue(':smtp_password', $smtpPassword, SQLITE3_TEXT);
- $stmt->bindValue(':from_email', $fromEmail, SQLITE3_TEXT);
- $result = $stmt->execute();
-
- if ($result) {
- die(json_encode([
- "success" => true,
- "message" => translate('success', $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
- }
-
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/admin/updatenotification.php b/endpoints/admin/updatenotification.php
index dfa00c5..275572e 100644
--- a/endpoints/admin/updatenotification.php
+++ b/endpoints/admin/updatenotification.php
@@ -1,46 +1,26 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint_admin.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$updateNotification = $data['notificationEnabled'];
+
+// Save settings
+$stmt = $db->prepare('UPDATE admin SET update_notification = :update_notification');
+$stmt->bindValue(':update_notification', $updateNotification, SQLITE3_INTEGER);
+$result = $stmt->execute();
+
+if ($result) {
die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
+ "success" => true,
+ "message" => translate('success', $i18n)
]));
-}
-
-// Check that user is an admin
-if ($userId !== 1) {
+} else {
die(json_encode([
"success" => false,
"message" => translate('error', $i18n)
]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
-
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $updateNotification = $data['notificationEnabled'];
-
- // Save settings
- $stmt = $db->prepare('UPDATE admin SET update_notification = :update_notification');
- $stmt->bindValue(':update_notification', $updateNotification, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- if ($result) {
- die(json_encode([
- "success" => true,
- "message" => translate('success', $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
- }
-
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/ai/delete_recommendation.php b/endpoints/ai/delete_recommendation.php
index ef88be2..74e6906 100644
--- a/endpoints/ai/delete_recommendation.php
+++ b/endpoints/ai/delete_recommendation.php
@@ -1,52 +1,37 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $input = file_get_contents('php://input');
- $data = json_decode($input, true);
+$input = file_get_contents('php://input');
+$data = json_decode($input, true);
- $recommendationId = isset($data['id']) ? (int) $data['id'] : 0;
+$recommendationId = isset($data['id']) ? (int) $data['id'] : 0;
- if ($recommendationId <= 0) {
- $response = [
- "success" => false,
- "message" => translate('error', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
-
- // Delete the recommendation for the user
- $stmt = $db->prepare("DELETE FROM ai_recommendations WHERE id = ? AND user_id = ?");
- $stmt->bindValue(1, $recommendationId, SQLITE3_INTEGER);
- $stmt->bindValue(2, $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+if ($recommendationId <= 0) {
+ $response = [
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+}
- if ($db->changes() > 0) {
- $response = [
- "success" => true,
- "message" => translate('success', $i18n)
- ];
- } else {
- $response = [
- "success" => false,
- "message" => translate('error', $i18n)
- ];
- }
+// Delete the recommendation for the user
+$stmt = $db->prepare("DELETE FROM ai_recommendations WHERE id = ? AND user_id = ?");
+$stmt->bindValue(1, $recommendationId, SQLITE3_INTEGER);
+$stmt->bindValue(2, $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
- echo json_encode($response);
- } else {
- http_response_code(405);
- echo json_encode([
- "success" => false,
- "message" => translate('invalid_request_method', $i18n)
- ]);
- }
+if ($db->changes() > 0) {
+ $response = [
+ "success" => true,
+ "message" => translate('success', $i18n)
+ ];
} else {
$response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate('error', $i18n)
];
- echo json_encode($response);
-}
\ No newline at end of file
+}
+
+echo json_encode($response);
\ No newline at end of file
diff --git a/endpoints/ai/fetch_models.php b/endpoints/ai/fetch_models.php
index 36bcd0d..29bf9bd 100644
--- a/endpoints/ai/fetch_models.php
+++ b/endpoints/ai/fetch_models.php
@@ -1,148 +1,130 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
$chatgptModelsApiUrl = 'https://api.openai.com/v1/models';
$geminiModelsApiUrl = 'https://generativelanguage.googleapis.com/v1beta/models';
$openrouterModelsApiUrl = 'https://openrouter.ai/api/v1/models';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $input = file_get_contents('php://input');
- $data = json_decode($input, true);
- // Check if ai-type and ai-api-key are set
- $aiType = isset($data["type"]) ? trim($data["type"]) : '';
- $aiApiKey = isset($data["api_key"]) ? trim($data["api_key"]) : '';
- $aiOllamaHost = isset($data["ollama_host"]) ? trim($data["ollama_host"]) : '';
+$input = file_get_contents('php://input');
+$data = json_decode($input, true);
+// Check if ai-type and ai-api-key are set
+$aiType = isset($data["type"]) ? trim($data["type"]) : '';
+$aiApiKey = isset($data["api_key"]) ? trim($data["api_key"]) : '';
+$aiOllamaHost = isset($data["ollama_host"]) ? trim($data["ollama_host"]) : '';
- // Validate ai-type
- if (!in_array($aiType, ['chatgpt', 'gemini', 'openrouter', 'ollama'])) {
- $response = [
- "success" => false,
- "message" => translate('error', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
-
- // Validate ai-api-key and fetch models if ai-type is chatgpt, gemini or openrouter
- if ($aiType === 'chatgpt' || $aiType === 'gemini' || $aiType === 'openrouter') {
- if (empty($aiApiKey)) {
- $response = [
- "success" => false,
- "message" => translate('invalid_api_key', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
- }
+// Validate ai-type
+if (!in_array($aiType, ['chatgpt', 'gemini', 'openrouter', 'ollama'])) {
+ $response = [
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+}
- // Prepare the request headers
- $headers = [
- 'Content-Type: application/json',
+// Validate ai-api-key and fetch models if ai-type is chatgpt, gemini or openrouter
+if ($aiType === 'chatgpt' || $aiType === 'gemini' || $aiType === 'openrouter') {
+ if (empty($aiApiKey)) {
+ $response = [
+ "success" => false,
+ "message" => translate('invalid_api_key', $i18n)
];
- if ($aiType === 'chatgpt') {
- $headers[] = 'Authorization: Bearer ' . $aiApiKey;
- $apiUrl = $chatgptModelsApiUrl;
- } elseif ($aiType === 'gemini') {
- $apiUrl = $geminiModelsApiUrl . '?key=' . urlencode($aiApiKey);
- } elseif ($aiType === 'openrouter') {
- $headers[] = 'Authorization: Bearer ' . $aiApiKey;
- $apiUrl = $openrouterModelsApiUrl;
- }
- else {
- // For ollama, no API key is needed
- // Check for ollama host
- if (empty($aiOllamaHost)) {
- $response = [
- "success" => false,
- "message" => translate('invalid_host', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
- $apiUrl = $aiOllamaHost . '/api/tags';
- }
- // Initialize cURL
- $ch = curl_init($apiUrl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_TIMEOUT, 60); // Set a timeout for the request
- // Execute the request
- $response = curl_exec($ch);
- // Check for cURL errors
- if (curl_errno($ch)) {
- $response = [
- "success" => false,
- "message" => ($aiType === 'ollama')
- ? translate('invalid_host', $i18n)
- : translate('error', $i18n)
- ];
- } else {
- // Decode the response
- $modelsData = json_decode($response, true);
- if ($aiType === 'gemini' && isset($modelsData['models']) && is_array($modelsData['models'])) {
- // Normalize Gemini response
- $models = array_map(function ($model) {
- return [
- 'id' => str_replace('models/', '', $model['name']),
- 'name' => $model['displayName'] ?? $model['name'],
- ];
- }, $modelsData['models']);
- $response = [
- "success" => true,
- "models" => $models
- ];
- } elseif (isset($modelsData['data']) && is_array($modelsData['data'])) {
- // OpenAI format
- $models = array_map(function ($model) {
- return [
- 'id' => $model['id'],
- 'name' => $model['name'] ?? $model['id'],
- ];
- }, $modelsData['data']);
- $response = [
- "success" => true,
- "models" => $models
- ];
- } elseif ($aiType === 'ollama' && isset($modelsData['models']) && is_array($modelsData['models'])) {
- // Normalize Ollama response
- $models = array_map(function ($model) {
- return [
- 'id' => $model['name'],
- 'name' => $model['name'],
- ];
- }, $modelsData['models']);
- $response = [
- "success" => true,
- "models" => $models
- ];
- } else {
- $response = [
- "success" => false,
- "message" => ($aiType === 'ollama')
- ? translate('invalid_host', $i18n)
- : translate('invalid_api_key', $i18n)
- ];
- }
- }
- // Close cURL session
- curl_close($ch);
- // Return the response as JSON
echo json_encode($response);
+ exit;
+ }
+}
-
- } else {
+// Prepare the request headers
+$headers = [
+ 'Content-Type: application/json',
+];
+if ($aiType === 'chatgpt') {
+ $headers[] = 'Authorization: Bearer ' . $aiApiKey;
+ $apiUrl = $chatgptModelsApiUrl;
+} elseif ($aiType === 'gemini') {
+ $apiUrl = $geminiModelsApiUrl . '?key=' . urlencode($aiApiKey);
+} elseif ($aiType === 'openrouter') {
+ $headers[] = 'Authorization: Bearer ' . $aiApiKey;
+ $apiUrl = $openrouterModelsApiUrl;
+} else {
+ // For ollama, no API key is needed
+ // Check for ollama host
+ if (empty($aiOllamaHost)) {
$response = [
"success" => false,
- "message" => translate('invalid_request_method', $i18n)
+ "message" => translate('invalid_host', $i18n)
];
echo json_encode($response);
+ exit;
}
-} else {
+ $apiUrl = $aiOllamaHost . '/api/tags';
+}
+// Initialize cURL
+$ch = curl_init($apiUrl);
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+curl_setopt($ch, CURLOPT_TIMEOUT, 60); // Set a timeout for the request
+// Execute the request
+$response = curl_exec($ch);
+// Check for cURL errors
+if (curl_errno($ch)) {
$response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => ($aiType === 'ollama')
+ ? translate('invalid_host', $i18n)
+ : translate('error', $i18n)
];
- echo json_encode($response);
-}
\ No newline at end of file
+} else {
+ // Decode the response
+ $modelsData = json_decode($response, true);
+ if ($aiType === 'gemini' && isset($modelsData['models']) && is_array($modelsData['models'])) {
+ // Normalize Gemini response
+ $models = array_map(function ($model) {
+ return [
+ 'id' => str_replace('models/', '', $model['name']),
+ 'name' => $model['displayName'] ?? $model['name'],
+ ];
+ }, $modelsData['models']);
+ $response = [
+ "success" => true,
+ "models" => $models
+ ];
+ } elseif (isset($modelsData['data']) && is_array($modelsData['data'])) {
+ // OpenAI format
+ $models = array_map(function ($model) {
+ return [
+ 'id' => $model['id'],
+ 'name' => $model['name'] ?? $model['id'],
+ ];
+ }, $modelsData['data']);
+ $response = [
+ "success" => true,
+ "models" => $models
+ ];
+ } elseif ($aiType === 'ollama' && isset($modelsData['models']) && is_array($modelsData['models'])) {
+ // Normalize Ollama response
+ $models = array_map(function ($model) {
+ return [
+ 'id' => $model['name'],
+ 'name' => $model['name'],
+ ];
+ }, $modelsData['models']);
+ $response = [
+ "success" => true,
+ "models" => $models
+ ];
+ } else {
+ $response = [
+ "success" => false,
+ "message" => ($aiType === 'ollama')
+ ? translate('invalid_host', $i18n)
+ : translate('invalid_api_key', $i18n)
+ ];
+ }
+}
+// Close cURL session
+curl_close($ch);
+// Return the response as JSON
+echo json_encode($response);
\ No newline at end of file
diff --git a/endpoints/ai/generate_recommendations.php b/endpoints/ai/generate_recommendations.php
index 5fba4e5..3ed511c 100644
--- a/endpoints/ai/generate_recommendations.php
+++ b/endpoints/ai/generate_recommendations.php
@@ -1,6 +1,7 @@
<?php
set_time_limit(300);
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
function getPricePerMonth($cycle, $frequency, $price)
{
@@ -40,141 +41,139 @@ function describeCurrency($currencyId, $currencies)
return $currencies[$currencyId]['code'] ?? '';
}
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
+// Get AI settings for the user from the database
+$stmt = $db->prepare("SELECT * FROM ai_settings WHERE user_id = ?");
+$stmt->bindValue(1, $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
+$aiSettings = $result->fetchArray(SQLITE3_ASSOC);
+$stmt->close();
+if (!$aiSettings) {
+ $response = [
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+}
- // Get AI settings for the user from the database
- $stmt = $db->prepare("SELECT * FROM ai_settings WHERE user_id = ?");
- $stmt->bindValue(1, $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $aiSettings = $result->fetchArray(SQLITE3_ASSOC);
- $stmt->close();
- if (!$aiSettings) {
+$type = isset($aiSettings['type']) ? $aiSettings['type'] : '';
+$enabled = isset($aiSettings['enabled']) ? (bool) $aiSettings['enabled'] : false;
+$model = isset($aiSettings['model']) ? $aiSettings['model'] : '';
+$host = "";
+$apiKey = "";
+if (!in_array($type, ['chatgpt', 'gemini', 'openrouter', 'ollama']) || !$enabled || empty($model)) {
+ $response = [
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+}
+
+if ($type == 'ollama') {
+ $host = isset($aiSettings['url']) ? $aiSettings['url'] : '';
+ if (empty($host)) {
$response = [
"success" => false,
- "message" => translate('error', $i18n)
+ "message" => translate('invalid_host', $i18n)
];
echo json_encode($response);
exit;
}
-
- $type = isset($aiSettings['type']) ? $aiSettings['type'] : '';
- $enabled = isset($aiSettings['enabled']) ? (bool) $aiSettings['enabled'] : false;
- $model = isset($aiSettings['model']) ? $aiSettings['model'] : '';
- $host = "";
- $apiKey = "";
- if (!in_array($type, ['chatgpt', 'gemini', 'openrouter', 'ollama']) || !$enabled || empty($model)) {
+} else {
+ $apiKey = isset($aiSettings['api_key']) ? $aiSettings['api_key'] : '';
+ if (empty($apiKey)) {
$response = [
"success" => false,
- "message" => translate('error', $i18n)
+ "message" => translate('invalid_api_key', $i18n)
];
echo json_encode($response);
exit;
}
+}
- if ($type == 'ollama') {
- $host = isset($aiSettings['url']) ? $aiSettings['url'] : '';
- if (empty($host)) {
- $response = [
- "success" => false,
- "message" => translate('invalid_host', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
- } else {
- $apiKey = isset($aiSettings['api_key']) ? $aiSettings['api_key'] : '';
- if (empty($apiKey)) {
- $response = [
- "success" => false,
- "message" => translate('invalid_api_key', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
- }
-
- // We have everything we need, fetch information from the dabase to send to the AI API
- // Get the categories from the database for user with ID 1
- $stmt = $db->prepare("SELECT * FROM categories WHERE user_id = :user_id");
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $categories = [];
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $categories[$row['id']] = $row;
- }
-
- // Get the currencies from the database for user with ID 1
- $stmt = $db->prepare("SELECT * FROM currencies WHERE user_id = :user_id");
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $currencies = [];
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $currencies[$row['id']] = $row;
- }
+// We have everything we need, fetch information from the dabase to send to the AI API
+// Get the categories from the database for user with ID 1
+$stmt = $db->prepare("SELECT * FROM categories WHERE user_id = :user_id");
+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
+$categories = [];
+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $categories[$row['id']] = $row;
+}
- // Get houswhold members from the database for user with ID 1
- $stmt = $db->prepare("SELECT * FROM household WHERE user_id = :user_id");
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $members = [];
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $members[$row['id']] = $row;
- }
+// Get the currencies from the database for user with ID 1
+$stmt = $db->prepare("SELECT * FROM currencies WHERE user_id = :user_id");
+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
+$currencies = [];
+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $currencies[$row['id']] = $row;
+}
- // Get language from the user table
- $stmt = $db->prepare("SELECT language FROM user WHERE id = :user_id");
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $userLanguage = $result->fetchArray(SQLITE3_ASSOC)['language'] ?? 'en';
+// Get houswhold members from the database for user with ID 1
+$stmt = $db->prepare("SELECT * FROM household WHERE user_id = :user_id");
+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
+$members = [];
+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $members[$row['id']] = $row;
+}
- // Get name from includes/i18n/languages.php
- require_once '../../includes/i18n/languages.php';
- $userLanguageName = $languages[$userLanguage]['name'] ?? 'English';
+// Get language from the user table
+$stmt = $db->prepare("SELECT language FROM user WHERE id = :user_id");
+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
+$userLanguage = $result->fetchArray(SQLITE3_ASSOC)['language'] ?? 'en';
- // Get subscriptions from the database for user with ID 1
- $stmt = $db->prepare("SELECT * FROM subscriptions WHERE user_id = :user_id AND inactive = 0");
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+// Get name from includes/i18n/languages.php
+require_once '../../includes/i18n/languages.php';
+$userLanguageName = $languages[$userLanguage]['name'] ?? 'English';
- $subscriptions = [];
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $subscriptions[] = $row;
- }
+// Get subscriptions from the database for user with ID 1
+$stmt = $db->prepare("SELECT * FROM subscriptions WHERE user_id = :user_id AND inactive = 0");
+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
- if (!empty($subscriptions)) {
- $subscriptionsForAI = [];
+$subscriptions = [];
+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $subscriptions[] = $row;
+}
- foreach ($subscriptions as $row) {
- if ($row['inactive'])
- continue;
+if (!empty($subscriptions)) {
+ $subscriptionsForAI = [];
- $price = round($row['price'], 2);
- $currencyCode = $currencies[$row['currency_id']]['code'] ?? '';
- $priceFormatted = $currencyCode ? "$price $currencyCode" : "$price";
+ foreach ($subscriptions as $row) {
+ if ($row['inactive'])
+ continue;
- $payerName = $members[$row['payer_user_id']]['name'] ?? 'Unknown';
+ $price = round($row['price'], 2);
+ $currencyCode = $currencies[$row['currency_id']]['code'] ?? '';
+ $priceFormatted = $currencyCode ? "$price $currencyCode" : "$price";
- $subscriptionsForAI[] = [
- 'name' => $row['name'],
- 'price' => $priceFormatted,
- 'frequency' => describeFrequency($row['cycle'], $row['frequency']),
- 'category' => $categories[$row['category_id']]['name'] ?? 'Uncategorized',
- 'payer' => $payerName
- ];
- }
+ $payerName = $members[$row['payer_user_id']]['name'] ?? 'Unknown';
- // encode
- $aiDataJson = json_encode($subscriptionsForAI, JSON_PRETTY_PRINT);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error', $i18n)
+ $subscriptionsForAI[] = [
+ 'name' => $row['name'],
+ 'price' => $priceFormatted,
+ 'frequency' => describeFrequency($row['cycle'], $row['frequency']),
+ 'category' => $categories[$row['category_id']]['name'] ?? 'Uncategorized',
+ 'payer' => $payerName
];
- echo json_encode($response);
- exit;
}
- $prompt = <<<PROMPT
+ // encode
+ $aiDataJson = json_encode($subscriptionsForAI, JSON_PRETTY_PRINT);
+} else {
+ $response = [
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+}
+
+$prompt = <<<PROMPT
You are a helpful assistant designed to help users save money on digital subscriptions.
The user has shared a list of their active subscriptions across household members. For each subscription, you are given:
@@ -210,126 +209,118 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
Here is the user’s data:
PROMPT;
- $prompt .= "\n\n" . json_encode($subscriptionsForAI, JSON_PRETTY_PRINT);
+$prompt .= "\n\n" . json_encode($subscriptionsForAI, JSON_PRETTY_PRINT);
- // Prepare the cURL request
- $ch = curl_init();
+// Prepare the cURL request
+$ch = curl_init();
- if ($type === 'ollama') {
- curl_setopt($ch, CURLOPT_URL, $host . '/api/generate');
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['model' => $model, 'prompt' => $prompt, 'stream' => false]));
- } else {
- $headers = ['Content-Type: application/json'];
-
- if ($type === 'chatgpt') {
- $headers[] = 'Authorization: Bearer ' . $apiKey;
- curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
- 'model' => $model,
- 'messages' => [['role' => 'user', 'content' => $prompt]]
- ]));
- } elseif ($type === 'gemini') {
- curl_setopt(
- $ch,
- CURLOPT_URL,
- 'https://generativelanguage.googleapis.com/v1beta/models/' . urlencode($model) .
- ':generateContent?key=' . urlencode($apiKey)
- );
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
- 'contents' => [
- [
- 'parts' => [['text' => $prompt]]
- ]
+if ($type === 'ollama') {
+ curl_setopt($ch, CURLOPT_URL, $host . '/api/generate');
+ curl_setopt($ch, CURLOPT_POST, true);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['model' => $model, 'prompt' => $prompt, 'stream' => false]));
+} else {
+ $headers = ['Content-Type: application/json'];
+
+ if ($type === 'chatgpt') {
+ $headers[] = 'Authorization: Bearer ' . $apiKey;
+ curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
+ 'model' => $model,
+ 'messages' => [['role' => 'user', 'content' => $prompt]]
+ ]));
+ } elseif ($type === 'gemini') {
+ curl_setopt(
+ $ch,
+ CURLOPT_URL,
+ 'https://generativelanguage.googleapis.com/v1beta/models/' . urlencode($model) .
+ ':generateContent?key=' . urlencode($apiKey)
+ );
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
+ 'contents' => [
+ [
+ 'parts' => [['text' => $prompt]]
]
- ]));
- } elseif ($type === 'openrouter') {
- $headers[] = 'Authorization: Bearer ' . $apiKey;
- curl_setopt($ch, CURLOPT_URL, 'https://openrouter.ai/api/v1/chat/completions');
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
- 'model' => $model,
- 'messages' => [['role' => 'user', 'content' => $prompt]]
- ]));
- }
-
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+ ]
+ ]));
+ } elseif ($type === 'openrouter') {
+ $headers[] = 'Authorization: Bearer ' . $apiKey;
+ curl_setopt($ch, CURLOPT_URL, 'https://openrouter.ai/api/v1/chat/completions');
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
+ 'model' => $model,
+ 'messages' => [['role' => 'user', 'content' => $prompt]]
+ ]));
}
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300);
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+}
- // Execute the cURL request
- $reply = curl_exec($ch);
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_TIMEOUT, 300);
- // Check for errors
- if (curl_errno($ch)) {
- $response = [
- "success" => false,
- "message" => curl_error($ch)
- ];
- echo json_encode($response);
- exit;
- }
+// Execute the cURL request
+$reply = curl_exec($ch);
- // Close the cURL session
- curl_close($ch);
-
- // Try to decode the AI's JSON reply
- $replyData = json_decode($reply, true); // decode into array
- if (($type === 'chatgpt' || $type === 'openrouter') && isset($replyData['choices'][0]['message']['content'])) {
- $recommendationsJson = $replyData['choices'][0]['message']['content'];
- $recommendations = json_decode($recommendationsJson, true);
- } elseif ($type === 'gemini' && isset($replyData['candidates'][0]['content']['parts'][0]['text'])) {
- $recommendationsJson = $replyData['candidates'][0]['content']['parts'][0]['text'];
- // Gemini has a habit of returning the JSON wrapped in markdown syntax, no matter the prompting, strip before parsing.
- $recommendationsJson = preg_replace('/^```json\s*|\s*```$/m', '', $recommendationsJson);
- $recommendationsJson = trim($recommendationsJson);
- $recommendations = json_decode($recommendationsJson, true);
- } else {
- $recommendations = json_decode($replyData['response'], true);
- }
+// Check for errors
+if (curl_errno($ch)) {
+ $response = [
+ "success" => false,
+ "message" => curl_error($ch)
+ ];
+ echo json_encode($response);
+ exit;
+}
- if (json_last_error() === JSON_ERROR_NONE && is_array($recommendations)) {
- // Remove old recommendations for this user
- $stmt = $db->prepare("DELETE FROM ai_recommendations WHERE user_id = :user_id");
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $stmt->execute();
+// Close the cURL session
+curl_close($ch);
+
+// Try to decode the AI's JSON reply
+$replyData = json_decode($reply, true); // decode into array
+if (($type === 'chatgpt' || $type === 'openrouter') && isset($replyData['choices'][0]['message']['content'])) {
+ $recommendationsJson = $replyData['choices'][0]['message']['content'];
+ $recommendations = json_decode($recommendationsJson, true);
+} elseif ($type === 'gemini' && isset($replyData['candidates'][0]['content']['parts'][0]['text'])) {
+ $recommendationsJson = $replyData['candidates'][0]['content']['parts'][0]['text'];
+ // Gemini has a habit of returning the JSON wrapped in markdown syntax, no matter the prompting, strip before parsing.
+ $recommendationsJson = preg_replace('/^```json\s*|\s*```$/m', '', $recommendationsJson);
+ $recommendationsJson = trim($recommendationsJson);
+ $recommendations = json_decode($recommendationsJson, true);
+} else {
+ $recommendations = json_decode($replyData['response'], true);
+}
- // Insert each new recommendation
- $insert = $db->prepare("
+if (json_last_error() === JSON_ERROR_NONE && is_array($recommendations)) {
+ // Remove old recommendations for this user
+ $stmt = $db->prepare("DELETE FROM ai_recommendations WHERE user_id = :user_id");
+ $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+ $stmt->execute();
+
+ // Insert each new recommendation
+ $insert = $db->prepare("
INSERT INTO ai_recommendations (user_id, type, title, description, savings)
VALUES (:user_id, :type, :title, :description, :savings)
");
- foreach ($recommendations as $rec) {
- $insert->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $insert->bindValue(':type', 'subscription', SQLITE3_TEXT); // or any category you want
- $insert->bindValue(':title', $rec['title'] ?? '', SQLITE3_TEXT);
- $insert->bindValue(':description', $rec['description'] ?? '', SQLITE3_TEXT);
- $insert->bindValue(':savings', $rec['savings'] ?? '', SQLITE3_TEXT);
- $insert->execute();
- }
-
- $response = [
- "success" => true,
- "message" => translate('success', $i18n),
- "recommendations" => $recommendations
- ];
- echo json_encode($response);
- exit;
- } else {
- $response = [
- "success" => false,
- "message" => translate('error', $i18n),
- "json_error" => json_last_error_msg()
- ];
- echo json_encode($response);
- exit;
+ foreach ($recommendations as $rec) {
+ $insert->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+ $insert->bindValue(':type', 'subscription', SQLITE3_TEXT); // or any category you want
+ $insert->bindValue(':title', $rec['title'] ?? '', SQLITE3_TEXT);
+ $insert->bindValue(':description', $rec['description'] ?? '', SQLITE3_TEXT);
+ $insert->bindValue(':savings', $rec['savings'] ?? '', SQLITE3_TEXT);
+ $insert->execute();
}
+
+ $response = [
+ "success" => true,
+ "message" => translate('success', $i18n),
+ "recommendations" => $recommendations
+ ];
+ echo json_encode($response);
+ exit;
} else {
$response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate('error', $i18n),
+ "json_error" => json_last_error_msg()
];
echo json_encode($response);
exit;
diff --git a/endpoints/ai/save_settings.php b/endpoints/ai/save_settings.php
index af8c8d7..99d34cf 100644
--- a/endpoints/ai/save_settings.php
+++ b/endpoints/ai/save_settings.php
@@ -1,99 +1,84 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $input = file_get_contents('php://input');
- $data = json_decode($input, true);
+$input = file_get_contents('php://input');
+$data = json_decode($input, true);
- $aiEnabled = isset($data['ai_enabled']) ? (bool) $data['ai_enabled'] : false;
- $aiType = isset($data['ai_type']) ? trim($data['ai_type']) : '';
- $aiApiKey = isset($data['api_key']) ? trim($data['api_key']) : '';
- $aiOllamaHost = isset($data['ollama_host']) ? trim($data['ollama_host']) : '';
- $aiModel = isset($data['model']) ? trim($data['model']) : '';
+$aiEnabled = isset($data['ai_enabled']) ? (bool) $data['ai_enabled'] : false;
+$aiType = isset($data['ai_type']) ? trim($data['ai_type']) : '';
+$aiApiKey = isset($data['api_key']) ? trim($data['api_key']) : '';
+$aiOllamaHost = isset($data['ollama_host']) ? trim($data['ollama_host']) : '';
+$aiModel = isset($data['model']) ? trim($data['model']) : '';
- if (empty($aiType) || !in_array($aiType, ['chatgpt', 'gemini', 'openrouter', 'ollama'])) {
- $response = [
- "success" => false,
- "message" => translate('error', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
+if (empty($aiType) || !in_array($aiType, ['chatgpt', 'gemini', 'openrouter', 'ollama'])) {
+ $response = [
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+}
- if (($aiType === 'chatgpt' || $aiType === 'gemini' || $aiType === 'openrouter') && empty($aiApiKey)) {
- $response = [
- "success" => false,
- "message" => translate('invalid_api_key', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
+if (($aiType === 'chatgpt' || $aiType === 'gemini' || $aiType === 'openrouter') && empty($aiApiKey)) {
+ $response = [
+ "success" => false,
+ "message" => translate('invalid_api_key', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+}
- if ($aiType === 'ollama' && empty($aiOllamaHost)) {
- $response = [
- "success" => false,
- "message" => translate('invalid_host', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
+if ($aiType === 'ollama' && empty($aiOllamaHost)) {
+ $response = [
+ "success" => false,
+ "message" => translate('invalid_host', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+}
- if (empty($aiModel)) {
- $response = [
- "success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- echo json_encode($response);
- exit;
- }
+if (empty($aiModel)) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+}
- if ($aiType === 'ollama') {
- $aiApiKey = ''; // Ollama does not require an API key
- } else {
- $aiOllamaHost = ''; // Clear Ollama host if not using Ollama
- }
+if ($aiType === 'ollama') {
+ $aiApiKey = ''; // Ollama does not require an API key
+} else {
+ $aiOllamaHost = ''; // Clear Ollama host if not using Ollama
+}
- // Remove existing AI settings for the user
- $stmt = $db->prepare("DELETE FROM ai_settings WHERE user_id = ?");
- $stmt->bindValue(1, $userId, SQLITE3_INTEGER);
- $stmt->execute();
- $stmt->close();
+// Remove existing AI settings for the user
+$stmt = $db->prepare("DELETE FROM ai_settings WHERE user_id = ?");
+$stmt->bindValue(1, $userId, SQLITE3_INTEGER);
+$stmt->execute();
+$stmt->close();
- // Insert new AI settings
- $stmt = $db->prepare("INSERT INTO ai_settings (user_id, type, enabled, api_key, model, url) VALUES (:user_id, :type, :enabled, :api_key, :model, :url)");
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $stmt->bindValue(':type', $aiType, SQLITE3_TEXT);
- $stmt->bindValue(':enabled', $aiEnabled, SQLITE3_INTEGER);
- $stmt->bindValue(':api_key', $aiApiKey, SQLITE3_TEXT);
- $stmt->bindValue(':model', $aiModel, SQLITE3_TEXT);
- $stmt->bindValue(':url', $aiOllamaHost, SQLITE3_TEXT);
- $result = $stmt->execute();
+// Insert new AI settings
+$stmt = $db->prepare("INSERT INTO ai_settings (user_id, type, enabled, api_key, model, url) VALUES (:user_id, :type, :enabled, :api_key, :model, :url)");
+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+$stmt->bindValue(':type', $aiType, SQLITE3_TEXT);
+$stmt->bindValue(':enabled', $aiEnabled, SQLITE3_INTEGER);
+$stmt->bindValue(':api_key', $aiApiKey, SQLITE3_TEXT);
+$stmt->bindValue(':model', $aiModel, SQLITE3_TEXT);
+$stmt->bindValue(':url', $aiOllamaHost, SQLITE3_TEXT);
+$result = $stmt->execute();
- if ($result) {
- $response = [
- "success" => true,
- "message" => translate('success', $i18n),
- "enabled" => $aiEnabled
- ];
- } else {
- $response = [
- "success" => false,
- "message" => translate('error', $i18n)
- ];
- }
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('invalid_request_method', $i18n)
- ];
- echo json_encode($response);
- }
+if ($result) {
+ $response = [
+ "success" => true,
+ "message" => translate('success', $i18n),
+ "enabled" => $aiEnabled
+ ];
} else {
$response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate('error', $i18n)
];
- echo json_encode($response);
-}
\ No newline at end of file
+}
+echo json_encode($response);
diff --git a/endpoints/categories/category.php b/endpoints/categories/category.php
index d33501f..4de84bf 100644
--- a/endpoints/categories/category.php
+++ b/endpoints/categories/category.php
@@ -1,123 +1,165 @@
<?php
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if (isset($_GET['action']) && $_GET['action'] == "add") {
- $stmt = $db->prepare('SELECT MAX("order") as maxOrder FROM categories WHERE user_id = :userId');
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $maxOrder = $row['maxOrder'];
+$action = $_POST['action'] ?? '';
- if ($maxOrder === NULL) {
- $maxOrder = 0;
- }
+switch ($action) {
+ case "add":
+ handleAddCategory($db, $userId, $i18n);
+ break;
+ case "edit":
+ handleEditCategory($db, $userId, $i18n);
+ break;
+ case "delete":
+ handleDeleteCategory($db, $userId, $i18n);
+ break;
+ case "sort":
+ handleSortCategories($db, $userId, $i18n);
+ break;
+ default:
+ echo json_encode(["success" => false, "message" => translate('error', $i18n)]);
+ break;
+}
+
+function handleAddCategory($db, $userId, $i18n)
+{
+ $stmt = $db->prepare('SELECT MAX("order") as maxOrder FROM categories WHERE user_id = :userId');
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $maxOrder = $row['maxOrder'];
+
+ if ($maxOrder === NULL) {
+ $maxOrder = 0;
+ }
+
+ $order = $maxOrder + 1;
+
+ $categoryName = "Category";
+ $sqlInsert = 'INSERT INTO categories ("name", "order", "user_id") VALUES (:name, :order, :userId)';
+ $stmtInsert = $db->prepare($sqlInsert);
+ $stmtInsert->bindParam(':name', $categoryName, SQLITE3_TEXT);
+ $stmtInsert->bindParam(':order', $order, SQLITE3_INTEGER);
+ $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $resultInsert = $stmtInsert->execute();
- $order = $maxOrder + 1;
+ if ($resultInsert) {
+ $categoryId = $db->lastInsertRowID();
+ $response = [
+ "success" => true,
+ "categoryId" => $categoryId
+ ];
+ echo json_encode($response);
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('failed_add_category', $i18n)
+ ];
+ echo json_encode($response);
+ }
+}
- $categoryName = "Category";
- $sqlInsert = 'INSERT INTO categories ("name", "order", "user_id") VALUES (:name, :order, :userId)';
- $stmtInsert = $db->prepare($sqlInsert);
- $stmtInsert->bindParam(':name', $categoryName, SQLITE3_TEXT);
- $stmtInsert->bindParam(':order', $order, SQLITE3_INTEGER);
- $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $resultInsert = $stmtInsert->execute();
+function handleEditCategory($db, $userId, $i18n)
+{
+ if (isset($_POST['categoryId']) && $_POST['categoryId'] != "" && isset($_POST['name']) && $_POST['name'] != "") {
+ $categoryId = $_POST['categoryId'];
+ $name = validate($_POST['name']);
+ $sql = "UPDATE categories SET name = :name WHERE id = :categoryId AND user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':name', $name, SQLITE3_TEXT);
+ $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
- if ($resultInsert) {
- $categoryId = $db->lastInsertRowID();
+ if ($result) {
$response = [
"success" => true,
- "categoryId" => $categoryId
+ "message" => translate('category_saved', $i18n)
];
echo json_encode($response);
} else {
$response = [
"success" => false,
- "errorMessage" => translate('failed_add_category', $i18n)
+ "message" => translate('failed_edit_category', $i18n)
];
echo json_encode($response);
}
- } else if (isset($_GET['action']) && $_GET['action'] == "edit") {
- if (isset($_GET['categoryId']) && $_GET['categoryId'] != "" && isset($_GET['name']) && $_GET['name'] != "") {
- $categoryId = $_GET['categoryId'];
- $name = validate($_GET['name']);
- $sql = "UPDATE categories SET name = :name WHERE id = :categoryId AND user_id = :userId";
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_all_fields', $i18n)
+ ];
+ echo json_encode($response);
+ }
+}
+
+function handleDeleteCategory($db, $userId, $i18n)
+{
+ if (isset($_POST['categoryId']) && $_POST['categoryId'] != "" && $_POST['categoryId'] != 1) {
+ $categoryId = $_POST['categoryId'];
+ $checkCategory = "SELECT COUNT(*) FROM subscriptions WHERE category_id = :categoryId AND user_id = :userId";
+ $checkStmt = $db->prepare($checkCategory);
+ $checkStmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
+ $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $checkResult = $checkStmt->execute();
+ $row = $checkResult->fetchArray();
+ $count = $row[0];
+
+ if ($count > 0) {
+ $response = [
+ "success" => false,
+ "message" => translate('category_in_use', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
+ $sql = "DELETE FROM categories WHERE id = :categoryId AND user_id = :userId";
$stmt = $db->prepare($sql);
- $stmt->bindParam(':name', $name, SQLITE3_TEXT);
$stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
$result = $stmt->execute();
-
if ($result) {
$response = [
"success" => true,
- "message" => translate('category_saved', $i18n)
+ "message" => translate('category_removed', $i18n)
];
echo json_encode($response);
} else {
$response = [
"success" => false,
- "errorMessage" => translate('failed_edit_category', $i18n)
- ];
- echo json_encode($response);
- }
- } else {
- $response = [
- "success" => false,
- "errorMessage" => translate('fill_all_fields', $i18n)
- ];
- echo json_encode($response);
- }
- } else if (isset($_GET['action']) && $_GET['action'] == "delete") {
- if (isset($_GET['categoryId']) && $_GET['categoryId'] != "" && $_GET['categoryId'] != 1) {
- $categoryId = $_GET['categoryId'];
- $checkCategory = "SELECT COUNT(*) FROM subscriptions WHERE category_id = :categoryId AND user_id = :userId";
- $checkStmt = $db->prepare($checkCategory);
- $checkStmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
- $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $checkResult = $checkStmt->execute();
- $row = $checkResult->fetchArray();
- $count = $row[0];
-
- if ($count > 0) {
- $response = [
- "success" => false,
- "errorMessage" => translate('category_in_use', $i18n)
+ "message" => translate('failed_remove_category', $i18n)
];
echo json_encode($response);
- } else {
- $sql = "DELETE FROM categories WHERE id = :categoryId AND user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- if ($result) {
- $response = [
- "success" => true,
- "message" => translate('category_removed', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "errorMessage" => translate('failed_remove_category', $i18n)
- ];
- echo json_encode($response);
- }
}
- } else {
- $response = [
- "success" => false,
- "errorMessage" => translate('failed_remove_category', $i18n)
- ];
- echo json_encode($response);
}
} else {
- echo translate('error', $i18n);
+ $response = [
+ "success" => false,
+ "message" => translate('failed_remove_category', $i18n)
+ ];
+ echo json_encode($response);
}
-} else {
- echo translate('error', $i18n);
}
-?>
\ No newline at end of file
+function handleSortCategories($db, $userId, $i18n)
+{
+ $categories = $_POST['categoryIds'];
+ $order = 2;
+
+ foreach ($categories as $categoryId) {
+ $sql = "UPDATE categories SET `order` = :order WHERE id = :categoryId AND user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':order', $order, SQLITE3_INTEGER);
+ $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $order++;
+ }
+
+ $response = [
+ "success" => true,
+ "message" => translate("sort_order_saved", $i18n)
+ ];
+ echo json_encode($response);
+}
\ No newline at end of file
diff --git a/endpoints/categories/sort.php b/endpoints/categories/sort.php
deleted file mode 100644
index 68d61f2..0000000
--- a/endpoints/categories/sort.php
+++ /dev/null
@@ -1,33 +0,0 @@
-<?php
-
-require_once '../../includes/connect_endpoint.php';
-
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- $categories = $_POST['categoryIds'];
- $order = 2;
-
- foreach ($categories as $categoryId) {
- $sql = "UPDATE categories SET `order` = :order WHERE id = :categoryId AND user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':order', $order, SQLITE3_INTEGER);
- $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $order++;
- }
-
- $response = [
- "success" => true,
- "message" => translate("sort_order_saved", $i18n)
- ];
- echo json_encode($response);
-} else {
- $response = [
- "success" => false,
- "errorMessage" => translate("session_expired", $i18n)
- ];
- echo json_encode($response);
- die();
-}
-
-?>
\ No newline at end of file
diff --git a/endpoints/currency/add.php b/endpoints/currency/add.php
deleted file mode 100644
index 8e2b8cd..0000000
--- a/endpoints/currency/add.php
+++ /dev/null
@@ -1,33 +0,0 @@
-<?php
-require_once '../../includes/connect_endpoint.php';
-require_once '../../includes/inputvalidation.php';
-
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- $currencyName = "Currency";
- $currencySymbol = "$";
- $currencyCode = "CODE";
- $currencyRate = 1;
- $sqlInsert = "INSERT INTO currencies (name, symbol, code, rate, user_id) VALUES (:name, :symbol, :code, :rate, :userId)";
- $stmtInsert = $db->prepare($sqlInsert);
- $stmtInsert->bindParam(':name', $currencyName, SQLITE3_TEXT);
- $stmtInsert->bindParam(':symbol', $currencySymbol, SQLITE3_TEXT);
- $stmtInsert->bindParam(':code', $currencyCode, SQLITE3_TEXT);
- $stmtInsert->bindParam(':rate', $currencyRate, SQLITE3_TEXT);
- $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $resultInsert = $stmtInsert->execute();
-
- if ($resultInsert) {
- $currencyId = $db->lastInsertRowID();
- echo $currencyId;
- } else {
- echo translate('error_adding_currency', $i18n);
- }
-} else {
- $response = [
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ];
- echo json_encode($response);
-}
-
-?>
\ No newline at end of file
diff --git a/endpoints/currency/currency.php b/endpoints/currency/currency.php
index f2e30ab..f9f7774 100644
--- a/endpoints/currency/currency.php
+++ b/endpoints/currency/currency.php
@@ -1,129 +1,143 @@
<?php
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if (isset($_GET['action']) && $_GET['action'] == "add") {
- $currencyName = "Currency";
- $currencySymbol = "$";
- $currencyCode = "CODE";
- $currencyRate = 1;
- $sqlInsert = "INSERT INTO currencies (name, symbol, code, rate, user_id) VALUES (:name, :symbol, :code, :rate, :userId)";
- $stmtInsert = $db->prepare($sqlInsert);
- $stmtInsert->bindParam(':name', $currencyName, SQLITE3_TEXT);
- $stmtInsert->bindParam(':symbol', $currencySymbol, SQLITE3_TEXT);
- $stmtInsert->bindParam(':code', $currencyCode, SQLITE3_TEXT);
- $stmtInsert->bindParam(':rate', $currencyRate, SQLITE3_TEXT);
- $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $resultInsert = $stmtInsert->execute();
+$action = $_POST['action'] ?? '';
- if ($resultInsert) {
- $currencyId = $db->lastInsertRowID();
- echo $currencyId;
- } else {
- echo translate('error_adding_currency', $i18n);
- }
- } else if (isset($_GET['action']) && $_GET['action'] == "edit") {
- if (isset($_GET['currencyId']) && $_GET['currencyId'] != "" && isset($_GET['name']) && $_GET['name'] != "" && isset($_GET['symbol']) && $_GET['symbol'] != "") {
- $currencyId = $_GET['currencyId'];
- $name = validate($_GET['name']);
- $symbol = validate($_GET['symbol']);
- $code = validate($_GET['code']);
- $sql = "UPDATE currencies SET name = :name, symbol = :symbol, code = :code WHERE id = :currencyId AND user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':name', $name, SQLITE3_TEXT);
- $stmt->bindParam(':symbol', $symbol, SQLITE3_TEXT);
- $stmt->bindParam(':code', $code, SQLITE3_TEXT);
- $stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+switch ($action) {
+ case "add":
+ handleAddCurrency($db, $userId, $i18n);
+ break;
+ case "edit":
+ handleEditCurrency($db, $userId, $i18n);
+ break;
+ case "delete":
+ handleDeleteCurrency($db, $userId, $i18n);
+ break;
+ default:
+ echo json_encode(["success" => false, "message" => translate('error', $i18n)]);
+ break;
+}
- if ($result) {
- $response = [
- "success" => true,
- "message" => $name . " " . translate('currency_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('failed_to_store_currency', $i18n)
- ];
- echo json_encode($response);
- }
+
+function handleAddCurrency($db, $userId, $i18n)
+{
+ $currencyName = "Currency";
+ $currencySymbol = "$";
+ $currencyCode = "CODE";
+ $currencyRate = 1;
+ $sqlInsert = "INSERT INTO currencies (name, symbol, code, rate, user_id) VALUES (:name, :symbol, :code, :rate, :userId)";
+ $stmtInsert = $db->prepare($sqlInsert);
+ $stmtInsert->bindParam(':name', $currencyName, SQLITE3_TEXT);
+ $stmtInsert->bindParam(':symbol', $currencySymbol, SQLITE3_TEXT);
+ $stmtInsert->bindParam(':code', $currencyCode, SQLITE3_TEXT);
+ $stmtInsert->bindParam(':rate', $currencyRate, SQLITE3_TEXT);
+ $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $resultInsert = $stmtInsert->execute();
+
+ if ($resultInsert) {
+ $currencyId = $db->lastInsertRowID();
+ echo json_encode(["success" => true, "currencyId" => $currencyId]);
+ } else {
+ echo translate('error_adding_currency', $i18n);
+ }
+}
+
+function handleEditCurrency($db, $userId, $i18n)
+{
+ if (isset($_POST['currencyId']) && $_POST['currencyId'] != "" && isset($_POST['name']) && $_POST['name'] != "" && isset($_POST['symbol']) && $_POST['symbol'] != "") {
+ $currencyId = $_POST['currencyId'];
+ $name = validate($_POST['name']);
+ $symbol = validate($_POST['symbol']);
+ $code = validate($_POST['code']);
+ $sql = "UPDATE currencies SET name = :name, symbol = :symbol, code = :code WHERE id = :currencyId AND user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':name', $name, SQLITE3_TEXT);
+ $stmt->bindParam(':symbol', $symbol, SQLITE3_TEXT);
+ $stmt->bindParam(':code', $code, SQLITE3_TEXT);
+ $stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result) {
+ $response = [
+ "success" => true,
+ "message" => $name . " " . translate('currency_saved', $i18n)
+ ];
+ echo json_encode($response);
} else {
$response = [
"success" => false,
- "message" => translate('fields_missing', $i18n)
+ "message" => translate('failed_to_store_currency', $i18n)
];
echo json_encode($response);
}
- } else if (isset($_GET['action']) && $_GET['action'] == "delete") {
- if (isset($_GET['currencyId']) && $_GET['currencyId'] != "") {
- $query = "SELECT main_currency FROM user WHERE id = :userId";
- $stmt = $db->prepare($query);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $mainCurrencyId = $row['main_currency'];
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('fields_missing', $i18n)
+ ];
+ echo json_encode($response);
+ }
+}
- $currencyId = $_GET['currencyId'];
- $checkQuery = "SELECT COUNT(*) FROM subscriptions WHERE currency_id = :currencyId AND user_id = :userId";
- $checkStmt = $db->prepare($checkQuery);
- $checkStmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
- $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $checkResult = $checkStmt->execute();
- $row = $checkResult->fetchArray();
- $count = $row[0];
+function handleDeleteCurrency($db, $userId, $i18n)
+{
+ if (isset($_POST['currencyId']) && $_POST['currencyId'] != "") {
+ $query = "SELECT main_currency FROM user WHERE id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $mainCurrencyId = $row['main_currency'];
- if ($count > 0) {
+ $currencyId = $_POST['currencyId'];
+ $checkQuery = "SELECT COUNT(*) FROM subscriptions WHERE currency_id = :currencyId AND user_id = :userId";
+ $checkStmt = $db->prepare($checkQuery);
+ $checkStmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
+ $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $checkResult = $checkStmt->execute();
+ $row = $checkResult->fetchArray();
+ $count = $row[0];
+
+ if ($count > 0) {
+ $response = [
+ "success" => false,
+ "message" => translate('currency_in_use', $i18n)
+ ];
+ echo json_encode($response);
+ exit;
+ } else {
+ if ($currencyId == $mainCurrencyId) {
$response = [
"success" => false,
- "message" => translate('currency_in_use', $i18n)
+ "message" => translate('currency_is_main', $i18n)
];
echo json_encode($response);
exit;
} else {
- if ($currencyId == $mainCurrencyId) {
+ $sql = "DELETE FROM currencies WHERE id = :currencyId AND user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ if ($result) {
+ echo json_encode(["success" => true, "message" => translate('currency_removed', $i18n)]);
+ } else {
$response = [
"success" => false,
- "message" => translate('currency_is_main', $i18n)
+ "message" => translate('failed_to_remove_currency', $i18n)
];
echo json_encode($response);
- exit;
- } else {
- $sql = "DELETE FROM currencies WHERE id = :currencyId AND user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- if ($result) {
- echo json_encode(["success" => true, "message" => translate('currency_removed', $i18n)]);
- } else {
- $response = [
- "success" => false,
- "message" => translate('failed_to_remove_currency', $i18n)
- ];
- echo json_encode($response);
- }
}
}
- } else {
- $response = [
- "success" => false,
- "message" => translate('fields_missing', $i18n)
- ];
- echo json_encode($response);
}
} else {
- echo "Error";
+ $response = [
+ "success" => false,
+ "message" => translate('fields_missing', $i18n)
+ ];
+ echo json_encode($response);
}
-} else {
- $response = [
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ];
- echo json_encode($response);
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/currency/edit.php b/endpoints/currency/edit.php
deleted file mode 100644
index a40cc24..0000000
--- a/endpoints/currency/edit.php
+++ /dev/null
@@ -1,48 +0,0 @@
-<?php
-require_once '../../includes/connect_endpoint.php';
-require_once '../../includes/inputvalidation.php';
-
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if (isset($_GET['currencyId']) && $_GET['currencyId'] != "" && isset($_GET['name']) && $_GET['name'] != "" && isset($_GET['symbol']) && $_GET['symbol'] != "") {
- $currencyId = $_GET['currencyId'];
- $name = validate($_GET['name']);
- $symbol = validate($_GET['symbol']);
- $code = validate($_GET['code']);
- $sql = "UPDATE currencies SET name = :name, symbol = :symbol, code = :code WHERE id = :currencyId AND user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':name', $name, SQLITE3_TEXT);
- $stmt->bindParam(':symbol', $symbol, SQLITE3_TEXT);
- $stmt->bindParam(':code', $code, SQLITE3_TEXT);
- $stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- if ($result) {
- $response = [
- "success" => true,
- "message" => $name . " " . translate('currency_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('failed_to_store_currency', $i18n)
- ];
- echo json_encode($response);
- }
- } else {
- $response = [
- "success" => false,
- "message" => translate('fields_missing', $i18n)
- ];
- echo json_encode($response);
- }
-} else {
- $response = [
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ];
- echo json_encode($response);
-}
-
-?>
\ No newline at end of file
diff --git a/endpoints/currency/fixer_api_key.php b/endpoints/currency/fixer_api_key.php
index 4f40f06..5059d16 100644
--- a/endpoints/currency/fixer_api_key.php
+++ b/endpoints/currency/fixer_api_key.php
@@ -1,59 +1,54 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $newApiKey = isset($_POST["api_key"]) ? trim($_POST["api_key"]) : "";
- $provider = isset($_POST["provider"]) ? $_POST["provider"] : 0;
+$newApiKey = isset($_POST["api_key"]) ? trim($_POST["api_key"]) : "";
+$provider = isset($_POST["provider"]) ? $_POST["provider"] : 0;
- $removeOldKey = "DELETE FROM fixer WHERE user_id = :userId";
- $stmt = $db->prepare($removeOldKey);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $stmt->execute();
+$removeOldKey = "DELETE FROM fixer WHERE user_id = :userId";
+$stmt = $db->prepare($removeOldKey);
+$stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+$stmt->execute();
- if ($provider == 1) {
- $testKeyUrl = "https://api.apilayer.com/fixer/latest?base=USD&symbols=EUR";
- $context = stream_context_create([
- 'http' => [
- 'method' => 'GET',
- 'header' => 'apikey: ' . $newApiKey,
- ]
- ]);
- $response = file_get_contents($testKeyUrl, false, $context);
- } else {
- $testKeyUrl = "http://data.fixer.io/api/latest?access_key=$newApiKey";
- $response = file_get_contents($testKeyUrl);
- }
+if ($provider == 1) {
+ $testKeyUrl = "https://api.apilayer.com/fixer/latest?base=USD&symbols=EUR";
+ $context = stream_context_create([
+ 'http' => [
+ 'method' => 'GET',
+ 'header' => 'apikey: ' . $newApiKey,
+ ]
+ ]);
+ $response = file_get_contents($testKeyUrl, false, $context);
+} else {
+ $testKeyUrl = "http://data.fixer.io/api/latest?access_key=$newApiKey";
+ $response = file_get_contents($testKeyUrl);
+}
- $apiData = json_decode($response, true);
- if ($apiData['success'] && $apiData['success'] == 1) {
- if (!empty($newApiKey)) {
- $insertNewKey = "INSERT INTO fixer (api_key, provider, user_id) VALUES (:api_key, :provider, :userId)";
- $stmt = $db->prepare($insertNewKey);
- $stmt->bindParam(":api_key", $newApiKey, SQLITE3_TEXT);
- $stmt->bindParam(":provider", $provider, SQLITE3_INTEGER);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- if ($result) {
- echo json_encode(["success" => true, "message" => translate('api_key_saved', $i18n)]);
- } else {
- $response = [
- "success" => false,
- "message" => translate('failed_to_store_api_key', $i18n)
- ];
- echo json_encode($response);
- }
- } else {
- echo json_encode(["success" => true, "message" => translate('apy_key_saved', $i18n)]);
- }
+$apiData = json_decode($response, true);
+if ($apiData['success'] && $apiData['success'] == 1) {
+ if (!empty($newApiKey)) {
+ $insertNewKey = "INSERT INTO fixer (api_key, provider, user_id) VALUES (:api_key, :provider, :userId)";
+ $stmt = $db->prepare($insertNewKey);
+ $stmt->bindParam(":api_key", $newApiKey, SQLITE3_TEXT);
+ $stmt->bindParam(":provider", $provider, SQLITE3_INTEGER);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ if ($result) {
+ echo json_encode(["success" => true, "message" => translate('api_key_saved', $i18n)]);
} else {
$response = [
"success" => false,
- "message" => translate('invalid_api_key', $i18n)
+ "message" => translate('failed_to_store_api_key', $i18n)
];
echo json_encode($response);
}
+ } else {
+ echo json_encode(["success" => true, "message" => translate('apy_key_saved', $i18n)]);
}
-}
-
-?>
\ No newline at end of file
+} else {
+ $response = [
+ "success" => false,
+ "message" => translate('invalid_api_key', $i18n)
+ ];
+ echo json_encode($response);
+}
\ No newline at end of file
diff --git a/endpoints/currency/remove.php b/endpoints/currency/remove.php
deleted file mode 100644
index a836831..0000000
--- a/endpoints/currency/remove.php
+++ /dev/null
@@ -1,70 +0,0 @@
-<?php
-require_once '../../includes/connect_endpoint.php';
-require_once '../../includes/inputvalidation.php';
-
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if (isset($_GET['currencyId']) && $_GET['currencyId'] != "") {
- $query = "SELECT main_currency FROM user WHERE id = :userId";
- $stmt = $db->prepare($query);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $mainCurrencyId = $row['main_currency'];
-
- $currencyId = $_GET['currencyId'];
- $checkQuery = "SELECT COUNT(*) FROM subscriptions WHERE currency_id = :currencyId AND user_id = :userId";
- $checkStmt = $db->prepare($checkQuery);
- $checkStmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
- $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $checkResult = $checkStmt->execute();
- $row = $checkResult->fetchArray();
- $count = $row[0];
-
- if ($count > 0) {
- $response = [
- "success" => false,
- "message" => translate('currency_in_use', $i18n)
- ];
- echo json_encode($response);
- exit;
- } else {
- if ($currencyId == $mainCurrencyId) {
- $response = [
- "success" => false,
- "message" => translate('currency_is_main', $i18n)
- ];
- echo json_encode($response);
- exit;
- } else {
- $sql = "DELETE FROM currencies WHERE id = :currencyId AND user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- if ($result) {
- echo json_encode(["success" => true, "message" => translate('currency_removed', $i18n)]);
- } else {
- $response = [
- "success" => false,
- "message" => translate('failed_to_remove_currency', $i18n)
- ];
- echo json_encode($response);
- }
- }
- }
- } else {
- $response = [
- "success" => false,
- "message" => translate('fields_missing', $i18n)
- ];
- echo json_encode($response);
- }
-} else {
- $response = [
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ];
- echo json_encode($response);
-}
-
-?>
\ No newline at end of file
diff --git a/endpoints/currency/update_exchange.php b/endpoints/currency/update_exchange.php
index 1ce46a2..494dfc6 100644
--- a/endpoints/currency/update_exchange.php
+++ b/endpoints/currency/update_exchange.php
@@ -1,9 +1,10 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
$shouldUpdate = true;
-if (isset($_GET['force']) && $_GET['force'] === "true") {
+if (isset($_POST['force']) && $_POST['force'] === "true") {
$shouldUpdate = true;
} else {
$query = "SELECT date FROM last_exchange_update WHERE user_id = :userId";
@@ -107,5 +108,4 @@ if ($result) {
} else {
echo "Exchange rates update skipped. No fixer.io api key provided";
$apiKey = null;
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/db/backup.php b/endpoints/db/backup.php
index f27c5cf..34e94e7 100644
--- a/endpoints/db/backup.php
+++ b/endpoints/db/backup.php
@@ -1,12 +1,6 @@
<?php
require_once '../../includes/connect_endpoint.php';
-
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+require_once '../../includes/validate_endpoint_admin.php';
function addFolderToZip($dir, $zipArchive, $zipdir = '')
{
@@ -67,7 +61,4 @@ if ($zip->close() === false) {
"numFiles" => $numberOfFilesAdded,
"file" => $filename
]));
-}
-
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/db/restore.php b/endpoints/db/restore.php
index 1fd8b41..174c561 100644
--- a/endpoints/db/restore.php
+++ b/endpoints/db/restore.php
@@ -1,21 +1,9 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint_admin.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-if ($userId !== 1) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
-}
-
-function emptyRestoreFolder() {
+function emptyRestoreFolder()
+{
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('../../.tmp', RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
@@ -27,96 +15,88 @@ function emptyRestoreFolder() {
}
}
-if ($_SERVER['REQUEST_METHOD'] === 'POST') {
- if (isset($_FILES['file'])) {
- $file = $_FILES['file'];
- $fileTmpName = $file['tmp_name'];
- $fileError = $file['error'];
-
- if ($fileError === 0) {
- $fileDestination = '../../.tmp/restore.zip';
- move_uploaded_file($fileTmpName, $fileDestination);
-
- $zip = new ZipArchive();
- if ($zip->open($fileDestination) === true) {
- $zip->extractTo('../../.tmp/restore/');
- $zip->close();
- } else {
- die(json_encode([
- "success" => false,
- "message" => "Failed to extract the uploaded file"
- ]));
- }
+if (isset($_FILES['file'])) {
+ $file = $_FILES['file'];
+ $fileTmpName = $file['tmp_name'];
+ $fileError = $file['error'];
- if (file_exists('../../.tmp/restore/wallos.db')) {
- if (file_exists('../../db/wallos.db')) {
- unlink('../../db/wallos.db');
- }
- rename('../../.tmp/restore/wallos.db', '../../db/wallos.db');
-
- if (file_exists('../../.tmp/restore/logos/')) {
- $dir = '../../images/uploads/logos/';
- $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
- $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
-
- foreach ($ri as $file) {
- if ($file->isDir()) {
- rmdir($file->getPathname());
- } else {
- unlink($file->getPathname());
- }
- }
-
- $dir = new RecursiveDirectoryIterator('../../.tmp/restore/logos/');
- $ite = new RecursiveIteratorIterator($dir);
- $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp'];
-
- foreach ($ite as $filePath) {
- if (in_array(pathinfo($filePath, PATHINFO_EXTENSION), $allowedExtensions)) {
- $destination = str_replace('../../.tmp/restore/', '../../images/uploads/', $filePath);
- $destinationDir = pathinfo($destination, PATHINFO_DIRNAME);
+ if ($fileError === 0) {
+ $fileDestination = '../../.tmp/restore.zip';
+ move_uploaded_file($fileTmpName, $fileDestination);
- if (!is_dir($destinationDir)) {
- mkdir($destinationDir, 0755, true);
- }
+ $zip = new ZipArchive();
+ if ($zip->open($fileDestination) === true) {
+ $zip->extractTo('../../.tmp/restore/');
+ $zip->close();
+ } else {
+ die(json_encode([
+ "success" => false,
+ "message" => "Failed to extract the uploaded file"
+ ]));
+ }
- copy($filePath, $destination);
- }
+ if (file_exists('../../.tmp/restore/wallos.db')) {
+ if (file_exists('../../db/wallos.db')) {
+ unlink('../../db/wallos.db');
+ }
+ rename('../../.tmp/restore/wallos.db', '../../db/wallos.db');
+
+ if (file_exists('../../.tmp/restore/logos/')) {
+ $dir = '../../images/uploads/logos/';
+ $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
+ $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
+
+ foreach ($ri as $file) {
+ if ($file->isDir()) {
+ rmdir($file->getPathname());
+ } else {
+ unlink($file->getPathname());
}
}
- emptyRestoreFolder();
+ $dir = new RecursiveDirectoryIterator('../../.tmp/restore/logos/');
+ $ite = new RecursiveIteratorIterator($dir);
+ $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp'];
- echo json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]);
- } else {
- emptyRestoreFolder();
+ foreach ($ite as $filePath) {
+ if (in_array(pathinfo($filePath, PATHINFO_EXTENSION), $allowedExtensions)) {
+ $destination = str_replace('../../.tmp/restore/', '../../images/uploads/', $filePath);
+ $destinationDir = pathinfo($destination, PATHINFO_DIRNAME);
+
+ if (!is_dir($destinationDir)) {
+ mkdir($destinationDir, 0755, true);
+ }
- die(json_encode([
- "success" => false,
- "message" => "wallos.db does not exist in the backup file"
- ]));
+ copy($filePath, $destination);
+ }
+ }
}
+ emptyRestoreFolder();
- } else {
echo json_encode([
- "success" => false,
- "message" => "Failed to upload file"
+ "success" => true,
+ "message" => translate("success", $i18n)
]);
+ } else {
+ emptyRestoreFolder();
+
+ die(json_encode([
+ "success" => false,
+ "message" => "wallos.db does not exist in the backup file"
+ ]));
}
+
+
} else {
echo json_encode([
"success" => false,
- "message" => "No file uploaded"
+ "message" => "Failed to upload file"
]);
}
} else {
echo json_encode([
"success" => false,
- "message" => "Invalid request method"
+ "message" => "No file uploaded"
]);
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/household/household.php b/endpoints/household/household.php
index d82861f..520a911 100644
--- a/endpoints/household/household.php
+++ b/endpoints/household/household.php
@@ -1,113 +1,132 @@
<?php
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if (isset($_GET['action']) && $_GET['action'] == "add") {
- $householdName = "Member";
- $sqlInsert = "INSERT INTO household (name, user_id) VALUES (:name, :userId)";
- $stmtInsert = $db->prepare($sqlInsert);
- $stmtInsert->bindParam(':name', $householdName, SQLITE3_TEXT);
- $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $resultInsert = $stmtInsert->execute();
+$action = $_POST['action'] ?? '';
- if ($resultInsert) {
- $householdId = $db->lastInsertRowID();
+switch ($action) {
+ case 'add':
+ handleAddMember($db, $userId, $i18n);
+ break;
+ case 'edit':
+ handleEditMember($db, $userId, $i18n);
+ break;
+ case 'delete':
+ handleDeleteMember($db, $userId, $i18n);
+ break;
+ default:
+ echo translate('error', $i18n);
+ break;
+}
+
+function handleAddMember($db, $userId, $i18n)
+{
+ $householdName = "Member";
+ $sqlInsert = "INSERT INTO household (name, user_id) VALUES (:name, :userId)";
+ $stmtInsert = $db->prepare($sqlInsert);
+ $stmtInsert->bindParam(':name', $householdName, SQLITE3_TEXT);
+ $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $resultInsert = $stmtInsert->execute();
+
+ if ($resultInsert) {
+ $householdId = $db->lastInsertRowID();
+ $response = [
+ "success" => true,
+ "householdId" => $householdId,
+ ];
+ echo json_encode($response);
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('failed_add_household', $i18n)
+ ];
+ echo json_encode($response);
+ }
+}
+
+function handleEditMember($db, $userId, $i18n)
+{
+ if (isset($_POST['memberId']) && $_POST['memberId'] != "" && isset($_POST['name']) && $_POST['name'] != "") {
+ $memberId = $_POST['memberId'];
+ $name = validate($_POST['name']);
+ $email = $_POST['email'] ? $_POST['email'] : "";
+ $email = validate($email);
+ $sql = "UPDATE household SET name = :name, email = :email WHERE id = :memberId AND user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':name', $name, SQLITE3_TEXT);
+ $stmt->bindParam(':email', $email, SQLITE3_TEXT);
+ $stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result) {
$response = [
"success" => true,
- "householdId" => $householdId,
+ "message" => translate('member_saved', $i18n)
];
echo json_encode($response);
} else {
$response = [
"success" => false,
- "errorMessage" => translate('failed_add_household', $i18n)
+ "message" => translate('failed_edit_household', $i18n)
];
echo json_encode($response);
}
- } else if (isset($_GET['action']) && $_GET['action'] == "edit") {
- if (isset($_GET['memberId']) && $_GET['memberId'] != "" && isset($_GET['name']) && $_GET['name'] != "") {
- $memberId = $_GET['memberId'];
- $name = validate($_GET['name']);
- $email = $_GET['email'] ? $_GET['email'] : "";
- $email = validate($email);
- $sql = "UPDATE household SET name = :name, email = :email WHERE id = :memberId AND user_id = :userId";
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_all_fields', $i18n)
+ ];
+ echo json_encode($response);
+ }
+}
+
+function handleDeleteMember($db, $userId, $i18n)
+{
+ if (isset($_POST['memberId']) && $_POST['memberId'] != "" && $_POST['memberId'] != 1) {
+ $memberId = $_POST['memberId'];
+ $checkMember = "SELECT COUNT(*) FROM subscriptions WHERE payer_user_id = :memberId AND user_id = :userId";
+ $checkStmt = $db->prepare($checkMember);
+ $checkStmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);
+ $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $checkResult = $checkStmt->execute();
+ $row = $checkResult->fetchArray();
+ $count = $row[0];
+
+ if ($count > 0) {
+ $response = [
+ "success" => false,
+ "message" => translate('household_in_use', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
+ $sql = "DELETE FROM household WHERE id = :memberId and user_id = :userId";
$stmt = $db->prepare($sql);
- $stmt->bindParam(':name', $name, SQLITE3_TEXT);
- $stmt->bindParam(':email', $email, SQLITE3_TEXT);
$stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);
$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
$result = $stmt->execute();
-
if ($result) {
$response = [
"success" => true,
- "message" => translate('member_saved', $i18n)
+ "message" => translate('member_removed', $i18n)
];
echo json_encode($response);
} else {
$response = [
"success" => false,
- "errorMessage" => translate('failed_edit_household', $i18n)
+ "message" => translate('failed_remove_household', $i18n)
];
echo json_encode($response);
}
- } else {
- $response = [
- "success" => false,
- "errorMessage" => translate('fill_all_fields', $i18n)
- ];
- echo json_encode($response);
- }
- } else if (isset($_GET['action']) && $_GET['action'] == "delete") {
- if (isset($_GET['memberId']) && $_GET['memberId'] != "" && $_GET['memberId'] != 1) {
- $memberId = $_GET['memberId'];
- $checkMember = "SELECT COUNT(*) FROM subscriptions WHERE payer_user_id = :memberId AND user_id = :userId";
- $checkStmt = $db->prepare($checkMember);
- $checkStmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);
- $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $checkResult = $checkStmt->execute();
- $row = $checkResult->fetchArray();
- $count = $row[0];
-
- if ($count > 0) {
- $response = [
- "success" => false,
- "errorMessage" => translate('household_in_use', $i18n)
- ];
- echo json_encode($response);
- } else {
- $sql = "DELETE FROM household WHERE id = :memberId and user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- if ($result) {
- $response = [
- "success" => true,
- "message" => translate('member_removed', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "errorMessage" => translate('failed_remove_household', $i18n)
- ];
- echo json_encode($response);
- }
- }
- } else {
- $response = [
- "success" => false,
- "errorMessage" => translate('failed_remove_household', $i18n)
- ];
- echo json_encode($response);
}
} else {
- echo translate('error', $i18n);
+ $response = [
+ "success" => false,
+ "message" => translate('failed_remove_household', $i18n)
+ ];
+ echo json_encode($response);
}
-} else {
- echo translate('error', $i18n);
}
?>
\ No newline at end of file
diff --git a/endpoints/notifications/savediscordnotifications.php b/endpoints/notifications/savediscordnotifications.php
index 9eb2e91..1a3a2e1 100644
--- a/endpoints/notifications/savediscordnotifications.php
+++ b/endpoints/notifications/savediscordnotifications.php
@@ -1,77 +1,67 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["url"]) || $data["url"] == ""
+) {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $enabled = $data["enabled"];
+ $webhook_url = $data["url"];
+ $bot_username = $data["bot_username"];
+ $bot_avatar_url = $data["bot_avatar"];
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $query = "SELECT COUNT(*) FROM discord_notifications WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
- if (
- !isset($data["url"]) || $data["url"] == ""
- ) {
+ if ($result === false) {
$response = [
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
+ "message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
- $enabled = $data["enabled"];
- $webhook_url = $data["url"];
- $bot_username = $data["bot_username"];
- $bot_avatar_url = $data["bot_avatar"];
+ $row = $result->fetchArray();
+ $count = $row[0];
+ if ($count == 0) {
+ $query = "INSERT INTO discord_notifications (enabled, webhook_url, bot_username, bot_avatar_url, user_id)
+ VALUES (:enabled, :webhook_url, :bot_username, :bot_avatar_url, :userId)";
+ } else {
+ $query = "UPDATE discord_notifications
+ SET enabled = :enabled, webhook_url = :webhook_url, bot_username = :bot_username, bot_avatar_url = :bot_avatar_url
+ WHERE user_id = :userId";
+ }
- $query = "SELECT COUNT(*) FROM discord_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
+ $stmt->bindValue(':webhook_url', $webhook_url, SQLITE3_TEXT);
+ $stmt->bindValue(':bot_username', $bot_username, SQLITE3_TEXT);
+ $stmt->bindValue(':bot_avatar_url', $bot_avatar_url, SQLITE3_TEXT);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- if ($result === false) {
+ if ($stmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notifications_settings_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
- } else {
- $row = $result->fetchArray();
- $count = $row[0];
- if ($count == 0) {
- $query = "INSERT INTO discord_notifications (enabled, webhook_url, bot_username, bot_avatar_url, user_id)
- VALUES (:enabled, :webhook_url, :bot_username, :bot_avatar_url, :userId)";
- } else {
- $query = "UPDATE discord_notifications
- SET enabled = :enabled, webhook_url = :webhook_url, bot_username = :bot_username, bot_avatar_url = :bot_avatar_url
- WHERE user_id = :userId";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
- $stmt->bindValue(':webhook_url', $webhook_url, SQLITE3_TEXT);
- $stmt->bindValue(':bot_username', $bot_username, SQLITE3_TEXT);
- $stmt->bindValue(':bot_avatar_url', $bot_avatar_url, SQLITE3_TEXT);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('notifications_settings_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_saving_notifications', $i18n)
- ];
- echo json_encode($response);
- }
}
}
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/saveemailnotifications.php b/endpoints/notifications/saveemailnotifications.php
index a2e5fbe..e090726 100644
--- a/endpoints/notifications/saveemailnotifications.php
+++ b/endpoints/notifications/saveemailnotifications.php
@@ -1,87 +1,78 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["smtpaddress"]) || $data["smtpaddress"] == "" ||
+ !isset($data["smtpport"]) || $data["smtpport"] == ""
+) {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $enabled = $data["enabled"];
+ $smtpAddress = $data["smtpaddress"];
+ $smtpPort = $data["smtpport"];
+ $encryption = "tls";
+ if (isset($data["encryption"])) {
+ $encryption = $data["encryption"];
+ }
+ $smtpUsername = $data["smtpusername"];
+ $smtpPassword = $data["smtppassword"];
+ $fromEmail = $data["fromemail"];
+ $otherEmails = $data["otheremails"];
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $query = "SELECT COUNT(*) FROM email_notifications WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
- if (
- !isset($data["smtpaddress"]) || $data["smtpaddress"] == "" ||
- !isset($data["smtpport"]) || $data["smtpport"] == ""
- ) {
+ if ($result === false) {
$response = [
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
+ "message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
- $enabled = $data["enabled"];
- $smtpAddress = $data["smtpaddress"];
- $smtpPort = $data["smtpport"];
- $encryption = "tls";
- if (isset($data["encryption"])) {
- $encryption = $data["encryption"];
+ $row = $result->fetchArray();
+ $count = $row[0];
+ if ($count == 0) {
+ $query = "INSERT INTO email_notifications (enabled, smtp_address, smtp_port, smtp_username, smtp_password, from_email, other_emails, encryption, user_id)
+ VALUES (:enabled, :smtpAddress, :smtpPort, :smtpUsername, :smtpPassword, :fromEmail, :otherEmails, :encryption, :userId)";
+ } else {
+ $query = "UPDATE email_notifications
+ SET enabled = :enabled, smtp_address = :smtpAddress, smtp_port = :smtpPort,
+ smtp_username = :smtpUsername, smtp_password = :smtpPassword, from_email = :fromEmail, other_emails = :otherEmails, encryption = :encryption WHERE user_id = :userId";
}
- $smtpUsername = $data["smtpusername"];
- $smtpPassword = $data["smtppassword"];
- $fromEmail = $data["fromemail"];
- $otherEmails = $data["otheremails"];
- $query = "SELECT COUNT(*) FROM email_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
+ $stmt->bindValue(':smtpAddress', $smtpAddress, SQLITE3_TEXT);
+ $stmt->bindValue(':smtpPort', $smtpPort, SQLITE3_INTEGER);
+ $stmt->bindValue(':smtpUsername', $smtpUsername, SQLITE3_TEXT);
+ $stmt->bindValue(':smtpPassword', $smtpPassword, SQLITE3_TEXT);
+ $stmt->bindValue(':fromEmail', $fromEmail, SQLITE3_TEXT);
+ $stmt->bindValue(':otherEmails', $otherEmails, SQLITE3_TEXT);
+ $stmt->bindValue(':encryption', $encryption, SQLITE3_TEXT);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- if ($result === false) {
+ if ($stmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notifications_settings_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
- } else {
- $row = $result->fetchArray();
- $count = $row[0];
- if ($count == 0) {
- $query = "INSERT INTO email_notifications (enabled, smtp_address, smtp_port, smtp_username, smtp_password, from_email, other_emails, encryption, user_id)
- VALUES (:enabled, :smtpAddress, :smtpPort, :smtpUsername, :smtpPassword, :fromEmail, :otherEmails, :encryption, :userId)";
- } else {
- $query = "UPDATE email_notifications
- SET enabled = :enabled, smtp_address = :smtpAddress, smtp_port = :smtpPort,
- smtp_username = :smtpUsername, smtp_password = :smtpPassword, from_email = :fromEmail, other_emails = :otherEmails, encryption = :encryption WHERE user_id = :userId";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
- $stmt->bindValue(':smtpAddress', $smtpAddress, SQLITE3_TEXT);
- $stmt->bindValue(':smtpPort', $smtpPort, SQLITE3_INTEGER);
- $stmt->bindValue(':smtpUsername', $smtpUsername, SQLITE3_TEXT);
- $stmt->bindValue(':smtpPassword', $smtpPassword, SQLITE3_TEXT);
- $stmt->bindValue(':fromEmail', $fromEmail, SQLITE3_TEXT);
- $stmt->bindValue(':otherEmails', $otherEmails, SQLITE3_TEXT);
- $stmt->bindValue(':encryption', $encryption, SQLITE3_TEXT);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('notifications_settings_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_saving_notifications', $i18n)
- ];
- echo json_encode($response);
- }
}
}
-}
-?>
+}
\ No newline at end of file
diff --git a/endpoints/notifications/savegotifynotifications.php b/endpoints/notifications/savegotifynotifications.php
index b97b7ef..bd452cf 100644
--- a/endpoints/notifications/savegotifynotifications.php
+++ b/endpoints/notifications/savegotifynotifications.php
@@ -1,88 +1,80 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["gotify_url"]) || $data["gotify_url"] == "" ||
+ !isset($data["token"]) || $data["token"] == ""
+) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $enabled = $data["enabled"];
+ $url = $data["gotify_url"];
+ $token = $data["token"];
+ $ignore_ssl = $data["ignore_ssl"];
+ // Validate URL scheme
+ $parsedUrl = parse_url($url);
if (
- !isset($data["gotify_url"]) || $data["gotify_url"] == "" ||
- !isset($data["token"]) || $data["token"] == ""
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($url, FILTER_VALIDATE_URL)
) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+ }
+
+ $query = "SELECT COUNT(*) FROM gotify_notifications WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result === false) {
$response = [
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
+ "message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
- $enabled = $data["enabled"];
- $url = $data["gotify_url"];
- $token = $data["token"];
- $ignore_ssl = $data["ignore_ssl"];
-
- // Validate URL scheme
- $parsedUrl = parse_url($url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
+ $row = $result->fetchArray();
+ $count = $row[0];
+ if ($count == 0) {
+ $query = "INSERT INTO gotify_notifications (enabled, url, token, user_id, ignore_ssl)
+ VALUES (:enabled, :url, :token, :userId, :ignore_ssl)";
+ } else {
+ $query = "UPDATE gotify_notifications
+ SET enabled = :enabled, url = :url, token = :token, ignore_ssl = :ignore_ssl WHERE user_id = :userId";
}
- $query = "SELECT COUNT(*) FROM gotify_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
+ $stmt->bindValue(':url', $url, SQLITE3_TEXT);
+ $stmt->bindValue(':token', $token, SQLITE3_TEXT);
+ $stmt->bindValue(':ignore_ssl', $ignore_ssl, SQLITE3_INTEGER);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- if ($result === false) {
+ if ($stmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notifications_settings_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
- } else {
- $row = $result->fetchArray();
- $count = $row[0];
- if ($count == 0) {
- $query = "INSERT INTO gotify_notifications (enabled, url, token, user_id, ignore_ssl)
- VALUES (:enabled, :url, :token, :userId, :ignore_ssl)";
- } else {
- $query = "UPDATE gotify_notifications
- SET enabled = :enabled, url = :url, token = :token, ignore_ssl = :ignore_ssl WHERE user_id = :userId";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
- $stmt->bindValue(':url', $url, SQLITE3_TEXT);
- $stmt->bindValue(':token', $token, SQLITE3_TEXT);
- $stmt->bindValue(':ignore_ssl', $ignore_ssl, SQLITE3_INTEGER);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('notifications_settings_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_saving_notifications', $i18n)
- ];
- echo json_encode($response);
- }
}
}
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/savemattermostnotifications.php b/endpoints/notifications/savemattermostnotifications.php
index 2132b34..6faa2f4 100755
--- a/endpoints/notifications/savemattermostnotifications.php
+++ b/endpoints/notifications/savemattermostnotifications.php
@@ -1,72 +1,63 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (!isset($data["webhook_url"]) || $data["webhook_url"] == "") {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $enabled = $data["enabled"];
+ $webhook_url = $data["webhook_url"];
+ $bot_username = $data["bot_username"];
+ $bot_iconemoji = $data["bot_icon_emoji"];
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $query = "SELECT COUNT(*) FROM mattermost_notifications WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
- if (!isset($data["webhook_url"]) || $data["webhook_url"] == "") {
+ if ($result === false) {
$response = [
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
+ "message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
- $enabled = $data["enabled"];
- $webhook_url = $data["webhook_url"];
- $bot_username = $data["bot_username"];
- $bot_iconemoji = $data["bot_icon_emoji"];
+ $row = $result->fetchArray();
+ $count = $row[0];
+ if ($count == 0) {
+ $query = "INSERT INTO mattermost_notifications (enabled, webhook_url, user_id, bot_username, bot_icon_emoji)
+ VALUES (:enabled, :webhook_url, :userId, :bot_username, :bot_icon_emoji)";
+ } else {
+ $query = "UPDATE mattermost_notifications
+ SET enabled = :enabled, webhook_url = :webhook_url WHERE user_id = :userId";
+ }
- $query = "SELECT COUNT(*) FROM mattermost_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
+ $stmt->bindValue(':webhook_url', $webhook_url, SQLITE3_TEXT);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $stmt->bindValue(':bot_username', $bot_username, SQLITE3_TEXT);
+ $stmt->bindValue(':bot_icon_emoji', $bot_iconemoji, SQLITE3_TEXT);
- if ($result === false) {
+ if ($stmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notifications_settings_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
- } else {
- $row = $result->fetchArray();
- $count = $row[0];
- if ($count == 0) {
- $query = "INSERT INTO mattermost_notifications (enabled, webhook_url, user_id, bot_username, bot_icon_emoji)
- VALUES (:enabled, :webhook_url, :userId, :bot_username, :bot_icon_emoji)";
- } else {
- $query = "UPDATE mattermost_notifications
- SET enabled = :enabled, webhook_url = :webhook_url WHERE user_id = :userId";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
- $stmt->bindValue(':webhook_url', $webhook_url, SQLITE3_TEXT);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $stmt->bindValue(':bot_username', $bot_username, SQLITE3_TEXT);
- $stmt->bindValue(':bot_icon_emoji', $bot_iconemoji, SQLITE3_TEXT);
-
- if ($stmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('notifications_settings_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_saving_notifications', $i18n)
- ];
- echo json_encode($response);
- }
}
}
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/savenotificationsettings.php b/endpoints/notifications/savenotificationsettings.php
index eb88713..b5aa025 100644
--- a/endpoints/notifications/savenotificationsettings.php
+++ b/endpoints/notifications/savenotificationsettings.php
@@ -1,71 +1,56 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+if (!isset($data["days"]) || $data['days'] == "") {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $days = $data["days"];
+ $query = "SELECT COUNT(*) FROM notification_settings WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
- if (!isset($data["days"]) || $data['days'] == "") {
+ if ($result === false) {
$response = [
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
+ "message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
- $days = $data["days"];
- $query = "SELECT COUNT(*) FROM notification_settings WHERE user_id = :userId";
+ $row = $result->fetchArray();
+ $count = $row[0];
+ if ($count == 0) {
+ $query = "INSERT INTO notification_settings (days, user_id)
+ VALUES (:days, :userId)";
+ } else {
+ $query = "UPDATE notification_settings SET days = :days WHERE user_id = :userId";
+ }
+
$stmt = $db->prepare($query);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':days', $days, SQLITE3_INTEGER);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- if ($result === false) {
+ if ($stmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notifications_settings_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
- } else {
- $row = $result->fetchArray();
- $count = $row[0];
- if ($count == 0) {
- $query = "INSERT INTO notification_settings (days, user_id)
- VALUES (:days, :userId)";
- } else {
- $query = "UPDATE notification_settings SET days = :days WHERE user_id = :userId";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindValue(':days', $days, SQLITE3_INTEGER);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('notifications_settings_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_saving_notifications', $i18n)
- ];
- echo json_encode($response);
- }
}
}
-} else {
- $response = [
- "success" => false,
- "message" => "Invalid request method"
- ];
- echo json_encode($response);
- exit();
}
\ No newline at end of file
diff --git a/endpoints/notifications/saventfynotifications.php b/endpoints/notifications/saventfynotifications.php
index 0e3032e..401efa0 100644
--- a/endpoints/notifications/saventfynotifications.php
+++ b/endpoints/notifications/saventfynotifications.php
@@ -1,100 +1,83 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+if (
+ !isset($data["topic"]) || $data["topic"] == "" ||
+ !isset($data["host"]) || $data["host"] == ""
+) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $enabled = $data["enabled"];
+ $host = $data["host"];
+ $topic = $data["topic"];
+ $headers = $data["headers"];
+ $ignore_ssl = $data["ignore_ssl"];
+ $url = rtrim($host, '/') . '/' . ltrim($topic, '/');
+ // Validate URL scheme
+ $parsedUrl = parse_url($url);
if (
- !isset($data["topic"]) || $data["topic"] == "" ||
- !isset($data["host"]) || $data["host"] == ""
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($url, FILTER_VALIDATE_URL)
) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+ }
+
+ $query = "SELECT COUNT(*) FROM ntfy_notifications WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result === false) {
$response = [
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
+ "message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
- $enabled = $data["enabled"];
- $host = $data["host"];
- $topic = $data["topic"];
- $headers = $data["headers"];
- $ignore_ssl = $data["ignore_ssl"];
-
- $url = rtrim($host, '/') . '/' . ltrim($topic, '/');
- // Validate URL scheme
- $parsedUrl = parse_url($url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
+ $row = $result->fetchArray();
+ $count = $row[0];
+ if ($count == 0) {
+ $query = "INSERT INTO ntfy_notifications (enabled, host, topic, headers, user_id, ignore_ssl)
+ VALUES (:enabled, :host, :topic, :headers, :userId, :ignore_ssl)";
+ } else {
+ $query = "UPDATE ntfy_notifications
+ SET enabled = :enabled, host = :host, topic = :topic, headers = :headers, ignore_ssl = :ignore_ssl WHERE user_id = :userId";
}
- $query = "SELECT COUNT(*) FROM ntfy_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
+ $stmt->bindValue(':host', $host, SQLITE3_TEXT);
+ $stmt->bindValue(':topic', $topic, SQLITE3_TEXT);
+ $stmt->bindValue(':headers', $headers, SQLITE3_TEXT);
+ $stmt->bindValue(':ignore_ssl', $ignore_ssl, SQLITE3_INTEGER);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- if ($result === false) {
+ if ($stmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notifications_settings_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
- } else {
- $row = $result->fetchArray();
- $count = $row[0];
- if ($count == 0) {
- $query = "INSERT INTO ntfy_notifications (enabled, host, topic, headers, user_id, ignore_ssl)
- VALUES (:enabled, :host, :topic, :headers, :userId, :ignore_ssl)";
- } else {
- $query = "UPDATE ntfy_notifications
- SET enabled = :enabled, host = :host, topic = :topic, headers = :headers, ignore_ssl = :ignore_ssl WHERE user_id = :userId";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
- $stmt->bindValue(':host', $host, SQLITE3_TEXT);
- $stmt->bindValue(':topic', $topic, SQLITE3_TEXT);
- $stmt->bindValue(':headers', $headers, SQLITE3_TEXT);
- $stmt->bindValue(':ignore_ssl', $ignore_ssl, SQLITE3_INTEGER);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('notifications_settings_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_saving_notifications', $i18n)
- ];
- echo json_encode($response);
- }
}
}
-
-} else {
- $response = [
- "success" => false,
- "message" => translate('invalid_request_method', $i18n)
- ];
- echo json_encode($response);
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/savepushovernotifications.php b/endpoints/notifications/savepushovernotifications.php
index cff844a..22616e1 100644
--- a/endpoints/notifications/savepushovernotifications.php
+++ b/endpoints/notifications/savepushovernotifications.php
@@ -1,81 +1,66 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["user_key"]) || $data["user_key"] == "" ||
+ !isset($data["token"]) || $data["token"] == ""
+) {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $enabled = $data["enabled"];
+ $user_key = $data["user_key"];
+ $token = $data["token"];
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $query = "SELECT COUNT(*) FROM pushover_notifications WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
- if (
- !isset($data["user_key"]) || $data["user_key"] == "" ||
- !isset($data["token"]) || $data["token"] == ""
- ) {
+ if ($result === false) {
$response = [
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
+ "message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
- $enabled = $data["enabled"];
- $user_key = $data["user_key"];
- $token = $data["token"];
+ $row = $result->fetchArray();
+ $count = $row[0];
+ if ($count == 0) {
+ $query = "INSERT INTO pushover_notifications (enabled, user_key, token, user_id)
+ VALUES (:enabled, :user_key, :token, :userId)";
+ } else {
+ $query = "UPDATE pushover_notifications
+ SET enabled = :enabled, user_key = :user_key, token = :token, user_id = :userId";
+ }
- $query = "SELECT COUNT(*) FROM pushover_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
+ $stmt->bindValue(':user_key', $user_key, SQLITE3_TEXT);
+ $stmt->bindValue(':token', $token, SQLITE3_TEXT);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- if ($result === false) {
+ if ($stmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notifications_settings_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
- } else {
- $row = $result->fetchArray();
- $count = $row[0];
- if ($count == 0) {
- $query = "INSERT INTO pushover_notifications (enabled, user_key, token, user_id)
- VALUES (:enabled, :user_key, :token, :userId)";
- } else {
- $query = "UPDATE pushover_notifications
- SET enabled = :enabled, user_key = :user_key, token = :token, user_id = :userId";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
- $stmt->bindValue(':user_key', $user_key, SQLITE3_TEXT);
- $stmt->bindValue(':token', $token, SQLITE3_TEXT);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('notifications_settings_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_saving_notifications', $i18n)
- ];
- echo json_encode($response);
- }
}
}
-} else {
- $response = [
- "success" => false,
- "message" => translate('invalid_request_method', $i18n)
- ];
- echo json_encode($response);
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/savepushplusnotifications.php b/endpoints/notifications/savepushplusnotifications.php
index d12e16b..58ef61c 100644
--- a/endpoints/notifications/savepushplusnotifications.php
+++ b/endpoints/notifications/savepushplusnotifications.php
@@ -1,14 +1,8 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
@@ -63,6 +57,4 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") {
echo json_encode($response);
}
}
- }
-}
-?>
\ No newline at end of file
+ }
\ No newline at end of file
diff --git a/endpoints/notifications/savetelegramnotifications.php b/endpoints/notifications/savetelegramnotifications.php
index 8910386..42fbc51 100644
--- a/endpoints/notifications/savetelegramnotifications.php
+++ b/endpoints/notifications/savetelegramnotifications.php
@@ -1,73 +1,65 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["bot_token"]) || $data["bot_token"] == "" ||
+ !isset($data["chat_id"]) || $data["chat_id"] == ""
+) {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $enabled = $data["enabled"];
+ $bot_token = $data["bot_token"];
+ $chat_id = $data["chat_id"];
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $query = "SELECT COUNT(*) FROM telegram_notifications WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
- if (
- !isset($data["bot_token"]) || $data["bot_token"] == "" ||
- !isset($data["chat_id"]) || $data["chat_id"] == ""
- ) {
+ if ($result === false) {
$response = [
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
+ "message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
- $enabled = $data["enabled"];
- $bot_token = $data["bot_token"];
- $chat_id = $data["chat_id"];
+ $row = $result->fetchArray();
+ $count = $row[0];
+ if ($count == 0) {
+ $query = "INSERT INTO telegram_notifications (enabled, bot_token, chat_id, user_id)
+ VALUES (:enabled, :bot_token, :chat_id, :userId)";
+ } else {
+ $query = "UPDATE telegram_notifications
+ SET enabled = :enabled, bot_token = :bot_token, chat_id = :chat_id WHERE user_id = :userId";
+ }
- $query = "SELECT COUNT(*) FROM telegram_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
+ $stmt->bindValue(':bot_token', $bot_token, SQLITE3_TEXT);
+ $stmt->bindValue(':chat_id', $chat_id, SQLITE3_TEXT);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- if ($result === false) {
+ if ($stmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notifications_settings_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
- } else {
- $row = $result->fetchArray();
- $count = $row[0];
- if ($count == 0) {
- $query = "INSERT INTO telegram_notifications (enabled, bot_token, chat_id, user_id)
- VALUES (:enabled, :bot_token, :chat_id, :userId)";
- } else {
- $query = "UPDATE telegram_notifications
- SET enabled = :enabled, bot_token = :bot_token, chat_id = :chat_id WHERE user_id = :userId";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
- $stmt->bindValue(':bot_token', $bot_token, SQLITE3_TEXT);
- $stmt->bindValue(':chat_id', $chat_id, SQLITE3_TEXT);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('notifications_settings_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_saving_notifications', $i18n)
- ];
- echo json_encode($response);
- }
}
}
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/savewebhooknotifications.php b/endpoints/notifications/savewebhooknotifications.php
index 45c9cd9..cdd5766 100644
--- a/endpoints/notifications/savewebhooknotifications.php
+++ b/endpoints/notifications/savewebhooknotifications.php
@@ -1,91 +1,82 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+if (
+ !isset($data["webhook_url"]) || $data["webhook_url"] == ""
+) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $enabled = $data["enabled"];
+ $url = $data["webhook_url"];
+ $headers = $data["headers"];
+ $payload = $data["payload"];
+ $cancelation_payload = $data["cancelation_payload"];
+ $ignore_ssl = $data["ignore_ssl"];
+ // Validate URL scheme
+ $parsedUrl = parse_url($url);
if (
- !isset($data["webhook_url"]) || $data["webhook_url"] == ""
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($url, FILTER_VALIDATE_URL)
) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+ }
+
+ $query = "SELECT COUNT(*) FROM webhook_notifications WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result === false) {
$response = [
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
+ "message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
} else {
- $enabled = $data["enabled"];
- $url = $data["webhook_url"];
- $headers = $data["headers"];
- $payload = $data["payload"];
- $cancelation_payload = $data["cancelation_payload"];
- $ignore_ssl = $data["ignore_ssl"];
-
- // Validate URL scheme
- $parsedUrl = parse_url($url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
+ $row = $result->fetchArray();
+ $count = $row[0];
+ if ($count == 0) {
+ $query = "INSERT INTO webhook_notifications (enabled, url, headers, payload, cancelation_payload, user_id, ignore_ssl)
+ VALUES (:enabled, :url, :headers, :payload, :cancelation_payload, :userId, :ignore_ssl)";
+ } else {
+ $query = "UPDATE webhook_notifications
+ SET enabled = :enabled, url = :url, headers = :headers, payload = :payload, cancelation_payload = :cancelation_payload, ignore_ssl = :ignore_ssl WHERE user_id = :userId";
}
- $query = "SELECT COUNT(*) FROM webhook_notifications WHERE user_id = :userId";
$stmt = $db->prepare($query);
- $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
+ $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
+ $stmt->bindValue(':url', $url, SQLITE3_TEXT);
+ $stmt->bindValue(':headers', $headers, SQLITE3_TEXT);
+ $stmt->bindValue(':payload', $payload, SQLITE3_TEXT);
+ $stmt->bindValue(':cancelation_payload', $cancelation_payload, SQLITE3_TEXT);
+ $stmt->bindValue(':ignore_ssl', $ignore_ssl, SQLITE3_INTEGER);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- if ($result === false) {
+ if ($stmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notifications_settings_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
$response = [
"success" => false,
"message" => translate('error_saving_notifications', $i18n)
];
echo json_encode($response);
- } else {
- $row = $result->fetchArray();
- $count = $row[0];
- if ($count == 0) {
- $query = "INSERT INTO webhook_notifications (enabled, url, headers, payload, cancelation_payload, user_id, ignore_ssl)
- VALUES (:enabled, :url, :headers, :payload, :cancelation_payload, :userId, :ignore_ssl)";
- } else {
- $query = "UPDATE webhook_notifications
- SET enabled = :enabled, url = :url, headers = :headers, payload = :payload, cancelation_payload = :cancelation_payload, ignore_ssl = :ignore_ssl WHERE user_id = :userId";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER);
- $stmt->bindValue(':url', $url, SQLITE3_TEXT);
- $stmt->bindValue(':headers', $headers, SQLITE3_TEXT);
- $stmt->bindValue(':payload', $payload, SQLITE3_TEXT);
- $stmt->bindValue(':cancelation_payload', $cancelation_payload, SQLITE3_TEXT);
- $stmt->bindValue(':ignore_ssl', $ignore_ssl, SQLITE3_INTEGER);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('notifications_settings_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_saving_notifications', $i18n)
- ];
- echo json_encode($response);
- }
}
}
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/testdiscordnotifications.php b/endpoints/notifications/testdiscordnotifications.php
index a8be959..ef0e42b 100644
--- a/endpoints/notifications/testdiscordnotifications.php
+++ b/endpoints/notifications/testdiscordnotifications.php
@@ -1,102 +1,87 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["url"]) || $data["url"] == ""
+) {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ // Set the message parameters
+ $title = translate('wallos_notification', $i18n);
+ $message = translate('test_notification', $i18n);
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $webhook_url = $data["url"];
+ $bot_username = $data["bot_username"];
+ $bot_avatar_url = $data["bot_avatar"];
+ // Validate URL scheme
+ $parsedUrl = parse_url($webhook_url);
if (
- !isset($data["url"]) || $data["url"] == ""
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($webhook_url, FILTER_VALIDATE_URL)
) {
- $response = [
+ die(json_encode([
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- echo json_encode($response);
- } else {
- // Set the message parameters
- $title = translate('wallos_notification', $i18n);
- $message = translate('test_notification', $i18n);
-
- $webhook_url = $data["url"];
- $bot_username = $data["bot_username"];
- $bot_avatar_url = $data["bot_avatar"];
-
- // Validate URL scheme
- $parsedUrl = parse_url($webhook_url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($webhook_url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
+ "message" => translate("error", $i18n)
+ ]));
+ }
- $postfields = [
- 'content' => $message,
- 'embeds' => [
- [
- 'title' => $title,
- 'description' => $message,
- 'color' => hexdec("FF0000")
- ]
+ $postfields = [
+ 'content' => $message,
+ 'embeds' => [
+ [
+ 'title' => $title,
+ 'description' => $message,
+ 'color' => hexdec("FF0000")
]
- ];
+ ]
+ ];
- if (!empty($bot_username)) {
- $postfields['username'] = $bot_username;
- }
+ if (!empty($bot_username)) {
+ $postfields['username'] = $bot_username;
+ }
- if (!empty($bot_avatar_url)) {
- $postfields['avatar_url'] = $bot_avatar_url;
- }
+ if (!empty($bot_avatar_url)) {
+ $postfields['avatar_url'] = $bot_avatar_url;
+ }
- $ch = curl_init();
+ $ch = curl_init();
- // Set the URL and other options
- curl_setopt($ch, CURLOPT_URL, $webhook_url);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postfields));
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json'
- ]);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ // Set the URL and other options
+ curl_setopt($ch, CURLOPT_URL, $webhook_url);
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postfields));
+ curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Content-Type: application/json'
+ ]);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // Execute the request
- $response = curl_exec($ch);
+ // Execute the request
+ $response = curl_exec($ch);
- // Close the cURL session
- curl_close($ch);
+ // Close the cURL session
+ curl_close($ch);
- // Check if the message was sent successfully
- if ($response === false) {
- die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n)
- ]));
- }
+ // Check if the message was sent successfully
+ if ($response === false) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('notification_failed', $i18n)
+ ]));
+ } else {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n)
+ ]));
}
-} else {
- die(json_encode([
- "success" => false,
- "message" => translate("invalid_request_method", $i18n)
- ]));
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/testemailnotifications.php b/endpoints/notifications/testemailnotifications.php
index b5c76c4..f921bec 100644
--- a/endpoints/notifications/testemailnotifications.php
+++ b/endpoints/notifications/testemailnotifications.php
@@ -5,98 +5,88 @@ use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["smtpaddress"]) || $data["smtpaddress"] == "" ||
+ !isset($data["smtpport"]) || $data["smtpport"] == ""
+) {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- if (
- !isset($data["smtpaddress"]) || $data["smtpaddress"] == "" ||
- !isset($data["smtpport"]) || $data["smtpport"] == ""
- ) {
- $response = [
- "success" => false,
- "message" => translate('fill_all_fields', $i18n)
- ];
- die(json_encode($response));
- } else {
- $encryption = "none";
- if (isset($data["encryption"])) {
- $encryption = $data["encryption"];
- }
+ "message" => translate('fill_all_fields', $i18n)
+ ];
+ die(json_encode($response));
+} else {
+ $encryption = "none";
+ if (isset($data["encryption"])) {
+ $encryption = $data["encryption"];
+ }
- $smtpAuth = (isset($data["smtpusername"]) && $data["smtpusername"] != "") || (isset($data["smtppassword"]) && $data["smtppassword"] != "");
+ $smtpAuth = (isset($data["smtpusername"]) && $data["smtpusername"] != "") || (isset($data["smtppassword"]) && $data["smtppassword"] != "");
- require '../../libs/PHPMailer/PHPMailer.php';
- require '../../libs/PHPMailer/SMTP.php';
- require '../../libs/PHPMailer/Exception.php';
+ require '../../libs/PHPMailer/PHPMailer.php';
+ require '../../libs/PHPMailer/SMTP.php';
+ require '../../libs/PHPMailer/Exception.php';
- $smtpAddress = $data["smtpaddress"];
- $smtpPort = $data["smtpport"];
- $smtpUsername = $data["smtpusername"];
- $smtpPassword = $data["smtppassword"];
- $fromEmail = $data["fromemail"] ? $data['fromemail'] : "[email protected]";
+ $smtpAddress = $data["smtpaddress"];
+ $smtpPort = $data["smtpport"];
+ $smtpUsername = $data["smtpusername"];
+ $smtpPassword = $data["smtppassword"];
+ $fromEmail = $data["fromemail"] ? $data['fromemail'] : "[email protected]";
- $mail = new PHPMailer(true);
- $mail->CharSet = "UTF-8";
- $mail->isSMTP();
+ $mail = new PHPMailer(true);
+ $mail->CharSet = "UTF-8";
+ $mail->isSMTP();
- $mail->Host = $smtpAddress;
- $mail->SMTPAuth = $smtpAuth;
- if ($smtpAuth) {
- $mail->Username = $smtpUsername;
- $mail->Password = $smtpPassword;
- }
+ $mail->Host = $smtpAddress;
+ $mail->SMTPAuth = $smtpAuth;
+ if ($smtpAuth) {
+ $mail->Username = $smtpUsername;
+ $mail->Password = $smtpPassword;
+ }
- if ($encryption != "none") {
- $mail->SMTPSecure = $encryption;
- } else {
- $mail->SMTPSecure = false;
- $mail->SMTPAutoTLS = false;
- }
+ if ($encryption != "none") {
+ $mail->SMTPSecure = $encryption;
+ } else {
+ $mail->SMTPSecure = false;
+ $mail->SMTPAutoTLS = false;
+ }
- $mail->Port = $smtpPort;
-
- $getUser = "SELECT * FROM user WHERE id = $userId";
- $user = $db->querySingle($getUser, true);
- $email = $user['email'];
- $name = $user['username'];
-
- $mail->setFrom($fromEmail, 'Wallos App');
- $mail->addAddress($email, $name);
-
- $mail->Subject = translate('wallos_notification', $i18n);
- $mail->Body = translate('test_notification', $i18n);
-
- try {
- if ($mail->send()) {
- $response = [
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n)
- ];
- } else {
- $response = [
- "success" => false,
- "message" => translate('email_error', $i18n) . $mail->ErrorInfo
- ];
- }
- } catch (Exception $e) {
+ $mail->Port = $smtpPort;
+
+ $getUser = "SELECT * FROM user WHERE id = $userId";
+ $user = $db->querySingle($getUser, true);
+ $email = $user['email'];
+ $name = $user['username'];
+
+ $mail->setFrom($fromEmail, 'Wallos App');
+ $mail->addAddress($email, $name);
+
+ $mail->Subject = translate('wallos_notification', $i18n);
+ $mail->Body = translate('test_notification', $i18n);
+
+ try {
+ if ($mail->send()) {
+ $response = [
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n)
+ ];
+ } else {
$response = [
"success" => false,
- "message" => translate('email_error', $i18n) . $e->getMessage()
+ "message" => translate('email_error', $i18n) . $mail->ErrorInfo
];
}
-
- die(json_encode($response));
-
+ } catch (Exception $e) {
+ $response = [
+ "success" => false,
+ "message" => translate('email_error', $i18n) . $e->getMessage()
+ ];
}
-}
-?>
+ die(json_encode($response));
+
+}
\ No newline at end of file
diff --git a/endpoints/notifications/testgotifynotifications.php b/endpoints/notifications/testgotifynotifications.php
index 6c66f1b..69d0687 100644
--- a/endpoints/notifications/testgotifynotifications.php
+++ b/endpoints/notifications/testgotifynotifications.php
@@ -1,93 +1,80 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["gotify_url"]) || $data["gotify_url"] == "" ||
+ !isset($data["token"]) || $data["token"] == ""
+) {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ die(json_encode($response));
+} else {
+ // Set the message parameters
+ $title = translate('wallos_notification', $i18n);
+ $message = translate('test_notification', $i18n);
+ $priority = 5;
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $url = $data["gotify_url"];
+ $token = $data["token"];
+ $ignore_ssl = $data["ignore_ssl"];
+ // Validate URL scheme
+ $parsedUrl = parse_url($url);
if (
- !isset($data["gotify_url"]) || $data["gotify_url"] == "" ||
- !isset($data["token"]) || $data["token"] == ""
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($url, FILTER_VALIDATE_URL)
) {
- $response = [
+ die(json_encode([
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- die(json_encode($response));
- } else {
- // Set the message parameters
- $title = translate('wallos_notification', $i18n);
- $message = translate('test_notification', $i18n);
- $priority = 5;
-
- $url = $data["gotify_url"];
- $token = $data["token"];
- $ignore_ssl = $data["ignore_ssl"];
-
- // Validate URL scheme
- $parsedUrl = parse_url($url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
+ "message" => translate("error", $i18n)
+ ]));
+ }
- $ch = curl_init();
+ $ch = curl_init();
- // Set the URL and other options
- curl_setopt($ch, CURLOPT_URL, $url . "/message?token=" . $token);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
- 'title' => $title,
- 'message' => $message,
- 'priority' => $priority,
- ]));
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ // Set the URL and other options
+ curl_setopt($ch, CURLOPT_URL, $url . "/message?token=" . $token);
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
+ 'title' => $title,
+ 'message' => $message,
+ 'priority' => $priority,
+ ]));
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- if ($ignore_ssl) {
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- }
+ if ($ignore_ssl) {
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+ }
- // Execute the request
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ // Execute the request
+ $response = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- // Close the cURL session
- curl_close($ch);
+ // Close the cURL session
+ curl_close($ch);
- // Check if the message was sent successfully
- if ($response === false || $httpCode < 200 || $httpCode >= 300) {
- die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n),
- "response" => $response,
- "http_code" => $httpCode
- ]));
- } else {
- die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n),
- "response" => $response
- ]));
- }
+ // Check if the message was sent successfully
+ if ($response === false || $httpCode < 200 || $httpCode >= 300) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('notification_failed', $i18n),
+ "response" => $response,
+ "http_code" => $httpCode
+ ]));
+ } else {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n),
+ "response" => $response
+ ]));
}
-} else {
- die(json_encode([
- "success" => false,
- "message" => translate("invalid_request_method", $i18n)
- ]));
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/testmattermostnotifications.php b/endpoints/notifications/testmattermostnotifications.php
index c72a5da..663f243 100755
--- a/endpoints/notifications/testmattermostnotifications.php
+++ b/endpoints/notifications/testmattermostnotifications.php
@@ -1,97 +1,82 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["webhook_url"]) || $data["webhook_url"] == "" ||
+ !isset($data["bot_username"]) || $data["bot_username"] == "" ||
+ !isset($data["bot_icon_emoji"]) || $data["bot_icon_emoji"] == ""
+) {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ // Set the message parameters
+ $title = translate('wallos_notification', $i18n);
+ $message = translate('test_notification', $i18n);
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $webhook_url = $data["webhook_url"];
+ $bot_username = $data["bot_username"];
+ $bot_icon_emoji = $data["bot_icon_emoji"];
+ // Validate URL scheme
+ $parsedUrl = parse_url($webhook_url);
if (
- !isset($data["webhook_url"]) || $data["webhook_url"] == "" ||
- !isset($data["bot_username"]) || $data["bot_username"] == "" ||
- !isset($data["bot_icon_emoji"]) || $data["bot_icon_emoji"] == ""
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($webhook_url, FILTER_VALIDATE_URL)
) {
- $response = [
+ die(json_encode([
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- echo json_encode($response);
- } else {
- // Set the message parameters
- $title = translate('wallos_notification', $i18n);
- $message = translate('test_notification', $i18n);
-
- $webhook_url = $data["webhook_url"];
- $bot_username = $data["bot_username"];
- $bot_icon_emoji = $data["bot_icon_emoji"];
-
- // Validate URL scheme
- $parsedUrl = parse_url($webhook_url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($webhook_url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
+ "message" => translate("error", $i18n)
+ ]));
+ }
- $postfields = [
- 'text' => $message,
- ];
+ $postfields = [
+ 'text' => $message,
+ ];
- if (!empty($bot_username)) {
- $postfields['username'] = $bot_username;
- }
+ if (!empty($bot_username)) {
+ $postfields['username'] = $bot_username;
+ }
- if (!empty($bot_icon_emoji)) {
- $postfields['icon_emoji'] = $bot_icon_emoji;
- }
+ if (!empty($bot_icon_emoji)) {
+ $postfields['icon_emoji'] = $bot_icon_emoji;
+ }
- $ch = curl_init();
+ $ch = curl_init();
- // Set the URL and other options
- curl_setopt($ch, CURLOPT_URL, $webhook_url);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postfields));
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json'
- ]);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ // Set the URL and other options
+ curl_setopt($ch, CURLOPT_URL, $webhook_url);
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postfields));
+ curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Content-Type: application/json'
+ ]);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // Execute the request
- $response = curl_exec($ch);
+ // Execute the request
+ $response = curl_exec($ch);
- // Close the cURL session
- curl_close($ch);
+ // Close the cURL session
+ curl_close($ch);
- // Check if the message was sent successfully
- if ($response === false) {
- die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n)
- ]));
- }
+ // Check if the message was sent successfully
+ if ($response === false) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('notification_failed', $i18n)
+ ]));
+ } else {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n)
+ ]));
}
-} else {
- die(json_encode([
- "success" => false,
- "message" => translate("invalid_request_method", $i18n)
- ]));
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/testntfynotifications.php b/endpoints/notifications/testntfynotifications.php
index d18fb96..61d6b3c 100644
--- a/endpoints/notifications/testntfynotifications.php
+++ b/endpoints/notifications/testntfynotifications.php
@@ -1,91 +1,80 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["host"]) || $data["host"] == "" ||
+ !isset($data["topic"]) || $data["topic"] == ""
+) {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $host = rtrim($data["host"], '/');
+ $topic = $data["topic"];
+ $headers = json_decode($data["headers"], true);
+ if ($headers === null) {
+ $headers = [];
+ }
+ $customheaders = array_map(function ($key, $value) {
+ return "$key: $value";
+ }, array_keys($headers), $headers);
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $url = rtrim($host, '/') . '/' . ltrim($topic, '/');
+ $ignore_ssl = $data["ignore_ssl"];
+ // Validate URL scheme
+ $parsedUrl = parse_url($url);
if (
- !isset($data["host"]) || $data["host"] == "" ||
- !isset($data["topic"]) || $data["topic"] == ""
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($url, FILTER_VALIDATE_URL)
) {
- $response = [
+ die(json_encode([
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- echo json_encode($response);
- } else {
- $host = rtrim($data["host"], '/');
- $topic = $data["topic"];
- $headers = json_decode($data["headers"], true);
- if ($headers === null) {
- $headers = [];
- }
- $customheaders = array_map(function ($key, $value) {
- return "$key: $value";
- }, array_keys($headers), $headers);
-
- $url = rtrim($host, '/') . '/' . ltrim($topic, '/');
- $ignore_ssl = $data["ignore_ssl"];
-
- // Validate URL scheme
- $parsedUrl = parse_url($url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- // Set the message parameters
- $message = translate('test_notification', $i18n);
+ "message" => translate("error", $i18n)
+ ]));
+ }
- $ch = curl_init();
+ // Set the message parameters
+ $message = translate('test_notification', $i18n);
- // Set the URL and other options
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ $ch = curl_init();
- if ($ignore_ssl) {
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- }
+ // Set the URL and other options
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // Execute the request
- $response = curl_exec($ch);
+ if ($ignore_ssl) {
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+ }
- // Close the cURL session
- curl_close($ch);
+ // Execute the request
+ $response = curl_exec($ch);
- // Check if the message was sent successfully
- if ($response === false) {
- die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n)
- ]));
- }
+ // Close the cURL session
+ curl_close($ch);
+ // Check if the message was sent successfully
+ if ($response === false) {
die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n)
+ "success" => false,
+ "message" => translate('notification_failed', $i18n)
]));
}
-}
-
-?>
\ No newline at end of file
+ die(json_encode([
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/notifications/testpushovernotifications.php b/endpoints/notifications/testpushovernotifications.php
index 37e7fe0..3bdaeb9 100644
--- a/endpoints/notifications/testpushovernotifications.php
+++ b/endpoints/notifications/testpushovernotifications.php
@@ -1,70 +1,55 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
- if (
- !isset($data["user_key"]) || $data["user_key"] == "" ||
- !isset($data["token"]) || $data["token"] == ""
- ) {
- $response = [
- "success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- echo json_encode($response);
- } else {
- // Set the message parameters
- $message = translate('test_notification', $i18n);
+if (
+ !isset($data["user_key"]) || $data["user_key"] == "" ||
+ !isset($data["token"]) || $data["token"] == ""
+) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ // Set the message parameters
+ $message = translate('test_notification', $i18n);
- $user_key = $data["user_key"];
- $token = $data["token"];
+ $user_key = $data["user_key"];
+ $token = $data["token"];
- $ch = curl_init();
+ $ch = curl_init();
- // Set the URL and other options
- curl_setopt($ch, CURLOPT_URL, "https://api.pushover.net/1/messages.json");
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
- 'token' => $token,
- 'user' => $user_key,
- 'message' => $message,
- ]));
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ // Set the URL and other options
+ curl_setopt($ch, CURLOPT_URL, "https://api.pushover.net/1/messages.json");
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
+ 'token' => $token,
+ 'user' => $user_key,
+ 'message' => $message,
+ ]));
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // Execute the request
- $response = curl_exec($ch);
+ // Execute the request
+ $response = curl_exec($ch);
- // Close the cURL session
- curl_close($ch);
+ // Close the cURL session
+ curl_close($ch);
- // Check if the message was sent successfully
- if ($response === false) {
- die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n)
- ]));
- }
+ // Check if the message was sent successfully
+ if ($response === false) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('notification_failed', $i18n)
+ ]));
+ } else {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n)
+ ]));
}
-} else {
- die(json_encode([
- "success" => false,
- "message" => translate("invalid_request_method", $i18n)
- ]));
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/testpushplusnotifications.php b/endpoints/notifications/testpushplusnotifications.php
index a0fe8eb..653e641 100644
--- a/endpoints/notifications/testpushplusnotifications.php
+++ b/endpoints/notifications/testpushplusnotifications.php
@@ -1,85 +1,71 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
- if (!isset($data["token"]) || $data["token"] == "") {
- $response = [
- "success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- echo json_encode($response);
- } else {
- // Set the message parameters
- $title = translate('wallos_notification', $i18n);
- $message = translate('test_notification', $i18n);
+if (!isset($data["token"]) || $data["token"] == "") {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ // Set the message parameters
+ $title = translate('wallos_notification', $i18n);
+ $message = translate('test_notification', $i18n);
- $token = $data["token"];
+ $token = $data["token"];
- $ch = curl_init();
+ $ch = curl_init();
- // Set the URL and other options for PushPlus
- $postData = [
- "token" => $token,
- "title" => "您的订阅到期拉",
- "content" => $message,
- "template" => "json"
- ];
+ // Set the URL and other options for PushPlus
+ $postData = [
+ "token" => $token,
+ "title" => "您的订阅到期拉",
+ "content" => $message,
+ "template" => "json"
+ ];
- curl_setopt_array($ch, [
- CURLOPT_URL => 'https://www.pushplus.plus/send',
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_POST => true,
- CURLOPT_POSTFIELDS => json_encode($postData),
- CURLOPT_HTTPHEADER => [
- 'Content-Type: application/json'
- ],
- CURLOPT_TIMEOUT => 10
- ]);
+ curl_setopt_array($ch, [
+ CURLOPT_URL => 'https://www.pushplus.plus/send',
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_POST => true,
+ CURLOPT_POSTFIELDS => json_encode($postData),
+ CURLOPT_HTTPHEADER => [
+ 'Content-Type: application/json'
+ ],
+ CURLOPT_TIMEOUT => 10
+ ]);
- // Execute the request
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $curlError = curl_error($ch);
+ // Execute the request
+ $response = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ $curlError = curl_error($ch);
- // Close the cURL session
- curl_close($ch);
+ // Close the cURL session
+ curl_close($ch);
- // Check if the message was sent successfully
- if ($response === false) {
+ // Check if the message was sent successfully
+ if ($response === false) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('notification_failed', $i18n) . ": " . $curlError
+ ]));
+ } else {
+ $responseData = json_decode($response, true);
+ if (isset($responseData['code']) && $responseData['code'] == 200) {
die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n) . ": " . $curlError
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n)
]));
} else {
- $responseData = json_decode($response, true);
- if (isset($responseData['code']) && $responseData['code'] == 200) {
- die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n)
- ]));
- } else {
- $errorMsg = isset($responseData['msg']) ? $responseData['msg'] : translate('notification_failed', $i18n);
- die(json_encode([
- "success" => false,
- "message" => $errorMsg
- ]));
- }
+ $errorMsg = isset($responseData['msg']) ? $responseData['msg'] : translate('notification_failed', $i18n);
+ die(json_encode([
+ "success" => false,
+ "message" => $errorMsg
+ ]));
}
}
-} else {
- die(json_encode([
- "success" => false,
- "message" => translate("invalid_request_method", $i18n)
- ]));
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/testtelegramnotifications.php b/endpoints/notifications/testtelegramnotifications.php
index 0ba6548..4e594db 100644
--- a/endpoints/notifications/testtelegramnotifications.php
+++ b/endpoints/notifications/testtelegramnotifications.php
@@ -1,68 +1,54 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- if (
- !isset($data["bottoken"]) || $data["bottoken"] == "" ||
- !isset($data["chatid"]) || $data["chatid"] == ""
- ) {
- $response = [
- "success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- echo json_encode($response);
- } else {
- // Set the message parameters
- $title = translate('wallos_notification', $i18n);
- $message = translate('test_notification', $i18n);
+if (
+ !isset($data["bottoken"]) || $data["bottoken"] == "" ||
+ !isset($data["chatid"]) || $data["chatid"] == ""
+) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ // Set the message parameters
+ $title = translate('wallos_notification', $i18n);
+ $message = translate('test_notification', $i18n);
- $botToken = $data["bottoken"];
- $chatId = $data["chatid"];
+ $botToken = $data["bottoken"];
+ $chatId = $data["chatid"];
- $ch = curl_init();
+ $ch = curl_init();
- // Set the URL and other options
- curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot" . $botToken . "/sendMessage");
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
- 'chat_id' => $chatId,
- 'text' => $message,
- ]));
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ // Set the URL and other options
+ curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot" . $botToken . "/sendMessage");
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
+ 'chat_id' => $chatId,
+ 'text' => $message,
+ ]));
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // Execute the request
- $response = curl_exec($ch);
+ // Execute the request
+ $response = curl_exec($ch);
- // Close the cURL session
- curl_close($ch);
+ // Close the cURL session
+ curl_close($ch);
- // Check if the message was sent successfully
- if ($response === false) {
- die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n)
- ]));
- }
+ // Check if the message was sent successfully
+ if ($response === false) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('notification_failed', $i18n)
+ ]));
+ } else {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n)
+ ]));
}
-} else {
- die(json_encode([
- "success" => false,
- "message" => translate("invalid_request_method", $i18n)
- ]));
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/notifications/testwebhooknotifications.php b/endpoints/notifications/testwebhooknotifications.php
index d10a402..7e0880e 100644
--- a/endpoints/notifications/testwebhooknotifications.php
+++ b/endpoints/notifications/testwebhooknotifications.php
@@ -1,6 +1,7 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
// Variables available: {{days_until}}, {{subscription_name}}, {{subscription_price}}, {{subscription_currency}}, {{subscription_category}}, {{subscription_date}}, {{subscription_payer}}, {{subscription_days_until_payment}}, {{subscription_notes}}, {{subscription_url}}
$fakeSubscription = [
@@ -16,97 +17,81 @@ $fakeSubscription = [
"subscription_url" => "https://example.com/test-subscription"
];
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+if (
+ !isset($data["requestmethod"]) || $data["requestmethod"] == "" ||
+ !isset($data["url"]) || $data["url"] == "" ||
+ !isset($data["payload"]) || $data["payload"] == ""
+) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ die(json_encode($response));
+} else {
+ $requestmethod = $data["requestmethod"];
+ $url = $data["url"];
+ $payload = $data["payload"];
+ // Validate URL scheme
+ $parsedUrl = parse_url($url);
if (
- !isset($data["requestmethod"]) || $data["requestmethod"] == "" ||
- !isset($data["url"]) || $data["url"] == "" ||
- !isset($data["payload"]) || $data["payload"] == ""
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($url, FILTER_VALIDATE_URL)
) {
- $response = [
+ die(json_encode([
"success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- die(json_encode($response));
- } else {
- $requestmethod = $data["requestmethod"];
- $url = $data["url"];
- $payload = $data["payload"];
-
- // Validate URL scheme
- $parsedUrl = parse_url($url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
+ "message" => translate("error", $i18n)
+ ]));
+ }
- // Replace placeholders in the payload with fake subscription data
- foreach ($fakeSubscription as $key => $value) {
- $placeholder = "{{" . $key . "}}";
- $payload = str_replace($placeholder, $value, $payload);
- }
+ // Replace placeholders in the payload with fake subscription data
+ foreach ($fakeSubscription as $key => $value) {
+ $placeholder = "{{" . $key . "}}";
+ $payload = str_replace($placeholder, $value, $payload);
+ }
- $customheaders = json_decode($data["customheaders"], true);
- $ignore_ssl = $data["ignore_ssl"];
+ $customheaders = json_decode($data["customheaders"], true);
+ $ignore_ssl = $data["ignore_ssl"];
- $ch = curl_init();
+ $ch = curl_init();
- // Set the URL and other options
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestmethod);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- if (!empty($customheaders)) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
- }
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ // Set the URL and other options
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestmethod);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
+ if (!empty($customheaders)) {
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
+ }
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- if ($ignore_ssl) {
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- }
+ if ($ignore_ssl) {
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+ }
- // Execute the request
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ // Execute the request
+ $response = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- // Close the cURL session
- curl_close($ch);
+ // Close the cURL session
+ curl_close($ch);
- // Check if the message was sent successfully
- if ($response === false || $httpCode >= 400) {
- die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n),
- "response" => curl_error($ch)
- ]));
- } else {
- die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n),
- "response" => $response
- ]));
- }
+ // Check if the message was sent successfully
+ if ($response === false || $httpCode >= 400) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('notification_failed', $i18n),
+ "response" => curl_error($ch)
+ ]));
+ } else {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n),
+ "response" => $response
+ ]));
}
-} else {
- die(json_encode([
- "success" => false,
- "message" => translate("invalid_request_method", $i18n)
- ]));
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/payments/add.php b/endpoints/payments/add.php
index 57b99c6..c9fe488 100644
--- a/endpoints/payments/add.php
+++ b/endpoints/payments/add.php
@@ -3,6 +3,7 @@ error_reporting(E_ERROR | E_PARSE);
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
require_once '../../includes/getsettings.php';
+require_once '../../includes/validate_endpoint.php';
if (!file_exists('../../images/uploads/logos')) {
mkdir('../../images/uploads/logos', 0777, true);
@@ -28,7 +29,7 @@ function getLogoFromUrl($url, $uploadDir, $name, $i18n, $settings)
if (!filter_var($url, FILTER_VALIDATE_URL) || !preg_match('/^https?:\/\//i', $url)) {
$response = [
"success" => false,
- "errorMessage" => "Invalid URL format."
+ "message" => "Invalid URL format."
];
echo json_encode($response);
exit();
@@ -39,7 +40,7 @@ function getLogoFromUrl($url, $uploadDir, $name, $i18n, $settings)
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
$response = [
"success" => false,
- "errorMessage" => "Invalid IP Address."
+ "message" => "Invalid IP Address."
];
echo json_encode($response);
exit();
@@ -194,72 +195,69 @@ function resizeAndUploadLogo($uploadedFile, $uploadDir, $name)
return "";
}
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $enabled = 1;
- $name = validate($_POST["paymentname"]);
- $iconUrl = validate($_POST['icon-url']);
+$enabled = 1;
+$name = validate($_POST["paymentname"]);
+$iconUrl = validate($_POST['icon-url']);
+
+if ($name === "" || ($iconUrl === "" && empty($_FILES['paymenticon']['name']))) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_all_fields', $i18n)
+ ];
+ echo json_encode($response);
+ exit();
+}
+
- if ($name === "" || ($iconUrl === "" && empty($_FILES['paymenticon']['name']))) {
+$icon = "";
+
+if ($iconUrl !== "") {
+ $icon = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name, $i18n, $settings);
+} else {
+ if (!empty($_FILES['paymenticon']['name'])) {
+ $fileType = mime_content_type($_FILES['paymenticon']['tmp_name']);
+ if (strpos($fileType, 'image') === false) {
$response = [
"success" => false,
- "errorMessage" => translate('fill_all_fields', $i18n)
+ "message" => translate('fill_all_fields', $i18n)
];
echo json_encode($response);
exit();
}
-
-
- $icon = "";
-
- if ($iconUrl !== "") {
- $icon = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name, $i18n, $settings);
- } else {
- if (!empty($_FILES['paymenticon']['name'])) {
- $fileType = mime_content_type($_FILES['paymenticon']['tmp_name']);
- if (strpos($fileType, 'image') === false) {
- $response = [
- "success" => false,
- "errorMessage" => translate('fill_all_fields', $i18n)
- ];
- echo json_encode($response);
- exit();
- }
- $icon = resizeAndUploadLogo($_FILES['paymenticon'], '../../images/uploads/logos/', $name);
- }
- }
-
- // Get the maximum existing ID
- $stmt = $db->prepare("SELECT MAX(id) as maxID FROM payment_methods");
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $maxID = $row['maxID'];
-
- // Ensure the new ID is greater than 31
- $newID = max($maxID + 1, 32);
-
- // Insert the new record with the new ID
- $sql = "INSERT INTO payment_methods (id, name, icon, enabled, user_id) VALUES (:id, :name, :icon, :enabled, :userId)";
- $stmt = $db->prepare($sql);
-
- $stmt->bindParam(':id', $newID, SQLITE3_INTEGER);
- $stmt->bindParam(':name', $name, SQLITE3_TEXT);
- $stmt->bindParam(':icon', $icon, SQLITE3_TEXT);
- $stmt->bindParam(':enabled', $enabled, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $success['success'] = true;
- $success['message'] = translate('payment_method_added_successfuly', $i18n);
- $json = json_encode($success);
- header('Content-Type: application/json');
- echo $json;
- exit();
- } else {
- echo translate('error', $i18n) . ": " . $db->lastErrorMsg();
- }
+ $icon = resizeAndUploadLogo($_FILES['paymenticon'], '../../images/uploads/logos/', $name);
}
}
+
+// Get the maximum existing ID
+$stmt = $db->prepare("SELECT MAX(id) as maxID FROM payment_methods");
+$result = $stmt->execute();
+$row = $result->fetchArray(SQLITE3_ASSOC);
+$maxID = $row['maxID'];
+
+// Ensure the new ID is greater than 31
+$newID = max($maxID + 1, 32);
+
+// Insert the new record with the new ID
+$sql = "INSERT INTO payment_methods (id, name, icon, enabled, user_id) VALUES (:id, :name, :icon, :enabled, :userId)";
+$stmt = $db->prepare($sql);
+
+$stmt->bindParam(':id', $newID, SQLITE3_INTEGER);
+$stmt->bindParam(':name', $name, SQLITE3_TEXT);
+$stmt->bindParam(':icon', $icon, SQLITE3_TEXT);
+$stmt->bindParam(':enabled', $enabled, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+
+if ($stmt->execute()) {
+ $success['success'] = true;
+ $success['message'] = translate('payment_method_added_successfuly', $i18n);
+ $json = json_encode($success);
+ header('Content-Type: application/json');
+ echo $json;
+ exit();
+} else {
+ echo translate('error', $i18n) . ": " . $db->lastErrorMsg();
+}
+
$db->close();
?>
\ No newline at end of file
diff --git a/endpoints/payments/delete.php b/endpoints/payments/delete.php
index bee5264..17ea67f 100644
--- a/endpoints/payments/delete.php
+++ b/endpoints/payments/delete.php
@@ -1,30 +1,28 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "DELETE") {
- $paymentMethodId = $_GET["id"];
- $deleteQuery = "DELETE FROM payment_methods WHERE id = :paymentMethodId and user_id = :userId";
- $deleteStmt = $db->prepare($deleteQuery);
- $deleteStmt->bindParam(':paymentMethodId', $paymentMethodId, SQLITE3_INTEGER);
- $deleteStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+$input = file_get_contents('php://input');
+$data = json_decode($input, true);
- if ($deleteStmt->execute()) {
- $success['success'] = true;
- $success['message'] = translate('payment_method_removed', $i18n);
- $json = json_encode($success);
- header('Content-Type: application/json');
- echo $json;
- } else {
- http_response_code(500);
- echo json_encode(array("message" => translate('error', $i18n)));
- }
- } else {
- http_response_code(405);
- echo json_encode(array("message" => translate('invalid_request_method', $i18n)));
- }
+$paymentMethodId = $data["id"];
+$deleteQuery = "DELETE FROM payment_methods WHERE id = :paymentMethodId and user_id = :userId";
+$deleteStmt = $db->prepare($deleteQuery);
+$deleteStmt->bindParam(':paymentMethodId', $paymentMethodId, SQLITE3_INTEGER);
+$deleteStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+
+if ($deleteStmt->execute()) {
+ $success['success'] = true;
+ $success['message'] = translate('payment_method_removed', $i18n);
+ $json = json_encode($success);
+ header('Content-Type: application/json');
+ echo $json;
+} else {
+ http_response_code(500);
+ echo json_encode(array("message" => translate('error', $i18n)));
}
+
$db->close();
?>
\ No newline at end of file
diff --git a/endpoints/payments/rename.php b/endpoints/payments/rename.php
index ba0a76b..fcd8c9a 100644
--- a/endpoints/payments/rename.php
+++ b/endpoints/payments/rename.php
@@ -1,13 +1,7 @@
<?php
require_once '../../includes/connect_endpoint.php';
-
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+require_once '../../includes/validate_endpoint.php';
if (!isset($_POST['paymentId']) || !isset($_POST['name']) || $_POST['paymentId'] === '' || $_POST['name'] === '') {
die(json_encode([
diff --git a/endpoints/payments/sort.php b/endpoints/payments/sort.php
index 7fc5a22..bb6eb54 100644
--- a/endpoints/payments/sort.php
+++ b/endpoints/payments/sort.php
@@ -1,33 +1,25 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- $paymentMethods = $_POST['paymentMethodIds'];
- $order = 1;
+$paymentMethods = $_POST['paymentMethodIds'];
+$order = 1;
- foreach ($paymentMethods as $paymentMethodId) {
- $sql = "UPDATE payment_methods SET `order` = :order WHERE id = :paymentMethodId and user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':order', $order, SQLITE3_INTEGER);
- $stmt->bindParam(':paymentMethodId', $paymentMethodId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $order++;
- }
-
- $response = [
- "success" => true,
- "message" => translate("sort_order_saved", $i18n)
- ];
- echo json_encode($response);
-} else {
- $response = [
- "success" => false,
- "errorMessage" => translate("session_expired", $i18n)
- ];
- echo json_encode($response);
- die();
+foreach ($paymentMethods as $paymentMethodId) {
+ $sql = "UPDATE payment_methods SET `order` = :order WHERE id = :paymentMethodId and user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':order', $order, SQLITE3_INTEGER);
+ $stmt->bindParam(':paymentMethodId', $paymentMethodId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $order++;
}
+$response = [
+ "success" => true,
+ "message" => translate("sort_order_saved", $i18n)
+];
+echo json_encode($response);
+
?>
\ No newline at end of file
diff --git a/endpoints/payments/payment.php b/endpoints/payments/toggle.php
similarity index 76%
rename from endpoints/payments/payment.php
rename to endpoints/payments/toggle.php
index e377afc..b2a1dad 100644
--- a/endpoints/payments/payment.php
+++ b/endpoints/payments/toggle.php
@@ -1,21 +1,15 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-if (!isset($_GET['paymentId']) || !isset($_GET['enabled'])) {
+if (!isset($_POST['paymentId']) || !isset($_POST['enabled'])) {
die(json_encode([
"success" => false,
"message" => translate('fields_missing', $i18n)
]));
}
-$paymentId = $_GET['paymentId'];
+$paymentId = $_POST['paymentId'];
$stmt = $db->prepare('SELECT COUNT(*) as count FROM subscriptions WHERE payment_method_id=:paymentId and user_id=:userId');
$stmt->bindValue(':paymentId', $paymentId, SQLITE3_INTEGER);
@@ -31,7 +25,7 @@ if ($inUse) {
]));
}
-$enabled = $_GET['enabled'];
+$enabled = $_POST['enabled'];
$sqlUpdate = 'UPDATE payment_methods SET enabled=:enabled WHERE id=:id and user_id=:userId';
$stmtUpdate = $db->prepare($sqlUpdate);
diff --git a/endpoints/settings/colortheme.php b/endpoints/settings/colortheme.php
index 98daf94..3fdcd5c 100644
--- a/endpoints/settings/colortheme.php
+++ b/endpoints/settings/colortheme.php
@@ -1,44 +1,34 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+// Valiudate input, should be a color from the allowed list
+$allowedColors = ['blue', 'red', 'green', 'yellow', 'purple'];
+if (!isset($data['color']) || !in_array($data['color'], $allowedColors)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- // Valiudate input, should be a color from the allowed list
- $allowedColors = ['blue', 'red', 'green', 'yellow', 'purple'];
- if (!isset($data['color']) || !in_array($data['color'], $allowedColors)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $color = $data['color'];
+$color = $data['color'];
- $stmt = $db->prepare('UPDATE settings SET color_theme = :color WHERE user_id = :userId');
- $stmt->bindParam(':color', $color, SQLITE3_TEXT);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
+$stmt = $db->prepare('UPDATE settings SET color_theme = :color WHERE user_id = :userId');
+$stmt->bindParam(':color', $color, SQLITE3_TEXT);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/convert_currency.php b/endpoints/settings/convert_currency.php
index b6a2ef3..84d8d17 100644
--- a/endpoints/settings/convert_currency.php
+++ b/endpoints/settings/convert_currency.php
@@ -1,42 +1,32 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$convert_currency = $data['value'];
+
+// Validate input
+if (!isset($convert_currency) || !is_bool($convert_currency)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $convert_currency = $data['value'];
-
- // Validate input
- if (!isset($convert_currency) || !is_bool($convert_currency)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('UPDATE settings SET convert_currency = :convert_currency WHERE user_id = :userId');
- $stmt->bindParam(':convert_currency', $convert_currency, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
+$stmt = $db->prepare('UPDATE settings SET convert_currency = :convert_currency WHERE user_id = :userId');
+$stmt->bindParam(':convert_currency', $convert_currency, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/customcss.php b/endpoints/settings/customcss.php
index 2b29858..bb2b6b2 100644
--- a/endpoints/settings/customcss.php
+++ b/endpoints/settings/customcss.php
@@ -1,37 +1,29 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$customCss = $data['customCss'];
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+$stmt = $db->prepare('DELETE FROM custom_css_style WHERE user_id = :userId');
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+$stmt->execute();
- $customCss = $data['customCss'];
-
- $stmt = $db->prepare('DELETE FROM custom_css_style WHERE user_id = :userId');
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $stmt->execute();
-
- $stmt = $db->prepare('INSERT INTO custom_css_style (css, user_id) VALUES (:customCss, :userId)');
- $stmt->bindParam(':customCss', $customCss, SQLITE3_TEXT);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+$stmt = $db->prepare('INSERT INTO custom_css_style (css, user_id) VALUES (:customCss, :userId)');
+$stmt->bindParam(':customCss', $customCss, SQLITE3_TEXT);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
}
diff --git a/endpoints/settings/customtheme.php b/endpoints/settings/customtheme.php
index 74b9622..8e6e37d 100644
--- a/endpoints/settings/customtheme.php
+++ b/endpoints/settings/customtheme.php
@@ -1,58 +1,48 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$main_color = $data['mainColor'];
+$accent_color = $data['accentColor'];
+$hover_color = $data['hoverColor'];
+
+// Validate input, should be a color in #RRGGBB format
+if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $main_color) || !preg_match('/^#[0-9A-Fa-f]{6}$/', $accent_color) || !preg_match('/^#[0-9A-Fa-f]{6}$/', $hover_color)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $main_color = $data['mainColor'];
- $accent_color = $data['accentColor'];
- $hover_color = $data['hoverColor'];
-
- // Validate input, should be a color in #RRGGBB format
- if (!preg_match('/^#[0-9A-Fa-f]{6}$/', $main_color) || !preg_match('/^#[0-9A-Fa-f]{6}$/', $accent_color) || !preg_match('/^#[0-9A-Fa-f]{6}$/', $hover_color)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- if ($main_color == $accent_color) {
- die(json_encode([
- "success" => false,
- "message" => translate("main_accent_color_error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :userId');
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $stmt->execute();
-
- $stmt = $db->prepare('INSERT INTO custom_colors (main_color, accent_color, hover_color, user_id) VALUES (:main_color, :accent_color, :hover_color, :userId)');
- $stmt->bindParam(':main_color', $main_color, SQLITE3_TEXT);
- $stmt->bindParam(':accent_color', $accent_color, SQLITE3_TEXT);
- $stmt->bindParam(':hover_color', $hover_color, SQLITE3_TEXT);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
+if ($main_color == $accent_color) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("main_accent_color_error", $i18n)
+ ]));
}
-?>
\ No newline at end of file
+$stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :userId');
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+$stmt->execute();
+
+$stmt = $db->prepare('INSERT INTO custom_colors (main_color, accent_color, hover_color, user_id) VALUES (:main_color, :accent_color, :hover_color, :userId)');
+$stmt->bindParam(':main_color', $main_color, SQLITE3_TEXT);
+$stmt->bindParam(':accent_color', $accent_color, SQLITE3_TEXT);
+$stmt->bindParam(':hover_color', $hover_color, SQLITE3_TEXT);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/deleteaccount.php b/endpoints/settings/deleteaccount.php
index 9b46268..8df4903 100644
--- a/endpoints/settings/deleteaccount.php
+++ b/endpoints/settings/deleteaccount.php
@@ -1,134 +1,117 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$userIdToDelete = $data['userId'];
+
+if ($userIdToDelete == 1 || $userIdToDelete != $userId) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate('error', $i18n)
]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
-
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $userIdToDelete = $data['userId'];
-
- if ($userIdToDelete == 1 || $userIdToDelete != $userId) {
- die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
- ]));
- } else {
- // Delete user
- $stmt = $db->prepare('DELETE FROM user WHERE id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete subscriptions
- $stmt = $db->prepare('DELETE FROM subscriptions WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete settings
- $stmt = $db->prepare('DELETE FROM settings WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete fixer
- $stmt = $db->prepare('DELETE FROM fixer WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete custom colors
- $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete currencies
- $stmt = $db->prepare('DELETE FROM currencies WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete categories
- $stmt = $db->prepare('DELETE FROM categories WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete household
- $stmt = $db->prepare('DELETE FROM household WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete payment methods
- $stmt = $db->prepare('DELETE FROM payment_methods WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete email notifications
- $stmt = $db->prepare('DELETE FROM email_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete telegram notifications
- $stmt = $db->prepare('DELETE FROM telegram_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete webhook notifications
- $stmt = $db->prepare('DELETE FROM webhook_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete gotify notifications
- $stmt = $db->prepare('DELETE FROM gotify_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete pushover notifications
- $stmt = $db->prepare('DELETE FROM pushover_notifications WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Dele notification settings
- $stmt = $db->prepare('DELETE FROM notification_settings WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete last exchange update
- $stmt = $db->prepare('DELETE FROM last_exchange_update WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete email verification
- $stmt = $db->prepare('DELETE FROM email_verification WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete totp
- $stmt = $db->prepare('DELETE FROM totp WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- // Delete total yearly cost
- $stmt = $db->prepare('DELETE FROM total_yearly_cost WHERE user_id = :id');
- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- die(json_encode([
- "success" => true,
- "message" => translate('success', $i18n)
- ]));
-
- }
-
} else {
+ // Delete user
+ $stmt = $db->prepare('DELETE FROM user WHERE id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete subscriptions
+ $stmt = $db->prepare('DELETE FROM subscriptions WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete settings
+ $stmt = $db->prepare('DELETE FROM settings WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete fixer
+ $stmt = $db->prepare('DELETE FROM fixer WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete custom colors
+ $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete currencies
+ $stmt = $db->prepare('DELETE FROM currencies WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete categories
+ $stmt = $db->prepare('DELETE FROM categories WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete household
+ $stmt = $db->prepare('DELETE FROM household WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete payment methods
+ $stmt = $db->prepare('DELETE FROM payment_methods WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete email notifications
+ $stmt = $db->prepare('DELETE FROM email_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete telegram notifications
+ $stmt = $db->prepare('DELETE FROM telegram_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete webhook notifications
+ $stmt = $db->prepare('DELETE FROM webhook_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete gotify notifications
+ $stmt = $db->prepare('DELETE FROM gotify_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete pushover notifications
+ $stmt = $db->prepare('DELETE FROM pushover_notifications WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Dele notification settings
+ $stmt = $db->prepare('DELETE FROM notification_settings WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete last exchange update
+ $stmt = $db->prepare('DELETE FROM last_exchange_update WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete email verification
+ $stmt = $db->prepare('DELETE FROM email_verification WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete totp
+ $stmt = $db->prepare('DELETE FROM totp WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ // Delete total yearly cost
+ $stmt = $db->prepare('DELETE FROM total_yearly_cost WHERE user_id = :id');
+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
die(json_encode([
- "success" => false,
- "message" => translate('error', $i18n)
+ "success" => true,
+ "message" => translate('success', $i18n)
]));
-}
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/settings/disabled_to_bottom.php b/endpoints/settings/disabled_to_bottom.php
index 208a195..00e4a28 100644
--- a/endpoints/settings/disabled_to_bottom.php
+++ b/endpoints/settings/disabled_to_bottom.php
@@ -1,42 +1,32 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$disabled_to_bottom = $data['value'];
+
+// Validate input
+if (!isset($disabled_to_bottom) || !is_bool($disabled_to_bottom)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $disabled_to_bottom = $data['value'];
-
- // Validate input
- if (!isset($disabled_to_bottom) || !is_bool($disabled_to_bottom)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('UPDATE settings SET disabled_to_bottom = :disabled_to_bottom WHERE user_id = :userId');
- $stmt->bindParam(':disabled_to_bottom', $disabled_to_bottom, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
+$stmt = $db->prepare('UPDATE settings SET disabled_to_bottom = :disabled_to_bottom WHERE user_id = :userId');
+$stmt->bindParam(':disabled_to_bottom', $disabled_to_bottom, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/hide_disabled.php b/endpoints/settings/hide_disabled.php
index 9bac679..214520a 100644
--- a/endpoints/settings/hide_disabled.php
+++ b/endpoints/settings/hide_disabled.php
@@ -1,42 +1,32 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$hide_disabled = $data['value'];
+
+// Validate input
+if (!isset($hide_disabled) || !is_bool($hide_disabled)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $hide_disabled = $data['value'];
-
- // Validate input
- if (!isset($hide_disabled) || !is_bool($hide_disabled)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('UPDATE settings SET hide_disabled = :hide_disabled WHERE user_id = :userId');
- $stmt->bindParam(':hide_disabled', $hide_disabled, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
+$stmt = $db->prepare('UPDATE settings SET hide_disabled = :hide_disabled WHERE user_id = :userId');
+$stmt->bindParam(':hide_disabled', $hide_disabled, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/mobile_navigation.php b/endpoints/settings/mobile_navigation.php
index 9cd1bfb..11664dc 100644
--- a/endpoints/settings/mobile_navigation.php
+++ b/endpoints/settings/mobile_navigation.php
@@ -1,44 +1,33 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$mobile_nav = $data['value'];
+
+// Validate input
+if (!isset($mobile_nav) || !is_bool($mobile_nav)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $mobile_nav = $data['value'];
-
- // Validate input
- if (!isset($mobile_nav) || !is_bool($mobile_nav)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('UPDATE settings SET mobile_nav = :mobile_nav WHERE user_id = :userId');
- $stmt->bindParam(':mobile_nav', $mobile_nav, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
-«
+$stmt = $db->prepare('UPDATE settings SET mobile_nav = :mobile_nav WHERE user_id = :userId');
+$stmt->bindParam(':mobile_nav', $mobile_nav, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/monthly_price.php b/endpoints/settings/monthly_price.php
index 716d2a0..a06fc09 100644
--- a/endpoints/settings/monthly_price.php
+++ b/endpoints/settings/monthly_price.php
@@ -1,42 +1,33 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$monthly_price = $data['value'];
+
+// Validate input
+if (!isset($monthly_price) || !is_bool($monthly_price)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $monthly_price = $data['value'];
+$stmt = $db->prepare('UPDATE settings SET monthly_price = :monthly_price WHERE user_id = :userId');
+$stmt->bindParam(':monthly_price', $monthly_price, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- // Validate input
- if (!isset($monthly_price) || !is_bool($monthly_price)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('UPDATE settings SET monthly_price = :monthly_price WHERE user_id = :userId');
- $stmt->bindParam(':monthly_price', $monthly_price, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
-
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/remove_background.php b/endpoints/settings/remove_background.php
index 87e4363..2e95500 100644
--- a/endpoints/settings/remove_background.php
+++ b/endpoints/settings/remove_background.php
@@ -1,42 +1,32 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$remove_background = $data['value'];
+
+// Validate input
+if (!isset($remove_background) || !is_bool($remove_background)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $remove_background = $data['value'];
-
- // Validate input
- if (!isset($remove_background) || !is_bool($remove_background)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('UPDATE settings SET remove_background = :remove_background WHERE user_id = :userId');
- $stmt->bindParam(':remove_background', $remove_background, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
+$stmt = $db->prepare('UPDATE settings SET remove_background = :remove_background WHERE user_id = :userId');
+$stmt->bindParam(':remove_background', $remove_background, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/resettheme.php b/endpoints/settings/resettheme.php
index 8204c9d..eab7479 100644
--- a/endpoints/settings/resettheme.php
+++ b/endpoints/settings/resettheme.php
@@ -1,29 +1,19 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :userId');
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "DELETE") {
- $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :userId');
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/settings/show_original_price.php b/endpoints/settings/show_original_price.php
index d23b94c..eb6ab98 100644
--- a/endpoints/settings/show_original_price.php
+++ b/endpoints/settings/show_original_price.php
@@ -1,42 +1,32 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$show_original_price = $data['value'];
+
+// Validate input
+if (!isset($show_original_price) || !is_bool($show_original_price)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $show_original_price = $data['value'];
-
- // Validate input
- if (!isset($show_original_price) || !is_bool($show_original_price)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('UPDATE settings SET show_original_price = :show_original_price WHERE user_id = :userId');
- $stmt->bindParam(':show_original_price', $show_original_price, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
+$stmt = $db->prepare('UPDATE settings SET show_original_price = :show_original_price WHERE user_id = :userId');
+$stmt->bindParam(':show_original_price', $show_original_price, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/subscription_progress.php b/endpoints/settings/subscription_progress.php
index e44e09e..daf6305 100644
--- a/endpoints/settings/subscription_progress.php
+++ b/endpoints/settings/subscription_progress.php
@@ -1,42 +1,32 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$show_subscription_progress = $data['value'];
+
+// Validate input
+if (!isset($show_subscription_progress) || !is_bool($show_subscription_progress)) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $show_subscription_progress = $data['value'];
-
- // Validate input
- if (!isset($show_subscription_progress) || !is_bool($show_subscription_progress)) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('UPDATE settings SET show_subscription_progress = :show_subscription_progress WHERE user_id = :userId');
- $stmt->bindParam(':show_subscription_progress', $show_subscription_progress, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
+$stmt = $db->prepare('UPDATE settings SET show_subscription_progress = :show_subscription_progress WHERE user_id = :userId');
+$stmt->bindParam(':show_subscription_progress', $show_subscription_progress, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/settings/theme.php b/endpoints/settings/theme.php
index 74c7197..dae0198 100644
--- a/endpoints/settings/theme.php
+++ b/endpoints/settings/theme.php
@@ -1,42 +1,32 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$theme = (int) $data['theme'];
+
+// Validate input, should be an integer (0, 1 or 2)
+if (!isset($theme) || !is_int($theme) || $theme < 0 || $theme > 2) {
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $theme = (int)$data['theme'];
-
- // Validate input, should be an integer (0, 1 or 2)
- if (!isset($theme) || !is_int($theme) || $theme < 0 || $theme > 2) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $stmt = $db->prepare('UPDATE settings SET dark_theme = :theme WHERE user_id = :userId');
- $stmt->bindParam(':theme', $theme, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- die(json_encode([
- "success" => true,
- "message" => translate("success", $i18n)
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-}
+$stmt = $db->prepare('UPDATE settings SET dark_theme = :theme WHERE user_id = :userId');
+$stmt->bindParam(':theme', $theme, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-?>
\ No newline at end of file
+if ($stmt->execute()) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate("success", $i18n)
+ ]));
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.php
index 790f92d..bf97b97 100644
--- a/endpoints/subscription/add.php
+++ b/endpoints/subscription/add.php
@@ -1,6 +1,7 @@
<?php
error_reporting(E_ERROR | E_PARSE);
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
require_once '../../includes/inputvalidation.php';
require_once '../../includes/getsettings.php';
@@ -28,7 +29,7 @@ function getLogoFromUrl($url, $uploadDir, $name, $settings, $i18n)
if (!filter_var($url, FILTER_VALIDATE_URL) || !preg_match('/^https?:\/\//i', $url)) {
$response = [
"success" => false,
- "errorMessage" => "Invalid URL format."
+ "message" => "Invalid URL format."
];
echo json_encode($response);
exit();
@@ -39,7 +40,7 @@ function getLogoFromUrl($url, $uploadDir, $name, $settings, $i18n)
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
$response = [
"success" => false,
- "errorMessage" => "Invalid IP Address."
+ "message" => "Invalid IP Address."
];
echo json_encode($response);
exit();
@@ -202,49 +203,47 @@ function resizeAndUploadLogo($uploadedFile, $uploadDir, $name, $settings)
return "";
}
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $isEdit = isset($_POST['id']) && $_POST['id'] != "";
- $name = validate($_POST["name"]);
- $price = $_POST['price'];
- $currencyId = $_POST["currency_id"];
- $frequency = $_POST["frequency"];
- $cycle = $_POST["cycle"];
- $nextPayment = $_POST["next_payment"];
- $autoRenew = isset($_POST['auto_renew']) ? true : false;
- $startDate = $_POST["start_date"];
- $paymentMethodId = $_POST["payment_method_id"];
- $payerUserId = $_POST["payer_user_id"];
- $categoryId = $_POST['category_id'];
- $notes = validate($_POST["notes"]);
- $url = validate($_POST['url']);
- $logoUrl = validate($_POST['logo-url']);
- $logo = "";
- $notify = isset($_POST['notifications']) ? true : false;
- $notifyDaysBefore = $_POST['notify_days_before'];
- $inactive = isset($_POST['inactive']) ? true : false;
- $cancellationDate = $_POST['cancellation_date'] ?? null;
- $replacementSubscriptionId = $_POST['replacement_subscription_id'];
-
- if ($replacementSubscriptionId == 0 || $inactive == 0) {
- $replacementSubscriptionId = null;
- }
+$isEdit = isset($_POST['id']) && $_POST['id'] != "";
+$name = validate($_POST["name"]);
+$price = $_POST['price'];
+$currencyId = $_POST["currency_id"];
+$frequency = $_POST["frequency"];
+$cycle = $_POST["cycle"];
+$nextPayment = $_POST["next_payment"];
+$autoRenew = isset($_POST['auto_renew']) ? true : false;
+$startDate = $_POST["start_date"];
+$paymentMethodId = $_POST["payment_method_id"];
+$payerUserId = $_POST["payer_user_id"];
+$categoryId = $_POST['category_id'];
+$notes = validate($_POST["notes"]);
+$url = validate($_POST['url']);
+$logoUrl = validate($_POST['logo-url']);
+$logo = "";
+$notify = isset($_POST['notifications']) ? true : false;
+$notifyDaysBefore = $_POST['notify_days_before'];
+$inactive = isset($_POST['inactive']) ? true : false;
+$cancellationDate = $_POST['cancellation_date'] ?? null;
+$replacementSubscriptionId = $_POST['replacement_subscription_id'];
+
+if ($replacementSubscriptionId == 0 || $inactive == 0) {
+ $replacementSubscriptionId = null;
+}
- if ($logoUrl !== "") {
- $logo = getLogoFromUrl($logoUrl, '../../images/uploads/logos/', $name, $settings, $i18n);
- } else {
- if (!empty($_FILES['logo']['name'])) {
- $fileType = mime_content_type($_FILES['logo']['tmp_name']);
- if (strpos($fileType, 'image') === false) {
- echo translate("fill_all_fields", $i18n);
- exit();
- }
- $logo = resizeAndUploadLogo($_FILES['logo'], '../../images/uploads/logos/', $name, $settings);
- }
+if ($logoUrl !== "") {
+ $logo = getLogoFromUrl($logoUrl, '../../images/uploads/logos/', $name, $settings, $i18n);
+} else {
+ if (!empty($_FILES['logo']['name'])) {
+ $fileType = mime_content_type($_FILES['logo']['tmp_name']);
+ if (strpos($fileType, 'image') === false) {
+ echo translate("fill_all_fields", $i18n);
+ exit();
}
+ $logo = resizeAndUploadLogo($_FILES['logo'], '../../images/uploads/logos/', $name, $settings);
+ }
+}
- if (!$isEdit) {
- $sql = "INSERT INTO subscriptions (
+if (!$isEdit) {
+ $sql = "INSERT INTO subscriptions (
name, logo, price, currency_id, next_payment, cycle, frequency, notes,
payment_method_id, payer_user_id, category_id, notify, inactive, url,
notify_days_before, user_id, cancellation_date, replacement_subscription_id,
@@ -255,9 +254,9 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
:notifyDaysBefore, :userId, :cancellationDate, :replacement_subscription_id,
:autoRenew, :startDate
)";
- } else {
- $id = $_POST['id'];
- $sql = "UPDATE subscriptions SET
+} else {
+ $id = $_POST['id'];
+ $sql = "UPDATE subscriptions SET
name = :name,
price = :price,
currency_id = :currencyId,
@@ -277,52 +276,50 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
cancellation_date = :cancellationDate,
replacement_subscription_id = :replacement_subscription_id";
- if ($logo != "") {
- $sql .= ", logo = :logo";
- }
+ if ($logo != "") {
+ $sql .= ", logo = :logo";
+ }
- $sql .= " WHERE id = :id AND user_id = :userId";
- }
+ $sql .= " WHERE id = :id AND user_id = :userId";
+}
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':name', $name, SQLITE3_TEXT);
- if ($logo != "") {
- $stmt->bindParam(':logo', $logo, SQLITE3_TEXT);
- }
- $stmt->bindParam(':price', $price, SQLITE3_FLOAT);
- $stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
- $stmt->bindParam(':nextPayment', $nextPayment, SQLITE3_TEXT);
- $stmt->bindParam(':autoRenew', $autoRenew, SQLITE3_INTEGER);
- $stmt->bindParam(':startDate', $startDate, SQLITE3_TEXT);
- $stmt->bindParam(':cycle', $cycle, SQLITE3_INTEGER);
- $stmt->bindParam(':frequency', $frequency, SQLITE3_INTEGER);
- $stmt->bindParam(':notes', $notes, SQLITE3_TEXT);
- $stmt->bindParam(':paymentMethodId', $paymentMethodId, SQLITE3_INTEGER);
- $stmt->bindParam(':payerUserId', $payerUserId, SQLITE3_INTEGER);
- $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
- $stmt->bindParam(':notify', $notify, SQLITE3_INTEGER);
- $stmt->bindParam(':inactive', $inactive, SQLITE3_INTEGER);
- $stmt->bindParam(':url', $url, SQLITE3_TEXT);
- $stmt->bindParam(':notifyDaysBefore', $notifyDaysBefore, SQLITE3_INTEGER);
- $stmt->bindParam(':cancellationDate', $cancellationDate, SQLITE3_TEXT);
- if ($isEdit) {
- $stmt->bindParam(':id', $id, SQLITE3_INTEGER);
- }
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $stmt->bindParam(':replacement_subscription_id', $replacementSubscriptionId, SQLITE3_INTEGER);
-
- if ($stmt->execute()) {
- $success['status'] = "Success";
- $text = $isEdit ? "updated" : "added";
- $success['message'] = translate('subscription_' . $text . '_successfuly', $i18n);
- $json = json_encode($success);
- header('Content-Type: application/json');
- echo $json;
- exit();
- } else {
- echo translate('error', $i18n) . ": " . $db->lastErrorMsg();
- }
- }
+$stmt = $db->prepare($sql);
+$stmt->bindParam(':name', $name, SQLITE3_TEXT);
+if ($logo != "") {
+ $stmt->bindParam(':logo', $logo, SQLITE3_TEXT);
+}
+$stmt->bindParam(':price', $price, SQLITE3_FLOAT);
+$stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);
+$stmt->bindParam(':nextPayment', $nextPayment, SQLITE3_TEXT);
+$stmt->bindParam(':autoRenew', $autoRenew, SQLITE3_INTEGER);
+$stmt->bindParam(':startDate', $startDate, SQLITE3_TEXT);
+$stmt->bindParam(':cycle', $cycle, SQLITE3_INTEGER);
+$stmt->bindParam(':frequency', $frequency, SQLITE3_INTEGER);
+$stmt->bindParam(':notes', $notes, SQLITE3_TEXT);
+$stmt->bindParam(':paymentMethodId', $paymentMethodId, SQLITE3_INTEGER);
+$stmt->bindParam(':payerUserId', $payerUserId, SQLITE3_INTEGER);
+$stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
+$stmt->bindParam(':notify', $notify, SQLITE3_INTEGER);
+$stmt->bindParam(':inactive', $inactive, SQLITE3_INTEGER);
+$stmt->bindParam(':url', $url, SQLITE3_TEXT);
+$stmt->bindParam(':notifyDaysBefore', $notifyDaysBefore, SQLITE3_INTEGER);
+$stmt->bindParam(':cancellationDate', $cancellationDate, SQLITE3_TEXT);
+if ($isEdit) {
+ $stmt->bindParam(':id', $id, SQLITE3_INTEGER);
+}
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+$stmt->bindParam(':replacement_subscription_id', $replacementSubscriptionId, SQLITE3_INTEGER);
+
+if ($stmt->execute()) {
+ $success['status'] = "Success";
+ $text = $isEdit ? "updated" : "added";
+ $success['message'] = translate('subscription_' . $text . '_successfuly', $i18n);
+ $json = json_encode($success);
+ header('Content-Type: application/json');
+ echo $json;
+ exit();
+} else {
+ echo translate('error', $i18n) . ": " . $db->lastErrorMsg();
}
$db->close();
?>
\ No newline at end of file
diff --git a/endpoints/subscription/clone.php b/endpoints/subscription/clone.php
index 567d9f0..5c2b2ef 100644
--- a/endpoints/subscription/clone.php
+++ b/endpoints/subscription/clone.php
@@ -1,64 +1,60 @@
<?php
- require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
- if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "GET") {
- $subscriptionId = $_GET["id"];
- $query = "SELECT * FROM subscriptions WHERE id = :id AND user_id = :user_id";
- $stmt = $db->prepare($query);
- $stmt->bindValue(':id', $subscriptionId, SQLITE3_INTEGER);
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $subscriptionToClone = $result->fetchArray(SQLITE3_ASSOC);
- if ($subscriptionToClone === false) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
- $query = "INSERT INTO subscriptions (name, logo, price, currency_id, next_payment, cycle, frequency, notes, payment_method_id, payer_user_id, category_id, notify, url, inactive, notify_days_before, user_id, cancellation_date, replacement_subscription_id) VALUES (:name, :logo, :price, :currency_id, :next_payment, :cycle, :frequency, :notes, :payment_method_id, :payer_user_id, :category_id, :notify, :url, :inactive, :notify_days_before, :user_id, :cancellation_date, :replacement_subscription_id)";
- $cloneStmt = $db->prepare($query);
- $cloneStmt->bindValue(':name', $subscriptionToClone['name'], SQLITE3_TEXT);
- $cloneStmt->bindValue(':logo', $subscriptionToClone['logo'], SQLITE3_TEXT);
- $cloneStmt->bindValue(':price', $subscriptionToClone['price'], SQLITE3_TEXT);
- $cloneStmt->bindValue(':currency_id', $subscriptionToClone['currency_id'], SQLITE3_INTEGER);
- $cloneStmt->bindValue(':next_payment', $subscriptionToClone['next_payment'], SQLITE3_TEXT);
- $cloneStmt->bindValue(':auto_renew', $subscriptionToClone['auto_renew'], SQLITE3_INTEGER);
- $cloneStmt->bindValue(':start_date', $subscriptionToClone['start_date'], SQLITE3_TEXT);
- $cloneStmt->bindValue(':cycle', $subscriptionToClone['cycle'], SQLITE3_TEXT);
- $cloneStmt->bindValue(':frequency', $subscriptionToClone['frequency'], SQLITE3_INTEGER);
- $cloneStmt->bindValue(':notes', $subscriptionToClone['notes'], SQLITE3_TEXT);
- $cloneStmt->bindValue(':payment_method_id', $subscriptionToClone['payment_method_id'], SQLITE3_INTEGER);
- $cloneStmt->bindValue(':payer_user_id', $subscriptionToClone['payer_user_id'], SQLITE3_INTEGER);
- $cloneStmt->bindValue(':category_id', $subscriptionToClone['category_id'], SQLITE3_INTEGER);
- $cloneStmt->bindValue(':notify', $subscriptionToClone['notify'], SQLITE3_INTEGER);
- $cloneStmt->bindValue(':url', $subscriptionToClone['url'], SQLITE3_TEXT);
- $cloneStmt->bindValue(':inactive', $subscriptionToClone['inactive'], SQLITE3_INTEGER);
- $cloneStmt->bindValue(':notify_days_before', $subscriptionToClone['notify_days_before'], SQLITE3_INTEGER);
- $cloneStmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $cloneStmt->bindValue(':cancellation_date', $subscriptionToClone['cancellation_date'], SQLITE3_TEXT);
- $cloneStmt->bindValue(':replacement_subscription_id', $subscriptionToClone['replacement_subscription_id'], SQLITE3_INTEGER);
+$subscriptionId = $data["id"];
+$query = "SELECT * FROM subscriptions WHERE id = :id AND user_id = :user_id";
+$stmt = $db->prepare($query);
+$stmt->bindValue(':id', $subscriptionId, SQLITE3_INTEGER);
+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
+$subscriptionToClone = $result->fetchArray(SQLITE3_ASSOC);
+if ($subscriptionToClone === false) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
- if ($cloneStmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('success', $i18n),
- "id" => $db->lastInsertRowID()
- ];
- echo json_encode($response);
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate('invalid_request_method', $i18n)
- ]));
- }
- }
- $db->close();
+$query = "INSERT INTO subscriptions (name, logo, price, currency_id, next_payment, cycle, frequency, notes, payment_method_id, payer_user_id, category_id, notify, url, inactive, notify_days_before, user_id, cancellation_date, replacement_subscription_id) VALUES (:name, :logo, :price, :currency_id, :next_payment, :cycle, :frequency, :notes, :payment_method_id, :payer_user_id, :category_id, :notify, :url, :inactive, :notify_days_before, :user_id, :cancellation_date, :replacement_subscription_id)";
+$cloneStmt = $db->prepare($query);
+$cloneStmt->bindValue(':name', $subscriptionToClone['name'], SQLITE3_TEXT);
+$cloneStmt->bindValue(':logo', $subscriptionToClone['logo'], SQLITE3_TEXT);
+$cloneStmt->bindValue(':price', $subscriptionToClone['price'], SQLITE3_TEXT);
+$cloneStmt->bindValue(':currency_id', $subscriptionToClone['currency_id'], SQLITE3_INTEGER);
+$cloneStmt->bindValue(':next_payment', $subscriptionToClone['next_payment'], SQLITE3_TEXT);
+$cloneStmt->bindValue(':auto_renew', $subscriptionToClone['auto_renew'], SQLITE3_INTEGER);
+$cloneStmt->bindValue(':start_date', $subscriptionToClone['start_date'], SQLITE3_TEXT);
+$cloneStmt->bindValue(':cycle', $subscriptionToClone['cycle'], SQLITE3_TEXT);
+$cloneStmt->bindValue(':frequency', $subscriptionToClone['frequency'], SQLITE3_INTEGER);
+$cloneStmt->bindValue(':notes', $subscriptionToClone['notes'], SQLITE3_TEXT);
+$cloneStmt->bindValue(':payment_method_id', $subscriptionToClone['payment_method_id'], SQLITE3_INTEGER);
+$cloneStmt->bindValue(':payer_user_id', $subscriptionToClone['payer_user_id'], SQLITE3_INTEGER);
+$cloneStmt->bindValue(':category_id', $subscriptionToClone['category_id'], SQLITE3_INTEGER);
+$cloneStmt->bindValue(':notify', $subscriptionToClone['notify'], SQLITE3_INTEGER);
+$cloneStmt->bindValue(':url', $subscriptionToClone['url'], SQLITE3_TEXT);
+$cloneStmt->bindValue(':inactive', $subscriptionToClone['inactive'], SQLITE3_INTEGER);
+$cloneStmt->bindValue(':notify_days_before', $subscriptionToClone['notify_days_before'], SQLITE3_INTEGER);
+$cloneStmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+$cloneStmt->bindValue(':cancellation_date', $subscriptionToClone['cancellation_date'], SQLITE3_TEXT);
+$cloneStmt->bindValue(':replacement_subscription_id', $subscriptionToClone['replacement_subscription_id'], SQLITE3_INTEGER);
+
+if ($cloneStmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('success', $i18n),
+ "id" => $db->lastInsertRowID()
+ ];
+ echo json_encode($response);
+} else {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
+
+$db->close();
?>
\ No newline at end of file
diff --git a/endpoints/subscription/delete.php b/endpoints/subscription/delete.php
index bac56ac..e8d7cf0 100644
--- a/endpoints/subscription/delete.php
+++ b/endpoints/subscription/delete.php
@@ -1,30 +1,31 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "DELETE") {
- $subscriptionId = $_GET["id"];
- $deleteQuery = "DELETE FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId";
- $deleteStmt = $db->prepare($deleteQuery);
- $deleteStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
- $deleteStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
- if ($deleteStmt->execute()) {
- $query = "UPDATE subscriptions SET replacement_subscription_id = NULL WHERE replacement_subscription_id = :subscriptionId AND user_id = :userId";
- $stmt = $db->prepare($query);
- $stmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $stmt->execute();
+$subscriptionId = $data["id"];
+$deleteQuery = "DELETE FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId";
+$deleteStmt = $db->prepare($deleteQuery);
+$deleteStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
+$deleteStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- http_response_code(204);
- } else {
- http_response_code(500);
- echo json_encode(array("message" => translate('error_deleting_subscription', $i18n)));
- }
- } else {
- http_response_code(405);
- echo json_encode(array("message" => translate('invalid_request_method', $i18n)));
- }
+if ($deleteStmt->execute()) {
+ $query = "UPDATE subscriptions SET replacement_subscription_id = NULL WHERE replacement_subscription_id = :subscriptionId AND user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $stmt->execute();
+
+ echo json_encode([
+ "success" => true,
+ "message" => translate('subscription_deleted', $i18n)
+ ]);
+} else {
+ echo json_encode([
+ "success" => false,
+ "message" => translate('error_deleting_subscription', $i18n)
+ ]);
}
-$db->close();
-?>
\ No newline at end of file
+$db->close();
\ No newline at end of file
diff --git a/endpoints/subscription/exportcalendar.php b/endpoints/subscription/exportcalendar.php
index 396179f..b44d6e0 100644
--- a/endpoints/subscription/exportcalendar.php
+++ b/endpoints/subscription/exportcalendar.php
@@ -1,53 +1,46 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
require_once '../../includes/getdbkeys.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+$id = $data['id'];
- $id = $data['id'];
+$stmt = $db->prepare('SELECT * FROM subscriptions WHERE id = :id AND user_id = :userId');
+$stmt->bindParam(':id', $id, SQLITE3_INTEGER);
+$stmt->bindParam(':userId', $_SESSION['userId'], SQLITE3_INTEGER);
+$result = $stmt->execute();
- $stmt = $db->prepare('SELECT * FROM subscriptions WHERE id = :id AND user_id = :userId');
- $stmt->bindParam(':id', $id, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $_SESSION['userId'], SQLITE3_INTEGER); // Assuming $_SESSION['userId'] holds the logged-in user's ID
- $result = $stmt->execute();
+if ($result === false) {
+ die(json_encode([
+ 'success' => false,
+ 'message' => "Subscription not found"
+ ]));
+}
- if ($result === false) {
- die(json_encode([
- 'success' => false,
- 'message' => "Subscription not found"
- ]));
- }
+$subscription = $result->fetchArray(SQLITE3_ASSOC); // Fetch the subscription details as an associative array
- $subscription = $result->fetchArray(SQLITE3_ASSOC); // Fetch the subscription details as an associative array
+if ($subscription) {
+ $subscription['payer_user'] = $members[$subscription['payer_user_id']]['name'];
+ $subscription['category'] = $categories[$subscription['category_id']]['name'];
+ $subscription['payment_method'] = $payment_methods[$subscription['payment_method_id']]['name'];
+ $subscription['currency'] = $currencies[$subscription['currency_id']]['symbol'];
+ $subscription['trigger'] = $subscription['notify_days_before'] ? $subscription['notify_days_before'] : 1;
+ $subscription['price'] = number_format($subscription['price'], 2);
- if ($subscription) {
- $subscription['payer_user'] = $members[$subscription['payer_user_id']]['name'];
- $subscription['category'] = $categories[$subscription['category_id']]['name'];
- $subscription['payment_method'] = $payment_methods[$subscription['payment_method_id']]['name'];
- $subscription['currency'] = $currencies[$subscription['currency_id']]['symbol'];
- $subscription['trigger'] = $subscription['notify_days_before'] ? $subscription['notify_days_before'] : 1;
- $subscription['price'] = number_format($subscription['price'], 2);
+ // Create ICS from subscription information
+ $uid = uniqid();
+ $summary = html_entity_decode($subscription['name'], ENT_QUOTES, 'UTF-8');
+ $description = "Price: {$subscription['currency']}{$subscription['price']}\nCategory: {$subscription['category']}\nPayment Method: {$subscription['payment_method']}\nPayer: {$subscription['payer_user']}\n\nNotes: {$subscription['notes']}";
- // Create ICS from subscription information
- $uid = uniqid();
- $summary = html_entity_decode($subscription['name'], ENT_QUOTES, 'UTF-8');
- $description = "Price: {$subscription['currency']}{$subscription['price']}\nCategory: {$subscription['category']}\nPayment Method: {$subscription['payment_method']}\nPayer: {$subscription['payer_user']}\n\nNotes: {$subscription['notes']}";
-
- $dtstart = (new DateTime($subscription['next_payment']))->format('Ymd\THis\Z');
- $dtend = (new DateTime($subscription['next_payment']))->modify('+1 hour')->format('Ymd\THis\Z');
- $location = isset($subscription['url']) ? $subscription['url'] : '';
- $alarm_trigger = '-P' . $subscription['trigger'] . 'D';
+ $dtstart = (new DateTime($subscription['next_payment']))->format('Ymd\THis\Z');
+ $dtend = (new DateTime($subscription['next_payment']))->modify('+1 hour')->format('Ymd\THis\Z');
+ $location = isset($subscription['url']) ? $subscription['url'] : '';
+ $alarm_trigger = '-P' . $subscription['trigger'] . 'D';
- $icsContent = <<<ICS
+ $icsContent = <<<ICS
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Your Organization//Your Application//EN
@@ -71,16 +64,14 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") {
END:VCALENDAR
ICS;
- echo json_encode([
- 'success' => true,
- 'ics' => $icsContent,
- 'name' => $subscription['name']
- ]);
- } else {
- echo json_encode([
- 'success' => false,
- 'message' => "Subscription not found"
- ]);
- }
-}
-?>
\ No newline at end of file
+ echo json_encode([
+ 'success' => true,
+ 'ics' => $icsContent,
+ 'name' => $subscription['name']
+ ]);
+} else {
+ echo json_encode([
+ 'success' => false,
+ 'message' => "Subscription not found"
+ ]);
+}
\ No newline at end of file
diff --git a/endpoints/subscription/renew.php b/endpoints/subscription/renew.php
index 174fd6c..f35d377 100644
--- a/endpoints/subscription/renew.php
+++ b/endpoints/subscription/renew.php
@@ -1,89 +1,75 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
- if ($_SERVER["REQUEST_METHOD"] === "GET") {
- $currentDate = new DateTime();
- $currentDateString = $currentDate->format('Y-m-d');
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
- $cycles = array();
- $query = "SELECT * FROM cycles";
- $result = $db->query($query);
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $cycleId = $row['id'];
- $cycles[$cycleId] = $row;
- }
+$currentDate = new DateTime();
+$currentDateString = $currentDate->format('Y-m-d');
- $subscriptionId = $_GET["id"];
- $query = "SELECT * FROM subscriptions WHERE id = :id AND user_id = :user_id AND auto_renew = 0";
- $stmt = $db->prepare($query);
- $stmt->bindValue(':id', $subscriptionId, SQLITE3_INTEGER);
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $subscriptionToRenew = $result->fetchArray(SQLITE3_ASSOC);
- if ($subscriptionToRenew === false) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
+$cycles = array();
+$query = "SELECT * FROM cycles";
+$result = $db->query($query);
+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $cycleId = $row['id'];
+ $cycles[$cycleId] = $row;
+}
+
+$subscriptionId = $data["id"];
+$query = "SELECT * FROM subscriptions WHERE id = :id AND user_id = :user_id AND auto_renew = 0";
+$stmt = $db->prepare($query);
+$stmt->bindValue(':id', $subscriptionId, SQLITE3_INTEGER);
+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
+$subscriptionToRenew = $result->fetchArray(SQLITE3_ASSOC);
+if ($subscriptionToRenew === false) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+}
- $nextPaymentDate = new DateTime($subscriptionToRenew['next_payment']);
- $frequency = $subscriptionToRenew['frequency'];
- $cycle = $cycles[$subscriptionToRenew['cycle']]['name'];
+$nextPaymentDate = new DateTime($subscriptionToRenew['next_payment']);
+$frequency = $subscriptionToRenew['frequency'];
+$cycle = $cycles[$subscriptionToRenew['cycle']]['name'];
- // Calculate the interval to add based on the cycle
- $intervalSpec = "P";
- if ($cycle == 'Daily') {
- $intervalSpec .= "{$frequency}D";
- } elseif ($cycle === 'Weekly') {
- $intervalSpec .= "{$frequency}W";
- } elseif ($cycle === 'Monthly') {
- $intervalSpec .= "{$frequency}M";
- } elseif ($cycle === 'Yearly') {
- $intervalSpec .= "{$frequency}Y";
- }
+// Calculate the interval to add based on the cycle
+$intervalSpec = "P";
+if ($cycle == 'Daily') {
+ $intervalSpec .= "{$frequency}D";
+} elseif ($cycle === 'Weekly') {
+ $intervalSpec .= "{$frequency}W";
+} elseif ($cycle === 'Monthly') {
+ $intervalSpec .= "{$frequency}M";
+} elseif ($cycle === 'Yearly') {
+ $intervalSpec .= "{$frequency}Y";
+}
- $interval = new DateInterval($intervalSpec);
+$interval = new DateInterval($intervalSpec);
- // Add intervals until the next payment date is in the future and after current next payment date
- while ($nextPaymentDate < $currentDate || $nextPaymentDate == new DateTime($subscriptionToRenew['next_payment'])) {
- $nextPaymentDate->add($interval);
- }
+// Add intervals until the next payment date is in the future and after current next payment date
+while ($nextPaymentDate < $currentDate || $nextPaymentDate == new DateTime($subscriptionToRenew['next_payment'])) {
+ $nextPaymentDate->add($interval);
+}
- // Update the subscription's next_payment date
- $updateQuery = "UPDATE subscriptions SET next_payment = :nextPaymentDate WHERE id = :subscriptionId";
- $updateStmt = $db->prepare($updateQuery);
- $updateStmt->bindValue(':nextPaymentDate', $nextPaymentDate->format('Y-m-d'));
- $updateStmt->bindValue(':subscriptionId', $subscriptionId);
- $updateStmt->execute();
+// Update the subscription's next_payment date
+$updateQuery = "UPDATE subscriptions SET next_payment = :nextPaymentDate WHERE id = :subscriptionId";
+$updateStmt = $db->prepare($updateQuery);
+$updateStmt->bindValue(':nextPaymentDate', $nextPaymentDate->format('Y-m-d'));
+$updateStmt->bindValue(':subscriptionId', $subscriptionId);
+$updateStmt->execute();
- if ($updateStmt->execute()) {
- $response = [
- "success" => true,
- "message" => translate('success', $i18n),
- "id" => $subscriptionId
- ];
- echo json_encode($response);
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
- } else {
- $db->close();
- die(json_encode([
- "success" => false,
- "message" => translate('invalid_request_method', $i18n)
- ]));
- }
+if ($updateStmt->execute()) {
+ $response = [
+ "success" => true,
+ "message" => translate('success', $i18n),
+ "id" => $subscriptionId
+ ];
+ echo json_encode($response);
} else {
- $db->close();
die(json_encode([
"success" => false,
- "message" => translate('session_expired', $i18n)
+ "message" => translate("error", $i18n)
]));
-}
-
-?>
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/endpoints/user/budget.php b/endpoints/user/budget.php
index a129882..0ad07f9 100644
--- a/endpoints/user/budget.php
+++ b/endpoints/user/budget.php
@@ -2,39 +2,31 @@
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
-
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
+require_once '../../includes/validate_endpoint.php';
+
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+$budget = $data["budget"];
+
+$sql = "UPDATE user SET budget = :budget WHERE id = :userId";
+$stmt = $db->prepare($sql);
+$stmt->bindValue(':budget', $budget, SQLITE3_TEXT);
+$stmt->bindValue(':userId', $userId, SQLITE3_TEXT);
+$result = $stmt->execute();
+
+if ($result) {
+ $response = [
+ "success" => true,
+ "message" => translate('user_details_saved', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $response = [
"success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $budget = $data["budget"];
-
- $sql = "UPDATE user SET budget = :budget WHERE id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':budget', $budget, SQLITE3_TEXT);
- $stmt->bindValue(':userId', $userId, SQLITE3_TEXT);
- $result = $stmt->execute();
-
- if ($result) {
- $response = [
- "success" => true,
- "message" => translate('user_details_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_updating_user_data', $i18n)
- ];
- echo json_encode($response);
- }
+ "message" => translate('error_updating_user_data', $i18n)
+ ];
+ echo json_encode($response);
}
diff --git a/endpoints/user/delete_avatar.php b/endpoints/user/delete_avatar.php
index 8217670..ae9ec47 100644
--- a/endpoints/user/delete_avatar.php
+++ b/endpoints/user/delete_avatar.php
@@ -1,13 +1,7 @@
<?php
require_once '../../includes/connect_endpoint.php';
-
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+require_once '../../includes/validate_endpoint.php';
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input['avatar'])) {
diff --git a/endpoints/user/disable_totp.php b/endpoints/user/disable_totp.php
index ecdaa55..25a4ddc 100644
--- a/endpoints/user/disable_totp.php
+++ b/endpoints/user/disable_totp.php
@@ -2,6 +2,7 @@
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
+require_once '../../includes/validate_endpoint.php';
if (!function_exists('trigger_deprecation')) {
function trigger_deprecation($package, $version, $message, ...$args)
@@ -12,15 +13,6 @@ if (!function_exists('trigger_deprecation')) {
}
}
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n),
- "reload" => false
- ]));
-}
-
-
$statement = $db->prepare('SELECT totp_enabled FROM user WHERE id = :id');
$statement->bindValue(':id', $userId, SQLITE3_INTEGER);
$result = $statement->execute();
@@ -34,43 +26,69 @@ if ($row['totp_enabled'] == 0) {
]));
}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- if (isset($data['totpCode']) && $data['totpCode'] != "") {
- require_once __DIR__ . '/../../libs/OTPHP/FactoryInterface.php';
- require_once __DIR__ . '/../../libs/OTPHP/Factory.php';
- require_once __DIR__ . '/../../libs/OTPHP/ParameterTrait.php';
- require_once __DIR__ . '/../../libs/OTPHP/OTPInterface.php';
- require_once __DIR__ . '/../../libs/OTPHP/OTP.php';
- require_once __DIR__ . '/../../libs/OTPHP/TOTPInterface.php';
- require_once __DIR__ . '/../../libs/OTPHP/TOTP.php';
- require_once __DIR__ . '/../../libs/Psr/Clock/ClockInterface.php';
- require_once __DIR__ . '/../../libs/OTPHP/InternalClock.php';
- require_once __DIR__ . '/../../libs/constant_time_encoding/Binary.php';
- require_once __DIR__ . '/../../libs/constant_time_encoding/EncoderInterface.php';
- require_once __DIR__ . '/../../libs/constant_time_encoding/Base32.php';
-
- $totp_code = $data['totpCode'];
-
- $statement = $db->prepare('SELECT totp_secret FROM totp WHERE user_id = :id');
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (isset($data['totpCode']) && $data['totpCode'] != "") {
+ require_once __DIR__ . '/../../libs/OTPHP/FactoryInterface.php';
+ require_once __DIR__ . '/../../libs/OTPHP/Factory.php';
+ require_once __DIR__ . '/../../libs/OTPHP/ParameterTrait.php';
+ require_once __DIR__ . '/../../libs/OTPHP/OTPInterface.php';
+ require_once __DIR__ . '/../../libs/OTPHP/OTP.php';
+ require_once __DIR__ . '/../../libs/OTPHP/TOTPInterface.php';
+ require_once __DIR__ . '/../../libs/OTPHP/TOTP.php';
+ require_once __DIR__ . '/../../libs/Psr/Clock/ClockInterface.php';
+ require_once __DIR__ . '/../../libs/OTPHP/InternalClock.php';
+ require_once __DIR__ . '/../../libs/constant_time_encoding/Binary.php';
+ require_once __DIR__ . '/../../libs/constant_time_encoding/EncoderInterface.php';
+ require_once __DIR__ . '/../../libs/constant_time_encoding/Base32.php';
+
+ $totp_code = $data['totpCode'];
+
+ $statement = $db->prepare('SELECT totp_secret FROM totp WHERE user_id = :id');
+ $statement->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $statement->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $secret = $row['totp_secret'];
+
+ $statement = $db->prepare('SELECT backup_codes FROM totp WHERE user_id = :id');
+ $statement->bindValue(':id', $userId, SQLITE3_INTEGER);
+ $result = $statement->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $backupCodes = $row['backup_codes'];
+
+ $clock = new OTPHP\InternalClock();
+ $totp = OTPHP\TOTP::createFromSecret($secret, $clock);
+ $totp->setPeriod(30);
+
+ if ($totp->verify($totp_code, null, 15)) {
+ $statement = $db->prepare('UPDATE user SET totp_enabled = 0 WHERE id = :id');
$statement->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $statement->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $secret = $row['totp_secret'];
+ $statement->execute();
- $statement = $db->prepare('SELECT backup_codes FROM totp WHERE user_id = :id');
+ $statement = $db->prepare('DELETE FROM totp WHERE user_id = :id');
$statement->bindValue(':id', $userId, SQLITE3_INTEGER);
- $result = $statement->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $backupCodes = $row['backup_codes'];
+ $statement->execute();
- $clock = new OTPHP\InternalClock();
- $totp = OTPHP\TOTP::createFromSecret($secret, $clock);
- $totp->setPeriod(30);
-
- if ($totp->verify($totp_code, null, 15)) {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('success', $i18n),
+ "reload" => true
+ ]));
+ } else {
+ // Compare the TOTP code agains the backup codes
+ // Normalize TOTP input
+ $totp_code = strtolower(trim((string) $totp_code));
+
+ // Decode and normalize backup codes
+ $backupCodes = json_decode($backupCodes, true);
+ $normalizedBackupCodes = array_map(function ($code) {
+ return strtolower(trim((string) $code));
+ }, $backupCodes);
+
+ // Search for the normalized code
+ if (($key = array_search($totp_code, $normalizedBackupCodes)) !== false) {
+ // Match found, disable TOTP
$statement = $db->prepare('UPDATE user SET totp_enabled = 0 WHERE id = :id');
$statement->bindValue(':id', $userId, SQLITE3_INTEGER);
$statement->execute();
@@ -85,53 +103,19 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") {
"reload" => true
]));
} else {
- // Compare the TOTP code agains the backup codes
- // Normalize TOTP input
- $totp_code = strtolower(trim((string) $totp_code));
-
- // Decode and normalize backup codes
- $backupCodes = json_decode($backupCodes, true);
- $normalizedBackupCodes = array_map(function ($code) {
- return strtolower(trim((string) $code));
- }, $backupCodes);
-
- // Search for the normalized code
- if (($key = array_search($totp_code, $normalizedBackupCodes)) !== false) {
- // Match found, disable TOTP
- $statement = $db->prepare('UPDATE user SET totp_enabled = 0 WHERE id = :id');
- $statement->bindValue(':id', $userId, SQLITE3_INTEGER);
- $statement->execute();
-
- $statement = $db->prepare('DELETE FROM totp WHERE user_id = :id');
- $statement->bindValue(':id', $userId, SQLITE3_INTEGER);
- $statement->execute();
-
- die(json_encode([
- "success" => true,
- "message" => translate('success', $i18n),
- "reload" => true
- ]));
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate('totp_code_incorrect', $i18n),
- "reload" => false
- ]));
- }
-
+ die(json_encode([
+ "success" => false,
+ "message" => translate('totp_code_incorrect', $i18n),
+ "reload" => false
+ ]));
}
- } else {
- die(json_encode([
- "success" => false,
- "message" => translate('fields_missing', $i18n),
- "reload" => false
- ]));
}
+
} else {
die(json_encode([
"success" => false,
- "message" => translate('invalid_request_method', $i18n),
+ "message" => translate('fields_missing', $i18n),
"reload" => false
]));
}
\ No newline at end of file
diff --git a/endpoints/user/enable_totp.php b/endpoints/user/enable_totp.php
index 0e77307..c306003 100644
--- a/endpoints/user/enable_totp.php
+++ b/endpoints/user/enable_totp.php
@@ -2,6 +2,7 @@
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
+require_once '../../includes/validate_endpoint.php';
if (!function_exists('trigger_deprecation')) {
function trigger_deprecation($package, $version, $message, ...$args)
@@ -12,14 +13,13 @@ if (!function_exists('trigger_deprecation')) {
}
}
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true) ?? [];
+
+$action = $data['action'] ?? '';
+
+if ($action === 'generate') {
-if ($_SERVER["REQUEST_METHOD"] === "GET") {
function base32_encode($hex)
{
$alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
@@ -39,23 +39,19 @@ if ($_SERVER["REQUEST_METHOD"] === "GET") {
return $base32;
}
- $data = $_GET;
- if (isset($data['generate']) && $data['generate'] == true) {
- $secret = base32_encode(bin2hex(random_bytes(20)));
- $qrCodeUrl = "otpauth://totp/Wallos:" . $_SESSION['username'] . "?secret=" . $secret . "&issuer=Wallos";
- $response = [
- "success" => true,
- "secret" => $secret,
- "qrCodeUrl" => $qrCodeUrl
- ];
- echo json_encode($response);
- }
-}
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
+ $secret = base32_encode(bin2hex(random_bytes(20)));
+ $qrCodeUrl = "otpauth://totp/Wallos:" . $_SESSION['username'] . "?secret=" . $secret . "&issuer=Wallos";
+ echo json_encode([
+ "success" => true,
+ "secret" => $secret,
+ "qrCodeUrl" => $qrCodeUrl,
+ ]);
+ exit;
+}
+
+if ($action === 'verify') {
if (isset($data['totpSecret']) && $data['totpSecret'] != "" && isset($data['totpCode']) && $data['totpCode'] != "") {
require_once __DIR__ . '/../../libs/OTPHP/FactoryInterface.php';
require_once __DIR__ . '/../../libs/OTPHP/Factory.php';
@@ -134,8 +130,4 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") {
"message" => translate('totp_code_incorrect', $i18n)
]));
}
-
-
-
-
}
\ No newline at end of file
diff --git a/endpoints/user/regenerateapikey.php b/endpoints/user/regenerateapikey.php
index 3034d12..f4412c3 100644
--- a/endpoints/user/regenerateapikey.php
+++ b/endpoints/user/regenerateapikey.php
@@ -1,40 +1,29 @@
<?php
require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
-if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
- die(json_encode([
- "success" => false,
- "message" => translate('session_expired', $i18n)
- ]));
-}
-
-if ($_SERVER["REQUEST_METHOD"] === "POST") {
- $postData = file_get_contents("php://input");
- $data = json_decode($postData, true);
-
- $apiKey = bin2hex(random_bytes(32));
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
- $sql = "UPDATE user SET api_key = :apiKey WHERE id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':apiKey', $apiKey, SQLITE3_TEXT);
- $stmt->bindValue(':userId', $userId, SQLITE3_TEXT);
- $result = $stmt->execute();
+$apiKey = bin2hex(random_bytes(32));
- if ($result) {
- $response = [
- "success" => true,
- "message" => translate('user_details_saved', $i18n),
- "apiKey" => $apiKey
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_updating_user_data', $i18n)
- ];
- echo json_encode($response);
- }
+$sql = "UPDATE user SET api_key = :apiKey WHERE id = :userId";
+$stmt = $db->prepare($sql);
+$stmt->bindValue(':apiKey', $apiKey, SQLITE3_TEXT);
+$stmt->bindValue(':userId', $userId, SQLITE3_TEXT);
+$result = $stmt->execute();
-}
-
-?>
\ No newline at end of file
+if ($result) {
+ $response = [
+ "success" => true,
+ "message" => translate('user_details_saved', $i18n),
+ "apiKey" => $apiKey
+ ];
+ echo json_encode($response);
+} else {
+ $response = [
+ "success" => false,
+ "message" => translate('error_updating_user_data', $i18n)
+ ];
+ echo json_encode($response);
+}
\ No newline at end of file
diff --git a/endpoints/user/save_user.php b/endpoints/user/save_user.php
index 7cbdb15..e94661a 100644
--- a/endpoints/user/save_user.php
+++ b/endpoints/user/save_user.php
@@ -1,6 +1,7 @@
<?php
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
+require_once '../../includes/validate_endpoint.php';
if (!file_exists('../../images/uploads/logos')) {
mkdir('../../images/uploads/logos', 0777, true);
@@ -229,7 +230,7 @@ if (
if ($otherUser) {
$response = [
"success" => false,
- "errorMessage" => translate('email_exists', $i18n)
+ "message" => translate('email_exists', $i18n)
];
echo json_encode($response);
exit();
@@ -247,7 +248,7 @@ if (
if (strpos($fileType, 'image') === false) {
$response = [
"success" => false,
- "errorMessage" => translate('fill_all_fields', $i18n)
+ "message" => translate('fill_all_fields', $i18n)
];
echo json_encode($response);
exit();
@@ -263,7 +264,7 @@ if (
if ($password != $confirm) {
$response = [
"success" => false,
- "errorMessage" => translate('passwords_dont_match', $i18n)
+ "message" => translate('passwords_dont_match', $i18n)
];
echo json_encode($response);
exit();
@@ -271,7 +272,7 @@ if (
} else {
$response = [
"success" => false,
- "errorMessage" => translate('passwords_dont_match', $i18n)
+ "message" => translate('passwords_dont_match', $i18n)
];
echo json_encode($response);
exit();
@@ -329,7 +330,7 @@ if (
} else {
$response = [
"success" => false,
- "errorMessage" => translate('error_updating_user_data', $i18n)
+ "message" => translate('error_updating_user_data', $i18n)
];
echo json_encode($response);
}
@@ -338,9 +339,8 @@ if (
} else {
$response = [
"success" => false,
- "errorMessage" => translate('fill_all_fields', $i18n)
+ "message" => translate('fill_all_fields', $i18n)
];
echo json_encode($response);
exit();
}
-?>
diff --git a/includes/header.php b/includes/header.php
index 2251a18..593821c 100644
--- a/includes/header.php
+++ b/includes/header.php
@@ -5,6 +5,8 @@ require_once 'checksession.php';
require_once 'checkredirect.php';
require_once 'currency_formatter.php';
+require_once 'libs/csrf.php';
+
require_once 'i18n/languages.php';
require_once 'i18n/getlang.php';
require_once 'i18n/' . $lang . '.php';
@@ -108,6 +110,7 @@ $mobileNavigation = $settings['mobile_nav'] ? "mobile-navigation" : "";
window.lang = "<?= $lang ?>";
window.colorTheme = "<?= $colorTheme ?>";
window.mobileNavigation = "<?= $settings['mobileNavigation'] == "true" ?>";
+ window.csrfToken = "<?= htmlspecialchars(generate_csrf_token()) ?>";
</script>
<style>
<?= htmlspecialchars($customCss, ENT_QUOTES, 'UTF-8') ?>
diff --git a/includes/validate_endpoint.php b/includes/validate_endpoint.php
new file mode 100644
index 0000000..c20d1b9
--- /dev/null
+++ b/includes/validate_endpoint.php
@@ -0,0 +1,22 @@
+<?php
+// All requests should be POST requests
+// CSRF Token must be included and match the token stored on the session
+// User must be logged in
+
+require_once __DIR__ . '/../libs/csrf.php';
+
+if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
+ echo json_encode(["success" => false, "message" => "Invalid request method"]);
+ exit;
+}
+
+$csrf = $_POST['csrf_token'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
+if (!verify_csrf_token($csrf)) {
+ echo json_encode(["success" => false, "message" => "Invalid CSRF token"]);
+ exit;
+}
+
+if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
+ echo json_encode(["success" => false, "message" => translate('session_expired', $i18n)]);
+ exit;
+}
\ No newline at end of file
diff --git a/includes/validate_endpoint_admin.php b/includes/validate_endpoint_admin.php
new file mode 100644
index 0000000..4068b72
--- /dev/null
+++ b/includes/validate_endpoint_admin.php
@@ -0,0 +1,9 @@
+<?php
+require_once __DIR__ . '/validate_endpoint.php';
+// Check that user is an admin
+if ($userId !== 1) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('error', $i18n)
+ ]));
+}
\ No newline at end of file
diff --git a/includes/version.php b/includes/version.php
index 86a1644..5417fee 100644
--- a/includes/version.php
+++ b/includes/version.php
@@ -1,3 +1,3 @@
<?php
-$version = "v4.4.1";
+$version = "v4.5.0";
?>
\ No newline at end of file
diff --git a/libs/csrf.php b/libs/csrf.php
new file mode 100644
index 0000000..1ff4311
--- /dev/null
+++ b/libs/csrf.php
@@ -0,0 +1,18 @@
+<?php
+
+if (session_status() !== PHP_SESSION_ACTIVE) {
+ session_start();
+}
+
+function generate_csrf_token(): string {
+ if (empty($_SESSION['csrf_token'])) {
+ $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
+ }
+ return $_SESSION['csrf_token'];
+}
+
+function verify_csrf_token(?string $token): bool {
+ if (empty($_SESSION['csrf_token']) || empty($token)) return false;
+ // Use hash_equals to avoid timing attacks
+ return hash_equals($_SESSION['csrf_token'], $token);
+}
\ No newline at end of file
diff --git a/scripts/admin.js b/scripts/admin.js
index 29e945b..a19b293 100644
--- a/scripts/admin.js
+++ b/scripts/admin.js
@@ -3,6 +3,7 @@ function makeFetchCall(url, data, button) {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify(data),
})
@@ -69,6 +70,7 @@ function saveSmtpSettingsButton() {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify(data),
})
@@ -94,37 +96,45 @@ function backupDB() {
const button = document.getElementById("backupDB");
button.disabled = true;
- fetch('endpoints/db/backup.php')
+ fetch("endpoints/db/backup.php", {
+ method: "POST",
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
+ })
.then(response => response.json())
.then(data => {
if (data.success) {
- const link = document.createElement('a');
+ const link = document.createElement("a");
const filename = data.file;
- link.href = '.tmp/' + filename;
+ link.href = ".tmp/" + filename;
+
const date = new Date();
const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0');
- const day = String(date.getDate()).padStart(2, '0');
- const hours = String(date.getHours()).padStart(2, '0');
- const minutes = String(date.getMinutes()).padStart(2, '0');
+ const month = String(date.getMonth() + 1).padStart(2, "0");
+ const day = String(date.getDate()).padStart(2, "0");
+ const hours = String(date.getHours()).padStart(2, "0");
+ const minutes = String(date.getMinutes()).padStart(2, "0");
const timestamp = `${year}${month}${day}-${hours}${minutes}`;
link.download = `Wallos-Backup-${timestamp}.zip`;
+
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
-
- button.disabled = false;
} else {
- showErrorMessage(data.errorMessage);
- button.disabled = false;
+ showErrorMessage(data.message || translate("backup_failed"));
}
})
.catch(error => {
- showErrorMessage(error);
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ })
+ .finally(() => {
button.disabled = false;
});
}
+
function openRestoreDBFileSelect() {
document.getElementById('restoreDBFile').click();
};
@@ -134,34 +144,47 @@ function restoreDB() {
const file = input.files[0];
if (!file) {
- console.error('No file selected');
+ showErrorMessage(translate('no_file_selected'));
return;
}
const formData = new FormData();
formData.append('file', file);
+ const button = document.getElementById('restoreDB');
+ button.disabled = true;
+
fetch('endpoints/db/restore.php', {
method: 'POST',
- body: formData
+ headers: {
+ 'X-CSRF-Token': window.csrfToken, // ✅ CSRF protection
+ },
+ body: formData,
})
.then(response => response.json())
.then(data => {
if (data.success) {
showSuccessMessage(data.message);
+
+ // After restoring, run migrations then log out (force re-login)
fetch('endpoints/db/migrate.php')
- .then(response => response.text())
.then(() => {
window.location.href = 'logout.php';
})
- .catch(error => {
+ .catch(() => {
window.location.href = 'logout.php';
});
} else {
- showErrorMessage(data.message);
+ showErrorMessage(data.message || translate('restore_failed'));
}
})
- .catch(error => showErrorMessage('Error:', error));
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(translate('unknown_error'));
+ })
+ .finally(() => {
+ button.disabled = false;
+ });
}
function saveAccountRegistrationsButton() {
@@ -185,7 +208,8 @@ function saveAccountRegistrationsButton() {
fetch('endpoints/admin/saveopenregistrations.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify(data)
})
@@ -213,7 +237,8 @@ function removeUser(userId) {
fetch('endpoints/admin/deleteuser.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify(data)
})
@@ -250,7 +275,8 @@ function addUserButton() {
fetch('endpoints/admin/adduser.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify(data)
})
@@ -275,7 +301,13 @@ function deleteUnusedLogos() {
const button = document.getElementById('deleteUnusedLogos');
button.disabled = true;
- fetch('endpoints/admin/deleteunusedlogos.php')
+ fetch('endpoints/admin/deleteunusedlogos.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
+ }
+ })
.then(response => response.json())
.then(data => {
if (data.success) {
@@ -304,7 +336,8 @@ function toggleUpdateNotification() {
fetch('endpoints/admin/updatenotification.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify(data)
})
@@ -346,7 +379,7 @@ function toggleOidcEnabled() {
toggle.disabled = true;
const oidcEnabled = toggle.checked ? 1 : 0;
-
+
const data = {
oidcEnabled: oidcEnabled
};
@@ -354,7 +387,8 @@ function toggleOidcEnabled() {
fetch('endpoints/admin/enableoidc.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify(data)
})
@@ -412,7 +446,8 @@ function saveOidcSettingsButton() {
fetch('endpoints/admin/saveoidcsettings.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify(data)
})
diff --git a/scripts/calendar.js b/scripts/calendar.js
index 83ba4ad..578329c 100644
--- a/scripts/calendar.js
+++ b/scripts/calendar.js
@@ -84,7 +84,8 @@ function exportCalendar(subscriptionId) {
method: 'POST',
body: JSON.stringify({id: subscriptionId}),
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
}
})
.then(response => response.json())
@@ -100,7 +101,7 @@ function exportCalendar(subscriptionId) {
a.click();
window.URL.revokeObjectURL(url);
} else {
- console.error('Failed to download the calendar file.');
+ showErrorMessage(data.message);
}
})
.catch(error => console.error('Error:', error));
diff --git a/scripts/dashboard.js b/scripts/dashboard.js
index 3ea5b7b..e0443ef 100644
--- a/scripts/dashboard.js
+++ b/scripts/dashboard.js
@@ -9,24 +9,33 @@ document.addEventListener("DOMContentLoaded", function () {
el.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
+
const item = el.closest(".ai-recommendation-item");
const id = item.getAttribute("data-id");
+
fetch("endpoints/ai/delete_recommendation.php", {
method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ id: id })
+ headers: {
+ "Content-Type": "application/json",
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ id: id }),
})
.then(res => res.json())
.then(data => {
if (data.success) {
item.remove();
- showSuccessMessage(translate('success'));
+ showSuccessMessage(translate("success"));
} else {
- showErrorMessage(data.message || "Delete failed.");
+ showErrorMessage(data.message || translate("failed_delete_ai_recommendation"));
}
})
- .catch(() => showErrorMessage(translate('unknown_error')));
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ });
});
});
+
});
diff --git a/scripts/notifications.js b/scripts/notifications.js
index 123f802..44d2fae 100644
--- a/scripts/notifications.js
+++ b/scripts/notifications.js
@@ -24,6 +24,7 @@ function makeFetchCall(url, data, button) {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
},
body: JSON.stringify(data),
})
diff --git a/scripts/profile.js b/scripts/profile.js
index e1f9768..d4c06ab 100644
--- a/scripts/profile.js
+++ b/scripts/profile.js
@@ -2,29 +2,40 @@ document.addEventListener('DOMContentLoaded', function () {
document.getElementById("userForm").addEventListener("submit", function (event) {
event.preventDefault();
- document.getElementById("userSubmit").disabled = true;
+ const submitButton = document.getElementById("userSubmit");
+ submitButton.disabled = true;
+
const formData = new FormData(event.target);
+ formData.append("action", "save");
+
fetch("endpoints/user/save_user.php", {
method: "POST",
- body: formData
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: formData,
})
.then(response => response.json())
.then(data => {
if (data.success) {
document.getElementById("avatar").src = document.getElementById("avatarImg").src;
- var newUsername = document.getElementById("username").value;
+ const newUsername = document.getElementById("username").value;
document.getElementById("user").textContent = newUsername;
showSuccessMessage(data.message);
+
if (data.reload) {
location.reload();
}
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message || translate("failed_save_user"));
}
- document.getElementById("userSubmit").disabled = false;
})
.catch(error => {
- showErrorMessage(translate('unknown_error'));
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ })
+ .finally(() => {
+ submitButton.disabled = false;
});
});
@@ -81,6 +92,7 @@ function deleteAvatar(path) {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
},
body: JSON.stringify({ avatar: path }),
})
@@ -102,31 +114,36 @@ function deleteAvatar(path) {
}
function enableTotp() {
- const totpSecret = document.querySelector('#totp-secret');
- const totpSecretCode = document.querySelector('#totp-secret-code');
- const qrCode = document.getElementById('totp-qr-code');
- totpSecret.value = '';
- totpSecretCode.textContent = '';
- qrCode.innerHTML = '';
-
- fetch('endpoints/user/enable_totp.php?generate=true', {
- method: 'GET'
+ const totpSecret = document.querySelector("#totp-secret");
+ const totpSecretCode = document.querySelector("#totp-secret-code");
+ const qrCode = document.getElementById("totp-qr-code");
+ totpSecret.value = "";
+ totpSecretCode.textContent = "";
+ qrCode.innerHTML = "";
+
+ fetch("endpoints/user/enable_totp.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ action: "generate" }),
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ totpSecret.value = data.secret;
+ totpSecretCode.textContent = data.secret;
+ new QRCode(qrCode, data.qrCodeUrl);
+ openTotpPopup();
+ } else {
+ showErrorMessage(data.message);
+ }
})
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- totpSecret.value = data.secret;
- totpSecretCode.textContent = data.secret;
- new QRCode(qrCode, data.qrCodeUrl);
-
- openTotpPopup();
- } else {
- showErrorMessage(data.message);
- }
- })
- .catch(error => {
- showErrorMessage(error);
- });
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ });
}
function openTotpPopup() {
@@ -157,8 +174,9 @@ function submitTotp() {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
},
- body: JSON.stringify({ totpCode: totpCode, totpSecret: totpSecret }),
+ body: JSON.stringify({ totpCode: totpCode, totpSecret: totpSecret, action: 'verify' }),
})
.then(response => response.json())
.then(data => {
@@ -233,6 +251,7 @@ function submitDisableTotp() {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
},
body: JSON.stringify({ totpCode: totpCode }),
})
@@ -253,29 +272,34 @@ function submitDisableTotp() {
}
function regenerateApiKey() {
- const regenerateButton = document.getElementById('regenerateApiKey');
- regenerateButton.disabled = true;
-
- fetch('endpoints/user/regenerateapikey.php', {
- method: 'POST',
- })
+ const regenerateButton = document.getElementById("regenerateApiKey");
+ regenerateButton.disabled = true;
+
+ fetch("endpoints/user/regenerateapikey.php", {
+ method: "POST",
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
+ })
.then(response => response.json())
.then(data => {
- regenerateButton.disabled = false;
- if (data.success) {
- const newApiKey = data.apiKey;
- document.getElementById('apikey').value = newApiKey;
- showSuccessMessage(data.message);
- } else {
- showErrorMessage(data.message);
- }
+ regenerateButton.disabled = false;
+ if (data.success) {
+ const newApiKey = data.apiKey;
+ document.getElementById("apikey").value = newApiKey;
+ showSuccessMessage(data.message);
+ } else {
+ showErrorMessage(data.message || translate("failed_regenerate_api_key"));
+ }
})
.catch(error => {
- regenerateButton.disabled = false;
- showErrorMessage(error);
+ console.error(error);
+ regenerateButton.disabled = false;
+ showErrorMessage(translate("unknown_error"));
});
}
+
function exportAsJson() {
fetch("endpoints/subscriptions/export.php")
.then(response => response.json())
@@ -337,6 +361,7 @@ function deleteAccount(userId) {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
},
body: JSON.stringify({ userId: userId }),
})
diff --git a/scripts/settings.js b/scripts/settings.js
index 448a80e..9713a62 100644
--- a/scripts/settings.js
+++ b/scripts/settings.js
@@ -27,9 +27,10 @@ function saveBudget() {
fetch('endpoints/user/budget.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
- body: JSON.stringify({ budget: budget })
+ body: JSON.stringify({budget: budget}),
})
.then(response => response.json())
.then(data => {
@@ -38,65 +39,70 @@ function saveBudget() {
} else {
showErrorMessage(data.message);
}
- button.disabled = false;
})
.catch(error => {
+ console.error(error);
showErrorMessage(translate('unknown_error'));
+ })
+ .finally(() => {
button.disabled = false;
});
-
}
+
function addMemberButton(memberId) {
- document.getElementById("addMember").disabled = true;
- const url = 'endpoints/household/household.php?action=add';
- fetch(url)
+ const addButton = document.getElementById("addMember");
+ addButton.disabled = true;
+
+ fetch("endpoints/household/household.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({action: "add"}),
+ })
.then(response => {
if (!response.ok) {
- throw new Error(translate('network_response_error'));
- showErrorMessage(translate('failed_add_member'));
+ showErrorMessage(translate("failed_add_member"));
+ throw new Error(translate("network_response_error"));
}
return response.json();
})
.then(responseData => {
if (responseData.success) {
- const newMemberId = responseData.householdId;;
- let container = document.getElementById("householdMembers");
- let div = document.createElement("div");
+ const newMemberId = responseData.householdId;
+ const container = document.getElementById("householdMembers");
+
+ const div = document.createElement("div");
div.className = "form-group-inline";
div.dataset.memberid = newMemberId;
- let input = document.createElement("input");
+ const input = document.createElement("input");
input.type = "text";
- input.placeholder = translate('member');
+ input.placeholder = translate("member");
input.name = "member";
- input.value = translate('member');
+ input.value = translate("member");
- let emailInput = document.createElement("input");
+ const emailInput = document.createElement("input");
emailInput.type = "text";
- emailInput.placeholder = translate('email');
+ emailInput.placeholder = translate("email");
emailInput.name = "email";
emailInput.value = "";
- let editLink = document.createElement("button");
- editLink.className = "image-button medium"
+ const editLink = document.createElement("button");
+ editLink.className = "image-button medium";
editLink.name = "save";
- editLink.onclick = function () {
- editMember(newMemberId);
- };
-
+ editLink.onclick = () => editMember(newMemberId);
editLink.innerHTML = editSvgContent;
- editLink.title = translate('save_member');
+ editLink.title = translate("save_member");
- let deleteLink = document.createElement("button");
- deleteLink.className = "image-button medium"
+ const deleteLink = document.createElement("button");
+ deleteLink.className = "image-button medium";
deleteLink.name = "delete";
- deleteLink.onclick = function () {
- removeMember(newMemberId);
- };
-
+ deleteLink.onclick = () => removeMember(newMemberId);
deleteLink.innerHTML = deleteSvgContent;
- deleteLink.title = translate('delete_member');
+ deleteLink.title = translate("delete_member");
div.appendChild(input);
div.appendChild(emailInput);
@@ -105,78 +111,115 @@ function addMemberButton(memberId) {
container.appendChild(div);
} else {
- showErrorMessage(responseData.errorMessage);
+ showErrorMessage(responseData.message || translate("failed_add_member"));
}
- document.getElementById("addMember").disabled = false;
})
.catch(error => {
- showErrorMessage(translate('failed_add_member'));
- document.getElementById("addMember").disabled = false;
+ console.error(error);
+ showErrorMessage(translate("failed_add_member"));
+ })
+ .finally(() => {
+ addButton.disabled = false;
});
-
}
function removeMember(memberId) {
- let url = `endpoints/household/household.php?action=delete&memberId=${memberId}`;
- fetch(url)
+ fetch("endpoints/household/household.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({
+ action: "delete",
+ memberId: memberId,
+ }),
+ })
.then(response => {
if (!response.ok) {
- throw new Error(translate('network_response_error'));
+ throw new Error(translate("network_response_error"));
}
return response.json();
})
.then(responseData => {
if (responseData.success) {
- let divToRemove = document.querySelector(`[data-memberid="${memberId}"]`);
- if (divToRemove) {
- divToRemove.parentNode.removeChild(divToRemove);
- }
+ const divToRemove = document.querySelector(`[data-memberid="${memberId}"]`);
+ if (divToRemove) divToRemove.remove();
showSuccessMessage(responseData.message);
} else {
- showErrorMessage(responseData.errorMessage || translate('failed_remove_member'));
+ showErrorMessage(responseData.message || translate("failed_remove_member"));
}
})
.catch(error => {
- showErrorMessage(translate('failed_remove_member'));
+ console.error(error);
+ showErrorMessage(translate("failed_remove_member"));
});
}
+
function editMember(memberId) {
- var saveButton = document.querySelector(`div[data-memberid="${memberId}"] button[name="save"]`);
- var memberNameElement = document.querySelector(`div[data-memberid="${memberId}"] input[name="member"]`);
- var memberEmailElement = document.querySelector(`div[data-memberid="${memberId}"] input[name="email"]`);
+ const saveButton = document.querySelector(`div[data-memberid="${memberId}"] button[name="save"]`);
+ const memberNameElement = document.querySelector(`div[data-memberid="${memberId}"] input[name="member"]`);
+ const memberEmailElement = document.querySelector(`div[data-memberid="${memberId}"] input[name="email"]`);
+
+ if (!memberNameElement) return;
+
saveButton.classList.add("disabled");
saveButton.disabled = true;
- if (memberNameElement) {
- var memberName = encodeURIComponent(memberNameElement.value);
- var memberEmail = memberEmailElement ? encodeURIComponent(memberEmailElement.value) : '';
- var url = `endpoints/household/household.php?action=edit&memberId=${memberId}&name=${memberName}&email=${memberEmail}`;
-
- fetch(url)
- .then(response => {
- saveButton.classList.remove("disabled");
- if (!response.ok) {
- showErrorMessage(translate('failed_save_member'));
- }
- return response.json();
- })
- .then(responseData => {
- if (responseData.success) {
- showSuccessMessage(responseData.message);
- } else {
- showErrorMessage(responseData.errorMessage || translate('failed_save_member'));
- }
- })
- .catch(error => {
- showErrorMessage(translate('failed_save_member'));
- });
- }
+
+ const memberName = memberNameElement.value;
+ const memberEmail = memberEmailElement ? memberEmailElement.value : "";
+
+ fetch("endpoints/household/household.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({
+ action: "edit",
+ memberId: memberId,
+ name: memberName,
+ email: memberEmail,
+ }),
+ })
+ .then(response => {
+ if (!response.ok) {
+ showErrorMessage(translate("failed_save_member"));
+ throw new Error(translate("network_response_error"));
+ }
+ return response.json();
+ })
+ .then(responseData => {
+ if (responseData.success) {
+ showSuccessMessage(responseData.message);
+ } else {
+ showErrorMessage(responseData.message || translate("failed_save_member"));
+ }
+ })
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(translate("failed_save_member"));
+ })
+ .finally(() => {
+ saveButton.classList.remove("disabled");
+ saveButton.disabled = false;
+ });
}
+
function addCategoryButton(categoryId) {
- document.getElementById("addCategory").disabled = true;
- const url = 'endpoints/categories/category.php?action=add';
- fetch(url)
+ const addButton = document.getElementById("addCategory");
+ addButton.disabled = true;
+
+ fetch('endpoints/categories/category.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({action: 'add'}),
+ })
.then(response => {
if (!response.ok) {
showErrorMessage(translate('failed_add_category'));
@@ -186,38 +229,37 @@ function addCategoryButton(categoryId) {
})
.then(responseData => {
if (responseData.success) {
- const newCategoryId = responseData.categoryId;;
- let container = document.getElementById("categories");
- let row = document.createElement("div");
+ const newCategoryId = responseData.categoryId;
+ const container = document.getElementById("categories");
+
+ const row = document.createElement("div");
row.className = "form-group-inline";
row.dataset.categoryid = newCategoryId;
- let dragIcon = document.createElement("div");
+ const dragIcon = document.createElement("div");
dragIcon.className = "drag-icon";
- let input = document.createElement("input");
+ const input = document.createElement("input");
input.type = "text";
input.placeholder = translate('category');
input.name = "category";
input.value = translate('category');
- let editLink = document.createElement("button");
- editLink.className = "image-button medium"
+ const editLink = document.createElement("button");
+ editLink.className = "image-button medium";
editLink.name = "save";
editLink.onclick = function () {
editCategory(newCategoryId);
};
-
editLink.innerHTML = editSvgContent;
editLink.title = translate('save_member');
- let deleteLink = document.createElement("button");
- deleteLink.className = "image-button medium"
+ const deleteLink = document.createElement("button");
+ deleteLink.className = "image-button medium";
deleteLink.name = "delete";
deleteLink.onclick = function () {
removeCategory(newCategoryId);
};
-
deleteLink.innerHTML = deleteSvgContent;
deleteLink.title = translate('delete_member');
@@ -225,23 +267,33 @@ function addCategoryButton(categoryId) {
row.appendChild(input);
row.appendChild(editLink);
row.appendChild(deleteLink);
-
container.appendChild(row);
} else {
- showErrorMessage(responseData.errorMessage);
+ showErrorMessage(responseData.message);
}
- document.getElementById("addCategory").disabled = false;
})
.catch(error => {
+ console.error(error);
showErrorMessage(translate('failed_add_category'));
- document.getElementById("addCategory").disabled = false;
+ })
+ .finally(() => {
+ addButton.disabled = false;
});
-
}
+
function removeCategory(categoryId) {
- let url = `endpoints/categories/category.php?action=delete&categoryId=${categoryId}`;
- fetch(url)
+ fetch('endpoints/categories/category.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({
+ action: 'delete',
+ categoryId: categoryId,
+ }),
+ })
.then(response => {
if (!response.ok) {
throw new Error(translate('network_response_error'));
@@ -250,106 +302,130 @@ function removeCategory(categoryId) {
})
.then(responseData => {
if (responseData.success) {
- let divToRemove = document.querySelector(`[data-categoryid="${categoryId}"]`);
- if (divToRemove) {
- divToRemove.parentNode.removeChild(divToRemove);
- }
+ const divToRemove = document.querySelector(`[data-categoryid="${categoryId}"]`);
+ if (divToRemove) divToRemove.remove();
showSuccessMessage(responseData.message);
} else {
- showErrorMessage(responseData.errorMessage || translate('failed_remove_category'));
+ showErrorMessage(responseData.message || translate('failed_remove_category'));
}
})
.catch(error => {
+ console.error(error);
showErrorMessage(translate('failed_remove_category'));
});
}
+
function editCategory(categoryId) {
- var saveButton = document.querySelector(`div[data-categoryid="${categoryId}"] button[name="save"]`);
- var inputElement = document.querySelector(`div[data-categoryid="${categoryId}"] input[name="category"]`);
+ const saveButton = document.querySelector(`div[data-categoryid="${categoryId}"] button[name="save"]`);
+ const inputElement = document.querySelector(`div[data-categoryid="${categoryId}"] input[name="category"]`);
+
+ if (!inputElement) return;
saveButton.classList.add("disabled");
saveButton.disabled = true;
- if (inputElement) {
- var categoryName = encodeURIComponent(inputElement.value);
- var url = `endpoints/categories/category.php?action=edit&categoryId=${categoryId}&name=${categoryName}`;
-
- fetch(url)
- .then(response => {
- saveButton.classList.remove("disabled");
- if (!response.ok) {
- showErrorMessage(translate('failed_save_category'));
- }
- return response.json();
- })
- .then(responseData => {
- if (responseData.success) {
- showSuccessMessage(responseData.message);
- } else {
- showErrorMessage(responseData.errorMessage || translate('failed_save_category'));
- }
- })
- .catch(error => {
+
+ const categoryName = inputElement.value;
+
+ fetch('endpoints/categories/category.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({
+ action: 'edit',
+ categoryId: categoryId,
+ name: categoryName,
+ }),
+ })
+ .then(response => {
+ saveButton.classList.remove("disabled");
+ saveButton.disabled = false;
+
+ if (!response.ok) {
showErrorMessage(translate('failed_save_category'));
- });
- }
+ throw new Error(translate('network_response_error'));
+ }
+ return response.json();
+ })
+ .then(responseData => {
+ if (responseData.success) {
+ showSuccessMessage(responseData.message);
+ } else {
+ showErrorMessage(responseData.message || translate('failed_save_category'));
+ }
+ })
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(translate('failed_save_category'));
+ saveButton.classList.remove("disabled");
+ saveButton.disabled = false;
+ });
}
+
function addCurrencyButton(currencyId) {
- document.getElementById("addCurrency").disabled = true;
- const url = 'endpoints/currency/add.php';
- fetch(url)
+ const addButton = document.getElementById("addCurrency");
+ addButton.disabled = true;
+
+ fetch('endpoints/currency/currency.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({action: 'add'}),
+ })
.then(response => {
if (!response.ok) {
throw new Error(translate('network_response_error'));
- showErrorMessage(response.text());
}
- return response.text();
+ return response.json();
})
- .then(responseText => {
- if (responseText !== "Error") {
- const newCurrencyId = responseText;
- let container = document.getElementById("currencies");
- let div = document.createElement("div");
+ .then(responseData => {
+ if (responseData.success) {
+ const newCurrencyId = responseData.currencyId;
+ const container = document.getElementById("currencies");
+
+ const div = document.createElement("div");
div.className = "form-group-inline";
div.dataset.currencyid = newCurrencyId;
- let inputSymbol = document.createElement("input");
+ const inputSymbol = document.createElement("input");
inputSymbol.type = "text";
inputSymbol.placeholder = "$";
inputSymbol.name = "symbol";
inputSymbol.value = "$";
inputSymbol.classList.add("short");
- let inputName = document.createElement("input");
+ const inputName = document.createElement("input");
inputName.type = "text";
inputName.placeholder = translate('currency');
inputName.name = "currency";
inputName.value = translate('currency');
- let inputCode = document.createElement("input");
+ const inputCode = document.createElement("input");
inputCode.type = "text";
inputCode.placeholder = translate('currency_code');
inputCode.name = "code";
inputCode.value = "CODE";
- let editLink = document.createElement("button");
- editLink.className = "image-button medium"
+ const editLink = document.createElement("button");
+ editLink.className = "image-button medium";
editLink.name = "save";
editLink.onclick = function () {
editCurrency(newCurrencyId);
};
-
editLink.innerHTML = editSvgContent;
editLink.title = translate('save_member');
- let deleteLink = document.createElement("button");
- deleteLink.className = "image-button medium"
+ const deleteLink = document.createElement("button");
+ deleteLink.className = "image-button medium";
deleteLink.name = "delete";
deleteLink.onclick = function () {
removeCurrency(newCurrencyId);
};
-
deleteLink.innerHTML = deleteSvgContent;
deleteLink.title = translate('delete_member');
@@ -361,20 +437,30 @@ function addCurrencyButton(currencyId) {
container.appendChild(div);
} else {
- // TODO: Show error
+ showErrorMessage(responseData.message || translate('failed_add_currency'));
}
- document.getElementById("addCurrency").disabled = false;
})
.catch(error => {
- // TODO: Show error
- document.getElementById("addCurrency").disabled = false;
+ console.error(error);
+ showErrorMessage(translate('failed_add_currency'));
+ })
+ .finally(() => {
+ addButton.disabled = false;
});
-
}
function removeCurrency(currencyId) {
- let url = `endpoints/currency/remove.php?currencyId=${currencyId}`;
- fetch(url)
+ fetch('endpoints/currency/currency.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({
+ action: 'delete',
+ currencyId: currencyId,
+ }),
+ })
.then(response => {
if (!response.ok) {
throw new Error(translate('network_response_error'));
@@ -384,85 +470,110 @@ function removeCurrency(currencyId) {
.then(data => {
if (data.success) {
showSuccessMessage(data.message);
- let divToRemove = document.querySelector(`[data-currencyid="${currencyId}"]`);
- if (divToRemove) {
- divToRemove.parentNode.removeChild(divToRemove);
- }
+ const divToRemove = document.querySelector(`[data-currencyid="${currencyId}"]`);
+ if (divToRemove) divToRemove.remove();
} else {
showErrorMessage(data.message || translate('failed_remove_currency'));
}
})
.catch(error => {
+ console.error(error);
showErrorMessage(error.message || translate('failed_remove_currency'));
});
}
function editCurrency(currencyId) {
- var saveButton = document.querySelector(`div[data-currencyid="${currencyId}"] button[name="save"]`);
- var inputSymbolElement = document.querySelector(`div[data-currencyid="${currencyId}"] input[name="symbol"]`);
- var inputNameElement = document.querySelector(`div[data-currencyid="${currencyId}"] input[name="currency"]`);
- var inputCodeElement = document.querySelector(`div[data-currencyid="${currencyId}"] input[name="code"]`);
+ const saveButton = document.querySelector(`div[data-currencyid="${currencyId}"] button[name="save"]`);
+ const inputSymbolElement = document.querySelector(`div[data-currencyid="${currencyId}"] input[name="symbol"]`);
+ const inputNameElement = document.querySelector(`div[data-currencyid="${currencyId}"] input[name="currency"]`);
+ const inputCodeElement = document.querySelector(`div[data-currencyid="${currencyId}"] input[name="code"]`);
+
+ if (!inputNameElement) return;
+
saveButton.classList.add("disabled");
saveButton.disabled = true;
- if (inputNameElement) {
- var currencyName = encodeURIComponent(inputNameElement.value);
- var currencySymbol = encodeURIComponent(inputSymbolElement.value);
- var currencyCode = encodeURIComponent(inputCodeElement.value);
- var url = `endpoints/currency/edit.php?currencyId=${currencyId}&name=${currencyName}&symbol=${currencySymbol}&code=${currencyCode}`;
-
- fetch(url)
- .then(response => {
- if (!response.ok) {
- throw new Error(translate('network_response_error'));
- }
- return response.json();
- })
- .then(data => {
- if (data.success) {
- saveButton.classList.remove("disabled");
- saveButton.disabled = false;
- showSuccessMessage(decodeURI(data.message));
- } else {
- saveButton.classList.remove("disabled");
- saveButton.disabled = false;
- showErrorMessage(data.message || translate('failed_save_currency'));
- }
- })
- .catch(error => {
- saveButton.classList.remove("disabled");
- saveButton.disabled = false;
- showErrorMessage(error.message || translate('failed_save_currency'));
- });
- }
+
+ const currencyName = inputNameElement.value;
+ const currencySymbol = inputSymbolElement.value;
+ const currencyCode = inputCodeElement.value;
+
+ fetch('endpoints/currency/currency.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({
+ action: 'edit',
+ currencyId: currencyId,
+ name: currencyName,
+ symbol: currencySymbol,
+ code: currencyCode,
+ }),
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(translate('network_response_error'));
+ }
+ return response.json();
+ })
+ .then(data => {
+ saveButton.classList.remove("disabled");
+ saveButton.disabled = false;
+
+ if (data.success) {
+ showSuccessMessage(data.message);
+ } else {
+ showErrorMessage(data.message || translate('failed_save_currency'));
+ }
+ })
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(error.message || translate('failed_save_currency'));
+ saveButton.classList.remove("disabled");
+ saveButton.disabled = false;
+ });
}
function togglePayment(paymentId) {
const element = document.querySelector(`div[data-paymentid="${paymentId}"]`);
- if (element.dataset.inUse === 'yes') {
- return showErrorMessage(translate('cant_disable_payment_in_use'));
+ if (element.dataset.inUse === "yes") {
+ return showErrorMessage(translate("cant_disable_payment_in_use"));
}
- const newEnabledState = element.dataset.enabled === '1' ? '0' : '1';
- const paymentMethodName = element.querySelector('.payment-name').innerText;
-
- const url = `endpoints/payments/payment.php?action=toggle&paymentId=${paymentId}&enabled=${newEnabledState}`;
+ const newEnabledState = element.dataset.enabled === "1" ? "0" : "1";
+ const paymentMethodName = element.querySelector(".payment-name").innerText;
- fetch(url).then(response => {
- if (!response.ok) {
- throw new Error(translate('network_response_error'));
- }
- return response.json();
- }).then(data => {
- if (data.success) {
- element.dataset.enabled = newEnabledState;
- showSuccessMessage(`${paymentMethodName} ${data.message}`);
- } else {
- showErrorMessage(data.message || translate('failed_save_payment_method'));
- }
- }).catch(error => {
- showErrorMessage(error.message || translate('failed_save_payment_method'));
- });
+ fetch("endpoints/payments/toggle.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: new URLSearchParams({
+ paymentId: paymentId,
+ enabled: newEnabledState,
+ }),
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(translate("network_response_error"));
+ }
+ return response.json();
+ })
+ .then(data => {
+ if (data.success) {
+ element.dataset.enabled = newEnabledState;
+ showSuccessMessage(`${paymentMethodName} ${data.message}`);
+ } else {
+ showErrorMessage(data.message || translate("failed_save_payment_method"));
+ }
+ })
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(error.message || translate("failed_save_payment_method"));
+ });
}
document.body.addEventListener('click', function (e) {
@@ -496,28 +607,39 @@ document.body.addEventListener('blur', function (e) {
function renamePayment(paymentId, newName) {
const name = newName.trim();
+ if (!name) return;
+
const formData = new FormData();
- formData.append('paymentId', paymentId);
- formData.append('name', name);
- fetch('endpoints/payments/rename.php', {
- method: 'POST',
- body: formData
- }).then(response => {
- if (!response.ok) {
- throw new Error(translate('network_response_error'));
- }
- return response.json();
- }).then(data => {
- if (data.success) {
- showSuccessMessage(`${newName} ${data.message}`);
- } else {
- showErrorMessage(data.message);
- }
- }).catch(error => {
- showErrorMessage(translate('unknown_error'));
- });
+ formData.append("paymentId", paymentId);
+ formData.append("name", name);
+
+ fetch("endpoints/payments/rename.php", {
+ method: "POST",
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: formData,
+ })
+ .then(response => {
+ if (!response.ok) {
+ throw new Error(translate("network_response_error"));
+ }
+ return response.json();
+ })
+ .then(data => {
+ if (data.success) {
+ showSuccessMessage(`${newName} ${data.message}`);
+ } else {
+ showErrorMessage(data.message || translate("failed_save_payment_method"));
+ }
+ })
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ });
}
+
document.body.addEventListener('keypress', function (e) {
let targetElement = e.target;
if (targetElement.classList && targetElement.classList.contains('payment-name')) {
@@ -642,10 +764,14 @@ function addPaymentMethod() {
submitButton.disabled = true;
const formData = new FormData(paymentMethodForm);
+ formData.append("action", "add");
fetch(addPaymentMethodEndpoint, {
method: "POST",
- body: formData
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: formData,
})
.then(response => response.json())
.then(data => {
@@ -655,22 +781,25 @@ function addPaymentMethod() {
resetFormIcon();
reloadPaymentMethods();
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message || translate("failed_add_payment_method"));
}
- submitButton.disabled = false;
})
.catch(error => {
- showErrorMessage(translate('unknown_error'));
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ })
+ .finally(() => {
submitButton.disabled = false;
});
-
}
+
function deletePaymentMethod(paymentId) {
fetch(`endpoints/payments/delete.php?id=${paymentId}`, {
- method: 'DELETE',
+ method: 'POST',
headers: {
'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
},
body: JSON.stringify({ id: paymentId }),
})
@@ -683,7 +812,7 @@ function deletePaymentMethod(paymentId) {
paymentToRemove.remove();
}
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message);
}
})
.catch((error) => {
@@ -692,31 +821,37 @@ function deletePaymentMethod(paymentId) {
}
function savePaymentMethodsSorting() {
- const paymentMethods = document.getElementById('payments-list');
- const paymentMethodIds = Array.from(paymentMethods.children).map(paymentMethod => paymentMethod.dataset.paymentid);
+ const paymentMethods = document.getElementById("payments-list");
+ const paymentMethodIds = Array.from(paymentMethods.children).map(
+ paymentMethod => paymentMethod.dataset.paymentid
+ );
const formData = new FormData();
- paymentMethodIds.forEach(paymentMethodId => {
- formData.append('paymentMethodIds[]', paymentMethodId);
- });
+ paymentMethodIds.forEach(id => formData.append("paymentMethodIds[]", id));
+ formData.append("action", "sort");
- fetch('endpoints/payments/sort.php', {
- method: 'POST',
- body: formData
+ fetch("endpoints/payments/sort.php", {
+ method: "POST",
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: formData,
})
.then(response => response.json())
.then(data => {
if (data.success) {
showSuccessMessage(data.message);
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message || translate("failed_sort_payment_methods"));
}
})
.catch(error => {
- showErrorMessage(translate('unknown_error'));
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
});
}
+
var el = document.getElementById('payments-list');
var sortable = Sortable.create(el, {
handle: '.drag-icon',
@@ -745,42 +880,59 @@ document.addEventListener('DOMContentLoaded', function () {
});
function addFixerKeyButton() {
- document.getElementById("addFixerKey").disabled = true;
+ const addButton = document.getElementById("addFixerKey");
+ addButton.disabled = true;
+
const apiKeyInput = document.querySelector("#fixerKey");
- apiKey = apiKeyInput.value.trim();
+ const apiKey = apiKeyInput.value.trim();
const provider = document.querySelector("#fixerProvider").value;
const convertCurrencyCheckbox = document.querySelector("#convertcurrency");
+
fetch("endpoints/currency/fixer_api_key.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
+ 'X-CSRF-Token': window.csrfToken,
},
- body: `api_key=${encodeURIComponent(apiKey)}&provider=${encodeURIComponent(provider)}`,
+ body: new URLSearchParams({
+ api_key: apiKey,
+ provider: provider,
+ }),
})
.then(response => response.json())
.then(data => {
if (data.success) {
showSuccessMessage(data.message);
- document.getElementById("addFixerKey").disabled = false;
+ addButton.disabled = false;
convertCurrencyCheckbox.disabled = false;
- // update currency exchange rates
- fetch("endpoints/currency/update_exchange.php?force=true");
+
+ fetch("endpoints/currency/update_exchange.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ 'X-CSRF-Token': window.csrfToken,
+ },
+ body: new URLSearchParams({force: "true"}),
+ }).catch(console.error);
} else {
showErrorMessage(data.message);
- document.getElementById("addFixerKey").disabled = false;
+ addButton.disabled = false;
}
})
.catch(error => {
- showErrorMessage(error);
- document.getElementById("addFixerKey").disabled = false;
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ addButton.disabled = false;
});
}
+
function storeSettingsOnDB(endpoint, value) {
fetch('endpoints/settings/' + endpoint + '.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify({ "value": value })
})
@@ -789,7 +941,7 @@ function storeSettingsOnDB(endpoint, value) {
if (data.success) {
showSuccessMessage(data.message);
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message);
}
});
}
@@ -851,31 +1003,33 @@ function setShowSubscriptionProgress() {
}
function saveCategorySorting() {
- const categories = document.getElementById('categories');
- const categoryIds = Array.from(categories.children).map(category => category.dataset.categoryid);
+ const categories = document.getElementById("categories");
+ const categoryIds = Array.from(categories.children).map(c => c.dataset.categoryid);
const formData = new FormData();
- categoryIds.forEach(categoryId => {
- formData.append('categoryIds[]', categoryId);
- });
+ categoryIds.forEach(categoryId => formData.append("categoryIds[]", categoryId));
+ formData.append("action", "sort");
- fetch('endpoints/categories/sort.php', {
- method: 'POST',
- body: formData
+ fetch("endpoints/categories/category.php", {
+ method: "POST",
+ headers: {"X-CSRF-Token": window.csrfToken},
+ body: formData,
})
.then(response => response.json())
.then(data => {
if (data.success) {
showSuccessMessage(data.message);
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message);
}
})
.catch(error => {
- showErrorMessage(translate('unknown_error'));
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
});
}
+
var el = document.getElementById('categories');
var sortable = Sortable.create(el, {
handle: '.drag-icon',
@@ -898,7 +1052,8 @@ function fetch_ai_models() {
fetch(endpoint, {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify({ type, api_key, ollama_host })
})
@@ -913,7 +1068,7 @@ function fetch_ai_models() {
modelSelect.appendChild(option);
});
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message);
}
})
.catch(error => {
@@ -945,7 +1100,8 @@ function saveAiSettingsButton() {
fetch('endpoints/ai/save_settings.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify({ ai_enabled: aiEnabled, ai_type: aiType, api_key: aiApiKey, ollama_host: aiOllamaHost, model: aiModel })
})
@@ -960,7 +1116,7 @@ function saveAiSettingsButton() {
runAiActionButton.classList.add("hidden");
}
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message);
}
})
.catch(error => {
@@ -979,7 +1135,8 @@ function runAiRecommendations() {
fetch(endpoint, {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
}
})
.then(response => response.json())
@@ -987,7 +1144,7 @@ function runAiRecommendations() {
if (data.success) {
showSuccessMessage(data.message);
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message);
}
})
.catch(error => {
diff --git a/scripts/subscriptions.js b/scripts/subscriptions.js
index f3e0d16..c674c83 100644
--- a/scripts/subscriptions.js
+++ b/scripts/subscriptions.js
@@ -203,79 +203,102 @@ function handleFileSelect(event) {
function deleteSubscription(event, id) {
event.stopPropagation();
event.preventDefault();
- if (confirm(translate('confirm_delete_subscription'))) {
- fetch(`endpoints/subscription/delete.php?id=${id}`, {
- method: 'DELETE',
- })
- .then(response => {
- if (response.ok) {
- showSuccessMessage(translate('subscription_deleted'));
- fetchSubscriptions(null, null, "delete");
- closeAddSubscription();
- } else {
- showErrorMessage(translate('error_deleting_subscription'));
- }
- })
- .catch(error => {
- console.error('Error:', error);
- });
+
+ if (!confirm(translate('confirm_delete_subscription'))) {
+ return;
}
+
+ fetch("endpoints/subscription/delete.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ id: id }),
+ })
+ .then((response) => response.json())
+ .then((data) => {
+ if (data.success) {
+ showSuccessMessage(translate('subscription_deleted'));
+ fetchSubscriptions(null, null, "delete");
+ closeAddSubscription();
+ } else {
+ showErrorMessage(data.message || translate('error_deleting_subscription'));
+ }
+ })
+ .catch((error) => {
+ console.error("Error:", error);
+ showErrorMessage(translate('error_deleting_subscription'));
+ });
}
+
function cloneSubscription(event, id) {
event.stopPropagation();
event.preventDefault();
- const url = `endpoints/subscription/clone.php?id=${id}`;
-
- fetch(url)
- .then(response => {
+ fetch("endpoints/subscription/clone.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ id: id }),
+ })
+ .then((response) => {
if (!response.ok) {
- throw new Error(translate('network_response_error'));
+ throw new Error(translate("network_response_error"));
}
return response.json();
})
- .then(data => {
+ .then((data) => {
if (data.success) {
- const id = data.id;
- fetchSubscriptions(id, event, "clone");
+ const newId = data.id;
+ fetchSubscriptions(newId, event, "clone");
showSuccessMessage(decodeURI(data.message));
} else {
- showErrorMessage(data.message || translate('error'));
+ showErrorMessage(data.message || translate("error"));
}
})
- .catch(error => {
- showErrorMessage(error.message || translate('error'));
+ .catch((error) => {
+ showErrorMessage(error.message || translate("error"));
});
}
+
function renewSubscription(event, id) {
event.stopPropagation();
event.preventDefault();
- const url = `endpoints/subscription/renew.php?id=${id}`;
-
- fetch(url)
- .then(response => {
+ fetch("endpoints/subscription/renew.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ id: id }),
+ })
+ .then((response) => {
if (!response.ok) {
- throw new Error(translate('network_response_error'));
+ throw new Error(translate("network_response_error"));
}
return response.json();
})
- .then(data => {
+ .then((data) => {
if (data.success) {
- const id = data.id;
- fetchSubscriptions(id, event, "renew");
+ const newId = data.id;
+ fetchSubscriptions(newId, event, "renew");
showSuccessMessage(decodeURI(data.message));
} else {
- showErrorMessage(data.message || translate('error'));
+ showErrorMessage(data.message || translate("error"));
}
})
- .catch(error => {
- showErrorMessage(error.message || translate('error'));
+ .catch((error) => {
+ showErrorMessage(error.message || translate("error"));
});
}
+
function setSearchButtonStatus() {
const nameInput = document.querySelector("#name");
@@ -454,6 +477,9 @@ function dataURLtoFile(dataurl, filename) {
function submitFormData(formData, submitButton, endpoint) {
fetch(endpoint, {
method: "POST",
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
body: formData,
})
.then((response) => response.json())
@@ -462,11 +488,15 @@ function submitFormData(formData, submitButton, endpoint) {
showSuccessMessage(data.message);
fetchSubscriptions(null, null, "add");
closeAddSubscription();
-
+ } else {
+ showErrorMessage(data.message || translate("unknown_error"));
}
})
.catch((error) => {
- showErrorMessage(error);
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ })
+ .finally(() => {
submitButton.disabled = false;
});
}
diff --git a/scripts/theme.js b/scripts/theme.js
index 6ff1c6b..a102f03 100644
--- a/scripts/theme.js
+++ b/scripts/theme.js
@@ -13,7 +13,8 @@ function switchTheme() {
fetch('endpoints/settings/theme.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify({ theme: themeChoice === 'dark' })
})
@@ -22,7 +23,7 @@ function switchTheme() {
if (data.success) {
showSuccessMessage(data.message);
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message);
}
button.disabled = false;
}).catch(error => {
@@ -46,7 +47,8 @@ function setDarkTheme(theme) {
fetch('endpoints/settings/theme.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify({ theme: theme })
})
@@ -83,7 +85,7 @@ function setDarkTheme(theme) {
showSuccessMessage(data.message);
} else {
- showErrorMessage(data.errorMessage);
+ showErrorMessage(data.message);
darkThemeButton.disabled = false;
lightThemeButton.disabled = false;
automaticThemeButton.disabled = false;
@@ -134,7 +136,8 @@ function setTheme(themeColor) {
fetch('endpoints/settings/colortheme.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify({ color: themeColor })
})
@@ -156,34 +159,46 @@ function resetCustomColors() {
const button = document.getElementById("reset-colors");
button.disabled = true;
- fetch('endpoints/settings/resettheme.php', {
- method: 'DELETE',
+ fetch("endpoints/settings/resettheme.php", {
+ method: "POST",
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: new URLSearchParams({
+ action: "reset",
+ }),
})
.then(response => response.json())
.then(data => {
if (data.success) {
showSuccessMessage(data.message);
- const custom_theme_colors = document.getElementById('custom_theme_colors');
- if (custom_theme_colors) {
- custom_theme_colors.remove();
+
+ const customThemeColors = document.getElementById("custom_theme_colors");
+ if (customThemeColors) {
+ customThemeColors.remove();
}
- document.documentElement.style.removeProperty('--main-color');
- document.documentElement.style.removeProperty('--accent-color');
- document.documentElement.style.removeProperty('--hover-color');
+
+ document.documentElement.style.removeProperty("--main-color");
+ document.documentElement.style.removeProperty("--accent-color");
+ document.documentElement.style.removeProperty("--hover-color");
+
document.getElementById("mainColor").value = "#FFFFFF";
document.getElementById("accentColor").value = "#FFFFFF";
document.getElementById("hoverColor").value = "#FFFFFF";
} else {
- showErrorMessage(data.message);
+ showErrorMessage(data.message || translate("failed_reset_colors"));
}
- button.disabled = false;
})
.catch(error => {
- showErrorMessage(translate('unknown_error'));
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ })
+ .finally(() => {
button.disabled = false;
});
}
+
function saveCustomColors() {
const button = document.getElementById("save-colors");
button.disabled = true;
@@ -195,7 +210,8 @@ function saveCustomColors() {
fetch('endpoints/settings/customtheme.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify({ mainColor: mainColor, accentColor: accentColor, hoverColor: hoverColor })
})
@@ -227,7 +243,8 @@ function saveCustomCss() {
fetch('endpoints/settings/customcss.php', {
method: 'POST',
headers: {
- 'Content-Type': 'application/json'
+ 'Content-Type': 'application/json',
+ 'X-CSRF-Token': window.csrfToken,
},
body: JSON.stringify({ customCss: customCss })
})