From c2e85d6e109d9d07cc2fdbcb09b51564d1f73341 Mon Sep 17 00:00:00 2001 From: Miguel Ribeiro Date: Wed, 26 Jun 2024 18:11:37 +0200 Subject: [PATCH] feat: support automatic dark mode refactor: run linter and cleanup php files fix: not every payment cycle was shown on the calendar feat: also show previous payments on the calendar for the current month --- about.php | 28 +- admin.php | 179 +-- auth.php | 0 calendar.php | 85 +- endpoints/admin/deleteuser.php | 4 +- endpoints/categories/category.php | 4 +- endpoints/categories/sort.php | 2 +- endpoints/cronjobs/createdatabase.php | 4 +- endpoints/cronjobs/sendnotifications.php | 925 +++++++------- .../cronjobs/sendresetpasswordemails.php | 116 +- endpoints/cronjobs/sendverificationemails.php | 122 +- endpoints/cronjobs/updateexchange.php | 164 +-- endpoints/cronjobs/updatenextpayment.php | 102 +- endpoints/currency/add.php | 40 +- endpoints/currency/currency.php | 4 +- endpoints/currency/edit.php | 2 +- endpoints/currency/fixer_api_key.php | 98 +- endpoints/currency/remove.php | 2 +- endpoints/currency/update_exchange.php | 8 +- endpoints/db/backup.php | 12 +- endpoints/db/import.php | 8 +- endpoints/db/migrate.php | 11 +- endpoints/db/restore.php | 8 +- endpoints/household/household.php | 4 +- endpoints/logos/search.php | 109 +- .../savediscordnotifications.php | 108 +- .../notifications/saveemailnotifications.php | 130 +- .../notifications/savegotifynotifications.php | 104 +- .../savenotificationsettings.php | 106 +- .../notifications/saventfynotifications.php | 124 +- .../savepushovernotifications.php | 116 +- .../savetelegramnotifications.php | 104 +- .../savewebhooknotifications.php | 108 +- .../testdiscordnotifications.php | 6 +- .../notifications/testemailnotifications.php | 4 +- .../notifications/testgotifynotifications.php | 2 +- .../notifications/testntfynotifications.php | 4 +- .../testwebhooknotifications.php | 2 +- endpoints/payments/add.php | 385 +++--- endpoints/payments/delete.php | 2 +- endpoints/payments/get.php | 43 +- endpoints/payments/payment.php | 2 +- endpoints/payments/search.php | 107 +- endpoints/payments/sort.php | 2 +- endpoints/settings/colortheme.php | 54 +- endpoints/settings/convert_currency.php | 2 +- endpoints/settings/customtheme.php | 66 +- endpoints/settings/hide_disabled.php | 2 +- endpoints/settings/monthly_price.php | 2 +- endpoints/settings/remove_background.php | 2 +- endpoints/settings/resettheme.php | 42 +- endpoints/settings/theme.php | 2 +- endpoints/subscription/add.php | 416 ++++--- endpoints/subscription/get.php | 70 +- endpoints/subscription/getcalendar.php | 2 +- endpoints/subscriptions/get.php | 236 ++-- endpoints/user/delete_avatar.php | 48 +- endpoints/user/save_user.php | 540 ++++---- includes/checksession.php | 138 +- includes/checkuser.php | 8 +- includes/footer.php | 9 +- includes/getsettings.php | 16 +- includes/header.php | 12 +- includes/i18n/de.php | 4 +- includes/i18n/el.php | 4 +- includes/i18n/en.php | 4 +- includes/i18n/es.php | 4 +- includes/i18n/fr.php | 4 +- includes/i18n/getlang.php | 3 +- includes/i18n/it.php | 2 +- includes/i18n/jp.php | 4 +- includes/i18n/ko.php | 4 +- includes/i18n/languages.php | 50 +- includes/i18n/pl.php | 4 +- includes/i18n/pt.php | 4 +- includes/i18n/pt_br.php | 2 +- includes/i18n/ru.php | 4 +- includes/i18n/sl.php | 4 +- includes/i18n/sr.php | 4 +- includes/i18n/sr_lat.php | 4 +- includes/i18n/tr.php | 3 +- includes/i18n/zh_cn.php | 4 +- includes/i18n/zh_tw.php | 4 +- includes/inputvalidation.php | 3 +- includes/list_subscriptions.php | 8 - includes/version.php | 4 +- index.php | 678 +++++----- login.php | 126 +- logos.php | 79 +- logout.php | 36 +- passwordreset.php | 98 +- registration.php | 259 ++-- scripts/common.js | 141 ++- scripts/login.js | 18 + scripts/registration.js | 17 + scripts/settings.js | 59 + service-worker.js | 1 + settings.php | 1106 +++++++++-------- stats.php | 536 ++++---- styles/styles.css | 4 + verifyemail.php | 40 +- 101 files changed, 4443 insertions(+), 4057 deletions(-) delete mode 100644 auth.php create mode 100644 scripts/login.js diff --git a/about.php b/about.php index 7ba6c7445..b46e7a4d9 100644 --- a/about.php +++ b/about.php @@ -1,5 +1,5 @@
@@ -10,25 +10,27 @@

Wallos

-

: +

: GPLv3 - +

- : + : GitHub - +

- : + : https://henrique.pt @@ -37,25 +39,27 @@

- : + : https://www.streamlinehq.com/freebies/plump-flat-free - +

- : + : https://www.figma.com/file/5IMW8JfoXfB5GRlPNdTyeg/Credit-Cards-and-Payment-Methods-Icons-(Community) - +

- Chart.js: + Chart.js: https://www.chartjs.org/ @@ -69,5 +73,5 @@

\ No newline at end of file diff --git a/admin.php b/admin.php index adf4b1289..598d55243 100644 --- a/admin.php +++ b/admin.php @@ -1,27 +1,27 @@ prepare('SELECT * FROM admin'); - $result = $stmt->execute(); - $settings = $result->fetchArray(SQLITE3_ASSOC); +// get admin settings from admin table +$stmt = $db->prepare('SELECT * FROM admin'); +$result = $stmt->execute(); +$settings = $result->fetchArray(SQLITE3_ASSOC); - // get user accounts - $stmt = $db->prepare('SELECT id, username, email FROM user ORDER BY id ASC'); - $result = $stmt->execute(); +// get user accounts +$stmt = $db->prepare('SELECT id, username, email FROM user ORDER BY id ASC'); +$result = $stmt->execute(); - $users = []; - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $users[] = $row; - } - $userCount = is_array($users) ? count($users) : 0; +$users = []; +while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $users[] = $row; +} +$userCount = is_array($users) ? count($users) : 0; - $loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0; +$loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0; ?>
@@ -43,28 +43,30 @@

-

+

+

By enabling user registrations, the setting to disable login will be unavailable.

- /> + + />
-
-

- - -

-
- +
+

+ + +

+
+
@@ -82,7 +84,8 @@

- /> + + />
@@ -96,64 +99,68 @@

- +
= 0) { - ?> + if ($userCount >= 0) { + ?> -
-
-

-
-
- +
+

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

- - -

-
-
+ ?> + +
+

+ + +

+
+ -
@@ -162,8 +169,10 @@
- - + +
/> @@ -172,13 +181,16 @@
- +
- +
- +

@@ -190,8 +202,10 @@

- - + +
@@ -203,11 +217,14 @@
- -
+ +
- - + +
@@ -215,12 +232,12 @@

-
+ \ No newline at end of file diff --git a/auth.php b/auth.php deleted file mode 100644 index e69de29bb..000000000 diff --git a/calendar.php b/calendar.php index 61bc0eb7c..bb7f71d84 100644 --- a/calendar.php +++ b/calendar.php @@ -1,22 +1,6 @@ $startOfMonth) { + $startDate = strtotime("-" . $incrementString, $startDate); + } + + for ($date = $startDate; $date <= $endDate; $date = strtotime($incrementString, $date)) { if (date('Y-m', $date) == $calendarYear . '-' . str_pad($calendarMonth, 2, '0', STR_PAD_LEFT)) { if (date('d', $date) == $day) { ?>
- +
$startOfMonth) { + $startDate = strtotime("-" . $incrementString, $startDate); + } + + for ($date = $startDate; $date <= $endDate; $date = strtotime($incrementString, $date)) { if (date('Y-m', $date) == $calendarYear . '-' . str_pad($calendarMonth, 2, '0', STR_PAD_LEFT)) { if (date('d', $date) == $day) { ?>
- +
prepare('DELETE FROM payment_methods WHERE user_id = :id'); $stmt->bindValue(':id', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); + $result = $stmt->execute(); // Delete email notifications $stmt = $db->prepare('DELETE FROM email_notifications WHERE user_id = :id'); @@ -114,7 +114,7 @@ $stmt = $db->prepare('DELETE FROM email_verification WHERE user_id = :id'); $stmt->bindValue(':id', $userId, SQLITE3_INTEGER); $result = $stmt->execute(); - + die(json_encode([ "success" => true, "message" => translate('success', $i18n) diff --git a/endpoints/categories/category.php b/endpoints/categories/category.php index cb70f0898..d33501f81 100644 --- a/endpoints/categories/category.php +++ b/endpoints/categories/category.php @@ -23,7 +23,7 @@ $stmtInsert->bindParam(':order', $order, SQLITE3_INTEGER); $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER); $resultInsert = $stmtInsert->execute(); - + if ($resultInsert) { $categoryId = $db->lastInsertRowID(); $response = [ @@ -120,4 +120,4 @@ echo translate('error', $i18n); } -?> +?> \ No newline at end of file diff --git a/endpoints/categories/sort.php b/endpoints/categories/sort.php index 1da427731..68d61f2b0 100644 --- a/endpoints/categories/sort.php +++ b/endpoints/categories/sort.php @@ -20,7 +20,7 @@ "success" => true, "message" => translate("sort_order_saved", $i18n) ]; - echo json_encode($response); + echo json_encode($response); } else { $response = [ "success" => false, diff --git a/endpoints/cronjobs/createdatabase.php b/endpoints/cronjobs/createdatabase.php index 27a05c6dd..7dbb753b5 100644 --- a/endpoints/cronjobs/createdatabase.php +++ b/endpoints/cronjobs/createdatabase.php @@ -1,4 +1,4 @@ - +?> \ No newline at end of file diff --git a/endpoints/cronjobs/sendnotifications.php b/endpoints/cronjobs/sendnotifications.php index 192e3cf0f..3471c8b8e 100644 --- a/endpoints/cronjobs/sendnotifications.php +++ b/endpoints/cronjobs/sendnotifications.php @@ -1,569 +1,580 @@ prepare($query); +$usersToNotify = $stmt->execute(); + +while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) { + $userId = $userToNotify['id']; + echo "For user: " . $userToNotify['username'] . "
"; + + $days = 1; + $emailNotificationsEnabled = false; + $gotifyNotificationsEnabled = false; + $telegramNotificationsEnabled = false; + $webhookNotificationsEnabled = false; + $pushoverNotificationsEnabled = false; + $discordNotificationsEnabled = false; + $ntfyNotificationsEnabled = false; + + // Get notification settings (how many days before the subscription ends should the notification be sent) + $query = "SELECT days FROM notification_settings WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); - require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php'; + if ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $days = $row['days']; + } - require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php'; - require __DIR__ . '/../../libs/PHPMailer/SMTP.php'; - require __DIR__ . '/../../libs/PHPMailer/Exception.php'; - // Get all user ids - $query = "SELECT id, username FROM user"; + // Check if email notifications are enabled and get the settings + $query = "SELECT * FROM email_notifications WHERE user_id = :userId"; $stmt = $db->prepare($query); - $usersToNotify = $stmt->execute(); - - while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) { - $userId = $userToNotify['id']; - echo "For user: " . $userToNotify['username'] . "
"; - - $days = 1; - $emailNotificationsEnabled = false; - $gotifyNotificationsEnabled = false; - $telegramNotificationsEnabled = false; - $webhookNotificationsEnabled = false; - $pushoverNotificationsEnabled = false; - $discordNotificationsEnabled = false; - $ntfyNotificationsEnabled = false; - - // Get notification settings (how many days before the subscription ends should the notification be sent) - $query = "SELECT days FROM notification_settings WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + + if ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $emailNotificationsEnabled = $row['enabled']; + $email['smtpAddress'] = $row["smtp_address"]; + $email['smtpPort'] = $row["smtp_port"]; + $email['encryption'] = $row["encryption"]; + $email['smtpUsername'] = $row["smtp_username"]; + $email['smtpPassword'] = $row["smtp_password"]; + $email['fromEmail'] = $row["from_email"] ? $row["from_email"] : "wallos@wallosapp.com"; + } - if ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $days = $row['days']; - } + // Check if Discord notifications are enabled and get the settings + $query = "SELECT * FROM discord_notifications WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + + if ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $discordNotificationsEnabled = $row['enabled']; + $discord['webhook_url'] = $row["webhook_url"]; + $discord['bot_username'] = $row["bot_username"]; + $discord['bot_avatar_url'] = $row["bot_avatar_url"]; + } + // Check if Gotify notifications are enabled and get the settings + $query = "SELECT * FROM gotify_notifications WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); - // Check if email notifications are enabled and get the settings - $query = "SELECT * FROM email_notifications WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); + $gotify = []; - if ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $emailNotificationsEnabled = $row['enabled']; - $email['smtpAddress'] = $row["smtp_address"]; - $email['smtpPort'] = $row["smtp_port"]; - $email['encryption'] = $row["encryption"]; - $email['smtpUsername'] = $row["smtp_username"]; - $email['smtpPassword'] = $row["smtp_password"]; - $email['fromEmail'] = $row["from_email"] ? $row["from_email"] : "wallos@wallosapp.com"; - } + if ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $gotifyNotificationsEnabled = $row['enabled']; + $gotify['serverUrl'] = $row["url"]; + $gotify['appToken'] = $row["token"]; + } - // Check if Discord notifications are enabled and get the settings - $query = "SELECT * FROM discord_notifications WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); + // Check if Telegram notifications are enabled and get the settings + $query = "SELECT * FROM telegram_notifications WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); - if ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $discordNotificationsEnabled = $row['enabled']; - $discord['webhook_url'] = $row["webhook_url"]; - $discord['bot_username'] = $row["bot_username"]; - $discord['bot_avatar_url'] = $row["bot_avatar_url"]; - } + if ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $telegramNotificationsEnabled = $row['enabled']; + $telegram['botToken'] = $row["bot_token"]; + $telegram['chatId'] = $row["chat_id"]; + } - // Check if Gotify notifications are enabled and get the settings - $query = "SELECT * FROM gotify_notifications WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); + // Check if Pushover notifications are enabled and get the settings + $query = "SELECT * FROM pushover_notifications WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + + if ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $pushoverNotificationsEnabled = $row['enabled']; + $pushover['user_key'] = $row["user_key"]; + $pushover['token'] = $row["token"]; + } + + // Check if Nrfy notifications are enabled and get the settings + $query = "SELECT * FROM ntfy_notifications WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + + if ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $ntfyNotificationsEnabled = $row['enabled']; + $ntfy['host'] = $row["host"]; + $ntfy['topic'] = $row["topic"]; + $ntfy['headers'] = $row["headers"]; + } - if ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $gotifyNotificationsEnabled = $row['enabled']; - $gotify['serverUrl'] = $row["url"]; - $gotify['appToken'] = $row["token"]; + // Check if Webhook notifications are enabled and get the settings + $query = "SELECT * FROM webhook_notifications WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + + if ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $webhookNotificationsEnabled = $row['enabled']; + $webhook['url'] = $row["url"]; + $webhook['request_method'] = $row["request_method"]; + $webhook['headers'] = $row["headers"]; + $webhook['payload'] = $row["payload"]; + $webhook['iterator'] = $row["iterator"]; + if ($webhook['iterator'] === "") { + $webhook['iterator'] = "subscriptions"; } + } - // Check if Telegram notifications are enabled and get the settings - $query = "SELECT * FROM telegram_notifications WHERE user_id = :userId"; + $notificationsEnabled = $emailNotificationsEnabled || $gotifyNotificationsEnabled || $telegramNotificationsEnabled || + $webhookNotificationsEnabled || $pushoverNotificationsEnabled || $discordNotificationsEnabled || + $ntfyNotificationsEnabled; + + // If no notifications are enabled, no need to run + if (!$notificationsEnabled) { + echo "Notifications are disabled. No need to run.
"; + continue; + } else { + // Get all currencies + $currencies = array(); + $query = "SELECT * FROM currencies WHERE user_id = :userId"; $stmt = $db->prepare($query); $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); $result = $stmt->execute(); - if ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $telegramNotificationsEnabled = $row['enabled']; - $telegram['botToken'] = $row["bot_token"]; - $telegram['chatId'] = $row["chat_id"]; + while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $currencies[$row['id']] = $row; } - // Check if Pushover notifications are enabled and get the settings - $query = "SELECT * FROM pushover_notifications WHERE user_id = :userId"; + // Get all household members + $query = "SELECT * FROM household WHERE user_id = :userId"; $stmt = $db->prepare($query); $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); + $resultHousehold = $stmt->execute(); - if ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $pushoverNotificationsEnabled = $row['enabled']; - $pushover['user_key'] = $row["user_key"]; - $pushover['token'] = $row["token"]; + $household = []; + while ($rowHousehold = $resultHousehold->fetchArray(SQLITE3_ASSOC)) { + $household[$rowHousehold['id']] = $rowHousehold; } - // Check if Nrfy notifications are enabled and get the settings - $query = "SELECT * FROM ntfy_notifications WHERE user_id = :userId"; + // Get all categories + $query = "SELECT * FROM categories WHERE user_id = :userId"; $stmt = $db->prepare($query); $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); + $resultCategories = $stmt->execute(); - if ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $ntfyNotificationsEnabled = $row['enabled']; - $ntfy['host'] = $row["host"]; - $ntfy['topic'] = $row["topic"]; - $ntfy['headers'] = $row["headers"]; + $categories = []; + while ($rowCategory = $resultCategories->fetchArray(SQLITE3_ASSOC)) { + $categories[$rowCategory['id']] = $rowCategory; } - // Check if Webhook notifications are enabled and get the settings - $query = "SELECT * FROM webhook_notifications WHERE user_id = :userId"; + $query = "SELECT * FROM subscriptions WHERE user_id = :user_id AND notify = :notify AND inactive = :inactive ORDER BY payer_user_id ASC"; $stmt = $db->prepare($query); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - - if ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $webhookNotificationsEnabled = $row['enabled']; - $webhook['url'] = $row["url"]; - $webhook['request_method'] = $row["request_method"]; - $webhook['headers'] = $row["headers"]; - $webhook['payload'] = $row["payload"]; - $webhook['iterator'] = $row["iterator"]; - if ($webhook['iterator'] === "") { - $webhook['iterator'] = "subscriptions"; + $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER); + $stmt->bindValue(':notify', 1, SQLITE3_INTEGER); + $stmt->bindValue(':inactive', 0, SQLITE3_INTEGER); + $resultSubscriptions = $stmt->execute(); + + $notify = []; + $i = 0; + $currentDate = new DateTime('now'); + while ($rowSubscription = $resultSubscriptions->fetchArray(SQLITE3_ASSOC)) { + if ($rowSubscription['notify_days_before'] !== 0) { + $daysToCompare = $rowSubscription['notify_days_before']; + } else { + $daysToCompare = $days; + } + $nextPaymentDate = new DateTime($rowSubscription['next_payment']); + $difference = $currentDate->diff($nextPaymentDate)->days + 1; + if ($difference === $daysToCompare) { + $notify[$rowSubscription['payer_user_id']][$i]['name'] = $rowSubscription['name']; + $notify[$rowSubscription['payer_user_id']][$i]['price'] = $rowSubscription['price'] . $currencies[$rowSubscription['currency_id']]['symbol']; + $notify[$rowSubscription['payer_user_id']][$i]['currency'] = $currencies[$rowSubscription['currency_id']]['name']; + $notify[$rowSubscription['payer_user_id']][$i]['category'] = $categories[$rowSubscription['category_id']]['name']; + $notify[$rowSubscription['payer_user_id']][$i]['payer'] = $household[$rowSubscription['payer_user_id']]['name']; + $notify[$rowSubscription['payer_user_id']][$i]['date'] = $rowSubscription['next_payment']; + $notify[$rowSubscription['payer_user_id']][$i]['days'] = $daysToCompare; + $i++; } } - $notificationsEnabled = $emailNotificationsEnabled || $gotifyNotificationsEnabled || $telegramNotificationsEnabled || - $webhookNotificationsEnabled || $pushoverNotificationsEnabled || $discordNotificationsEnabled || - $ntfyNotificationsEnabled; + if (!empty($notify)) { - // If no notifications are enabled, no need to run - if (!$notificationsEnabled) { - echo "Notifications are disabled. No need to run.
"; - continue; - } else { - // Get all currencies - $currencies = array(); - $query = "SELECT * FROM currencies WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $currencies[$row['id']] = $row; - } + // Email notifications if enabled + if ($emailNotificationsEnabled) { - // Get all household members - $query = "SELECT * FROM household WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $resultHousehold = $stmt->execute(); + $stmt = $db->prepare('SELECT * FROM user WHERE id = :user_id'); + $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + $defaultUser = $result->fetchArray(SQLITE3_ASSOC); + $defaultEmail = $defaultUser['email']; + $defaultName = $defaultUser['username']; - $household = []; - while ($rowHousehold = $resultHousehold->fetchArray(SQLITE3_ASSOC)) { - $household[$rowHousehold['id']] = $rowHousehold; - } + foreach ($notify as $userId => $perUser) { + $message = "The following subscriptions are up for renewal:\n"; - // Get all categories - $query = "SELECT * FROM categories WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $resultCategories = $stmt->execute(); + foreach ($perUser as $subscription) { + $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; + $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; + } - $categories = []; - while ($rowCategory = $resultCategories->fetchArray(SQLITE3_ASSOC)) { - $categories[$rowCategory['id']] = $rowCategory; - } + $mail = new PHPMailer(true); + $mail->CharSet = "UTF-8"; + $mail->isSMTP(); - $query = "SELECT * FROM subscriptions WHERE user_id = :user_id AND notify = :notify AND inactive = :inactive ORDER BY payer_user_id ASC"; - $stmt = $db->prepare($query); - $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER); - $stmt->bindValue(':notify', 1, SQLITE3_INTEGER); - $stmt->bindValue(':inactive', 0, SQLITE3_INTEGER); - $resultSubscriptions = $stmt->execute(); - - $notify = []; $i = 0; - $currentDate = new DateTime('now'); - while ($rowSubscription = $resultSubscriptions->fetchArray(SQLITE3_ASSOC)) { - if ($rowSubscription['notify_days_before'] !== 0) { - $daysToCompare = $rowSubscription['notify_days_before']; - } else { - $daysToCompare = $days; - } - $nextPaymentDate = new DateTime($rowSubscription['next_payment']); - $difference = $currentDate->diff($nextPaymentDate)->days + 1; - if ($difference === $daysToCompare) { - $notify[$rowSubscription['payer_user_id']][$i]['name'] = $rowSubscription['name']; - $notify[$rowSubscription['payer_user_id']][$i]['price'] = $rowSubscription['price'] . $currencies[$rowSubscription['currency_id']]['symbol']; - $notify[$rowSubscription['payer_user_id']][$i]['currency'] = $currencies[$rowSubscription['currency_id']]['name']; - $notify[$rowSubscription['payer_user_id']][$i]['category'] = $categories[$rowSubscription['category_id']]['name']; - $notify[$rowSubscription['payer_user_id']][$i]['payer'] = $household[$rowSubscription['payer_user_id']]['name']; - $notify[$rowSubscription['payer_user_id']][$i]['date'] = $rowSubscription['next_payment']; - $notify[$rowSubscription['payer_user_id']][$i]['days'] = $daysToCompare; - $i++; - } - } + $mail->Host = $email['smtpAddress']; + $mail->SMTPAuth = true; + $mail->Username = $email['smtpUsername']; + $mail->Password = $email['smtpPassword']; + $mail->SMTPSecure = $email['encryption']; + $mail->Port = $email['smtpPort']; + + $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + $user = $result->fetchArray(SQLITE3_ASSOC); - if (!empty($notify)) { + $emailaddress = !empty($user['email']) ? $user['email'] : $defaultEmail; + $name = !empty($user['name']) ? $user['name'] : $defaultName; - // Email notifications if enabled - if ($emailNotificationsEnabled) { + $mail->setFrom($email['fromEmail'], 'Wallos App'); + $mail->addAddress($emailaddress, $name); - $stmt = $db->prepare('SELECT * FROM user WHERE id = :user_id'); - $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER); + $mail->Subject = 'Wallos Notification'; + $mail->Body = $message; + + if ($mail->send()) { + echo "Email Notifications sent
"; + } else { + echo "Error sending notifications: " . $mail->ErrorInfo . "
"; + } + } + } + + // Discord notifications if enabled + if ($discordNotificationsEnabled) { + foreach ($notify as $userId => $perUser) { + // Get name of user from household table + $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); $result = $stmt->execute(); - $defaultUser = $result->fetchArray(SQLITE3_ASSOC); - $defaultEmail = $defaultUser['email']; - $defaultName = $defaultUser['username']; + $user = $result->fetchArray(SQLITE3_ASSOC); + + $title = translate('wallos_notification', $i18n); - foreach ($notify as $userId => $perUser) { + if ($user['name']) { + $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; + } else { $message = "The following subscriptions are up for renewal:\n"; + } - foreach ($perUser as $subscription) { - $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; - $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; - } - - $mail = new PHPMailer(true); - $mail->CharSet="UTF-8"; - $mail->isSMTP(); - - $mail->Host = $email['smtpAddress']; - $mail->SMTPAuth = true; - $mail->Username = $email['smtpUsername']; - $mail->Password = $email['smtpPassword']; - $mail->SMTPSecure = $email['encryption']; - $mail->Port = $email['smtpPort']; - - $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $user = $result->fetchArray(SQLITE3_ASSOC); - - $emailaddress = !empty($user['email']) ? $user['email'] : $defaultEmail; - $name = !empty($user['name']) ? $user['name'] : $defaultName; - - $mail->setFrom($email['fromEmail'], 'Wallos App'); - $mail->addAddress($emailaddress, $name); - - $mail->Subject = 'Wallos Notification'; - $mail->Body = $message; - - if ($mail->send()) { - echo "Email Notifications sent
"; - } else { - echo "Error sending notifications: " . $mail->ErrorInfo . "
"; - } + foreach ($perUser as $subscription) { + $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; + $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; } - } - // Discord notifications if enabled - if ($discordNotificationsEnabled) { - foreach ($notify as $userId => $perUser) { - // Get name of user from household table - $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $user = $result->fetchArray(SQLITE3_ASSOC); - - $title = translate('wallos_notification', $i18n); - - if ($user['name']) { - $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; - } else { - $message = "The following subscriptions are up for renewal:\n"; - } + $postfields = [ + 'content' => $message + ]; - foreach ($perUser as $subscription) { - $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; - $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; - } + if (!empty($discord['bot_username'])) { + $postfields['username'] = $discord['bot_username']; + } - $postfields = [ - 'content' => $message - ]; - - if (!empty($discord['bot_username'])) { - $postfields['username'] = $discord['bot_username']; - } - - if (!empty($discord['bot_avatar_url'])) { - $postfields['avatar_url'] = $discord['bot_avatar_url']; - } + if (!empty($discord['bot_avatar_url'])) { + $postfields['avatar_url'] = $discord['bot_avatar_url']; + } - $ch = curl_init(); + $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $discord['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); + curl_setopt($ch, CURLOPT_URL, $discord['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); - $response = curl_exec($ch); - curl_close($ch); + $response = curl_exec($ch); + curl_close($ch); - if ($result === false) { - echo "Error sending notifications: " . curl_error($ch) . "
"; - } else { - echo "Discord Notifications sent
"; - } + if ($result === false) { + echo "Error sending notifications: " . curl_error($ch) . "
"; + } else { + echo "Discord Notifications sent
"; } } + } - // Gotify notifications if enabled - if ($gotifyNotificationsEnabled) { - foreach ($notify as $userId => $perUser) { - // Get name of user from household table - $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $user = $result->fetchArray(SQLITE3_ASSOC); - - if ($user['name']) { - $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; - } else { - $message = "The following subscriptions are up for renewal:\n"; - } + // Gotify notifications if enabled + if ($gotifyNotificationsEnabled) { + foreach ($notify as $userId => $perUser) { + // Get name of user from household table + $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + $user = $result->fetchArray(SQLITE3_ASSOC); - foreach ($perUser as $subscription) { - $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; - $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; - } + if ($user['name']) { + $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; + } else { + $message = "The following subscriptions are up for renewal:\n"; + } + + foreach ($perUser as $subscription) { + $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; + $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; + } - $data = array( - 'message' => $message, - 'priority' => 5 - ); + $data = array( + 'message' => $message, + 'priority' => 5 + ); - $data_string = json_encode($data); + $data_string = json_encode($data); - $ch = curl_init($gotify['serverUrl'] . '/message?token=' . $gotify['appToken']); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); - curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_HTTPHEADER, array( + $ch = curl_init($gotify['serverUrl'] . '/message?token=' . $gotify['appToken']); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt( + $ch, + CURLOPT_HTTPHEADER, + array( 'Content-Type: application/json', - 'Content-Length: ' . strlen($data_string)) - ); - - $result = curl_exec($ch); - if ($result === false) { - echo "Error sending notifications: " . curl_error($ch) . "
"; - } else { - echo "Gotify Notifications sent
"; - } + 'Content-Length: ' . strlen($data_string) + ) + ); + + $result = curl_exec($ch); + if ($result === false) { + echo "Error sending notifications: " . curl_error($ch) . "
"; + } else { + echo "Gotify Notifications sent
"; } } + } - // Telegram notifications if enabled - if ($telegramNotificationsEnabled) { - foreach ($notify as $userId => $perUser) { - // Get name of user from household table - $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $user = $result->fetchArray(SQLITE3_ASSOC); - - if ($user['name']) { - $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; - } else { - $message = "The following subscriptions are up for renewal:\n"; - } + // Telegram notifications if enabled + if ($telegramNotificationsEnabled) { + foreach ($notify as $userId => $perUser) { + // Get name of user from household table + $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + $user = $result->fetchArray(SQLITE3_ASSOC); - foreach ($perUser as $subscription) { - $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; - $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; - } + if ($user['name']) { + $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; + } else { + $message = "The following subscriptions are up for renewal:\n"; + } - $data = array( - 'chat_id' => $telegram['chatId'], - 'text' => $message - ); + foreach ($perUser as $subscription) { + $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; + $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; + } - $data_string = json_encode($data); + $data = array( + 'chat_id' => $telegram['chatId'], + 'text' => $message + ); - $ch = curl_init('https://api.telegram.org/bot' . $telegram['botToken'] . '/sendMessage'); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); - curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_HTTPHEADER, array( + $data_string = json_encode($data); + + $ch = curl_init('https://api.telegram.org/bot' . $telegram['botToken'] . '/sendMessage'); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); + curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt( + $ch, + CURLOPT_HTTPHEADER, + array( 'Content-Type: application/json', - 'Content-Length: ' . strlen($data_string)) - ); - - $result = curl_exec($ch); - if ($result === false) { - echo "Error sending notifications: " . curl_error($ch) . "
"; - } else { - echo "Telegram Notifications sent
"; - } + 'Content-Length: ' . strlen($data_string) + ) + ); + + $result = curl_exec($ch); + if ($result === false) { + echo "Error sending notifications: " . curl_error($ch) . "
"; + } else { + echo "Telegram Notifications sent
"; } } + } - // Pushover notifications if enabled - if ($pushoverNotificationsEnabled) { - foreach ($notify as $userId => $perUser) { - // Get name of user from household table - $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $user = $result->fetchArray(SQLITE3_ASSOC); - - if ($user['name']) { - $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; - } else { - $message = "The following subscriptions are up for renewal:\n"; - } + // Pushover notifications if enabled + if ($pushoverNotificationsEnabled) { + foreach ($notify as $userId => $perUser) { + // Get name of user from household table + $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + $user = $result->fetchArray(SQLITE3_ASSOC); - foreach ($perUser as $subscription) { - $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; - $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; - } + if ($user['name']) { + $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; + } else { + $message = "The following subscriptions are up for renewal:\n"; + } - $ch = curl_init(); - 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' => $pushover['token'], - 'user' => $pushover['user_key'], - 'message' => $message, - ])); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + foreach ($perUser as $subscription) { + $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; + $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; + } - $result = curl_exec($ch); + $ch = curl_init(); + 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' => $pushover['token'], + 'user' => $pushover['user_key'], + 'message' => $message, + ])); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_close($ch); + $result = curl_exec($ch); - if ($result === false) { - echo "Error sending notifications: " . curl_error($ch) . "
"; - } else { - echo "Pushover Notifications sent
"; - } + curl_close($ch); + + if ($result === false) { + echo "Error sending notifications: " . curl_error($ch) . "
"; + } else { + echo "Pushover Notifications sent
"; } } + } - // Ntfy notifications if enabled - if ($ntfyNotificationsEnabled) { - foreach ($notify as $userId => $perUser) { - // Get name of user from household table - $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $user = $result->fetchArray(SQLITE3_ASSOC); - - if ($user['name']) { - $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; - } else { - $message = "The following subscriptions are up for renewal:\n"; - } + // Ntfy notifications if enabled + if ($ntfyNotificationsEnabled) { + foreach ($notify as $userId => $perUser) { + // Get name of user from household table + $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + $user = $result->fetchArray(SQLITE3_ASSOC); - foreach ($perUser as $subscription) { - $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; - $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; - } + if ($user['name']) { + $message = $user['name'] . ", the following subscriptions are up for renewal:\n"; + } else { + $message = "The following subscriptions are up for renewal:\n"; + } - $headers = json_decode($ntfy["headers"], true); - $customheaders = array_map(function($key, $value) { - return "$key: $value"; - }, array_keys($headers), $headers); + foreach ($perUser as $subscription) { + $dayText = $subscription['days'] == 1 ? "Tomorrow" : "In " . $subscription['days'] . " days"; + $message .= $subscription['name'] . " for " . $subscription['price'] . " (" . $dayText . ")\n"; + } - $ch = curl_init(); + $headers = json_decode($ntfy["headers"], true); + $customheaders = array_map(function ($key, $value) { + return "$key: $value"; + }, array_keys($headers), $headers); - $ntfyHost = rtrim($ntfy["host"], '/'); - $ntfyTopic = $ntfy['topic']; + $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $ntfyHost . '/' . $ntfyTopic); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $message); - curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $ntfyHost = rtrim($ntfy["host"], '/'); + $ntfyTopic = $ntfy['topic']; - $response = curl_exec($ch); - curl_close($ch); + curl_setopt($ch, CURLOPT_URL, $ntfyHost . '/' . $ntfyTopic); + 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 ($response === false) { - echo "Error sending notifications: " . curl_error($ch) . "
"; - } else { - echo "Ntfy Notifications sent
"; - } + $response = curl_exec($ch); + curl_close($ch); + + if ($response === false) { + echo "Error sending notifications: " . curl_error($ch) . "
"; + } else { + echo "Ntfy Notifications sent
"; } } + } - // Webhook notifications if enabled - if ($webhookNotificationsEnabled) { - // Get webhook payload and turn it into a json object + // Webhook notifications if enabled + if ($webhookNotificationsEnabled) { + // Get webhook payload and turn it into a json object - $payload = str_replace("{{days_until}}", $days, $webhook['payload']); // The default value for all subscriptions - $payload_json = json_decode($payload, true); + $payload = str_replace("{{days_until}}", $days, $webhook['payload']); // The default value for all subscriptions + $payload_json = json_decode($payload, true); - $subscription_template = $payload_json["{{subscriptions}}"]; - $subscriptions = []; + $subscription_template = $payload_json["{{subscriptions}}"]; + $subscriptions = []; - foreach ($notify as $userId => $perUser) { - // Get name of user from household table - $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $user = $result->fetchArray(SQLITE3_ASSOC); + foreach ($notify as $userId => $perUser) { + // Get name of user from household table + $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId'); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + $user = $result->fetchArray(SQLITE3_ASSOC); - if ($user['name']) { - $payer = $user['name']; - } + if ($user['name']) { + $payer = $user['name']; + } - foreach ($perUser as $k => $subscription) { - $temp_subscription = $subscription_template[0]; - - foreach ($temp_subscription as $key => $value) { - if (is_string($value)) { - $temp_subscription[$key] = str_replace("{{subscription_name}}", $subscription['name'], $value); - $temp_subscription[$key] = str_replace("{{subscription_price}}", $subscription['price'], $temp_subscription[$key]); - $temp_subscription[$key] = str_replace("{{subscription_currency}}", $subscription['currency'], $temp_subscription[$key]); - $temp_subscription[$key] = str_replace("{{subscription_category}}", $subscription['category'], $temp_subscription[$key]); - $temp_subscription[$key] = str_replace("{{subscription_payer}}", $subscription['payer'], $temp_subscription[$key]); - $temp_subscription[$key] = str_replace("{{subscription_date}}", $subscription['date'], $temp_subscription[$key]); - $temp_subscription[$key] = str_replace("{{subscription_days_until_payment}}", $subscription['days'], $temp_subscription[$key]); // The de facto value for this subscription - } + foreach ($perUser as $k => $subscription) { + $temp_subscription = $subscription_template[0]; + + foreach ($temp_subscription as $key => $value) { + if (is_string($value)) { + $temp_subscription[$key] = str_replace("{{subscription_name}}", $subscription['name'], $value); + $temp_subscription[$key] = str_replace("{{subscription_price}}", $subscription['price'], $temp_subscription[$key]); + $temp_subscription[$key] = str_replace("{{subscription_currency}}", $subscription['currency'], $temp_subscription[$key]); + $temp_subscription[$key] = str_replace("{{subscription_category}}", $subscription['category'], $temp_subscription[$key]); + $temp_subscription[$key] = str_replace("{{subscription_payer}}", $subscription['payer'], $temp_subscription[$key]); + $temp_subscription[$key] = str_replace("{{subscription_date}}", $subscription['date'], $temp_subscription[$key]); + $temp_subscription[$key] = str_replace("{{subscription_days_until_payment}}", $subscription['days'], $temp_subscription[$key]); // The de facto value for this subscription } - $subscriptions[] = $temp_subscription; - } - } - - $payload_json["{{subscriptions}}"] = $subscriptions; - $payload_json[$webhook['iterator']] = $subscriptions; - unset($payload_json["{{subscriptions}}"]); + $subscriptions[] = $temp_subscription; - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $webhook['url']); - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook['request_method']); - curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload_json)); - if (!empty($webhook['headers'])) { - $customheaders = preg_split("/\r\n|\n|\r/", $webhook['headers']); - curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders); } - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + } - $response = curl_exec($ch); - curl_close($ch); + $payload_json["{{subscriptions}}"] = $subscriptions; + $payload_json[$webhook['iterator']] = $subscriptions; + unset($payload_json["{{subscriptions}}"]); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $webhook['url']); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook['request_method']); + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload_json)); + if (!empty($webhook['headers'])) { + $customheaders = preg_split("/\r\n|\n|\r/", $webhook['headers']); + curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders); + } + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - if ($response === false) { - echo "Error sending notifications: " . curl_error($ch) . "
"; - } else { - echo "Webhook Notifications sent
"; - } + $response = curl_exec($ch); + curl_close($ch); + if ($response === false) { + echo "Error sending notifications: " . curl_error($ch) . "
"; + } else { + echo "Webhook Notifications sent
"; } - - - } else { - echo "Nothing to notify.
"; + } + + } else { + echo "Nothing to notify.
"; } } -?> +} + +?> \ No newline at end of file diff --git a/endpoints/cronjobs/sendresetpasswordemails.php b/endpoints/cronjobs/sendresetpasswordemails.php index 50cebbff2..d31117a47 100644 --- a/endpoints/cronjobs/sendresetpasswordemails.php +++ b/endpoints/cronjobs/sendresetpasswordemails.php @@ -1,82 +1,82 @@ prepare($query); - $result = $stmt->execute(); - $admin = $result->fetchArray(SQLITE3_ASSOC); +$query = "SELECT * FROM admin"; +$stmt = $db->prepare($query); +$result = $stmt->execute(); +$admin = $result->fetchArray(SQLITE3_ASSOC); - $query = "SELECT * FROM password_resets WHERE email_sent = 0"; - $stmt = $db->prepare($query); - $result = $stmt->execute(); +$query = "SELECT * FROM password_resets WHERE email_sent = 0"; +$stmt = $db->prepare($query); +$result = $stmt->execute(); - $rows = []; - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $rows[] = $row; - } +$rows = []; +while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $rows[] = $row; +} - if ($rows) { - if ($admin['smtp_address'] && $admin['smtp_port'] && $admin['smtp_username'] && $admin['smtp_password'] && $admin['encryption']) { - // There are SMTP settings - $smtpAddress = $admin['smtp_address']; - $smtpPort = $admin['smtp_port']; - $smtpUsername = $admin['smtp_username']; - $smtpPassword = $admin['smtp_password']; - $fromEmail = empty($admin['from_email']) ? 'wallos@wallosapp.com' : $admin['from_email']; - $encryption = $admin['encryption']; - $server_url = $admin['server_url']; +if ($rows) { + if ($admin['smtp_address'] && $admin['smtp_port'] && $admin['smtp_username'] && $admin['smtp_password'] && $admin['encryption']) { + // There are SMTP settings + $smtpAddress = $admin['smtp_address']; + $smtpPort = $admin['smtp_port']; + $smtpUsername = $admin['smtp_username']; + $smtpPassword = $admin['smtp_password']; + $fromEmail = empty($admin['from_email']) ? 'wallos@wallosapp.com' : $admin['from_email']; + $encryption = $admin['encryption']; + $server_url = $admin['server_url']; - require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php'; - require __DIR__ . '/../../libs/PHPMailer/SMTP.php'; - require __DIR__ . '/../../libs/PHPMailer/Exception.php'; + require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php'; + require __DIR__ . '/../../libs/PHPMailer/SMTP.php'; + require __DIR__ . '/../../libs/PHPMailer/Exception.php'; - $mail = new PHPMailer(true); - $mail->isSMTP(); - $mail->Host = $smtpAddress; - $mail->SMTPAuth = true; - $mail->Username = $smtpUsername; - $mail->Password = $smtpPassword; - $mail->SMTPSecure = $encryption; - $mail->Port = $smtpPort; - $mail->setFrom($fromEmail); + $mail = new PHPMailer(true); + $mail->isSMTP(); + $mail->Host = $smtpAddress; + $mail->SMTPAuth = true; + $mail->Username = $smtpUsername; + $mail->Password = $smtpPassword; + $mail->SMTPSecure = $encryption; + $mail->Port = $smtpPort; + $mail->setFrom($fromEmail); - try { - foreach ($rows as $user) { - $mail->addAddress($user['email']); - $mail->isHTML(true); - $mail->Subject = 'Wallos - Reset Password'; - $mail->Body = 'Logo + try { + foreach ($rows as $user) { + $mail->addAddress($user['email']); + $mail->isHTML(true); + $mail->Subject = 'Wallos - Reset Password'; + $mail->Body = 'Logo
A password reset was requested for your account.
Please click the following link to reset your password: Reset Password'; - - $mail->send(); - $query = "UPDATE password_resets SET email_sent = 1 WHERE id = :id"; - $stmt = $db->prepare($query); - $stmt->bindParam(':id', $user['id'], SQLITE3_INTEGER); - $stmt->execute(); + $mail->send(); + + $query = "UPDATE password_resets SET email_sent = 1 WHERE id = :id"; + $stmt = $db->prepare($query); + $stmt->bindParam(':id', $user['id'], SQLITE3_INTEGER); + $stmt->execute(); - $mail->clearAddresses(); + $mail->clearAddresses(); - echo "Password reset email sent to " . $user['email'] . "
"; + echo "Password reset email sent to " . $user['email'] . "
"; - } - } catch (Exception $e) { - echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}
"; } - } else { - // There are no SMTP settings - exit(); + } catch (Exception $e) { + echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}
"; } } else { - // There are no password reset emails to be sent + // There are no SMTP settings exit(); } +} else { + // There are no password reset emails to be sent + exit(); +} ?> \ No newline at end of file diff --git a/endpoints/cronjobs/sendverificationemails.php b/endpoints/cronjobs/sendverificationemails.php index 6f05ac156..cdf7564be 100644 --- a/endpoints/cronjobs/sendverificationemails.php +++ b/endpoints/cronjobs/sendverificationemails.php @@ -1,85 +1,85 @@ prepare($query); - $result = $stmt->execute(); - $admin = $result->fetchArray(SQLITE3_ASSOC); +$query = "SELECT * FROM admin"; +$stmt = $db->prepare($query); +$result = $stmt->execute(); +$admin = $result->fetchArray(SQLITE3_ASSOC); - if ($admin['require_email_verification'] == 0) { - die("Email verification is not required."); - } +if ($admin['require_email_verification'] == 0) { + die("Email verification is not required."); +} - $query = "SELECT * FROM email_verification WHERE email_sent = 0"; - $stmt = $db->prepare($query); - $result = $stmt->execute(); +$query = "SELECT * FROM email_verification WHERE email_sent = 0"; +$stmt = $db->prepare($query); +$result = $stmt->execute(); - $rows = []; - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $rows[] = $row; - } +$rows = []; +while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $rows[] = $row; +} - if ($rows) { - if ($admin['smtp_address'] && $admin['smtp_port'] && $admin['smtp_username'] && $admin['smtp_password'] && $admin['encryption']) { - // There are SMTP settings - $smtpAddress = $admin['smtp_address']; - $smtpPort = $admin['smtp_port']; - $smtpUsername = $admin['smtp_username']; - $smtpPassword = $admin['smtp_password']; - $fromEmail = empty($admin['from_email']) ? 'wallos@wallosapp.com' : $admin['from_email']; - $encryption = $admin['encryption']; - $server_url = $admin['server_url']; +if ($rows) { + if ($admin['smtp_address'] && $admin['smtp_port'] && $admin['smtp_username'] && $admin['smtp_password'] && $admin['encryption']) { + // There are SMTP settings + $smtpAddress = $admin['smtp_address']; + $smtpPort = $admin['smtp_port']; + $smtpUsername = $admin['smtp_username']; + $smtpPassword = $admin['smtp_password']; + $fromEmail = empty($admin['from_email']) ? 'wallos@wallosapp.com' : $admin['from_email']; + $encryption = $admin['encryption']; + $server_url = $admin['server_url']; - require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php'; - require __DIR__ . '/../../libs/PHPMailer/SMTP.php'; - require __DIR__ . '/../../libs/PHPMailer/Exception.php'; + require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php'; + require __DIR__ . '/../../libs/PHPMailer/SMTP.php'; + require __DIR__ . '/../../libs/PHPMailer/Exception.php'; - $mail = new PHPMailer(true); - $mail->isSMTP(); - $mail->Host = $smtpAddress; - $mail->SMTPAuth = true; - $mail->Username = $smtpUsername; - $mail->Password = $smtpPassword; - $mail->SMTPSecure = $encryption; - $mail->Port = $smtpPort; - $mail->setFrom($fromEmail); + $mail = new PHPMailer(true); + $mail->isSMTP(); + $mail->Host = $smtpAddress; + $mail->SMTPAuth = true; + $mail->Username = $smtpUsername; + $mail->Password = $smtpPassword; + $mail->SMTPSecure = $encryption; + $mail->Port = $smtpPort; + $mail->setFrom($fromEmail); - try { - foreach ($rows as $user) { - $mail->addAddress($user['email']); - $mail->isHTML(true); - $mail->Subject = 'Wallos - Email Verification'; - $mail->Body = 'Logo + try { + foreach ($rows as $user) { + $mail->addAddress($user['email']); + $mail->isHTML(true); + $mail->Subject = 'Wallos - Email Verification'; + $mail->Body = 'Logo
Registration on Wallos was successful.
Please click the following link to verify your email: Verify Email'; - - $mail->send(); - $query = "UPDATE email_verification SET email_sent = 1 WHERE id = :id"; - $stmt = $db->prepare($query); - $stmt->bindParam(':id', $user['id'], SQLITE3_INTEGER); - $stmt->execute(); + $mail->send(); + + $query = "UPDATE email_verification SET email_sent = 1 WHERE id = :id"; + $stmt = $db->prepare($query); + $stmt->bindParam(':id', $user['id'], SQLITE3_INTEGER); + $stmt->execute(); - $mail->clearAddresses(); + $mail->clearAddresses(); - echo "Verification email sent to " . $user['email'] . "
"; - } - } catch (Exception $e) { - echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; + echo "Verification email sent to " . $user['email'] . "
"; } - } else { - // There are no SMTP settings - exit(); + } catch (Exception $e) { + echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } } else { - // There are no verification emails to be sent + // There are no SMTP settings exit(); } +} else { + // There are no verification emails to be sent + exit(); +} ?> \ No newline at end of file diff --git a/endpoints/cronjobs/updateexchange.php b/endpoints/cronjobs/updateexchange.php index 999e70459..40f61969a 100644 --- a/endpoints/cronjobs/updateexchange.php +++ b/endpoints/cronjobs/updateexchange.php @@ -1,104 +1,104 @@ prepare($query); +$usersToUpdateExchange = $stmt->execute(); + +while ($userToUpdateExchange = $usersToUpdateExchange->fetchArray(SQLITE3_ASSOC)) { + $userId = $userToUpdateExchange['id']; + echo "For user: " . $userToUpdateExchange['username'] . "
"; + + $query = "SELECT api_key, provider FROM fixer WHERE user_id = :userId"; $stmt = $db->prepare($query); - $usersToUpdateExchange = $stmt->execute(); + $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); - while ($userToUpdateExchange = $usersToUpdateExchange->fetchArray(SQLITE3_ASSOC)) { - $userId = $userToUpdateExchange['id']; - echo "For user: " . $userToUpdateExchange['username'] . "
"; + if ($result) { + $row = $result->fetchArray(SQLITE3_ASSOC); - $query = "SELECT api_key, provider FROM fixer WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); + if ($row) { + $apiKey = $row['api_key']; + $provider = $row['provider']; - if ($result) { + $codes = ""; + $query = "SELECT id, name, symbol, code FROM currencies WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $codes .= $row['code'] . ","; + } + $codes = rtrim($codes, ','); + $query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); $row = $result->fetchArray(SQLITE3_ASSOC); - - if ($row) { - $apiKey = $row['api_key']; - $provider = $row['provider']; + $mainCurrencyCode = $row['code']; + $mainCurrencyId = $row['main_currency']; - $codes = ""; - $query = "SELECT id, name, symbol, code FROM currencies WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $codes .= $row['code'].","; - } - $codes = rtrim($codes, ','); - $query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $row = $result->fetchArray(SQLITE3_ASSOC); - $mainCurrencyCode = $row['code']; - $mainCurrencyId = $row['main_currency']; - - if ($provider === 1) { - $api_url = "https://api.apilayer.com/fixer/latest?base=EUR&symbols=" . $codes; - $context = stream_context_create([ - 'http' => [ - 'method' => 'GET', - 'header' => 'apikey: ' . $apiKey, - ] - ]); - $response = file_get_contents($api_url, false, $context); - } else { - $api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=EUR&symbols=" . $codes; - $response = file_get_contents($api_url); - } + if ($provider === 1) { + $api_url = "https://api.apilayer.com/fixer/latest?base=EUR&symbols=" . $codes; + $context = stream_context_create([ + 'http' => [ + 'method' => 'GET', + 'header' => 'apikey: ' . $apiKey, + ] + ]); + $response = file_get_contents($api_url, false, $context); + } else { + $api_url = "http://data.fixer.io/api/latest?access_key=" . $apiKey . "&base=EUR&symbols=" . $codes; + $response = file_get_contents($api_url); + } - $apiData = json_decode($response, true); - - $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode]; - - if ($apiData !== null && isset($apiData['rates'])) { - foreach ($apiData['rates'] as $currencyCode => $rate) { - if ($currencyCode === $mainCurrencyCode) { - $exchangeRate = 1.0; - } else { - $exchangeRate = $rate / $mainCurrencyToEUR; - } - $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code"; - $updateStmt = $db->prepare($updateQuery); - $updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT); - $updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT); - $updateResult = $updateStmt->execute(); - - if (!$updateResult) { - echo "Error updating rate for currency: $currencyCode
"; - } - } - $currentDate = new DateTime(); - $formattedDate = $currentDate->format('Y-m-d'); + $apiData = json_decode($response, true); - $deleteQuery = "DELETE FROM last_exchange_update WHERE user_id = :userId"; - $deleteStmt = $db->prepare($deleteQuery); - $deleteResult = $deleteStmt->execute(); + $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode]; - $query = "INSERT INTO last_exchange_update (date, user_id) VALUES (:formattedDate, :userId)"; - $stmt = $db->prepare($query); - $stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); + if ($apiData !== null && isset($apiData['rates'])) { + foreach ($apiData['rates'] as $currencyCode => $rate) { + if ($currencyCode === $mainCurrencyCode) { + $exchangeRate = 1.0; + } else { + $exchangeRate = $rate / $mainCurrencyToEUR; + } + $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code"; + $updateStmt = $db->prepare($updateQuery); + $updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT); + $updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT); + $updateResult = $updateStmt->execute(); - echo "Rates updated successfully!
"; + if (!$updateResult) { + echo "Error updating rate for currency: $currencyCode
"; + } } - } else { - echo "Exchange rates update skipped. No fixer.io api key provided
"; - $apiKey = null; + $currentDate = new DateTime(); + $formattedDate = $currentDate->format('Y-m-d'); + + $deleteQuery = "DELETE FROM last_exchange_update WHERE user_id = :userId"; + $deleteStmt = $db->prepare($deleteQuery); + $deleteResult = $deleteStmt->execute(); + + $query = "INSERT INTO last_exchange_update (date, user_id) VALUES (:formattedDate, :userId)"; + $stmt = $db->prepare($query); + $stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT); + $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + + echo "Rates updated successfully!
"; } } else { echo "Exchange rates update skipped. No fixer.io api key provided
"; $apiKey = null; } + } else { + echo "Exchange rates update skipped. No fixer.io api key provided
"; + $apiKey = null; } - $db->close(); +} +$db->close(); ?> \ No newline at end of file diff --git a/endpoints/cronjobs/updatenextpayment.php b/endpoints/cronjobs/updatenextpayment.php index f3a4ef5b1..70ad02806 100644 --- a/endpoints/cronjobs/updatenextpayment.php +++ b/endpoints/cronjobs/updatenextpayment.php @@ -1,66 +1,66 @@ format('Y-m-d'); +$currentDate = new DateTime(); +$currentDateString = $currentDate->format('Y-m-d'); - $cycles = array(); - $query = "SELECT * FROM cycles"; - $result = $db->query($query); - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $cycleId = $row['id']; - $cycles[$cycleId] = $row; - } - - $query = "SELECT id, next_payment, frequency, cycle FROM subscriptions WHERE next_payment < :currentDate"; - $stmt = $db->prepare($query); - $stmt->bindValue(':currentDate', $currentDate->format('Y-m-d')); - $result = $stmt->execute(); +$cycles = array(); +$query = "SELECT * FROM cycles"; +$result = $db->query($query); +while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $cycleId = $row['id']; + $cycles[$cycleId] = $row; +} - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $subscriptionId = $row['id']; - $nextPaymentDate = new DateTime($row['next_payment']); - $frequency = $row['frequency']; - $cycle = $cycles[$row['cycle']]['name']; +$query = "SELECT id, next_payment, frequency, cycle FROM subscriptions WHERE next_payment < :currentDate"; +$stmt = $db->prepare($query); +$stmt->bindValue(':currentDate', $currentDate->format('Y-m-d')); +$result = $stmt->execute(); - // 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"; - } +while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $subscriptionId = $row['id']; + $nextPaymentDate = new DateTime($row['next_payment']); + $frequency = $row['frequency']; + $cycle = $cycles[$row['cycle']]['name']; - $interval = new DateInterval($intervalSpec); + // 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"; + } - // Add intervals until the next payment date is in the future - while ($nextPaymentDate < $currentDate) { - $nextPaymentDate->add($interval); - } + $interval = new DateInterval($intervalSpec); - // 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(); + // Add intervals until the next payment date is in the future + while ($nextPaymentDate < $currentDate) { + $nextPaymentDate->add($interval); } - $formattedDate = $currentDate->format('Y-m-d'); + // 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(); +} + +$formattedDate = $currentDate->format('Y-m-d'); - $deleteQuery = "DELETE FROM last_update_next_payment_date"; - $deleteStmt = $db->prepare($deleteQuery); - $deleteResult = $deleteStmt->execute(); +$deleteQuery = "DELETE FROM last_update_next_payment_date"; +$deleteStmt = $db->prepare($deleteQuery); +$deleteResult = $deleteStmt->execute(); - $query = "INSERT INTO last_update_next_payment_date (date) VALUES (:formattedDate)"; - $stmt = $db->prepare($query); - $stmt->bindParam(':formattedDate', $currentDateString, SQLITE3_TEXT); - $result = $stmt->execute(); +$query = "INSERT INTO last_update_next_payment_date (date) VALUES (:formattedDate)"; +$stmt = $db->prepare($query); +$stmt->bindParam(':formattedDate', $currentDateString, SQLITE3_TEXT); +$result = $stmt->execute(); - echo "Updated next payment dates"; +echo "Updated next payment dates"; ?> \ No newline at end of file diff --git a/endpoints/currency/add.php b/endpoints/currency/add.php index 7af026b1a..8e2b8cdef 100644 --- a/endpoints/currency/add.php +++ b/endpoints/currency/add.php @@ -3,25 +3,25 @@ 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); - } + $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, @@ -30,4 +30,4 @@ echo json_encode($response); } -?> +?> \ No newline at end of file diff --git a/endpoints/currency/currency.php b/endpoints/currency/currency.php index 92f8aff03..f2e30ab9c 100644 --- a/endpoints/currency/currency.php +++ b/endpoints/currency/currency.php @@ -16,7 +16,7 @@ $stmtInsert->bindParam(':rate', $currencyRate, SQLITE3_TEXT); $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER); $resultInsert = $stmtInsert->execute(); - + if ($resultInsert) { $currencyId = $db->lastInsertRowID(); echo $currencyId; @@ -126,4 +126,4 @@ echo json_encode($response); } -?> +?> \ No newline at end of file diff --git a/endpoints/currency/edit.php b/endpoints/currency/edit.php index 4ea3c9c7a..a40cc2460 100644 --- a/endpoints/currency/edit.php +++ b/endpoints/currency/edit.php @@ -45,4 +45,4 @@ echo json_encode($response); } -?> +?> \ No newline at end of file diff --git a/endpoints/currency/fixer_api_key.php b/endpoints/currency/fixer_api_key.php index 10f301a1c..4f40f06ba 100644 --- a/endpoints/currency/fixer_api_key.php +++ b/endpoints/currency/fixer_api_key.php @@ -1,59 +1,59 @@ prepare($removeOldKey); - $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER); - $stmt->execute(); +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; - 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); - } + $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); + $result = $stmt->execute(); + if ($result) { + echo json_encode(["success" => true, "message" => translate('api_key_saved', $i18n)]); } else { - echo json_encode(["success" => true, "message" => translate('apy_key_saved', $i18n)]); + $response = [ + "success" => false, + "message" => translate('failed_to_store_api_key', $i18n) + ]; + echo json_encode($response); } } else { - $response = [ - "success" => false, - "message" => translate('invalid_api_key', $i18n) - ]; - echo json_encode($response); + 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); } } - +} + ?> \ No newline at end of file diff --git a/endpoints/currency/remove.php b/endpoints/currency/remove.php index b65a293d1..a8368314c 100644 --- a/endpoints/currency/remove.php +++ b/endpoints/currency/remove.php @@ -67,4 +67,4 @@ echo json_encode($response); } -?> +?> \ No newline at end of file diff --git a/endpoints/currency/update_exchange.php b/endpoints/currency/update_exchange.php index 49f96de7c..1ce46a2b3 100644 --- a/endpoints/currency/update_exchange.php +++ b/endpoints/currency/update_exchange.php @@ -18,7 +18,7 @@ $currentDateString = $currentDate->format('Y-m-d'); $shouldUpdate = $lastUpdateDateString < $currentDateString; } - + if (!$shouldUpdate) { echo "Rates are current, no need to update."; exit; @@ -30,7 +30,7 @@ if ($result) { $row = $result->fetchArray(SQLITE3_ASSOC); - + if ($row) { $apiKey = $row['api_key']; $provider = $row['provider']; @@ -41,7 +41,7 @@ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); $result = $stmt->execute(); while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $codes .= $row['code'].","; + $codes .= $row['code'] . ","; } $codes = rtrim($codes, ','); $query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = :userId"; @@ -62,7 +62,7 @@ ]); $response = file_get_contents($api_url, false, $context); } else { - $api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=EUR&symbols=" . $codes; + $api_url = "http://data.fixer.io/api/latest?access_key=" . $apiKey . "&base=EUR&symbols=" . $codes; $response = file_get_contents($api_url); } diff --git a/endpoints/db/backup.php b/endpoints/db/backup.php index 346e3a7f2..f27c5cfe6 100644 --- a/endpoints/db/backup.php +++ b/endpoints/db/backup.php @@ -8,21 +8,23 @@ ])); } -function addFolderToZip($dir, $zipArchive, $zipdir = ''){ +function addFolderToZip($dir, $zipArchive, $zipdir = '') +{ if (is_dir($dir)) { if ($dh = opendir($dir)) { //Add the directory - if(!empty($zipdir)) $zipArchive->addEmptyDir($zipdir); + if (!empty($zipdir)) + $zipArchive->addEmptyDir($zipdir); while (($file = readdir($dh)) !== false) { // Skip '.' and '..' if ($file == "." || $file == "..") { continue; } //If it's a folder, run the function again! - if(is_dir($dir . $file)){ + if (is_dir($dir . $file)) { $newdir = $dir . $file . '/'; addFolderToZip($newdir, $zipArchive, $zipdir . $file . '/'); - }else{ + } else { //Add the files $zipArchive->addFile($dir . $file, $zipdir . $file); } @@ -40,7 +42,7 @@ function addFolderToZip($dir, $zipArchive, $zipdir = ''){ $filename = "backup_" . uniqid() . ".zip"; $zipname = "../../.tmp/" . $filename; -if ($zip->open($zipname, ZipArchive::CREATE)!==TRUE) { +if ($zip->open($zipname, ZipArchive::CREATE) !== TRUE) { die(json_encode([ "success" => false, "message" => translate('cannot_open_zip', $i18n) diff --git a/endpoints/db/import.php b/endpoints/db/import.php index d346e7e08..41907f0f5 100644 --- a/endpoints/db/import.php +++ b/endpoints/db/import.php @@ -42,8 +42,8 @@ $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); - foreach ( $ri as $file ) { - if ( $file->isDir() ) { + foreach ($ri as $file) { + if ($file->isDir()) { rmdir($file->getPathname()); } else { unlink($file->getPathname()); @@ -67,12 +67,12 @@ } } } - + $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator('../../.tmp', RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); - + foreach ($files as $fileinfo) { $removeFunction = ($fileinfo->isDir() ? 'rmdir' : 'unlink'); $removeFunction($fileinfo->getRealPath()); diff --git a/endpoints/db/migrate.php b/endpoints/db/migrate.php index e78947709..0e5b9893a 100644 --- a/endpoints/db/migrate.php +++ b/endpoints/db/migrate.php @@ -1,5 +1,6 @@ query('SELECT name FROM sqlite_master WHERE type="table" AND name="migrations"') - ->fetchArray(SQLITE3_ASSOC) !== false; + ->query('SELECT name FROM sqlite_master WHERE type="table" AND name="migrations"') + ->fetchArray(SQLITE3_ASSOC) !== false; if ($migrationTableExists) { $migrationQuery = $db->query('SELECT migration FROM migrations'); @@ -34,11 +35,11 @@ function errorHandler($severity, $message, $file, $line) { $allMigrations = glob('../../migrations/*.php'); } -$allMigrations = array_map(function($migration) { +$allMigrations = array_map(function ($migration) { return str_replace('../../', '', $migration); }, $allMigrations); -$completedMigrations = array_map(function($migration) { +$completedMigrations = array_map(function ($migration) { return str_replace('../../', '', $migration); }, $completedMigrations); diff --git a/endpoints/db/restore.php b/endpoints/db/restore.php index 580316436..787295475 100644 --- a/endpoints/db/restore.php +++ b/endpoints/db/restore.php @@ -40,8 +40,8 @@ $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); - foreach ( $ri as $file ) { - if ( $file->isDir() ) { + foreach ($ri as $file) { + if ($file->isDir()) { rmdir($file->getPathname()); } else { unlink($file->getPathname()); @@ -70,12 +70,12 @@ new RecursiveDirectoryIterator('../../.tmp', RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); - + foreach ($files as $fileinfo) { $removeFunction = ($fileinfo->isDir() ? 'rmdir' : 'unlink'); $removeFunction($fileinfo->getRealPath()); } - + echo json_encode([ "success" => true, "message" => translate("success", $i18n) diff --git a/endpoints/household/household.php b/endpoints/household/household.php index 334e61474..d82861f53 100644 --- a/endpoints/household/household.php +++ b/endpoints/household/household.php @@ -10,7 +10,7 @@ $stmtInsert->bindParam(':name', $householdName, SQLITE3_TEXT); $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER); $resultInsert = $stmtInsert->execute(); - + if ($resultInsert) { $householdId = $db->lastInsertRowID(); $response = [ @@ -110,4 +110,4 @@ echo translate('error', $i18n); } -?> +?> \ No newline at end of file diff --git a/endpoints/logos/search.php b/endpoints/logos/search.php index f5f585400..f89aa6373 100644 --- a/endpoints/logos/search.php +++ b/endpoints/logos/search.php @@ -1,83 +1,84 @@ 'Failed to fetch data from Google.']); - } else { - $imageUrls = extractImageUrlsFromPage($response); - header('Content-Type: application/json'); - echo json_encode(['imageUrls' => $imageUrls]); - } + echo json_encode(['error' => 'Failed to fetch data from Google.']); } else { - // Parse the HTML response to extract image URLs $imageUrls = extractImageUrlsFromPage($response); - - // Pass the image URLs to the client header('Content-Type: application/json'); echo json_encode(['imageUrls' => $imageUrls]); } - - curl_close($ch); } else { - echo json_encode(['error' => 'Invalid request.']); + // Parse the HTML response to extract image URLs + $imageUrls = extractImageUrlsFromPage($response); + + // Pass the image URLs to the client + header('Content-Type: application/json'); + echo json_encode(['imageUrls' => $imageUrls]); } - function extractImageUrlsFromPage($html) { - $imageUrls = []; + curl_close($ch); +} else { + echo json_encode(['error' => 'Invalid request.']); +} + +function extractImageUrlsFromPage($html) +{ + $imageUrls = []; - $doc = new DOMDocument(); - @$doc->loadHTML($html); + $doc = new DOMDocument(); + @$doc->loadHTML($html); - $imgTags = $doc->getElementsByTagName('img'); - foreach ($imgTags as $imgTag) { - $src = $imgTag->getAttribute('src'); - if (!strstr($imgTag->getAttribute('class'), "favicon") && !strstr($imgTag->getAttribute('class'), "logo")) { - if (filter_var($src, FILTER_VALIDATE_URL)) { - $imageUrls[] = $src; - } + $imgTags = $doc->getElementsByTagName('img'); + foreach ($imgTags as $imgTag) { + $src = $imgTag->getAttribute('src'); + if (!strstr($imgTag->getAttribute('class'), "favicon") && !strstr($imgTag->getAttribute('class'), "logo")) { + if (filter_var($src, FILTER_VALIDATE_URL)) { + $imageUrls[] = $src; } } - - return $imageUrls; } - -?> + + return $imageUrls; +} + +?> \ No newline at end of file diff --git a/endpoints/notifications/savediscordnotifications.php b/endpoints/notifications/savediscordnotifications.php index f3caaf7f4..9eb2e91b6 100644 --- a/endpoints/notifications/savediscordnotifications.php +++ b/endpoints/notifications/savediscordnotifications.php @@ -1,77 +1,77 @@ 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('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(); - - if ($result === false) { + $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); - } else { - $row = $result->fetchArray(); - $count = $row[0]; - if ($count == 0) { - $query = "INSERT INTO discord_notifications (enabled, webhook_url, bot_username, bot_avatar_url, user_id) - VALUES (:enabled, :webhook_url, :bot_username, :bot_avatar_url, :userId)"; - } else { - $query = "UPDATE discord_notifications - SET enabled = :enabled, webhook_url = :webhook_url, bot_username = :bot_username, bot_avatar_url = :bot_avatar_url - WHERE user_id = :userId"; - } - - $stmt = $db->prepare($query); - $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER); - $stmt->bindValue(':webhook_url', $webhook_url, SQLITE3_TEXT); - $stmt->bindValue(':bot_username', $bot_username, SQLITE3_TEXT); - $stmt->bindValue(':bot_avatar_url', $bot_avatar_url, SQLITE3_TEXT); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - - if ($stmt->execute()) { - $response = [ - "success" => true, - "message" => translate('notifications_settings_saved', $i18n) - ]; - echo json_encode($response); - } else { - $response = [ - "success" => false, - "message" => translate('error_saving_notifications', $i18n) - ]; - echo json_encode($response); - } } } } +} ?> \ No newline at end of file diff --git a/endpoints/notifications/saveemailnotifications.php b/endpoints/notifications/saveemailnotifications.php index 625043199..1965462ca 100644 --- a/endpoints/notifications/saveemailnotifications.php +++ b/endpoints/notifications/saveemailnotifications.php @@ -1,87 +1,87 @@ false, + "message" => translate('session_expired', $i18n) + ])); +} + +if ($_SERVER["REQUEST_METHOD"] === "POST") { + $postData = file_get_contents("php://input"); + $data = json_decode($postData, true); + + if ( + !isset($data["smtpaddress"]) || $data["smtpaddress"] == "" || + !isset($data["smtpport"]) || $data["smtpport"] == "" || + !isset($data["smtpusername"]) || $data["smtpusername"] == "" || + !isset($data["smtppassword"]) || $data["smtppassword"] == "" + ) { + $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"]; - 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"] == "" || - !isset($data["smtpusername"]) || $data["smtpusername"] == "" || - !isset($data["smtppassword"]) || $data["smtppassword"] == "" - ) { + 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, encryption, user_id) + VALUES (:enabled, :smtpAddress, :smtpPort, :smtpUsername, :smtpPassword, :fromEmail, :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, encryption = :encryption WHERE user_id = :userId"; } - $smtpUsername = $data["smtpusername"]; - $smtpPassword = $data["smtppassword"]; - $fromEmail = $data["fromemail"]; - $query = "SELECT COUNT(*) FROM email_notifications WHERE user_id = :userId"; $stmt = $db->prepare($query); - $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - - if ($result === false) { + $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(':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); - } 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, encryption, user_id) - VALUES (:enabled, :smtpAddress, :smtpPort, :smtpUsername, :smtpPassword, :fromEmail, :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, 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(':encryption', $encryption, SQLITE3_TEXT); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - - if ($stmt->execute()) { - $response = [ - "success" => true, - "message" => translate('notifications_settings_saved', $i18n) - ]; - echo json_encode($response); - } else { - $response = [ - "success" => false, - "message" => translate('error_saving_notifications', $i18n) - ]; - echo json_encode($response); - } } } } +} ?> \ No newline at end of file diff --git a/endpoints/notifications/savegotifynotifications.php b/endpoints/notifications/savegotifynotifications.php index 6dda4e73c..77a5db23a 100644 --- a/endpoints/notifications/savegotifynotifications.php +++ b/endpoints/notifications/savegotifynotifications.php @@ -1,73 +1,73 @@ 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('session_expired', $i18n) - ])); - } + "message" => translate('fill_mandatory_fields', $i18n) + ]; + echo json_encode($response); + } else { + $enabled = $data["enabled"]; + $url = $data["gotify_url"]; + $token = $data["token"]; - if ($_SERVER["REQUEST_METHOD"] === "POST") { - $postData = file_get_contents("php://input"); - $data = json_decode($postData, true); + $query = "SELECT COUNT(*) FROM gotify_notifications WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); - if ( - !isset($data["gotify_url"]) || $data["gotify_url"] == "" || - !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"]; - $url = $data["gotify_url"]; - $token = $data["token"]; + $row = $result->fetchArray(); + $count = $row[0]; + if ($count == 0) { + $query = "INSERT INTO gotify_notifications (enabled, url, token, user_id) + VALUES (:enabled, :url, :token, :userId)"; + } else { + $query = "UPDATE gotify_notifications + SET enabled = :enabled, url = :url, token = :token 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(); - - if ($result === false) { + $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER); + $stmt->bindValue(':url', $url, 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 { - $row = $result->fetchArray(); - $count = $row[0]; - if ($count == 0) { - $query = "INSERT INTO gotify_notifications (enabled, url, token, user_id) - VALUES (:enabled, :url, :token, :userId)"; - } else { - $query = "UPDATE gotify_notifications - SET enabled = :enabled, url = :url, token = :token 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(':userId', $userId, SQLITE3_INTEGER); - - if ($stmt->execute()) { - $response = [ - "success" => true, - "message" => translate('notifications_settings_saved', $i18n) - ]; - echo json_encode($response); - } else { - $response = [ - "success" => false, - "message" => translate('error_saving_notifications', $i18n) - ]; - echo json_encode($response); - } } } } +} ?> \ No newline at end of file diff --git a/endpoints/notifications/savenotificationsettings.php b/endpoints/notifications/savenotificationsettings.php index f6addcc25..eb88713a8 100644 --- a/endpoints/notifications/savenotificationsettings.php +++ b/endpoints/notifications/savenotificationsettings.php @@ -1,71 +1,71 @@ false, - "message" => translate('session_expired', $i18n) - ])); - } +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); +if ($_SERVER["REQUEST_METHOD"] === "POST") { + $postData = file_get_contents("php://input"); + $data = json_decode($postData, true); - if (!isset($data["days"]) || $data['days'] == "") { + if (!isset($data["days"]) || $data['days'] == "") { + $response = [ + "success" => false, + "message" => translate('fill_mandatory_fields', $i18n) + ]; + echo json_encode($response); + } else { + $days = $data["days"]; + $query = "SELECT COUNT(*) FROM notification_settings WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + + if ($result === false) { $response = [ "success" => false, - "message" => translate('fill_mandatory_fields', $i18n) + "message" => translate('error_saving_notifications', $i18n) ]; echo json_encode($response); } else { - $days = $data["days"]; - $query = "SELECT COUNT(*) FROM notification_settings WHERE user_id = :userId"; + $row = $result->fetchArray(); + $count = $row[0]; + if ($count == 0) { + $query = "INSERT INTO notification_settings (days, user_id) + VALUES (:days, :userId)"; + } else { + $query = "UPDATE notification_settings SET days = :days WHERE user_id = :userId"; + } + $stmt = $db->prepare($query); - $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - - if ($result === false) { + $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(); - } \ No newline at end of file + } +} else { + $response = [ + "success" => false, + "message" => "Invalid request method" + ]; + echo json_encode($response); + exit(); +} \ No newline at end of file diff --git a/endpoints/notifications/saventfynotifications.php b/endpoints/notifications/saventfynotifications.php index ec663bc99..0797e04a6 100644 --- a/endpoints/notifications/saventfynotifications.php +++ b/endpoints/notifications/saventfynotifications.php @@ -1,84 +1,84 @@ 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["topic"]) || $data["topic"] == "" || + !isset($data["host"]) || $data["host"] == "" + ) { + $response = [ "success" => false, - "message" => translate('session_expired', $i18n) - ])); - } + "message" => translate('fill_mandatory_fields', $i18n) + ]; + echo json_encode($response); + } else { + $enabled = $data["enabled"]; + $host = $data["host"]; + $topic = $data["topic"]; + $headers = $data["headers"]; - if ($_SERVER["REQUEST_METHOD"] === "POST") { - $postData = file_get_contents("php://input"); - $data = json_decode($postData, true); + $query = "SELECT COUNT(*) FROM ntfy_notifications WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindParam(":userId", $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); - if ( - !isset($data["topic"]) || $data["topic"] == "" || - !isset($data["host"]) || $data["host"] == "" - ) { + 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"]; + $row = $result->fetchArray(); + $count = $row[0]; + if ($count == 0) { + $query = "INSERT INTO ntfy_notifications (enabled, host, topic, headers, user_id) + VALUES (:enabled, :host, :topic, :headers, :userId)"; + } else { + $query = "UPDATE ntfy_notifications + SET enabled = :enabled, host = :host, topic = :topic, headers = :headers 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(':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) - VALUES (:enabled, :host, :topic, :headers, :userId)"; - } else { - $query = "UPDATE ntfy_notifications - SET enabled = :enabled, host = :host, topic = :topic, headers = :headers 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(':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); } -?> +} else { + $response = [ + "success" => false, + "message" => translate('invalid_request_method', $i18n) + ]; + echo json_encode($response); +} + +?> \ No newline at end of file diff --git a/endpoints/notifications/savepushovernotifications.php b/endpoints/notifications/savepushovernotifications.php index 0c171de12..cff844a4e 100644 --- a/endpoints/notifications/savepushovernotifications.php +++ b/endpoints/notifications/savepushovernotifications.php @@ -1,81 +1,81 @@ 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('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(); - - if ($result === false) { + $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 { - $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); } +} else { + $response = [ + "success" => false, + "message" => translate('invalid_request_method', $i18n) + ]; + echo json_encode($response); +} ?> \ No newline at end of file diff --git a/endpoints/notifications/savetelegramnotifications.php b/endpoints/notifications/savetelegramnotifications.php index af54cb211..8910386cf 100644 --- a/endpoints/notifications/savetelegramnotifications.php +++ b/endpoints/notifications/savetelegramnotifications.php @@ -1,73 +1,73 @@ 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["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(); - - if ($result === false) { + $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); - } else { - $row = $result->fetchArray(); - $count = $row[0]; - if ($count == 0) { - $query = "INSERT INTO telegram_notifications (enabled, bot_token, chat_id, user_id) - VALUES (:enabled, :bot_token, :chat_id, :userId)"; - } else { - $query = "UPDATE telegram_notifications - SET enabled = :enabled, bot_token = :bot_token, chat_id = :chat_id WHERE user_id = :userId"; - } - - $stmt = $db->prepare($query); - $stmt->bindValue(':enabled', $enabled, SQLITE3_INTEGER); - $stmt->bindValue(':bot_token', $bot_token, SQLITE3_TEXT); - $stmt->bindValue(':chat_id', $chat_id, SQLITE3_TEXT); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - - if ($stmt->execute()) { - $response = [ - "success" => true, - "message" => translate('notifications_settings_saved', $i18n) - ]; - echo json_encode($response); - } else { - $response = [ - "success" => false, - "message" => translate('error_saving_notifications', $i18n) - ]; - echo json_encode($response); - } } } } +} ?> \ No newline at end of file diff --git a/endpoints/notifications/savewebhooknotifications.php b/endpoints/notifications/savewebhooknotifications.php index 25fa1be34..c3d099e3a 100644 --- a/endpoints/notifications/savewebhooknotifications.php +++ b/endpoints/notifications/savewebhooknotifications.php @@ -1,75 +1,75 @@ 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["payload"]) || $data["payload"] == "" + ) { + $response = [ "success" => false, - "message" => translate('session_expired', $i18n) - ])); - } + "message" => translate('fill_mandatory_fields', $i18n) + ]; + echo json_encode($response); + } else { + $enabled = $data["enabled"]; + $url = $data["webhook_url"]; + $headers = $data["headers"]; + $payload = $data["payload"]; - if ($_SERVER["REQUEST_METHOD"] === "POST") { - $postData = file_get_contents("php://input"); - $data = json_decode($postData, true); + $query = "SELECT COUNT(*) FROM webhook_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"] == "" || - !isset($data["payload"]) || $data["payload"] == "" - ) { + 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"]; + $row = $result->fetchArray(); + $count = $row[0]; + if ($count == 0) { + $query = "INSERT INTO webhook_notifications (enabled, url, headers, payload, user_id) + VALUES (:enabled, :url, :headers, :payload, :userId)"; + } else { + $query = "UPDATE webhook_notifications + SET enabled = :enabled, url = :url, headers = :headers, payload = :payload 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(); - - if ($result === false) { + $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(':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 webhook_notifications (enabled, url, headers, payload, user_id) - VALUES (:enabled, :url, :headers, :payload, :userId)"; - } else { - $query = "UPDATE webhook_notifications - SET enabled = :enabled, url = :url, headers = :headers, payload = :payload 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(':userId', $userId, SQLITE3_INTEGER); - - if ($stmt->execute()) { - $response = [ - "success" => true, - "message" => translate('notifications_settings_saved', $i18n) - ]; - echo json_encode($response); - } else { - $response = [ - "success" => false, - "message" => translate('error_saving_notifications', $i18n) - ]; - echo json_encode($response); - } } } } +} ?> \ No newline at end of file diff --git a/endpoints/notifications/testdiscordnotifications.php b/endpoints/notifications/testdiscordnotifications.php index 0d0a7dd46..d87eec067 100644 --- a/endpoints/notifications/testdiscordnotifications.php +++ b/endpoints/notifications/testdiscordnotifications.php @@ -40,17 +40,17 @@ ] ] ]; - + 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); diff --git a/endpoints/notifications/testemailnotifications.php b/endpoints/notifications/testemailnotifications.php index 654bb8593..266411af4 100644 --- a/endpoints/notifications/testemailnotifications.php +++ b/endpoints/notifications/testemailnotifications.php @@ -45,7 +45,7 @@ $fromEmail = $data["fromemail"] ? $data['fromemail'] : "wallos@wallosapp.com"; $mail = new PHPMailer(true); - $mail->CharSet="UTF-8"; + $mail->CharSet = "UTF-8"; $mail->isSMTP(); $mail->Host = $smtpAddress; @@ -83,4 +83,4 @@ } } -?> +?> \ No newline at end of file diff --git a/endpoints/notifications/testgotifynotifications.php b/endpoints/notifications/testgotifynotifications.php index 50a594c22..88e5a5697 100644 --- a/endpoints/notifications/testgotifynotifications.php +++ b/endpoints/notifications/testgotifynotifications.php @@ -28,7 +28,7 @@ $priority = 5; $url = $data["gotify_url"]; - $token = $data["token"]; + $token = $data["token"]; $ch = curl_init(); diff --git a/endpoints/notifications/testntfynotifications.php b/endpoints/notifications/testntfynotifications.php index da0d29f81..1f7efb06c 100644 --- a/endpoints/notifications/testntfynotifications.php +++ b/endpoints/notifications/testntfynotifications.php @@ -26,9 +26,9 @@ $host = rtrim($data["host"], '/'); $topic = $data["topic"]; $headers = json_decode($data["headers"], true); - $customheaders = array_map(function($key, $value) { + $customheaders = array_map(function ($key, $value) { return "$key: $value"; - }, array_keys($headers), $headers); + }, array_keys($headers), $headers); $url = "$host/$topic"; diff --git a/endpoints/notifications/testwebhooknotifications.php b/endpoints/notifications/testwebhooknotifications.php index 0543d5671..221c2fded 100644 --- a/endpoints/notifications/testwebhooknotifications.php +++ b/endpoints/notifications/testwebhooknotifications.php @@ -46,7 +46,7 @@ // Execute the request $response = curl_exec($ch); - + // Close the cURL session curl_close($ch); diff --git a/endpoints/payments/add.php b/endpoints/payments/add.php index 165b2929a..6a674ac31 100644 --- a/endpoints/payments/add.php +++ b/endpoints/payments/add.php @@ -1,217 +1,222 @@ transparentPaintImage("rgb(247, 247, 247)", 0, $fuzz, false); + } + $imagick->setImageFormat('png'); + $imagick->writeImage($uploadFile); - function saveLogo($imageData, $uploadFile, $name) { - $image = imagecreatefromstring($imageData); - $removeBackground = isset($settings['removeBackground']) && $settings['removeBackground'] === 'true'; - if ($image !== false) { - $tempFile = tempnam(sys_get_temp_dir(), 'logo'); - imagepng($image, $tempFile); - imagedestroy($image); + $imagick->clear(); + $imagick->destroy(); + unlink($tempFile); - $imagick = new Imagick($tempFile); - if ($removeBackground) { - $fuzz = Imagick::getQuantum() * 0.1; // 10% - $imagick->transparentPaintImage("rgb(247, 247, 247)", 0, $fuzz, false); + return true; + } else { + return false; + } +} + +function resizeAndUploadLogo($uploadedFile, $uploadDir, $name) +{ + $targetWidth = 70; + $targetHeight = 48; + + $timestamp = time(); + $originalFileName = $uploadedFile['name']; + $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION); + $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png'; + $fileName = $timestamp . '-payments-' . sanitizeFilename($name) . '.' . $fileExtension; + $uploadFile = $uploadDir . $fileName; + + if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) { + $fileInfo = getimagesize($uploadFile); + + if ($fileInfo !== false) { + $width = $fileInfo[0]; + $height = $fileInfo[1]; + + // Load the image based on its format + if ($fileExtension === 'png') { + $image = imagecreatefrompng($uploadFile); + } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { + $image = imagecreatefromjpeg($uploadFile); + } elseif ($fileExtension === 'gif') { + $image = imagecreatefromgif($uploadFile); + } elseif ($fileExtension === 'webp') { + $image = imagecreatefromwebp($uploadFile); + } else { + // Handle other image formats as needed + return ""; } - $imagick->setImageFormat('png'); - $imagick->writeImage($uploadFile); - $imagick->clear(); - $imagick->destroy(); - unlink($tempFile); + // Enable alpha channel (transparency) for PNG images + if ($fileExtension === 'png') { + imagesavealpha($image, true); + } - return true; - } else { - return false; - } - } + $newWidth = $width; + $newHeight = $height; - function resizeAndUploadLogo($uploadedFile, $uploadDir, $name) { - $targetWidth = 70; - $targetHeight = 48; - - $timestamp = time(); - $originalFileName = $uploadedFile['name']; - $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION); - $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png'; - $fileName = $timestamp . '-payments-' . sanitizeFilename($name) . '.' . $fileExtension; - $uploadFile = $uploadDir . $fileName; - - if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) { - $fileInfo = getimagesize($uploadFile); - - if ($fileInfo !== false) { - $width = $fileInfo[0]; - $height = $fileInfo[1]; - - // Load the image based on its format - if ($fileExtension === 'png') { - $image = imagecreatefrompng($uploadFile); - } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { - $image = imagecreatefromjpeg($uploadFile); - } elseif ($fileExtension === 'gif') { - $image = imagecreatefromgif($uploadFile); - } elseif ($fileExtension === 'webp') { - $image = imagecreatefromwebp($uploadFile); - } else { - // Handle other image formats as needed - return ""; - } - - // Enable alpha channel (transparency) for PNG images - if ($fileExtension === 'png') { - imagesavealpha($image, true); - } - - $newWidth = $width; - $newHeight = $height; - - if ($width > $targetWidth) { - $newWidth = $targetWidth; - $newHeight = ($targetWidth / $width) * $height; - } - - if ($newHeight > $targetHeight) { - $newWidth = ($targetHeight / $newHeight) * $newWidth; - $newHeight = $targetHeight; - } - - $resizedImage = imagecreatetruecolor($newWidth, $newHeight); - imagesavealpha($resizedImage, true); - $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127); - imagefill($resizedImage, 0, 0, $transparency); - imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); - - if ($fileExtension === 'png') { - imagepng($resizedImage, $uploadFile); - } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { - imagejpeg($resizedImage, $uploadFile); - } elseif ($fileExtension === 'gif') { - imagegif($resizedImage, $uploadFile); - } elseif ($fileExtension === 'webp') { - imagewebp($resizedImage, $uploadFile); - } else { - return ""; - } - - imagedestroy($image); - imagedestroy($resizedImage); - return $fileName; + if ($width > $targetWidth) { + $newWidth = $targetWidth; + $newHeight = ($targetWidth / $width) * $height; + } + + if ($newHeight > $targetHeight) { + $newWidth = ($targetHeight / $newHeight) * $newWidth; + $newHeight = $targetHeight; } + + $resizedImage = imagecreatetruecolor($newWidth, $newHeight); + imagesavealpha($resizedImage, true); + $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127); + imagefill($resizedImage, 0, 0, $transparency); + imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); + + if ($fileExtension === 'png') { + imagepng($resizedImage, $uploadFile); + } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { + imagejpeg($resizedImage, $uploadFile); + } elseif ($fileExtension === 'gif') { + imagegif($resizedImage, $uploadFile); + } elseif ($fileExtension === 'webp') { + imagewebp($resizedImage, $uploadFile); + } else { + return ""; + } + + imagedestroy($image); + imagedestroy($resizedImage); + return $fileName; } - - return ""; } - if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) { - if ($_SERVER["REQUEST_METHOD"] === "POST") { - $enabled = 1; - $name = validate($_POST["paymentname"]); - $iconUrl = validate($_POST['icon-url']); - - if ($name === "" || ($iconUrl === "" && empty($_FILES['paymenticon']['name']))) { - $response = [ - "success" => false, - "errorMessage" => translate('fill_all_fields', $i18n) - ]; - echo json_encode($response); - exit(); - } + return ""; +} + +if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) { + if ($_SERVER["REQUEST_METHOD"] === "POST") { + $enabled = 1; + $name = validate($_POST["paymentname"]); + $iconUrl = validate($_POST['icon-url']); + + if ($name === "" || ($iconUrl === "" && empty($_FILES['paymenticon']['name']))) { + $response = [ + "success" => false, + "errorMessage" => translate('fill_all_fields', $i18n) + ]; + echo json_encode($response); + exit(); + } - - $icon = ""; - if($iconUrl !== "") { - $icon = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name); - } 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); + $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(); - } + // 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(); +} +$db->close(); ?> \ No newline at end of file diff --git a/endpoints/payments/delete.php b/endpoints/payments/delete.php index 010f9af16..bee526406 100644 --- a/endpoints/payments/delete.php +++ b/endpoints/payments/delete.php @@ -27,4 +27,4 @@ } $db->close(); -?> +?> \ No newline at end of file diff --git a/endpoints/payments/get.php b/endpoints/payments/get.php index 5ff6af418..f6348db96 100644 --- a/endpoints/payments/get.php +++ b/endpoints/payments/get.php @@ -6,12 +6,12 @@ $paymentsInUseQuery = $db->prepare('SELECT id FROM payment_methods WHERE id IN (SELECT DISTINCT payment_method_id FROM subscriptions) AND user_id = :userId'); $paymentsInUseQuery->bindParam(':userId', $userId, SQLITE3_INTEGER); $result = $paymentsInUseQuery->execute(); - + $paymentsInUse = []; while ($row = $result->fetchArray(SQLITE3_ASSOC)) { $paymentsInUse[] = $row['id']; } - + $sql = "SELECT * FROM payment_methods WHERE user_id = :userId"; $stmt = $db->prepare($sql); $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); @@ -20,7 +20,7 @@ if ($result) { $payments = array(); while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $payments[] = $row; + $payments[] = $row; } } else { http_response_code(500); @@ -32,26 +32,25 @@ $paymentIconFolder = (strpos($payment['icon'], 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/"; $inUse = in_array($payment['id'], $paymentsInUse); ?> -
- Logo - - - - -
- x -
- " data-in-use="" + data-paymentid="" + title="" + onClick="togglePayment()"> + Logo + + + + -
+
+ x +
+ + false, - "message" => tranlate('failed_update_payment', $i18n) + "message" => translate('failed_update_payment', $i18n) ])); diff --git a/endpoints/payments/search.php b/endpoints/payments/search.php index 8deb47fbe..b88a08be0 100644 --- a/endpoints/payments/search.php +++ b/endpoints/payments/search.php @@ -1,83 +1,84 @@ 'Failed to fetch data from Google.']); - } else { - $imageUrls = extractImageUrlsFromPage($response); - header('Content-Type: application/json'); - echo json_encode(['imageUrls' => $imageUrls]); - } + echo json_encode(['error' => 'Failed to fetch data from Google.']); } else { - // Parse the HTML response to extract image URLs $imageUrls = extractImageUrlsFromPage($response); - - // Pass the image URLs to the client header('Content-Type: application/json'); echo json_encode(['imageUrls' => $imageUrls]); } - - curl_close($ch); } else { - echo json_encode(['error' => 'Invalid request.']); + // Parse the HTML response to extract image URLs + $imageUrls = extractImageUrlsFromPage($response); + + // Pass the image URLs to the client + header('Content-Type: application/json'); + echo json_encode(['imageUrls' => $imageUrls]); } - function extractImageUrlsFromPage($html) { - $imageUrls = []; + curl_close($ch); +} else { + echo json_encode(['error' => 'Invalid request.']); +} + +function extractImageUrlsFromPage($html) +{ + $imageUrls = []; - $doc = new DOMDocument(); - @$doc->loadHTML($html); + $doc = new DOMDocument(); + @$doc->loadHTML($html); - $imgTags = $doc->getElementsByTagName('img'); - foreach ($imgTags as $imgTag) { - $src = $imgTag->getAttribute('src'); - if (!strstr($imgTag->getAttribute('class'), "favicon") && !strstr($imgTag->getAttribute('class'), "logo")) { - if (filter_var($src, FILTER_VALIDATE_URL)) { - $imageUrls[] = $src; - } + $imgTags = $doc->getElementsByTagName('img'); + foreach ($imgTags as $imgTag) { + $src = $imgTag->getAttribute('src'); + if (!strstr($imgTag->getAttribute('class'), "favicon") && !strstr($imgTag->getAttribute('class'), "logo")) { + if (filter_var($src, FILTER_VALIDATE_URL)) { + $imageUrls[] = $src; } } - - return $imageUrls; } - + + return $imageUrls; +} + ?> \ No newline at end of file diff --git a/endpoints/payments/sort.php b/endpoints/payments/sort.php index a217beb84..7fc5a221c 100644 --- a/endpoints/payments/sort.php +++ b/endpoints/payments/sort.php @@ -20,7 +20,7 @@ "success" => true, "message" => translate("sort_order_saved", $i18n) ]; - echo json_encode($response); + echo json_encode($response); } else { $response = [ "success" => false, diff --git a/endpoints/settings/colortheme.php b/endpoints/settings/colortheme.php index 00b9c1e7f..c8632ac4f 100644 --- a/endpoints/settings/colortheme.php +++ b/endpoints/settings/colortheme.php @@ -1,35 +1,35 @@ false, - "message" => translate('session_expired', $i18n) - ])); - } +require_once '../../includes/connect_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); - if ($_SERVER["REQUEST_METHOD"] === "POST") { - $postData = file_get_contents("php://input"); - $data = json_decode($postData, true); - - $color = $data['color']; + $color = $data['color']; - $stmt = $db->prepare('UPDATE settings SET color_theme = :color WHERE user_id = :userId'); - $stmt->bindParam(':color', $color, SQLITE3_TEXT); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $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) + ])); } +} ?> \ No newline at end of file diff --git a/endpoints/settings/convert_currency.php b/endpoints/settings/convert_currency.php index 0f04d5698..a84701696 100644 --- a/endpoints/settings/convert_currency.php +++ b/endpoints/settings/convert_currency.php @@ -11,7 +11,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") { $postData = file_get_contents("php://input"); $data = json_decode($postData, true); - + $convert_currency = $data['value']; $stmt = $db->prepare('UPDATE settings SET convert_currency = :convert_currency WHERE user_id = :userId'); diff --git a/endpoints/settings/customtheme.php b/endpoints/settings/customtheme.php index 4d05a100c..270304164 100644 --- a/endpoints/settings/customtheme.php +++ b/endpoints/settings/customtheme.php @@ -1,42 +1,42 @@ false, + "message" => translate('session_expired', $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']; + + $stmt = $db->prepare('DELETE FROM custom_colors'); + $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('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']; - - $stmt = $db->prepare('DELETE FROM custom_colors'); - $stmt->execute(); - - $stmt = $db->prepare('INSERT INTO custom_colors (main_color, accent_color, hover_color, user_id) VALUES (:main_color, :accent_color, :hover_color, :userId)'); - $stmt->bindParam(':main_color', $main_color, SQLITE3_TEXT); - $stmt->bindParam(':accent_color', $accent_color, SQLITE3_TEXT); - $stmt->bindParam(':hover_color', $hover_color, SQLITE3_TEXT); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - - if ($stmt->execute()) { - die(json_encode([ - "success" => true, - "message" => translate("success", $i18n) - ])); - } else { - die(json_encode([ - "success" => false, - "message" => translate("error", $i18n) - ])); - } - } +} ?> \ No newline at end of file diff --git a/endpoints/settings/hide_disabled.php b/endpoints/settings/hide_disabled.php index 37da59896..bf07b42ae 100644 --- a/endpoints/settings/hide_disabled.php +++ b/endpoints/settings/hide_disabled.php @@ -11,7 +11,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") { $postData = file_get_contents("php://input"); $data = json_decode($postData, true); - + $hide_disabled = $data['value']; $stmt = $db->prepare('UPDATE settings SET hide_disabled = :hide_disabled WHERE user_id = :userId'); diff --git a/endpoints/settings/monthly_price.php b/endpoints/settings/monthly_price.php index 8894a99be..a3410ced8 100644 --- a/endpoints/settings/monthly_price.php +++ b/endpoints/settings/monthly_price.php @@ -11,7 +11,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") { $postData = file_get_contents("php://input"); $data = json_decode($postData, true); - + $monthly_price = $data['value']; $stmt = $db->prepare('UPDATE settings SET monthly_price = :monthly_price WHERE user_id = :userId'); diff --git a/endpoints/settings/remove_background.php b/endpoints/settings/remove_background.php index 2eabd3008..92badd430 100644 --- a/endpoints/settings/remove_background.php +++ b/endpoints/settings/remove_background.php @@ -11,7 +11,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") { $postData = file_get_contents("php://input"); $data = json_decode($postData, true); - + $remove_background = $data['value']; $stmt = $db->prepare('UPDATE settings SET remove_background = :remove_background WHERE user_id = :userId'); diff --git a/endpoints/settings/resettheme.php b/endpoints/settings/resettheme.php index f3e38c995..8204c9dd0 100644 --- a/endpoints/settings/resettheme.php +++ b/endpoints/settings/resettheme.php @@ -1,29 +1,29 @@ false, + "message" => translate('session_expired', $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('session_expired', $i18n) + "message" => translate("error", $i18n) ])); } - - if ($_SERVER["REQUEST_METHOD"] === "DELETE") { - $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :userId'); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - - if ($stmt->execute()) { - die(json_encode([ - "success" => true, - "message" => translate("success", $i18n) - ])); - } else { - die(json_encode([ - "success" => false, - "message" => translate("error", $i18n) - ])); - } - } +} ?> \ No newline at end of file diff --git a/endpoints/settings/theme.php b/endpoints/settings/theme.php index 46ca9ce52..bcc1967ba 100644 --- a/endpoints/settings/theme.php +++ b/endpoints/settings/theme.php @@ -11,7 +11,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") { $postData = file_get_contents("php://input"); $data = json_decode($postData, true); - + $theme = $data['theme']; $stmt = $db->prepare('UPDATE settings SET dark_theme = :theme WHERE user_id = :userId'); diff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.php index 5fb3f6647..222e80103 100644 --- a/endpoints/subscription/add.php +++ b/endpoints/subscription/add.php @@ -1,240 +1,246 @@ transparentPaintImage("rgb(247, 247, 247)", 0, $fuzz, false); - } - $imagick->setImageFormat('png'); - $imagick->writeImage($uploadFile); + $imagick = new Imagick($tempFile); + if ($removeBackground) { + $fuzz = Imagick::getQuantum() * 0.1; // 10% + $imagick->transparentPaintImage("rgb(247, 247, 247)", 0, $fuzz, false); + } + $imagick->setImageFormat('png'); + $imagick->writeImage($uploadFile); - $imagick->clear(); - $imagick->destroy(); - unlink($tempFile); + $imagick->clear(); + $imagick->destroy(); + unlink($tempFile); - return true; - } else { - return false; - } + return true; + } else { + return false; } +} - function resizeAndUploadLogo($uploadedFile, $uploadDir, $name, $settings) { - $targetWidth = 135; - $targetHeight = 42; - - $timestamp = time(); - $originalFileName = $uploadedFile['name']; - $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION); - $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png'; - $fileName = $timestamp . '-' . sanitizeFilename($name) . '.' . $fileExtension; - $uploadFile = $uploadDir . $fileName; - - if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) { - $fileInfo = getimagesize($uploadFile); - - if ($fileInfo !== false) { - $width = $fileInfo[0]; - $height = $fileInfo[1]; - - // Load the image based on its format - if ($fileExtension === 'png') { - $image = imagecreatefrompng($uploadFile); - } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { - $image = imagecreatefromjpeg($uploadFile); - } elseif ($fileExtension === 'gif') { - $image = imagecreatefromgif($uploadFile); - } elseif ($fileExtension === 'webp') { - $image = imagecreatefromwebp($uploadFile); - } else { - // Handle other image formats as needed - return ""; - } - - // Enable alpha channel (transparency) for PNG images - if ($fileExtension === 'png') { - imagesavealpha($image, true); - } - - $newWidth = $width; - $newHeight = $height; - - if ($width > $targetWidth) { - $newWidth = $targetWidth; - $newHeight = ($targetWidth / $width) * $height; - } - - if ($newHeight > $targetHeight) { - $newWidth = ($targetHeight / $newHeight) * $newWidth; - $newHeight = $targetHeight; - } - - $resizedImage = imagecreatetruecolor($newWidth, $newHeight); - imagesavealpha($resizedImage, true); - $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127); - imagefill($resizedImage, 0, 0, $transparency); - imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); - - if ($fileExtension === 'png') { - imagepng($resizedImage, $uploadFile); - } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { - imagejpeg($resizedImage, $uploadFile); - } elseif ($fileExtension === 'gif') { - imagegif($resizedImage, $uploadFile); - } elseif ($fileExtension === 'webp') { - imagewebp($resizedImage, $uploadFile); - } else { - return ""; - } - - imagedestroy($image); - imagedestroy($resizedImage); - - return $fileName; +function resizeAndUploadLogo($uploadedFile, $uploadDir, $name, $settings) +{ + $targetWidth = 135; + $targetHeight = 42; + + $timestamp = time(); + $originalFileName = $uploadedFile['name']; + $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION); + $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png'; + $fileName = $timestamp . '-' . sanitizeFilename($name) . '.' . $fileExtension; + $uploadFile = $uploadDir . $fileName; + + if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) { + $fileInfo = getimagesize($uploadFile); + + if ($fileInfo !== false) { + $width = $fileInfo[0]; + $height = $fileInfo[1]; + + // Load the image based on its format + if ($fileExtension === 'png') { + $image = imagecreatefrompng($uploadFile); + } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { + $image = imagecreatefromjpeg($uploadFile); + } elseif ($fileExtension === 'gif') { + $image = imagecreatefromgif($uploadFile); + } elseif ($fileExtension === 'webp') { + $image = imagecreatefromwebp($uploadFile); + } else { + // Handle other image formats as needed + return ""; + } + + // Enable alpha channel (transparency) for PNG images + if ($fileExtension === 'png') { + imagesavealpha($image, true); } + + $newWidth = $width; + $newHeight = $height; + + if ($width > $targetWidth) { + $newWidth = $targetWidth; + $newHeight = ($targetWidth / $width) * $height; + } + + if ($newHeight > $targetHeight) { + $newWidth = ($targetHeight / $newHeight) * $newWidth; + $newHeight = $targetHeight; + } + + $resizedImage = imagecreatetruecolor($newWidth, $newHeight); + imagesavealpha($resizedImage, true); + $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127); + imagefill($resizedImage, 0, 0, $transparency); + imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); + + if ($fileExtension === 'png') { + imagepng($resizedImage, $uploadFile); + } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { + imagejpeg($resizedImage, $uploadFile); + } elseif ($fileExtension === 'gif') { + imagegif($resizedImage, $uploadFile); + } elseif ($fileExtension === 'webp') { + imagewebp($resizedImage, $uploadFile); + } else { + return ""; + } + + imagedestroy($image); + imagedestroy($resizedImage); + + return $fileName; } - - 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"]; - $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; - - if($logoUrl !== "") { - $logo = getLogoFromUrl($logoUrl, '../../images/uploads/logos/', $name, $settings); - } 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); + 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"]; + $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; + + 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 (name, logo, price, currency_id, next_payment, cycle, frequency, notes, + 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) VALUES (:name, :logo, :price, :currencyId, :nextPayment, :cycle, :frequency, :notes, :paymentMethodId, :payerUserId, :categoryId, :notify, :inactive, :url, :notifyDaysBefore, :userId)"; - } else { - $id = $_POST['id']; - if ($logo != "") { - $sql = "UPDATE subscriptions SET name = :name, logo = :logo, price = :price, currency_id = :currencyId, + } else { + $id = $_POST['id']; + if ($logo != "") { + $sql = "UPDATE subscriptions SET name = :name, logo = :logo, price = :price, currency_id = :currencyId, next_payment = :nextPayment, cycle = :cycle, frequency = :frequency, notes = :notes, payment_method_id = :paymentMethodId, payer_user_id = :payerUserId, category_id = :categoryId, notify = :notify, inactive = :inactive, url = :url, notify_days_before = :notifyDaysBefore WHERE id = :id AND user_id = :userId"; - } else { - $sql = "UPDATE subscriptions SET name = :name, price = :price, currency_id = :currencyId, next_payment = :nextPayment, + } else { + $sql = "UPDATE subscriptions SET name = :name, price = :price, currency_id = :currencyId, next_payment = :nextPayment, cycle = :cycle, frequency = :frequency, notes = :notes, payment_method_id = :paymentMethodId, payer_user_id = :payerUserId, category_id = :categoryId, notify = :notify, inactive = :inactive, url = :url,notify_days_before = :notifyDaysBefore WHERE id = :id AND user_id = :userId"; - } } + } - $stmt = $db->prepare($sql); - if ($isEdit) { - $stmt->bindParam(':id', $id, SQLITE3_INTEGER); - } - $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(':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(':userId', $userId, SQLITE3_INTEGER); - - if ($stmt->execute()) { - $success['status'] = "Success"; - $text = $isEdit ? "updated" : "added"; - $success['message'] = translate('subscription_' . $text . '_successfuly', $i18n); - $json = json_encode($success); - header('Content-Type: application/json'); - echo $json; - exit(); - } else { - echo translate('error', $i18n) . ": " . $db->lastErrorMsg(); - } + $stmt = $db->prepare($sql); + if ($isEdit) { + $stmt->bindParam(':id', $id, SQLITE3_INTEGER); + } + $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(':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(':userId', $userId, 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(); -?> +} +$db->close(); +?> \ No newline at end of file diff --git a/endpoints/subscription/get.php b/endpoints/subscription/get.php index b69a03150..f9e2134ba 100644 --- a/endpoints/subscription/get.php +++ b/endpoints/subscription/get.php @@ -1,44 +1,44 @@ prepare($query); - $stmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); +require_once '../../includes/connect_endpoint.php'; - $subscriptionData = array(); +if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) { + if (isset($_GET['id']) && $_GET['id'] != "") { + $subscriptionId = intval($_GET['id']); + $query = "SELECT * FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER); + $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); - if ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $subscriptionData['id'] = $subscriptionId; - $subscriptionData['name'] = htmlspecialchars_decode($row['name'] ?? ""); - $subscriptionData['logo'] = $row['logo']; - $subscriptionData['price'] = $row['price']; - $subscriptionData['currency_id'] = $row['currency_id']; - $subscriptionData['next_payment'] = $row['next_payment']; - $subscriptionData['frequency'] = $row['frequency']; - $subscriptionData['cycle'] = $row['cycle']; - $subscriptionData['notes'] = htmlspecialchars_decode($row['notes'] ?? ""); - $subscriptionData['payment_method_id'] = $row['payment_method_id']; - $subscriptionData['payer_user_id'] = $row['payer_user_id']; - $subscriptionData['category_id'] = $row['category_id']; - $subscriptionData['notify'] = $row['notify']; - $subscriptionData['inactive'] = $row['inactive']; - $subscriptionData['url'] = htmlspecialchars_decode($row['url'] ?? ""); - $subscriptionData['notify_days_before'] = $row['notify_days_before']; + $subscriptionData = array(); - $subscriptionJson = json_encode($subscriptionData); - header('Content-Type: application/json'); - echo $subscriptionJson; - } else { - echo translate('error', $i18n); - } + if ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $subscriptionData['id'] = $subscriptionId; + $subscriptionData['name'] = htmlspecialchars_decode($row['name'] ?? ""); + $subscriptionData['logo'] = $row['logo']; + $subscriptionData['price'] = $row['price']; + $subscriptionData['currency_id'] = $row['currency_id']; + $subscriptionData['next_payment'] = $row['next_payment']; + $subscriptionData['frequency'] = $row['frequency']; + $subscriptionData['cycle'] = $row['cycle']; + $subscriptionData['notes'] = htmlspecialchars_decode($row['notes'] ?? ""); + $subscriptionData['payment_method_id'] = $row['payment_method_id']; + $subscriptionData['payer_user_id'] = $row['payer_user_id']; + $subscriptionData['category_id'] = $row['category_id']; + $subscriptionData['notify'] = $row['notify']; + $subscriptionData['inactive'] = $row['inactive']; + $subscriptionData['url'] = htmlspecialchars_decode($row['url'] ?? ""); + $subscriptionData['notify_days_before'] = $row['notify_days_before']; + + $subscriptionJson = json_encode($subscriptionData); + header('Content-Type: application/json'); + echo $subscriptionJson; } else { echo translate('error', $i18n); } + } else { + echo translate('error', $i18n); } - $db->close(); +} +$db->close(); ?> \ No newline at end of file diff --git a/endpoints/subscription/getcalendar.php b/endpoints/subscription/getcalendar.php index 493dd17f6..298be0abc 100644 --- a/endpoints/subscription/getcalendar.php +++ b/endpoints/subscription/getcalendar.php @@ -31,7 +31,7 @@ if ($subscription) { // get payer name from household object - $subscription['payer_user'] = $members[$subscription['payer_user_id']]['name']; + $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']; diff --git a/endpoints/subscriptions/get.php b/endpoints/subscriptions/get.php index 908a05853..ea9302bf9 100644 --- a/endpoints/subscriptions/get.php +++ b/endpoints/subscriptions/get.php @@ -1,128 +1,128 @@ prepare($sql); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) { - $sort = "next_payment"; - $order = "ASC"; - $sql = "SELECT * FROM subscriptions ORDER BY next_payment ASC, inactive ASC"; - if (isset($_COOKIE['sortOrder']) && $_COOKIE['sortOrder'] != "") { - $sort = $_COOKIE['sortOrder']; - $allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id']; - if ($sort == "price" || $sort == "id") { - $order = "DESC"; - } - if (!in_array($sort, $allowedSortCriteria)) { - $sort = "next_payment"; - } - } - - $params = array(); - $sql = "SELECT * FROM subscriptions WHERE user_id = :userId"; - - if (isset($_GET['category']) && $_GET['category'] != "") { - $sql .= " AND category_id = :category"; - $params[':category'] = $_GET['category']; - } - - if (isset($_GET['payment']) && $_GET['payment'] != "") { - $sql .= " AND payment_method_id = :payment"; - $params[':payment'] = $_GET['payment']; - } - - if (isset($_GET['member']) && $_GET['member'] != "") { - $sql .= " AND payer_user_id = :member"; - $params[':member'] = $_GET['member']; - } - - $sql .= " ORDER BY $sort $order, inactive ASC"; - - $stmt = $db->prepare($sql); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - - foreach ($params as $key => $value) { - $stmt->bindValue($key, $value); - } - - $result = $stmt->execute(); - if ($result) { - $subscriptions = array(); - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $subscriptions[] = $row; - } - } - - $defaultLogo = $theme == "light" ? "images/siteicons/" . $colorTheme . "/wallos.png" : "images/siteicons/" . $colorTheme . "/walloswhite.png"; - foreach ($subscriptions as $subscription) { - if ($subscription['inactive'] == 1 && isset($settings['hideDisabledSubscriptions']) && $settings['hideDisabledSubscriptions'] === 'true') { - continue; - } - $id = $subscription['id']; - $print[$id]['id'] = $id; - $print[$id]['logo'] = $subscription['logo'] != "" ? "images/uploads/logos/".$subscription['logo'] : $defaultLogo; - $print[$id]['name'] = htmlspecialchars_decode($subscription['name'] ?? ""); - $cycle = $subscription['cycle']; - $frequency = $subscription['frequency']; - $print[$id]['billing_cycle'] = getBillingCycle($cycle, $frequency, $i18n); - $paymentMethodId = $subscription['payment_method_id']; - $print[$id]['currency_code'] = $currencies[$subscription['currency_id']]['code']; - $currencyId = $subscription['currency_id']; - $print[$id]['next_payment'] = date('M d, Y', strtotime($subscription['next_payment'])); - $paymentIconFolder = (strpos($payment_methods[$paymentMethodId]['icon'], 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/"; - $print[$id]['payment_method_icon'] = $paymentIconFolder . $payment_methods[$paymentMethodId]['icon']; - $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId]['name']; - $print[$id]['payment_method_id'] = $paymentMethodId; - $print[$id]['category_id'] = $subscription['category_id']; - $print[$id]['payer_user_id'] = $subscription['payer_user_id']; - $print[$id]['price'] = floatval($subscription['price']); - $print[$id]['inactive'] = $subscription['inactive']; - $print[$id]['url'] = htmlspecialchars_decode($subscription['url'] ?? ""); - $print[$id]['notes'] = htmlspecialchars_decode($subscription['notes'] ?? ""); - - if (isset($settings['convertCurrency']) && $settings['convertCurrency'] === 'true' && $currencyId != $mainCurrencyId) { - $print[$id]['price'] = getPriceConverted($print[$id]['price'], $currencyId, $db); - $print[$id]['currency_code'] = $currencies[$mainCurrencyId]['code']; - } - if (isset($settings['showMonthlyPrice']) && $settings['showMonthlyPrice'] === 'true') { - $print[$id]['price'] = getPricePerMonth($cycle, $frequency, $print[$id]['price']); - } - } - - if (isset($print)) { - printSubscriptions($print, $sort, $categories, $members, $i18n, $colorTheme); - } - - if (count($subscriptions) == 0) { - ?> -
-

- -

- - <?= translate('empty_page', $i18n) ?> -
- $value) { + $stmt->bindValue($key, $value); + } + + $result = $stmt->execute(); + if ($result) { + $subscriptions = array(); + while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $subscriptions[] = $row; } + } - $db->close(); + $defaultLogo = $theme == "light" ? "images/siteicons/" . $colorTheme . "/wallos.png" : "images/siteicons/" . $colorTheme . "/walloswhite.png"; + foreach ($subscriptions as $subscription) { + if ($subscription['inactive'] == 1 && isset($settings['hideDisabledSubscriptions']) && $settings['hideDisabledSubscriptions'] === 'true') { + continue; + } + $id = $subscription['id']; + $print[$id]['id'] = $id; + $print[$id]['logo'] = $subscription['logo'] != "" ? "images/uploads/logos/" . $subscription['logo'] : $defaultLogo; + $print[$id]['name'] = htmlspecialchars_decode($subscription['name'] ?? ""); + $cycle = $subscription['cycle']; + $frequency = $subscription['frequency']; + $print[$id]['billing_cycle'] = getBillingCycle($cycle, $frequency, $i18n); + $paymentMethodId = $subscription['payment_method_id']; + $print[$id]['currency_code'] = $currencies[$subscription['currency_id']]['code']; + $currencyId = $subscription['currency_id']; + $print[$id]['next_payment'] = date('M d, Y', strtotime($subscription['next_payment'])); + $paymentIconFolder = (strpos($payment_methods[$paymentMethodId]['icon'], 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/"; + $print[$id]['payment_method_icon'] = $paymentIconFolder . $payment_methods[$paymentMethodId]['icon']; + $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId]['name']; + $print[$id]['payment_method_id'] = $paymentMethodId; + $print[$id]['category_id'] = $subscription['category_id']; + $print[$id]['payer_user_id'] = $subscription['payer_user_id']; + $print[$id]['price'] = floatval($subscription['price']); + $print[$id]['inactive'] = $subscription['inactive']; + $print[$id]['url'] = htmlspecialchars_decode($subscription['url'] ?? ""); + $print[$id]['notes'] = htmlspecialchars_decode($subscription['notes'] ?? ""); + + if (isset($settings['convertCurrency']) && $settings['convertCurrency'] === 'true' && $currencyId != $mainCurrencyId) { + $print[$id]['price'] = getPriceConverted($print[$id]['price'], $currencyId, $db); + $print[$id]['currency_code'] = $currencies[$mainCurrencyId]['code']; + } + if (isset($settings['showMonthlyPrice']) && $settings['showMonthlyPrice'] === 'true') { + $print[$id]['price'] = getPricePerMonth($cycle, $frequency, $print[$id]['price']); + } + } + + if (isset($print)) { + printSubscriptions($print, $sort, $categories, $members, $i18n, $colorTheme); + } + + if (count($subscriptions) == 0) { + ?> +
+

+ +

+ + <?= translate('empty_page', $i18n) ?> +
+ close(); ?> \ No newline at end of file diff --git a/endpoints/user/delete_avatar.php b/endpoints/user/delete_avatar.php index 0e6846ca8..0a5d09438 100644 --- a/endpoints/user/delete_avatar.php +++ b/endpoints/user/delete_avatar.php @@ -1,38 +1,38 @@ false, - "message" => translate('session_expired', $i18n) - ])); - } +if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) { + die(json_encode([ + "success" => false, + "message" => translate('session_expired', $i18n) + ])); +} - $input = json_decode(file_get_contents('php://input'), true); - if (isset($input['avatar'])) { - $avatar = "images/uploads/logos/avatars/".$input['avatar']; - $sql = "SELECT avatar FROM user WHERE id = :userId"; - $stmt = $db->prepare($sql); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $userAvatar = $result->fetchArray(SQLITE3_ASSOC)['avatar']; +$input = json_decode(file_get_contents('php://input'), true); +if (isset($input['avatar'])) { + $avatar = "images/uploads/logos/avatars/" . $input['avatar']; + $sql = "SELECT avatar FROM user WHERE id = :userId"; + $stmt = $db->prepare($sql); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + $userAvatar = $result->fetchArray(SQLITE3_ASSOC)['avatar']; - // Check if $avatar matches the avatar in the user table - if ($avatar === $userAvatar) { - echo json_encode(array("success" => false)); - } else { - // The avatars do not match - $filePath = "../../" . $avatar; + // Check if $avatar matches the avatar in the user table + if ($avatar === $userAvatar) { + echo json_encode(array("success" => false)); + } else { + // The avatars do not match + $filePath = "../../" . $avatar; if (file_exists($filePath)) { unlink($filePath); echo json_encode(array("success" => true, "message" => translate("success", $i18n))); } else { echo json_encode(array("success" => false, "message" => translate("error", $i18n))); } - } - } else { - echo json_encode(array("success" => false, "message" => translate("error", $i18n))); } +} else { + echo json_encode(array("success" => false, "message" => translate("error", $i18n))); +} ?> \ No newline at end of file diff --git a/endpoints/user/save_user.php b/endpoints/user/save_user.php index b2cd660da..51a3e719d 100644 --- a/endpoints/user/save_user.php +++ b/endpoints/user/save_user.php @@ -1,256 +1,254 @@ prepare($query); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); +function update_exchange_rate($db, $userId) +{ + $query = "SELECT api_key, provider FROM fixer WHERE user_id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); + + if ($result) { + $row = $result->fetchArray(SQLITE3_ASSOC); + + if ($row) { + $apiKey = $row['api_key']; + $provider = $row['provider']; + + $codes = ""; + $query = "SELECT id, name, symbol, code FROM currencies"; + $result = $db->query($query); + while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $codes .= $row['code'] . ","; + } + $codes = rtrim($codes, ','); - if ($result) { + $query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = :userId"; + $stmt = $db->prepare($query); + $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $result = $stmt->execute(); $row = $result->fetchArray(SQLITE3_ASSOC); - - if ($row) { - $apiKey = $row['api_key']; - $provider = $row['provider']; - - $codes = ""; - $query = "SELECT id, name, symbol, code FROM currencies"; - $result = $db->query($query); - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $codes .= $row['code'].","; + $mainCurrencyCode = $row['code']; + $mainCurrencyId = $row['main_currency']; + + if ($provider === 1) { + $api_url = "https://api.apilayer.com/fixer/latest?base=EUR&symbols=" . $codes; + $context = stream_context_create([ + 'http' => [ + 'method' => 'GET', + 'header' => 'apikey: ' . $apiKey, + ] + ]); + $response = file_get_contents($api_url, false, $context); + } else { + $api_url = "http://data.fixer.io/api/latest?access_key=" . $apiKey . "&base=EUR&symbols=" . $codes; + $response = file_get_contents($api_url); + } + + $apiData = json_decode($response, true); + + $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode]; + + if ($apiData !== null && isset($apiData['rates'])) { + foreach ($apiData['rates'] as $currencyCode => $rate) { + if ($currencyCode === $mainCurrencyCode) { + $exchangeRate = 1.0; + } else { + $exchangeRate = $rate / $mainCurrencyToEUR; + } + $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId"; + $updateStmt = $db->prepare($updateQuery); + $updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT); + $updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT); + $updateStmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $updateResult = $updateStmt->execute(); } - $codes = rtrim($codes, ','); + $currentDate = new DateTime(); + $formattedDate = $currentDate->format('Y-m-d'); - $query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = :userId"; + $query = "SELECT * FROM last_exchange_update WHERE user_id = :userId"; $stmt = $db->prepare($query); $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); $result = $stmt->execute(); $row = $result->fetchArray(SQLITE3_ASSOC); - $mainCurrencyCode = $row['code']; - $mainCurrencyId = $row['main_currency']; - - if ($provider === 1) { - $api_url = "https://api.apilayer.com/fixer/latest?base=EUR&symbols=" . $codes; - $context = stream_context_create([ - 'http' => [ - 'method' => 'GET', - 'header' => 'apikey: ' . $apiKey, - ] - ]); - $response = file_get_contents($api_url, false, $context); + + if ($row) { + $query = "UPDATE last_exchange_update SET date = :formattedDate WHERE user_id = :userId"; } else { - $api_url = "http://data.fixer.io/api/latest?access_key=". $apiKey . "&base=EUR&symbols=" . $codes; - $response = file_get_contents($api_url); + $query = "INSERT INTO last_exchange_update (date, user_id) VALUES (:formattedDate, :userId)"; } - $apiData = json_decode($response, true); - - $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode]; - - if ($apiData !== null && isset($apiData['rates'])) { - foreach ($apiData['rates'] as $currencyCode => $rate) { - if ($currencyCode === $mainCurrencyCode) { - $exchangeRate = 1.0; - } else { - $exchangeRate = $rate / $mainCurrencyToEUR; - } - $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId"; - $updateStmt = $db->prepare($updateQuery); - $updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT); - $updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT); - $updateStmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $updateResult = $updateStmt->execute(); - } - $currentDate = new DateTime(); - $formattedDate = $currentDate->format('Y-m-d'); + $stmt = $db->prepare($query); + $stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT); + $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); + $resutl = $stmt->execute(); - $query = "SELECT * FROM last_exchange_update WHERE user_id = :userId"; - $stmt = $db->prepare($query); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $row = $result->fetchArray(SQLITE3_ASSOC); + $db->close(); + } + } + } +} - if ($row) { - $query = "UPDATE last_exchange_update SET date = :formattedDate WHERE user_id = :userId"; - } else { - $query = "INSERT INTO last_exchange_update (date, user_id) VALUES (:formattedDate, :userId)"; - } +$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']; - $stmt = $db->prepare($query); - $stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $resutl = $stmt->execute(); +function sanitizeFilename($filename) +{ + $filename = preg_replace("/[^a-zA-Z0-9\s]/", "", $filename); + $filename = str_replace(" ", "-", $filename); + $filename = str_replace(".", "", $filename); + return $filename; +} - $db->close(); - } - } - } - } +function validateFileExtension($fileExtension) +{ + $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'jtif', 'webp']; + return in_array($fileExtension, $allowedExtensions); +} - $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']; - - function sanitizeFilename($filename) { - $filename = preg_replace("/[^a-zA-Z0-9\s]/", "", $filename); - $filename = str_replace(" ", "-", $filename); - $filename = str_replace(".", "", $filename); - return $filename; - } +function resizeAndUploadAvatar($uploadedFile, $uploadDir, $name) +{ + $targetWidth = 80; + $targetHeight = 80; - function validateFileExtension($fileExtension) { - $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'jtif', 'webp']; - return in_array($fileExtension, $allowedExtensions); - } + $timestamp = time(); + $originalFileName = $uploadedFile['name']; + $fileExtension = strtolower(pathinfo($originalFileName, PATHINFO_EXTENSION)); + $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png'; + $fileName = $timestamp . '-avatars-' . sanitizeFilename($name) . '.' . $fileExtension; + $uploadFile = $uploadDir . $fileName; - function resizeAndUploadAvatar($uploadedFile, $uploadDir, $name) { - $targetWidth = 80; - $targetHeight = 80; - - $timestamp = time(); - $originalFileName = $uploadedFile['name']; - $fileExtension = strtolower(pathinfo($originalFileName, PATHINFO_EXTENSION)); - $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png'; - $fileName = $timestamp . '-avatars-' . sanitizeFilename($name) . '.' . $fileExtension; - $uploadFile = $uploadDir . $fileName; - - if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) { - $fileInfo = getimagesize($uploadFile); - - if ($fileInfo !== false) { - $width = $fileInfo[0]; - $height = $fileInfo[1]; - - // Load the image based on its format - if ($fileExtension === 'png') { - $image = imagecreatefrompng($uploadFile); - } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { - $image = imagecreatefromjpeg($uploadFile); - } elseif ($fileExtension === 'gif') { - $image = imagecreatefromgif($uploadFile); - } elseif ($fileExtension === 'webp') { - $image = imagecreatefromwebp($uploadFile); - } else { - // Handle other image formats as needed - return ""; - } - - // Enable alpha channel (transparency) for PNG images - if ($fileExtension === 'png') { - imagesavealpha($image, true); - } - - $newWidth = $width; - $newHeight = $height; - - if ($width > $targetWidth) { - $newWidth = $targetWidth; - $newHeight = ($targetWidth / $width) * $height; - } - - if ($newHeight > $targetHeight) { - $newWidth = ($targetHeight / $newHeight) * $newWidth; - $newHeight = $targetHeight; - } - - $resizedImage = imagecreatetruecolor($newWidth, $newHeight); - imagesavealpha($resizedImage, true); - $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127); - imagefill($resizedImage, 0, 0, $transparency); - imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); - - if ($fileExtension === 'png') { - imagepng($resizedImage, $uploadFile); - } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { - imagejpeg($resizedImage, $uploadFile); - } elseif ($fileExtension === 'gif') { - imagegif($resizedImage, $uploadFile); - } elseif ($fileExtension === 'webp') { - imagewebp($resizedImage, $uploadFile); - } else { - return ""; - } - - imagedestroy($image); - imagedestroy($resizedImage); - return "images/uploads/logos/avatars/".$fileName; + if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) { + $fileInfo = getimagesize($uploadFile); + + if ($fileInfo !== false) { + $width = $fileInfo[0]; + $height = $fileInfo[1]; + + // Load the image based on its format + if ($fileExtension === 'png') { + $image = imagecreatefrompng($uploadFile); + } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { + $image = imagecreatefromjpeg($uploadFile); + } elseif ($fileExtension === 'gif') { + $image = imagecreatefromgif($uploadFile); + } elseif ($fileExtension === 'webp') { + $image = imagecreatefromwebp($uploadFile); + } else { + // Handle other image formats as needed + return ""; } + + // Enable alpha channel (transparency) for PNG images + if ($fileExtension === 'png') { + imagesavealpha($image, true); + } + + $newWidth = $width; + $newHeight = $height; + + if ($width > $targetWidth) { + $newWidth = $targetWidth; + $newHeight = ($targetWidth / $width) * $height; + } + + if ($newHeight > $targetHeight) { + $newWidth = ($targetHeight / $newHeight) * $newWidth; + $newHeight = $targetHeight; + } + + $resizedImage = imagecreatetruecolor($newWidth, $newHeight); + imagesavealpha($resizedImage, true); + $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127); + imagefill($resizedImage, 0, 0, $transparency); + imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); + + if ($fileExtension === 'png') { + imagepng($resizedImage, $uploadFile); + } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') { + imagejpeg($resizedImage, $uploadFile); + } elseif ($fileExtension === 'gif') { + imagegif($resizedImage, $uploadFile); + } elseif ($fileExtension === 'webp') { + imagewebp($resizedImage, $uploadFile); + } else { + return ""; + } + + imagedestroy($image); + imagedestroy($resizedImage); + return "images/uploads/logos/avatars/" . $fileName; } - - return ""; } - if (isset($_SESSION['username']) && isset($_POST['email']) && $_POST['email'] !== "" - && isset($_POST['avatar']) && $_POST['avatar'] !== "" - && isset($_POST['main_currency']) && $_POST['main_currency'] !== "" - && isset($_POST['language']) && $_POST['language'] !== "") { - - $email = validate($_POST['email']); - - $query = "SELECT email FROM user WHERE id = :user_id"; + return ""; +} + +if ( + isset($_SESSION['username']) && isset($_POST['email']) && $_POST['email'] !== "" + && isset($_POST['avatar']) && $_POST['avatar'] !== "" + && isset($_POST['main_currency']) && $_POST['main_currency'] !== "" + && isset($_POST['language']) && $_POST['language'] !== "" +) { + + $email = validate($_POST['email']); + + $query = "SELECT email FROM user WHERE id = :user_id"; + $stmt = $db->prepare($query); + $stmt->bindValue(':user_id', $userId, SQLITE3_TEXT); + $result = $stmt->execute(); + $user = $result->fetchArray(SQLITE3_ASSOC); + + $oldEmail = $user['email']; + + if ($oldEmail != $email) { + $query = "SELECT email FROM user WHERE email = :email AND id != :userId"; $stmt = $db->prepare($query); - $stmt->bindValue(':user_id', $userId, SQLITE3_TEXT); + $stmt->bindValue(':email', $email, SQLITE3_TEXT); + $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); $result = $stmt->execute(); - $user = $result->fetchArray(SQLITE3_ASSOC); - - $oldEmail = $user['email']; + $otherUser = $result->fetchArray(SQLITE3_ASSOC); - if ($oldEmail != $email) { - $query = "SELECT email FROM user WHERE email = :email AND id != :userId"; - $stmt = $db->prepare($query); - $stmt->bindValue(':email', $email, SQLITE3_TEXT); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - $otherUser = $result->fetchArray(SQLITE3_ASSOC); - - if ($otherUser) { - $response = [ - "success" => false, - "errorMessage" => translate('email_exists', $i18n) - ]; - echo json_encode($response); - exit(); - } + if ($otherUser) { + $response = [ + "success" => false, + "errorMessage" => translate('email_exists', $i18n) + ]; + echo json_encode($response); + exit(); } + } - $avatar = $_POST['avatar']; - $main_currency = $_POST['main_currency']; - $language = $_POST['language']; + $avatar = $_POST['avatar']; + $main_currency = $_POST['main_currency']; + $language = $_POST['language']; - if (! empty($_FILES['profile_pic']["name"])) { - $file = $_FILES['profile_pic']; + if (!empty($_FILES['profile_pic']["name"])) { + $file = $_FILES['profile_pic']; - $fileType = mime_content_type($_FILES['profile_pic']['tmp_name']); - if (strpos($fileType, 'image') === false) { - $response = [ - "success" => false, - "errorMessage" => translate('fill_all_fields', $i18n) - ]; - echo json_encode($response); - exit(); - } - $name = $file['name']; - $avatar = resizeAndUploadAvatar($_FILES['profile_pic'], '../../images/uploads/logos/avatars/', $name); + $fileType = mime_content_type($_FILES['profile_pic']['tmp_name']); + if (strpos($fileType, 'image') === false) { + $response = [ + "success" => false, + "errorMessage" => translate('fill_all_fields', $i18n) + ]; + echo json_encode($response); + exit(); } + $name = $file['name']; + $avatar = resizeAndUploadAvatar($_FILES['profile_pic'], '../../images/uploads/logos/avatars/', $name); + } - if (isset($_POST['password']) && $_POST['password'] != "") { - $password = $_POST['password']; - if (isset($_POST['confirm_password'])) { - $confirm = $_POST['confirm_password']; - if ($password != $confirm) { - $response = [ - "success" => false, - "errorMessage" => translate('passwords_dont_match', $i18n) - ]; - echo json_encode($response); - exit(); - } - } else { + if (isset($_POST['password']) && $_POST['password'] != "") { + $password = $_POST['password']; + if (isset($_POST['confirm_password'])) { + $confirm = $_POST['confirm_password']; + if ($password != $confirm) { $response = [ "success" => false, "errorMessage" => translate('passwords_dont_match', $i18n) @@ -258,64 +256,72 @@ function resizeAndUploadAvatar($uploadedFile, $uploadDir, $name) { echo json_encode($response); exit(); } - } - - if (isset($_POST['password']) && $_POST['password'] != "") { - $sql = "UPDATE user SET avatar = :avatar, email = :email, password = :password, main_currency = :main_currency, language = :language WHERE id = :userId"; } else { - $sql = "UPDATE user SET avatar = :avatar, email = :email, main_currency = :main_currency, language = :language WHERE id = :userId"; - } - - $stmt = $db->prepare($sql); - $stmt->bindParam(':avatar', $avatar, SQLITE3_TEXT); - $stmt->bindParam(':email', $email, SQLITE3_TEXT); - $stmt->bindParam(':main_currency', $main_currency, SQLITE3_INTEGER); - $stmt->bindParam(':language', $language, SQLITE3_TEXT); - $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - - if (isset($_POST['password']) && $_POST['password'] != "") { - $hashedPassword = password_hash($password, PASSWORD_DEFAULT); - $stmt->bindParam(':password', $hashedPassword, SQLITE3_TEXT); + $response = [ + "success" => false, + "errorMessage" => translate('passwords_dont_match', $i18n) + ]; + echo json_encode($response); + exit(); } + } - $result = $stmt->execute(); + if (isset($_POST['password']) && $_POST['password'] != "") { + $sql = "UPDATE user SET avatar = :avatar, email = :email, password = :password, main_currency = :main_currency, language = :language WHERE id = :userId"; + } else { + $sql = "UPDATE user SET avatar = :avatar, email = :email, main_currency = :main_currency, language = :language WHERE id = :userId"; + } - if ($result) { - $cookieExpire = time() + (30 * 24 * 60 * 60); - $oldLanguage = isset($_COOKIE['language']) ? $_COOKIE['language'] : "en"; - $root = str_replace('/endpoints/user', '', dirname($_SERVER['PHP_SELF'])); - $root = $root == '' ? '/' : $root; - setcookie('language', $language, $cookieExpire, $root); - $_SESSION['avatar'] = $avatar; - $_SESSION['main_currency'] = $main_currency; - - if ($main_currency != $mainCurrencyId) { - update_exchange_rate($db); - } + $stmt = $db->prepare($sql); + $stmt->bindParam(':avatar', $avatar, SQLITE3_TEXT); + $stmt->bindParam(':email', $email, SQLITE3_TEXT); + $stmt->bindParam(':main_currency', $main_currency, SQLITE3_INTEGER); + $stmt->bindParam(':language', $language, SQLITE3_TEXT); + $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER); - $reload = $oldLanguage != $language; + if (isset($_POST['password']) && $_POST['password'] != "") { + $hashedPassword = password_hash($password, PASSWORD_DEFAULT); + $stmt->bindParam(':password', $hashedPassword, SQLITE3_TEXT); + } - $response = [ - "success" => true, - "message" => translate('user_details_saved', $i18n), - "reload" => $reload - ]; - echo json_encode($response); - } else { - $response = [ - "success" => false, - "errorMessage" => translate('error_updating_user_data', $i18n) - ]; - echo json_encode($response); + $result = $stmt->execute(); + + if ($result) { + $cookieExpire = time() + (30 * 24 * 60 * 60); + $oldLanguage = isset($_COOKIE['language']) ? $_COOKIE['language'] : "en"; + $root = str_replace('/endpoints/user', '', dirname($_SERVER['PHP_SELF'])); + $root = $root == '' ? '/' : $root; + setcookie('language', $language, $cookieExpire, $root); + $_SESSION['avatar'] = $avatar; + $_SESSION['main_currency'] = $main_currency; + + if ($main_currency != $mainCurrencyId) { + update_exchange_rate($db, $userId); } - exit(); + $reload = $oldLanguage != $language; + + $response = [ + "success" => true, + "message" => translate('user_details_saved', $i18n), + "reload" => $reload + ]; + echo json_encode($response); } else { $response = [ "success" => false, - "errorMessage" => translate('fill_all_fields', $i18n) + "errorMessage" => translate('error_updating_user_data', $i18n) ]; echo json_encode($response); - exit(); } -?> + + exit(); +} else { + $response = [ + "success" => false, + "errorMessage" => translate('fill_all_fields', $i18n) + ]; + echo json_encode($response); + exit(); +} +?> \ No newline at end of file diff --git a/includes/checksession.php b/includes/checksession.php index 9ceed0a57..8250bb522 100644 --- a/includes/checksession.php +++ b/includes/checksession.php @@ -1,90 +1,90 @@ prepare($sql); + $stmt->bindValue(':username', $username, SQLITE3_TEXT); + $result = $stmt->execute(); + $userData = $result->fetchArray(SQLITE3_ASSOC); + $userId = $userData['id']; + + if ($userData === false) { + header('Location: logout.php'); + exit(); + } else { + $_SESSION['userId'] = $userData['id']; + } + + if ($userData['avatar'] == "") { + $userData['avatar'] = "0"; + } +} else { + + if (isset($_COOKIE['wallos_login'])) { + $cookie = explode('|', $_COOKIE['wallos_login'], 3); + $username = $cookie[0]; + $token = $cookie[1]; + $main_currency = $cookie[2]; + $sql = "SELECT * FROM user WHERE username = :username"; $stmt = $db->prepare($sql); $stmt->bindValue(':username', $username, SQLITE3_TEXT); $result = $stmt->execute(); - $userData = $result->fetchArray(SQLITE3_ASSOC); - $userId = $userData['id']; - if ($userData === false) { - header('Location: logout.php'); - exit(); - } else { - $_SESSION['userId'] = $userData['id']; - } - - if ($userData['avatar'] == "") { - $userData['avatar'] = "0"; - } - } else { + if ($result) { + $userData = $result->fetchArray(SQLITE3_ASSOC); + if (!isset($userData['id'])) { + $db->close(); + header("Location: logout.php"); + exit(); + } - if (isset($_COOKIE['wallos_login'])) { - $cookie = explode('|', $_COOKIE['wallos_login'], 3); - $username = $cookie[0]; - $token = $cookie[1]; - $main_currency = $cookie[2]; + if ($userData['avatar'] == "") { + $userData['avatar'] = "0"; + } + $userId = $userData['id']; + $main_currency = $userData['main_currency']; - $sql = "SELECT * FROM user WHERE username = :username"; - $stmt = $db->prepare($sql); - $stmt->bindValue(':username', $username, SQLITE3_TEXT); + $adminQuery = "SELECT login_disabled FROM admin"; + $adminResult = $db->query($adminQuery); + $adminRow = $adminResult->fetchArray(SQLITE3_ASSOC); + if ($adminRow['login_disabled'] == 1) { + $sql = "SELECT * FROM login_tokens WHERE user_id = :userId"; + $stmt = $db->prepare($sql); + $stmt->bindParam(':userId', $userId, SQLITE3_TEXT); + } else { + $sql = "SELECT * FROM login_tokens WHERE user_id = :userId AND token = :token"; + $stmt = $db->prepare($sql); + $stmt->bindParam(':userId', $userId, SQLITE3_TEXT); + $stmt->bindParam(':token', $token, SQLITE3_TEXT); + } $result = $stmt->execute(); - - if ($result) { - $userData = $result->fetchArray(SQLITE3_ASSOC); - if (!isset($userData['id'])) { - $db->close(); - header("Location: logout.php"); - exit(); - } + $row = $result->fetchArray(SQLITE3_ASSOC); - if ($userData['avatar'] == "") { - $userData['avatar'] = "0"; - } - $userId = $userData['id']; - $main_currency = $userData['main_currency']; - - $adminQuery = "SELECT login_disabled FROM admin"; - $adminResult = $db->query($adminQuery); - $adminRow = $adminResult->fetchArray(SQLITE3_ASSOC); - if ($adminRow['login_disabled'] == 1) { - $sql = "SELECT * FROM login_tokens WHERE user_id = :userId"; - $stmt = $db->prepare($sql); - $stmt->bindParam(':userId', $userId, SQLITE3_TEXT); - } else { - $sql = "SELECT * FROM login_tokens WHERE user_id = :userId AND token = :token"; - $stmt = $db->prepare($sql); - $stmt->bindParam(':userId', $userId, SQLITE3_TEXT); - $stmt->bindParam(':token', $token, SQLITE3_TEXT); - } - $result = $stmt->execute(); - $row = $result->fetchArray(SQLITE3_ASSOC); - - if ($row != false) { - $_SESSION['username'] = $username; - $_SESSION['token'] = $token; - $_SESSION['loggedin'] = true; - $_SESSION['main_currency'] = $main_currency; - $_SESSION['userId'] = $userId; - } else { - $db->close(); - header("Location: logout.php"); - exit(); - } + if ($row != false) { + $_SESSION['username'] = $username; + $_SESSION['token'] = $token; + $_SESSION['loggedin'] = true; + $_SESSION['main_currency'] = $main_currency; + $_SESSION['userId'] = $userId; } else { $db->close(); header("Location: logout.php"); exit(); } - - } else { $db->close(); - header("Location: login.php"); + header("Location: logout.php"); exit(); } + + + } else { + $db->close(); + header("Location: login.php"); + exit(); } +} ?> \ No newline at end of file diff --git a/includes/checkuser.php b/includes/checkuser.php index d0a5d374a..c2f086ce6 100644 --- a/includes/checkuser.php +++ b/includes/checkuser.php @@ -1,6 +1,6 @@ query($query); - $row = $result->fetchArray(SQLITE3_ASSOC); - $userCount = $row['count']; +$query = "SELECT COUNT(*) as count FROM user"; +$result = $db->query($query); +$row = $result->fetchArray(SQLITE3_ASSOC); +$userCount = $row['count']; ?> \ No newline at end of file diff --git a/includes/footer.php b/includes/footer.php index 55c8038a0..0ef9f170a 100644 --- a/includes/footer.php +++ b/includes/footer.php @@ -25,10 +25,11 @@ close(); - } + if (isset($db)) { + $db->close(); + } ?> - + + \ No newline at end of file diff --git a/includes/getsettings.php b/includes/getsettings.php index 135c7433a..da531002b 100644 --- a/includes/getsettings.php +++ b/includes/getsettings.php @@ -8,8 +8,20 @@ $settings = $result->fetchArray(SQLITE3_ASSOC); if ($settings) { $cookieExpire = time() + (30 * 24 * 60 * 60); - setcookie('theme', $settings['dark_theme'] ? 'dark': 'light', $cookieExpire); - $settings['theme'] = $settings['dark_theme'] ? 'dark': 'light'; + $themeMapping = array(0 => 'light', 1 => 'dark', 2 => 'automatic'); + $themeKey = isset($settings['dark_theme']) ? $settings['dark_theme'] : 2; + $themeValue = $themeMapping[$themeKey]; + setcookie('theme', $themeValue, $cookieExpire); + $settings['update_theme_setttings'] = false; + if (isset($_COOKIE['inUseTheme']) && $settings['dark_theme'] == 2) { + $inUseTheme = $_COOKIE['inUseTheme']; + $settings['theme'] = $inUseTheme; + } else { + $settings['theme'] = $themeValue; + } + if ($themeValue == "automatic") { + $settings['update_theme_setttings'] = true; + } $settings['color_theme'] = $settings['color_theme'] ? $settings['color_theme'] : "blue"; $settings['showMonthlyPrice'] = $settings['monthly_price'] ? 'true': 'false'; $settings['convertCurrency'] = $settings['convert_currency'] ? 'true': 'false'; diff --git a/includes/header.php b/includes/header.php index e066be983..9dc6d15d0 100644 --- a/includes/header.php +++ b/includes/header.php @@ -18,11 +18,16 @@ exit(); } - $theme = "light"; + $theme = "automatic"; if (isset($settings['theme'])) { $theme = $settings['theme']; } + $updateThemeSettings = false; + if (isset($settings['update_theme_setttings'])) { + $updateThemeSettings = $settings['update_theme_setttings']; + } + $colorTheme = "blue"; if (isset($settings['color_theme'])) { $colorTheme = $settings['color_theme']; @@ -37,13 +42,13 @@ Wallos - Subscription Tracker - "/> + " id="theme-color"/> - > + > > > > @@ -54,6 +59,7 @@ diff --git a/includes/i18n/de.php b/includes/i18n/de.php index 4260256db..74ae898dd 100644 --- a/includes/i18n/de.php +++ b/includes/i18n/de.php @@ -77,8 +77,6 @@ "payment_every" => "Zahlung alle", "frequency" => "Abrechnungsfrequenz", "cycle" => "Zeitraum", - "next_payment" => "Nächste Zahlung", - "payment_method" => "Zahlungsmethode", "no_category" => "Keine Kategorie", "paid_by" => "Gezahlt durch", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Themen-Einstellungen", "custom_colors" => "Benutzerdefinierte Farben", "dark_theme" => "Dark Theme", - "switch_theme" => "Light / Dark Theme umschalten", + "automatic"=> "Automatisch", "calculate_monthly_price" => "Berechne und zeige monatlichen Preis für alle Abonnements an", "convert_prices" => "Preise immer in meine Hauptwährung umrechnen und darin anzeigen (langsamer)", "hide_disabled_subscriptions" => "Deaktivierte Abonnements verstecken", diff --git a/includes/i18n/el.php b/includes/i18n/el.php index f2b241455..d668c9907 100644 --- a/includes/i18n/el.php +++ b/includes/i18n/el.php @@ -77,8 +77,6 @@ "payment_every" => "Πληρωμή κάθε", "frequency" => "Συχνότητα", "cycle" => "Κύκλος", - "next_payment" => "Επόμενη πληρωμή", - "payment_method" => "Τρόπος πληρωμής", "no_category" => "Καμία κατηγορία", "paid_by" => "Πληρώνεται από", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Ρυθμίσεις θέματος", "custom_colors" => "Προσαρμοσμένα χρώματα", "dark_theme" => "Dark Theme", - "switch_theme" => "Διακόπτης Light / Dark Theme", + "automatic"=> "Αυτόματο", "calculate_monthly_price" => "Υπολογισμός και εμφάνιση της μηνιαίας τιμής για όλες τις συνδρομές", "convert_prices" => "Πάντα να μετατρέπει και να εμφανίζει τις τιμές στο κύριο νόμισμά μου (πιο αργό)", "hide_disabled_subscriptions" => "Απόκρυψη απενεργοποιημένων συνδρομών", diff --git a/includes/i18n/en.php b/includes/i18n/en.php index e2e491443..9963bde4b 100644 --- a/includes/i18n/en.php +++ b/includes/i18n/en.php @@ -77,8 +77,6 @@ "payment_every" => "Payment every", "frequency" => "Frequency", "cycle" => "Cycle", - "next_payment" => "Next Payment", - "payment_method" => "Payment Method", "no_category" => "No category", "paid_by" => "Paid by", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Theme Settings", "custom_colors" => "Custom Colors", "dark_theme" => "Dark Theme", - "switch_theme" => "Switch Light / Dark Theme", + "automatic"=> "Automatic", "calculate_monthly_price" => "Calculate and show monthly price for all subscriptions", "convert_prices" => "Always convert and show prices on my main currency (slower)", "hide_disabled_subscriptions" => "Hide disabled subscriptions", diff --git a/includes/i18n/es.php b/includes/i18n/es.php index 0c631b390..d1b51296f 100644 --- a/includes/i18n/es.php +++ b/includes/i18n/es.php @@ -77,8 +77,6 @@ "payment_every" => "Pago cada", "frequency" => "Frecuencia", "cycle" => "Ciclo", - "next_payment" => "Próximo Pago", - "payment_method" => "Método de Pago", "no_category" => "Sin categoría", "paid_by" => "Pagado por", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Configuración de Tema", "custom_collors" => "Colores Personalizados", "dark_theme" => "Tema Oscuro", - "switch_theme" => "Cambiar entre Tema Claro / Oscuro", + "automatic"=> "Automático", "calculate_monthly_price" => "Calcular y mostrar el precio mensual de todas las suscripciones", "convert_prices" => "Convertir y mostrar siempre los precios en mi moneda principal (más lento)", "hide_disabled_subscriptions" => "Ocultar suscripciones desactivadas", diff --git a/includes/i18n/fr.php b/includes/i18n/fr.php index 027ef90ce..0aa42c8df 100644 --- a/includes/i18n/fr.php +++ b/includes/i18n/fr.php @@ -77,8 +77,6 @@ "payment_every" => "Paiement tous les", "frequency" => "Fréquence", "cycle" => "Cycle", - "next_payment" => "Prochain paiement", - "payment_method" => "Méthode de paiement", "no_category" => "Pas de catégorie", "paid_by" => "Payé par", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Paramètres de thème", "custom_colors" => "Couleurs personnalisées", "dark_theme" => "Thème sombre", - "switch_theme" => "Basculer entre le thème clair et sombre", + "automatic"=> "Automatique", "calculate_monthly_price" => "Calculer et afficher le prix mensuel pour tous les abonnements", "convert_prices" => "Convertir toujours et afficher les prix dans ma devise principale (plus lent)", "hide_disabled_subscriptions" => "Masquer les abonnements désactivés", diff --git a/includes/i18n/getlang.php b/includes/i18n/getlang.php index b615d1cd5..a80f93eef 100644 --- a/includes/i18n/getlang.php +++ b/includes/i18n/getlang.php @@ -9,7 +9,8 @@ } } -function translate($text, $translations) { +function translate($text, $translations) +{ if (array_key_exists($text, $translations)) { return $translations[$text]; } else { diff --git a/includes/i18n/it.php b/includes/i18n/it.php index 269257628..3cc255480 100644 --- a/includes/i18n/it.php +++ b/includes/i18n/it.php @@ -186,7 +186,7 @@ "theme_settings" => 'Impostazioni del tema', "custom_colors" => 'Colori personalizzati', "dark_theme" => 'Tema scuro', - 'switch_theme' => 'Cambia tema chiaro/scuro', + "automatic" => "Automatico", 'calculate_monthly_price' => 'Calcola e mostra il prezzo mensile per tutti gli abbonamenti', 'convert_prices' => 'Converti sempre e mostra i prezzi nella mia valuta principale (più lento)', "hide_disabled_subscriptions" => 'Nascondi gli abbonamenti disattivati', diff --git a/includes/i18n/jp.php b/includes/i18n/jp.php index 1f7a6af87..fb6dfa677 100644 --- a/includes/i18n/jp.php +++ b/includes/i18n/jp.php @@ -77,8 +77,6 @@ "payment_every" => "支払い頻度", "frequency" => "頻度", "cycle" => "サイクル", - "next_payment" => "次回支払い", - "payment_method" => "支払い方法", "no_category" => "カテゴリなし", "paid_by" => "支払い元", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "テーマ設定", "custom_colors" => "カスタムカラー", "dark_theme" => "ダークテーマ", - "switch_theme" => "ライト/ダーク テーマの切り替え", + "automatic"=> "自動", "calculate_monthly_price" => "すべての定期購入の月額料金を計算して表示する", "convert_prices" => "常にメイン通貨で価格を換算して表示する (遅い)", "hide_disabled_subscriptions" => "無効な定期購入を非表示にする", diff --git a/includes/i18n/ko.php b/includes/i18n/ko.php index 63a7fbb63..20a0de05a 100644 --- a/includes/i18n/ko.php +++ b/includes/i18n/ko.php @@ -77,8 +77,6 @@ "payment_every" => "지불 빈도", "frequency" => "빈도", "cycle" => "주기", - "next_payment" => "다음 결제", - "payment_method" => "결제 방법", "no_category" => "카테고리 없음", "paid_by" => "결제하는 사람", "url" => "URL", @@ -181,7 +179,7 @@ "theme_settings" => "테마 설정", "custom_colors" => "커스텀 색상", "dark_theme" => "다크 테마", - "switch_theme" => "라이트/다크 테마 전환", + "automatic"=> "자동", "calculate_monthly_price" => "모든 구독에 대한 월별 요금을 계산하고 표시", "convert_prices" => "항상 기본 통화로 가격을 환산하고 표시 (느림)", "hide_disabled_subscriptions" => "비활성화된 구독 숨기기", diff --git a/includes/i18n/languages.php b/includes/i18n/languages.php index dcb1e4f07..f2f1ef1d2 100644 --- a/includes/i18n/languages.php +++ b/includes/i18n/languages.php @@ -1,26 +1,26 @@ Language Name - $languages = [ - // English first - "en" => ["name" => "English", "dir" => "ltr"], - // Remaining sorted alphabetically by language code - "de" => ["name" => "Deutsch", "dir" => "ltr"], - "el" => ["name" => "Ελληνικά", "dir" => "ltr"], - "es" => ["name" => "Español", "dir" => "ltr"], - "fr" => ["name" => "Français", "dir" => "ltr"], - "it" => ["name" => "Italiano", "dir" => "ltr"], - "jp" => ["name" => "日本語", "dir" => "ltr"], - "ko" => ["name" => "한국어", "dir" => "ltr"], - "pl" => ["name" => "Polski", "dir" => "ltr"], - "pt" => ["name" => "Português", "dir" => "ltr"], - "pt_br" => ["name" => "Português Brasileiro", "dir" => "ltr"], - "ru" => ["name" => "Русский", "dir" => "ltr"], - "sl" => ["name" => "Slovenščina", "dir" => "ltr"], - "sr_lat" => ["name" => "Srpski", "dir" => "ltr"], - "sr" => ["name" => "Српски", "dir" => "ltr"], - "tr" => ["name" => "Türkçe", "dir" => "ltr"], - "zh_cn" => ["name" => "简体中文", "dir" => "ltr"], - "zh_tw" => ["name" => "繁體中文", "dir" => "ltr"], - ] - -?> \ No newline at end of file +// File Name => Language Name +$languages = [ + // English first + "en" => ["name" => "English", "dir" => "ltr"], + // Remaining sorted alphabetically by language code + "de" => ["name" => "Deutsch", "dir" => "ltr"], + "el" => ["name" => "Ελληνικά", "dir" => "ltr"], + "es" => ["name" => "Español", "dir" => "ltr"], + "fr" => ["name" => "Français", "dir" => "ltr"], + "it" => ["name" => "Italiano", "dir" => "ltr"], + "jp" => ["name" => "日本語", "dir" => "ltr"], + "ko" => ["name" => "한국어", "dir" => "ltr"], + "pl" => ["name" => "Polski", "dir" => "ltr"], + "pt" => ["name" => "Português", "dir" => "ltr"], + "pt_br" => ["name" => "Português Brasileiro", "dir" => "ltr"], + "ru" => ["name" => "Русский", "dir" => "ltr"], + "sl" => ["name" => "Slovenščina", "dir" => "ltr"], + "sr_lat" => ["name" => "Srpski", "dir" => "ltr"], + "sr" => ["name" => "Српски", "dir" => "ltr"], + "tr" => ["name" => "Türkçe", "dir" => "ltr"], + "zh_cn" => ["name" => "简体中文", "dir" => "ltr"], + "zh_tw" => ["name" => "繁體中文", "dir" => "ltr"], +] + + ?> \ No newline at end of file diff --git a/includes/i18n/pl.php b/includes/i18n/pl.php index 48e24fd78..997aae0c5 100644 --- a/includes/i18n/pl.php +++ b/includes/i18n/pl.php @@ -77,8 +77,6 @@ "payment_every" => "Płatność co", "frequency" => "Częstotliwość", "cycle" => "Cykl", - "next_payment" => "Następna płatność", - "payment_method" => "Metoda płatności", "no_category" => "Brak kategorii", "paid_by" => "Zapłacone przez", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Ustawienia motywu", "custom_colors" => "Kolory niestandardowe", "dark_theme" => "Przełącz na jasny/ciemny motyw", - "switch_theme" => "Przełącz na jasny/ciemny motyw", + "automatic"=> "Automatycznie", "calculate_monthly_price" => "Oblicz i pokaż miesięczną cenę wszystkich subskrypcji", "convert_prices" => "Zawsze przeliczaj i pokazuj ceny w mojej głównej walucie (wolniej)", "hide_disabled_subscriptions" => "Ukryj wyłączone subskrypcje", diff --git a/includes/i18n/pt.php b/includes/i18n/pt.php index 0c61571bf..72b1f8e04 100644 --- a/includes/i18n/pt.php +++ b/includes/i18n/pt.php @@ -77,8 +77,6 @@ "payment_every" => "Pagamento a cada", "frequency" => "Frequencia", "Cycle" => "Ciclo", - "next_payment" => "Próximo Pagamento", - "payment_method" => "Método de Pagamento", "no_category" => "Sem categoria", "paid_by" => "Pago por", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Definições de Tema", "custom_colors" => "Cores Personalizadas", "dark_theme" => "Tema Escuro", - "switch_theme" => "Trocar Tema Claro / Escuro", + "automatic"=> "Automático", "calculate_monthly_price" => "Calcular e mostrar preço mensal para todas as subscrições", "convert_prices" => "Converter e mostrar todas as subscrições na moeda principal (mais lento)", "hide_disabled_subscriptions" => "Esconder subscrições desactivadas", diff --git a/includes/i18n/pt_br.php b/includes/i18n/pt_br.php index 81f9df07f..0c8cc5ee5 100644 --- a/includes/i18n/pt_br.php +++ b/includes/i18n/pt_br.php @@ -178,7 +178,7 @@ "theme_settings" => "Configurações de tema", "custom_colors" => "Cores personalizadas", "dark_theme" => "Tema Escuro", - "switch_theme" => "Alternar entre tema Claro / Escuro", + "automatic" => "Automático", "calculate_monthly_price" => "Calcular e exibir o custo mensal para todas as assinaturas", "convert_prices" => "Sempre converter e exibir preços na moeda principal (mais lento)", "hide_disabled_subscriptions" => "Ocultar assinaturas desativadas", diff --git a/includes/i18n/ru.php b/includes/i18n/ru.php index 07430c6f6..1d612450f 100644 --- a/includes/i18n/ru.php +++ b/includes/i18n/ru.php @@ -77,8 +77,6 @@ "payment_every" => "Оплата каждые", "frequency" => "Частота", "cycle" => "Цикл", - "next_payment" => "Следующий платеж", - "payment_method" => "Способ оплаты", "no_category" => "Нет категории", "paid_by" => "Оплачивает", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Настройки темы", "custom_colors" => "Пользовательские цвета", "dark_theme" => "Темная тема", - "switch_theme" => "Переключить светлую/темную тему", + "automatic"=> "Автоматически", "calculate_monthly_price" => "Рассчитать и показать ежемесячную цену для всех подписок", "convert_prices" => "Всегда конвертировать и показывать цены в моей основной валюте (медленнее)", "hide_disabled_subscriptions" => "Скрыть отключенные подписки", diff --git a/includes/i18n/sl.php b/includes/i18n/sl.php index 4ccf82560..d3f367ad3 100644 --- a/includes/i18n/sl.php +++ b/includes/i18n/sl.php @@ -77,8 +77,6 @@ "payment_every" => "Plačilo vsakih", "frequency" => "Ponavljanje", "cycle" => "cikel", - "next_payment" => "Naslednje plačilo", - "payment_method" => "Način plačila", "no_category" => "Brez kategorije", "paid_by" => "Plačal", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Nastavitve teme", "custom_colors" => "Barve po meri", "dark_theme" => "Temna tema", - "switch_theme" => "Preklop med svetlo/temno temo", + "automatic"=> "Samodejno", "calculate_monthly_price" => "Izračunaj in prikaži mesečno ceno za vse naročnine", "convert_prices" => "Vedno pretvori in prikaži cene v moji glavni valuti (počasneje)", "hide_disabled_subscriptions" => "Skrij onemogočene naročnine", diff --git a/includes/i18n/sr.php b/includes/i18n/sr.php index 5a3e029fc..d892c489e 100644 --- a/includes/i18n/sr.php +++ b/includes/i18n/sr.php @@ -77,8 +77,6 @@ "payment_every" => "Плаћање сваког", "frequency" => "Фреквенција", "cycle" => "Циклус", - "next_payment" => "Следећа уплата", - "payment_method" => "Начин плаћања", "no_category" => "Без категорије", "paid_by" => "Плаћено од", "url" => "URL", @@ -179,7 +177,7 @@ "theme_settings" => "Подешавања теме", "custom_colors" => "Прилагођене боје", "dark_theme" => "Тамна тема", - "switch_theme" => "Промени светлу / тамну тему", + "automatic"=> "Аутоматски", "calculate_monthly_price" => "Израчунајте и прикажите месечну цену за све претплате", "convert_prices" => "Увек конвертујте и прикажите цене на мојој главној валути (спорије)", "hide_disabled_subscriptions" => "Сакриј онемогућене претплате", diff --git a/includes/i18n/sr_lat.php b/includes/i18n/sr_lat.php index c44ac2537..f27495e66 100644 --- a/includes/i18n/sr_lat.php +++ b/includes/i18n/sr_lat.php @@ -77,8 +77,6 @@ "payment_every" => "Plaćanje svakog", "frequency" => "Frekvencija", "cycle" => "Ciklus", - "next_payment" => "Sledeća uplata", - "payment_method" => "Način plaćanja", "no_category" => "Bez kategorije", "paid_by" => "Plaćeno od strane", "url" => "URL", @@ -180,7 +178,7 @@ "theme_settings" => "Podešavanja teme", "custom_colors" => "Prilagođene boje", "dark_theme" => "Tamna tema", - "switch_theme" => "Promeni svetli / tamni temu", + "automatic"=> "Automatski", "calculate_monthly_price" => "Izračunaj i prikaži mesečnu cenu za sve pretplate", "convert_prices" => "Uvek konvertuj i prikaži cene u mojoj glavnoj valuti (sporije)", "hide_disabled_subscriptions" => "Sakrij onemogućene pretplate", diff --git a/includes/i18n/tr.php b/includes/i18n/tr.php index 2a73f7f3b..a7e7cda26 100644 --- a/includes/i18n/tr.php +++ b/includes/i18n/tr.php @@ -77,8 +77,6 @@ "payment_every" => "Ödeme Sıklığı", "frequency" => "Frekans", "cycle" => "Döngü", - "next_payment" => "Sonraki Ödeme", - "payment_method" => "Ödeme Yöntemi", "no_category" => "Kategori yok", "paid_by" => "Ödeyen", "url" => "URL", @@ -181,6 +179,7 @@ "custom_colors" => "Özel Renkler", "dark_theme" => "Koyu Temayı", "switch_theme" => "Açık / Koyu Temayı Değiştir", + "automatic"=> "Otomatik", "calculate_monthly_price" => "Tüm aboneliklerin aylık fiyatını hesaplayın ve gösterin", "convert_prices" => "Fiyatları her zaman ana para birimimde dönüştürün ve gösterin (daha yavaş)", "hide_disabled_subscriptions" => "Devre dışı bırakılan abonelikleri gizle", diff --git a/includes/i18n/zh_cn.php b/includes/i18n/zh_cn.php index c3b11f8a8..cbbd8d151 100644 --- a/includes/i18n/zh_cn.php +++ b/includes/i18n/zh_cn.php @@ -82,8 +82,6 @@ "payment_every" => "支付频率", "frequency" => "频率", "cycle" => "周期", - "next_payment" => "下次支付", - "payment_method" => "支付方式", "no_category" => "无分类", "paid_by" => "付款人", "url" => "链接", @@ -188,7 +186,7 @@ "theme_settings" => "主题设置", "custom_colors" => "自定义颜色", "dark_theme" => "深色主题", - "switch_theme" => "切换浅色/深色主题", + "automatic"=> "自动", "calculate_monthly_price" => "计算并显示所有订阅的月价格", "convert_prices" => "始终按我的主要货币转换和显示价格(较慢)", "hide_disabled_subscriptions" => "隐藏已停用的订阅", diff --git a/includes/i18n/zh_tw.php b/includes/i18n/zh_tw.php index a85f71a80..3e2d8aa87 100644 --- a/includes/i18n/zh_tw.php +++ b/includes/i18n/zh_tw.php @@ -77,8 +77,6 @@ "payment_every" => "付款頻率", "frequency" => "頻率", "cycle" => "週期", - "next_payment" => "下次付款", - "payment_method" => "付款方式", "no_category" => "無分類", "paid_by" => "付款人", "url" => "連結", @@ -180,7 +178,7 @@ "theme_settings" => "主題設定", "custom_colors" => "自訂顏色", "dark_theme" => "深色主題", - "switch_theme" => "切換淺色/深色主題", + "automatic"=> "自動", "calculate_monthly_price" => "計算並顯示所有訂閱的每月價格", "convert_prices" => "始終按照我的主要貨幣單位轉換和顯示價格(較慢)", "hide_disabled_subscriptions" => "隱藏已停用的訂閱", diff --git a/includes/inputvalidation.php b/includes/inputvalidation.php index f3d8d0100..fdd1c850f 100644 --- a/includes/inputvalidation.php +++ b/includes/inputvalidation.php @@ -1,6 +1,7 @@ +$version = "v2.8.0"; +?> \ No newline at end of file diff --git a/index.php b/index.php index 429ca24d9..b93247a39 100644 --- a/index.php +++ b/index.php @@ -1,372 +1,392 @@ prepare($sql); - $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); - $result = $stmt->execute(); - if ($result) { - $subscriptions = array(); - while ($row = $result->fetchArray(SQLITE3_ASSOC)) { - $subscriptions[] = $row; - } + if (in_array($sort, $allowedSortCriteria)) { + $sql = "SELECT * FROM subscriptions WHERE user_id = :userId ORDER BY $sort $order, inactive ASC"; + } +} + +$stmt = $db->prepare($sql); +$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER); +$result = $stmt->execute(); +if ($result) { + $subscriptions = array(); + while ($row = $result->fetchArray(SQLITE3_ASSOC)) { + $subscriptions[] = $row; } +} - $headerClass = count($subscriptions) > 0 ? "main-actions" : "main-actions hidden"; - $defaultLogo = $theme == "light" ? "images/siteicons/" . $colorTheme . "/wallos.png" : "images/siteicons/" . $colorTheme . "/walloswhite.png"; +$headerClass = count($subscriptions) > 0 ? "main-actions" : "main-actions hidden"; +$defaultLogo = $theme == "light" ? "images/siteicons/" . $colorTheme . "/wallos.png" : "images/siteicons/" . $colorTheme . "/walloswhite.png"; ?> - -
-
- -
- + +
+
+ +
+ -
- -
- 1) { - ?> -
-
-
- -
- +
+ +
+ 1) { + ?> +
+
+
+ +
-
- - 1) { - ?> -
-
-
- -
- -
-
- +
+
+ + 1) { + ?> +
+
+
+ +
+
+ - 1) { - ?> -
-
-
- -
- -
-
- +
+
+ + 1) { + ?> +
+
+
+ +
+
+ -
-
- -
+ ?>
-
- -
- -
-
    -
  • onClick="setSortOption('name')" id="sort-name">
  • -
  • onClick="setSortOption('id')" id="sort-id">
  • -
  • onClick="setSortOption('price')" id="sort-price">
  • -
  • onClick="setSortOption('next_payment')" id="sort-next_payment">
  • -
  • onClick="setSortOption('payer_user_id')" id="sort-payer_user_id">
  • -
  • onClick="setSortOption('category_id')" id="sort-category_id">
  • -
  • onClick="setSortOption('payment_method_id')" id="sort-payment_method_id">
  • -
+ +
+
+
-
-
- - if (isset($settings['convertCurrency']) && $settings['convertCurrency'] === 'true' && $currencyId != $mainCurrencyId) { - $print[$id]['price'] = getPriceConverted($print[$id]['price'], $currencyId, $db); - $print[$id]['currency_code'] = $currencies[$mainCurrencyId]['code']; - } - if (isset($settings['showMonthlyPrice']) && $settings['showMonthlyPrice'] === 'true') { - $print[$id]['price'] = getPricePerMonth($cycle, $frequency, $print[$id]['price']); - } - } +
+ +
+
    +
  • onClick="setSortOption('name')" id="sort-name"> +
  • +
  • onClick="setSortOption('id')" id="sort-id"> +
  • +
  • onClick="setSortOption('price')" id="sort-price"> +
  • +
  • onClick="setSortOption('next_payment')" + id="sort-next_payment">
  • +
  • onClick="setSortOption('payer_user_id')" + id="sort-payer_user_id">
  • +
  • onClick="setSortOption('category_id')" + id="sort-category_id">
  • +
  • onClick="setSortOption('payment_method_id')" + id="sort-payment_method_id">
  • +
+
+
+
+
+
+ close(); + if (isset($settings['convertCurrency']) && $settings['convertCurrency'] === 'true' && $currencyId != $mainCurrencyId) { + $print[$id]['price'] = getPriceConverted($print[$id]['price'], $currencyId, $db); + $print[$id]['currency_code'] = $currencies[$mainCurrencyId]['code']; + } + if (isset($settings['showMonthlyPrice']) && $settings['showMonthlyPrice'] === 'true') { + $print[$id]['price'] = getPricePerMonth($cycle, $frequency, $print[$id]['price']); + } + } + + if (isset($print)) { + printSubscriptions($print, $sort, $categories, $members, $i18n, $colorTheme); + } + $db->close(); - if (count($subscriptions) == 0) { + if (count($subscriptions) == 0) { + ?> +
+ <?= translate('empty_page', $i18n) ?> +

+ +

+ +
+ +
+ +
+
+

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

- -
- - -
- - - - -
- -
- - -
- -
- - -
- -
+
+
+
+
-
- -
- + - -
-
-
- - -
+ } + ?> +
- -
- - +
+ +
+
+
-
- - -
+
+ + +
-
- - -
+
+ + +
-
- - -
- +
+ + +
-
- - -
+
+ + +
-
- -
-
- -
+
+ + +
-
- - -
+
+ +
-
- - - -
- -
-
- +
+ +
+ +
+ + +
+ +
+ + + +
+ +
+ + +require_once 'includes/footer.php'; +?> \ No newline at end of file diff --git a/login.php b/login.php index 501a9c1cf..e20898d6b 100644 --- a/login.php +++ b/login.php @@ -18,14 +18,14 @@ $db->close(); header("Location: ."); exit(); -} +} // Check if login is disabled $adminQuery = "SELECT login_disabled FROM admin"; $adminResult = $db->query($adminQuery); $adminRow = $adminResult->fetchArray(SQLITE3_ASSOC); if ($adminRow['login_disabled'] == 1) { - + $query = "SELECT id, username, main_currency, language FROM user WHERE id = :id"; $stmt = $db->prepare($query); $stmt->bindValue(':id', 1, SQLITE3_INTEGER); @@ -57,7 +57,7 @@ $stmt = $db->prepare($query); $result = $stmt->execute(); $settings = $result->fetchArray(SQLITE3_ASSOC); - setcookie('colorTheme', $settings['color_theme'], $cookieExpire); + setcookie('colorTheme', $settings['color_theme'], $cookieExpire); $cookieValue = $username . "|" . "abc123ABC" . "|" . $main_currency; setcookie('wallos_login', $cookieValue, $cookieExpire); @@ -69,8 +69,11 @@ $theme = "light"; +$updateThemeSettings = false; if (isset($_COOKIE['theme'])) { $theme = $_COOKIE['theme']; +} else { + $updateThemeSettings = true; } $colorTheme = "blue"; @@ -123,7 +126,7 @@ $result = $stmt->execute(); $settings = $result->fetchArray(SQLITE3_ASSOC); setcookie('colorTheme', $settings['color_theme'], $cookieExpire); - + $token = bin2hex(random_bytes(32)); $addLoginTokens = "INSERT INTO login_tokens (user_id, token) VALUES (:userId, :token)"; $addLoginTokensStmt = $db->prepare($addLoginTokens); @@ -138,7 +141,7 @@ header("Location: ."); exit(); } - + } else { $loginFailed = true; } @@ -175,10 +178,11 @@ ?> + - "/> + " id="theme-color" /> Wallos - Subscription Tracker @@ -191,17 +195,25 @@ > + + +
- Wallos Logo Wallos Logo

@@ -224,62 +236,65 @@

-