Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
feat: add OIDC_REQUIRE_EMAIL_VERIFIED environment variable and SSRF_ALLOWLIST environment variable
Miguel Ribeiroaff3ed06b154
diff --git a/admin.php b/admin.phpindex 46e5137..4724f9b 100644--- a/admin.php+++ b/admin.php@@ -398,7 +398,7 @@ $loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0;// find unused upload logos// Get all logos in the subscriptions table- $query = 'SELECT logo FROM subscriptions';+ $query = 'SELECT logo, logo_variant FROM subscriptions';$stmt = $db->prepare($query);$result = $stmt->execute();@@ -406,6 +406,7 @@ $loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0;$logosOnDB = [];while ($row = $result->fetchArray(SQLITE3_ASSOC)) {$logosOnDB[] = $row['logo'];+ $logosOnDB[] = $row['logo_variant'];}// Get all logos in the payment_methods tablediff --git a/api/admin/set_admin_settings.php b/api/admin/set_admin_settings.phpindex 9215f18..d4cf165 100644--- a/api/admin/set_admin_settings.php+++ b/api/admin/set_admin_settings.php@@ -33,6 +33,7 @@ Example response:require_once '../../includes/connect_endpoint.php';require_once '../../includes/ssrf_helper.php';+require_once '../../includes/oidc_settings.php';header('Content-Type: application/json; charset=UTF-8');@@ -185,6 +186,10 @@ if (wallos_get_effective_ssrf_allowlist($db)['is_managed']) {unset($columnsMap['local_webhook_notifications_allowlist']);}+if (isset(wallos_get_effective_oidc_configuration($db)['managed_fields']['enabled'])) {+ unset($columnsMap['oidc_oauth_enabled']);+}+foreach ($columnsMap as $postKey => $dataType) {if (isset($_POST[$postKey])) {$fields[] = "$postKey = :$postKey";diff --git a/docker-compose.yaml b/docker-compose.yamlindex 092d555..aa6659f 100644--- a/docker-compose.yaml+++ b/docker-compose.yaml@@ -23,6 +23,8 @@ services:# OIDC_AUTO_CREATE_USER: "true"# OIDC_DISABLE_PASSWORD_LOGIN: "false"# OIDC_REQUIRE_EMAIL_VERIFIED: "true"+ # Optional SSRF allowlist (overrides the Security Settings allowlist in the Admin UI)+ # SSRF_ALLOWLIST: "auth.example.com,192.168.1.100:8123"# Volumes store your data between container upgradesvolumes:- './db:/var/www/html/db'diff --git a/endpoints/admin/deleteunusedlogos.php b/endpoints/admin/deleteunusedlogos.phpindex 3a75709..e6b45c1 100644--- a/endpoints/admin/deleteunusedlogos.php+++ b/endpoints/admin/deleteunusedlogos.php@@ -3,13 +3,14 @@require_once '../../includes/connect_endpoint.php';require_once '../../includes/validate_endpoint_admin.php';-$query = 'SELECT logo FROM subscriptions';+$query = 'SELECT logo, logo_variant FROM subscriptions';$stmt = $db->prepare($query);$result = $stmt->execute();$logosOnDB = [];while ($row = $result->fetchArray(SQLITE3_ASSOC)) {$logosOnDB[] = $row['logo'];+ $logosOnDB[] = $row['logo_variant'];}$logosOnDB = array_unique($logosOnDB);@@ -39,9 +40,9 @@ foreach ($uploadFiles as $file) {// Find and delete unused logos$count = 0;foreach ($logosOnDisk as $disk) {- foreach ($logosOnDB as $db) {- $found = false;- if ($disk['logo'] == $db) {+ $found = false;+ foreach ($logosOnDB as $dbLogo) {+ if ($disk['logo'] == $dbLogo) {$found = true;break;}diff --git a/endpoints/cronjobs/sendcancellationnotifications.php b/endpoints/cronjobs/sendcancellationnotifications.phpindex 9eba9e7..dd07cb7 100644--- a/endpoints/cronjobs/sendcancellationnotifications.php+++ b/endpoints/cronjobs/sendcancellationnotifications.php@@ -1,626 +1,639 @@-<?php-use PHPMailer\PHPMailer\PHPMailer;-use PHPMailer\PHPMailer\SMTP;-use PHPMailer\PHPMailer\Exception;--require_once 'validate.php';-require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';-require_once __DIR__ . '/../../includes/ssrf_helper.php';--require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php';-require __DIR__ . '/../../libs/PHPMailer/SMTP.php';-require __DIR__ . '/../../libs/PHPMailer/Exception.php';--require 'settimezone.php';--// Get all user ids-$query = "SELECT id, username FROM user";-$stmt = $db->prepare($query);-$usersToNotify = $stmt->execute();--while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {- $userId = $userToNotify['id'];- if (php_sapi_name() !== 'cli') {- echo "For user: " . $userToNotify['username'] . "<br />";- }-- $emailNotificationsEnabled = false;- $gotifyNotificationsEnabled = false;- $telegramNotificationsEnabled = false;- $pushoverNotificationsEnabled = false;- $discordNotificationsEnabled = false;- $ntfyNotificationsEnabled = false;- $webhookNotificationsEnabled = false;-- // 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();-- 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"] : "[email protected]";- $email['otherEmails'] = $row["other_emails"];- }-- // 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();-- $gotify = [];-- if ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $gotifyNotificationsEnabled = $row['enabled'];- $gotify['serverUrl'] = $row["url"];- $gotify['appToken'] = $row["token"];- $gotify['ignore_ssl'] = $row["ignore_ssl"];- }-- // 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)) {- $telegramNotificationsEnabled = $row['enabled'];- $telegram['botToken'] = $row["bot_token"];- $telegram['chatId'] = $row["chat_id"];- }-- // 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 Ntfy 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"];- $ntfy['ignore_ssl'] = $row["ignore_ssl"];- }-- // Check if webhook notifications are enabled and have cancelation payload set 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();-- $webhook = [];- if ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $webhook['url'] = $row["url"];- $webhook['headers'] = $row["headers"];- $webhook['cancelation_payload'] = $row["cancelation_payload"];- $webhook['ignore_ssl'] = $row["ignore_ssl"];- $webhook['request_method'] = $row["request_method"];- $webhookNotificationsEnabled = $row['enabled'] && $row['cancelation_payload'] != "";- }-- $notificationsEnabled = $emailNotificationsEnabled || $gotifyNotificationsEnabled || $telegramNotificationsEnabled ||- $pushoverNotificationsEnabled || $discordNotificationsEnabled ||$ntfyNotificationsEnabled || $webhookNotificationsEnabled;-- // If no notifications are enabled, no need to run- if (!$notificationsEnabled) {- if (php_sapi_name() !== 'cli') {- echo "Notifications are disabled. No need to run.<br />";- }- 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;- }-- // 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();-- $household = [];- while ($rowHousehold = $resultHousehold->fetchArray(SQLITE3_ASSOC)) {- $household[$rowHousehold['id']] = $rowHousehold;- }-- // Get all categories- $query = "SELECT * FROM categories WHERE user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $resultCategories = $stmt->execute();-- $categories = [];- while ($rowCategory = $resultCategories->fetchArray(SQLITE3_ASSOC)) {- $categories[$rowCategory['id']] = $rowCategory;- }-- // Get current date to check which subscriptions are set to notify for cancellation- $currentDate = new DateTime('now');- $currentDate = $currentDate->format('Y-m-d');-- $query = "SELECT * FROM subscriptions WHERE user_id = :user_id AND inactive = :inactive AND cancellation_date = :cancellationDate ORDER BY payer_user_id ASC";- $stmt = $db->prepare($query);- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);- $stmt->bindValue(':inactive', 0, SQLITE3_INTEGER);- $stmt->bindValue(':cancellationDate', $currentDate, SQLITE3_TEXT);- $resultSubscriptions = $stmt->execute();-- $notify = [];- $i = 0;- $currentDate = new DateTime('now');- while ($rowSubscription = $resultSubscriptions->fetchArray(SQLITE3_ASSOC)) {- $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]['url'] = $rowSubscription['url'];- $notify[$rowSubscription['payer_user_id']][$i]['notes'] = $rowSubscription['notes'];- $i++;- }-- if (!empty($notify)) {-- // Email notifications if enabled- if ($emailNotificationsEnabled) {- // Re-validate at send time: a save-time check alone is bypassable via- // DNS rebinding between when the host was saved and when the cron fires.- if (!validate_smtp_host($email['smtpAddress'], (int) $email['smtpPort'], $db)) {- echo "SSRF attempt detected for SMTP host. Email notifications not sent.<br />";- } else {- $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'];-- foreach ($notify as $userId => $perUser) {- $message = "The following subscriptions are up for cancellation:\n";-- foreach ($perUser as $subscription) {- $message .= $subscription['name'] . " for " . $subscription['price'] ."\n";- }-- $smtpAuth = (isset($email["smtpUsername"]) && $email["smtpUsername"] != "") || (isset($email["smtpPassword"]) && $email["smtpPassword"] != "");-- $mail = new PHPMailer(true);- $mail->CharSet = "UTF-8";- $mail->isSMTP();-- $mail->Host = $email['smtpAddress'];- $mail->SMTPAuth = $smtpAuth;- if ($smtpAuth) {- $mail->Username = $email['smtpUsername'];- $mail->Password = $email['smtpPassword'];- }- if ($email['encryption'] != "none") {- $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);-- if (!empty($email['otherEmails'])) {- $list = explode(';', $email['otherEmails']);-- // Avoid duplicate emails- $list = array_unique($list);- $list = array_filter($list, function ($value) use ($emailaddress) {- return $value !== $emailaddress;- });-- foreach($list as $value) {- $mail->addCC(trim($value));- }- }-- $mail->Subject = 'Wallos Cancellation Notification';- $mail->Body = $message;-- if ($mail->send()) {- echo "Email Notifications sent<br />";- } else {- echo "Error sending notifications: " . $mail->ErrorInfo . "<br />";- }- }- }- }-- // Discord notifications if enabled- if ($discordNotificationsEnabled) {- $ssrf = is_url_safe_for_ssrf($discord['webhook_url'], $db, $userId);- if (!$ssrf) {- echo "Discord notification skipped: URL failed SSRF validation.<br />";- } else {- 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 cancellation:\n";- } else {- $message = "The following subscriptions are up for cancellation:\n";- }-- foreach ($perUser as $subscription) {- $message .= $subscription['name'] . " for " . $subscription['price'] . "\n";- }-- $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'];- }-- $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_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);-- $response = curl_exec($ch);-- if ($response === false) {- echo "Error sending notifications: " . curl_error($ch) . "<br />";- } else {- echo "Discord Notifications sent<br />";- }-- unset($ch);- }- }- }-- // Gotify notifications if enabled- if ($gotifyNotificationsEnabled) {- $ssrf = is_url_safe_for_ssrf($gotify['serverUrl'], $db, $userId);- if (!$ssrf) {- echo "Gotify notification skipped: URL failed SSRF validation.<br />";- } else {- 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 cancellation:\n";- } else {- $message = "The following subscriptions are up for cancellation:\n";- }-- foreach ($perUser as $subscription) {- $message .= $subscription['name'] . " for " . $subscription['price'] . "\n";- }-- $data = array(- 'message' => $message,- 'priority' => 5- );-- $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(- 'Content-Type: application/json',- 'Content-Length: ' . strlen($data_string)- )- );-- if ($gotify['ignore_ssl']) {- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);- }- curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);-- $result = curl_exec($ch);- if ($result === false) {- echo "Error sending notifications: " . curl_error($ch) . "<br />";- } else {- echo "Gotify Notifications sent<br />";- }- }- }- }-- // 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 cancellation:\n";- } else {- $message = "The following subscriptions are up for cancellation:\n";- }-- foreach ($perUser as $subscription) {- $message .= $subscription['name'] . " for " . $subscription['price'] . "\n";- }-- $data = array(- 'chat_id' => $telegram['chatId'],- 'text' => $message- );-- $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) . "<br />";- } else {- echo "Telegram Notifications sent<br />";- }- }- }-- // 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 cancellation:\n";- } else {- $message = "The following subscriptions are up for cancellation:\n";- }-- foreach ($perUser as $subscription) {- $message .= $subscription['name'] . " for " . $subscription['price'] . "\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);-- $result = curl_exec($ch);-- if ($result === false) {- echo "Error sending notifications: " . curl_error($ch) . "<br />";- } else {- echo "Pushover Notifications sent<br />";- }-- unset($ch);- }- }-- // Ntfy notifications if enabled- if ($ntfyNotificationsEnabled) {- $ssrf = is_url_safe_for_ssrf($ntfy['host'], $db, $userId);- if (!$ssrf) {- echo "Ntfy notification skipped: URL failed SSRF validation.<br />";- } else {- 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 cancellation:\n";- } else {- $message = "The following subscriptions are up for cancellation:\n";- }-- foreach ($perUser as $subscription) {- $message .= $subscription['name'] . " for " . $subscription['price'] . "\n";- }-- $headers = json_decode($ntfy["headers"], true);- $customheaders = array_map(function ($key, $value) {- return "$key: $value";- }, array_keys($headers), $headers);-- $ch = curl_init();-- $ntfyHost = rtrim($ntfy["host"], '/');- $ntfyTopic = $ntfy['topic'];-- 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 ($ntfy['ignore_ssl']) {- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);- }- curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);-- $response = curl_exec($ch);-- if ($response === false) {- echo "Error sending notifications: " . curl_error($ch) . "<br />";- } else {- echo "Ntfy Notifications sent<br />";- }-- unset($ch);- }- }- }-- // Webhook notifications if enabled- if ($webhookNotificationsEnabled) {- $ssrf = is_url_safe_for_ssrf($webhook['url'], $db, $userId);- if (!$ssrf) {- echo "Webhook notification skipped: URL failed SSRF validation.<br />";- } else {- 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'];- }-- foreach ($perUser as $subscription) {- // Ensure the payload is reset for each subscription- $payload = $webhook['cancelation_payload'];- $payload = str_replace("{{subscription_name}}", $subscription['name'], $payload);- $payload = str_replace("{{subscription_price}}", $subscription['price'], $payload);- $payload = str_replace("{{subscription_currency}}", $subscription['currency'], $payload);- $payload = str_replace("{{subscription_category}}", $subscription['category'], $payload);- $payload = str_replace("{{subscription_payer}}", $payer, $payload);- $payload = str_replace("{{subscription_date}}", $subscription['date'], $payload);- $payload = str_replace("{{subscription_url}}", $subscription['url'], $payload);- $payload = str_replace("{{subscription_notes}}", $subscription['notes'], $payload);-- // Initialize cURL for each subscription- $ch = curl_init();- curl_setopt($ch, CURLOPT_URL, $webhook['url']);- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook['request_method']);- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);-- // Add headers if they exist- 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);-- // Handle SSL settings- if ($webhook['ignore_ssl']) {- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);- }- curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);-- // Execute the cURL request- $response = curl_exec($ch);- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);-- if ($response === false || $httpCode >= 400) {- echo "Error sending cancellation notifications: " . curl_error($ch) . "<br />";- } else {- echo "Webhook Cancellation Notification sent for subscription: " . $subscription['name'] . "<br />";- }-- unset($ch);-- usleep(1000000); // 1s delay between requests- }- }- }- }--- } else {- if (php_sapi_name() !== 'cli') {- echo "Nothing to notify.<br />";- }- }-- }--}--?>+<?php+use PHPMailer\PHPMailer\PHPMailer;+use PHPMailer\PHPMailer\SMTP;+use PHPMailer\PHPMailer\Exception;++require_once 'validate.php';+require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';+require_once __DIR__ . '/../../includes/ssrf_helper.php';++require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php';+require __DIR__ . '/../../libs/PHPMailer/SMTP.php';+require __DIR__ . '/../../libs/PHPMailer/Exception.php';++require 'settimezone.php';++// Get all user ids+$query = "SELECT id, username FROM user";+$stmt = $db->prepare($query);+$usersToNotify = $stmt->execute();++while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {+ $userId = $userToNotify['id'];+ if (php_sapi_name() !== 'cli') {+ echo "For user: " . $userToNotify['username'] . "<br />";+ }++ $emailNotificationsEnabled = false;+ $gotifyNotificationsEnabled = false;+ $telegramNotificationsEnabled = false;+ $pushoverNotificationsEnabled = false;+ $discordNotificationsEnabled = false;+ $ntfyNotificationsEnabled = false;+ $webhookNotificationsEnabled = false;++ // 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();++ 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"] : "[email protected]";+ $email['otherEmails'] = $row["other_emails"];+ }++ // 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();++ $gotify = [];++ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $gotifyNotificationsEnabled = $row['enabled'];+ $gotify['serverUrl'] = $row["url"];+ $gotify['appToken'] = $row["token"];+ $gotify['ignore_ssl'] = $row["ignore_ssl"];+ }++ // 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)) {+ $telegramNotificationsEnabled = $row['enabled'];+ $telegram['botToken'] = $row["bot_token"];+ $telegram['chatId'] = $row["chat_id"];+ }++ // 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 Ntfy 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"];+ $ntfy['ignore_ssl'] = $row["ignore_ssl"];+ }++ // Check if webhook notifications are enabled and have cancelation payload set 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();++ $webhook = [];+ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $webhook['url'] = $row["url"];+ $webhook['headers'] = $row["headers"];+ $webhook['cancelation_payload'] = $row["cancelation_payload"];+ $webhook['ignore_ssl'] = $row["ignore_ssl"];+ $webhook['request_method'] = $row["request_method"];+ $webhookNotificationsEnabled = $row['enabled'] && $row['cancelation_payload'] != "";+ }++ $notificationsEnabled = $emailNotificationsEnabled || $gotifyNotificationsEnabled || $telegramNotificationsEnabled ||+ $pushoverNotificationsEnabled || $discordNotificationsEnabled ||$ntfyNotificationsEnabled || $webhookNotificationsEnabled;++ // If no notifications are enabled, no need to run+ if (!$notificationsEnabled) {+ if (php_sapi_name() !== 'cli') {+ echo "Notifications are disabled. No need to run.<br />";+ }+ 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;+ }++ // 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();++ $household = [];+ while ($rowHousehold = $resultHousehold->fetchArray(SQLITE3_ASSOC)) {+ $household[$rowHousehold['id']] = $rowHousehold;+ }++ // Get all categories+ $query = "SELECT * FROM categories WHERE user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $resultCategories = $stmt->execute();++ $categories = [];+ while ($rowCategory = $resultCategories->fetchArray(SQLITE3_ASSOC)) {+ $categories[$rowCategory['id']] = $rowCategory;+ }++ // Get current date to check which subscriptions are set to notify for cancellation+ $currentDate = new DateTime('now');+ $currentDate = $currentDate->format('Y-m-d');++ $query = "SELECT * FROM subscriptions WHERE user_id = :user_id AND inactive = :inactive AND cancellation_date = :cancellationDate ORDER BY payer_user_id ASC";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);+ $stmt->bindValue(':inactive', 0, SQLITE3_INTEGER);+ $stmt->bindValue(':cancellationDate', $currentDate, SQLITE3_TEXT);+ $resultSubscriptions = $stmt->execute();++ $notify = [];+ $i = 0;+ $currentDate = new DateTime('now');+ while ($rowSubscription = $resultSubscriptions->fetchArray(SQLITE3_ASSOC)) {+ $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]['url'] = $rowSubscription['url'];+ $notify[$rowSubscription['payer_user_id']][$i]['notes'] = $rowSubscription['notes'];+ $i++;+ }++ if (!empty($notify)) {++ // Email notifications if enabled+ if ($emailNotificationsEnabled) {+ // Re-validate at send time: a save-time check alone is bypassable via+ // DNS rebinding between when the host was saved and when the cron fires.+ if (!validate_smtp_host($email['smtpAddress'], (int) $email['smtpPort'], $db)) {+ echo "SSRF attempt detected for SMTP host. Email notifications not sent.<br />";+ } else {+ $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'];++ foreach ($notify as $userId => $perUser) {+ $message = "The following subscriptions are up for cancellation:\n";++ foreach ($perUser as $subscription) {+ $message .= $subscription['name'] . " for " . $subscription['price'] ."\n";+ }++ $smtpAuth = (isset($email["smtpUsername"]) && $email["smtpUsername"] != "") || (isset($email["smtpPassword"]) && $email["smtpPassword"] != "");++ $mail = new PHPMailer(true);+ $mail->CharSet = "UTF-8";+ $mail->isSMTP();+ $mail->Timeout = 15;++ $mail->Host = $email['smtpAddress'];+ $mail->SMTPAuth = $smtpAuth;+ if ($smtpAuth) {+ $mail->Username = $email['smtpUsername'];+ $mail->Password = $email['smtpPassword'];+ }+ if ($email['encryption'] != "none") {+ $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);++ if (!empty($email['otherEmails'])) {+ $list = explode(';', $email['otherEmails']);++ // Avoid duplicate emails+ $list = array_unique($list);+ $list = array_filter($list, function ($value) use ($emailaddress) {+ return $value !== $emailaddress;+ });++ foreach($list as $value) {+ $mail->addCC(trim($value));+ }+ }++ $mail->Subject = 'Wallos Cancellation Notification';+ $mail->Body = $message;++ if ($mail->send()) {+ echo "Email Notifications sent<br />";+ } else {+ echo "Error sending notifications: " . $mail->ErrorInfo . "<br />";+ }+ }+ }+ }++ // Discord notifications if enabled+ if ($discordNotificationsEnabled) {+ $ssrf = is_url_safe_for_ssrf($discord['webhook_url'], $db, $userId);+ if (!$ssrf) {+ echo "Discord notification skipped: URL failed SSRF validation.<br />";+ } else {+ 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 cancellation:\n";+ } else {+ $message = "The following subscriptions are up for cancellation:\n";+ }++ foreach ($perUser as $subscription) {+ $message .= $subscription['name'] . " for " . $subscription['price'] . "\n";+ }++ $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'];+ }++ $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_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);++ $response = curl_exec($ch);++ if ($response === false) {+ echo "Error sending notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Discord Notifications sent<br />";+ }++ unset($ch);+ }+ }+ }++ // Gotify notifications if enabled+ if ($gotifyNotificationsEnabled) {+ $ssrf = is_url_safe_for_ssrf($gotify['serverUrl'], $db, $userId);+ if (!$ssrf) {+ echo "Gotify notification skipped: URL failed SSRF validation.<br />";+ } else {+ 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 cancellation:\n";+ } else {+ $message = "The following subscriptions are up for cancellation:\n";+ }++ foreach ($perUser as $subscription) {+ $message .= $subscription['name'] . " for " . $subscription['price'] . "\n";+ }++ $data = array(+ 'message' => $message,+ 'priority' => 5+ );++ $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_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);+ curl_setopt(+ $ch,+ CURLOPT_HTTPHEADER,+ array(+ 'Content-Type: application/json',+ 'Content-Length: ' . strlen($data_string)+ )+ );++ if ($gotify['ignore_ssl']) {+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);+ }+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);++ $result = curl_exec($ch);+ if ($result === false) {+ echo "Error sending notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Gotify Notifications sent<br />";+ }+ }+ }+ }++ // 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 cancellation:\n";+ } else {+ $message = "The following subscriptions are up for cancellation:\n";+ }++ foreach ($perUser as $subscription) {+ $message .= $subscription['name'] . " for " . $subscription['price'] . "\n";+ }++ $data = array(+ 'chat_id' => $telegram['chatId'],+ 'text' => $message+ );++ $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_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);+ 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) . "<br />";+ } else {+ echo "Telegram Notifications sent<br />";+ }+ }+ }++ // 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 cancellation:\n";+ } else {+ $message = "The following subscriptions are up for cancellation:\n";+ }++ foreach ($perUser as $subscription) {+ $message .= $subscription['name'] . " for " . $subscription['price'] . "\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);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);++ $result = curl_exec($ch);++ if ($result === false) {+ echo "Error sending notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Pushover Notifications sent<br />";+ }++ unset($ch);+ }+ }++ // Ntfy notifications if enabled+ if ($ntfyNotificationsEnabled) {+ $ssrf = is_url_safe_for_ssrf($ntfy['host'], $db, $userId);+ if (!$ssrf) {+ echo "Ntfy notification skipped: URL failed SSRF validation.<br />";+ } else {+ 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 cancellation:\n";+ } else {+ $message = "The following subscriptions are up for cancellation:\n";+ }++ foreach ($perUser as $subscription) {+ $message .= $subscription['name'] . " for " . $subscription['price'] . "\n";+ }++ $headers = json_decode($ntfy["headers"], true);+ $customheaders = array_map(function ($key, $value) {+ return "$key: $value";+ }, array_keys($headers), $headers);++ $ch = curl_init();++ $ntfyHost = rtrim($ntfy["host"], '/');+ $ntfyTopic = $ntfy['topic'];++ 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);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);++ if ($ntfy['ignore_ssl']) {+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);+ }+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);++ $response = curl_exec($ch);++ if ($response === false) {+ echo "Error sending notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Ntfy Notifications sent<br />";+ }++ unset($ch);+ }+ }+ }++ // Webhook notifications if enabled+ if ($webhookNotificationsEnabled) {+ $ssrf = is_url_safe_for_ssrf($webhook['url'], $db, $userId);+ if (!$ssrf) {+ echo "Webhook notification skipped: URL failed SSRF validation.<br />";+ } else {+ 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'];+ }++ foreach ($perUser as $subscription) {+ // Ensure the payload is reset for each subscription+ $payload = $webhook['cancelation_payload'];+ $payload = str_replace("{{subscription_name}}", $subscription['name'], $payload);+ $payload = str_replace("{{subscription_price}}", $subscription['price'], $payload);+ $payload = str_replace("{{subscription_currency}}", $subscription['currency'], $payload);+ $payload = str_replace("{{subscription_category}}", $subscription['category'], $payload);+ $payload = str_replace("{{subscription_payer}}", $payer, $payload);+ $payload = str_replace("{{subscription_date}}", $subscription['date'], $payload);+ $payload = str_replace("{{subscription_url}}", $subscription['url'], $payload);+ $payload = str_replace("{{subscription_notes}}", $subscription['notes'], $payload);++ // Initialize cURL for each subscription+ $ch = curl_init();+ curl_setopt($ch, CURLOPT_URL, $webhook['url']);+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook['request_method']);+ curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);++ // Add headers if they exist+ 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);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);++ // Handle SSL settings+ if ($webhook['ignore_ssl']) {+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);+ }+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);++ // Execute the cURL request+ $response = curl_exec($ch);+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);++ if ($response === false || $httpCode >= 400) {+ echo "Error sending cancellation notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Webhook Cancellation Notification sent for subscription: " . $subscription['name'] . "<br />";+ }++ unset($ch);++ usleep(1000000); // 1s delay between requests+ }+ }+ }+ }+++ } else {+ if (php_sapi_name() !== 'cli') {+ echo "Nothing to notify.<br />";+ }+ }++ }++}++?>diff --git a/endpoints/cronjobs/sendnotifications.php b/endpoints/cronjobs/sendnotifications.phpindex c7aa186..d4333ba 100644--- a/endpoints/cronjobs/sendnotifications.php+++ b/endpoints/cronjobs/sendnotifications.php@@ -1,972 +1,991 @@-<?php-use PHPMailer\PHPMailer\PHPMailer;-use PHPMailer\PHPMailer\SMTP;-use PHPMailer\PHPMailer\Exception;--require_once 'validate.php';-require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';-require_once __DIR__ . '/../../includes/ssrf_helper.php';--require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php';-require __DIR__ . '/../../libs/PHPMailer/SMTP.php';-require __DIR__ . '/../../libs/PHPMailer/Exception.php';--require __DIR__ . '/../../includes/currency_formatter.php';-require __DIR__ . '/../../includes/budget_period_calculations.php';--require 'settimezone.php';--if (php_sapi_name() == 'cli') {- $date = new DateTime('now');- echo "\n" . $date->format('Y-m-d') . " " . $date->format('H:i:s') . "<br />\n";-} else {- echo "On Timezone: " . date_default_timezone_get() . "<br /><br />";-}--// Get all user ids-$query = "SELECT id, username FROM user";-$stmt = $db->prepare($query);-$usersToNotify = $stmt->execute();-$periodSummaryColumnCheck = $db->query("SELECT * FROM pragma_table_info('notification_settings') WHERE name='period_summary_at_period_start'");-$hasPeriodSummaryColumn = $periodSummaryColumnCheck && $periodSummaryColumnCheck->fetchArray(SQLITE3_ASSOC);--function getDaysText($days)-{- if ($days == 0) {- return "Today";- } elseif ($days == 1) {- return "Tomorrow";- } else {- return "In " . $days . " days";- }-}--function formatPrice($price, $currencyCode, $currencySymbol)-{- $formattedPrice = CurrencyFormatter::format($price, $currencyCode);-- if (strpos($formattedPrice, $currencyCode) !== false) {- $formattedPrice = str_replace($currencyCode, $currencySymbol . ' ', $formattedPrice);- $formattedPrice = preg_replace('/\s+/', ' ', $formattedPrice);- }-- return $formattedPrice;-}--function buildNotificationMessage($name, $perUser, $periodSummaryLine, $includePeriodSummary)-{- if (empty($perUser) && !$includePeriodSummary) {- return "";- }-- if (empty($perUser)) {- return ($name ? $name . ", " : "") . $periodSummaryLine . "\n";- }-- if ($name) {- $message = $name . ", the following subscriptions are up for renewal:\n";- } else {- $message = "The following subscriptions are up for renewal:\n";- }-- foreach ($perUser as $subscription) {- $dayText = getDaysText($subscription['days']);- $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";- }-- if ($includePeriodSummary) {- $message .= "\n" . $periodSummaryLine . "\n";- }-- return $message;-}--while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {- $userId = $userToNotify['id'];- if (php_sapi_name() !== 'cli') {- echo "For user: " . $userToNotify['username'] . "<br /><br />";- }-- $days = 1;- $periodSummaryAtPeriodStart = 0;- $emailNotificationsEnabled = false;- $gotifyNotificationsEnabled = false;- $telegramNotificationsEnabled = false;- $webhookNotificationsEnabled = false;- $pushoverNotificationsEnabled = false;- $pushplusNotificationsEnabled = false;- $mattermostNotificationsEnabled = false;- $discordNotificationsEnabled = false;- $ntfyNotificationsEnabled = false;- $serverchanNotificationsEnabled = false;-- // Get notification settings (how many days before the subscription ends should the notification be sent)- $query = $hasPeriodSummaryColumn- ? "SELECT days, period_summary_at_period_start FROM notification_settings WHERE user_id = :userId"- : "SELECT days FROM notification_settings WHERE user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- if ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $days = $row['days'];- if ($hasPeriodSummaryColumn) {- $periodSummaryAtPeriodStart = (int) ($row['period_summary_at_period_start'] ?? 0);- }- }-- // 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();-- 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"] : "[email protected]";- $email['otherEmails'] = $row["other_emails"];- }-- // 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();-- $gotify = [];-- if ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $gotifyNotificationsEnabled = $row['enabled'];- $gotify['serverUrl'] = $row["url"];- $gotify['appToken'] = $row["token"];- $gotify['ignore_ssl'] = $row["ignore_ssl"];- }-- // 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)) {- $telegramNotificationsEnabled = $row['enabled'];- $telegram['botToken'] = $row["bot_token"];- $telegram['chatId'] = $row["chat_id"];- }- // Check if PushPlus notifications are enabled and get the settings- $query = "SELECT * FROM pushplus_notifications WHERE user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- if ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $pushplusNotificationsEnabled = $row['enabled'];- $pushplus['token'] = $row["token"];- }- // Check if Mattermost notifications are enabled and get the settings- $query = "SELECT * FROM mattermost_notifications WHERE user_id = :userID";- $stmt = $db->prepare($query);- $stmt->bindValue(':userID', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- if ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $mattermostNotificationsEnabled = $row['enabled'];- $mattermost['webhook_url'] = $row['webhook_url'];- $mattermost['bot_username'] = $row['bot_username'];- $mattermost['bot_icon_emoji'] = $row['bot_icon_emoji'];- }-- // 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 Ntfy 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"];- $ntfy['ignore_ssl'] = $row["ignore_ssl"];- }-- // 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['ignore_ssl'] = $row["ignore_ssl"];- }-- // Check if Serverchan notifications are enabled and get the settings- $query = "SELECT * FROM serverchan_notifications WHERE user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- if ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $serverchanNotificationsEnabled = $row['enabled'];- $serverchan['sendkey'] = $row['sendkey'];- }-- $notificationsEnabled = $emailNotificationsEnabled || $gotifyNotificationsEnabled || $telegramNotificationsEnabled ||- $webhookNotificationsEnabled || $pushoverNotificationsEnabled || $discordNotificationsEnabled || $pushplusNotificationsEnabled ||- $mattermostNotificationsEnabled || $ntfyNotificationsEnabled || $serverchanNotificationsEnabled;-- // If no notifications are enabled, no need to run- if (!$notificationsEnabled) {- if (php_sapi_name() !== 'cli') {- echo "Notifications are disabled. No need to run.<br />";- }- 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;- }-- // 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();-- $household = [];- while ($rowHousehold = $resultHousehold->fetchArray(SQLITE3_ASSOC)) {- $household[$rowHousehold['id']] = $rowHousehold;- }-- // Get all categories- $query = "SELECT * FROM categories WHERE user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $resultCategories = $stmt->execute();-- $categories = [];- while ($rowCategory = $resultCategories->fetchArray(SQLITE3_ASSOC)) {- $categories[$rowCategory['id']] = $rowCategory;- }-- $currentDate = new DateTime('now');-- $query = "SELECT main_currency, period_budget, budget_period_type, budget_period_anchor_date FROM user WHERE id = :userId";- $stmt = $db->prepare($query);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();- $userBudgetConfig = $result->fetchArray(SQLITE3_ASSOC);-- $mainCurrencyId = $userBudgetConfig['main_currency'];- $budgetPeriodType = sanitizeBudgetPeriodType($userBudgetConfig['budget_period_type'] ?? 'monthly');- $budgetPeriodAnchorDate = sanitizeBudgetAnchorDate($userBudgetConfig['budget_period_anchor_date'] ?? getDefaultBudgetAnchorDate());- $activeBudgetPeriod = getActiveBudgetPeriod($currentDate, $budgetPeriodType, $budgetPeriodAnchorDate);- $isPeriodStart = $activeBudgetPeriod['start']->format('Y-m-d') === $currentDate->format('Y-m-d');-- $query = "SELECT price, currency_id, next_payment, cycle, frequency, inactive, auto_renew FROM subscriptions WHERE user_id = :userId AND inactive = 0";- $stmt = $db->prepare($query);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();- $periodSubscriptions = [];- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $periodSubscriptions[] = $row;- }-- $amountNeededThisPeriod = computeAmountNeededInPeriod($periodSubscriptions, $currentDate, $activeBudgetPeriod['end'], $db, $userId);- $mainCurrencyCode = $currencies[$mainCurrencyId]['code'] ?? 'USD';- $mainCurrencySymbol = $currencies[$mainCurrencyId]['symbol'] ?? '$';- $periodSummaryLine = translate('amount_for_pay_period', $i18n) . ": " . formatPrice($amountNeededThisPeriod, $mainCurrencyCode, $mainCurrencySymbol);-- if (!empty($userBudgetConfig['period_budget']) && $userBudgetConfig['period_budget'] > 0) {- $remaining = max(0, $userBudgetConfig['period_budget'] - $amountNeededThisPeriod);- $periodSummaryLine .= " | " . translate('remaining', $i18n) . ": " . formatPrice($remaining, $mainCurrencyCode, $mainCurrencySymbol);- }-- $sendPeriodStartSummaryOnly = $periodSummaryAtPeriodStart === 1 && $isPeriodStart;-- $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;- while ($rowSubscription = $resultSubscriptions->fetchArray(SQLITE3_ASSOC)) {- if ($rowSubscription['notify_days_before'] !== -1) {- $daysToCompare = $rowSubscription['notify_days_before'];- } else {- $daysToCompare = $days;- }- $nextPaymentDate = new DateTime($rowSubscription['next_payment']);-- $difference = $currentDate->diff($nextPaymentDate)->days;- if ($nextPaymentDate > $currentDate) {- $difference += 1;- }-- if ($difference === $daysToCompare && $nextPaymentDate->format('Y-m-d') >= $currentDate->format('Y-m-d')) {- echo "Subscription: " . $rowSubscription['name'] . "<br />";- echo "Next payment date: " . $nextPaymentDate->format('Y-m-d') . "<br />";- echo "Current date: " . $currentDate->format('Y-m-d') . "<br />";- echo "Difference: " . $difference . "<br /><br />";- $notify[$rowSubscription['payer_user_id']][$i]['name'] = html_entity_decode($rowSubscription['name'], ENT_QUOTES, 'UTF-8');- $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]['currency_symbol'] = $currencies[$rowSubscription['currency_id']]['symbol'];- $notify[$rowSubscription['payer_user_id']][$i]['formatted_price'] = formatPrice($rowSubscription['price'], $currencies[$rowSubscription['currency_id']]['code'], $currencies[$rowSubscription['currency_id']]['symbol']);- $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;- $notify[$rowSubscription['payer_user_id']][$i]['url'] = $rowSubscription['url'];- $notify[$rowSubscription['payer_user_id']][$i]['notes'] = $rowSubscription['notes'];- $i++;- }- }-- if (empty($notify) && $sendPeriodStartSummaryOnly) {- $defaultPayerUserId = array_key_first($household);- if ($defaultPayerUserId !== null) {- $notify[$defaultPayerUserId] = [];- }- }-- if (!empty($notify)) {-- // Email notifications if enabled- if ($emailNotificationsEnabled) {- // Re-validate at send time: a save-time check alone is bypassable via- // DNS rebinding between when the host was saved and when the cron fires.- if (!validate_smtp_host($email['smtpAddress'], (int) $email['smtpPort'], $db)) {- echo "SSRF attempt detected for SMTP host. Email notifications not sent.<br />";- } else {-- $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'];-- foreach ($notify as $userId => $perUser) {- $message = buildNotificationMessage("", $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);- if ($message === "") {- continue;- }-- $smtpAuth = (isset($email["smtpUsername"]) && $email["smtpUsername"] != "") || (isset($email["smtpPassword"]) && $email["smtpPassword"] != "");-- $mail = new PHPMailer(true);- $mail->CharSet = "UTF-8";- $mail->isSMTP();-- $mail->Host = $email['smtpAddress'];- $mail->SMTPAuth = $smtpAuth;-- if ($smtpAuth) {- $mail->Username = $email['smtpUsername'];- $mail->Password = $email['smtpPassword'];- }-- if ($email['encryption'] != "none") {- $mail->SMTPSecure = $email['encryption'];- } else {- $mail->SMTPSecure = false;- $mail->SMTPAutoTLS = false;- }-- $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);-- if (!empty($email['otherEmails'])) {- $list = explode(';', $email['otherEmails']);-- // Avoid duplicate emails- $list = array_unique($list);- $list = array_filter($list, function ($value) use ($emailaddress) {- return $value !== $emailaddress;- });-- foreach ($list as $value) {- $mail->addCC(trim($value));- }- }-- $mail->Subject = 'Wallos Notification';- $mail->Body = $message;-- if ($mail->send()) {- echo "Email Notifications sent<br />";- } else {- echo "Error sending notifications: " . $mail->ErrorInfo . "<br />";- }- }- }- }-- // Discord notifications if enabled- if ($discordNotificationsEnabled) {- $ssrf = is_url_safe_for_ssrf($discord['webhook_url'], $db, $userId);- if (!$ssrf) {- echo "SSRF attempt detected for Discord webhook URL. Notifications not sent.<br />";- } else {- 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);-- $name = $user['name'] ?? "";- $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);- if ($message === "") {- continue;- }-- $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'];- }-- $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_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);-- $response = curl_exec($ch);-- if ($response === false) {- echo "Error sending notifications: " . curl_error($ch) . "<br />";- } else {- echo "Discord Notifications sent<br />";- }-- unset($ch);- }- }- }-- // Gotify notifications if enabled- if ($gotifyNotificationsEnabled) {- $ssrf = is_url_safe_for_ssrf($gotify['serverUrl'], $db, $userId);- if (!$ssrf) {- echo "SSRF attempt detected for Gotify server URL. Notifications not sent.<br />";- } else {- 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);-- $name = $user['name'] ?? "";- $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);- if ($message === "") {- continue;- }-- $data = array(- 'message' => $message,- 'priority' => 5- );-- $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(- 'Content-Type: application/json',- 'Content-Length: ' . strlen($data_string)- )- );-- if ($gotify['ignore_ssl']) {- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);- }- curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);-- $result = curl_exec($ch);- if ($result === false) {- echo "Error sending notifications: " . curl_error($ch) . "<br />";- } else {- echo "Gotify Notifications sent<br />";- }-- unset($ch);- }- }- }-- // 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']) {- $name = $user['name'];- } else {- $name = "";- }- $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);- if ($message === "") {- continue;- }-- $data = array(- 'chat_id' => $telegram['chatId'],- 'text' => mb_convert_encoding($message, 'UTF-8', 'auto')- );-- $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) . "<br />";- } else {- echo "Telegram Notifications sent<br />";- }-- unset($ch);- }- }--- // PushPlus notifications if enabled- if ($pushplusNotificationsEnabled) {- 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);-- // Build Message Content- $name = $user['name'] ?? "";- $messageContent = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);- if ($messageContent === "") {- continue;- }-- // Prepare PushPlus Data- $data = array(- 'token' => $pushplus['token'],- 'title' => '订阅续期提醒 - Wallos',- 'content' => mb_convert_encoding($messageContent, 'UTF-8', 'auto'),- 'template' => 'json'- );-- $data_string = json_encode($data);-- $ch = curl_init('https://www.pushplus.plus/send');- 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'- ),- );-- $result = curl_exec($ch);- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);-- if ($result === false) {- echo "Error sending PushPlus notifications: " . curl_error($ch) . "<br />";- } else {- $resultData = json_decode($result, true);- if (isset($resultData['code']) && $resultData['code'] == 200) {- echo "PushPlus Notifications sent successfully<br />";- } else {- $errorMsg = isset($resultData['msg']) ? $resultData['msg'] : 'Unknown error';- echo "PushPlus API error: " . $errorMsg . "<br />";- }- }- unset($ch);- }- }-- // Mattermost notifications if enabled- if ($mattermostNotificationsEnabled) {- $ssrf = is_url_safe_for_ssrf($mattermost['webhook_url'], $db, $userId);- if (!$ssrf) {- echo "SSRF attempt detected for Mattermost webhook URL. Notifications not sent.<br />";- } else {- 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);-- // Build Message Content- $name = $user['name'] ?? "";- $messageContent = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);- if ($messageContent === "") {- continue;- }- // Prepare Mattermost Data- $webhook_url = $mattermost['webhook_url'];- $data = array(- 'username' => $mattermost['bot_username'],- 'icon_emoji' => $mattermost['bot_icon_emoji'],- 'text' => mb_convert_encoding($messageContent, 'UTF-8', 'auto'),- );-- $data_string = json_encode($data);-- $ch = curl_init();- curl_setopt($ch, CURLOPT_URL, $webhook_url);- 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'- ),- );- curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);-- $result = curl_exec($ch);- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);-- if ($result === false) {- echo "Error sending Mattermost notifications: " . curl_error($ch) . "<br />";- } else {- $resultData = json_decode($result, true);- if (isset($resultData['code']) && $resultData['code'] == 200) {- echo "Mattermost Notifications sent successfully<br />";- } else {- $errorMsg = isset($resultData['msg']) ? $resultData['msg'] : 'Unknown error';- echo "Mattermost API error: " . $errorMsg . "<br />";- }- }- unset($ch);- }- }- }-- // 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']) {- $name = $user['name'];- } else {- $name = "";- }- $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);- if ($message === "") {- continue;- }-- $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);-- $result = curl_exec($ch);-- if ($result === false) {- echo "Error sending notifications: " . curl_error($ch) . "<br />";- } else {- echo "Pushover Notifications sent<br />";- }-- unset($ch);- }- }-- // Ntfy notifications if enabled- if ($ntfyNotificationsEnabled) {- $ssrf = is_url_safe_for_ssrf($ntfy['host'], $db, $userId);- if (!$ssrf) {- echo "SSRF attempt detected for Ntfy host URL. Notifications not sent.<br />";- } else {- 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);-- $name = $user['name'] ?? "";- $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);- if ($message === "") {- continue;- }-- $headers = json_decode($ntfy["headers"], true);- $customheaders = [];-- if (is_array($headers)) {- $customheaders = array_map(function ($key, $value) {- return "$key: $value";- }, array_keys($headers), $headers);- }-- $ch = curl_init();-- $ntfyHost = rtrim($ntfy["host"], '/');- $ntfyTopic = $ntfy['topic'];-- curl_setopt($ch, CURLOPT_URL, $ntfyHost . '/' . $ntfyTopic);- curl_setopt($ch, CURLOPT_POST, 1);- curl_setopt($ch, CURLOPT_POSTFIELDS, $message);- $ntfyHeaders = array_merge(['Content-Type: text/plain; charset=utf-8'], $customheaders);- curl_setopt($ch, CURLOPT_HTTPHEADER, $ntfyHeaders);- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);-- if ($ntfy['ignore_ssl']) {- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);- }- curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);-- $response = curl_exec($ch);-- if ($response === false) {- echo "Error sending notifications: " . curl_error($ch) . "<br />";- } else {- echo "Ntfy Notifications sent<br />";- }-- unset($ch);- }- }- }-- // Webhook notifications if enabled- if ($webhookNotificationsEnabled) {- $ssrf = is_url_safe_for_ssrf($webhook['url'], $db, $userId);- if (!$ssrf) {- echo "SSRF attempt detected for webhook URL. Notifications not sent.<br />";;- } else {- 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'];- }-- foreach ($perUser as $subscription) {- // Ensure the payload is reset for each subscription- $payload = $webhook['payload'];- $payload = str_replace("{{days_until}}", $days, $payload);- $payload = str_replace("{{subscription_name}}", $subscription['name'], $payload);- $payload = str_replace("{{subscription_price}}", $subscription['formatted_price'], $payload);- $payload = str_replace("{{subscription_currency}}", $subscription['currency'], $payload);- $payload = str_replace("{{subscription_category}}", $subscription['category'], $payload);- $payload = str_replace("{{subscription_payer}}", $payer, $payload); // Use $payer instead of $subscription['payer']- $payload = str_replace("{{subscription_date}}", $subscription['date'], $payload);- $payload = str_replace("{{subscription_days_until_payment}}", $subscription['days'], $payload);- $payload = str_replace("{{subscription_url}}", $subscription['url'], $payload);- $payload = str_replace("{{subscription_notes}}", $subscription['notes'], $payload);-- // Initialize cURL for each subscription- $ch = curl_init();- curl_setopt($ch, CURLOPT_URL, $webhook['url']);- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook['request_method']);- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);-- // Add headers if they exist- if (!empty($webhook['headers'])) {- $customheaders = json_decode($webhook["headers"], true);- curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);- }-- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);-- // Handle SSL settings- if ($webhook['ignore_ssl']) {- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);- }- curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);-- // Execute the cURL request- $response = curl_exec($ch);- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);-- if ($response === false || $httpCode >= 400) {- echo "Error sending notifications: " . curl_error($ch) . "<br />";- } else {- echo "Webhook Notification sent for subscription: " . $subscription['name'] . "<br />";- }-- unset($ch);-- usleep(1000000); // 1s delay between requests- }- }- }- }-- // Serverchan notifications if enabled- if ($serverchanNotificationsEnabled) {- 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 = 'Wallos Notification';- $name = $user['name'] ?? "";- $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);- if ($message === "") {- continue;- }-- // Build Serverchan request- $postdata = http_build_query(array('text' => $title, 'desp' => $message));-- $sendkey = $serverchan['sendkey'];- if (strpos($sendkey, 'sctp') === 0) {- preg_match('/^sctp(\d+)t/', $sendkey, $matches);- $num = $matches[1] ?? '';- $url = "https://{$num}.push.ft07.com/send/{$sendkey}.send";- } else {- $url = "https://sctapi.ftqq.com/{$sendkey}.send";- }-- $ch = curl_init();- curl_setopt($ch, CURLOPT_URL, $url);- curl_setopt($ch, CURLOPT_POST, 1);- curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);- curl_setopt($ch, CURLOPT_HTTPHEADER, [- 'Content-Type: application/x-www-form-urlencoded'- ]);- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);-- $response = curl_exec($ch);- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);-- if ($response === false || $httpCode >= 400) {- $errorMessage = $response === false ? curl_error($ch) : $httpCode;- unset($ch);- echo "Error sending Serverchan notifications: " . $errorMessage . "<br />";- } else {- unset($ch);- echo "Serverchan Notifications sent<br />";- }- }- }-- } else {- if (php_sapi_name() !== 'cli') {- echo "Nothing to notify.<br />";- }- }-- }-+<?php+use PHPMailer\PHPMailer\PHPMailer;+use PHPMailer\PHPMailer\SMTP;+use PHPMailer\PHPMailer\Exception;++require_once 'validate.php';+require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';+require_once __DIR__ . '/../../includes/ssrf_helper.php';++require __DIR__ . '/../../libs/PHPMailer/PHPMailer.php';+require __DIR__ . '/../../libs/PHPMailer/SMTP.php';+require __DIR__ . '/../../libs/PHPMailer/Exception.php';++require __DIR__ . '/../../includes/currency_formatter.php';+require __DIR__ . '/../../includes/budget_period_calculations.php';++require 'settimezone.php';++if (php_sapi_name() == 'cli') {+ $date = new DateTime('now');+ echo "\n" . $date->format('Y-m-d') . " " . $date->format('H:i:s') . "<br />\n";+} else {+ echo "On Timezone: " . date_default_timezone_get() . "<br /><br />";+}++// Get all user ids+$query = "SELECT id, username FROM user";+$stmt = $db->prepare($query);+$usersToNotify = $stmt->execute();+$periodSummaryColumnCheck = $db->query("SELECT * FROM pragma_table_info('notification_settings') WHERE name='period_summary_at_period_start'");+$hasPeriodSummaryColumn = $periodSummaryColumnCheck && $periodSummaryColumnCheck->fetchArray(SQLITE3_ASSOC);++function getDaysText($days)+{+ if ($days == 0) {+ return "Today";+ } elseif ($days == 1) {+ return "Tomorrow";+ } else {+ return "In " . $days . " days";+ }+}++function formatPrice($price, $currencyCode, $currencySymbol)+{+ $formattedPrice = CurrencyFormatter::format($price, $currencyCode);++ if (strpos($formattedPrice, $currencyCode) !== false) {+ $formattedPrice = str_replace($currencyCode, $currencySymbol . ' ', $formattedPrice);+ $formattedPrice = preg_replace('/\s+/', ' ', $formattedPrice);+ }++ return $formattedPrice;+}++function buildNotificationMessage($name, $perUser, $periodSummaryLine, $includePeriodSummary)+{+ if (empty($perUser) && !$includePeriodSummary) {+ return "";+ }++ if (empty($perUser)) {+ return ($name ? $name . ", " : "") . $periodSummaryLine . "\n";+ }++ if ($name) {+ $message = $name . ", the following subscriptions are up for renewal:\n";+ } else {+ $message = "The following subscriptions are up for renewal:\n";+ }++ foreach ($perUser as $subscription) {+ $dayText = getDaysText($subscription['days']);+ $message .= $subscription['name'] . " for " . $subscription['formatted_price'] . " (" . $dayText . ")\n";+ }++ if ($includePeriodSummary) {+ $message .= "\n" . $periodSummaryLine . "\n";+ }++ return $message;+}++while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {+ $userId = $userToNotify['id'];+ if (php_sapi_name() !== 'cli') {+ echo "For user: " . $userToNotify['username'] . "<br /><br />";+ }++ $days = 1;+ $periodSummaryAtPeriodStart = 0;+ $emailNotificationsEnabled = false;+ $gotifyNotificationsEnabled = false;+ $telegramNotificationsEnabled = false;+ $webhookNotificationsEnabled = false;+ $pushoverNotificationsEnabled = false;+ $pushplusNotificationsEnabled = false;+ $mattermostNotificationsEnabled = false;+ $discordNotificationsEnabled = false;+ $ntfyNotificationsEnabled = false;+ $serverchanNotificationsEnabled = false;++ // Get notification settings (how many days before the subscription ends should the notification be sent)+ $query = $hasPeriodSummaryColumn+ ? "SELECT days, period_summary_at_period_start FROM notification_settings WHERE user_id = :userId"+ : "SELECT days FROM notification_settings WHERE user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $days = $row['days'];+ if ($hasPeriodSummaryColumn) {+ $periodSummaryAtPeriodStart = (int) ($row['period_summary_at_period_start'] ?? 0);+ }+ }++ // 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();++ 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"] : "[email protected]";+ $email['otherEmails'] = $row["other_emails"];+ }++ // 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();++ $gotify = [];++ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $gotifyNotificationsEnabled = $row['enabled'];+ $gotify['serverUrl'] = $row["url"];+ $gotify['appToken'] = $row["token"];+ $gotify['ignore_ssl'] = $row["ignore_ssl"];+ }++ // 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)) {+ $telegramNotificationsEnabled = $row['enabled'];+ $telegram['botToken'] = $row["bot_token"];+ $telegram['chatId'] = $row["chat_id"];+ }+ // Check if PushPlus notifications are enabled and get the settings+ $query = "SELECT * FROM pushplus_notifications WHERE user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $pushplusNotificationsEnabled = $row['enabled'];+ $pushplus['token'] = $row["token"];+ }+ // Check if Mattermost notifications are enabled and get the settings+ $query = "SELECT * FROM mattermost_notifications WHERE user_id = :userID";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userID', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $mattermostNotificationsEnabled = $row['enabled'];+ $mattermost['webhook_url'] = $row['webhook_url'];+ $mattermost['bot_username'] = $row['bot_username'];+ $mattermost['bot_icon_emoji'] = $row['bot_icon_emoji'];+ }++ // 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 Ntfy 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"];+ $ntfy['ignore_ssl'] = $row["ignore_ssl"];+ }++ // 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['ignore_ssl'] = $row["ignore_ssl"];+ }++ // Check if Serverchan notifications are enabled and get the settings+ $query = "SELECT * FROM serverchan_notifications WHERE user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $serverchanNotificationsEnabled = $row['enabled'];+ $serverchan['sendkey'] = $row['sendkey'];+ }++ $notificationsEnabled = $emailNotificationsEnabled || $gotifyNotificationsEnabled || $telegramNotificationsEnabled ||+ $webhookNotificationsEnabled || $pushoverNotificationsEnabled || $discordNotificationsEnabled || $pushplusNotificationsEnabled ||+ $mattermostNotificationsEnabled || $ntfyNotificationsEnabled || $serverchanNotificationsEnabled;++ // If no notifications are enabled, no need to run+ if (!$notificationsEnabled) {+ if (php_sapi_name() !== 'cli') {+ echo "Notifications are disabled. No need to run.<br />";+ }+ 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;+ }++ // 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();++ $household = [];+ while ($rowHousehold = $resultHousehold->fetchArray(SQLITE3_ASSOC)) {+ $household[$rowHousehold['id']] = $rowHousehold;+ }++ // Get all categories+ $query = "SELECT * FROM categories WHERE user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $resultCategories = $stmt->execute();++ $categories = [];+ while ($rowCategory = $resultCategories->fetchArray(SQLITE3_ASSOC)) {+ $categories[$rowCategory['id']] = $rowCategory;+ }++ $currentDate = new DateTime('now');++ $query = "SELECT main_currency, period_budget, budget_period_type, budget_period_anchor_date FROM user WHERE id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();+ $userBudgetConfig = $result->fetchArray(SQLITE3_ASSOC);++ $mainCurrencyId = $userBudgetConfig['main_currency'];+ $budgetPeriodType = sanitizeBudgetPeriodType($userBudgetConfig['budget_period_type'] ?? 'monthly');+ $budgetPeriodAnchorDate = sanitizeBudgetAnchorDate($userBudgetConfig['budget_period_anchor_date'] ?? getDefaultBudgetAnchorDate());+ $activeBudgetPeriod = getActiveBudgetPeriod($currentDate, $budgetPeriodType, $budgetPeriodAnchorDate);+ $isPeriodStart = $activeBudgetPeriod['start']->format('Y-m-d') === $currentDate->format('Y-m-d');++ $query = "SELECT price, currency_id, next_payment, cycle, frequency, inactive, auto_renew FROM subscriptions WHERE user_id = :userId AND inactive = 0";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();+ $periodSubscriptions = [];+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $periodSubscriptions[] = $row;+ }++ $amountNeededThisPeriod = computeAmountNeededInPeriod($periodSubscriptions, $currentDate, $activeBudgetPeriod['end'], $db, $userId);+ $mainCurrencyCode = $currencies[$mainCurrencyId]['code'] ?? 'USD';+ $mainCurrencySymbol = $currencies[$mainCurrencyId]['symbol'] ?? '$';+ $periodSummaryLine = translate('amount_for_pay_period', $i18n) . ": " . formatPrice($amountNeededThisPeriod, $mainCurrencyCode, $mainCurrencySymbol);++ if (!empty($userBudgetConfig['period_budget']) && $userBudgetConfig['period_budget'] > 0) {+ $remaining = max(0, $userBudgetConfig['period_budget'] - $amountNeededThisPeriod);+ $periodSummaryLine .= " | " . translate('remaining', $i18n) . ": " . formatPrice($remaining, $mainCurrencyCode, $mainCurrencySymbol);+ }++ $sendPeriodStartSummaryOnly = $periodSummaryAtPeriodStart === 1 && $isPeriodStart;++ $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;+ while ($rowSubscription = $resultSubscriptions->fetchArray(SQLITE3_ASSOC)) {+ if ($rowSubscription['notify_days_before'] !== -1) {+ $daysToCompare = $rowSubscription['notify_days_before'];+ } else {+ $daysToCompare = $days;+ }+ $nextPaymentDate = new DateTime($rowSubscription['next_payment']);++ $difference = $currentDate->diff($nextPaymentDate)->days;+ if ($nextPaymentDate > $currentDate) {+ $difference += 1;+ }++ if ($difference === $daysToCompare && $nextPaymentDate->format('Y-m-d') >= $currentDate->format('Y-m-d')) {+ echo "Subscription: " . $rowSubscription['name'] . "<br />";+ echo "Next payment date: " . $nextPaymentDate->format('Y-m-d') . "<br />";+ echo "Current date: " . $currentDate->format('Y-m-d') . "<br />";+ echo "Difference: " . $difference . "<br /><br />";+ $notify[$rowSubscription['payer_user_id']][$i]['name'] = html_entity_decode($rowSubscription['name'], ENT_QUOTES, 'UTF-8');+ $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]['currency_symbol'] = $currencies[$rowSubscription['currency_id']]['symbol'];+ $notify[$rowSubscription['payer_user_id']][$i]['formatted_price'] = formatPrice($rowSubscription['price'], $currencies[$rowSubscription['currency_id']]['code'], $currencies[$rowSubscription['currency_id']]['symbol']);+ $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;+ $notify[$rowSubscription['payer_user_id']][$i]['url'] = $rowSubscription['url'];+ $notify[$rowSubscription['payer_user_id']][$i]['notes'] = $rowSubscription['notes'];+ $i++;+ }+ }++ if (empty($notify) && $sendPeriodStartSummaryOnly) {+ $defaultPayerUserId = array_key_first($household);+ if ($defaultPayerUserId !== null) {+ $notify[$defaultPayerUserId] = [];+ }+ }++ if (!empty($notify)) {++ // Email notifications if enabled+ if ($emailNotificationsEnabled) {+ // Re-validate at send time: a save-time check alone is bypassable via+ // DNS rebinding between when the host was saved and when the cron fires.+ if (!validate_smtp_host($email['smtpAddress'], (int) $email['smtpPort'], $db)) {+ echo "SSRF attempt detected for SMTP host. Email notifications not sent.<br />";+ } else {++ $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'];++ foreach ($notify as $userId => $perUser) {+ $message = buildNotificationMessage("", $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($message === "") {+ continue;+ }++ $smtpAuth = (isset($email["smtpUsername"]) && $email["smtpUsername"] != "") || (isset($email["smtpPassword"]) && $email["smtpPassword"] != "");++ $mail = new PHPMailer(true);+ $mail->CharSet = "UTF-8";+ $mail->isSMTP();+ $mail->Timeout = 15;++ $mail->Host = $email['smtpAddress'];+ $mail->SMTPAuth = $smtpAuth;++ if ($smtpAuth) {+ $mail->Username = $email['smtpUsername'];+ $mail->Password = $email['smtpPassword'];+ }++ if ($email['encryption'] != "none") {+ $mail->SMTPSecure = $email['encryption'];+ } else {+ $mail->SMTPSecure = false;+ $mail->SMTPAutoTLS = false;+ }++ $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);++ if (!empty($email['otherEmails'])) {+ $list = explode(';', $email['otherEmails']);++ // Avoid duplicate emails+ $list = array_unique($list);+ $list = array_filter($list, function ($value) use ($emailaddress) {+ return $value !== $emailaddress;+ });++ foreach ($list as $value) {+ $mail->addCC(trim($value));+ }+ }++ $mail->Subject = 'Wallos Notification';+ $mail->Body = $message;++ if ($mail->send()) {+ echo "Email Notifications sent<br />";+ } else {+ echo "Error sending notifications: " . $mail->ErrorInfo . "<br />";+ }+ }+ }+ }++ // Discord notifications if enabled+ if ($discordNotificationsEnabled) {+ $ssrf = is_url_safe_for_ssrf($discord['webhook_url'], $db, $userId);+ if (!$ssrf) {+ echo "SSRF attempt detected for Discord webhook URL. Notifications not sent.<br />";+ } else {+ 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);++ $name = $user['name'] ?? "";+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($message === "") {+ continue;+ }++ $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'];+ }++ $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_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);++ $response = curl_exec($ch);++ if ($response === false) {+ echo "Error sending notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Discord Notifications sent<br />";+ }++ unset($ch);+ }+ }+ }++ // Gotify notifications if enabled+ if ($gotifyNotificationsEnabled) {+ $ssrf = is_url_safe_for_ssrf($gotify['serverUrl'], $db, $userId);+ if (!$ssrf) {+ echo "SSRF attempt detected for Gotify server URL. Notifications not sent.<br />";+ } else {+ 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);++ $name = $user['name'] ?? "";+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($message === "") {+ continue;+ }++ $data = array(+ 'message' => $message,+ 'priority' => 5+ );++ $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_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);+ curl_setopt(+ $ch,+ CURLOPT_HTTPHEADER,+ array(+ 'Content-Type: application/json',+ 'Content-Length: ' . strlen($data_string)+ )+ );++ if ($gotify['ignore_ssl']) {+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);+ }+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);++ $result = curl_exec($ch);+ if ($result === false) {+ echo "Error sending notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Gotify Notifications sent<br />";+ }++ unset($ch);+ }+ }+ }++ // 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']) {+ $name = $user['name'];+ } else {+ $name = "";+ }+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($message === "") {+ continue;+ }++ $data = array(+ 'chat_id' => $telegram['chatId'],+ 'text' => mb_convert_encoding($message, 'UTF-8', 'auto')+ );++ $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_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);+ 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) . "<br />";+ } else {+ echo "Telegram Notifications sent<br />";+ }++ unset($ch);+ }+ }+++ // PushPlus notifications if enabled+ if ($pushplusNotificationsEnabled) {+ 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);++ // Build Message Content+ $name = $user['name'] ?? "";+ $messageContent = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($messageContent === "") {+ continue;+ }++ // Prepare PushPlus Data+ $data = array(+ 'token' => $pushplus['token'],+ 'title' => '订阅续期提醒 - Wallos',+ 'content' => mb_convert_encoding($messageContent, 'UTF-8', 'auto'),+ 'template' => 'json'+ );++ $data_string = json_encode($data);++ $ch = curl_init('https://www.pushplus.plus/send');+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");+ curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);+ curl_setopt(+ $ch,+ CURLOPT_HTTPHEADER,+ array(+ 'Content-Type: application/json'+ ),+ );++ $result = curl_exec($ch);+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);++ if ($result === false) {+ echo "Error sending PushPlus notifications: " . curl_error($ch) . "<br />";+ } else {+ $resultData = json_decode($result, true);+ if (isset($resultData['code']) && $resultData['code'] == 200) {+ echo "PushPlus Notifications sent successfully<br />";+ } else {+ $errorMsg = isset($resultData['msg']) ? $resultData['msg'] : 'Unknown error';+ echo "PushPlus API error: " . $errorMsg . "<br />";+ }+ }+ unset($ch);+ }+ }++ // Mattermost notifications if enabled+ if ($mattermostNotificationsEnabled) {+ $ssrf = is_url_safe_for_ssrf($mattermost['webhook_url'], $db, $userId);+ if (!$ssrf) {+ echo "SSRF attempt detected for Mattermost webhook URL. Notifications not sent.<br />";+ } else {+ 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);++ // Build Message Content+ $name = $user['name'] ?? "";+ $messageContent = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($messageContent === "") {+ continue;+ }+ // Prepare Mattermost Data+ $webhook_url = $mattermost['webhook_url'];+ $data = array(+ 'username' => $mattermost['bot_username'],+ 'icon_emoji' => $mattermost['bot_icon_emoji'],+ 'text' => mb_convert_encoding($messageContent, 'UTF-8', 'auto'),+ );++ $data_string = json_encode($data);++ $ch = curl_init();+ curl_setopt($ch, CURLOPT_URL, $webhook_url);+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");+ curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);+ curl_setopt(+ $ch,+ CURLOPT_HTTPHEADER,+ array(+ 'Content-Type: application/json'+ ),+ );+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);++ $result = curl_exec($ch);+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);++ if ($result === false) {+ echo "Error sending Mattermost notifications: " . curl_error($ch) . "<br />";+ } else {+ $resultData = json_decode($result, true);+ if (isset($resultData['code']) && $resultData['code'] == 200) {+ echo "Mattermost Notifications sent successfully<br />";+ } else {+ $errorMsg = isset($resultData['msg']) ? $resultData['msg'] : 'Unknown error';+ echo "Mattermost API error: " . $errorMsg . "<br />";+ }+ }+ unset($ch);+ }+ }+ }++ // 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']) {+ $name = $user['name'];+ } else {+ $name = "";+ }+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($message === "") {+ continue;+ }++ $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_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);++ $result = curl_exec($ch);++ if ($result === false) {+ echo "Error sending notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Pushover Notifications sent<br />";+ }++ unset($ch);+ }+ }++ // Ntfy notifications if enabled+ if ($ntfyNotificationsEnabled) {+ $ssrf = is_url_safe_for_ssrf($ntfy['host'], $db, $userId);+ if (!$ssrf) {+ echo "SSRF attempt detected for Ntfy host URL. Notifications not sent.<br />";+ } else {+ 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);++ $name = $user['name'] ?? "";+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($message === "") {+ continue;+ }++ $headers = json_decode($ntfy["headers"], true);+ $customheaders = [];++ if (is_array($headers)) {+ $customheaders = array_map(function ($key, $value) {+ return "$key: $value";+ }, array_keys($headers), $headers);+ }++ $ch = curl_init();++ $ntfyHost = rtrim($ntfy["host"], '/');+ $ntfyTopic = $ntfy['topic'];++ curl_setopt($ch, CURLOPT_URL, $ntfyHost . '/' . $ntfyTopic);+ curl_setopt($ch, CURLOPT_POST, 1);+ curl_setopt($ch, CURLOPT_POSTFIELDS, $message);+ $ntfyHeaders = array_merge(['Content-Type: text/plain; charset=utf-8'], $customheaders);+ curl_setopt($ch, CURLOPT_HTTPHEADER, $ntfyHeaders);+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);++ if ($ntfy['ignore_ssl']) {+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);+ }+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);++ $response = curl_exec($ch);++ if ($response === false) {+ echo "Error sending notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Ntfy Notifications sent<br />";+ }++ unset($ch);+ }+ }+ }++ // Webhook notifications if enabled+ if ($webhookNotificationsEnabled) {+ $ssrf = is_url_safe_for_ssrf($webhook['url'], $db, $userId);+ if (!$ssrf) {+ echo "SSRF attempt detected for webhook URL. Notifications not sent.<br />";;+ } else {+ 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'];+ }++ foreach ($perUser as $subscription) {+ // Ensure the payload is reset for each subscription+ $payload = $webhook['payload'];+ $payload = str_replace("{{days_until}}", $days, $payload);+ $payload = str_replace("{{subscription_name}}", $subscription['name'], $payload);+ $payload = str_replace("{{subscription_price}}", $subscription['formatted_price'], $payload);+ $payload = str_replace("{{subscription_currency}}", $subscription['currency'], $payload);+ $payload = str_replace("{{subscription_category}}", $subscription['category'], $payload);+ $payload = str_replace("{{subscription_payer}}", $payer, $payload); // Use $payer instead of $subscription['payer']+ $payload = str_replace("{{subscription_date}}", $subscription['date'], $payload);+ $payload = str_replace("{{subscription_days_until_payment}}", $subscription['days'], $payload);+ $payload = str_replace("{{subscription_url}}", $subscription['url'], $payload);+ $payload = str_replace("{{subscription_notes}}", $subscription['notes'], $payload);++ // Initialize cURL for each subscription+ $ch = curl_init();+ curl_setopt($ch, CURLOPT_URL, $webhook['url']);+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook['request_method']);+ curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);++ // Add headers if they exist+ if (!empty($webhook['headers'])) {+ $customheaders = json_decode($webhook["headers"], true);+ curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);+ }++ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);++ // Handle SSL settings+ if ($webhook['ignore_ssl']) {+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);+ }+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);++ // Execute the cURL request+ $response = curl_exec($ch);+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);++ if ($response === false || $httpCode >= 400) {+ echo "Error sending notifications: " . curl_error($ch) . "<br />";+ } else {+ echo "Webhook Notification sent for subscription: " . $subscription['name'] . "<br />";+ }++ unset($ch);++ usleep(1000000); // 1s delay between requests+ }+ }+ }+ }++ // Serverchan notifications if enabled+ if ($serverchanNotificationsEnabled) {+ 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 = 'Wallos Notification';+ $name = $user['name'] ?? "";+ $message = buildNotificationMessage($name, $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);+ if ($message === "") {+ continue;+ }++ // Build Serverchan request+ $postdata = http_build_query(array('text' => $title, 'desp' => $message));++ $sendkey = $serverchan['sendkey'];+ if (strpos($sendkey, 'sctp') === 0) {+ preg_match('/^sctp(\d+)t/', $sendkey, $matches);+ $num = $matches[1] ?? '';+ $url = "https://{$num}.push.ft07.com/send/{$sendkey}.send";+ } else {+ $url = "https://sctapi.ftqq.com/{$sendkey}.send";+ }++ $ch = curl_init();+ curl_setopt($ch, CURLOPT_URL, $url);+ curl_setopt($ch, CURLOPT_POST, 1);+ curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);+ curl_setopt($ch, CURLOPT_HTTPHEADER, [+ 'Content-Type: application/x-www-form-urlencoded'+ ]);+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);++ $response = curl_exec($ch);+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);++ if ($response === false || $httpCode >= 400) {+ $errorMessage = $response === false ? curl_error($ch) : $httpCode;+ unset($ch);+ echo "Error sending Serverchan notifications: " . $errorMessage . "<br />";+ } else {+ unset($ch);+ echo "Serverchan Notifications sent<br />";+ }+ }+ }++ } else {+ if (php_sapi_name() !== 'cli') {+ echo "Nothing to notify.<br />";+ }+ }++ }+}\ No newline at end of filediff --git a/endpoints/cronjobs/sendresetpasswordemails.php b/endpoints/cronjobs/sendresetpasswordemails.phpindex d470fbd..7792d13 100644--- a/endpoints/cronjobs/sendresetpasswordemails.php+++ b/endpoints/cronjobs/sendresetpasswordemails.php@@ -40,6 +40,7 @@ if ($rows) {$mail = new PHPMailer(true);$mail->isSMTP();+ $mail->Timeout = 15;$mail->Host = $smtpAddress;$mail->SMTPAuth = $smtpAuth;if ($smtpAuth) {diff --git a/endpoints/cronjobs/sendverificationemails.php b/endpoints/cronjobs/sendverificationemails.phpindex dc9d716..841e87d 100644--- a/endpoints/cronjobs/sendverificationemails.php+++ b/endpoints/cronjobs/sendverificationemails.php@@ -47,6 +47,7 @@ if ($rows) {$mail = new PHPMailer(true);$mail->isSMTP();+ $mail->Timeout = 15;$mail->Host = $smtpAddress;$mail->SMTPAuth = $smtpAuth;if ($smtpAuth) {diff --git a/endpoints/notifications/testdiscordnotifications.php b/endpoints/notifications/testdiscordnotifications.phpindex c99dd4d..2b832d9 100644--- a/endpoints/notifications/testdiscordnotifications.php+++ b/endpoints/notifications/testdiscordnotifications.php@@ -71,6 +71,8 @@ if ('Content-Type: application/json']);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);// Execute the request$response = curl_exec($ch);diff --git a/endpoints/notifications/testemailnotifications.php b/endpoints/notifications/testemailnotifications.phpindex eb4ba3a..b71ccb6 100644--- a/endpoints/notifications/testemailnotifications.php+++ b/endpoints/notifications/testemailnotifications.php@@ -5,7 +5,7 @@ use PHPMailer\PHPMailer\SMTP;use PHPMailer\PHPMailer\Exception;require_once '../../includes/connect_endpoint.php';-require_once '../../includes/validate_endpoint_admin.php';+require_once '../../includes/validate_endpoint.php';require_once '../../includes/ssrf_helper.php';$postData = file_get_contents("php://input");@@ -55,6 +55,7 @@ if ($mail = new PHPMailer(true);$mail->CharSet = "UTF-8";$mail->isSMTP();+ $mail->Timeout = 15;$mail->Host = $smtpAddress;$mail->SMTPAuth = $smtpAuth;diff --git a/endpoints/notifications/testgotifynotifications.php b/endpoints/notifications/testgotifynotifications.phpindex e00ecb6..1f13892 100644--- a/endpoints/notifications/testgotifynotifications.php+++ b/endpoints/notifications/testgotifynotifications.php@@ -54,6 +54,8 @@ if ('priority' => $priority,]));curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);if ($ignore_ssl) {curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);diff --git a/endpoints/notifications/testmattermostnotifications.php b/endpoints/notifications/testmattermostnotifications.phpindex e814567..376241b 100755--- a/endpoints/notifications/testmattermostnotifications.php+++ b/endpoints/notifications/testmattermostnotifications.php@@ -65,6 +65,8 @@ if ('Content-Type: application/json']);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);// Execute the request$response = curl_exec($ch);diff --git a/endpoints/notifications/testntfynotifications.php b/endpoints/notifications/testntfynotifications.phpindex ff22b73..0773786 100644--- a/endpoints/notifications/testntfynotifications.php+++ b/endpoints/notifications/testntfynotifications.php@@ -58,6 +58,8 @@ if (curl_setopt($ch, CURLOPT_POSTFIELDS, $message);curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);if ($ignore_ssl) {curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);diff --git a/endpoints/notifications/testpushovernotifications.php b/endpoints/notifications/testpushovernotifications.phpindex 714edc9..4ce1531 100644--- a/endpoints/notifications/testpushovernotifications.php+++ b/endpoints/notifications/testpushovernotifications.php@@ -33,6 +33,8 @@ if ('message' => $message,]));curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);// Execute the request$response = curl_exec($ch);diff --git a/endpoints/notifications/testpushplusnotifications.php b/endpoints/notifications/testpushplusnotifications.phpindex 110649c..57a5f71 100644--- a/endpoints/notifications/testpushplusnotifications.php+++ b/endpoints/notifications/testpushplusnotifications.php@@ -36,7 +36,8 @@ if (!isset($data["token"]) || $data["token"] == "") {CURLOPT_HTTPHEADER => ['Content-Type: application/json'],- CURLOPT_TIMEOUT => 10+ CURLOPT_TIMEOUT => 10,+ CURLOPT_CONNECTTIMEOUT => 5]);// Execute the requestdiff --git a/endpoints/notifications/testserverchannotifications.php b/endpoints/notifications/testserverchannotifications.phpindex 3b4329e..c20acd7 100644--- a/endpoints/notifications/testserverchannotifications.php+++ b/endpoints/notifications/testserverchannotifications.php@@ -30,7 +30,8 @@ function sc_send($text, $desp = '', $key = '') {$opts = array('http' => array('method' => 'POST','header' => 'Content-type: application/x-www-form-urlencoded',- 'content' => $postdata+ 'content' => $postdata,+ 'timeout' => 15));$context = stream_context_create($opts);diff --git a/endpoints/notifications/testtelegramnotifications.php b/endpoints/notifications/testtelegramnotifications.phpindex 29460a8..05ef477 100644--- a/endpoints/notifications/testtelegramnotifications.php+++ b/endpoints/notifications/testtelegramnotifications.php@@ -32,6 +32,8 @@ if ('text' => $message,]));curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);// Execute the request$response = curl_exec($ch);diff --git a/endpoints/notifications/testwebhooknotifications.php b/endpoints/notifications/testwebhooknotifications.phpindex 1e03283..7245650 100644--- a/endpoints/notifications/testwebhooknotifications.php+++ b/endpoints/notifications/testwebhooknotifications.php@@ -72,6 +72,8 @@ if (curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);}curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);if ($ignore_ssl) {curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);diff --git a/includes/header.php b/includes/header.phpindex 0054b2b..4a28bc6 100644--- a/includes/header.php+++ b/includes/header.php@@ -94,9 +94,6 @@ $mobileNavigation = $settings['mobile_nav'] ? "mobile-navigation" : "";<link rel="manifest" href="manifest.json" crossorigin="use-credentials"><link rel="stylesheet" href="styles/theme.css?<?= $version ?>"><link rel="stylesheet" href="styles/styles.css?<?= $version ?>">- <?php if ($languages[$lang]['dir'] === 'rtl') : ?>- <link rel="stylesheet" href="styles/rtl.css?<?= $version ?>">- <?php endif; ?><link rel="stylesheet" href="styles/dark-theme.css?<?= $version ?>" id="dark-theme" <?= $theme != "dark" ? "disabled" : "" ?>><link rel="stylesheet" href="styles/themes/red.css?<?= $version ?>" id="red-theme" <?= $colorTheme != "red" ? "disabled" : "" ?>><link rel="stylesheet" href="styles/themes/green.css?<?= $version ?>" id="green-theme" <?= $colorTheme != "green" ? "disabled" : "" ?>>diff --git a/includes/i18n/ar.php b/includes/i18n/ar.phpindex d684ee1..65dfdd0 100644--- a/includes/i18n/ar.php+++ b/includes/i18n/ar.php@@ -202,6 +202,19 @@ $i18n = ["api_key_info" => "يُستخدم مفتاح API للوصول إلى الواجهة البرمجية. احتفظ به سرًا.",// صفحة الإعدادات"monthly_budget" => "الميزانية الشهرية",+ "monthly_budget_info" => "تتم مقارنة الميزانية الشهرية بإجمالي التكلفة الشهرية لاشتراكاتك.",+ "period_budget" => "ميزانية الفترة",+ "period_budget_info" => "تتابع ميزانية الفترة ما يجب عليك دفعه خلال فترة الميزانية التي اخترتها.",+ "budget_period" => "فترة الميزانية",+ "budget_anchor_date" => "تاريخ البداية",+ "fortnightly" => "أسبوعين",+ "cost_vs_monthly_budget" => "التكلفة مقابل الميزانية الشهرية",+ "cost_vs_period_budget" => "التكلفة مقابل ميزانية الفترة",+ "send_period_summary_at_period_start" => "إرسال ملخص في بداية كل فترة دفع",+ "amount_for_pay_period" => "المبلغ لفترة الدفع",+ "remaining" => "المتبقي",+ "amount_needed_this_period" => "المبلغ المطلوب في هذه الفترة",+ "current_period" => "الفترة الحالية","budget_info" => "تُستخدم الميزانية الشهرية في حساب الإحصاءات","household" => "أفراد الأسرة","save_member" => "حفظ العضو",@@ -279,6 +292,9 @@ $i18n = ["manually" => "يدويًا","coming_soon" => "قريبًا","invalid_host" => "المضيف غير صالح",+ "ai_provider_error" => "خطأ في مزود الذكاء الاصطناعي",+ "ai_invalid_response" => "أعاد مزود الذكاء الاصطناعي استجابة غير صالحة.",+ "ai_invalid_json_response" => "لم تحتوِ استجابة الذكاء الاصطناعي على توصيات صالحة.","ai_recommendations_info" => "تُنشأ توصيات الذكاء الاصطناعي استنادًا إلى اشتراكاتك وأفراد أسرتك.","may_take_time" => "قد يستغرق إنشاء التوصيات بعض الوقت بحسب مزود الخدمة والنموذج وعدد الاشتراكات.","recommendations_visible_on_dashboard" => "ستظهر التوصيات في لوحة التحكم.",@@ -431,6 +447,7 @@ $i18n = ["security_settings" => "إعدادات الأمان","ssrf_protection_info" => "للوقاية من هجمات تزوير الطلبات من جانب الخادم (SSRF)، يحظر Wallos افتراضيًا إشعارات Webhook المرسلة إلى عناوين الشبكات الخاصة أو الداخلية.","local_webhook_info" => "إذا احتجت إلى إرسال Webhooks إلى خدمات محلية (مثل Home Assistant أو Gotify أو Node-RED)، فأدخل عناوين IP أو أسماء المضيفين أعلاه في قائمة مفصولة بفواصل (مثل: <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "يتم التحكم به عبر متغير البيئة SSRF_ALLOWLIST.","maintenance_tasks" => "مهام الصيانة","orphaned_logos" => "الشعارات غير المرتبطة","update" => "تحديث",diff --git a/includes/i18n/ca.php b/includes/i18n/ca.phpindex 0e33c22..7ac392d 100644--- a/includes/i18n/ca.php+++ b/includes/i18n/ca.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "Manualment","coming_soon" => "Pròximament","invalid_host" => "Host Invàid",+ "ai_provider_error" => "Error del proveïdor d'IA",+ "ai_invalid_response" => "El proveïdor d'IA ha retornat una resposta no vàlida.",+ "ai_invalid_json_response" => "La resposta de la IA no contenia recomanacions vàlides.","ai_recommendations_info" => "Les recomanacions per IA es generen en funció de les subscripcions i els membres de la llar.","may_take_time" => "En funció del proveïdor, model i número de subscripcions, la generació de recomanacions pot trigar un temps.","recommendations_visible_on_dashboard" => "Les recomanacions seran visibles al taulell.",@@ -417,6 +420,7 @@ $i18n = ["security_settings" => "Configuració de seguretat","ssrf_protection_info" => "Per evitar atacs de Server-Side Request Forgery (SSRF), Wallos bloqueja per defecte les notificacions webhook a adreces de xarxa privades o internes.","local_webhook_info" => "Si necessiteu enviar webhooks a serveis locals (com Home Assistant, Gotify o Node-RED), introduïu les seves adreces IP o noms d'amfitrió anteriorment com una llista separada per comes (p. ex., <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Gestionat per la variable d'entorn SSRF_ALLOWLIST.","maintenance_tasks" => "Tasques de Manteniment","orphaned_logos" => "Logotips orfes","update" => "Actualitzar",diff --git a/includes/i18n/cs.php b/includes/i18n/cs.phpindex 600680f..9074975 100644--- a/includes/i18n/cs.php+++ b/includes/i18n/cs.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "Manuálně","coming_soon" => "Brzy bude k dispozici","invalid_host" => "Neplatný hostitel",+ "ai_provider_error" => "Chyba poskytovatele AI",+ "ai_invalid_response" => "Poskytovatel AI vrátil neplatnou odpověď.",+ "ai_invalid_json_response" => "Odpověď AI neobsahovala platná doporučení.","ai_recommendations_info" => "AI Doporučení jsou generována na základě vašich předplatných a členů domácnosti.","may_take_time" => "V závislosti na poskytovateli, modelu a počtu předplatných může generování doporučení trvat nějakou dobu.","recommendations_visible_on_dashboard" => "Doporučení budou viditelná na řídicím panelu.",@@ -417,6 +420,7 @@ $i18n = ["security_settings" => "Nastavení zabezpečení","ssrf_protection_info" => "Aby se předešlo útokům Server-Side Request Forgery (SSRF), Wallos ve výchozím nastavení blokuje webhook notifikace směrem na soukromé nebo interní síťové adresy.","local_webhook_info" => "Pokud potřebujete posílat webhooks na lokální služby (např. Home Assistant, Gotify nebo Node-RED), zadejte jejich IP adresy nebo názvy hostitelů výše jako seznam oddělený čárkami (např. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Řízeno proměnnou prostředí SSRF_ALLOWLIST.","maintenance_tasks" => "Úkoly údržby","orphaned_logos" => "Osiřelá loga","update" => "Aktualizace",diff --git a/includes/i18n/da.php b/includes/i18n/da.phpindex 703911a..6e0b121 100644--- a/includes/i18n/da.php+++ b/includes/i18n/da.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "Manuelt","coming_soon" => "Kommer snart","invalid_host" => "Ugyldig vært",+ "ai_provider_error" => "AI-udbyderfejl",+ "ai_invalid_response" => "AI-udbyderen returnerede et ugyldigt svar.",+ "ai_invalid_json_response" => "AI-svaret indeholdt ikke gyldige anbefalinger.","ai_recommendations_info" => "AI anbefalinger genereres baseret på dine abonnementer og husstandsmedlemmer.","may_take_time" => "Afhængigt af udbyderen, modellen og antallet af abonnementer kan genereringen af anbefalinger tage noget tid.","recommendations_visible_on_dashboard" => "Anbefalinger vil være synlige på instrumentbrættet.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Sikkerhedsindstillinger","ssrf_protection_info" => "For at forhindre Server-Side Request Forgery (SSRF) angreb blokerer Wallos som standard webhook-notifikationer til private eller interne netværksadresser.","local_webhook_info" => "Hvis du skal sende webhooks til lokale tjenester (som Home Assistant, Gotify eller Node-RED), indtast deres IP-adresser eller værtsnavne ovenfor som en kommasepareret liste (fx <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Administreres af miljøvariablen SSRF_ALLOWLIST.","smtp_usage_info" => "Vil blive brugt til adgangskodenulstilling og andre systemmails.",// Maintenance Tasks"maintenance_tasks" => "Vedligeholdelsesopgaver",diff --git a/includes/i18n/de.php b/includes/i18n/de.phpindex 3b91fc1..ef64fb8 100644--- a/includes/i18n/de.php+++ b/includes/i18n/de.php@@ -419,6 +419,7 @@ $i18n = ["security_settings" => "Sicherheitseinstellungen","ssrf_protection_info" => "Um Server-Side Request Forgery (SSRF)-Angriffe zu verhindern, blockiert Wallos standardmäßig Webhook-Benachrichtigungen an private oder interne Netzwerkadressen.","local_webhook_info" => "Wenn Sie Webhooks an lokale Dienste (z. B. Home Assistant, Gotify oder Node-RED) senden müssen, geben Sie deren IP-Adressen oder Hostnamen oben als durch Kommas getrennte Liste ein (z. B. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Wird durch die Umgebungsvariable SSRF_ALLOWLIST verwaltet.","maintenance_tasks" => "Wartungsaufgaben","orphaned_logos" => "Verwaiste Logos","update" => "Update",diff --git a/includes/i18n/el.php b/includes/i18n/el.phpindex d00fd3f..2f5c7bf 100644--- a/includes/i18n/el.php+++ b/includes/i18n/el.php@@ -265,6 +265,9 @@ $i18n = ["manually" => "Χειροκίνητα","coming_soon" => "Έρχεται σύντομα","invalid_host" => "Μη έγκυρος διακομιστής",+ "ai_provider_error" => "Σφάλμα παρόχου AI",+ "ai_invalid_response" => "Ο πάροχος AI επέστρεψε μη έγκυρη απάντηση.",+ "ai_invalid_json_response" => "Η απάντηση AI δεν περιείχε έγκυρες προτάσεις.","ai_recommendations_info" => "AI προτάσεις δημιουργούνται με βάση τα συνδρομητικά σας και τα μέλη του νοικοκυριού σας.","may_take_time" => "Ανάλογα με τον πάροχο, το μοντέλο και τον αριθμό των συνδρομών, η δημιουργία προτάσεων μπορεί να διαρκέσει κάποιο χρόνο.","recommendations_visible_on_dashboard" => "Οι προτάσεις θα είναι ορατές στον πίνακα ελέγχου.",@@ -413,6 +416,7 @@ $i18n = ["security_settings" => "Ρυθμίσεις ασφάλειας","ssrf_protection_info" => "Για να αποτρέψετε επιθέσεις Server-Side Request Forgery (SSRF), το Wallos αποκλείει από προεπιλογή τις ειδοποιήσεις webhook σε ιδιωτικές ή εσωτερικές διευθύνσεις δικτύου.","local_webhook_info" => "Εάν πρέπει να στείλετε webhooks σε τοπικές υπηρεσίες (όπως Home Assistant, Gotify ή Node-RED), εισάγετε τις διευθύνσεις IP ή τα ονόματα κεντρικού υπολογιστή τους παραπάνω ως λίστα χωρισμένη με κόμματα (π.χ. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Διαχειρίζεται από τη μεταβλητή περιβάλλοντος SSRF_ALLOWLIST.","smtp_usage_info" => "Θα χρησιμοποιηθεί για ανάκτηση κωδικού πρόσβασης και άλλα μηνύματα ηλεκτρονικού ταχυδρομείου συστήματος.","maintenance_tasks" => "Εργασίες συντήρησης","orphaned_logos" => "Ορφανά λογότυπα",diff --git a/includes/i18n/es.php b/includes/i18n/es.phpindex 0547401..94d51dd 100644--- a/includes/i18n/es.php+++ b/includes/i18n/es.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Manualmente","coming_soon" => "Próximamente","invalid_host" => "Host Inválido",+ "ai_provider_error" => "Error del proveedor de IA",+ "ai_invalid_response" => "El proveedor de IA devolvió una respuesta no válida.",+ "ai_invalid_json_response" => "La respuesta de la IA no contenía recomendaciones válidas.","ai_recommendations_info" => "Las recomendaciones de IA se generan en función de sus suscripciones y miembros del hogar.","may_take_time" => "Dependiendo del proveedor, modelo y número de suscripciones, la generación de recomendaciones puede tardar algún tiempo.","recommendations_visible_on_dashboard" => "Las recomendaciones serán visibles en el panel.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Configuración de seguridad","ssrf_protection_info" => "Para evitar ataques de falsificación de solicitudes del lado del servidor (SSRF), Wallos bloquea por defecto las notificaciones webhook a direcciones de red privadas o internas.","local_webhook_info" => "Si necesita enviar webhooks a servicios locales (como Home Assistant, Gotify o Node-RED), introduzca sus direcciones IP o nombres de host arriba como una lista separada por comas (p. ej., <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Gestionado por la variable de entorno SSRF_ALLOWLIST.","maintenance_tasks" => "Tareas de Mantenimiento","orphaned_logos" => "Logotipos huérfanos","update" => "Actualizar",diff --git a/includes/i18n/fr.php b/includes/i18n/fr.phpindex 43f2ae9..bc9768f 100644--- a/includes/i18n/fr.php+++ b/includes/i18n/fr.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Manuellement","coming_soon" => "À venir","invalid_host" => "Hôte invalide",+ "ai_provider_error" => "Erreur du fournisseur d'IA",+ "ai_invalid_response" => "Le fournisseur d'IA a renvoyé une réponse invalide.",+ "ai_invalid_json_response" => "La réponse de l'IA ne contenait pas de recommandations valides.","ai_recommendations_info" => "Les recommandations de l'IA sont générées en fonction de vos abonnements et des membres de votre foyer.","may_take_time" => "En fonction du fournisseur, du modèle et du nombre d'abonnements, la génération de recommandations peut prendre un certain temps.","recommendations_visible_on_dashboard" => "Les recommandations seront visibles sur le tableau de bord.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Paramètres de sécurité","ssrf_protection_info" => "Pour prévenir les attaques Server-Side Request Forgery (SSRF), Wallos bloque par défaut les notifications webhook vers des adresses réseau privées ou internes.","local_webhook_info" => "Si vous devez envoyer des webhooks vers des services locaux (comme Home Assistant, Gotify ou Node-RED), saisissez leurs adresses IP ou noms d'hôte ci-dessus sous forme d'une liste séparée par des virgules (par ex. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Géré par la variable d'environnement SSRF_ALLOWLIST.","maintenance_tasks" => "Tâches de maintenance","orphaned_logos" => "Logos orphelins","update" => "Mise à jour",diff --git a/includes/i18n/hu.php b/includes/i18n/hu.phpindex 7010481..68bb7dc 100644--- a/includes/i18n/hu.php+++ b/includes/i18n/hu.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "Manuálisan","coming_soon" => "Hamarosan","invalid_host" => "Érvénytelen gazdagép",+ "ai_provider_error" => "AI-szolgáltató hiba",+ "ai_invalid_response" => "Az AI-szolgáltató érvénytelen választ küldött.",+ "ai_invalid_json_response" => "Az AI válasz nem tartalmazott érvényes ajánlásokat.","ai_recommendations_info" => "Az AI ajánlások az Ön előfizetései és háztartásának tagjai alapján jönnek létre.","may_take_time" => "A szolgáltatótól, a modelltől és az előfizetések számától függően az ajánlások létrehozása eltarthat egy ideig.","recommendations_visible_on_dashboard" => "Az ajánlások láthatók lesznek a vezérlőpulton.",@@ -417,6 +420,7 @@ $i18n = ["security_settings" => "Biztonsági beállítások","ssrf_protection_info" => "A Server-Side Request Forgery (SSRF) támadások megelőzése érdekében a Wallos alapértelmezés szerint blokkolja a privát vagy belső hálózati címekre küldött webhook értesítéseket.","local_webhook_info" => "Ha webhookokat kell küldenie helyi szolgáltatásoknak (mint a Home Assistant, Gotify vagy Node-RED), adja meg IP-címeiket vagy gazdagépneveiket fentebb vesszővel elválasztva (pl. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Az SSRF_ALLOWLIST környezeti változó kezeli.","maintenance_tasks" => "Karbantartási feladatok","orphaned_logos" => "Árva logók","update" => "Frissítés",diff --git a/includes/i18n/id.php b/includes/i18n/id.phpindex 533cd35..091cd1a 100644--- a/includes/i18n/id.php+++ b/includes/i18n/id.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "Secara Manual","coming_soon" => "Segera Hadir","invalid_host" => "Host Tidak Valid",+ "ai_provider_error" => "Kesalahan penyedia AI",+ "ai_invalid_response" => "Penyedia AI mengembalikan respons yang tidak valid.",+ "ai_invalid_json_response" => "Respons AI tidak berisi rekomendasi yang valid.","ai_recommendations_info" => "Rekomendasi AI dihasilkan berdasarkan langganan dan anggota rumah tangga Anda.","may_take_time" => "Bergantung pada penyedia, model, dan jumlah langganan, pembuatan rekomendasi mungkin memerlukan waktu.","recommendations_visible_on_dashboard" => "Rekomendasi akan terlihat di dasbor.",@@ -417,6 +420,7 @@ $i18n = ["security_settings" => "Pengaturan Keamanan","ssrf_protection_info" => "Untuk mencegah serangan Server-Side Request Forgery (SSRF), Wallos secara default memblokir notifikasi webhook ke alamat jaringan pribadi atau internal.","local_webhook_info" => "Jika Anda perlu mengirim webhook ke layanan lokal (seperti Home Assistant, Gotify, atau Node-RED), masukkan alamat IP atau nama host mereka di atas sebagai daftar yang dipisahkan koma (mis., <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Dikelola oleh variabel lingkungan SSRF_ALLOWLIST.","maintenance_tasks" => "Tugas Pemeliharaan","orphaned_logos" => "Logo Yatim Piatu","update" => "Perbarui",diff --git a/includes/i18n/it.php b/includes/i18n/it.phpindex c4f8a02..bc54ce9 100644--- a/includes/i18n/it.php+++ b/includes/i18n/it.php@@ -273,6 +273,9 @@ $i18n = ["manually" => "Manuale","coming_soon" => "In Arrivo","invalid_host" => "Host Non Valido",+ "ai_provider_error" => "Errore del provider IA",+ "ai_invalid_response" => "Il provider IA ha restituito una risposta non valida.",+ "ai_invalid_json_response" => "La risposta dell'IA non conteneva raccomandazioni valide.","ai_recommendations_info" => "Le raccomandazioni dell'IA sono generate in base ai tuoi abbonamenti e ai membri del tuo nucleo familiare.","may_take_time" => "A seconda del fornitore, del modello e del numero di abbonamenti, la generazione delle raccomandazioni potrebbe richiedere del tempo.","recommendations_visible_on_dashboard" => "Le raccomandazioni saranno visibili sul dashboard.",@@ -433,6 +436,7 @@ $i18n = ["security_settings" => "Impostazioni di sicurezza","ssrf_protection_info" => "Per prevenire attacchi Server-Side Request Forgery (SSRF), Wallos blocca per impostazione predefinita le notifiche webhook verso indirizzi di rete privati o interni.","local_webhook_info" => "Se è necessario inviare webhook a servizi locali (come Home Assistant, Gotify o Node-RED), inserisci i loro indirizzi IP o nomi host sopra come elenco separato da virgole (ad es. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Gestito dalla variabile d'ambiente SSRF_ALLOWLIST.","maintenance_tasks" => "Compiti di manutenzione","orphaned_logos" => "Loghi orfani","update" => "Aggiorna",diff --git a/includes/i18n/ja.php b/includes/i18n/ja.phpindex 94242b5..f41aabb 100644--- a/includes/i18n/ja.php+++ b/includes/i18n/ja.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "手動","coming_soon" => "近日公開","invalid_host" => "無効なホスト",+ "ai_provider_error" => "AIプロバイダーのエラー",+ "ai_invalid_response" => "AIプロバイダーが無効な応答を返しました。",+ "ai_invalid_json_response" => "AIの応答に有効な推奨事項が含まれていませんでした。","ai_recommendations_info" => "AIによる推奨は、あなたの定期購入と世帯メンバーに基づいて生成されます。","may_take_time" => "プロバイダ、モデル、定期購入数によっては、推奨の生成に時間がかかる場合があります。","recommendations_visible_on_dashboard" => "推奨はダッシュボードに表示されます。",@@ -417,6 +420,7 @@ $i18n = ["security_settings" => "セキュリティ設定","ssrf_protection_info" => "Server-Side Request Forgery(SSRF)攻撃を防ぐために、Wallosはデフォルトでプライベートまたは内部ネットワークアドレスへのWebhook通知をブロックします。","local_webhook_info" => "Home Assistant、Gotify、Node-REDなどのローカルサービスにWebhookを送信する必要がある場合は、それらのIPアドレスまたはホスト名を上記にカンマ区切りで入力してください(例:<code>192.168.1.100,192.168.1.101</code>)。",+ "ssrf_allowlist_env_managed" => "SSRF_ALLOWLIST 環境変数によって管理されています。","maintenance_tasks" => "メンテナンスタスク","orphaned_logos" => "孤立したロゴ","update" => "更新",diff --git a/includes/i18n/ko.php b/includes/i18n/ko.phpindex a8d08d0..31358ed 100644--- a/includes/i18n/ko.php+++ b/includes/i18n/ko.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "수동으로","coming_soon" => "곧 출시 예정","invalid_host" => "유효하지 않은 호스트",+ "ai_provider_error" => "AI 제공업체 오류",+ "ai_invalid_response" => "AI 제공업체가 잘못된 응답을 반환했습니다.",+ "ai_invalid_json_response" => "AI 응답에 유효한 추천이 포함되어 있지 않았습니다.","ai_recommendations_info" => "AI 추천은 사용자의 구독과 가구 구성원을 기반으로 생성됩니다.","may_take_time" => "제공자, 모델, 구독 수에 따라 추천 생성에 시간이 걸릴 수 있습니다.","recommendations_visible_on_dashboard" => "추천은 대시보드에서 확인할 수 있습니다.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "보안 설정","ssrf_protection_info" => "서버 측 요청 위조(SSRF) 공격을 방지하기 위해 Wallos는 기본적으로 개인 또는 내부 네트워크 주소로의 webhook 알림을 차단합니다.","local_webhook_info" => "Home Assistant, Gotify 또는 Node-RED와 같은 로컬 서비스로 webhook을 보내야 하는 경우 해당 IP 주소 또는 호스트 이름을 위에 쉼표로 구분된 목록으로 입력하세요(예: <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "SSRF_ALLOWLIST 환경 변수로 관리됩니다.","maintenance_tasks" => "유지보수 작업","orphaned_logos" => "고아 로고","update" => "업데이트",diff --git a/includes/i18n/nl.php b/includes/i18n/nl.phpindex 1ba3811..8607137 100644--- a/includes/i18n/nl.php+++ b/includes/i18n/nl.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "Handmatig","coming_soon" => "Binnenkort beschikbaar","invalid_host" => "Ongeldige host",+ "ai_provider_error" => "AI-providerfout",+ "ai_invalid_response" => "De AI-provider heeft een ongeldig antwoord geretourneerd.",+ "ai_invalid_json_response" => "Het AI-antwoord bevatte geen geldige aanbevelingen.","ai_recommendations_info" => "AI-aanbevelingen worden gegenereerd op basis van je abonnementen en huishoudleden.","may_take_time" => "Afhankelijk van de aanbieder, het model en het aantal abonnementen kan het genereren van aanbevelingen enige tijd duren.","recommendations_visible_on_dashboard" => "Aanbevelingen zijn zichtbaar op het dashboard.",@@ -417,6 +420,7 @@ $i18n = ["security_settings" => "Beveiligingsinstellingen","ssrf_protection_info" => "Om Server-Side Request Forgery (SSRF) aanvallen te voorkomen, blokkeert Wallos standaard webhookmeldingen naar privé- of interne netwerkadressen.","local_webhook_info" => "Als u webhooks naar lokale services moet sturen (zoals Home Assistant, Gotify of Node-RED), voer dan hun IP-adressen of hostnamen hierboven in als een door komma's gescheiden lijst (bijv. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Wordt beheerd door de omgevingsvariabele SSRF_ALLOWLIST.","maintenance_tasks" => "Onderhoudstaken","orphaned_logos" => "Ongebruikte logo's","update" => "Bijwerken",diff --git a/includes/i18n/pl.php b/includes/i18n/pl.phpindex cb12e4b..26dac60 100644--- a/includes/i18n/pl.php+++ b/includes/i18n/pl.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Ręcznie","coming_soon" => "Wkrótce dostępne","invalid_host" => "Nieprawidłowy host",+ "ai_provider_error" => "Błąd dostawcy AI",+ "ai_invalid_response" => "Dostawca AI zwrócił nieprawidłową odpowiedź.",+ "ai_invalid_json_response" => "Odpowiedź AI nie zawierała prawidłowych rekomendacji.","ai_recommendations_info" => "Rekomendacje AI są generowane na podstawie Twoich subskrypcji i członków gospodarstwa domowego.","may_take_time" => "W zależności od dostawcy, modelu i liczby subskrypcji, generowanie rekomendacji może zająć trochę czasu.","recommendations_visible_on_dashboard" => "Rekomendacje będą widoczne na pulpicie.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Ustawienia zabezpieczeń","ssrf_protection_info" => "Aby zapobiec atakom Server-Side Request Forgery (SSRF), Wallos domyślnie blokuje powiadomienia webhook wysyłane na prywatne lub wewnętrzne adresy sieciowe.","local_webhook_info" => "Jeśli musisz wysyłać webhooki do lokalnych usług (np. Home Assistant, Gotify lub Node-RED), wprowadź ich adresy IP lub nazwy hostów powyżej jako listę oddzieloną przecinkami (np. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Zarządzane przez zmienną środowiskową SSRF_ALLOWLIST.","maintenance_tasks" => "Zadania konserwacyjne","orphaned_logos" => "Osierocone logo","update" => "Aktualizacja",diff --git a/includes/i18n/pt.php b/includes/i18n/pt.phpindex d372c65..0a212fd 100644--- a/includes/i18n/pt.php+++ b/includes/i18n/pt.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Manual","coming_soon" => "Em breve","invalid_host" => "Host inválido",+ "ai_provider_error" => "Erro do fornecedor de IA",+ "ai_invalid_response" => "O fornecedor de IA devolveu uma resposta inválida.",+ "ai_invalid_json_response" => "A resposta da IA não continha recomendações válidas.","ai_recommendations_info" => "As recomendações de IA são geradas com base nas suas assinaturas e membros da família.","may_take_time" => "Dependendo do provedor, modelo e número de assinaturas, a geração de recomendações pode levar algum tempo.","recommendations_visible_on_dashboard" => "As recomendações serão visíveis no painel.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Configurações de Segurança","ssrf_protection_info" => "Para evitar ataques Server-Side Request Forgery (SSRF), o Wallos bloqueia por padrão notificações webhook para endereços de rede privados ou internos.","local_webhook_info" => "Se precisar enviar webhooks para serviços locais (como Home Assistant, Gotify ou Node-RED), insira seus endereços IP ou nomes de host acima como uma lista separada por vírgulas (por exemplo <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Gerido pela variável de ambiente SSRF_ALLOWLIST.","maintenance_tasks" => "Tarefas de Manutenção","orphaned_logos" => "Logos Órfãos","update" => "Actualizar",diff --git a/includes/i18n/pt_br.php b/includes/i18n/pt_br.phpindex 873e130..bfa296a 100644--- a/includes/i18n/pt_br.php+++ b/includes/i18n/pt_br.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Manual","coming_soon" => "Em breve","invalid_host" => "Host inválido",+ "ai_provider_error" => "Erro do provedor de IA",+ "ai_invalid_response" => "O provedor de IA retornou uma resposta inválida.",+ "ai_invalid_json_response" => "A resposta da IA não continha recomendações válidas.","ai_recommendations_info" => "As recomendações de IA são geradas com base em suas assinaturas e membros da família.","may_take_time" => "Dependendo do provedor, modelo e número de assinaturas, a geração de recomendações pode levar algum tempo.","recommendations_visible_on_dashboard" => "As recomendações serão visíveis no painel.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Configurações de Segurança","ssrf_protection_info" => "Para evitar ataques Server-Side Request Forgery (SSRF), o Wallos bloqueia por padrão notificações webhook para endereços de rede privados ou internos.","local_webhook_info" => "Se precisar enviar webhooks para serviços locais (como Home Assistant, Gotify ou Node-RED), insira seus endereços IP ou nomes de host acima como uma lista separada por vírgulas (por exemplo <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Gerenciado pela variável de ambiente SSRF_ALLOWLIST.","maintenance_tasks" => "Tarefas de manutenção","orphaned_logos" => "Logos órfãos","update" => "Atualizar",diff --git a/includes/i18n/ro.php b/includes/i18n/ro.phpindex 40fd6fe..e8efd99 100644--- a/includes/i18n/ro.php+++ b/includes/i18n/ro.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "Manual","coming_soon" => "Disponibil curând","invalid_host" => "Host invalid",+ "ai_provider_error" => "Eroare furnizor AI",+ "ai_invalid_response" => "Furnizorul AI a returnat un răspuns nevalid.",+ "ai_invalid_json_response" => "Răspunsul AI nu a conținut recomandări valide.","ai_recommendations_info" => "Recomandările AI sunt generate pe baza abonamentelor dvs. și a membrilor familiei.","may_take_time" => "În funcție de furnizor, model și numărul de abonamente, generarea recomandărilor poate dura ceva timp.","recommendations_visible_on_dashboard" => "Recomandările vor fi vizibile pe panoul Acasă.",@@ -417,6 +420,7 @@ $i18n = ["security_settings" => "Setări de srcuritate","ssrf_protection_info" => "Pentru a preveni atacurile de tip Server-Side Request Forgery (SSRF), Wallos blochează în mod implicit notificările webhook către adrese de rețea private sau interne.","local_webhook_info" => "Dacă trebuie să trimți webhook-uri către servicii locale (cum ar fi Home Assistant, Gotify sau Node-RED), introdu adresele IP sau numele de gazdă ale acestora mai sus, sub forma unei liste separate prin virgule (de exemplu, <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Gestionat de variabila de mediu SSRF_ALLOWLIST.","maintenance_tasks" => "Sarcini întreținere","orphaned_logos" => "Logo-uri fără uz","update" => "Actualizare",diff --git a/includes/i18n/ru.php b/includes/i18n/ru.phpindex edfd79a..e0fc37b 100644--- a/includes/i18n/ru.php+++ b/includes/i18n/ru.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Вручную","coming_soon" => "Скоро","invalid_host" => "Неверный хост",+ "ai_provider_error" => "Ошибка провайдера ИИ",+ "ai_invalid_response" => "Провайдер ИИ вернул недействительный ответ.",+ "ai_invalid_json_response" => "Ответ ИИ не содержал допустимых рекомендаций.","ai_recommendations_info" => "Рекомендации ИИ генерируются на основе ваших подписок и членов семьи.","may_take_time" => "В зависимости от провайдера, модели и количества подписок генерация рекомендаций может занять некоторое время.","recommendations_visible_on_dashboard" => "Рекомендации будут видны на панели управления.",@@ -415,6 +418,7 @@ $i18n = ["security_settings" => "Параметры безопасности","ssrf_protection_info" => "Чтобы предотвратить атаки Server-Side Request Forgery (SSRF), Wallos по умолчанию блокирует уведомления webhook на приватные или внутренние сетевые адреса.","local_webhook_info" => "Если вам нужно отправлять вебхуки на локальные сервисы (например, Home Assistant, Gotify или Node-RED), введите их IP-адреса или имена хостов выше через запятую (например <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Управляется переменной окружения SSRF_ALLOWLIST.","smtp_usage_info" => "Будет использоваться для восстановления пароля и других системных писем.","maintenance_tasks" => "Задачи обслуживания","orphaned_logos" => "Потерянные логотипы",diff --git a/includes/i18n/sl.php b/includes/i18n/sl.phpindex 05915bd..a2274f4 100644--- a/includes/i18n/sl.php+++ b/includes/i18n/sl.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Ročno","coming_soon" => "Kmalu","invalid_host" => "Neveljavna gostiteljska naprava",+ "ai_provider_error" => "Napaka ponudnika AI",+ "ai_invalid_response" => "Ponudnik AI je vrnil neveljaven odgovor.",+ "ai_invalid_json_response" => "Odgovor AI ni vseboval veljavnih priporočil.","ai_recommendations_info" => "Priporočila AI so generirana na podlagi vaših naročnin in članov gospodinjstva.","may_take_time" => "Odvisno od ponudnika, modela in števila naročnin lahko generiranje priporočil traja nekaj časa.","recommendations_visible_on_dashboard" => "Priporočila bodo vidna na nadzorni plošči.",@@ -409,6 +412,7 @@ $i18n = ["security_settings" => "Varnostne nastavitve","ssrf_protection_info" => "Za preprečevanje napadov Server-Side Request Forgery (SSRF) Wallos privzeto blokira webhook obvestila na zasebne ali notranje omrežne naslove.","local_webhook_info" => "Če morate pošiljati webhooke na lokalne storitve (npr. Home Assistant, Gotify ali Node-RED), vnesite njihove IP naslove ali imena gostiteljev zgoraj kot seznam, ločen z vejico (npr. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Upravljano s spremenljivko okolja SSRF_ALLOWLIST.","maintenance_tasks" => "Vzdrževalne naloge","orphaned_logos" => "Osamljeni logotipi","update" => "Posodobi",diff --git a/includes/i18n/sr.php b/includes/i18n/sr.phpindex e2e7e85..426bc36 100644--- a/includes/i18n/sr.php+++ b/includes/i18n/sr.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Ручно","coming_soon" => "Ускоро","invalid_host" => "Неважећи хост",+ "ai_provider_error" => "Грешка AI провајдера",+ "ai_invalid_response" => "AI провајдер је вратио неважећи одговор.",+ "ai_invalid_json_response" => "AI одговор није садржао важеће препоруке.","ai_recommendations_info" => "AI препоруке се генеришу на основу ваших претплата и чланова домаћинства.","may_take_time" => "У зависности од провајдера, модела и броја претплата, генерисање препорука може потрајати.","recommendations_visible_on_dashboard" => "Препоруке ће бити видљиве на контролној табли.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Поставке безбедности","ssrf_protection_info" => "Како би се спречили напади Server-Side Request Forgery (SSRF), Wallos подразумевано блокира webhook обавештења ка приватним или унутрашњим мрежним адресама.","local_webhook_info" => "Ако треба да шаљете вебхуке ка локалним сервисима (нпр. Home Assistant, Gotify или Node-RED), унесите њихове IP адресе или имена хостова горе, одвојене зарезима (нпр. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Управља се преко променљиве окружења SSRF_ALLOWLIST.","maintenance_tasks" => "Одржавање","orphaned_logos" => "Породични логотипови","update" => "Ажурирај",diff --git a/includes/i18n/sr_lat.php b/includes/i18n/sr_lat.phpindex b7b7f56..83c8be2 100644--- a/includes/i18n/sr_lat.php+++ b/includes/i18n/sr_lat.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Ručno","coming_soon" => "Uskoro","invalid_host" => "Nevažeći host",+ "ai_provider_error" => "Greška AI provajdera",+ "ai_invalid_response" => "AI provajder je vratio nevažeći odgovor.",+ "ai_invalid_json_response" => "AI odgovor nije sadržao važeće preporuke.","ai_recommendations_info" => "AI preporuke se generišu na osnovu vaših pretplata i članova domaćinstva.","may_take_time" => "U zavisnosti od provajdera, modela i broja pretplata, generisanje preporuka može potrajati.","recommendations_visible_on_dashboard" => "Preporuke će biti vidljive na kontrolnoj tabli.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Podešavanja bezbednosti","ssrf_protection_info" => "Kako bi se sprečile Server-Side Request Forgery (SSRF) napadi, Wallos podrazumevano blokira webhook obaveštenja ka privatnim ili internim mrežnim adresama.","local_webhook_info" => "Ako treba da šaljete webhooks ka lokalnim servisima (npr. Home Assistant, Gotify ili Node-RED), unesite njihove IP adrese ili imena hostova gore, odvojene zarezima (npr. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Upravlja se preko promenljive okruženja SSRF_ALLOWLIST.","maintenance_tasks" => "Održavanje","orphaned_logos" => "Nepovezani logotipi","update" => "Ažuriraj",diff --git a/includes/i18n/tr.php b/includes/i18n/tr.phpindex 4e38a67..840a9ce 100644--- a/includes/i18n/tr.php+++ b/includes/i18n/tr.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Manuel Olarak","coming_soon" => "Çok Yakında","invalid_host" => "Geçersiz Host",+ "ai_provider_error" => "AI sağlayıcı hatası",+ "ai_invalid_response" => "AI sağlayıcısı geçersiz bir yanıt döndürdü.",+ "ai_invalid_json_response" => "AI yanıtı geçerli öneriler içermiyordu.","ai_recommendations_info" => "AI önerileri, abonelikleriniz ve hane üyeleriniz temel alınarak oluşturulur.","may_take_time" => "Sağlayıcıya, modele ve abonelik sayısına bağlı olarak önerilerin oluşturulması biraz zaman alabilir.","recommendations_visible_on_dashboard" => "Öneriler panelde görüntülenecektir.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Güvenlik Ayarları","ssrf_protection_info" => "Sunucu tarafı istek sahteciliği (SSRF) saldırılarını önlemek için Wallos, varsayılan olarak webhook bildirimlerini özel veya dahili ağ adreslerine engeller.","local_webhook_info" => "Webhooks'u yerel hizmetlere (ör. Home Assistant, Gotify veya Node-RED) göndermeniz gerekiyorsa, IP adreslerini veya ana bilgisayar adlarını yukarıya virgülle ayrılmış bir liste olarak girin (ör. <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "SSRF_ALLOWLIST ortam değişkeni tarafından yönetilir.","maintenance_tasks" => "Bakım Görevleri","orphaned_logos" => "Yetim Logolar","update" => "Güncelle",diff --git a/includes/i18n/uk.php b/includes/i18n/uk.phpindex 87fc18c..92fc896 100644--- a/includes/i18n/uk.php+++ b/includes/i18n/uk.php@@ -267,6 +267,9 @@ $i18n = ["manually" => "Вручну","coming_soon" => "Незабаром","invalid_host" => "Неправильний Хост",+ "ai_provider_error" => "Помилка постачальника AI",+ "ai_invalid_response" => "Постачальник AI повернув недійсну відповідь.",+ "ai_invalid_json_response" => "Відповідь AI не містила дійсних рекомендацій.","ai_recommendations_info" => "AI рекомендації створюються на основі ваших підписок та членів домогосподарства.","may_take_time" => "В залежності від постачальника, моделі та кількості підписок, створення рекомендацій може зайняти деякий час.","recommendations_visible_on_dashboard" => "Рекомендації будуть видимі на панелі приладів.",@@ -416,6 +419,7 @@ $i18n = ["security_settings" => "Налаштування безпеки","ssrf_protection_info" => "Щоб запобігти атакам Server-Side Request Forgery (SSRF), Wallos за замовчуванням блокує вебхуки до приватних або внутрішніх мережевих адрес.","local_webhook_info" => "Якщо вам потрібно надсилати вебхуки до локальних сервісів (наприклад, Home Assistant, Gotify або Node-RED), введіть їх IP-адреси або імена хостів вище як список, розділений комами (наприклад <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Керується змінною середовища SSRF_ALLOWLIST.","maintenance_tasks" => "Завдання обслуговування","orphaned_logos" => "Втрачений логотип","update" => "Оновити",diff --git a/includes/i18n/vi.php b/includes/i18n/vi.phpindex 9ad5e81..27e3366 100644--- a/includes/i18n/vi.php+++ b/includes/i18n/vi.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "Thủ Công","coming_soon" => "Sắp Có","invalid_host" => "Máy Chủ Không Hợp Lệ",+ "ai_provider_error" => "Lỗi nhà cung cấp AI",+ "ai_invalid_response" => "Nhà cung cấp AI đã trả về phản hồi không hợp lệ.",+ "ai_invalid_json_response" => "Phản hồi AI không chứa đề xuất hợp lệ.","ai_recommendations_info" => "Các đề xuất AI được tạo dựa trên các đăng ký và thành viên hộ gia đình của bạn.","may_take_time" => "Tùy thuộc vào nhà cung cấp, mô hình và số lượng đăng ký, việc tạo đề xuất có thể mất một khoảng thời gian.","recommendations_visible_on_dashboard" => "Các đề xuất sẽ hiển thị trên bảng điều khiển.",@@ -417,6 +420,7 @@ $i18n = ["security_settings" => "Cài đặt bảo mật","ssrf_protection_info" => "Để ngăn chặn các cuộc tấn công Server-Side Request Forgery (SSRF), Wallos mặc định chặn các thông báo webhook đến các địa chỉ mạng riêng hoặc nội bộ.","local_webhook_info" => "Nếu bạn cần gửi webhooks đến các dịch vụ cục bộ (như Home Assistant, Gotify hoặc Node-RED), hãy nhập địa chỉ IP hoặc tên máy chủ của chúng ở trên dưới dạng danh sách cách nhau bởi dấu phẩy (ví dụ: <code>192.168.1.100,192.168.1.101</code>).",+ "ssrf_allowlist_env_managed" => "Được quản lý bởi biến môi trường SSRF_ALLOWLIST.","maintenance_tasks" => "Nhiệm vụ bảo trì","orphaned_logos" => "Logo bị bỏ rơi","update" => "Cập nhật",diff --git a/includes/i18n/zh_cn.php b/includes/i18n/zh_cn.phpindex 12c3651..a033c6d 100644--- a/includes/i18n/zh_cn.php+++ b/includes/i18n/zh_cn.php@@ -275,6 +275,9 @@ $i18n = ["manually" => "手动","coming_soon" => "即将推出","invalid_host" => "无效的主机",+ "ai_provider_error" => "AI 提供商错误",+ "ai_invalid_response" => "AI 提供商返回了无效响应。",+ "ai_invalid_json_response" => "AI 响应未包含有效建议。","ai_recommendations_info" => "AI 建议是基于您的订阅和家庭成员生成的。","may_take_time" => "根据提供商、模型和订阅数量,建议的生成可能需要一些时间。","recommendations_visible_on_dashboard" => "建议将在仪表板上可见。",@@ -434,6 +437,7 @@ $i18n = ["security_settings" => "安全设置","ssrf_protection_info" => "为防止服务端请求伪造(SSRF)攻击,Wallos 默认阻止发送到私有或内部网络地址的 webhook 通知。","local_webhook_info" => "如果需要将 webhook 发送到本地服务(例如 Home Assistant、Gotify 或 Node-RED),请在上方以逗号分隔的列表中输入它们的 IP 地址或主机名(例如 <code>192.168.1.100,192.168.1.101</code>)。",+ "ssrf_allowlist_env_managed" => "由 SSRF_ALLOWLIST 环境变量管理。","maintenance_tasks" => "维护任务","orphaned_logos" => "未关联的 Logo","update" => "更新",diff --git a/includes/i18n/zh_tw.php b/includes/i18n/zh_tw.phpindex e28b01f..50f1ebe 100644--- a/includes/i18n/zh_tw.php+++ b/includes/i18n/zh_tw.php@@ -268,6 +268,9 @@ $i18n = ["manually" => "手動","coming_soon" => "即將推出","invalid_host" => "無效的主機",+ "ai_provider_error" => "AI 提供商錯誤",+ "ai_invalid_response" => "AI 提供商返回了無效回應。",+ "ai_invalid_json_response" => "AI 回應未包含有效建議。","ai_recommendations_info" => "AI 推荐是基于您的订阅和家庭成员生成的。","may_take_time" => "根据提供商、模型和订阅数量,推荐生成可能需要一些时间。","recommendations_visible_on_dashboard" => "推荐将在仪表板上可见。",@@ -417,6 +420,7 @@ $i18n = ["security_settings" => "安全設定","ssrf_protection_info" => "為了防止服務端請求偽造(SSRF)攻擊,Wallos 預設會阻止發送到私人或內部網路位址的 webhook 通知。","local_webhook_info" => "如果您需要將 webhook 發送到本地服務(例如 Home Assistant、Gotify 或 Node-RED),請在上方以逗號分隔的列表中輸入它們的 IP 位址或主機名稱(例如 <code>192.168.1.100,192.168.1.101</code>)。",+ "ssrf_allowlist_env_managed" => "由 SSRF_ALLOWLIST 環境變數管理。","maintenance_tasks" => "維護工作","orphaned_logos" => "未使用的圖示","update" => "更新",diff --git a/includes/list_subscriptions.php b/includes/list_subscriptions.phpindex 0ce45b8..8fcaf51 100644--- a/includes/list_subscriptions.php+++ b/includes/list_subscriptions.php@@ -25,7 +25,7 @@ function getSubscriptionProgress($cycle, $frequency, $next_payment)}$nextPaymentDate = new DateTime($next_payment);- $currentDate = new DateTime('now');+ $currentDate = new DateTime((new DateTime('now'))->format('Y-m-d'));$paymentCycleDays = 30; // Default to monthlyif ($cycle === 1) {@@ -38,16 +38,25 @@ function getSubscriptionProgress($cycle, $frequency, $next_payment)$paymentCycleDays = 365 * $frequency;}+ if ($paymentCycleDays <= 0) {+ return 0;+ }++ // next_payment can be many cycles away from today (a stale value, or+ // several missed renewal runs), so we can't always assume it's within a+ // single cycle of "now". Walk back however many whole cycles are needed+ // so the window we measure progress against is the one that actually+ // contains today.+ $daysUntilNextPayment = $currentDate->diff($nextPaymentDate)->days;+ $cyclesBack = $currentDate <= $nextPaymentDate+ ? max(1, (int) ceil($daysUntilNextPayment / $paymentCycleDays))+ : 1;+$lastPaymentDate = clone $nextPaymentDate;- $lastPaymentDate->modify("-$paymentCycleDays days");+ $lastPaymentDate->modify('-' . ($cyclesBack * $paymentCycleDays) . ' days');- $totalCycleDays = $lastPaymentDate->diff($nextPaymentDate)->days;$daysSinceLastPayment = $lastPaymentDate->diff($currentDate)->days;-- $subscriptionProgress = 0;- if ($totalCycleDays > 0) {- $subscriptionProgress = ($daysSinceLastPayment / $totalCycleDays) * 100;- }+ $subscriptionProgress = ($daysSinceLastPayment / $paymentCycleDays) * 100;return floor($subscriptionProgress);}diff --git a/includes/stats_calculations.php b/includes/stats_calculations.phpindex 0c9a2c9..e26303c 100644--- a/includes/stats_calculations.php+++ b/includes/stats_calculations.php@@ -116,7 +116,7 @@ $totalSavingsPerMonth = 0;$totalCostsInReplacementsPerMonth = 0;$statsSubtitleParts = [];-$query = "SELECT name, price, logo, frequency, cycle, currency_id, next_payment, payer_user_id, category_id, payment_method_id, inactive, replacement_subscription_id, start_date, auto_renew FROM subscriptions";+$query = "SELECT name, price, logo, logo_text_color, logo_variant, frequency, cycle, currency_id, next_payment, payer_user_id, category_id, payment_method_id, inactive, replacement_subscription_id, start_date, auto_renew FROM subscriptions";$conditions = [];$params = [];@@ -209,6 +209,8 @@ if ($result) {$mostExpensiveSubscription['price'] = $price;$mostExpensiveSubscription['name'] = $name;$mostExpensiveSubscription['logo'] = $logo;+ $mostExpensiveSubscription['logo_text_color'] = $subscription['logo_text_color'] ?? null;+ $mostExpensiveSubscription['logo_variant'] = $subscription['logo_variant'] ?? null;}if ($cycle != 5) {diff --git a/includes/stats_extra_calculations.php b/includes/stats_extra_calculations.phpindex 64b93a5..8c70cca 100644--- a/includes/stats_extra_calculations.php+++ b/includes/stats_extra_calculations.php@@ -84,6 +84,8 @@ if (isset($subscriptions)) {'price' => $monthlyPrice,'name' => $subscription['name'],'logo' => $subscription['logo'],+ 'logo_text_color' => $subscription['logo_text_color'] ?? null,+ 'logo_variant' => $subscription['logo_variant'] ?? null,];}@@ -125,6 +127,8 @@ if (isset($subscriptions)) {'years' => $ageYears,'name' => $subscription['name'],'logo' => $subscription['logo'],+ 'logo_text_color' => $subscription['logo_text_color'] ?? null,+ 'logo_variant' => $subscription['logo_variant'] ?? null,];}}diff --git a/scripts/i18n/ar.js b/scripts/i18n/ar.jsindex 06fc134..0a890cc 100644--- a/scripts/i18n/ar.js+++ b/scripts/i18n/ar.js@@ -33,6 +33,9 @@ let i18n = {cant_disable_payment_in_use: "لا يمكن تعطيل طريقة دفع مستخدمة",failed_save_payment_method: "تعذر حفظ طريقة الدفع",unknown_error: "حدث خطأ غير معروف، يرجى المحاولة مرة أخرى.",+ invalid_budget: "يجب أن تكون الميزانية رقمًا غير سالب",+ invalid_budget_period: "فترة الميزانية المحددة غير صالحة",+ invalid_budget_anchor_date: "يجب أن يكون تاريخ البداية تاريخًا صالحًا",error_saving_notification_data: "حدث خطأ أثناء حفظ بيانات الإشعارات",error_sending_notification: "حدث خطأ أثناء إرسال الإشعار",delete_account_confirmation: "هل أنت متأكد من رغبتك في حذف حسابك؟",diff --git a/scripts/subscriptions.js b/scripts/subscriptions.jsindex dada54a..69741ac 100644--- a/scripts/subscriptions.js+++ b/scripts/subscriptions.js@@ -454,7 +454,10 @@ function fetchLogoSearchSource(url, retry = true) {}).catch(error => {if (retry) {- return fetchLogoSearchSource(url, false);+ // Wait a moment before retrying: sources like Brave rate-limit+ // aggressively, and retrying instantly just repeats the failure.+ return new Promise(resolve => setTimeout(resolve, 600))+ .then(() => fetchLogoSearchSource(url, false));}throw error;});diff --git a/stats.php b/stats.phpindex d43682e..ae44091 100644--- a/stats.php+++ b/stats.php@@ -1,5 +1,6 @@<?phprequire_once 'includes/header.php';+require_once 'includes/logo_theme_variant.php';// Get code of main currency to display on statistics@@ -228,10 +229,11 @@ require_once 'includes/stats_extra_calculations.php';<div class="title"><?= translate('most_expensive', $i18n) ?></div><?phpif (isset($mostExpensiveSubscription['logo']) && $mostExpensiveSubscription['logo'] != '') {+ $mostExpensiveLogoSrc = "images/uploads/logos/" . $mostExpensiveSubscription['logo'];+ $mostExpensiveLogoVariantSrc = !empty($mostExpensiveSubscription['logo_variant']) ? "images/uploads/logos/" . $mostExpensiveSubscription['logo_variant'] : null;?><div class="subtitle">- <img src="images/uploads/logos/<?= $mostExpensiveSubscription['logo'] ?>"- alt="<?= $mostExpensiveSubscription['name'] ?>" title="<?= $mostExpensiveSubscription['name'] ?>" />+ <?= renderThemedLogoImg($mostExpensiveLogoSrc, $mostExpensiveLogoVariantSrc, $mostExpensiveSubscription['logo_text_color'] ?? null, '', 'alt="' . $mostExpensiveSubscription['name'] . '" title="' . $mostExpensiveSubscription['name'] . '"') ?></div><?php} else if (isset($mostExpensiveSubscription['name']) && $mostExpensiveSubscription['name'] != '') {@@ -249,10 +251,11 @@ require_once 'includes/stats_extra_calculations.php';<div class="title"><?= translate('cheapest_subscription', $i18n) ?></div><?phpif (!empty($cheapestSubscription['logo'])) {+ $cheapestLogoSrc = "images/uploads/logos/" . $cheapestSubscription['logo'];+ $cheapestLogoVariantSrc = !empty($cheapestSubscription['logo_variant']) ? "images/uploads/logos/" . $cheapestSubscription['logo_variant'] : null;?><div class="subtitle">- <img src="images/uploads/logos/<?= $cheapestSubscription['logo'] ?>" alt="<?= $cheapestSubscription['name'] ?>"- title="<?= $cheapestSubscription['name'] ?>" />+ <?= renderThemedLogoImg($cheapestLogoSrc, $cheapestLogoVariantSrc, $cheapestSubscription['logo_text_color'] ?? null, '', 'alt="' . $cheapestSubscription['name'] . '" title="' . $cheapestSubscription['name'] . '"') ?></div><?php} else if (!empty($cheapestSubscription['name'])) {@@ -553,10 +556,11 @@ require_once 'includes/stats_extra_calculations.php';<div class="title"><?= translate('oldest_subscription', $i18n) ?></div><?phpif (!empty($oldestSubscription['logo'])) {+ $oldestLogoSrc = "images/uploads/logos/" . $oldestSubscription['logo'];+ $oldestLogoVariantSrc = !empty($oldestSubscription['logo_variant']) ? "images/uploads/logos/" . $oldestSubscription['logo_variant'] : null;?><div class="subtitle">- <img src="images/uploads/logos/<?= $oldestSubscription['logo'] ?>" alt="<?= $oldestSubscription['name'] ?>"- title="<?= $oldestSubscription['name'] ?>" />+ <?= renderThemedLogoImg($oldestLogoSrc, $oldestLogoVariantSrc, $oldestSubscription['logo_text_color'] ?? null, '', 'alt="' . $oldestSubscription['name'] . '" title="' . $oldestSubscription['name'] . '"') ?></div><?php} else if (!empty($oldestSubscription['name'])) {diff --git a/styles/rtl.css b/styles/rtl.cssdeleted file mode 100644index eb36035..0000000--- a/styles/rtl.css+++ /dev/null@@ -1,6 +0,0 @@-/* RTL-only layout corrections. This stylesheet is loaded only for RTL languages. */--.filtermenu-content .filter-item.selected::after {- right: auto;- left: 14px;-}diff --git a/styles/styles.css b/styles/styles.cssindex 4ee364d..7a7a2df 100644--- a/styles/styles.css+++ b/styles/styles.css@@ -2604,6 +2604,11 @@ button.dark-theme-button i {background-position: center left 10px;}+.rtl .filtermenu-content .filter-item.selected::after {+ right: auto;+ left: 14px;+}+.filtermenu-content .filter-title.filter-clear {color: var(--hover-color);font-weight: normal;diff --git a/subscriptions.php b/subscriptions.phpindex 07608d6..da06cd6 100644--- a/subscriptions.php+++ b/subscriptions.php@@ -561,7 +561,7 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip</section><?php require_once 'includes/subscription_details_popup.php'; ?>-<script src="scripts/subscriptions.js?<?= $version ?>&logo-search=4"></script>+<script src="scripts/subscriptions.js?<?= $version ?>"></script><?phpif (isset($_GET['add'])) {?>