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

This commit is contained in:
Miguel Ribeiro
2025-10-18 23:58:50 +02:00
committed by GitHub
parent 8c46d2ea68
commit 3247ce2c87
86 changed files with 3987 additions and 4512 deletions

View File

@@ -352,8 +352,4 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET
];
echo json_encode($response);
exit;
}
?>
}

View File

@@ -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";
// 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);
$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);
$stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
$result = $stmt->execute();
$currency = $result->fetchArray(SQLITE3_ASSOC);
// 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();
die(json_encode([
"success" => true,
"message" => translate('success', $i18n)
]));
}
} else {
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";
// 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);
$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);
$stmt->bindValue(':user_id', $newUserId, SQLITE3_INTEGER);
$result = $stmt->execute();
$currency = $result->fetchArray(SQLITE3_ASSOC);
// 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();
die(json_encode([
"success" => true,
"message" => translate('success', $i18n)
]));
}

View File

@@ -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);

View File

@@ -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);
// Check that user is an admin
if ($userId !== 1) {
$userId = $data['userId'];
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 {
die(json_encode([
"success" => false,
"message" => translate('error', $i18n)
]));
}
// 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)
]));
}

View File

@@ -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) {
$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" => false,
"message" => translate('session_expired', $i18n)
"success" => true,
"message" => translate('success', $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);
$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)
]));
}
} else {
die(json_encode([
"success" => false,

View File

@@ -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)

View File

@@ -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)
]));
}
$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)
]));
}
$openRegistrations = $data['open_registrations'];
$maxUsers = $data['max_users'];
$requireEmailVerification = $data['require_email_validation'];
$serverUrl = $data['server_url'];
$disableLogin = $data['disable_login'];
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'];
if ($userCount > 1) {
echo json_encode([
"success" => false,
"message" => translate('error', $i18n)
]);
die();
}
}
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 {
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'];
if ($userCount > 1) {
echo json_encode([
"success" => false,
"message" => translate('error', $i18n)
]);
die();
}
}
?>
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)
]);
}

View File

@@ -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)
]));
}
}
?>
}

View File

@@ -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)
]));
}
}
?>
}

View File

@@ -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;
}
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();
// 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 ($db->changes() > 0) {
$response = [
"success" => true,
"message" => translate('success', $i18n)
];
} else {
$response = [
"success" => false,
"message" => translate('error', $i18n)
];
}
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);
}
}
echo json_encode($response);

View File

@@ -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-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;
}
}
// 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;
}
}
// 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_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" => translate('invalid_request_method', $i18n)
"message" => ($aiType === 'ollama')
? translate('invalid_host', $i18n)
: translate('invalid_api_key', $i18n)
];
echo json_encode($response);
}
} else {
$response = [
"success" => false,
"message" => translate('session_expired', $i18n)
];
echo json_encode($response);
}
}
// Close cURL session
curl_close($ch);
// Return the response as JSON
echo json_encode($response);

View File

@@ -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;
}
// 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;
}
// 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 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 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 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 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 name from includes/i18n/languages.php
require_once '../../includes/i18n/languages.php';
$userLanguageName = $languages[$userLanguage]['name'] ?? 'English';
// Get name from includes/i18n/languages.php
require_once '../../includes/i18n/languages.php';
$userLanguageName = $languages[$userLanguage]['name'] ?? 'English';
// 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 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();
$subscriptions = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$subscriptions[] = $row;
}
$subscriptions = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$subscriptions[] = $row;
}
if (!empty($subscriptions)) {
$subscriptionsForAI = [];
if (!empty($subscriptions)) {
$subscriptionsForAI = [];
foreach ($subscriptions as $row) {
if ($row['inactive'])
continue;
foreach ($subscriptions as $row) {
if ($row['inactive'])
continue;
$price = round($row['price'], 2);
$currencyCode = $currencies[$row['currency_id']]['code'] ?? '';
$priceFormatted = $currencyCode ? "$price $currencyCode" : "$price";
$price = round($row['price'], 2);
$currencyCode = $currencies[$row['currency_id']]['code'] ?? '';
$priceFormatted = $currencyCode ? "$price $currencyCode" : "$price";
$payerName = $members[$row['payer_user_id']]['name'] ?? 'Unknown';
$payerName = $members[$row['payer_user_id']]['name'] ?? 'Unknown';
$subscriptionsForAI[] = [
'name' => $row['name'],
'price' => $priceFormatted,
'frequency' => describeFrequency($row['cycle'], $row['frequency']),
'category' => $categories[$row['category_id']]['name'] ?? 'Uncategorized',
'payer' => $payerName
];
}
// 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 users 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 === '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 === '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);
// Check for errors
if (curl_errno($ch)) {
$response = [
"success" => false,
"message" => curl_error($ch)
];
echo json_encode($response);
exit;
}
// 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);
}
// Close the cURL session
curl_close($ch);
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();
// 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;

View File

@@ -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);
}
}
echo json_encode($response);

View File

@@ -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');
$action = $_POST['action'] ?? '';
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();
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);
}
}
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();
$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();
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)
];
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";
$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)
];
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)
];
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)
"message" => translate('failed_edit_category', $i18n)
];
echo json_encode($response);
}
} else {
echo translate('error', $i18n);
$response = [
"success" => false,
"message" => translate('fill_all_fields', $i18n)
];
echo json_encode($response);
}
} else {
echo translate('error', $i18n);
}
?>
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(':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,
"message" => translate('failed_remove_category', $i18n)
];
echo json_encode($response);
}
}
} else {
$response = [
"success" => false,
"message" => translate('failed_remove_category', $i18n)
];
echo json_encode($response);
}
}
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);
}

View File

@@ -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();
}
?>

View File

@@ -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);
}
?>

View File

@@ -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);
}
} else {
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" => false,
"message" => translate('fields_missing', $i18n)
"success" => true,
"message" => $name . " " . translate('currency_saved', $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'];
$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)
"message" => translate('failed_to_store_currency', $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);
}
?>
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'];
$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_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);
}
}

View File

@@ -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);
}
?>

View File

@@ -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);
$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);
}
$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);
$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);
}
$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)]);
}
$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)]);
}
}
?>
} else {
$response = [
"success" => false,
"message" => translate('invalid_api_key', $i18n)
];
echo json_encode($response);
}

View File

@@ -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);
}
?>

View File

@@ -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;
}
?>
}

View File

@@ -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
]));
}
?>
}

View File

@@ -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 (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 (!is_dir($destinationDir)) {
mkdir($destinationDir, 0755, true);
}
copy($filePath, $destination);
}
}
}
emptyRestoreFolder();
echo json_encode([
"success" => true,
"message" => translate("success", $i18n)
]);
} else {
emptyRestoreFolder();
die(json_encode([
"success" => false,
"message" => "wallos.db does not exist in the backup file"
]));
}
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 {
echo json_encode([
die(json_encode([
"success" => false,
"message" => "Failed to upload file"
]);
"message" => "Failed to extract the uploaded file"
]));
}
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 (!is_dir($destinationDir)) {
mkdir($destinationDir, 0755, true);
}
copy($filePath, $destination);
}
}
}
emptyRestoreFolder();
echo json_encode([
"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"
]);
}
?>
}

View File

@@ -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)
];
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";
$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)
];
echo json_encode($response);
} else {
$response = [
"success" => false,
"errorMessage" => translate('failed_edit_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)
"message" => translate('failed_edit_household', $i18n)
];
echo json_encode($response);
}
} else {
echo translate('error', $i18n);
$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(':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,
"message" => translate('failed_remove_household', $i18n)
];
echo json_encode($response);
}
}
} else {
$response = [
"success" => false,
"message" => translate('failed_remove_household', $i18n)
];
echo json_encode($response);
}
} else {
echo translate('error', $i18n);
}
?>

View File

@@ -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);
}
}
}
}
?>
}

View File

@@ -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);
}
}
}
}
?>
}

View File

@@ -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([
$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)
]));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
"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);
}
}
}
}
?>
}

View File

@@ -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);
}
}
}
}
?>
}

View File

@@ -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([
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
if (!isset($data["days"]) || $data['days'] == "") {
$response = [
"success" => false,
"message" => translate('session_expired', $i18n)
]));
}
"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 ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
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";
$stmt = $db->prepare($query);
$stmt->bindParam(":userId", $userId, SQLITE3_INTEGER);
$result = $stmt->execute();
$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";
}
if ($result === false) {
$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 {
$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();
}

View File

@@ -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([
$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('session_expired', $i18n)
]));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
"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);
}
?>
}

View File

@@ -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);
}
?>
}

View File

@@ -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);
}
}
}
}
?>
}

View File

@@ -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);
}
}
}
}
?>
}

View File

@@ -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([
$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)
]));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
"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);
}
}
}
}
?>
}

View File

@@ -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)
]));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
if (
!isset($data["url"]) || $data["url"] == ""
) {
$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);
$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)
]));
}
$postfields = [
'content' => $message,
'embeds' => [
[
'title' => $title,
'description' => $message,
'color' => hexdec("FF0000")
]
]
];
if (!empty($bot_username)) {
$postfields['username'] = $bot_username;
}
if (!empty($bot_avatar_url)) {
$postfields['avatar_url'] = $bot_avatar_url;
}
$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);
// Execute the request
$response = curl_exec($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)
]));
}
}
"message" => translate('fill_mandatory_fields', $i18n)
];
echo json_encode($response);
} else {
die(json_encode([
"success" => false,
"message" => translate("invalid_request_method", $i18n)
]));
}
// 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)
]));
}
$postfields = [
'content' => $message,
'embeds' => [
[
'title' => $title,
'description' => $message,
'color' => hexdec("FF0000")
]
]
];
if (!empty($bot_username)) {
$postfields['username'] = $bot_username;
}
if (!empty($bot_avatar_url)) {
$postfields['avatar_url'] = $bot_avatar_url;
}
$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);
// Execute the request
$response = curl_exec($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)
]));
}
}

View File

@@ -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)
]));
}
"message" => translate('fill_all_fields', $i18n)
];
die(json_encode($response));
} else {
$encryption = "none";
if (isset($data["encryption"])) {
$encryption = $data["encryption"];
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
$smtpAuth = (isset($data["smtpusername"]) && $data["smtpusername"] != "") || (isset($data["smtppassword"]) && $data["smtppassword"] != "");
if (
!isset($data["smtpaddress"]) || $data["smtpaddress"] == "" ||
!isset($data["smtpport"]) || $data["smtpport"] == ""
) {
$response = [
"success" => false,
"message" => translate('fill_all_fields', $i18n)
];
die(json_encode($response));
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'] : "wallos@wallosapp.com";
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = $smtpAddress;
$mail->SMTPAuth = $smtpAuth;
if ($smtpAuth) {
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
}
if ($encryption != "none") {
$mail->SMTPSecure = $encryption;
} else {
$encryption = "none";
if (isset($data["encryption"])) {
$encryption = $data["encryption"];
}
$mail->SMTPSecure = false;
$mail->SMTPAutoTLS = false;
}
$smtpAuth = (isset($data["smtpusername"]) && $data["smtpusername"] != "") || (isset($data["smtppassword"]) && $data["smtppassword"] != "");
$mail->Port = $smtpPort;
require '../../libs/PHPMailer/PHPMailer.php';
require '../../libs/PHPMailer/SMTP.php';
require '../../libs/PHPMailer/Exception.php';
$getUser = "SELECT * FROM user WHERE id = $userId";
$user = $db->querySingle($getUser, true);
$email = $user['email'];
$name = $user['username'];
$smtpAddress = $data["smtpaddress"];
$smtpPort = $data["smtpport"];
$smtpUsername = $data["smtpusername"];
$smtpPassword = $data["smtppassword"];
$fromEmail = $data["fromemail"] ? $data['fromemail'] : "wallos@wallosapp.com";
$mail->setFrom($fromEmail, 'Wallos App');
$mail->addAddress($email, $name);
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Subject = translate('wallos_notification', $i18n);
$mail->Body = translate('test_notification', $i18n);
$mail->Host = $smtpAddress;
$mail->SMTPAuth = $smtpAuth;
if ($smtpAuth) {
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
}
if ($encryption != "none") {
$mail->SMTPSecure = $encryption;
try {
if ($mail->send()) {
$response = [
"success" => true,
"message" => translate('notification_sent_successfuly', $i18n)
];
} 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) {
$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));
}

View File

@@ -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)
]));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$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)
];
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)
]));
}
$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);
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);
// 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
]));
}
}
"message" => translate('fill_mandatory_fields', $i18n)
];
die(json_encode($response));
} else {
die(json_encode([
"success" => false,
"message" => translate("invalid_request_method", $i18n)
// 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)
]));
}
$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);
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);
// 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
]));
}
}

View File

@@ -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)
]));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$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('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)
]));
}
$postfields = [
'text' => $message,
];
if (!empty($bot_username)) {
$postfields['username'] = $bot_username;
}
if (!empty($bot_icon_emoji)) {
$postfields['icon_emoji'] = $bot_icon_emoji;
}
$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);
// Execute the request
$response = curl_exec($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)
]));
}
}
"message" => translate('fill_mandatory_fields', $i18n)
];
echo json_encode($response);
} else {
die(json_encode([
"success" => false,
"message" => translate("invalid_request_method", $i18n)
]));
}
// 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)
]));
}
$postfields = [
'text' => $message,
];
if (!empty($bot_username)) {
$postfields['username'] = $bot_username;
}
if (!empty($bot_icon_emoji)) {
$postfields['icon_emoji'] = $bot_icon_emoji;
}
$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);
// Execute the request
$response = curl_exec($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)
]));
}
}

View File

@@ -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 = [
"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);
$ch = curl_init();
// 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);
if ($ignore_ssl) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
// Execute the request
$response = curl_exec($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)
]));
}
die(json_encode([
"success" => true,
"message" => translate('notification_sent_successfuly', $i18n)
"success" => false,
"message" => translate("error", $i18n)
]));
}
}
// Set the message parameters
$message = translate('test_notification', $i18n);
?>
$ch = curl_init();
// 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);
if ($ignore_ssl) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
// Execute the request
$response = curl_exec($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)
]));
}
die(json_encode([
"success" => true,
"message" => translate('notification_sent_successfuly', $i18n)
]));
}

View File

@@ -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([
$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)
]));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$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);
$user_key = $data["user_key"];
$token = $data["token"];
$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);
// Execute the request
$response = curl_exec($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)
]));
}
}
"message" => translate('fill_mandatory_fields', $i18n)
];
echo json_encode($response);
} else {
die(json_encode([
"success" => false,
"message" => translate("invalid_request_method", $i18n)
]));
}
// Set the message parameters
$message = translate('test_notification', $i18n);
?>
$user_key = $data["user_key"];
$token = $data["token"];
$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);
// Execute the request
$response = curl_exec($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)
]));
}
}

View File

@@ -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([
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
if (!isset($data["token"]) || $data["token"] == "") {
$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);
$token = $data["token"];
if (!isset($data["token"]) || $data["token"] == "") {
$response = [
$ch = curl_init();
// 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
]);
// 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);
// Check if the message was sent successfully
if ($response === false) {
die(json_encode([
"success" => false,
"message" => translate('fill_mandatory_fields', $i18n)
];
echo json_encode($response);
"message" => translate('notification_failed', $i18n) . ": " . $curlError
]));
} else {
// Set the message parameters
$title = translate('wallos_notification', $i18n);
$message = translate('test_notification', $i18n);
$token = $data["token"];
$ch = curl_init();
// 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
]);
// 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);
// Check if the message was sent successfully
if ($response === false) {
$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)
]));
}
?>
}

View File

@@ -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([
$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('session_expired', $i18n)
]));
}
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);
$botToken = $data["bottoken"];
$chatId = $data["chatid"];
$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);
// Execute the request
$response = curl_exec($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)
]));
}
}
"message" => translate('fill_mandatory_fields', $i18n)
];
echo json_encode($response);
} else {
die(json_encode([
"success" => false,
"message" => translate("invalid_request_method", $i18n)
// Set the message parameters
$title = translate('wallos_notification', $i18n);
$message = translate('test_notification', $i18n);
$botToken = $data["bottoken"];
$chatId = $data["chatid"];
$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);
// Execute the request
$response = curl_exec($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)
]));
}
}

View File

@@ -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([
$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('session_expired', $i18n)
]));
}
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($parsedUrl['scheme']) ||
!in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
!filter_var($url, FILTER_VALIDATE_URL)
) {
die(json_encode([
"success" => false,
"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);
}
$customheaders = json_decode($data["customheaders"], true);
$ignore_ssl = $data["ignore_ssl"];
$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);
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);
// 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
]));
}
}
"message" => translate('fill_mandatory_fields', $i18n)
];
die(json_encode($response));
} else {
die(json_encode([
"success" => false,
"message" => translate("invalid_request_method", $i18n)
]));
}
$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)
]));
}
// 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"];
$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);
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);
// 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
]));
}
}

View File

@@ -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']))) {
if ($name === "" || ($iconUrl === "" && empty($_FILES['paymenticon']['name']))) {
$response = [
"success" => false,
"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)
"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();
?>

View File

@@ -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();
?>

View File

@@ -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([

View File

@@ -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);
?>

View File

@@ -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);

View File

@@ -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);
$color = $data['color'];
// 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)
]));
}
$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);
$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)
]));
}
}
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -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);
$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);
$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)
]));
}
}
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -1,37 +1,29 @@
<?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);
$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);
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"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
$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);
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}
}

View File

@@ -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)
]));
}
?>
$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)
]));
}

View File

@@ -1,134 +1,117 @@
<?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") {
$userIdToDelete = $data['userId'];
$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 {
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)
]));
}

View File

@@ -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);
$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);
$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)
]));
}
}
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -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);
$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);
$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)
]));
}
}
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -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);
$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);
$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)
]));
}
}
«
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -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);
$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);
$monthly_price = $data['value'];
// 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)
]));
}
}
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -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);
$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);
$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)
]));
}
}
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -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)
]));
}
}
?>
}

View File

@@ -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);
$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);
$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)
]));
}
}
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -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);
$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);
$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)
]));
}
}
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -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);
$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);
$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)
]));
}
}
?>
if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}

View File

@@ -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'];
$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 ($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";
}
$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();
}
if ($logo != "") {
$sql .= ", logo = :logo";
}
$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();
}
$db->close();
?>

View File

@@ -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();
?>

View File

@@ -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();
?>
$db->close();

View File

@@ -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) {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
$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();
if ($result === false) {
die(json_encode([
"success" => false,
"message" => translate('session_expired', $i18n)
'success' => false,
'message' => "Subscription not found"
]));
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
$subscription = $result->fetchArray(SQLITE3_ASSOC); // Fetch the subscription details as an associative array
$id = $data['id'];
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);
$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();
// 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']}";
if ($result === false) {
die(json_encode([
'success' => false,
'message' => "Subscription not found"
]));
}
$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';
$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);
// 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';
$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"
]);
}
}
?>
echo json_encode([
'success' => true,
'ics' => $icsContent,
'name' => $subscription['name']
]);
} else {
echo json_encode([
'success' => false,
'message' => "Subscription not found"
]);
}

View File

@@ -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;
}
$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";
}
$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);
}
// 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)
]));
}
} else {
$db->close();
$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('session_expired', $i18n)
"message" => translate("error", $i18n)
]));
}
?>
$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";
}
$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);
}
// 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)
]));
}

View File

@@ -2,39 +2,31 @@
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.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);
$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);
}

View File

@@ -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'])) {

View File

@@ -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);
$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';
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'];
$totp_code = $data['totpCode'];
$statement = $db->prepare('SELECT totp_secret FROM totp WHERE user_id = :id');
$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);
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));
if ($totp->verify($totp_code, null, 15)) {
// 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
]));
}

View File

@@ -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);
}
$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 ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
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)
]));
}
}

View File

@@ -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([
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);
$apiKey = bin2hex(random_bytes(32));
$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();
if ($result) {
$response = [
"success" => true,
"message" => translate('user_details_saved', $i18n),
"apiKey" => $apiKey
];
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);
$apiKey = bin2hex(random_bytes(32));
$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();
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);
}
}
?>
"message" => translate('error_updating_user_data', $i18n)
];
echo json_encode($response);
}

View File

@@ -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();
}
?>

View File

@@ -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') ?>

View File

@@ -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;
}

View File

@@ -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)
]));
}

View File

@@ -1,3 +1,3 @@
<?php
$version = "v4.4.1";
$version = "v4.5.0";
?>

18
libs/csrf.php Normal file
View File

@@ -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);
}

View File

@@ -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)
})

View File

@@ -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));

View File

@@ -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"));
});
});
});
});

View File

@@ -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),
})

View File

@@ -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 = '';
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'
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;
const regenerateButton = document.getElementById("regenerateApiKey");
regenerateButton.disabled = true;
fetch('endpoints/user/regenerateapikey.php', {
method: 'POST',
})
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 }),
})

View File

File diff suppressed because it is too large Load Diff

View File

@@ -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;
});
}

View File

@@ -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 })
})