Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
feat(subscriptions): allow several payers per subscription
Miguel Ribeirofaa0226801ca
diff --git a/api/household/get_household.php b/api/household/get_household.phpindex 5780b7c..487f975 100644--- a/api/household/get_household.php+++ b/api/household/get_household.php@@ -1,118 +1,118 @@-<?php-/*-This API Endpoint accepts both POST and GET requests.-It receives the following parameters:-- api_key: the API key of the user.--It returns a JSON object with the following properties:-- success: whether the request was successful (boolean).-- title: the title of the response (string).-- household: an array of household members.-- notes: warning messages or additional information (array).--Example response:-{- "success": true,- "title": "household",- "household": [- {- "id": 1,- "name": "John Doe",- "email": "[email protected]",- "in_use": true- },- {- "id": 2,- "name": "Jane Doe",- "email": "[email protected]",- "in_use": true- }- ],- "notes": []-}-*/--require_once '../../includes/connect_endpoint.php';--header('Content-Type: application/json; charset=UTF-8');--if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET") {- // if the parameters are not set, return an error-- $apiKey = $_REQUEST['api_key'] ?? $_REQUEST['apiKey'] ?? null;-- if (!$apiKey) {- $response = [- "success" => false,- "title" => "Missing parameters"- ];- echo json_encode($response);- exit;- }--- // Get user from API key- $sql = "SELECT * FROM user WHERE api_key = :apiKey";- $stmt = $db->prepare($sql);- $stmt->bindValue(':apiKey', $apiKey);- $result = $stmt->execute();- $user = $result->fetchArray(SQLITE3_ASSOC);-- // If the user is not found, return an error- if (!$user) {- $response = [- "success" => false,- "title" => "Invalid API key"- ];- echo json_encode($response);- exit;- }-- $userId = $user['id'];-- $sql = "SELECT * FROM household WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $household = [];- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $household[] = $row;- }-- foreach ($household as $key => $value) {- unset($household[$key]['user_id']);- // Check if is used in any subscriptions- $sql = "SELECT * FROM subscriptions WHERE user_id = :userId AND payer_user_id = :householdId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $stmt->bindValue(':householdId', $household[$key]['id']);- $result = $stmt->execute();- $subscription = $result->fetchArray(SQLITE3_ASSOC);- if ($subscription) {- $household[$key]['in_use'] = true;- } else {- $household[$key]['in_use'] = false;- }- }-- $response = [- "success" => true,- "title" => "household",- "household" => $household,- "notes" => []- ];-- echo json_encode($response);-- $db->close();--} else {- $response = [- "success" => false,- "title" => "Invalid request method"- ];- echo json_encode($response);- exit;-}-+<?php+/*+This API Endpoint accepts both POST and GET requests.+It receives the following parameters:+- api_key: the API key of the user.++It returns a JSON object with the following properties:+- success: whether the request was successful (boolean).+- title: the title of the response (string).+- household: an array of household members.+- notes: warning messages or additional information (array).++Example response:+{+ "success": true,+ "title": "household",+ "household": [+ {+ "id": 1,+ "name": "John Doe",+ "email": "[email protected]",+ "in_use": true+ },+ {+ "id": 2,+ "name": "Jane Doe",+ "email": "[email protected]",+ "in_use": true+ }+ ],+ "notes": []+}+*/++require_once '../../includes/connect_endpoint.php';++header('Content-Type: application/json; charset=UTF-8');++if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET") {+ // if the parameters are not set, return an error++ $apiKey = $_REQUEST['api_key'] ?? $_REQUEST['apiKey'] ?? null;++ if (!$apiKey) {+ $response = [+ "success" => false,+ "title" => "Missing parameters"+ ];+ echo json_encode($response);+ exit;+ }+++ // Get user from API key+ $sql = "SELECT * FROM user WHERE api_key = :apiKey";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':apiKey', $apiKey);+ $result = $stmt->execute();+ $user = $result->fetchArray(SQLITE3_ASSOC);++ // If the user is not found, return an error+ if (!$user) {+ $response = [+ "success" => false,+ "title" => "Invalid API key"+ ];+ echo json_encode($response);+ exit;+ }++ $userId = $user['id'];++ $sql = "SELECT * FROM household WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $household = [];+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $household[] = $row;+ }++ foreach ($household as $key => $value) {+ unset($household[$key]['user_id']);+ // Check if is used in any subscriptions+ $sql = "SELECT * FROM subscriptions WHERE user_id = :userId AND (payer_user_id = :householdId OR id IN (SELECT subscription_id FROM subscription_payers WHERE payer_id = :householdId))";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $stmt->bindValue(':householdId', $household[$key]['id']);+ $result = $stmt->execute();+ $subscription = $result->fetchArray(SQLITE3_ASSOC);+ if ($subscription) {+ $household[$key]['in_use'] = true;+ } else {+ $household[$key]['in_use'] = false;+ }+ }++ $response = [+ "success" => true,+ "title" => "household",+ "household" => $household,+ "notes" => []+ ];++ echo json_encode($response);++ $db->close();++} else {+ $response = [+ "success" => false,+ "title" => "Invalid request method"+ ];+ echo json_encode($response);+ exit;+}+?>\ No newline at end of filediff --git a/api/household/set_household.php b/api/household/set_household.phpindex 2616f24..707b3d8 100644--- a/api/household/set_household.php+++ b/api/household/set_household.php@@ -217,7 +217,7 @@ switch ($action) {}// Check if in use- $checkUseSql = "SELECT COUNT(*) FROM subscriptions WHERE payer_user_id = :memberId AND user_id = :userId";+ $checkUseSql = "SELECT COUNT(*) FROM subscriptions WHERE (payer_user_id = :memberId OR id IN (SELECT subscription_id FROM subscription_payers WHERE payer_id = :memberId)) AND user_id = :userId";$checkUseStmt = $db->prepare($checkUseSql);$checkUseStmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);$checkUseStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);diff --git a/api/subscriptions/get_ical_feed.php b/api/subscriptions/get_ical_feed.phpindex f9ce494..9a02acf 100644--- a/api/subscriptions/get_ical_feed.php+++ b/api/subscriptions/get_ical_feed.php@@ -1,221 +1,225 @@-<?php-/*-This API Endpoint accepts both POST and GET requests.-It receives the following parameters:-- convert_currency: whether to convert to the main currency (boolean) default false.-- api_key: the API key of the user.--It returns a downloadable VCAL file with the active subscriptions-*/--require_once '../../includes/connect_endpoint.php';-require_once '../../includes/currency_rates.php';-require_once '../../includes/ical_helper.php';--header('Content-Type: application/json; charset=UTF-8');--if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET") {- // if the parameters are not set, return an error-- $apiKey = $_REQUEST['api_key'] ?? $_REQUEST['apiKey'] ?? null;-- if (!$apiKey) {- $response = [- "success" => false,- "title" => "Missing parameters"- ];- echo json_encode($response);- exit;- }-- function getPriceConverted($price, $currency, $database)- {- return wallos_convert_price($price, $currency, $database);- }-- // Get user from API key- $sql = "SELECT * FROM user WHERE api_key = :apiKey";- $stmt = $db->prepare($sql);- $stmt->bindValue(':apiKey', $apiKey);- $result = $stmt->execute();- $user = $result->fetchArray(SQLITE3_ASSOC);-- // If the user is not found, return an error- if (!$user) {- $response = [- "success" => false,- "title" => "Invalid API key"- ];- echo json_encode($response);- exit;- }-- $userId = $user['id'];- $userCurrencyId = $user['main_currency'];-- // Get last exchange update date for user- $sql = "SELECT * FROM last_exchange_update WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $lastExchangeUpdate = $result->fetchArray(SQLITE3_ASSOC);-- $canConvertCurrency = empty($lastExchangeUpdate['date']) ? false : true;-- // Get currencies for user- $sql = "SELECT * FROM currencies WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $currencies = [];- while ($currency = $result->fetchArray(SQLITE3_ASSOC)) {- $currencies[$currency['id']] = $currency;- }-- // Get categories for user- $sql = "SELECT * FROM categories WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $categories = [];- while ($category = $result->fetchArray(SQLITE3_ASSOC)) {- $categories[$category['id']] = $category['name'];- }-- // Get members for user- $sql = "SELECT * FROM household WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $members = [];- while ($member = $result->fetchArray(SQLITE3_ASSOC)) {- $members[$member['id']] = $member['name'];- }-- // Get payment methods for user- $sql = "SELECT * FROM payment_methods WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $paymentMethods = [];- while ($paymentMethod = $result->fetchArray(SQLITE3_ASSOC)) {- $paymentMethods[$paymentMethod['id']] = $paymentMethod['name'];- }-- $sql = "SELECT * FROM subscriptions WHERE user_id = :userId AND inactive = 0 ORDER BY next_payment ASC";-- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- if ($result) {- $subscriptions = array();- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $subscriptions[] = $row;- }- }-- $subscriptionsToReturn = array();-- // Get notification settings- $notificationQuery = "SELECT days FROM notification_settings WHERE user_id = :userId";- $notificationQueryStmt = $db->prepare($notificationQuery);- $notificationQueryStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $notificationResult = $notificationQueryStmt->execute();- $globalNotificationDays = 1; // Default value- if ($row = $notificationResult->fetchArray(SQLITE3_ASSOC)) {- $globalNotificationDays = $row['days'];- }-- foreach ($subscriptions as $subscription) {- $subscriptionToReturn = $subscription;-- $wasConverted = isset($_REQUEST['convert_currency']) && $_REQUEST['convert_currency'] === 'true' && $canConvertCurrency && $subscription['currency_id'] != $userCurrencyId;- if ($wasConverted) {- $subscriptionToReturn['price'] = getPriceConverted($subscription['price'], $subscription['currency_id'], $db);- // Converted prices are now in the user's main currency, so the- // symbol shown alongside them has to switch too.- $subscriptionToReturn['currency_id'] = $userCurrencyId;- } else {- $subscriptionToReturn['price'] = $subscription['price'];- }-- $subscriptionToReturn['category_name'] = isset($categories[$subscription['category_id']]) ? $categories[$subscription['category_id']] : 'No category';- $subscriptionToReturn['payer_user_name'] = isset($members[$subscription['payer_user_id']]) ? $members[$subscription['payer_user_id']] : 'Unknown member';- $subscriptionToReturn['payment_method_name'] = isset($paymentMethods[$subscription['payment_method_id']]) ? $paymentMethods[$subscription['payment_method_id']] : 'Unknown payment method';-- $subscriptionsToReturn[] = $subscriptionToReturn;- }-- header('Content-Type: text/calendar; charset=utf-8');- header('Content-Disposition: attachment; filename="subscriptions.ics"');-- $icsContent = "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//Wallos//iCalendar//EN\nNAME:Wallos\nX-WR-CALNAME:Wallos\n";-- foreach ($subscriptionsToReturn as $subscription) {- $subscription['payer_user'] = $subscription['payer_user_name'];- $subscription['category'] = $subscription['category_name'];- $subscription['payment_method'] = $subscription['payment_method_name'];- $subscription['currency'] = isset($currencies[$subscription['currency_id']]) ? $currencies[$subscription['currency_id']]['symbol'] : '';- $subscription['trigger'] = ($subscription['notify_days_before'] == -1) ? $globalNotificationDays : ($subscription['notify_days_before'] ?: 1);- $subscription['price'] = number_format($subscription['price'], 2);-- $uid = 'wallos-subscription-' . $subscription['id'] . '@wallos';- $summary = icalEscape(html_entity_decode($subscription['name'], ENT_QUOTES, 'UTF-8'));- $notes = icalEscape($subscription['notes']);- $category = icalEscape($subscription['category']);- $paymentMethod = icalEscape($subscription['payment_method']);- $payer = icalEscape($subscription['payer_user']);- $description = "Price: {$subscription['currency']}{$subscription['price']}\\nCategory: {$category}\\nPayment Method: {$paymentMethod}\\nPayer: {$payer}\\nNotes: {$notes}";- $dtstamp = gmdate('Ymd\THis\Z');- $dtstart = (new DateTime($subscription['next_payment']))->format('Ymd');- $dtend = (new DateTime($subscription['next_payment']))->format('Ymd');- $location = icalEscape(isset($subscription['url']) ? $subscription['url'] : '');- $alarm_trigger = '-P' . $subscription['trigger'] . 'D';-- // Notes can now be multi-paragraph Markdown, so these lines- // (especially DESCRIPTION) can genuinely exceed the RFC 5545- // 75-octet limit.- $summaryLine = icalFold('SUMMARY:' . $summary);- $descriptionLine = icalFold('DESCRIPTION:' . $description);- $locationLine = icalFold('LOCATION:' . $location);-- $icsContent .= <<<ICS- BEGIN:VEVENT- UID:$uid- DTSTAMP:$dtstamp- $summaryLine- $descriptionLine- DTSTART;VALUE=DATE:$dtstart- DTEND;VALUE=DATE:$dtend- $locationLine- STATUS:CONFIRMED- TRANSP:OPAQUE- BEGIN:VALARM- ACTION:DISPLAY- DESCRIPTION:Reminder- TRIGGER:$alarm_trigger- END:VALARM- END:VEVENT-- ICS;- }-- $icsContent .= "END:VCALENDAR\n";- echo $icsContent;- $db->close();- exit;----} else {- $response = [- "success" => false,- "title" => "Invalid request method"- ];- echo json_encode($response);- exit;-}---?>+<?php+/*+This API Endpoint accepts both POST and GET requests.+It receives the following parameters:+- convert_currency: whether to convert to the main currency (boolean) default false.+- api_key: the API key of the user.++It returns a downloadable VCAL file with the active subscriptions+*/++require_once '../../includes/connect_endpoint.php';+require_once '../../includes/currency_rates.php';+require_once '../../includes/ical_helper.php';+require_once '../../includes/subscription_payers.php';++header('Content-Type: application/json; charset=UTF-8');++if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET") {+ // if the parameters are not set, return an error++ $apiKey = $_REQUEST['api_key'] ?? $_REQUEST['apiKey'] ?? null;++ if (!$apiKey) {+ $response = [+ "success" => false,+ "title" => "Missing parameters"+ ];+ echo json_encode($response);+ exit;+ }++ function getPriceConverted($price, $currency, $database)+ {+ return wallos_convert_price($price, $currency, $database);+ }++ // Get user from API key+ $sql = "SELECT * FROM user WHERE api_key = :apiKey";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':apiKey', $apiKey);+ $result = $stmt->execute();+ $user = $result->fetchArray(SQLITE3_ASSOC);++ // If the user is not found, return an error+ if (!$user) {+ $response = [+ "success" => false,+ "title" => "Invalid API key"+ ];+ echo json_encode($response);+ exit;+ }++ $userId = $user['id'];+ $userCurrencyId = $user['main_currency'];++ // Get last exchange update date for user+ $sql = "SELECT * FROM last_exchange_update WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $lastExchangeUpdate = $result->fetchArray(SQLITE3_ASSOC);++ $canConvertCurrency = empty($lastExchangeUpdate['date']) ? false : true;++ // Get currencies for user+ $sql = "SELECT * FROM currencies WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $currencies = [];+ while ($currency = $result->fetchArray(SQLITE3_ASSOC)) {+ $currencies[$currency['id']] = $currency;+ }++ // Get categories for user+ $sql = "SELECT * FROM categories WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $categories = [];+ while ($category = $result->fetchArray(SQLITE3_ASSOC)) {+ $categories[$category['id']] = $category['name'];+ }++ // Get members for user+ $sql = "SELECT * FROM household WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $members = [];+ while ($member = $result->fetchArray(SQLITE3_ASSOC)) {+ $members[$member['id']] = $member['name'];+ }++ // Get payment methods for user+ $sql = "SELECT * FROM payment_methods WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $paymentMethods = [];+ while ($paymentMethod = $result->fetchArray(SQLITE3_ASSOC)) {+ $paymentMethods[$paymentMethod['id']] = $paymentMethod['name'];+ }++ $sql = "SELECT * FROM subscriptions WHERE user_id = :userId AND inactive = 0 ORDER BY next_payment ASC";++ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ if ($result) {+ $subscriptions = array();+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $subscriptions[] = $row;+ }+ }++ $subscriptionsToReturn = array();++ // Get notification settings+ $notificationQuery = "SELECT days FROM notification_settings WHERE user_id = :userId";+ $notificationQueryStmt = $db->prepare($notificationQuery);+ $notificationQueryStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $notificationResult = $notificationQueryStmt->execute();+ $globalNotificationDays = 1; // Default value+ if ($row = $notificationResult->fetchArray(SQLITE3_ASSOC)) {+ $globalNotificationDays = $row['days'];+ }++ $payersBySubscription = getPayersBySubscription($db, $subscriptions);++ foreach ($subscriptions as $subscription) {+ $subscriptionToReturn = $subscription;++ $wasConverted = isset($_REQUEST['convert_currency']) && $_REQUEST['convert_currency'] === 'true' && $canConvertCurrency && $subscription['currency_id'] != $userCurrencyId;+ if ($wasConverted) {+ $subscriptionToReturn['price'] = getPriceConverted($subscription['price'], $subscription['currency_id'], $db);+ // Converted prices are now in the user's main currency, so the+ // symbol shown alongside them has to switch too.+ $subscriptionToReturn['currency_id'] = $userCurrencyId;+ } else {+ $subscriptionToReturn['price'] = $subscription['price'];+ }++ $subscriptionToReturn['category_name'] = isset($categories[$subscription['category_id']]) ? $categories[$subscription['category_id']] : 'No category';+ $payerLabel = payerNamesLabel($payersBySubscription[$subscription['id']] ?? [], $members);+ $subscriptionToReturn['payer_user_name'] = $payerLabel !== '' ? $payerLabel : 'Unknown member';+ $subscriptionToReturn['payment_method_name'] = isset($paymentMethods[$subscription['payment_method_id']]) ? $paymentMethods[$subscription['payment_method_id']] : 'Unknown payment method';++ $subscriptionsToReturn[] = $subscriptionToReturn;+ }++ header('Content-Type: text/calendar; charset=utf-8');+ header('Content-Disposition: attachment; filename="subscriptions.ics"');++ $icsContent = "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//Wallos//iCalendar//EN\nNAME:Wallos\nX-WR-CALNAME:Wallos\n";++ foreach ($subscriptionsToReturn as $subscription) {+ $subscription['payer_user'] = $subscription['payer_user_name'];+ $subscription['category'] = $subscription['category_name'];+ $subscription['payment_method'] = $subscription['payment_method_name'];+ $subscription['currency'] = isset($currencies[$subscription['currency_id']]) ? $currencies[$subscription['currency_id']]['symbol'] : '';+ $subscription['trigger'] = ($subscription['notify_days_before'] == -1) ? $globalNotificationDays : ($subscription['notify_days_before'] ?: 1);+ $subscription['price'] = number_format($subscription['price'], 2);++ $uid = 'wallos-subscription-' . $subscription['id'] . '@wallos';+ $summary = icalEscape(html_entity_decode($subscription['name'], ENT_QUOTES, 'UTF-8'));+ $notes = icalEscape($subscription['notes']);+ $category = icalEscape($subscription['category']);+ $paymentMethod = icalEscape($subscription['payment_method']);+ $payer = icalEscape($subscription['payer_user']);+ $description = "Price: {$subscription['currency']}{$subscription['price']}\\nCategory: {$category}\\nPayment Method: {$paymentMethod}\\nPayer: {$payer}\\nNotes: {$notes}";+ $dtstamp = gmdate('Ymd\THis\Z');+ $dtstart = (new DateTime($subscription['next_payment']))->format('Ymd');+ $dtend = (new DateTime($subscription['next_payment']))->format('Ymd');+ $location = icalEscape(isset($subscription['url']) ? $subscription['url'] : '');+ $alarm_trigger = '-P' . $subscription['trigger'] . 'D';++ // Notes can now be multi-paragraph Markdown, so these lines+ // (especially DESCRIPTION) can genuinely exceed the RFC 5545+ // 75-octet limit.+ $summaryLine = icalFold('SUMMARY:' . $summary);+ $descriptionLine = icalFold('DESCRIPTION:' . $description);+ $locationLine = icalFold('LOCATION:' . $location);++ $icsContent .= <<<ICS+ BEGIN:VEVENT+ UID:$uid+ DTSTAMP:$dtstamp+ $summaryLine+ $descriptionLine+ DTSTART;VALUE=DATE:$dtstart+ DTEND;VALUE=DATE:$dtend+ $locationLine+ STATUS:CONFIRMED+ TRANSP:OPAQUE+ BEGIN:VALARM+ ACTION:DISPLAY+ DESCRIPTION:Reminder+ TRIGGER:$alarm_trigger+ END:VALARM+ END:VEVENT++ ICS;+ }++ $icsContent .= "END:VCALENDAR\n";+ echo $icsContent;+ $db->close();+ exit;++++} else {+ $response = [+ "success" => false,+ "title" => "Invalid request method"+ ];+ echo json_encode($response);+ exit;+}+++?>diff --git a/api/subscriptions/get_subscription.php b/api/subscriptions/get_subscription.phpindex 8abeacd..1311203 100644--- a/api/subscriptions/get_subscription.php+++ b/api/subscriptions/get_subscription.php@@ -40,6 +40,8 @@ Example response:"cancellation_date": "","category_name": "Entertainment","payer_user_name": "John Doe",+ "payer_user_ids": [1, 2],+ "payer_user_names": ["John Doe", "Jane Doe"],"payment_method_name": "PayPal"},"notes": []@@ -48,6 +50,7 @@ Example response:require_once '../../includes/connect_endpoint.php';require_once '../../includes/currency_rates.php';+require_once '../../includes/subscription_payers.php';header('Content-Type: application/json; charset=UTF-8');@@ -120,6 +123,17 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET$payerRow = $payerResult->fetchArray(SQLITE3_ASSOC);$subscription['payer_user_name'] = $payerRow ? $payerRow['name'] : 'Unknown member';+ // All payers, the primary one first+ $subscription['payer_user_ids'] = getPayersBySubscription($db, [$subscription])[$subscription['id']] ?? [];+ $subscription['payer_user_names'] = [];+ foreach ($subscription['payer_user_ids'] as $payerId) {+ $namesStmt = $db->prepare("SELECT name FROM household WHERE id = :payerId AND user_id = :userId");+ $namesStmt->bindValue(':payerId', $payerId, SQLITE3_INTEGER);+ $namesStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $nameRow = $namesStmt->execute()->fetchArray(SQLITE3_ASSOC);+ $subscription['payer_user_names'][] = $nameRow ? $nameRow['name'] : 'Unknown member';+ }+// Resolve Payment Method Name$pmSql = "SELECT name FROM payment_methods WHERE id = :pmId AND (user_id = :userId OR user_id = 0 OR user_id IS NULL)";$pmStmt = $db->prepare($pmSql);diff --git a/api/subscriptions/get_subscriptions.php b/api/subscriptions/get_subscriptions.phpindex 0bdf2c0..7c45076 100644--- a/api/subscriptions/get_subscriptions.php+++ b/api/subscriptions/get_subscriptions.php@@ -1,356 +1,357 @@-<?php-/*-This API Endpoint accepts both POST and GET requests.-It receives the following parameters:-- member: comma-separated IDs of the members to filter (integer) default null.-- category: comma-separated IDs of the categories to filter (integer) default null.-- payment: comma-separated IDs of the payment methods to filter (integer) default null.-- state: the state of the subscription to filter (integer) default null [0 - active, 1 - inactive].-- disabled_to_bottom: whether to sort the inactive subscriptions to the bottom (string) default false. Must be the literal string "true" to take effect.-- sort: the sorting method (string) default next_payment ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric'].-- convert_currency: whether to convert to the main currency (string) default false. Must be the literal string "true" to take effect.-- all-user-subscription: whether to return subscriptions for every user instead of just the caller (string) default null. Only honored when api_key belongs to user id 1; adds the "users" field to the response.-- api_key: the API key of the user.--It returns a JSON object with the following properties:-- success: whether the request was successful (boolean).-- title: the title of the response (string).-- subscriptions: an array of subscriptions.-- users: an array of all users, only present when all-user-subscription is used by user id 1.-- notes: reserved for warning messages or additional information (array); currently always empty.--Example response:-{- "success": true,- "title": "subscriptions",- "subscriptions": [- {- "id": 1,- "name": "Example Subscription",- "logo": "example.png",- "price": 10.00,- "currency_id": 1,- "start_date": "2024-09-01",- "next_payment": "2024-09-01",- "cycle": 1,- "frequency": 1,- "auto_renew": 1,- "notes": "Example note",- "payment_method_id": 1,- "payer_user_id": 1,- "category_id": 1,- "notify": 1,- "url": "https://example.com",- "inactive": 0,- "notify_days_before": 1,- "user_id": 1,- "cancelation_date": null,- "cancellation_date": "",- "category_name": "General",- "payer_user_name": "John Doe",- "payment_method_name": "PayPal"- },- {- "id": 2,- "name": "Another Subscription",- "logo": "another.png",- "price": 15.00,- "currency_id": 2,- "start_date": "2024-09-02",- "next_payment": "2024-09-02",- "cycle": 1,- "frequency": 1,- "auto_renew": 0,- "notes": "",- "payment_method_id": 2,- "payer_user_id": 2,- "category_id": 2,- "notify": 0,- "url": "",- "inactive": 1,- "notify_days_before": null,- "user_id": 2,- "cancelation_date": null,- "cancellation_date": "",- "category_name": "Entertainment",- "payer_user_name": "Jane Doe",- "payment_method_name": "Credit Card",- "replacement_subscription_id": 1- }- ],- "users": [- {- "id": 1,- "name": "admin",- "email": "[email protected]"- },- {- "id": 2,- "name": "user",- "email": "[email protected]"- }- ],- "notes": []-}-*/--require_once '../../includes/connect_endpoint.php';-require_once '../../includes/currency_rates.php';--header('Content-Type: application/json; charset=UTF-8');--if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET") {- // if the parameters are not set, return an error- $apiKey = $_REQUEST['api_key'] ?? $_REQUEST['apiKey'] ?? null;- if (!$apiKey) {- $response = [- "success" => false,- "title" => "Missing parameters"- ];- echo json_encode($response);- exit;- }-- function getPriceConverted($price, $currency, $database)- {- return wallos_convert_price($price, $currency, $database);- }-- // Get user from API key- $sql = "SELECT * FROM user WHERE api_key = :apiKey";- $stmt = $db->prepare($sql);- $stmt->bindValue(':apiKey', $apiKey);- $result = $stmt->execute();- $user = $result->fetchArray(SQLITE3_ASSOC);-- // If the user is not found, return an error- if (!$user) {- $response = [- "success" => false,- "title" => "Invalid API key"- ];- echo json_encode($response);- exit;- }- $userId = $user['id'];- $userCurrencyId = $user['main_currency'];-- $allUserSubscription = isset($_REQUEST['all-user-subscription']) ? $_REQUEST['all-user-subscription'] : null;- if ($allUserSubscription == 1 && $userId != 1) {- $response = [- "success" => false,- "title" => "Denied. Not admin user"- ];- echo json_encode($response);- exit;- }-- // Get last exchange update date for user- $sql = "SELECT * FROM last_exchange_update WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $lastExchangeUpdate = $result->fetchArray(SQLITE3_ASSOC);- $canConvertCurrency = empty($lastExchangeUpdate['date']) ? false : true;-- // Get currencies for user- $sql = "SELECT * FROM currencies WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $currencies = [];- while ($currency = $result->fetchArray(SQLITE3_ASSOC)) {- $currencies[$currency['id']] = $currency;- }-- // Get categories for user- $sql = "SELECT * FROM categories WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $categories = [];- while ($category = $result->fetchArray(SQLITE3_ASSOC)) {- $categories[$category['id']] = $category['name'];- }-- // Get members for user- $sql = "SELECT * FROM household WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $members = [];- while ($member = $result->fetchArray(SQLITE3_ASSOC)) {- $members[$member['id']] = $member['name'];- }-- // Get payment methods for user- $sql = "SELECT * FROM payment_methods WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId);- $result = $stmt->execute();- $paymentMethods = [];- while ($paymentMethod = $result->fetchArray(SQLITE3_ASSOC)) {- $paymentMethods[$paymentMethod['id']] = $paymentMethod['name'];- }-- $sort = "next_payment";- if (isset($_REQUEST['sort'])) {- $sort = $_REQUEST['sort'];- }- $sortOrder = $sort;- $allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric'];- $order = ($sort == "price" || $sort == "id") ? "DESC" : "ASC";- if ($sort == "alphanumeric") {- $sort = "name";- }- if (!in_array($sort, $allowedSortCriteria)) {- $sort = "next_payment";- }-- // Construction of the main SQL Query- $params = [];- if ($allUserSubscription == 1 && $userId == 1) {- $sql = "SELECT * FROM subscriptions WHERE 1 = 1";- } else {- $sql = "SELECT * FROM subscriptions WHERE user_id = :userId";- $params[':userId'] = $userId;- }-- if (isset($_REQUEST['member'])) {- $memberIds = explode(',', $_REQUEST['member']);- $placeholders = array_map(function ($key) {- return ":member{$key}";- }, array_keys($memberIds));- $sql .= " AND payer_user_id IN (" . implode(',', $placeholders) . ")";- foreach ($memberIds as $key => $memberId) {- $params[":member{$key}"] = $memberId;- }- }- if (isset($_REQUEST['category'])) {- $categoryIds = explode(',', $_REQUEST['category']);- $placeholders = array_map(function ($key) {- return ":category{$key}";- }, array_keys($categoryIds));- $sql .= " AND category_id IN (" . implode(',', $placeholders) . ")";- foreach ($categoryIds as $key => $categoryId) {- $params[":category{$key}"] = $categoryId;- }- }- if (isset($_REQUEST['payment'])) {- $paymentIds = explode(',', $_REQUEST['payment']);- $placeholders = array_map(function ($key) {- return ":payment{$key}";- }, array_keys($paymentIds));- $sql .= " AND payment_method_id IN (" . implode(',', $placeholders) . ")";- foreach ($paymentIds as $key => $paymentId) {- $params[":payment{$key}"] = $paymentId;- }- }- if (isset($_REQUEST['state']) && $_REQUEST['state'] != "") {- $sql .= " AND inactive = :inactive";- $params[':inactive'] = $_REQUEST['state'];- }-- $orderByClauses = [];- if (isset($_REQUEST['disabled_to_bottom']) && $_REQUEST['disabled_to_bottom'] === 'true') {- if (in_array($sort, ["payer_user_id", "category_id", "payment_method_id"])) {- $orderByClauses[] = "$sort $order";- $orderByClauses[] = "inactive ASC";- } else {- $orderByClauses[] = "inactive ASC";- $orderByClauses[] = "$sort $order";- }- } else {- $orderByClauses[] = "$sort $order";- if ($sort != "inactive") {- $orderByClauses[] = "inactive ASC";- }- }- if ($sort != "next_payment") {- $orderByClauses[] = "next_payment ASC";- }- $sql .= " ORDER BY " . implode(", ", $orderByClauses);-- $stmt = $db->prepare($sql);- if ($stmt === false) {- $response = [- "success" => false,- "title" => "Invalid query parameters"- ];- echo json_encode($response);- exit;- }- if (!empty($params)) {- foreach ($params as $key => $value) {- $stmt->bindValue($key, $value, SQLITE3_INTEGER);- }- }- $result = $stmt->execute();- if ($result) {- $subscriptions = array();- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $subscriptions[] = $row;- }- }- $subscriptionsToReturn = array();- foreach ($subscriptions as $subscription) {- $subscriptionToReturn = $subscription;- if (isset($_REQUEST['convert_currency']) && $_REQUEST['convert_currency'] === 'true' && $canConvertCurrency && $subscription['currency_id'] != $userCurrencyId) {- $subscriptionToReturn['price'] = getPriceConverted($subscription['price'], $subscription['currency_id'], $db);- } else {- $subscriptionToReturn['price'] = $subscription['price'];- }- $subscriptionToReturn['category_name'] = isset($categories[$subscription['category_id']]) ? $categories[$subscription['category_id']] : 'No category';- $subscriptionToReturn['payer_user_name'] = isset($members[$subscription['payer_user_id']]) ? $members[$subscription['payer_user_id']] : 'Unknown member';- $subscriptionToReturn['payment_method_name'] = isset($paymentMethods[$subscription['payment_method_id']]) ? $paymentMethods[$subscription['payment_method_id']] : 'Unknown payment method';- $subscriptionsToReturn[] = $subscriptionToReturn;- }-- $response = [- "success" => true,- "title" => "subscriptions",- "subscriptions" => $subscriptionsToReturn,- "notes" => []- ];-- if ($allUserSubscription == 1 && $userId == 1) {- $sql = "PRAGMA table_info(user)";- $stmt = $db->prepare($sql);- $result = $stmt->execute();- $userColumns = array();- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $userColumns[] = $row['name'];- }- $userNameCol = in_array('username', $userColumns) ? 'username' : null;- $userEmailCol = in_array('email', $userColumns) ? 'email' : null;- if ($userNameCol && $userEmailCol) {- $sql = "SELECT id, $userNameCol as name, $userEmailCol as email FROM user";- } elseif ($userNameCol) {- $sql = "SELECT id, $userNameCol as name FROM user";- } elseif ($userEmailCol) {- $sql = "SELECT id, $userEmailCol as email FROM user";- } else {- $sql = "SELECT id FROM user";- }- $stmt = $db->prepare($sql);- $result = $stmt->execute();- $users = array();- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $users[] = $row;- }- $response['users'] = $users;- }-- echo json_encode($response);- $db->close();- exit;---} else {- $response = [- "success" => false,- "title" => "Invalid request method"- ];- echo json_encode($response);- exit;+<?php+/*+This API Endpoint accepts both POST and GET requests.+It receives the following parameters:+- member: comma-separated IDs of the members to filter (integer) default null.+- category: comma-separated IDs of the categories to filter (integer) default null.+- payment: comma-separated IDs of the payment methods to filter (integer) default null.+- state: the state of the subscription to filter (integer) default null [0 - active, 1 - inactive].+- disabled_to_bottom: whether to sort the inactive subscriptions to the bottom (string) default false. Must be the literal string "true" to take effect.+- sort: the sorting method (string) default next_payment ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric'].+- convert_currency: whether to convert to the main currency (string) default false. Must be the literal string "true" to take effect.+- all-user-subscription: whether to return subscriptions for every user instead of just the caller (string) default null. Only honored when api_key belongs to user id 1; adds the "users" field to the response.+- api_key: the API key of the user.++It returns a JSON object with the following properties:+- success: whether the request was successful (boolean).+- title: the title of the response (string).+- subscriptions: an array of subscriptions.+- users: an array of all users, only present when all-user-subscription is used by user id 1.+- notes: reserved for warning messages or additional information (array); currently always empty.++Example response:+{+ "success": true,+ "title": "subscriptions",+ "subscriptions": [+ {+ "id": 1,+ "name": "Example Subscription",+ "logo": "example.png",+ "price": 10.00,+ "currency_id": 1,+ "start_date": "2024-09-01",+ "next_payment": "2024-09-01",+ "cycle": 1,+ "frequency": 1,+ "auto_renew": 1,+ "notes": "Example note",+ "payment_method_id": 1,+ "payer_user_id": 1,+ "category_id": 1,+ "notify": 1,+ "url": "https://example.com",+ "inactive": 0,+ "notify_days_before": 1,+ "user_id": 1,+ "cancelation_date": null,+ "cancellation_date": "",+ "category_name": "General",+ "payer_user_name": "John Doe",+ "payer_user_ids": [1, 2],+ "payer_user_names": ["John Doe", "Jane Doe"],+ "payment_method_name": "PayPal"+ },+ {+ "id": 2,+ "name": "Another Subscription",+ "logo": "another.png",+ "price": 15.00,+ "currency_id": 2,+ "start_date": "2024-09-02",+ "next_payment": "2024-09-02",+ "cycle": 1,+ "frequency": 1,+ "auto_renew": 0,+ "notes": "",+ "payment_method_id": 2,+ "payer_user_id": 2,+ "category_id": 2,+ "notify": 0,+ "url": "",+ "inactive": 1,+ "notify_days_before": null,+ "user_id": 2,+ "cancelation_date": null,+ "cancellation_date": "",+ "category_name": "Entertainment",+ "payer_user_name": "Jane Doe",+ "payment_method_name": "Credit Card",+ "replacement_subscription_id": 1+ }+ ],+ "users": [+ {+ "id": 1,+ "name": "admin",+ "email": "[email protected]"+ },+ {+ "id": 2,+ "name": "user",+ "email": "[email protected]"+ }+ ],+ "notes": []+}+*/++require_once '../../includes/connect_endpoint.php';+require_once '../../includes/currency_rates.php';+require_once '../../includes/subscription_payers.php';++header('Content-Type: application/json; charset=UTF-8');++if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET") {+ // if the parameters are not set, return an error+ $apiKey = $_REQUEST['api_key'] ?? $_REQUEST['apiKey'] ?? null;+ if (!$apiKey) {+ $response = [+ "success" => false,+ "title" => "Missing parameters"+ ];+ echo json_encode($response);+ exit;+ }++ function getPriceConverted($price, $currency, $database)+ {+ return wallos_convert_price($price, $currency, $database);+ }++ // Get user from API key+ $sql = "SELECT * FROM user WHERE api_key = :apiKey";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':apiKey', $apiKey);+ $result = $stmt->execute();+ $user = $result->fetchArray(SQLITE3_ASSOC);++ // If the user is not found, return an error+ if (!$user) {+ $response = [+ "success" => false,+ "title" => "Invalid API key"+ ];+ echo json_encode($response);+ exit;+ }+ $userId = $user['id'];+ $userCurrencyId = $user['main_currency'];++ $allUserSubscription = isset($_REQUEST['all-user-subscription']) ? $_REQUEST['all-user-subscription'] : null;+ if ($allUserSubscription == 1 && $userId != 1) {+ $response = [+ "success" => false,+ "title" => "Denied. Not admin user"+ ];+ echo json_encode($response);+ exit;+ }++ // Get last exchange update date for user+ $sql = "SELECT * FROM last_exchange_update WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $lastExchangeUpdate = $result->fetchArray(SQLITE3_ASSOC);+ $canConvertCurrency = empty($lastExchangeUpdate['date']) ? false : true;++ // Get currencies for user+ $sql = "SELECT * FROM currencies WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $currencies = [];+ while ($currency = $result->fetchArray(SQLITE3_ASSOC)) {+ $currencies[$currency['id']] = $currency;+ }++ // Get categories for user+ $sql = "SELECT * FROM categories WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $categories = [];+ while ($category = $result->fetchArray(SQLITE3_ASSOC)) {+ $categories[$category['id']] = $category['name'];+ }++ // Get members for user+ $sql = "SELECT * FROM household WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $members = [];+ while ($member = $result->fetchArray(SQLITE3_ASSOC)) {+ $members[$member['id']] = $member['name'];+ }++ // Get payment methods for user+ $sql = "SELECT * FROM payment_methods WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId);+ $result = $stmt->execute();+ $paymentMethods = [];+ while ($paymentMethod = $result->fetchArray(SQLITE3_ASSOC)) {+ $paymentMethods[$paymentMethod['id']] = $paymentMethod['name'];+ }++ $sort = "next_payment";+ if (isset($_REQUEST['sort'])) {+ $sort = $_REQUEST['sort'];+ }+ $sortOrder = $sort;+ $allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric'];+ $order = ($sort == "price" || $sort == "id") ? "DESC" : "ASC";+ if ($sort == "alphanumeric") {+ $sort = "name";+ }+ if (!in_array($sort, $allowedSortCriteria)) {+ $sort = "next_payment";+ }++ // Construction of the main SQL Query+ $params = [];+ if ($allUserSubscription == 1 && $userId == 1) {+ $sql = "SELECT * FROM subscriptions WHERE 1 = 1";+ } else {+ $sql = "SELECT * FROM subscriptions WHERE user_id = :userId";+ $params[':userId'] = $userId;+ }++ if (isset($_REQUEST['member'])) {+ $memberIds = explode(',', $_REQUEST['member']);+ $sql .= " AND " . payerFilterCondition($memberIds, $params);+ }+ if (isset($_REQUEST['category'])) {+ $categoryIds = explode(',', $_REQUEST['category']);+ $placeholders = array_map(function ($key) {+ return ":category{$key}";+ }, array_keys($categoryIds));+ $sql .= " AND category_id IN (" . implode(',', $placeholders) . ")";+ foreach ($categoryIds as $key => $categoryId) {+ $params[":category{$key}"] = $categoryId;+ }+ }+ if (isset($_REQUEST['payment'])) {+ $paymentIds = explode(',', $_REQUEST['payment']);+ $placeholders = array_map(function ($key) {+ return ":payment{$key}";+ }, array_keys($paymentIds));+ $sql .= " AND payment_method_id IN (" . implode(',', $placeholders) . ")";+ foreach ($paymentIds as $key => $paymentId) {+ $params[":payment{$key}"] = $paymentId;+ }+ }+ if (isset($_REQUEST['state']) && $_REQUEST['state'] != "") {+ $sql .= " AND inactive = :inactive";+ $params[':inactive'] = $_REQUEST['state'];+ }++ $orderByClauses = [];+ if (isset($_REQUEST['disabled_to_bottom']) && $_REQUEST['disabled_to_bottom'] === 'true') {+ if (in_array($sort, ["payer_user_id", "category_id", "payment_method_id"])) {+ $orderByClauses[] = "$sort $order";+ $orderByClauses[] = "inactive ASC";+ } else {+ $orderByClauses[] = "inactive ASC";+ $orderByClauses[] = "$sort $order";+ }+ } else {+ $orderByClauses[] = "$sort $order";+ if ($sort != "inactive") {+ $orderByClauses[] = "inactive ASC";+ }+ }+ if ($sort != "next_payment") {+ $orderByClauses[] = "next_payment ASC";+ }+ $sql .= " ORDER BY " . implode(", ", $orderByClauses);++ $stmt = $db->prepare($sql);+ if ($stmt === false) {+ $response = [+ "success" => false,+ "title" => "Invalid query parameters"+ ];+ echo json_encode($response);+ exit;+ }+ if (!empty($params)) {+ foreach ($params as $key => $value) {+ $stmt->bindValue($key, $value, SQLITE3_INTEGER);+ }+ }+ $result = $stmt->execute();+ if ($result) {+ $subscriptions = array();+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $subscriptions[] = $row;+ }+ }+ $subscriptionsToReturn = array();+ $payersBySubscription = getPayersBySubscription($db, $subscriptions);+ foreach ($subscriptions as $subscription) {+ $subscriptionToReturn = $subscription;+ if (isset($_REQUEST['convert_currency']) && $_REQUEST['convert_currency'] === 'true' && $canConvertCurrency && $subscription['currency_id'] != $userCurrencyId) {+ $subscriptionToReturn['price'] = getPriceConverted($subscription['price'], $subscription['currency_id'], $db);+ } else {+ $subscriptionToReturn['price'] = $subscription['price'];+ }+ $subscriptionToReturn['category_name'] = isset($categories[$subscription['category_id']]) ? $categories[$subscription['category_id']] : 'No category';+ $payerIdsForSubscription = $payersBySubscription[$subscription['id']] ?? [];+ $subscriptionToReturn['payer_user_ids'] = $payerIdsForSubscription;+ $subscriptionToReturn['payer_user_names'] = array_map(fn($payerId) => $members[$payerId] ?? 'Unknown member', $payerIdsForSubscription);+ $subscriptionToReturn['payer_user_name'] = isset($members[$subscription['payer_user_id']]) ? $members[$subscription['payer_user_id']] : 'Unknown member';+ $subscriptionToReturn['payment_method_name'] = isset($paymentMethods[$subscription['payment_method_id']]) ? $paymentMethods[$subscription['payment_method_id']] : 'Unknown payment method';+ $subscriptionsToReturn[] = $subscriptionToReturn;+ }++ $response = [+ "success" => true,+ "title" => "subscriptions",+ "subscriptions" => $subscriptionsToReturn,+ "notes" => []+ ];++ if ($allUserSubscription == 1 && $userId == 1) {+ $sql = "PRAGMA table_info(user)";+ $stmt = $db->prepare($sql);+ $result = $stmt->execute();+ $userColumns = array();+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $userColumns[] = $row['name'];+ }+ $userNameCol = in_array('username', $userColumns) ? 'username' : null;+ $userEmailCol = in_array('email', $userColumns) ? 'email' : null;+ if ($userNameCol && $userEmailCol) {+ $sql = "SELECT id, $userNameCol as name, $userEmailCol as email FROM user";+ } elseif ($userNameCol) {+ $sql = "SELECT id, $userNameCol as name FROM user";+ } elseif ($userEmailCol) {+ $sql = "SELECT id, $userEmailCol as email FROM user";+ } else {+ $sql = "SELECT id FROM user";+ }+ $stmt = $db->prepare($sql);+ $result = $stmt->execute();+ $users = array();+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $users[] = $row;+ }+ $response['users'] = $users;+ }++ echo json_encode($response);+ $db->close();+ exit;+++} else {+ $response = [+ "success" => false,+ "title" => "Invalid request method"+ ];+ echo json_encode($response);+ exit;}\ No newline at end of filediff --git a/api/subscriptions/set_subscriptions.php b/api/subscriptions/set_subscriptions.phpindex 39ec3ba..5725772 100644--- a/api/subscriptions/set_subscriptions.php+++ b/api/subscriptions/set_subscriptions.php@@ -16,7 +16,8 @@ For 'add' and 'edit' actions (all optional for 'edit'):- start_date: the start date of the subscription (YYYY-MM-DD).- auto_renew: whether the subscription auto renews (1 or 0, default 1).- payment_method_id: the payment method ID (integer).-- payer_user_id: the household member payer ID (integer).+- payer_user_id: the household member payer ID (integer), or several IDs separated by commas (1,2) / as an array+ (payer_user_id[]=1&payer_user_id[]=2) when the subscription is shared. The first one is the primary payer.- category_id: the category ID (integer).- notes: subscription notes (string, Markdown supported).- url: subscription URL (string).@@ -49,6 +50,7 @@ require_once '../../includes/connect_endpoint.php';require_once '../../includes/inputvalidation.php';require_once '../../includes/ssrf_helper.php';require_once '../../includes/logo_theme_variant.php';+require_once '../../includes/subscription_payers.php';header('Content-Type: application/json; charset=UTF-8');@@ -372,7 +374,8 @@ switch ($action) {$autoRenew = ($autoRenew === '0' || $autoRenew === 0) ? 0 : 1;$paymentMethodId = $_POST['payment_method_id'] ?? null;- $payerUserId = $_POST['payer_user_id'] ?? null;+ $payerIds = parsePayerIds($_POST['payer_user_id'] ?? []);+ $payerUserId = $payerIds[0] ?? null;$categoryId = $_POST['category_id'] ?? null;$notes = isset($_POST['notes']) ? validate_markdown($_POST['notes']) : '';@@ -479,20 +482,13 @@ switch ($action) {}// Payer user- if ($payerUserId !== null) {- $payerUserId = intval($payerUserId);- $payerStmt = $db->prepare("SELECT id FROM household WHERE id = :id AND user_id = :userId");- $payerStmt->bindValue(':id', $payerUserId, SQLITE3_INTEGER);- $payerStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $payerRes = $payerStmt->execute()->fetchArray();- if (!$payerRes) {- echo json_encode([- 'success' => false,- 'title' => 'Invalid payer ID',- 'message' => 'The specified household member does not exist or does not belong to you.'- ]);- exit;- }+ if (!payersBelongToUser($db, $userId, $payerIds)) {+ echo json_encode([+ 'success' => false,+ 'title' => 'Invalid payer ID',+ 'message' => 'The specified household member does not exist or does not belong to you.'+ ]);+ exit;}// Payment Method@@ -584,10 +580,12 @@ switch ($action) {$stmtInsert->bindParam(':startDate', $startDate, SQLITE3_TEXT);if ($stmtInsert->execute()) {+ $newSubscriptionId = $db->lastInsertRowID();+ saveSubscriptionPayers($db, $newSubscriptionId, $payerIds);$addResponse = ['success' => true,'title' => 'Subscription added',- 'subscriptionId' => $db->lastInsertRowID(),+ 'subscriptionId' => $newSubscriptionId,'message' => 'Subscription added successfully.'];if ($logoWarning !== '') {@@ -652,9 +650,12 @@ switch ($action) {$paymentMethodId = $_POST['payment_method_id'] === '' ? null : intval($_POST['payment_method_id']);}+ // null means the payers were not sent and stay as they are+ $payerIds = null;$payerUserId = $subscription['payer_user_id'];if (isset($_POST['payer_user_id'])) {- $payerUserId = $_POST['payer_user_id'] === '' ? null : intval($_POST['payer_user_id']);+ $payerIds = parsePayerIds($_POST['payer_user_id']);+ $payerUserId = $payerIds[0] ?? null;}$categoryId = $subscription['category_id'];@@ -772,19 +773,13 @@ switch ($action) {}// Payer- if ($payerUserId !== null) {- $payerStmt = $db->prepare("SELECT id FROM household WHERE id = :id AND user_id = :userId");- $payerStmt->bindValue(':id', $payerUserId, SQLITE3_INTEGER);- $payerStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $payerRes = $payerStmt->execute()->fetchArray();- if (!$payerRes) {- echo json_encode([- 'success' => false,- 'title' => 'Invalid payer ID',- 'message' => 'The specified household member does not exist or does not belong to you.'- ]);- exit;- }+ if ($payerIds !== null && !payersBelongToUser($db, $userId, $payerIds)) {+ echo json_encode([+ 'success' => false,+ 'title' => 'Invalid payer ID',+ 'message' => 'The specified household member does not exist or does not belong to you.'+ ]);+ exit;}// Payment Method@@ -905,6 +900,9 @@ switch ($action) {$stmtUpdate->bindParam(':userId', $userId, SQLITE3_INTEGER);if ($stmtUpdate->execute()) {+ if ($payerIds !== null) {+ saveSubscriptionPayers($db, $subscriptionId, $payerIds);+ }$updateResponse = ['success' => true,'title' => 'Subscription updated',@@ -953,6 +951,10 @@ switch ($action) {}// Delete+ $stmtPayers = $db->prepare("DELETE FROM subscription_payers WHERE subscription_id = :subId");+ $stmtPayers->bindParam(':subId', $subscriptionId, SQLITE3_INTEGER);+ $stmtPayers->execute();+$sqlDelete = "DELETE FROM subscriptions WHERE id = :subId AND user_id = :userId";$stmtDelete = $db->prepare($sqlDelete);$stmtDelete->bindParam(':subId', $subscriptionId, SQLITE3_INTEGER);diff --git a/endpoints/admin/deleteuser.php b/endpoints/admin/deleteuser.phpindex fe25fd5..dd36474 100644--- a/endpoints/admin/deleteuser.php+++ b/endpoints/admin/deleteuser.php@@ -1,214 +1,218 @@-<?php--require_once '../../includes/connect_endpoint.php';-require_once '../../includes/validate_endpoint_admin.php';-require_once '../../includes/logo_cleanup.php';--$postData = file_get_contents("php://input");-$data = json_decode($postData, true);--$userId = $data['userId'];--if ($userId == 1) {- die(json_encode([- "success" => false,- "message" => translate('error', $i18n)- ]));-} else {- // Collect this account's uploaded logo files before its rows go, so they- // can be removed from disk afterwards if nothing else references them.- $logoFilesToCheck = [];- $logoQuery = $db->prepare('SELECT logo, logo_variant FROM subscriptions WHERE user_id = :id');- $logoQuery->bindValue(':id', $userId, SQLITE3_INTEGER);- $logoResult = $logoQuery->execute();- while ($logoResult && ($logoRow = $logoResult->fetchArray(SQLITE3_ASSOC))) {- $logoFilesToCheck[] = $logoRow['logo'];- $logoFilesToCheck[] = $logoRow['logo_variant'];- }- $iconQuery = $db->prepare("SELECT icon FROM payment_methods WHERE user_id = :id AND icon NOT LIKE 'images/uploads/icons/%'");- $iconQuery->bindValue(':id', $userId, SQLITE3_INTEGER);- $iconResult = $iconQuery->execute();- while ($iconResult && ($iconRow = $iconResult->fetchArray(SQLITE3_ASSOC))) {- $logoFilesToCheck[] = $iconRow['icon'];- }-- // Delete user- $stmt = $db->prepare('DELETE FROM user WHERE id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete subscriptions- $stmt = $db->prepare('DELETE FROM subscriptions WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete settings- $stmt = $db->prepare('DELETE FROM settings WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete fixer- $stmt = $db->prepare('DELETE FROM fixer WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete custom colors- $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete currencies- $stmt = $db->prepare('DELETE FROM currencies WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete categories- $stmt = $db->prepare('DELETE FROM categories WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete household- $stmt = $db->prepare('DELETE FROM household WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete payment methods- $stmt = $db->prepare('DELETE FROM payment_methods WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete email notifications- $stmt = $db->prepare('DELETE FROM email_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete telegram notifications- $stmt = $db->prepare('DELETE FROM telegram_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete webhook notifications- $stmt = $db->prepare('DELETE FROM webhook_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete gotify notifications- $stmt = $db->prepare('DELETE FROM gotify_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete pushover notifications- $stmt = $db->prepare('DELETE FROM pushover_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Dele notification settings- $stmt = $db->prepare('DELETE FROM notification_settings WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete last exchange update- $stmt = $db->prepare('DELETE FROM last_exchange_update WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete email verification- $stmt = $db->prepare('DELETE FROM email_verification WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete totp- $stmt = $db->prepare('DELETE FROM totp WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete total yearly cost- $stmt = $db->prepare('DELETE FROM total_yearly_cost WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // The twelve tables this used to leave behind. Two of them hold- // credentials (a remember-me token and a password reset token) and the- // user table has no AUTOINCREMENT, so SQLite hands a deleted id straight- // back to the next account created. That account inherited them.-- // Delete login tokens- $stmt = $db->prepare('DELETE FROM login_tokens WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete password reset tokens- $stmt = $db->prepare('DELETE FROM password_resets WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete custom CSS- $stmt = $db->prepare('DELETE FROM custom_css_style WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete uploaded avatars- $stmt = $db->prepare('DELETE FROM uploaded_avatars WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete AI settings- $stmt = $db->prepare('DELETE FROM ai_settings WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete AI recommendations- $stmt = $db->prepare('DELETE FROM ai_recommendations WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete Google search settings- $stmt = $db->prepare('DELETE FROM google_search WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete ntfy notifications- $stmt = $db->prepare('DELETE FROM ntfy_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete Mattermost notifications- $stmt = $db->prepare('DELETE FROM mattermost_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete Discord notifications- $stmt = $db->prepare('DELETE FROM discord_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete PushPlus notifications- $stmt = $db->prepare('DELETE FROM pushplus_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete ServerChan notifications- $stmt = $db->prepare('DELETE FROM serverchan_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete push notification settings and every device subscription- $stmt = $db->prepare('DELETE FROM push_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- $stmt = $db->prepare('DELETE FROM push_subscriptions WHERE user_id = :id');- $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- // The account's rows are gone; drop its logo files that nothing else uses.- foreach (array_unique(array_filter($logoFilesToCheck)) as $logoFile) {- deleteLogoFileIfUnused($db, $logoFile, '../../images/uploads/logos/');- }-- die(json_encode([- "success" => true,- "message" => translate('success', $i18n)- ]));-+<?php++require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint_admin.php';+require_once '../../includes/logo_cleanup.php';++$postData = file_get_contents("php://input");+$data = json_decode($postData, true);++$userId = $data['userId'];++if ($userId == 1) {+ die(json_encode([+ "success" => false,+ "message" => translate('error', $i18n)+ ]));+} else {+ // Collect this account's uploaded logo files before its rows go, so they+ // can be removed from disk afterwards if nothing else references them.+ $logoFilesToCheck = [];+ $logoQuery = $db->prepare('SELECT logo, logo_variant FROM subscriptions WHERE user_id = :id');+ $logoQuery->bindValue(':id', $userId, SQLITE3_INTEGER);+ $logoResult = $logoQuery->execute();+ while ($logoResult && ($logoRow = $logoResult->fetchArray(SQLITE3_ASSOC))) {+ $logoFilesToCheck[] = $logoRow['logo'];+ $logoFilesToCheck[] = $logoRow['logo_variant'];+ }+ $iconQuery = $db->prepare("SELECT icon FROM payment_methods WHERE user_id = :id AND icon NOT LIKE 'images/uploads/icons/%'");+ $iconQuery->bindValue(':id', $userId, SQLITE3_INTEGER);+ $iconResult = $iconQuery->execute();+ while ($iconResult && ($iconRow = $iconResult->fetchArray(SQLITE3_ASSOC))) {+ $logoFilesToCheck[] = $iconRow['icon'];+ }++ // Delete user+ $stmt = $db->prepare('DELETE FROM user WHERE id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete subscriptions+ $stmt = $db->prepare('DELETE FROM subscription_payers WHERE subscription_id IN (SELECT id FROM subscriptions WHERE user_id = :id)');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $stmt->execute();++ $stmt = $db->prepare('DELETE FROM subscriptions WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete settings+ $stmt = $db->prepare('DELETE FROM settings WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete fixer+ $stmt = $db->prepare('DELETE FROM fixer WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete custom colors+ $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete currencies+ $stmt = $db->prepare('DELETE FROM currencies WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete categories+ $stmt = $db->prepare('DELETE FROM categories WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete household+ $stmt = $db->prepare('DELETE FROM household WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete payment methods+ $stmt = $db->prepare('DELETE FROM payment_methods WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete email notifications+ $stmt = $db->prepare('DELETE FROM email_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete telegram notifications+ $stmt = $db->prepare('DELETE FROM telegram_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete webhook notifications+ $stmt = $db->prepare('DELETE FROM webhook_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete gotify notifications+ $stmt = $db->prepare('DELETE FROM gotify_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete pushover notifications+ $stmt = $db->prepare('DELETE FROM pushover_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Dele notification settings+ $stmt = $db->prepare('DELETE FROM notification_settings WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete last exchange update+ $stmt = $db->prepare('DELETE FROM last_exchange_update WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete email verification+ $stmt = $db->prepare('DELETE FROM email_verification WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete totp+ $stmt = $db->prepare('DELETE FROM totp WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete total yearly cost+ $stmt = $db->prepare('DELETE FROM total_yearly_cost WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // The twelve tables this used to leave behind. Two of them hold+ // credentials (a remember-me token and a password reset token) and the+ // user table has no AUTOINCREMENT, so SQLite hands a deleted id straight+ // back to the next account created. That account inherited them.++ // Delete login tokens+ $stmt = $db->prepare('DELETE FROM login_tokens WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete password reset tokens+ $stmt = $db->prepare('DELETE FROM password_resets WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete custom CSS+ $stmt = $db->prepare('DELETE FROM custom_css_style WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete uploaded avatars+ $stmt = $db->prepare('DELETE FROM uploaded_avatars WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete AI settings+ $stmt = $db->prepare('DELETE FROM ai_settings WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete AI recommendations+ $stmt = $db->prepare('DELETE FROM ai_recommendations WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete Google search settings+ $stmt = $db->prepare('DELETE FROM google_search WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete ntfy notifications+ $stmt = $db->prepare('DELETE FROM ntfy_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete Mattermost notifications+ $stmt = $db->prepare('DELETE FROM mattermost_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete Discord notifications+ $stmt = $db->prepare('DELETE FROM discord_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete PushPlus notifications+ $stmt = $db->prepare('DELETE FROM pushplus_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete ServerChan notifications+ $stmt = $db->prepare('DELETE FROM serverchan_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete push notification settings and every device subscription+ $stmt = $db->prepare('DELETE FROM push_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ $stmt = $db->prepare('DELETE FROM push_subscriptions WHERE user_id = :id');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // The account's rows are gone; drop its logo files that nothing else uses.+ foreach (array_unique(array_filter($logoFilesToCheck)) as $logoFile) {+ deleteLogoFileIfUnused($db, $logoFile, '../../images/uploads/logos/');+ }++ die(json_encode([+ "success" => true,+ "message" => translate('success', $i18n)+ ]));+}\ No newline at end of filediff --git a/endpoints/cronjobs/sendcancellationnotifications.php b/endpoints/cronjobs/sendcancellationnotifications.phpindex 76b0244..f80baef 100644--- a/endpoints/cronjobs/sendcancellationnotifications.php+++ b/endpoints/cronjobs/sendcancellationnotifications.php@@ -14,6 +14,7 @@ require __DIR__ . '/../../libs/PHPMailer/Exception.php';require 'settimezone.php';require_once __DIR__ . '/../../includes/webhook_headers.php';+require_once __DIR__ . '/../../includes/subscription_payers.php';// Get all user ids$query = "SELECT id, username FROM user";@@ -191,20 +192,40 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$resultSubscriptions = $stmt->execute();$notify = [];+ $notifyOtherPayers = [];$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'];+ $allPayerIds = getPayersBySubscription($db, [$rowSubscription])[$rowSubscription['id']] ?? [];+ $entry = [+ 'name' => $rowSubscription['name'],+ 'price' => $rowSubscription['price'] . $currencies[$rowSubscription['currency_id']]['symbol'],+ 'currency' => $currencies[$rowSubscription['currency_id']]['name'],+ 'category' => $categories[$rowSubscription['category_id']]['name'],+ 'payer' => payerNamesLabel($allPayerIds, array_map(fn($member) => $member['name'], $household)) ?: $household[$rowSubscription['payer_user_id']]['name'],+ 'date' => $rowSubscription['next_payment'],+ 'url' => $rowSubscription['url'],+ 'notes' => $rowSubscription['notes'],+ ];+ // Every channel hears about it once, under the primary payer.+ // Email goes to each payer on their own address, see $notifyEmail.+ $notify[$rowSubscription['payer_user_id']][$i] = $entry;+ foreach ($allPayerIds as $extraPayerId) {+ if ($extraPayerId != $rowSubscription['payer_user_id']) {+ $notifyOtherPayers[$extraPayerId][$i] = $entry;+ }+ }$i++;}+ // Email reaches every payer, the other channels the primary one only+ $notifyEmail = $notify;+ foreach ($notifyOtherPayers as $payerId => $entries) {+ foreach ($entries as $index => $entry) {+ $notifyEmail[$payerId][$index] = $entry;+ }+ }+if (!empty($notify)) {// Email notifications if enabled@@ -221,7 +242,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$defaultEmail = $defaultUser['email'];$defaultName = $defaultUser['username'];- foreach ($notify as $userId => $perUser) {+ foreach ($notifyEmail as $payerUserId => $perUser) {$message = "The following subscriptions are up for cancellation:\n";foreach ($perUser as $subscription) {@@ -246,11 +267,19 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {}$mail->Port = $email['smtpPort'];- $stmt = $db->prepare('SELECT * FROM household WHERE id = :userId');- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt = $db->prepare('SELECT * FROM household WHERE id = :payerId AND user_id = :ownerId');+ $stmt->bindValue(':payerId', $payerUserId, SQLITE3_INTEGER);+ $stmt->bindValue(':ownerId', $userId, SQLITE3_INTEGER);$result = $stmt->execute();$user = $result->fetchArray(SQLITE3_ASSOC);+ // A payer without an address is skipped, except the primary+ // ones, who have always fallen back to the account's email.+ if (empty($user['email']) && isset($notifyOtherPayers[$payerUserId]) && !isset($notify[$payerUserId])) {+ echo "No email set for " . ($user['name'] ?? $payerUserId) . ", skipped.<br />";+ continue;+ }+$emailaddress = !empty($user['email']) ? $user['email'] : $defaultEmail;$name = !empty($user['name']) ? $user['name'] : $defaultName;diff --git a/endpoints/cronjobs/sendnotifications.php b/endpoints/cronjobs/sendnotifications.phpindex e700dcb..48b126b 100644--- a/endpoints/cronjobs/sendnotifications.php+++ b/endpoints/cronjobs/sendnotifications.php@@ -19,6 +19,7 @@ require __DIR__ . '/../../includes/budget_period_calculations.php';require 'settimezone.php';require_once __DIR__ . '/../../includes/webhook_headers.php';+require_once __DIR__ . '/../../includes/subscription_payers.php';if (php_sapi_name() == 'cli') {$date = new DateTime('now');@@ -368,6 +369,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$resultSubscriptions = $stmt->execute();$notify = [];+ $notifyOtherPayers = [];$i = 0;while ($rowSubscription = $resultSubscriptions->fetchArray(SQLITE3_ASSOC)) {if ($rowSubscription['notify_days_before'] !== -1) {@@ -383,21 +385,32 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {}if ($difference === $daysToCompare && $nextPaymentDate->format('Y-m-d') >= $currentDate->format('Y-m-d')) {+ $allPayerIds = getPayersBySubscription($db, [$rowSubscription])[$rowSubscription['id']] ?? [];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'];+ $entry = [+ 'name' => html_entity_decode($rowSubscription['name'], ENT_QUOTES, 'UTF-8'),+ 'price' => $rowSubscription['price'] . $currencies[$rowSubscription['currency_id']]['symbol'],+ 'currency' => $currencies[$rowSubscription['currency_id']]['name'],+ 'currency_symbol' => $currencies[$rowSubscription['currency_id']]['symbol'],+ 'formatted_price' => formatPrice($rowSubscription['price'], $currencies[$rowSubscription['currency_id']]['code'], $currencies[$rowSubscription['currency_id']]['symbol']),+ 'category' => $categories[$rowSubscription['category_id']]['name'],+ 'payer' => payerNamesLabel($allPayerIds, array_map(fn($member) => $member['name'], $household)) ?: $household[$rowSubscription['payer_user_id']]['name'],+ 'date' => $rowSubscription['next_payment'],+ 'days' => $daysToCompare,+ 'url' => $rowSubscription['url'],+ 'notes' => $rowSubscription['notes'],+ ];+ // Every channel hears about it once, under the primary payer.+ // Email goes to each payer on their own address, see $notifyEmail.+ $notify[$rowSubscription['payer_user_id']][$i] = $entry;+ foreach ($allPayerIds as $extraPayerId) {+ if ($extraPayerId != $rowSubscription['payer_user_id']) {+ $notifyOtherPayers[$extraPayerId][$i] = $entry;+ }+ }$i++;}}@@ -409,6 +422,14 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {}}+ // Email reaches every payer, the other channels the primary one only+ $notifyEmail = $notify;+ foreach ($notifyOtherPayers as $payerId => $entries) {+ foreach ($entries as $index => $entry) {+ $notifyEmail[$payerId][$index] = $entry;+ }+ }+if (!empty($notify)) {// Email notifications if enabled@@ -426,7 +447,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$defaultEmail = $defaultUser['email'];$defaultName = $defaultUser['username'];- foreach ($notify as $payerUserId => $perUser) {+ foreach ($notifyEmail as $payerUserId => $perUser) {$message = buildNotificationMessage("", $perUser, $periodSummaryLine, $sendPeriodStartSummaryOnly);if ($message === "") {continue;@@ -462,6 +483,13 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {$result = $stmt->execute();$user = $result->fetchArray(SQLITE3_ASSOC);+ // A payer without an address is skipped, except the primary+ // ones, who have always fallen back to the account's email.+ if (empty($user['email']) && isset($notifyOtherPayers[$payerUserId]) && !isset($notify[$payerUserId])) {+ echo "No email set for " . ($user['name'] ?? $payerUserId) . ", skipped.<br />";+ continue;+ }+$emailaddress = !empty($user['email']) ? $user['email'] : $defaultEmail;$name = !empty($user['name']) ? $user['name'] : $defaultName;diff --git a/endpoints/household/household.php b/endpoints/household/household.phpindex 520a911..aa2af0b 100644--- a/endpoints/household/household.php+++ b/endpoints/household/household.php@@ -1,132 +1,132 @@-<?php-require_once '../../includes/connect_endpoint.php';-require_once '../../includes/inputvalidation.php';-require_once '../../includes/validate_endpoint.php';--$action = $_POST['action'] ?? '';--switch ($action) {- case 'add':- handleAddMember($db, $userId, $i18n);- break;- case 'edit':- handleEditMember($db, $userId, $i18n);- break;- case 'delete':- handleDeleteMember($db, $userId, $i18n);- break;- default:- echo translate('error', $i18n);- break;-}--function handleAddMember($db, $userId, $i18n)-{- $householdName = "Member";- $sqlInsert = "INSERT INTO household (name, user_id) VALUES (:name, :userId)";- $stmtInsert = $db->prepare($sqlInsert);- $stmtInsert->bindParam(':name', $householdName, SQLITE3_TEXT);- $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);- $resultInsert = $stmtInsert->execute();-- if ($resultInsert) {- $householdId = $db->lastInsertRowID();- $response = [- "success" => true,- "householdId" => $householdId,- ];- echo json_encode($response);- } else {- $response = [- "success" => false,- "message" => translate('failed_add_household', $i18n)- ];- echo json_encode($response);- }-}--function handleEditMember($db, $userId, $i18n)-{- if (isset($_POST['memberId']) && $_POST['memberId'] != "" && isset($_POST['name']) && $_POST['name'] != "") {- $memberId = $_POST['memberId'];- $name = validate($_POST['name']);- $email = $_POST['email'] ? $_POST['email'] : "";- $email = validate($email);- $sql = "UPDATE household SET name = :name, email = :email WHERE id = :memberId AND user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindParam(':name', $name, SQLITE3_TEXT);- $stmt->bindParam(':email', $email, SQLITE3_TEXT);- $stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- if ($result) {- $response = [- "success" => true,- "message" => translate('member_saved', $i18n)- ];- echo json_encode($response);- } else {- $response = [- "success" => false,- "message" => translate('failed_edit_household', $i18n)- ];- echo json_encode($response);- }- } else {- $response = [- "success" => false,- "message" => translate('fill_all_fields', $i18n)- ];- echo json_encode($response);- }-}--function handleDeleteMember($db, $userId, $i18n)-{- if (isset($_POST['memberId']) && $_POST['memberId'] != "" && $_POST['memberId'] != 1) {- $memberId = $_POST['memberId'];- $checkMember = "SELECT COUNT(*) FROM subscriptions WHERE payer_user_id = :memberId AND user_id = :userId";- $checkStmt = $db->prepare($checkMember);- $checkStmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);- $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $checkResult = $checkStmt->execute();- $row = $checkResult->fetchArray();- $count = $row[0];-- if ($count > 0) {- $response = [- "success" => false,- "message" => translate('household_in_use', $i18n)- ];- echo json_encode($response);- } else {- $sql = "DELETE FROM household WHERE id = :memberId and user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();- if ($result) {- $response = [- "success" => true,- "message" => translate('member_removed', $i18n)- ];- echo json_encode($response);- } else {- $response = [- "success" => false,- "message" => translate('failed_remove_household', $i18n)- ];- echo json_encode($response);- }- }- } else {- $response = [- "success" => false,- "message" => translate('failed_remove_household', $i18n)- ];- echo json_encode($response);- }-}-+<?php+require_once '../../includes/connect_endpoint.php';+require_once '../../includes/inputvalidation.php';+require_once '../../includes/validate_endpoint.php';++$action = $_POST['action'] ?? '';++switch ($action) {+ case 'add':+ handleAddMember($db, $userId, $i18n);+ break;+ case 'edit':+ handleEditMember($db, $userId, $i18n);+ break;+ case 'delete':+ handleDeleteMember($db, $userId, $i18n);+ break;+ default:+ echo translate('error', $i18n);+ break;+}++function handleAddMember($db, $userId, $i18n)+{+ $householdName = "Member";+ $sqlInsert = "INSERT INTO household (name, user_id) VALUES (:name, :userId)";+ $stmtInsert = $db->prepare($sqlInsert);+ $stmtInsert->bindParam(':name', $householdName, SQLITE3_TEXT);+ $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $resultInsert = $stmtInsert->execute();++ if ($resultInsert) {+ $householdId = $db->lastInsertRowID();+ $response = [+ "success" => true,+ "householdId" => $householdId,+ ];+ echo json_encode($response);+ } else {+ $response = [+ "success" => false,+ "message" => translate('failed_add_household', $i18n)+ ];+ echo json_encode($response);+ }+}++function handleEditMember($db, $userId, $i18n)+{+ if (isset($_POST['memberId']) && $_POST['memberId'] != "" && isset($_POST['name']) && $_POST['name'] != "") {+ $memberId = $_POST['memberId'];+ $name = validate($_POST['name']);+ $email = $_POST['email'] ? $_POST['email'] : "";+ $email = validate($email);+ $sql = "UPDATE household SET name = :name, email = :email WHERE id = :memberId AND user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindParam(':name', $name, SQLITE3_TEXT);+ $stmt->bindParam(':email', $email, SQLITE3_TEXT);+ $stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ if ($result) {+ $response = [+ "success" => true,+ "message" => translate('member_saved', $i18n)+ ];+ echo json_encode($response);+ } else {+ $response = [+ "success" => false,+ "message" => translate('failed_edit_household', $i18n)+ ];+ echo json_encode($response);+ }+ } else {+ $response = [+ "success" => false,+ "message" => translate('fill_all_fields', $i18n)+ ];+ echo json_encode($response);+ }+}++function handleDeleteMember($db, $userId, $i18n)+{+ if (isset($_POST['memberId']) && $_POST['memberId'] != "" && $_POST['memberId'] != 1) {+ $memberId = $_POST['memberId'];+ $checkMember = "SELECT COUNT(*) FROM subscriptions WHERE (payer_user_id = :memberId OR id IN (SELECT subscription_id FROM subscription_payers WHERE payer_id = :memberId)) AND user_id = :userId";+ $checkStmt = $db->prepare($checkMember);+ $checkStmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);+ $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $checkResult = $checkStmt->execute();+ $row = $checkResult->fetchArray();+ $count = $row[0];++ if ($count > 0) {+ $response = [+ "success" => false,+ "message" => translate('household_in_use', $i18n)+ ];+ echo json_encode($response);+ } else {+ $sql = "DELETE FROM household WHERE id = :memberId and user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();+ if ($result) {+ $response = [+ "success" => true,+ "message" => translate('member_removed', $i18n)+ ];+ echo json_encode($response);+ } else {+ $response = [+ "success" => false,+ "message" => translate('failed_remove_household', $i18n)+ ];+ echo json_encode($response);+ }+ }+ } else {+ $response = [+ "success" => false,+ "message" => translate('failed_remove_household', $i18n)+ ];+ echo json_encode($response);+ }+}+?>\ No newline at end of filediff --git a/endpoints/settings/deleteaccount.php b/endpoints/settings/deleteaccount.phpindex 18ac12d..4d37009 100644--- a/endpoints/settings/deleteaccount.php+++ b/endpoints/settings/deleteaccount.php@@ -1,214 +1,218 @@-<?php--require_once '../../includes/connect_endpoint.php';-require_once '../../includes/validate_endpoint.php';-require_once '../../includes/logo_cleanup.php';--$postData = file_get_contents("php://input");-$data = json_decode($postData, true);--$userIdToDelete = $data['userId'];--if ($userIdToDelete == 1 || $userIdToDelete != $userId) {- die(json_encode([- "success" => false,- "message" => translate('error', $i18n)- ]));-} else {- // Collect this account's uploaded logo files before its rows go, so they- // can be removed from disk afterwards if nothing else references them.- $logoFilesToCheck = [];- $logoQuery = $db->prepare('SELECT logo, logo_variant FROM subscriptions WHERE user_id = :id');- $logoQuery->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $logoResult = $logoQuery->execute();- while ($logoResult && ($logoRow = $logoResult->fetchArray(SQLITE3_ASSOC))) {- $logoFilesToCheck[] = $logoRow['logo'];- $logoFilesToCheck[] = $logoRow['logo_variant'];- }- $iconQuery = $db->prepare("SELECT icon FROM payment_methods WHERE user_id = :id AND icon NOT LIKE 'images/uploads/icons/%'");- $iconQuery->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $iconResult = $iconQuery->execute();- while ($iconResult && ($iconRow = $iconResult->fetchArray(SQLITE3_ASSOC))) {- $logoFilesToCheck[] = $iconRow['icon'];- }-- // Delete user- $stmt = $db->prepare('DELETE FROM user WHERE id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete subscriptions- $stmt = $db->prepare('DELETE FROM subscriptions WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete settings- $stmt = $db->prepare('DELETE FROM settings WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete fixer- $stmt = $db->prepare('DELETE FROM fixer WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete custom colors- $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete currencies- $stmt = $db->prepare('DELETE FROM currencies WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete categories- $stmt = $db->prepare('DELETE FROM categories WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete household- $stmt = $db->prepare('DELETE FROM household WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete payment methods- $stmt = $db->prepare('DELETE FROM payment_methods WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete email notifications- $stmt = $db->prepare('DELETE FROM email_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete telegram notifications- $stmt = $db->prepare('DELETE FROM telegram_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete webhook notifications- $stmt = $db->prepare('DELETE FROM webhook_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete gotify notifications- $stmt = $db->prepare('DELETE FROM gotify_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete pushover notifications- $stmt = $db->prepare('DELETE FROM pushover_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Dele notification settings- $stmt = $db->prepare('DELETE FROM notification_settings WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete last exchange update- $stmt = $db->prepare('DELETE FROM last_exchange_update WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete email verification- $stmt = $db->prepare('DELETE FROM email_verification WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete totp- $stmt = $db->prepare('DELETE FROM totp WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete total yearly cost- $stmt = $db->prepare('DELETE FROM total_yearly_cost WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // The twelve tables this used to leave behind. Two of them hold- // credentials (a remember-me token and a password reset token) and the- // user table has no AUTOINCREMENT, so SQLite hands a deleted id straight- // back to the next account created. That account inherited them.-- // Delete login tokens- $stmt = $db->prepare('DELETE FROM login_tokens WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete password reset tokens- $stmt = $db->prepare('DELETE FROM password_resets WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete custom CSS- $stmt = $db->prepare('DELETE FROM custom_css_style WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete uploaded avatars- $stmt = $db->prepare('DELETE FROM uploaded_avatars WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete AI settings- $stmt = $db->prepare('DELETE FROM ai_settings WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete AI recommendations- $stmt = $db->prepare('DELETE FROM ai_recommendations WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete Google search settings- $stmt = $db->prepare('DELETE FROM google_search WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete ntfy notifications- $stmt = $db->prepare('DELETE FROM ntfy_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete Mattermost notifications- $stmt = $db->prepare('DELETE FROM mattermost_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete Discord notifications- $stmt = $db->prepare('DELETE FROM discord_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete PushPlus notifications- $stmt = $db->prepare('DELETE FROM pushplus_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete ServerChan notifications- $stmt = $db->prepare('DELETE FROM serverchan_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // Delete push notification settings and every device subscription- $stmt = $db->prepare('DELETE FROM push_notifications WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- $stmt = $db->prepare('DELETE FROM push_subscriptions WHERE user_id = :id');- $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);- $result = $stmt->execute();-- // The account's rows are gone; drop its logo files that nothing else uses.- foreach (array_unique(array_filter($logoFilesToCheck)) as $logoFile) {- deleteLogoFileIfUnused($db, $logoFile, '../../images/uploads/logos/');- }-- die(json_encode([- "success" => true,- "message" => translate('success', $i18n)- ]));-+<?php++require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint.php';+require_once '../../includes/logo_cleanup.php';++$postData = file_get_contents("php://input");+$data = json_decode($postData, true);++$userIdToDelete = $data['userId'];++if ($userIdToDelete == 1 || $userIdToDelete != $userId) {+ die(json_encode([+ "success" => false,+ "message" => translate('error', $i18n)+ ]));+} else {+ // Collect this account's uploaded logo files before its rows go, so they+ // can be removed from disk afterwards if nothing else references them.+ $logoFilesToCheck = [];+ $logoQuery = $db->prepare('SELECT logo, logo_variant FROM subscriptions WHERE user_id = :id');+ $logoQuery->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $logoResult = $logoQuery->execute();+ while ($logoResult && ($logoRow = $logoResult->fetchArray(SQLITE3_ASSOC))) {+ $logoFilesToCheck[] = $logoRow['logo'];+ $logoFilesToCheck[] = $logoRow['logo_variant'];+ }+ $iconQuery = $db->prepare("SELECT icon FROM payment_methods WHERE user_id = :id AND icon NOT LIKE 'images/uploads/icons/%'");+ $iconQuery->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $iconResult = $iconQuery->execute();+ while ($iconResult && ($iconRow = $iconResult->fetchArray(SQLITE3_ASSOC))) {+ $logoFilesToCheck[] = $iconRow['icon'];+ }++ // Delete user+ $stmt = $db->prepare('DELETE FROM user WHERE id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete subscriptions+ $stmt = $db->prepare('DELETE FROM subscription_payers WHERE subscription_id IN (SELECT id FROM subscriptions WHERE user_id = :id)');+ $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);+ $stmt->execute();++ $stmt = $db->prepare('DELETE FROM subscriptions WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete settings+ $stmt = $db->prepare('DELETE FROM settings WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete fixer+ $stmt = $db->prepare('DELETE FROM fixer WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete custom colors+ $stmt = $db->prepare('DELETE FROM custom_colors WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete currencies+ $stmt = $db->prepare('DELETE FROM currencies WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete categories+ $stmt = $db->prepare('DELETE FROM categories WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete household+ $stmt = $db->prepare('DELETE FROM household WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete payment methods+ $stmt = $db->prepare('DELETE FROM payment_methods WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete email notifications+ $stmt = $db->prepare('DELETE FROM email_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete telegram notifications+ $stmt = $db->prepare('DELETE FROM telegram_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete webhook notifications+ $stmt = $db->prepare('DELETE FROM webhook_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete gotify notifications+ $stmt = $db->prepare('DELETE FROM gotify_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete pushover notifications+ $stmt = $db->prepare('DELETE FROM pushover_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Dele notification settings+ $stmt = $db->prepare('DELETE FROM notification_settings WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete last exchange update+ $stmt = $db->prepare('DELETE FROM last_exchange_update WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete email verification+ $stmt = $db->prepare('DELETE FROM email_verification WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete totp+ $stmt = $db->prepare('DELETE FROM totp WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete total yearly cost+ $stmt = $db->prepare('DELETE FROM total_yearly_cost WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // The twelve tables this used to leave behind. Two of them hold+ // credentials (a remember-me token and a password reset token) and the+ // user table has no AUTOINCREMENT, so SQLite hands a deleted id straight+ // back to the next account created. That account inherited them.++ // Delete login tokens+ $stmt = $db->prepare('DELETE FROM login_tokens WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete password reset tokens+ $stmt = $db->prepare('DELETE FROM password_resets WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete custom CSS+ $stmt = $db->prepare('DELETE FROM custom_css_style WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete uploaded avatars+ $stmt = $db->prepare('DELETE FROM uploaded_avatars WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete AI settings+ $stmt = $db->prepare('DELETE FROM ai_settings WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete AI recommendations+ $stmt = $db->prepare('DELETE FROM ai_recommendations WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete Google search settings+ $stmt = $db->prepare('DELETE FROM google_search WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete ntfy notifications+ $stmt = $db->prepare('DELETE FROM ntfy_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete Mattermost notifications+ $stmt = $db->prepare('DELETE FROM mattermost_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete Discord notifications+ $stmt = $db->prepare('DELETE FROM discord_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete PushPlus notifications+ $stmt = $db->prepare('DELETE FROM pushplus_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete ServerChan notifications+ $stmt = $db->prepare('DELETE FROM serverchan_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // Delete push notification settings and every device subscription+ $stmt = $db->prepare('DELETE FROM push_notifications WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ $stmt = $db->prepare('DELETE FROM push_subscriptions WHERE user_id = :id');+ $stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $result = $stmt->execute();++ // The account's rows are gone; drop its logo files that nothing else uses.+ foreach (array_unique(array_filter($logoFilesToCheck)) as $logoFile) {+ deleteLogoFileIfUnused($db, $logoFile, '../../images/uploads/logos/');+ }++ die(json_encode([+ "success" => true,+ "message" => translate('success', $i18n)+ ]));+}\ No newline at end of filediff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.phpindex 03d4e03..bcec7f2 100644--- a/endpoints/subscription/add.php+++ b/endpoints/subscription/add.php@@ -1,485 +1,484 @@-<?php-error_reporting(E_ERROR | E_PARSE);-require_once '../../includes/connect_endpoint.php';-require_once '../../includes/validate_endpoint.php';-require_once '../../includes/inputvalidation.php';-require_once '../../includes/getsettings.php';-require_once '../../includes/ssrf_helper.php';-require_once '../../includes/logo_theme_variant.php';-require_once '../../includes/logo_cleanup.php';--if (!file_exists('../../images/uploads/logos')) {- mkdir('../../images/uploads/logos', 0777, true);- mkdir('../../images/uploads/logos/avatars', 0777, true);-}--function sanitizeFilename($filename)-{- $filename = preg_replace("/[^a-zA-Z0-9\s]/", "", $filename);- $filename = str_replace(" ", "-", $filename);- $filename = str_replace(".", "", $filename);- return $filename;-}--function validateFileExtension($fileExtension)-{- $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp'];- return in_array($fileExtension, $allowedExtensions);-}--function getLogoFromUrl($url, $uploadDir, $name, $settings, $i18n)-{- $maxRedirects = 3;- $currentUrl = $url;-- for ($i = 0; $i <= $maxRedirects; $i++) {- if (!filter_var($currentUrl, FILTER_VALIDATE_URL) || !preg_match('/^https?:\/\//i', $currentUrl)) {- return ['success' => false, 'message' => 'Invalid URL format.'];- }-- $parts = parse_url($currentUrl);- $host = $parts['host'];- $port = $parts['port'] ?? ($parts['scheme'] === 'https' ? 443 : 80);-- $ip = gethostbyname($host);-- if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false- || is_cgnat_ip($ip)) {- return ['success' => false, 'message' => 'Invalid IP Address.'];- }-- $ch = curl_init($currentUrl);- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);- curl_setopt($ch, CURLOPT_TIMEOUT, 5);- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Manual handling to re-validate IPs-- curl_setopt($ch, CURLOPT_RESOLVE, ["$host:$port:$ip"]);-- $imageData = curl_exec($ch);- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);-- if ($httpCode >= 300 && $httpCode < 400) {- $redirectUrl = curl_getinfo($ch, CURLINFO_REDIRECT_URL);- unset($ch);-- if (!$redirectUrl) {- break;- }-- $currentUrl = $redirectUrl;- continue;- }-- if ($imageData !== false && $httpCode === 200) {- $timestamp = time();- $fileName = $timestamp . '-' . sanitizeFilename($name) . '.png';- $uploadFile = $uploadDir . $fileName; // Note: Use the provided $uploadDir variable-- if (saveLogo($imageData, $uploadFile, $name, $settings)) {- unset($ch);- return ['success' => true, 'filename' => $fileName];- }-- unset($ch);- return ['success' => false, 'message' => translate('error_saving_logo', $i18n)];- }-- $error = curl_error($ch);- unset($ch);- return ['success' => false, 'message' => translate('error_fetching_image', $i18n) . ': ' . $error];- }-- return ['success' => false, 'message' => translate('error_fetching_image', $i18n)];-}--function saveLogo($imageData, $uploadFile, $name, $settings)-{- $image = imagecreatefromstring($imageData);- $removeBackground = isset($settings['removeBackground']) && $settings['removeBackground'] === 'true';-- if ($image !== false) {- $tempFile = tempnam(sys_get_temp_dir(), 'logo');-- imagealphablending($image, false);- imagesavealpha($image, true);- imagepng($image, $tempFile);- imagedestroy($image);-- $newImage = imagecreatefrompng($tempFile);- if ($newImage !== false) {- imagealphablending($newImage, false);- imagesavealpha($newImage, true);-- if ($removeBackground) {- require_once __DIR__ . '/../../includes/gd_background_removal.php';- // On palette images imagecolorat() returns palette indexes, not RGB values- if (!imageistruecolor($newImage)) {- imagepalettetotruecolor($newImage);- imagealphablending($newImage, false);- imagesavealpha($newImage, true);- }- // Paint out the corner color with ~10% fuzz- $corner = imagecolorat($newImage, 0, 0);- if ((($corner >> 24) & 0x7F) !== 127) {- gdRemoveBackgroundColor($newImage, ($corner >> 16) & 0xFF, ($corner >> 8) & 0xFF, $corner & 0xFF);- }- }-- // Crop/trim transparent margins- require_once __DIR__ . '/../../includes/gd_background_removal.php';- $newImage = gdCropTransparent($newImage, 2);-- $saved = imagepng($newImage, $uploadFile);- imagedestroy($newImage);- } else {- unlink($tempFile);- return false;- }-- unlink($tempFile);- return $saved;- }-- return false;-}--function resizeAndUploadLogo($uploadedFile, $uploadDir, $name, $settings)-{- $targetWidth = 135;- $targetHeight = 42;-- $timestamp = time();- $originalFileName = $uploadedFile['name'];- $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);- $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png';- $fileName = $timestamp . '-' . sanitizeFilename($name) . '.' . $fileExtension;- $uploadFile = $uploadDir . $fileName;-- if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) {- $fileInfo = getimagesize($uploadFile);-- if ($fileInfo !== false) {- $width = $fileInfo[0];- $height = $fileInfo[1];-- if ($fileExtension === 'png') {- $image = imagecreatefrompng($uploadFile);- } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {- $image = imagecreatefromjpeg($uploadFile);- } elseif ($fileExtension === 'gif') {- $image = imagecreatefromgif($uploadFile);- } elseif ($fileExtension === 'webp') {- $image = imagecreatefromwebp($uploadFile);- } else {- return "";- }-- if ($fileExtension === 'png') {- imagesavealpha($image, true);- }-- // Crop/trim transparent margins (ensure we update dimensions after cropping)- require_once __DIR__ . '/../../includes/gd_background_removal.php';- $image = gdCropTransparent($image, 2);- $width = imagesx($image);- $height = imagesy($image);-- $newWidth = $width;- $newHeight = $height;-- if ($width > $targetWidth) {- $newWidth = (int) $targetWidth;- $newHeight = (int) (($targetWidth / $width) * $height);- }-- if ($newHeight > $targetHeight) {- $newWidth = (int) (($targetHeight / $newHeight) * $newWidth);- $newHeight = (int) $targetHeight;- }-- $resizedImage = imagecreatetruecolor($newWidth, $newHeight);- imagesavealpha($resizedImage, true);- $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);- imagefill($resizedImage, 0, 0, $transparency);- imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);-- if ($fileExtension === 'png') {- $saved = imagepng($resizedImage, $uploadFile);- } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {- $saved = imagejpeg($resizedImage, $uploadFile);- } elseif ($fileExtension === 'gif') {- $saved = imagegif($resizedImage, $uploadFile);- } elseif ($fileExtension === 'webp') {- $saved = imagewebp($resizedImage, $uploadFile);- } else {- return "";- }-- imagedestroy($image);- imagedestroy($resizedImage);-- if (!$saved) {- if (file_exists($uploadFile)) {- unlink($uploadFile);- }- return "";- }-- return $fileName;- }- }-- return "";-}--$isEdit = isset($_POST['id']) && $_POST['id'] != "";-$name = validate($_POST["name"]);-$price = $_POST['price'];-$currencyId = $_POST["currency_id"];-$frequency = $_POST["frequency"];-$cycle = $_POST["cycle"];-$nextPayment = $_POST["next_payment"];-$autoRenew = isset($_POST['auto_renew']) ? true : false;-$startDate = $_POST["start_date"];-$paymentMethodId = $_POST["payment_method_id"];-$payerUserId = $_POST["payer_user_id"];-$categoryId = $_POST['category_id'];-$notes = validate_markdown($_POST["notes"]);-$url = validate($_POST['url']);-$logoUrl = validate($_POST['logo-url']);-$logo = "";-$logoError = "";-$notify = isset($_POST['notifications']) ? true : false;-$notifyDaysBefore = $_POST['notify_days_before'];-$inactive = isset($_POST['inactive']) ? true : false;-$cancellationDate = $_POST['cancellation_date'] ?? null;-$replacementSubscriptionId = $_POST['replacement_subscription_id'];--if ($replacementSubscriptionId == 0 || $inactive == 0) {- $replacementSubscriptionId = null;-}--if ($replacementSubscriptionId !== null) {- $ownerCheck = $db->prepare("SELECT id FROM subscriptions WHERE id = :id AND user_id = :userId");- $ownerCheck->bindParam(':id', $replacementSubscriptionId, SQLITE3_INTEGER);- $ownerCheck->bindParam(':userId', $userId, SQLITE3_INTEGER);- $ownerResult = $ownerCheck->execute();- if (!$ownerResult || !$ownerResult->fetchArray()) {- $replacementSubscriptionId = null;- }-}--// Reject any foreign key that doesn't belong to the authenticated user, so a-// subscription can't be attached to another tenant's currency/category/-// household member/payment method (IDs are global auto-increment integers-// and easily enumerable).-function rejectForeignId($message)-{- header('Content-Type: application/json');- echo json_encode(['status' => 'Error', 'message' => $message]);- exit();-}--$currStmt = $db->prepare("SELECT id FROM currencies WHERE id = :id AND user_id = :userId");-$currStmt->bindParam(':id', $currencyId, SQLITE3_INTEGER);-$currStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);-$currResult = $currStmt->execute();-if (!$currResult || !$currResult->fetchArray()) {- rejectForeignId('The specified currency does not exist or does not belong to you.');-}--if ($categoryId !== null && $categoryId !== '') {- $catStmt = $db->prepare("SELECT id FROM categories WHERE id = :id AND user_id = :userId");- $catStmt->bindParam(':id', $categoryId, SQLITE3_INTEGER);- $catStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $catResult = $catStmt->execute();- if (!$catResult || !$catResult->fetchArray()) {- rejectForeignId('The specified category does not exist or does not belong to you.');- }-}--if ($payerUserId !== null && $payerUserId !== '') {- $payerStmt = $db->prepare("SELECT id FROM household WHERE id = :id AND user_id = :userId");- $payerStmt->bindParam(':id', $payerUserId, SQLITE3_INTEGER);- $payerStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $payerResult = $payerStmt->execute();- if (!$payerResult || !$payerResult->fetchArray()) {- rejectForeignId('The specified household member does not exist or does not belong to you.');- }-}--if ($paymentMethodId !== null && $paymentMethodId !== '') {- $pmStmt = $db->prepare("SELECT id FROM payment_methods WHERE id = :id AND (user_id = :userId OR user_id = 0 OR user_id IS NULL)");- $pmStmt->bindParam(':id', $paymentMethodId, SQLITE3_INTEGER);- $pmStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $pmResult = $pmStmt->execute();- if (!$pmResult || !$pmResult->fetchArray()) {- rejectForeignId('The specified payment method does not exist or does not belong to you.');- }-}--if ($logoUrl !== "") {- $result = getLogoFromUrl($logoUrl, '../../images/uploads/logos/', $name, $settings, $i18n);- if ($result['success']) {- $logo = $result['filename'];- } else {- $logoError = $result['message'];- }-} else {- if (!empty($_FILES['logo']['name'])) {- $fileType = mime_content_type($_FILES['logo']['tmp_name']);- if (strpos($fileType, 'image') === false) {- echo translate("fill_all_fields", $i18n);- exit();- }- $logo = resizeAndUploadLogo($_FILES['logo'], '../../images/uploads/logos/', $name, $settings);- if ($logo === "") {- $logoError = translate('error_saving_logo', $i18n);- }- }-}--$logoTextColor = null;-$logoVariant = null;-$removeBackgroundEnabled = isset($settings['removeBackground']) && $settings['removeBackground'] === 'true';--// Themed variant generation piggybacks on the same "remove background"-// setting: both only make sense for logos we're already reprocessing, and-// this avoids running pixel classification on every single upload.-if ($logo !== "" && $removeBackgroundEnabled) {- $logoExtension = strtolower(pathinfo($logo, PATHINFO_EXTENSION));- $logoPath = '../../images/uploads/logos/' . $logo;-- if ($logoExtension === 'png' || $logoExtension === 'webp') {- $sourceImage = $logoExtension === 'png' ? imagecreatefrompng($logoPath) : imagecreatefromwebp($logoPath);-- if ($sourceImage !== false) {- imagealphablending($sourceImage, false);- imagesavealpha($sourceImage, true);-- $logoTextColor = classifyLogoTextColor($sourceImage);-- if ($logoTextColor !== null) {- $variantImage = generateThemedLogoVariant($sourceImage);- $logoVariant = pathinfo($logo, PATHINFO_FILENAME) . '-variant.png';- imagepng($variantImage, '../../images/uploads/logos/' . $logoVariant);- imagedestroy($variantImage);- }-- imagedestroy($sourceImage);- }- }-}--if (!$isEdit) {- $sql = "INSERT INTO subscriptions (- name, logo, price, currency_id, next_payment, cycle, frequency, notes,- payment_method_id, payer_user_id, category_id, notify, inactive, url,- notify_days_before, user_id, cancellation_date, replacement_subscription_id,- auto_renew, start_date, logo_text_color, logo_variant- ) VALUES (- :name, :logo, :price, :currencyId, :nextPayment, :cycle, :frequency, :notes,- :paymentMethodId, :payerUserId, :categoryId, :notify, :inactive, :url,- :notifyDaysBefore, :userId, :cancellationDate, :replacement_subscription_id,- :autoRenew, :startDate, :logoTextColor, :logoVariant- )";-} else {- $id = $_POST['id'];-- // When the logo is being replaced, remember the old files so they can be- // removed after the update instead of lingering as orphans.- $oldLogo = null;- $oldLogoVariant = null;- if ($logo != "") {- $oldLogoStmt = $db->prepare("SELECT logo, logo_variant FROM subscriptions WHERE id = :id AND user_id = :userId");- $oldLogoStmt->bindParam(':id', $id, SQLITE3_INTEGER);- $oldLogoStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $oldLogoResult = $oldLogoStmt->execute();- if ($oldLogoResult && ($oldLogoRow = $oldLogoResult->fetchArray(SQLITE3_ASSOC))) {- $oldLogo = $oldLogoRow['logo'];- $oldLogoVariant = $oldLogoRow['logo_variant'];- }- }-- $sql = "UPDATE subscriptions SET- name = :name,- price = :price,- currency_id = :currencyId,- next_payment = :nextPayment,- auto_renew = :autoRenew,- start_date = :startDate,- cycle = :cycle,- frequency = :frequency,- notes = :notes,- payment_method_id = :paymentMethodId,- payer_user_id = :payerUserId,- category_id = :categoryId,- notify = :notify,- inactive = :inactive,- url = :url,- notify_days_before = :notifyDaysBefore,- cancellation_date = :cancellationDate,- replacement_subscription_id = :replacement_subscription_id";-- if ($logo != "") {- $sql .= ", logo = :logo, logo_text_color = :logoTextColor, logo_variant = :logoVariant";- }-- $sql .= " WHERE id = :id AND user_id = :userId";-}--$stmt = $db->prepare($sql);-$stmt->bindParam(':name', $name, SQLITE3_TEXT);-if ($logo != "") {- $stmt->bindParam(':logo', $logo, SQLITE3_TEXT);- $stmt->bindParam(':logoTextColor', $logoTextColor, SQLITE3_TEXT);- $stmt->bindParam(':logoVariant', $logoVariant, SQLITE3_TEXT);-}-$stmt->bindParam(':price', $price, SQLITE3_FLOAT);-$stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);-$stmt->bindParam(':nextPayment', $nextPayment, SQLITE3_TEXT);-$stmt->bindParam(':autoRenew', $autoRenew, SQLITE3_INTEGER);-$stmt->bindParam(':startDate', $startDate, SQLITE3_TEXT);-$stmt->bindParam(':cycle', $cycle, SQLITE3_INTEGER);-$stmt->bindParam(':frequency', $frequency, SQLITE3_INTEGER);-$stmt->bindParam(':notes', $notes, SQLITE3_TEXT);-$stmt->bindParam(':paymentMethodId', $paymentMethodId, SQLITE3_INTEGER);-$stmt->bindParam(':payerUserId', $payerUserId, SQLITE3_INTEGER);-$stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);-$stmt->bindParam(':notify', $notify, SQLITE3_INTEGER);-$stmt->bindParam(':inactive', $inactive, SQLITE3_INTEGER);-$stmt->bindParam(':url', $url, SQLITE3_TEXT);-$stmt->bindParam(':notifyDaysBefore', $notifyDaysBefore, SQLITE3_INTEGER);-$stmt->bindParam(':cancellationDate', $cancellationDate, SQLITE3_TEXT);-if ($isEdit) {- $stmt->bindParam(':id', $id, SQLITE3_INTEGER);-}-$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);-$stmt->bindParam(':replacement_subscription_id', $replacementSubscriptionId, SQLITE3_INTEGER);--if ($stmt->execute()) {- $success['status'] = "Success";- $text = $isEdit ? "updated" : "added";- $success['message'] = translate('subscription_' . $text . '_successfuly', $i18n);- if ($logoError !== "") {- $success['logo_warning'] = $logoError;- }-- // The logo was just replaced: drop the previous files if nothing else uses them.- if ($isEdit && $logo != "") {- if ($oldLogo !== null && $oldLogo !== $logo) {- deleteLogoFileIfUnused($db, $oldLogo, '../../images/uploads/logos/');- }- if ($oldLogoVariant !== null && $oldLogoVariant !== $logoVariant) {- deleteLogoFileIfUnused($db, $oldLogoVariant, '../../images/uploads/logos/');- }- }-- header('Content-Type: application/json');- echo json_encode($success);- exit();-} else {- echo translate('error', $i18n) . ": " . $db->lastErrorMsg();-}-$db->close();+<?php+error_reporting(E_ERROR | E_PARSE);+require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint.php';+require_once '../../includes/inputvalidation.php';+require_once '../../includes/getsettings.php';+require_once '../../includes/ssrf_helper.php';+require_once '../../includes/logo_theme_variant.php';+require_once '../../includes/logo_cleanup.php';+require_once '../../includes/subscription_payers.php';++if (!file_exists('../../images/uploads/logos')) {+ mkdir('../../images/uploads/logos', 0777, true);+ mkdir('../../images/uploads/logos/avatars', 0777, true);+}++function sanitizeFilename($filename)+{+ $filename = preg_replace("/[^a-zA-Z0-9\s]/", "", $filename);+ $filename = str_replace(" ", "-", $filename);+ $filename = str_replace(".", "", $filename);+ return $filename;+}++function validateFileExtension($fileExtension)+{+ $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp'];+ return in_array($fileExtension, $allowedExtensions);+}++function getLogoFromUrl($url, $uploadDir, $name, $settings, $i18n)+{+ $maxRedirects = 3;+ $currentUrl = $url;++ for ($i = 0; $i <= $maxRedirects; $i++) {+ if (!filter_var($currentUrl, FILTER_VALIDATE_URL) || !preg_match('/^https?:\/\//i', $currentUrl)) {+ return ['success' => false, 'message' => 'Invalid URL format.'];+ }++ $parts = parse_url($currentUrl);+ $host = $parts['host'];+ $port = $parts['port'] ?? ($parts['scheme'] === 'https' ? 443 : 80);++ $ip = gethostbyname($host);++ if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false+ || is_cgnat_ip($ip)) {+ return ['success' => false, 'message' => 'Invalid IP Address.'];+ }++ $ch = curl_init($currentUrl);+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);+ curl_setopt($ch, CURLOPT_TIMEOUT, 5);+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Manual handling to re-validate IPs++ curl_setopt($ch, CURLOPT_RESOLVE, ["$host:$port:$ip"]);++ $imageData = curl_exec($ch);+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);++ if ($httpCode >= 300 && $httpCode < 400) {+ $redirectUrl = curl_getinfo($ch, CURLINFO_REDIRECT_URL);+ unset($ch);++ if (!$redirectUrl) {+ break;+ }++ $currentUrl = $redirectUrl;+ continue;+ }++ if ($imageData !== false && $httpCode === 200) {+ $timestamp = time();+ $fileName = $timestamp . '-' . sanitizeFilename($name) . '.png';+ $uploadFile = $uploadDir . $fileName; // Note: Use the provided $uploadDir variable++ if (saveLogo($imageData, $uploadFile, $name, $settings)) {+ unset($ch);+ return ['success' => true, 'filename' => $fileName];+ }++ unset($ch);+ return ['success' => false, 'message' => translate('error_saving_logo', $i18n)];+ }++ $error = curl_error($ch);+ unset($ch);+ return ['success' => false, 'message' => translate('error_fetching_image', $i18n) . ': ' . $error];+ }++ return ['success' => false, 'message' => translate('error_fetching_image', $i18n)];+}++function saveLogo($imageData, $uploadFile, $name, $settings)+{+ $image = imagecreatefromstring($imageData);+ $removeBackground = isset($settings['removeBackground']) && $settings['removeBackground'] === 'true';++ if ($image !== false) {+ $tempFile = tempnam(sys_get_temp_dir(), 'logo');++ imagealphablending($image, false);+ imagesavealpha($image, true);+ imagepng($image, $tempFile);+ imagedestroy($image);++ $newImage = imagecreatefrompng($tempFile);+ if ($newImage !== false) {+ imagealphablending($newImage, false);+ imagesavealpha($newImage, true);++ if ($removeBackground) {+ require_once __DIR__ . '/../../includes/gd_background_removal.php';+ // On palette images imagecolorat() returns palette indexes, not RGB values+ if (!imageistruecolor($newImage)) {+ imagepalettetotruecolor($newImage);+ imagealphablending($newImage, false);+ imagesavealpha($newImage, true);+ }+ // Paint out the corner color with ~10% fuzz+ $corner = imagecolorat($newImage, 0, 0);+ if ((($corner >> 24) & 0x7F) !== 127) {+ gdRemoveBackgroundColor($newImage, ($corner >> 16) & 0xFF, ($corner >> 8) & 0xFF, $corner & 0xFF);+ }+ }++ // Crop/trim transparent margins+ require_once __DIR__ . '/../../includes/gd_background_removal.php';+ $newImage = gdCropTransparent($newImage, 2);++ $saved = imagepng($newImage, $uploadFile);+ imagedestroy($newImage);+ } else {+ unlink($tempFile);+ return false;+ }++ unlink($tempFile);+ return $saved;+ }++ return false;+}++function resizeAndUploadLogo($uploadedFile, $uploadDir, $name, $settings)+{+ $targetWidth = 135;+ $targetHeight = 42;++ $timestamp = time();+ $originalFileName = $uploadedFile['name'];+ $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);+ $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png';+ $fileName = $timestamp . '-' . sanitizeFilename($name) . '.' . $fileExtension;+ $uploadFile = $uploadDir . $fileName;++ if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) {+ $fileInfo = getimagesize($uploadFile);++ if ($fileInfo !== false) {+ $width = $fileInfo[0];+ $height = $fileInfo[1];++ if ($fileExtension === 'png') {+ $image = imagecreatefrompng($uploadFile);+ } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {+ $image = imagecreatefromjpeg($uploadFile);+ } elseif ($fileExtension === 'gif') {+ $image = imagecreatefromgif($uploadFile);+ } elseif ($fileExtension === 'webp') {+ $image = imagecreatefromwebp($uploadFile);+ } else {+ return "";+ }++ if ($fileExtension === 'png') {+ imagesavealpha($image, true);+ }++ // Crop/trim transparent margins (ensure we update dimensions after cropping)+ require_once __DIR__ . '/../../includes/gd_background_removal.php';+ $image = gdCropTransparent($image, 2);+ $width = imagesx($image);+ $height = imagesy($image);++ $newWidth = $width;+ $newHeight = $height;++ if ($width > $targetWidth) {+ $newWidth = (int) $targetWidth;+ $newHeight = (int) (($targetWidth / $width) * $height);+ }++ if ($newHeight > $targetHeight) {+ $newWidth = (int) (($targetHeight / $newHeight) * $newWidth);+ $newHeight = (int) $targetHeight;+ }++ $resizedImage = imagecreatetruecolor($newWidth, $newHeight);+ imagesavealpha($resizedImage, true);+ $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);+ imagefill($resizedImage, 0, 0, $transparency);+ imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);++ if ($fileExtension === 'png') {+ $saved = imagepng($resizedImage, $uploadFile);+ } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {+ $saved = imagejpeg($resizedImage, $uploadFile);+ } elseif ($fileExtension === 'gif') {+ $saved = imagegif($resizedImage, $uploadFile);+ } elseif ($fileExtension === 'webp') {+ $saved = imagewebp($resizedImage, $uploadFile);+ } else {+ return "";+ }++ imagedestroy($image);+ imagedestroy($resizedImage);++ if (!$saved) {+ if (file_exists($uploadFile)) {+ unlink($uploadFile);+ }+ return "";+ }++ return $fileName;+ }+ }++ return "";+}++$isEdit = isset($_POST['id']) && $_POST['id'] != "";+$name = validate($_POST["name"]);+$price = $_POST['price'];+$currencyId = $_POST["currency_id"];+$frequency = $_POST["frequency"];+$cycle = $_POST["cycle"];+$nextPayment = $_POST["next_payment"];+$autoRenew = isset($_POST['auto_renew']) ? true : false;+$startDate = $_POST["start_date"];+$paymentMethodId = $_POST["payment_method_id"];+$payerIds = parsePayerIds($_POST["payer_user_id"] ?? "");+$payerUserId = $payerIds[0] ?? null;+$categoryId = $_POST['category_id'];+$notes = validate_markdown($_POST["notes"]);+$url = validate($_POST['url']);+$logoUrl = validate($_POST['logo-url']);+$logo = "";+$logoError = "";+$notify = isset($_POST['notifications']) ? true : false;+$notifyDaysBefore = $_POST['notify_days_before'];+$inactive = isset($_POST['inactive']) ? true : false;+$cancellationDate = $_POST['cancellation_date'] ?? null;+$replacementSubscriptionId = $_POST['replacement_subscription_id'];++if ($replacementSubscriptionId == 0 || $inactive == 0) {+ $replacementSubscriptionId = null;+}++if ($replacementSubscriptionId !== null) {+ $ownerCheck = $db->prepare("SELECT id FROM subscriptions WHERE id = :id AND user_id = :userId");+ $ownerCheck->bindParam(':id', $replacementSubscriptionId, SQLITE3_INTEGER);+ $ownerCheck->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $ownerResult = $ownerCheck->execute();+ if (!$ownerResult || !$ownerResult->fetchArray()) {+ $replacementSubscriptionId = null;+ }+}++// Reject any foreign key that doesn't belong to the authenticated user, so a+// subscription can't be attached to another tenant's currency/category/+// household member/payment method (IDs are global auto-increment integers+// and easily enumerable).+function rejectForeignId($message)+{+ header('Content-Type: application/json');+ echo json_encode(['status' => 'Error', 'message' => $message]);+ exit();+}++$currStmt = $db->prepare("SELECT id FROM currencies WHERE id = :id AND user_id = :userId");+$currStmt->bindParam(':id', $currencyId, SQLITE3_INTEGER);+$currStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+$currResult = $currStmt->execute();+if (!$currResult || !$currResult->fetchArray()) {+ rejectForeignId('The specified currency does not exist or does not belong to you.');+}++if ($categoryId !== null && $categoryId !== '') {+ $catStmt = $db->prepare("SELECT id FROM categories WHERE id = :id AND user_id = :userId");+ $catStmt->bindParam(':id', $categoryId, SQLITE3_INTEGER);+ $catStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $catResult = $catStmt->execute();+ if (!$catResult || !$catResult->fetchArray()) {+ rejectForeignId('The specified category does not exist or does not belong to you.');+ }+}++if (!payersBelongToUser($db, $userId, $payerIds)) {+ rejectForeignId('The specified household member does not exist or does not belong to you.');+}++if ($paymentMethodId !== null && $paymentMethodId !== '') {+ $pmStmt = $db->prepare("SELECT id FROM payment_methods WHERE id = :id AND (user_id = :userId OR user_id = 0 OR user_id IS NULL)");+ $pmStmt->bindParam(':id', $paymentMethodId, SQLITE3_INTEGER);+ $pmStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $pmResult = $pmStmt->execute();+ if (!$pmResult || !$pmResult->fetchArray()) {+ rejectForeignId('The specified payment method does not exist or does not belong to you.');+ }+}++if ($logoUrl !== "") {+ $result = getLogoFromUrl($logoUrl, '../../images/uploads/logos/', $name, $settings, $i18n);+ if ($result['success']) {+ $logo = $result['filename'];+ } else {+ $logoError = $result['message'];+ }+} else {+ if (!empty($_FILES['logo']['name'])) {+ $fileType = mime_content_type($_FILES['logo']['tmp_name']);+ if (strpos($fileType, 'image') === false) {+ echo translate("fill_all_fields", $i18n);+ exit();+ }+ $logo = resizeAndUploadLogo($_FILES['logo'], '../../images/uploads/logos/', $name, $settings);+ if ($logo === "") {+ $logoError = translate('error_saving_logo', $i18n);+ }+ }+}++$logoTextColor = null;+$logoVariant = null;+$removeBackgroundEnabled = isset($settings['removeBackground']) && $settings['removeBackground'] === 'true';++// Themed variant generation piggybacks on the same "remove background"+// setting: both only make sense for logos we're already reprocessing, and+// this avoids running pixel classification on every single upload.+if ($logo !== "" && $removeBackgroundEnabled) {+ $logoExtension = strtolower(pathinfo($logo, PATHINFO_EXTENSION));+ $logoPath = '../../images/uploads/logos/' . $logo;++ if ($logoExtension === 'png' || $logoExtension === 'webp') {+ $sourceImage = $logoExtension === 'png' ? imagecreatefrompng($logoPath) : imagecreatefromwebp($logoPath);++ if ($sourceImage !== false) {+ imagealphablending($sourceImage, false);+ imagesavealpha($sourceImage, true);++ $logoTextColor = classifyLogoTextColor($sourceImage);++ if ($logoTextColor !== null) {+ $variantImage = generateThemedLogoVariant($sourceImage);+ $logoVariant = pathinfo($logo, PATHINFO_FILENAME) . '-variant.png';+ imagepng($variantImage, '../../images/uploads/logos/' . $logoVariant);+ imagedestroy($variantImage);+ }++ imagedestroy($sourceImage);+ }+ }+}++if (!$isEdit) {+ $sql = "INSERT INTO subscriptions (+ name, logo, price, currency_id, next_payment, cycle, frequency, notes,+ payment_method_id, payer_user_id, category_id, notify, inactive, url,+ notify_days_before, user_id, cancellation_date, replacement_subscription_id,+ auto_renew, start_date, logo_text_color, logo_variant+ ) VALUES (+ :name, :logo, :price, :currencyId, :nextPayment, :cycle, :frequency, :notes,+ :paymentMethodId, :payerUserId, :categoryId, :notify, :inactive, :url,+ :notifyDaysBefore, :userId, :cancellationDate, :replacement_subscription_id,+ :autoRenew, :startDate, :logoTextColor, :logoVariant+ )";+} else {+ $id = $_POST['id'];++ // When the logo is being replaced, remember the old files so they can be+ // removed after the update instead of lingering as orphans.+ $oldLogo = null;+ $oldLogoVariant = null;+ if ($logo != "") {+ $oldLogoStmt = $db->prepare("SELECT logo, logo_variant FROM subscriptions WHERE id = :id AND user_id = :userId");+ $oldLogoStmt->bindParam(':id', $id, SQLITE3_INTEGER);+ $oldLogoStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $oldLogoResult = $oldLogoStmt->execute();+ if ($oldLogoResult && ($oldLogoRow = $oldLogoResult->fetchArray(SQLITE3_ASSOC))) {+ $oldLogo = $oldLogoRow['logo'];+ $oldLogoVariant = $oldLogoRow['logo_variant'];+ }+ }++ $sql = "UPDATE subscriptions SET+ name = :name,+ price = :price,+ currency_id = :currencyId,+ next_payment = :nextPayment,+ auto_renew = :autoRenew,+ start_date = :startDate,+ cycle = :cycle,+ frequency = :frequency,+ notes = :notes,+ payment_method_id = :paymentMethodId,+ payer_user_id = :payerUserId,+ category_id = :categoryId,+ notify = :notify,+ inactive = :inactive,+ url = :url,+ notify_days_before = :notifyDaysBefore,+ cancellation_date = :cancellationDate,+ replacement_subscription_id = :replacement_subscription_id";++ if ($logo != "") {+ $sql .= ", logo = :logo, logo_text_color = :logoTextColor, logo_variant = :logoVariant";+ }++ $sql .= " WHERE id = :id AND user_id = :userId";+}++$stmt = $db->prepare($sql);+$stmt->bindParam(':name', $name, SQLITE3_TEXT);+if ($logo != "") {+ $stmt->bindParam(':logo', $logo, SQLITE3_TEXT);+ $stmt->bindParam(':logoTextColor', $logoTextColor, SQLITE3_TEXT);+ $stmt->bindParam(':logoVariant', $logoVariant, SQLITE3_TEXT);+}+$stmt->bindParam(':price', $price, SQLITE3_FLOAT);+$stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);+$stmt->bindParam(':nextPayment', $nextPayment, SQLITE3_TEXT);+$stmt->bindParam(':autoRenew', $autoRenew, SQLITE3_INTEGER);+$stmt->bindParam(':startDate', $startDate, SQLITE3_TEXT);+$stmt->bindParam(':cycle', $cycle, SQLITE3_INTEGER);+$stmt->bindParam(':frequency', $frequency, SQLITE3_INTEGER);+$stmt->bindParam(':notes', $notes, SQLITE3_TEXT);+$stmt->bindParam(':paymentMethodId', $paymentMethodId, SQLITE3_INTEGER);+$stmt->bindParam(':payerUserId', $payerUserId, SQLITE3_INTEGER);+$stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);+$stmt->bindParam(':notify', $notify, SQLITE3_INTEGER);+$stmt->bindParam(':inactive', $inactive, SQLITE3_INTEGER);+$stmt->bindParam(':url', $url, SQLITE3_TEXT);+$stmt->bindParam(':notifyDaysBefore', $notifyDaysBefore, SQLITE3_INTEGER);+$stmt->bindParam(':cancellationDate', $cancellationDate, SQLITE3_TEXT);+if ($isEdit) {+ $stmt->bindParam(':id', $id, SQLITE3_INTEGER);+}+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+$stmt->bindParam(':replacement_subscription_id', $replacementSubscriptionId, SQLITE3_INTEGER);++if ($stmt->execute()) {+ $success['status'] = "Success";+ $text = $isEdit ? "updated" : "added";+ $success['message'] = translate('subscription_' . $text . '_successfuly', $i18n);+ if ($logoError !== "") {+ $success['logo_warning'] = $logoError;+ }++ $savedSubscriptionId = $isEdit ? intval($id) : $db->lastInsertRowID();+ saveSubscriptionPayers($db, $savedSubscriptionId, $payerIds);++ // The logo was just replaced: drop the previous files if nothing else uses them.+ if ($isEdit && $logo != "") {+ if ($oldLogo !== null && $oldLogo !== $logo) {+ deleteLogoFileIfUnused($db, $oldLogo, '../../images/uploads/logos/');+ }+ if ($oldLogoVariant !== null && $oldLogoVariant !== $logoVariant) {+ deleteLogoFileIfUnused($db, $oldLogoVariant, '../../images/uploads/logos/');+ }+ }++ header('Content-Type: application/json');+ echo json_encode($success);+ exit();+} else {+ echo translate('error', $i18n) . ": " . $db->lastErrorMsg();+}+$db->close();?>\ No newline at end of filediff --git a/endpoints/subscription/clone.php b/endpoints/subscription/clone.phpindex 3599e0d..4403417 100644--- a/endpoints/subscription/clone.php+++ b/endpoints/subscription/clone.php@@ -1,60 +1,63 @@-<?php-require_once '../../includes/connect_endpoint.php';-require_once '../../includes/validate_endpoint.php';--$postData = file_get_contents("php://input");-$data = json_decode($postData, true);--$subscriptionId = $data["id"];-$query = "SELECT * FROM subscriptions WHERE id = :id AND user_id = :user_id";-$stmt = $db->prepare($query);-$stmt->bindValue(':id', $subscriptionId, SQLITE3_INTEGER);-$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();-$subscriptionToClone = $result->fetchArray(SQLITE3_ASSOC);-if ($subscriptionToClone === false) {- die(json_encode([- "success" => false,- "message" => translate("error", $i18n)- ]));-}--$query = "INSERT INTO subscriptions (name, logo, price, currency_id, next_payment, auto_renew, start_date, cycle, frequency, notes, payment_method_id, payer_user_id, category_id, notify, url, inactive, notify_days_before, user_id, cancellation_date, replacement_subscription_id) VALUES (:name, :logo, :price, :currency_id, :next_payment, :auto_renew, :start_date, :cycle, :frequency, :notes, :payment_method_id, :payer_user_id, :category_id, :notify, :url, :inactive, :notify_days_before, :user_id, :cancellation_date, :replacement_subscription_id)";-$cloneStmt = $db->prepare($query);-$cloneStmt->bindValue(':name', $subscriptionToClone['name'], SQLITE3_TEXT);-$cloneStmt->bindValue(':logo', $subscriptionToClone['logo'], SQLITE3_TEXT);-$cloneStmt->bindValue(':price', $subscriptionToClone['price'], SQLITE3_TEXT);-$cloneStmt->bindValue(':currency_id', $subscriptionToClone['currency_id'], SQLITE3_INTEGER);-$cloneStmt->bindValue(':next_payment', $subscriptionToClone['next_payment'], SQLITE3_TEXT);-$cloneStmt->bindValue(':auto_renew', $subscriptionToClone['auto_renew'], SQLITE3_INTEGER);-$cloneStmt->bindValue(':start_date', $subscriptionToClone['start_date'], SQLITE3_TEXT);-$cloneStmt->bindValue(':cycle', $subscriptionToClone['cycle'], SQLITE3_TEXT);-$cloneStmt->bindValue(':frequency', $subscriptionToClone['frequency'], SQLITE3_INTEGER);-$cloneStmt->bindValue(':notes', $subscriptionToClone['notes'], SQLITE3_TEXT);-$cloneStmt->bindValue(':payment_method_id', $subscriptionToClone['payment_method_id'], SQLITE3_INTEGER);-$cloneStmt->bindValue(':payer_user_id', $subscriptionToClone['payer_user_id'], SQLITE3_INTEGER);-$cloneStmt->bindValue(':category_id', $subscriptionToClone['category_id'], SQLITE3_INTEGER);-$cloneStmt->bindValue(':notify', $subscriptionToClone['notify'], SQLITE3_INTEGER);-$cloneStmt->bindValue(':url', $subscriptionToClone['url'], SQLITE3_TEXT);-$cloneStmt->bindValue(':inactive', $subscriptionToClone['inactive'], SQLITE3_INTEGER);-$cloneStmt->bindValue(':notify_days_before', $subscriptionToClone['notify_days_before'], SQLITE3_INTEGER);-$cloneStmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);-$cloneStmt->bindValue(':cancellation_date', $subscriptionToClone['cancellation_date'], SQLITE3_TEXT);-$cloneStmt->bindValue(':replacement_subscription_id', $subscriptionToClone['replacement_subscription_id'], SQLITE3_INTEGER);--if ($cloneStmt->execute()) {- $response = [- "success" => true,- "message" => translate('success', $i18n),- "id" => $db->lastInsertRowID()- ];- echo json_encode($response);-} else {- die(json_encode([- "success" => false,- "message" => translate("error", $i18n)- ]));-}--$db->close();+<?php+require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint.php';+require_once '../../includes/subscription_payers.php';++$postData = file_get_contents("php://input");+$data = json_decode($postData, true);++$subscriptionId = $data["id"];+$query = "SELECT * FROM subscriptions WHERE id = :id AND user_id = :user_id";+$stmt = $db->prepare($query);+$stmt->bindValue(':id', $subscriptionId, SQLITE3_INTEGER);+$stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();+$subscriptionToClone = $result->fetchArray(SQLITE3_ASSOC);+if ($subscriptionToClone === false) {+ die(json_encode([+ "success" => false,+ "message" => translate("error", $i18n)+ ]));+}++$query = "INSERT INTO subscriptions (name, logo, price, currency_id, next_payment, auto_renew, start_date, cycle, frequency, notes, payment_method_id, payer_user_id, category_id, notify, url, inactive, notify_days_before, user_id, cancellation_date, replacement_subscription_id) VALUES (:name, :logo, :price, :currency_id, :next_payment, :auto_renew, :start_date, :cycle, :frequency, :notes, :payment_method_id, :payer_user_id, :category_id, :notify, :url, :inactive, :notify_days_before, :user_id, :cancellation_date, :replacement_subscription_id)";+$cloneStmt = $db->prepare($query);+$cloneStmt->bindValue(':name', $subscriptionToClone['name'], SQLITE3_TEXT);+$cloneStmt->bindValue(':logo', $subscriptionToClone['logo'], SQLITE3_TEXT);+$cloneStmt->bindValue(':price', $subscriptionToClone['price'], SQLITE3_TEXT);+$cloneStmt->bindValue(':currency_id', $subscriptionToClone['currency_id'], SQLITE3_INTEGER);+$cloneStmt->bindValue(':next_payment', $subscriptionToClone['next_payment'], SQLITE3_TEXT);+$cloneStmt->bindValue(':auto_renew', $subscriptionToClone['auto_renew'], SQLITE3_INTEGER);+$cloneStmt->bindValue(':start_date', $subscriptionToClone['start_date'], SQLITE3_TEXT);+$cloneStmt->bindValue(':cycle', $subscriptionToClone['cycle'], SQLITE3_TEXT);+$cloneStmt->bindValue(':frequency', $subscriptionToClone['frequency'], SQLITE3_INTEGER);+$cloneStmt->bindValue(':notes', $subscriptionToClone['notes'], SQLITE3_TEXT);+$cloneStmt->bindValue(':payment_method_id', $subscriptionToClone['payment_method_id'], SQLITE3_INTEGER);+$cloneStmt->bindValue(':payer_user_id', $subscriptionToClone['payer_user_id'], SQLITE3_INTEGER);+$cloneStmt->bindValue(':category_id', $subscriptionToClone['category_id'], SQLITE3_INTEGER);+$cloneStmt->bindValue(':notify', $subscriptionToClone['notify'], SQLITE3_INTEGER);+$cloneStmt->bindValue(':url', $subscriptionToClone['url'], SQLITE3_TEXT);+$cloneStmt->bindValue(':inactive', $subscriptionToClone['inactive'], SQLITE3_INTEGER);+$cloneStmt->bindValue(':notify_days_before', $subscriptionToClone['notify_days_before'], SQLITE3_INTEGER);+$cloneStmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);+$cloneStmt->bindValue(':cancellation_date', $subscriptionToClone['cancellation_date'], SQLITE3_TEXT);+$cloneStmt->bindValue(':replacement_subscription_id', $subscriptionToClone['replacement_subscription_id'], SQLITE3_INTEGER);++if ($cloneStmt->execute()) {+ $clonedId = $db->lastInsertRowID();+ saveSubscriptionPayers($db, $clonedId, getPayersBySubscription($db, [$subscriptionToClone])[$subscriptionToClone['id']] ?? []);+ $response = [+ "success" => true,+ "message" => translate('success', $i18n),+ "id" => $clonedId+ ];+ echo json_encode($response);+} else {+ die(json_encode([+ "success" => false,+ "message" => translate("error", $i18n)+ ]));+}++$db->close();?>\ No newline at end of filediff --git a/endpoints/subscription/delete.php b/endpoints/subscription/delete.phpindex 46ee68e..5f1dd5a 100644--- a/endpoints/subscription/delete.php+++ b/endpoints/subscription/delete.php@@ -1,44 +1,49 @@-<?php-require_once '../../includes/connect_endpoint.php';-require_once '../../includes/validate_endpoint.php';-require_once '../../includes/logo_cleanup.php';--$postData = file_get_contents("php://input");-$data = json_decode($postData, true);--$subscriptionId = $data["id"];--$logoStmt = $db->prepare("SELECT logo, logo_variant FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId");-$logoStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);-$logoStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);-$logoResult = $logoStmt->execute();-$logoRow = $logoResult ? $logoResult->fetchArray(SQLITE3_ASSOC) : false;--$deleteQuery = "DELETE FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId";-$deleteStmt = $db->prepare($deleteQuery);-$deleteStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);-$deleteStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);--if ($deleteStmt->execute()) {- $query = "UPDATE subscriptions SET replacement_subscription_id = NULL WHERE replacement_subscription_id = :subscriptionId AND user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $stmt->execute();-- if ($logoRow !== false) {- deleteLogoFileIfUnused($db, $logoRow['logo'], '../../images/uploads/logos/');- deleteLogoFileIfUnused($db, $logoRow['logo_variant'], '../../images/uploads/logos/');- }-- echo json_encode([- "success" => true,- "message" => translate('subscription_deleted', $i18n)- ]);-} else {- echo json_encode([- "success" => false,- "message" => translate('error_deleting_subscription', $i18n)- ]);-}-$db->close();\ No newline at end of file+<?php+require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint.php';+require_once '../../includes/logo_cleanup.php';++$postData = file_get_contents("php://input");+$data = json_decode($postData, true);++$subscriptionId = $data["id"];++$logoStmt = $db->prepare("SELECT logo, logo_variant FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId");+$logoStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);+$logoStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+$logoResult = $logoStmt->execute();+$logoRow = $logoResult ? $logoResult->fetchArray(SQLITE3_ASSOC) : false;++$payersStmt = $db->prepare("DELETE FROM subscription_payers WHERE subscription_id IN (SELECT id FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId)");+$payersStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);+$payersStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+$payersStmt->execute();++$deleteQuery = "DELETE FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId";+$deleteStmt = $db->prepare($deleteQuery);+$deleteStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);+$deleteStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);++if ($deleteStmt->execute()) {+ $query = "UPDATE subscriptions SET replacement_subscription_id = NULL WHERE replacement_subscription_id = :subscriptionId AND user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $stmt->execute();++ if ($logoRow !== false) {+ deleteLogoFileIfUnused($db, $logoRow['logo'], '../../images/uploads/logos/');+ deleteLogoFileIfUnused($db, $logoRow['logo_variant'], '../../images/uploads/logos/');+ }++ echo json_encode([+ "success" => true,+ "message" => translate('subscription_deleted', $i18n)+ ]);+} else {+ echo json_encode([+ "success" => false,+ "message" => translate('error_deleting_subscription', $i18n)+ ]);+}+$db->close();diff --git a/endpoints/subscription/exportcalendar.php b/endpoints/subscription/exportcalendar.phpindex 2456375..a442fc5 100644--- a/endpoints/subscription/exportcalendar.php+++ b/endpoints/subscription/exportcalendar.php@@ -1,90 +1,91 @@-<?php-require_once '../../includes/connect_endpoint.php';-require_once '../../includes/validate_endpoint.php';-require_once '../../includes/getdbkeys.php';-require_once '../../includes/ical_helper.php';--$postData = file_get_contents("php://input");-$data = json_decode($postData, true);--$id = $data['id'];--$stmt = $db->prepare('SELECT * FROM subscriptions WHERE id = :id AND user_id = :userId');-$stmt->bindParam(':id', $id, SQLITE3_INTEGER);-$stmt->bindParam(':userId', $_SESSION['userId'], SQLITE3_INTEGER);-$result = $stmt->execute();--if ($result === false) {- die(json_encode([- 'success' => false,- 'message' => "Subscription not found"- ]));-}--$subscription = $result->fetchArray(SQLITE3_ASSOC); // Fetch the subscription details as an associative array--if ($subscription) {- $subscription['payer_user'] = $members[$subscription['payer_user_id']]['name'];- $subscription['category'] = $categories[$subscription['category_id']]['name'];- $subscription['payment_method'] = $payment_methods[$subscription['payment_method_id']]['name'];- $subscription['currency'] = $currencies[$subscription['currency_id']]['symbol'];- $subscription['trigger'] = $subscription['notify_days_before'] ? $subscription['notify_days_before'] : 1;- $subscription['price'] = number_format($subscription['price'], 2);-- // Create ICS from subscription information- $uid = 'wallos-subscription-' . $subscription['id'] . '@wallos';- $summary = icalEscape(html_entity_decode($subscription['name'], ENT_QUOTES, 'UTF-8'));- $notes = icalEscape($subscription['notes']);- $category = icalEscape($subscription['category']);- $paymentMethod = icalEscape($subscription['payment_method']);- $payer = icalEscape($subscription['payer_user']);- $description = "Price: {$subscription['currency']}{$subscription['price']}\\nCategory: {$category}\\nPayment Method: {$paymentMethod}\\nPayer: {$payer}\\n\\nNotes: {$notes}";-- $dtstamp = gmdate('Ymd\THis\Z');- $dtstart = (new DateTime($subscription['next_payment']))->format('Ymd');- $dtend = (new DateTime($subscription['next_payment']))->format('Ymd');- $location = icalEscape(isset($subscription['url']) ? $subscription['url'] : '');- $alarm_trigger = '-P' . $subscription['trigger'] . 'D';-- // Notes can now be multi-paragraph Markdown, so these lines (especially- // DESCRIPTION) can genuinely exceed the RFC 5545 75-octet limit.- $summaryLine = icalFold('SUMMARY:' . $summary);- $descriptionLine = icalFold('DESCRIPTION:' . $description);- $locationLine = icalFold('LOCATION:' . $location);-- $icsContent = <<<ICS- BEGIN:VCALENDAR- VERSION:2.0- PRODID:-//Your Organization//Your Application//EN- CALSCALE:GREGORIAN- METHOD:PUBLISH- BEGIN:VEVENT- UID:$uid- DTSTAMP:$dtstamp- $summaryLine- $descriptionLine- DTSTART;VALUE=DATE:$dtstart- DTEND;VALUE=DATE:$dtend- $locationLine- STATUS:CONFIRMED- TRANSP:OPAQUE- BEGIN:VALARM- ACTION:DISPLAY- DESCRIPTION:Reminder- TRIGGER:$alarm_trigger- END:VALARM- END:VEVENT- END:VCALENDAR- ICS;-- echo json_encode([- 'success' => true,- 'ics' => $icsContent,- 'name' => $subscription['name']- ]);-} else {- echo json_encode([- 'success' => false,- 'message' => "Subscription not found"- ]);+<?php+require_once '../../includes/connect_endpoint.php';+require_once '../../includes/validate_endpoint.php';+require_once '../../includes/getdbkeys.php';+require_once '../../includes/subscription_payers.php';+require_once '../../includes/ical_helper.php';++$postData = file_get_contents("php://input");+$data = json_decode($postData, true);++$id = $data['id'];++$stmt = $db->prepare('SELECT * FROM subscriptions WHERE id = :id AND user_id = :userId');+$stmt->bindParam(':id', $id, SQLITE3_INTEGER);+$stmt->bindParam(':userId', $_SESSION['userId'], SQLITE3_INTEGER);+$result = $stmt->execute();++if ($result === false) {+ die(json_encode([+ 'success' => false,+ 'message' => "Subscription not found"+ ]));+}++$subscription = $result->fetchArray(SQLITE3_ASSOC); // Fetch the subscription details as an associative array++if ($subscription) {+ $subscription['payer_user'] = payerNamesLabel(getPayersBySubscription($db, [$subscription])[$subscription['id']] ?? [], array_map(fn($m) => $m['name'] ?? '', $members));+ $subscription['category'] = $categories[$subscription['category_id']]['name'];+ $subscription['payment_method'] = $payment_methods[$subscription['payment_method_id']]['name'];+ $subscription['currency'] = $currencies[$subscription['currency_id']]['symbol'];+ $subscription['trigger'] = $subscription['notify_days_before'] ? $subscription['notify_days_before'] : 1;+ $subscription['price'] = number_format($subscription['price'], 2);++ // Create ICS from subscription information+ $uid = 'wallos-subscription-' . $subscription['id'] . '@wallos';+ $summary = icalEscape(html_entity_decode($subscription['name'], ENT_QUOTES, 'UTF-8'));+ $notes = icalEscape($subscription['notes']);+ $category = icalEscape($subscription['category']);+ $paymentMethod = icalEscape($subscription['payment_method']);+ $payer = icalEscape($subscription['payer_user']);+ $description = "Price: {$subscription['currency']}{$subscription['price']}\\nCategory: {$category}\\nPayment Method: {$paymentMethod}\\nPayer: {$payer}\\n\\nNotes: {$notes}";++ $dtstamp = gmdate('Ymd\THis\Z');+ $dtstart = (new DateTime($subscription['next_payment']))->format('Ymd');+ $dtend = (new DateTime($subscription['next_payment']))->format('Ymd');+ $location = icalEscape(isset($subscription['url']) ? $subscription['url'] : '');+ $alarm_trigger = '-P' . $subscription['trigger'] . 'D';++ // Notes can now be multi-paragraph Markdown, so these lines (especially+ // DESCRIPTION) can genuinely exceed the RFC 5545 75-octet limit.+ $summaryLine = icalFold('SUMMARY:' . $summary);+ $descriptionLine = icalFold('DESCRIPTION:' . $description);+ $locationLine = icalFold('LOCATION:' . $location);++ $icsContent = <<<ICS+ BEGIN:VCALENDAR+ VERSION:2.0+ PRODID:-//Your Organization//Your Application//EN+ CALSCALE:GREGORIAN+ METHOD:PUBLISH+ BEGIN:VEVENT+ UID:$uid+ DTSTAMP:$dtstamp+ $summaryLine+ $descriptionLine+ DTSTART;VALUE=DATE:$dtstart+ DTEND;VALUE=DATE:$dtend+ $locationLine+ STATUS:CONFIRMED+ TRANSP:OPAQUE+ BEGIN:VALARM+ ACTION:DISPLAY+ DESCRIPTION:Reminder+ TRIGGER:$alarm_trigger+ END:VALARM+ END:VEVENT+ END:VCALENDAR+ ICS;++ echo json_encode([+ 'success' => true,+ 'ics' => $icsContent,+ 'name' => $subscription['name']+ ]);+} else {+ echo json_encode([+ 'success' => false,+ 'message' => "Subscription not found"+ ]);}\ No newline at end of filediff --git a/endpoints/subscription/get.php b/endpoints/subscription/get.phpindex 986f8ad..95a1ea5 100644--- a/endpoints/subscription/get.php+++ b/endpoints/subscription/get.php@@ -1,56 +1,58 @@-<?php-require_once '../../includes/connect_endpoint.php';-require_once '../../includes/markdown.php';--if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {- if (isset($_GET['id']) && $_GET['id'] != "") {- $subscriptionId = intval($_GET['id']);- $query = "SELECT * FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();-- $subscriptionData = array();-- if ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $subscriptionData['id'] = $subscriptionId;- $subscriptionData['name'] = htmlspecialchars_decode($row['name'] ?? "");- $subscriptionData['logo'] = $row['logo'];- $subscriptionData['logo_text_color'] = $row['logo_text_color'];- $subscriptionData['logo_variant'] = $row['logo_variant'];- $subscriptionData['price'] = $row['price'];- $subscriptionData['currency_id'] = $row['currency_id'];- $subscriptionData['auto_renew'] = $row['auto_renew'];- $subscriptionData['start_date'] = $row['start_date'];- $subscriptionData['next_payment'] = $row['next_payment'];- $subscriptionData['frequency'] = $row['frequency'];- $subscriptionData['cycle'] = $row['cycle'];- $subscriptionData['notes'] = $row['notes'] ?? "";- $subscriptionData['notes_html'] = render_notes_markdown($row['notes'] ?? "");- $subscriptionData['payment_method_id'] = $row['payment_method_id'];- $subscriptionData['payer_user_id'] = $row['payer_user_id'];- $subscriptionData['category_id'] = $row['category_id'];- $subscriptionData['notify'] = $row['notify'];- $subscriptionData['inactive'] = $row['inactive'];- $subscriptionData['url'] = htmlspecialchars_decode($row['url'] ?? "");- $subscriptionData['notify_days_before'] = $row['notify_days_before'];- $subscriptionData['cancellation_date'] = $row['cancellation_date'];- $subscriptionData['replacement_subscription_id'] = $row['replacement_subscription_id'];-- $subscriptionJson = json_encode($subscriptionData);- header('Content-Type: application/json');- echo $subscriptionJson;- } else {- echo translate('error', $i18n);- }- } else {- echo translate('error', $i18n);- }-} else {- http_response_code(401);- header('Content-Type: application/json');- echo json_encode(['error' => translate('session_expired', $i18n)]);-}-$db->close();+<?php+require_once '../../includes/connect_endpoint.php';+require_once '../../includes/markdown.php';+require_once '../../includes/subscription_payers.php';++if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {+ if (isset($_GET['id']) && $_GET['id'] != "") {+ $subscriptionId = intval($_GET['id']);+ $query = "SELECT * FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ $subscriptionData = array();++ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $subscriptionData['id'] = $subscriptionId;+ $subscriptionData['name'] = htmlspecialchars_decode($row['name'] ?? "");+ $subscriptionData['logo'] = $row['logo'];+ $subscriptionData['logo_text_color'] = $row['logo_text_color'];+ $subscriptionData['logo_variant'] = $row['logo_variant'];+ $subscriptionData['price'] = $row['price'];+ $subscriptionData['currency_id'] = $row['currency_id'];+ $subscriptionData['auto_renew'] = $row['auto_renew'];+ $subscriptionData['start_date'] = $row['start_date'];+ $subscriptionData['next_payment'] = $row['next_payment'];+ $subscriptionData['frequency'] = $row['frequency'];+ $subscriptionData['cycle'] = $row['cycle'];+ $subscriptionData['notes'] = $row['notes'] ?? "";+ $subscriptionData['notes_html'] = render_notes_markdown($row['notes'] ?? "");+ $subscriptionData['payment_method_id'] = $row['payment_method_id'];+ $subscriptionData['payer_user_id'] = $row['payer_user_id'];+ $subscriptionData['payer_user_ids'] = getPayersBySubscription($db, [$row])[$row['id']] ?? [];+ $subscriptionData['category_id'] = $row['category_id'];+ $subscriptionData['notify'] = $row['notify'];+ $subscriptionData['inactive'] = $row['inactive'];+ $subscriptionData['url'] = htmlspecialchars_decode($row['url'] ?? "");+ $subscriptionData['notify_days_before'] = $row['notify_days_before'];+ $subscriptionData['cancellation_date'] = $row['cancellation_date'];+ $subscriptionData['replacement_subscription_id'] = $row['replacement_subscription_id'];++ $subscriptionJson = json_encode($subscriptionData);+ header('Content-Type: application/json');+ echo $subscriptionJson;+ } else {+ echo translate('error', $i18n);+ }+ } else {+ echo translate('error', $i18n);+ }+} else {+ http_response_code(401);+ header('Content-Type: application/json');+ echo json_encode(['error' => translate('session_expired', $i18n)]);+}+$db->close();?>\ No newline at end of filediff --git a/endpoints/subscription/getcalendar.php b/endpoints/subscription/getcalendar.phpindex 17e18ac..27bade3 100644--- a/endpoints/subscription/getcalendar.php+++ b/endpoints/subscription/getcalendar.php@@ -1,51 +1,52 @@-<?php-require_once '../../includes/connect_endpoint.php';-require_once '../../includes/getdbkeys.php';--if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {- die(json_encode([- "success" => false,- "message" => translate('session_expired', $i18n)- ]));-}--if ($_SERVER["REQUEST_METHOD"] === "POST") {- $postData = file_get_contents("php://input");- $data = json_decode($postData, true);-- $id = $data['id'];-- $stmt = $db->prepare('SELECT * FROM subscriptions WHERE id = :id AND user_id = :userId');- $stmt->bindParam(':id', $id, SQLITE3_INTEGER);- $stmt->bindParam(':userId', $_SESSION['userId'], SQLITE3_INTEGER); // Assuming $_SESSION['userId'] holds the logged-in user's ID- $result = $stmt->execute();-- if ($result === false) {- die(json_encode([- 'success' => false,- 'message' => "Subscription not found"- ]));- }-- $subscription = $result->fetchArray(SQLITE3_ASSOC); // Fetch the subscription details as an associative array-- if ($subscription) {- // get payer name from household object- $subscription['payer_user'] = $members[$subscription['payer_user_id']]['name'];- $subscription['category'] = $categories[$subscription['category_id']]['name'];- $subscription['payment_method'] = $payment_methods[$subscription['payment_method_id']]['name'];- $subscription['currency'] = $currencies[$subscription['currency_id']]['symbol'];- $subscription['price'] = number_format($subscription['price'], 2);-- echo json_encode([- 'success' => true,- 'data' => $subscription- ]);- } else {- echo json_encode([- 'success' => false,- 'message' => "Subscription not found"- ]);- }-}+<?php+require_once '../../includes/connect_endpoint.php';+require_once '../../includes/getdbkeys.php';+require_once '../../includes/subscription_payers.php';++if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {+ die(json_encode([+ "success" => false,+ "message" => translate('session_expired', $i18n)+ ]));+}++if ($_SERVER["REQUEST_METHOD"] === "POST") {+ $postData = file_get_contents("php://input");+ $data = json_decode($postData, true);++ $id = $data['id'];++ $stmt = $db->prepare('SELECT * FROM subscriptions WHERE id = :id AND user_id = :userId');+ $stmt->bindParam(':id', $id, SQLITE3_INTEGER);+ $stmt->bindParam(':userId', $_SESSION['userId'], SQLITE3_INTEGER); // Assuming $_SESSION['userId'] holds the logged-in user's ID+ $result = $stmt->execute();++ if ($result === false) {+ die(json_encode([+ 'success' => false,+ 'message' => "Subscription not found"+ ]));+ }++ $subscription = $result->fetchArray(SQLITE3_ASSOC); // Fetch the subscription details as an associative array++ if ($subscription) {+ // get payer name from household object+ $subscription['payer_user'] = payerNamesLabel(getPayersBySubscription($db, [$subscription])[$subscription['id']] ?? [], array_map(fn($m) => $m['name'] ?? '', $members));+ $subscription['category'] = $categories[$subscription['category_id']]['name'];+ $subscription['payment_method'] = $payment_methods[$subscription['payment_method_id']]['name'];+ $subscription['currency'] = $currencies[$subscription['currency_id']]['symbol'];+ $subscription['price'] = number_format($subscription['price'], 2);++ echo json_encode([+ 'success' => true,+ 'data' => $subscription+ ]);+ } else {+ echo json_encode([+ 'success' => false,+ 'message' => "Subscription not found"+ ]);+ }+}?>\ No newline at end of filediff --git a/endpoints/subscriptions/export.php b/endpoints/subscriptions/export.phpindex fd50369..b050c80 100644--- a/endpoints/subscriptions/export.php+++ b/endpoints/subscriptions/export.php@@ -1,63 +1,66 @@-<?php-require_once '../../includes/connect_endpoint.php';--if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {- die(json_encode([- "success" => false,- "message" => translate('session_expired', $i18n)- ]));-}--require_once '../../includes/getdbkeys.php';--$subscriptions = array();--$query = "SELECT * FROM subscriptions WHERE user_id = :userId";-$stmt = $db->prepare($query);-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();--while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $cycle = $cycles[$row['cycle']]['name'];- $frequency =$row['frequency'];-- $cyclesMap = array(- 'Daily' => 'Days',- 'Weekly' => 'Weeks',- 'Monthly' => 'Months',- 'Yearly' => 'Years'- );-- if ($frequency == 1) {- $cyclePrint = $cycle;- } else {- $cyclePrint = "Every " . $frequency . " " . $cyclesMap[$cycle];- }-- $subscriptionDetails = array(- 'Name' => str_replace(',', ' ', $row['name']),- 'Payment Cycle' => $cyclePrint,- 'Next Payment' => $row['next_payment'],- 'Renewal' => $row['auto_renew'] ? 'Automatic' : 'Manual',- 'Category' => str_replace(',', ' ', $categories[$row['category_id'] ?? '']['name'] ?? ''),- 'Payment Method' => str_replace(',', ' ', $payment_methods[$row['payment_method_id'] ?? '']['name'] ?? ''),- 'Paid By' => str_replace(',', ' ', $members[$row['payer_user_id'] ?? '']['name'] ?? ''),- 'Price' => ($currencies[$row['currency_id'] ?? '']['symbol'] ?? '') . $row['price'],- 'Notes' => str_replace(',', ' ', $row['notes'] ?? ''),- 'URL' => $row['url'],- 'State' => $row['inactive'] ? 'Disabled' : 'Enabled',- 'Notifications' => $row['notify'] ? 'Enabled' : 'Disabled',- 'Cancellation Date' => $row['cancellation_date'],- 'Active' => $row['inactive'] ? 'No' : 'Yes',- );-- $subscriptions[] = $subscriptionDetails;-}--die(json_encode([- "success" => true,- "subscriptions" => $subscriptions-]));---?>+<?php+require_once '../../includes/connect_endpoint.php';++if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {+ die(json_encode([+ "success" => false,+ "message" => translate('session_expired', $i18n)+ ]));+}++require_once '../../includes/getdbkeys.php';+require_once '../../includes/subscription_payers.php';++$subscriptions = array();++$query = "SELECT * FROM subscriptions WHERE user_id = :userId";+$stmt = $db->prepare($query);+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();++while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $cycle = $cycles[$row['cycle']]['name'];+ $frequency =$row['frequency'];++ $cyclesMap = array(+ 'Daily' => 'Days',+ 'Weekly' => 'Weeks',+ 'Monthly' => 'Months',+ 'Yearly' => 'Years'+ );++ if ($frequency == 1) {+ $cyclePrint = $cycle;+ } else {+ $cyclePrint = "Every " . $frequency . " " . $cyclesMap[$cycle];+ }++ $payerIds = getPayersBySubscription($db, [$row])[$row['id']] ?? [];++ $subscriptionDetails = array(+ 'Name' => str_replace(',', ' ', $row['name']),+ 'Payment Cycle' => $cyclePrint,+ 'Next Payment' => $row['next_payment'],+ 'Renewal' => $row['auto_renew'] ? 'Automatic' : 'Manual',+ 'Category' => str_replace(',', ' ', $categories[$row['category_id'] ?? '']['name'] ?? ''),+ 'Payment Method' => str_replace(',', ' ', $payment_methods[$row['payment_method_id'] ?? '']['name'] ?? ''),+ 'Paid By' => str_replace(',', ' ', payerNamesLabel($payerIds, array_map(fn($m) => $m['name'] ?? '', $members), ' / ')),+ 'Price' => ($currencies[$row['currency_id'] ?? '']['symbol'] ?? '') . $row['price'],+ 'Notes' => str_replace(',', ' ', $row['notes'] ?? ''),+ 'URL' => $row['url'],+ 'State' => $row['inactive'] ? 'Disabled' : 'Enabled',+ 'Notifications' => $row['notify'] ? 'Enabled' : 'Disabled',+ 'Cancellation Date' => $row['cancellation_date'],+ 'Active' => $row['inactive'] ? 'No' : 'Yes',+ );++ $subscriptions[] = $subscriptionDetails;+}++die(json_encode([+ "success" => true,+ "subscriptions" => $subscriptions+]));+++?>diff --git a/endpoints/subscriptions/get.php b/endpoints/subscriptions/get.phpindex d2ae10d..7158754 100644--- a/endpoints/subscriptions/get.php+++ b/endpoints/subscriptions/get.php@@ -1,275 +1,269 @@-<?php-require_once '../../includes/connect_endpoint.php';--require_once '../../includes/currency_formatter.php';-require_once '../../includes/getdbkeys.php';-require_once '../../includes/logo_theme_variant.php';--include_once '../../includes/list_subscriptions.php';--require_once '../../includes/getsettings.php';--$theme = "light";-if (isset($settings['theme'])) {- $theme = $settings['theme'];-}--$colorTheme = "blue";-if (isset($settings['color_theme'])) {- $colorTheme = $settings['color_theme'];-}--$formatter = new IntlDateFormatter(- 'en', // Force English locale- IntlDateFormatter::SHORT,- IntlDateFormatter::NONE,- null,- null,- 'MMM d, yyyy'-);--if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {--- $sort = "next_payment";- $sortOrder = $sort;- $order = "ASC";-- $params = array();- $sql = "SELECT * FROM subscriptions WHERE user_id = :userId";-- if (isset($_GET['categories']) && $_GET['categories'] != "") {- $allCategories = explode(',', $_GET['categories']);- $placeholders = array_map(function ($idx) {- return ":categories{$idx}";- }, array_keys($allCategories));-- $sql .= " AND (" . implode(' OR ', array_map(function ($placeholder) {- return "category_id = {$placeholder}";- }, $placeholders)) . ")";-- foreach ($allCategories as $idx => $category) {- $params[":categories{$idx}"] = $category;- }- }-- if (isset($_GET['payments']) && $_GET['payments'] !== "") {- $allPayments = explode(',', $_GET['payments']);- $placeholders = array_map(function ($idx) {- return ":payments{$idx}";- }, array_keys($allPayments));-- $sql .= " AND (" . implode(' OR ', array_map(function ($placeholder) {- return "payment_method_id = {$placeholder}";- }, $placeholders)) . ")";-- foreach ($allPayments as $idx => $payment) {- $params[":payments{$idx}"] = $payment;- }- }-- if (isset($_GET['members']) && $_GET['members'] != "") {- $allMembers = explode(',', $_GET['members']);- $placeholders = array_map(function ($idx) {- return ":members{$idx}";- }, array_keys($allMembers));-- $sql .= " AND (" . implode(' OR ', array_map(function ($placeholder) {- return "payer_user_id = {$placeholder}";- }, $placeholders)) . ")";-- foreach ($allMembers as $idx => $member) {- $params[":members{$idx}"] = $member;- }- }-- if (isset($_GET['state']) && $_GET['state'] != "") {- $sql .= " AND inactive = :inactive";- $params[':inactive'] = $_GET['state'];- }-- if (isset($_GET['renewalType']) && $_GET['renewalType'] != "") {- if ($_GET['renewalType'] === 'onetime') {- $sql .= " AND cycle = 5";- } else {- $sql .= " AND auto_renew = :auto_renew AND cycle != 5";- $params[':auto_renew'] = $_GET['renewalType'];- }- }-- if (isset($_GET['notifications']) && $_GET['notifications'] !== "") {- $notifTypes = array_filter(explode(',', $_GET['notifications']), fn($t) => in_array($t, ['reminder', 'cancellation', 'none']));- $notifConditions = [];- foreach ($notifTypes as $type) {- if ($type === 'reminder') {- $notifConditions[] = "notify = 1";- } elseif ($type === 'cancellation') {- // One-time purchases are never treated as cancellable, matching the- // dashboard, statistics page and cancellation notification cron.- $notifConditions[] = "(cancellation_date IS NOT NULL AND cancellation_date != '' AND cycle != 5)";- } elseif ($type === 'none') {- $notifConditions[] = "(notify = 0 AND (cancellation_date IS NULL OR cancellation_date = '' OR cycle = 5))";- }- }- if (!empty($notifConditions)) {- $sql .= " AND (" . implode(' OR ', $notifConditions) . ")";- }- }-- if (isset($_COOKIE['sortOrder']) && $_COOKIE['sortOrder'] != "") {- $sort = $_COOKIE['sortOrder'];- }-- $sortOrder = $sort;- $allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric', 'renewal_type'];- $order = ($sort == "price" || $sort == "id") ? "DESC" : "ASC";-- if ($sort == "alphanumeric") {- $sort = "name";- }-- if (!in_array($sort, $allowedSortCriteria)) {- $sort = "next_payment";- }-- if ($sort == "renewal_type") {- $sort = "auto_renew";- }-- $orderByClauses = [];-- if ($settings['disabledToBottom'] === 'true') {- if (in_array($sort, ["payer_user_id", "category_id", "payment_method_id"])) {- $orderByClauses[] = "$sort $order";- $orderByClauses[] = "inactive ASC";- } else {- $orderByClauses[] = "inactive ASC";- $orderByClauses[] = "$sort $order";- }- } else {- $orderByClauses[] = "$sort $order";- if ($sort != "inactive") {- $orderByClauses[] = "inactive ASC";- }- }-- if ($sort != "next_payment") {- $orderByClauses[] = "next_payment ASC";- }-- $sql .= " ORDER BY " . implode(", ", $orderByClauses);-- $stmt = $db->prepare($sql);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-- foreach ($params as $key => $value) {- $stmt->bindValue($key, $value);- }-- $result = $stmt->execute();- if ($result) {- $subscriptions = array();- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $subscriptions[] = $row;- }- }-- foreach ($subscriptions as $subscription) {- if ($subscription['inactive'] == 1 && isset($settings['hideDisabledSubscriptions']) && $settings['hideDisabledSubscriptions'] === 'true') {- continue;- }- $id = $subscription['id'];- $print[$id]['id'] = $id;- $print[$id]['logo'] = $subscription['logo'] != "" ? "images/uploads/logos/" . $subscription['logo'] : "";- $print[$id]['logo_text_color'] = $subscription['logo_text_color'] ?? null;- $print[$id]['logo_variant'] = !empty($subscription['logo_variant']) ? "images/uploads/logos/" . $subscription['logo_variant'] : null;- $print[$id]['name'] = $subscription['name'] ?? "";- $cycle = $subscription['cycle'];- $frequency = $subscription['frequency'];- $print[$id]['billing_cycle'] = getBillingCycle($cycle, $frequency, $i18n);- $print[$id]['one_time'] = ($cycle == 5);- $paymentMethodId = $subscription['payment_method_id'];- $print[$id]['currency_code'] = $currencies[$subscription['currency_id']]['code'];- $currencyId = $subscription['currency_id'];- $next_payment_timestamp = strtotime($subscription['next_payment']);- $formatted_date = $formatter->format($next_payment_timestamp);- $print[$id]['next_payment'] = $formatted_date;- $print[$id]['auto_renew'] = $subscription['auto_renew'];- $paymentIcon = $payment_methods[$paymentMethodId ?? ""]['icon'] ?? "";- $paymentIconFolder = (strpos($paymentIcon, 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";- $print[$id]['payment_method_icon'] = $paymentIcon === "" ? "" : $paymentIconFolder . $paymentIcon;- $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId ?? ""]['name'] ?? "";- $print[$id]['payment_method_id'] = $paymentMethodId;- $print[$id]['category_id'] = $subscription['category_id'];- $print[$id]['payer_user_id'] = $subscription['payer_user_id'];- $print[$id]['price'] = floatval($subscription['price']);- $print[$id]['sort_price'] = getSortPrice($subscription['price'], $subscription['currency_id'], $mainCurrencyId, $cycle, $frequency, $settings, $db);- $print[$id]['progress'] = getSubscriptionProgress($cycle, $frequency, $subscription['next_payment']);- $print[$id]['inactive'] = $subscription['inactive'];- $print[$id]['url'] = $subscription['url'] ?? "";- $print[$id]['notes'] = $subscription['notes'] ?? "";- $print[$id]['replacement_subscription_id'] = $subscription['replacement_subscription_id'];-- if (isset($settings['convertCurrency']) && $settings['convertCurrency'] === 'true' && $currencyId != $mainCurrencyId) {- $print[$id]['price'] = getPriceConverted($print[$id]['price'], $currencyId, $db);- $print[$id]['currency_code'] = $currencies[$mainCurrencyId]['code'];- }- if (isset($settings['showMonthlyPrice']) && $settings['showMonthlyPrice'] === 'true') {- $print[$id]['price'] = getPricePerMonth($cycle, $frequency, $print[$id]['price']);- }- if (isset($settings['showOriginalPrice']) && $settings['showOriginalPrice'] === 'true') {- $print[$id]['original_price'] = floatval($subscription['price']);- $print[$id]['original_currency_code'] = $currencies[$subscription['currency_id']]['code'];- }- }-- if ($sortOrder == "alphanumeric") {- usort($print, function ($a, $b) {- return strnatcmp(strtolower($a['name']), strtolower($b['name']));- });- if ($settings['disabledToBottom'] === 'true') {- usort($print, function ($a, $b) {- return $a['inactive'] - $b['inactive'];- });- }- }-- if ($sortOrder == "category_id") {- usort($print, function ($a, $b) use ($categories) {- return ($categories[$a['category_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($categories[$b['category_id'] ?? ""]['order'] ?? PHP_INT_MAX);- });- }-- if ($sortOrder == "payment_method_id") {- usort($print, function ($a, $b) use ($payment_methods) {- return ($payment_methods[$a['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($payment_methods[$b['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX);- });- }-- if (isset($print)) {- printSubscriptions($print, $sort, $categories, $members, $i18n, $colorTheme, "../../", $settings['disabledToBottom'], $settings['mobileNavigation'], $settings['showSubscriptionProgress'], $currencies, $lang);- }-- if (count($subscriptions) == 0) {- ?>- <div class="no-matching-subscriptions">- <p>- <?= translate('no_matching_subscriptions', $i18n) ?>- </p>- <button class="button" onClick="clearFilters()">- <span clasS="fa-solid fa-minus-circle"></span>- <?= translate('clear_filters', $i18n) ?>- </button>- <img src="images/siteimages/empty.png" alt="<?= translate('empty_page', $i18n) ?>" />- </div>- <?php- }-} else {- http_response_code(401);- ?>- <p class="no-matching-subscriptions"><?= translate('session_expired', $i18n) ?></p>- <?php-}--$db->close();+<?php+require_once '../../includes/connect_endpoint.php';++require_once '../../includes/currency_formatter.php';+require_once '../../includes/getdbkeys.php';+require_once '../../includes/logo_theme_variant.php';++include_once '../../includes/list_subscriptions.php';+require_once '../../includes/subscription_payers.php';++require_once '../../includes/getsettings.php';++$theme = "light";+if (isset($settings['theme'])) {+ $theme = $settings['theme'];+}++$colorTheme = "blue";+if (isset($settings['color_theme'])) {+ $colorTheme = $settings['color_theme'];+}++$formatter = new IntlDateFormatter(+ 'en', // Force English locale+ IntlDateFormatter::SHORT,+ IntlDateFormatter::NONE,+ null,+ null,+ 'MMM d, yyyy'+);++if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {+++ $sort = "next_payment";+ $sortOrder = $sort;+ $order = "ASC";++ $params = array();+ $sql = "SELECT * FROM subscriptions WHERE user_id = :userId";++ if (isset($_GET['categories']) && $_GET['categories'] != "") {+ $allCategories = explode(',', $_GET['categories']);+ $placeholders = array_map(function ($idx) {+ return ":categories{$idx}";+ }, array_keys($allCategories));++ $sql .= " AND (" . implode(' OR ', array_map(function ($placeholder) {+ return "category_id = {$placeholder}";+ }, $placeholders)) . ")";++ foreach ($allCategories as $idx => $category) {+ $params[":categories{$idx}"] = $category;+ }+ }++ if (isset($_GET['payments']) && $_GET['payments'] !== "") {+ $allPayments = explode(',', $_GET['payments']);+ $placeholders = array_map(function ($idx) {+ return ":payments{$idx}";+ }, array_keys($allPayments));++ $sql .= " AND (" . implode(' OR ', array_map(function ($placeholder) {+ return "payment_method_id = {$placeholder}";+ }, $placeholders)) . ")";++ foreach ($allPayments as $idx => $payment) {+ $params[":payments{$idx}"] = $payment;+ }+ }++ if (isset($_GET['members']) && $_GET['members'] != "") {+ $allMembers = explode(',', $_GET['members']);+ $sql .= " AND " . payerFilterCondition($allMembers, $params);+ }++ if (isset($_GET['state']) && $_GET['state'] != "") {+ $sql .= " AND inactive = :inactive";+ $params[':inactive'] = $_GET['state'];+ }++ if (isset($_GET['renewalType']) && $_GET['renewalType'] != "") {+ if ($_GET['renewalType'] === 'onetime') {+ $sql .= " AND cycle = 5";+ } else {+ $sql .= " AND auto_renew = :auto_renew AND cycle != 5";+ $params[':auto_renew'] = $_GET['renewalType'];+ }+ }++ if (isset($_GET['notifications']) && $_GET['notifications'] !== "") {+ $notifTypes = array_filter(explode(',', $_GET['notifications']), fn($t) => in_array($t, ['reminder', 'cancellation', 'none']));+ $notifConditions = [];+ foreach ($notifTypes as $type) {+ if ($type === 'reminder') {+ $notifConditions[] = "notify = 1";+ } elseif ($type === 'cancellation') {+ // One-time purchases are never treated as cancellable, matching the+ // dashboard, statistics page and cancellation notification cron.+ $notifConditions[] = "(cancellation_date IS NOT NULL AND cancellation_date != '' AND cycle != 5)";+ } elseif ($type === 'none') {+ $notifConditions[] = "(notify = 0 AND (cancellation_date IS NULL OR cancellation_date = '' OR cycle = 5))";+ }+ }+ if (!empty($notifConditions)) {+ $sql .= " AND (" . implode(' OR ', $notifConditions) . ")";+ }+ }++ if (isset($_COOKIE['sortOrder']) && $_COOKIE['sortOrder'] != "") {+ $sort = $_COOKIE['sortOrder'];+ }++ $sortOrder = $sort;+ $allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric', 'renewal_type'];+ $order = ($sort == "price" || $sort == "id") ? "DESC" : "ASC";++ if ($sort == "alphanumeric") {+ $sort = "name";+ }++ if (!in_array($sort, $allowedSortCriteria)) {+ $sort = "next_payment";+ }++ if ($sort == "renewal_type") {+ $sort = "auto_renew";+ }++ $orderByClauses = [];++ if ($settings['disabledToBottom'] === 'true') {+ if (in_array($sort, ["payer_user_id", "category_id", "payment_method_id"])) {+ $orderByClauses[] = "$sort $order";+ $orderByClauses[] = "inactive ASC";+ } else {+ $orderByClauses[] = "inactive ASC";+ $orderByClauses[] = "$sort $order";+ }+ } else {+ $orderByClauses[] = "$sort $order";+ if ($sort != "inactive") {+ $orderByClauses[] = "inactive ASC";+ }+ }++ if ($sort != "next_payment") {+ $orderByClauses[] = "next_payment ASC";+ }++ $sql .= " ORDER BY " . implode(", ", $orderByClauses);++ $stmt = $db->prepare($sql);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);++ foreach ($params as $key => $value) {+ $stmt->bindValue($key, $value);+ }++ $result = $stmt->execute();+ if ($result) {+ $subscriptions = array();+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $subscriptions[] = $row;+ }+ }++ $payersBySubscription = getPayersBySubscription($db, $subscriptions);++ foreach ($subscriptions as $subscription) {+ if ($subscription['inactive'] == 1 && isset($settings['hideDisabledSubscriptions']) && $settings['hideDisabledSubscriptions'] === 'true') {+ continue;+ }+ $id = $subscription['id'];+ $print[$id]['id'] = $id;+ $print[$id]['logo'] = $subscription['logo'] != "" ? "images/uploads/logos/" . $subscription['logo'] : "";+ $print[$id]['logo_text_color'] = $subscription['logo_text_color'] ?? null;+ $print[$id]['logo_variant'] = !empty($subscription['logo_variant']) ? "images/uploads/logos/" . $subscription['logo_variant'] : null;+ $print[$id]['name'] = $subscription['name'] ?? "";+ $cycle = $subscription['cycle'];+ $frequency = $subscription['frequency'];+ $print[$id]['billing_cycle'] = getBillingCycle($cycle, $frequency, $i18n);+ $print[$id]['one_time'] = ($cycle == 5);+ $paymentMethodId = $subscription['payment_method_id'];+ $print[$id]['currency_code'] = $currencies[$subscription['currency_id']]['code'];+ $currencyId = $subscription['currency_id'];+ $next_payment_timestamp = strtotime($subscription['next_payment']);+ $formatted_date = $formatter->format($next_payment_timestamp);+ $print[$id]['next_payment'] = $formatted_date;+ $print[$id]['auto_renew'] = $subscription['auto_renew'];+ $paymentIcon = $payment_methods[$paymentMethodId ?? ""]['icon'] ?? "";+ $paymentIconFolder = (strpos($paymentIcon, 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";+ $print[$id]['payment_method_icon'] = $paymentIcon === "" ? "" : $paymentIconFolder . $paymentIcon;+ $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId ?? ""]['name'] ?? "";+ $print[$id]['payment_method_id'] = $paymentMethodId;+ $print[$id]['category_id'] = $subscription['category_id'];+ $print[$id]['payer_user_id'] = $subscription['payer_user_id'];+ $print[$id]['payer_user_ids'] = $payersBySubscription[$id] ?? [];+ $print[$id]['price'] = floatval($subscription['price']);+ $print[$id]['sort_price'] = getSortPrice($subscription['price'], $subscription['currency_id'], $mainCurrencyId, $cycle, $frequency, $settings, $db);+ $print[$id]['progress'] = getSubscriptionProgress($cycle, $frequency, $subscription['next_payment']);+ $print[$id]['inactive'] = $subscription['inactive'];+ $print[$id]['url'] = $subscription['url'] ?? "";+ $print[$id]['notes'] = $subscription['notes'] ?? "";+ $print[$id]['replacement_subscription_id'] = $subscription['replacement_subscription_id'];++ if (isset($settings['convertCurrency']) && $settings['convertCurrency'] === 'true' && $currencyId != $mainCurrencyId) {+ $print[$id]['price'] = getPriceConverted($print[$id]['price'], $currencyId, $db);+ $print[$id]['currency_code'] = $currencies[$mainCurrencyId]['code'];+ }+ if (isset($settings['showMonthlyPrice']) && $settings['showMonthlyPrice'] === 'true') {+ $print[$id]['price'] = getPricePerMonth($cycle, $frequency, $print[$id]['price']);+ }+ if (isset($settings['showOriginalPrice']) && $settings['showOriginalPrice'] === 'true') {+ $print[$id]['original_price'] = floatval($subscription['price']);+ $print[$id]['original_currency_code'] = $currencies[$subscription['currency_id']]['code'];+ }+ }++ if ($sortOrder == "alphanumeric") {+ usort($print, function ($a, $b) {+ return strnatcmp(strtolower($a['name']), strtolower($b['name']));+ });+ if ($settings['disabledToBottom'] === 'true') {+ usort($print, function ($a, $b) {+ return $a['inactive'] - $b['inactive'];+ });+ }+ }++ if ($sortOrder == "category_id") {+ usort($print, function ($a, $b) use ($categories) {+ return ($categories[$a['category_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($categories[$b['category_id'] ?? ""]['order'] ?? PHP_INT_MAX);+ });+ }++ if ($sortOrder == "payment_method_id") {+ usort($print, function ($a, $b) use ($payment_methods) {+ return ($payment_methods[$a['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($payment_methods[$b['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX);+ });+ }++ if (isset($print)) {+ printSubscriptions($print, $sort, $categories, $members, $i18n, $colorTheme, "../../", $settings['disabledToBottom'], $settings['mobileNavigation'], $settings['showSubscriptionProgress'], $currencies, $lang);+ }++ if (count($subscriptions) == 0) {+ ?>+ <div class="no-matching-subscriptions">+ <p>+ <?= translate('no_matching_subscriptions', $i18n) ?>+ </p>+ <button class="button" onClick="clearFilters()">+ <span clasS="fa-solid fa-minus-circle"></span>+ <?= translate('clear_filters', $i18n) ?>+ </button>+ <img src="images/siteimages/empty.png" alt="<?= translate('empty_page', $i18n) ?>" />+ </div>+ <?php+ }+} else {+ http_response_code(401);+ ?>+ <p class="no-matching-subscriptions"><?= translate('session_expired', $i18n) ?></p>+ <?php+}++$db->close();?>\ No newline at end of filediff --git a/includes/stats_calculations.php b/includes/stats_calculations.phpindex 6981c6e..c5d6751 100644--- a/includes/stats_calculations.php+++ b/includes/stats_calculations.php@@ -1,383 +1,402 @@-<?php-require_once __DIR__ . '/budget_period_calculations.php';-require_once __DIR__ . '/currency_rates.php';-require_once __DIR__ . '/default_names.php';--function getPricePerMonth($cycle, $frequency, $price)-{- switch ($cycle) {- case 1:- $numberOfPaymentsPerMonth = (30 / $frequency);- return $price * $numberOfPaymentsPerMonth;- case 2:- $numberOfPaymentsPerMonth = (4.35 / $frequency);- return $price * $numberOfPaymentsPerMonth;- case 3:- $numberOfPaymentsPerMonth = (1 / $frequency);- return $price * $numberOfPaymentsPerMonth;- case 4:- $numberOfMonths = (12 * $frequency);- return $price / $numberOfMonths;- case 5:- return 0;- }-}--function getPriceConverted($price, $currency, $database, $userId)-{- return wallos_convert_price($price, $currency, $database, $userId);-}--// Get categories-$categories = array();-$query = "SELECT * FROM categories WHERE user_id = :userId ORDER BY `order` ASC";-$stmt = $db->prepare($query);-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();-while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $categoryId = $row['id'];- $categories[$categoryId] = $row;- $categories[$categoryId]['count'] = 0;- $categoryCost[$categoryId]['cost'] = 0;- $categoryCost[$categoryId]['name'] = $row['name'];-}--// Get payment methods-$paymentMethods = array();-$query = "SELECT * FROM payment_methods WHERE user_id = :userId AND enabled = 1";-$stmt = $db->prepare($query);-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();-while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $paymentMethodId = $row['id'];- $paymentMethods[$paymentMethodId] = $row;- $paymentMethods[$paymentMethodId]['count'] = 0;- $paymentMethodsCount[$paymentMethodId]['count'] = 0;- $paymentMethodsCount[$paymentMethodId]['name'] = $row['name'];-}--//Get household members-$members = array();-$query = "SELECT * FROM household WHERE user_id = :userId";-$stmt = $db->prepare($query);-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();-while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $memberId = $row['id'];- $members[$memberId] = $row;- $members[$memberId]['count'] = 0;- $memberCost[$memberId]['cost'] = 0;- $memberCost[$memberId]['name'] = $row['name'];-}--// Unfiltered counts for filter menu display (so non-selected items remain visible when a filter is active)-$stmt = $db->prepare("SELECT category_id, COUNT(*) as cnt FROM subscriptions WHERE user_id = :userId GROUP BY category_id");-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$r = $stmt->execute();-$menuCategoryCounts = [];-while ($row = $r->fetchArray(SQLITE3_ASSOC)) {- $menuCategoryCounts[$row['category_id']] = $row['cnt'];-}--$stmt = $db->prepare("SELECT payer_user_id, COUNT(*) as cnt FROM subscriptions WHERE user_id = :userId GROUP BY payer_user_id");-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$r = $stmt->execute();-$menuMemberCounts = [];-while ($row = $r->fetchArray(SQLITE3_ASSOC)) {- $menuMemberCounts[$row['payer_user_id']] = $row['cnt'];-}--$stmt = $db->prepare("SELECT payment_method_id, COUNT(*) as cnt FROM subscriptions WHERE user_id = :userId AND inactive = 0 GROUP BY payment_method_id");-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$r = $stmt->execute();-$menuPaymentCounts = [];-while ($row = $r->fetchArray(SQLITE3_ASSOC)) {- $menuPaymentCounts[$row['payment_method_id']] = $row['cnt'];-}--$activeSubscriptions = 0;-$inactiveSubscriptions = 0;-// Calculate total monthly price-$mostExpensiveSubscription = array();-$mostExpensiveSubscription['price'] = 0;-$amountDueThisMonth = 0;-$totalCostPerMonth = 0;-$totalSavingsPerMonth = 0;-$totalCostsInReplacementsPerMonth = 0;--$statsSubtitleParts = [];-$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 = [];--if (isset($_GET['member']) && $_GET['member'] !== '') {- $memberIds = array_map('intval', explode(',', $_GET['member']));- $conditions[] = "payer_user_id IN (" . implode(',', $memberIds) . ")";- foreach ($memberIds as $mid) {- if (isset($members[$mid])) {- $statsSubtitleParts[] = $members[$mid]['name'];- }- }-}--if (isset($_GET['category']) && $_GET['category'] !== '') {- $categoryIds = array_map('intval', explode(',', $_GET['category']));- $conditions[] = "category_id IN (" . implode(',', $categoryIds) . ")";- // A category still carrying its untouched default name is recognised- // against the account's own creation-language default, not a literal- // English string - #1216 gives every language its own default, so an- // account created in German never had an English name to match here.- $noCategoryDefaultName = default_no_category_name($userData['language'] ?? 'en');- foreach ($categoryIds as $cid) {- if (isset($categories[$cid])) {- $statsSubtitleParts[] = $categories[$cid]['name'] === $noCategoryDefaultName ? translate("no_category", $i18n) : $categories[$cid]['name'];- }- }-}--if (isset($_GET['payment']) && $_GET['payment'] !== '') {- $paymentIds = array_map('intval', explode(',', $_GET['payment']));- $conditions[] = "payment_method_id IN (" . implode(',', $paymentIds) . ")";- foreach ($paymentIds as $pid) {- if (isset($paymentMethodsCount[$pid])) {- $statsSubtitleParts[] = $paymentMethodsCount[$pid]['name'];- }- }-}--$conditions[] = "user_id = :userId";-$params[':userId'] = $userId;--if (!empty($conditions)) {- $query .= " WHERE " . implode(' AND ', $conditions);-}--$stmt = $db->prepare($query);-$statsSubtitle = !empty($statsSubtitleParts) ? '(' . implode(', ', $statsSubtitleParts) . ')' : "";--foreach ($params as $key => $value) {- $stmt->bindValue($key, $value, SQLITE3_INTEGER);-}--$result = $stmt->execute();-$usesMultipleCurrencies = false;-$subscriptions = [];--if ($result) {- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $subscriptions[] = $row;- }- if (isset($subscriptions)) {- $replacementSubscriptions = array();-- foreach ($subscriptions as $subscription) {- $name = $subscription['name'];- $price = $subscription['price'];- $logo = $subscription['logo'];- $frequency = $subscription['frequency'];- $cycle = $subscription['cycle'];- $currency = $subscription['currency_id'];- if ($currency != $userData['main_currency']) {- $usesMultipleCurrencies = true;- }- $next_payment = $subscription['next_payment'];- $payerId = $subscription['payer_user_id'];- if (isset($members[$payerId])) {- $members[$payerId]['count'] += 1;- }- $categoryId = $subscription['category_id'];- if (isset($categories[$categoryId])) {- $categories[$categoryId]['count'] += 1;- }- $paymentMethodId = $subscription['payment_method_id'];- if (isset($paymentMethods[$paymentMethodId])) {- $paymentMethods[$paymentMethodId]['count'] += 1;- }- $inactive = $subscription['inactive'];- $replacementSubscriptionId = $subscription['replacement_subscription_id'];- $originalSubscriptionPrice = getPriceConverted($price, $currency, $db, $userId);- $price = getPricePerMonth($cycle, $frequency, $originalSubscriptionPrice);-- if ($inactive == 0) {- if ($cycle != 5) {- $activeSubscriptions++;- if (isset($paymentMethodsCount[$paymentMethodId])) {- $paymentMethodsCount[$paymentMethodId]['count'] += 1;- }- }- $totalCostPerMonth += $price;- if (isset($memberCost[$payerId])) {- $memberCost[$payerId]['cost'] += $price;- }- if (isset($categoryCost[$categoryId])) {- $categoryCost[$categoryId]['cost'] += $price;- }- if ($price > $mostExpensiveSubscription['price']) {- $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) {- // Calculate ammount due this month- $nextPaymentDate = DateTime::createFromFormat('Y-m-d', trim($next_payment));- $todayVal = new DateTime('today');- $endOfMonth = new DateTime('last day of this month');-- if ($nextPaymentDate >= $todayVal && $nextPaymentDate <= $endOfMonth) {- $timesToPay = 1;- $daysInMonth = $endOfMonth->diff($todayVal)->days + 1;- $daysRemaining = $endOfMonth->diff($nextPaymentDate)->days + 1;- if ($cycle == 1) {- $timesToPay = $daysRemaining / $frequency;- }- if ($cycle == 2) {- $weeksInMonth = ceil($daysInMonth / 7);- $weeksRemaining = ceil($daysRemaining / 7);- $timesToPay = $weeksRemaining / $frequency;- }- $amountDueThisMonth += $originalSubscriptionPrice * $timesToPay;- }- }- } else {- $inactiveSubscriptions++;- $totalSavingsPerMonth += $price;-- // Check if it has a replacement subscription and if it was not already counted- if ($replacementSubscriptionId && !in_array($replacementSubscriptionId, $replacementSubscriptions)) {- $query = "SELECT price, currency_id, cycle, frequency FROM subscriptions WHERE id = :replacementSubscriptionId AND user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindValue(':replacementSubscriptionId', $replacementSubscriptionId, SQLITE3_INTEGER);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();- $replacementSubscription = $result->fetchArray(SQLITE3_ASSOC);- if ($replacementSubscription) {- $replacementSubscriptionPrice = getPriceConverted($replacementSubscription['price'], $replacementSubscription['currency_id'], $db, $userId);- $replacementSubscriptionPrice = getPricePerMonth($replacementSubscription['cycle'], $replacementSubscription['frequency'], $replacementSubscriptionPrice);- $totalCostsInReplacementsPerMonth += $replacementSubscriptionPrice;- }- }-- $replacementSubscriptions[] = $replacementSubscriptionId;- }-- }-- // Subtract the total cost of replacement subscriptions from the total savings- $totalSavingsPerMonth -= $totalCostsInReplacementsPerMonth;-- // Calculate yearly price- $totalCostPerYear = $totalCostPerMonth * 12;-- // Calculate average subscription monthly cost- if ($activeSubscriptions > 0) {- $averageSubscriptionCost = $totalCostPerMonth / $activeSubscriptions;- } else {- $totalCostPerYear = 0;- $averageSubscriptionCost = 0;- }- } else {- $totalCostPerYear = 0;- $averageSubscriptionCost = 0;- }-}--$today = new DateTime('now');-$budgetPeriodType = sanitizeBudgetPeriodType($userData['budget_period_type'] ?? 'monthly');-$budgetPeriodAnchorDate = sanitizeBudgetAnchorDate($userData['budget_period_anchor_date'] ?? getDefaultBudgetAnchorDate());-$activeBudgetPeriod = getActiveBudgetPeriod($today, $budgetPeriodType, $budgetPeriodAnchorDate);-$budgetPeriodStart = $activeBudgetPeriod['start'];-$budgetPeriodEnd = $activeBudgetPeriod['end'];-$budgetPeriodLabel = $activeBudgetPeriod['label'];--// A monthly period whose anchor lands on the calendar month's boundaries is-// identical to the plain monthly budget, so there's nothing distinct to show.-$calendarMonthStart = new DateTime($today->format('Y-m-01'));-$calendarMonthEnd = new DateTime($today->format('Y-m-t'));-$periodDiffersFromCalendarMonth = $budgetPeriodStart->format('Y-m-d') !== $calendarMonthStart->format('Y-m-d')- || $budgetPeriodEnd->format('Y-m-d') !== $calendarMonthEnd->format('Y-m-d');--$amountNeededThisPeriod = computeAmountNeededInPeriod($subscriptions ?? [], $today, $budgetPeriodEnd, $db, $userId);--$showVsMonthlyBudgetGraph = false;-$vsMonthlyBudgetDataPoints = [];-if (isset($userData['budget']) && $userData['budget'] > 0) {- $monthlyBudget = $userData['budget'];- $monthlyBudgetLeft = max(0, $monthlyBudget - $totalCostPerMonth);- $monthlyBudgetUsed = min(100, ($totalCostPerMonth / $monthlyBudget) * 100);- if ($totalCostPerMonth > $monthlyBudget) {- $monthlyOverBudgetAmount = $totalCostPerMonth - $monthlyBudget;- }- $showVsMonthlyBudgetGraph = true;- $vsMonthlyBudgetDataPoints = [- [- "label" => translate('budget_remaining', $i18n),- "y" => $monthlyBudgetLeft,- ],- [- "label" => translate('monthly_cost', $i18n),- "y" => $totalCostPerMonth,- ],- ];- // Backwards compatibility for pages still referencing legacy monthly budget variables.- $budget = $monthlyBudget;- $budgetLeft = $monthlyBudgetLeft;- $budgetUsed = $monthlyBudgetUsed;- $overBudgetAmount = $monthlyOverBudgetAmount ?? 0;-}--$showVsPeriodBudgetGraph = false;-$vsPeriodBudgetDataPoints = [];-if ($periodDiffersFromCalendarMonth && isset($userData['period_budget']) && $userData['period_budget'] > 0) {- $periodBudget = $userData['period_budget'];- $periodBudgetLeft = max(0, $periodBudget - $amountNeededThisPeriod);- $periodBudgetUsed = min(100, ($amountNeededThisPeriod / $periodBudget) * 100);- if ($amountNeededThisPeriod > $periodBudget) {- $periodOverBudgetAmount = $amountNeededThisPeriod - $periodBudget;- }- $showVsPeriodBudgetGraph = true;- $vsPeriodBudgetDataPoints = [- [- "label" => translate('budget_remaining', $i18n),- "y" => $periodBudgetLeft,- ],- [- "label" => translate('amount_needed_this_period', $i18n),- "y" => $amountNeededThisPeriod,- ],- ];-}--// Backwards compatibility for pages still referencing legacy graph variables.-$showVsBudgetGraph = $showVsMonthlyBudgetGraph;-$vsBudgetDataPoints = $vsMonthlyBudgetDataPoints;--$showCantConverErrorMessage = false;-if ($usesMultipleCurrencies) {- $query = "SELECT api_key FROM fixer WHERE user_id = :userId";- $stmt = $db->prepare($query);- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $result = $stmt->execute();- if ($result->fetchArray(SQLITE3_ASSOC) === false) {- $showCantConverErrorMessage = true;- }-}--$query = "SELECT * FROM total_yearly_cost WHERE user_id = :userId";-$stmt = $db->prepare($query);-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();--$totalMonthlyCostDataPoints = [];-while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $totalMonthlyCostDataPoints[] = [- "label" => html_entity_decode($row['date']),- "y" => round($row['cost'] / 12, 2),- ];-}--$showTotalMonthlyCostGraph = count($totalMonthlyCostDataPoints) > 1;-+<?php+require_once __DIR__ . '/budget_period_calculations.php';+require_once __DIR__ . '/currency_rates.php';+require_once __DIR__ . '/default_names.php';+require_once __DIR__ . '/subscription_payers.php';++function getPricePerMonth($cycle, $frequency, $price)+{+ switch ($cycle) {+ case 1:+ $numberOfPaymentsPerMonth = (30 / $frequency);+ return $price * $numberOfPaymentsPerMonth;+ case 2:+ $numberOfPaymentsPerMonth = (4.35 / $frequency);+ return $price * $numberOfPaymentsPerMonth;+ case 3:+ $numberOfPaymentsPerMonth = (1 / $frequency);+ return $price * $numberOfPaymentsPerMonth;+ case 4:+ $numberOfMonths = (12 * $frequency);+ return $price / $numberOfMonths;+ case 5:+ return 0;+ }+}++function getPriceConverted($price, $currency, $database, $userId)+{+ return wallos_convert_price($price, $currency, $database, $userId);+}++// Get categories+$categories = array();+$query = "SELECT * FROM categories WHERE user_id = :userId ORDER BY `order` ASC";+$stmt = $db->prepare($query);+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $categoryId = $row['id'];+ $categories[$categoryId] = $row;+ $categories[$categoryId]['count'] = 0;+ $categoryCost[$categoryId]['cost'] = 0;+ $categoryCost[$categoryId]['name'] = $row['name'];+}++// Get payment methods+$paymentMethods = array();+$query = "SELECT * FROM payment_methods WHERE user_id = :userId AND enabled = 1";+$stmt = $db->prepare($query);+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $paymentMethodId = $row['id'];+ $paymentMethods[$paymentMethodId] = $row;+ $paymentMethods[$paymentMethodId]['count'] = 0;+ $paymentMethodsCount[$paymentMethodId]['count'] = 0;+ $paymentMethodsCount[$paymentMethodId]['name'] = $row['name'];+}++//Get household members+$members = array();+$query = "SELECT * FROM household WHERE user_id = :userId";+$stmt = $db->prepare($query);+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $memberId = $row['id'];+ $members[$memberId] = $row;+ $members[$memberId]['count'] = 0;+ $memberCost[$memberId]['cost'] = 0;+ $memberCost[$memberId]['name'] = $row['name'];+}++// Unfiltered counts for filter menu display (so non-selected items remain visible when a filter is active)+$stmt = $db->prepare("SELECT category_id, COUNT(*) as cnt FROM subscriptions WHERE user_id = :userId GROUP BY category_id");+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$r = $stmt->execute();+$menuCategoryCounts = [];+while ($row = $r->fetchArray(SQLITE3_ASSOC)) {+ $menuCategoryCounts[$row['category_id']] = $row['cnt'];+}++$stmt = $db->prepare("SELECT sp.payer_id AS payer_user_id, COUNT(*) as cnt FROM subscription_payers sp JOIN subscriptions s ON s.id = sp.subscription_id WHERE s.user_id = :userId GROUP BY sp.payer_id");+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$r = $stmt->execute();+$menuMemberCounts = [];+while ($row = $r->fetchArray(SQLITE3_ASSOC)) {+ $menuMemberCounts[$row['payer_user_id']] = $row['cnt'];+}++$stmt = $db->prepare("SELECT payment_method_id, COUNT(*) as cnt FROM subscriptions WHERE user_id = :userId AND inactive = 0 GROUP BY payment_method_id");+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$r = $stmt->execute();+$menuPaymentCounts = [];+while ($row = $r->fetchArray(SQLITE3_ASSOC)) {+ $menuPaymentCounts[$row['payment_method_id']] = $row['cnt'];+}++$activeSubscriptions = 0;+$inactiveSubscriptions = 0;+// Calculate total monthly price+$mostExpensiveSubscription = array();+$mostExpensiveSubscription['price'] = 0;+$amountDueThisMonth = 0;+$totalCostPerMonth = 0;+$totalSavingsPerMonth = 0;+$totalCostsInReplacementsPerMonth = 0;++$statsSubtitleParts = [];+$query = "SELECT id, 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 = [];++$filteredMemberIds = [];+if (isset($_GET['member']) && $_GET['member'] !== '') {+ $memberIds = array_map('intval', explode(',', $_GET['member']));+ $filteredMemberIds = $memberIds;+ $conditions[] = payerFilterCondition($memberIds, $params);+ foreach ($memberIds as $mid) {+ if (isset($members[$mid])) {+ $statsSubtitleParts[] = $members[$mid]['name'];+ }+ }+}++if (isset($_GET['category']) && $_GET['category'] !== '') {+ $categoryIds = array_map('intval', explode(',', $_GET['category']));+ $conditions[] = "category_id IN (" . implode(',', $categoryIds) . ")";+ // A category still carrying its untouched default name is recognised+ // against the account's own creation-language default, not a literal+ // English string - #1216 gives every language its own default, so an+ // account created in German never had an English name to match here.+ $noCategoryDefaultName = default_no_category_name($userData['language'] ?? 'en');+ foreach ($categoryIds as $cid) {+ if (isset($categories[$cid])) {+ $statsSubtitleParts[] = $categories[$cid]['name'] === $noCategoryDefaultName ? translate("no_category", $i18n) : $categories[$cid]['name'];+ }+ }+}++if (isset($_GET['payment']) && $_GET['payment'] !== '') {+ $paymentIds = array_map('intval', explode(',', $_GET['payment']));+ $conditions[] = "payment_method_id IN (" . implode(',', $paymentIds) . ")";+ foreach ($paymentIds as $pid) {+ if (isset($paymentMethodsCount[$pid])) {+ $statsSubtitleParts[] = $paymentMethodsCount[$pid]['name'];+ }+ }+}++$conditions[] = "user_id = :userId";+$params[':userId'] = $userId;++if (!empty($conditions)) {+ $query .= " WHERE " . implode(' AND ', $conditions);+}++$stmt = $db->prepare($query);+$statsSubtitle = !empty($statsSubtitleParts) ? '(' . implode(', ', $statsSubtitleParts) . ')' : "";++foreach ($params as $key => $value) {+ $stmt->bindValue($key, $value, SQLITE3_INTEGER);+}++$result = $stmt->execute();+$usesMultipleCurrencies = false;+$subscriptions = [];++if ($result) {+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $subscriptions[] = $row;+ }+ if (isset($subscriptions)) {+ $replacementSubscriptions = array();+ $payersBySubscription = getPayersBySubscription($db, $subscriptions);++ foreach ($subscriptions as $subscription) {+ $name = $subscription['name'];+ $price = $subscription['price'];+ $logo = $subscription['logo'];+ $frequency = $subscription['frequency'];+ $cycle = $subscription['cycle'];+ $currency = $subscription['currency_id'];+ if ($currency != $userData['main_currency']) {+ $usesMultipleCurrencies = true;+ }+ $next_payment = $subscription['next_payment'];+ $subscriptionPayerIds = $payersBySubscription[$subscription['id']] ?? [];+ foreach ($subscriptionPayerIds as $payerId) {+ if (isset($members[$payerId])) {+ $members[$payerId]['count'] += 1;+ }+ }+ $categoryId = $subscription['category_id'];+ if (isset($categories[$categoryId])) {+ $categories[$categoryId]['count'] += 1;+ }+ $paymentMethodId = $subscription['payment_method_id'];+ if (isset($paymentMethods[$paymentMethodId])) {+ $paymentMethods[$paymentMethodId]['count'] += 1;+ }+ $inactive = $subscription['inactive'];+ $replacementSubscriptionId = $subscription['replacement_subscription_id'];+ $originalSubscriptionPrice = getPriceConverted($price, $currency, $db, $userId);+ $fullPrice = getPricePerMonth($cycle, $frequency, $originalSubscriptionPrice);++ // Filtering by member counts only that member's share of a shared+ // subscription, the same share the per-member breakdown uses.+ $memberShare = 1;+ if (!empty($filteredMemberIds) && count($subscriptionPayerIds) > 0) {+ $memberShare = count(array_intersect($subscriptionPayerIds, $filteredMemberIds)) / count($subscriptionPayerIds);+ }+ $originalSubscriptionPrice *= $memberShare;+ $price = $fullPrice * $memberShare;++ if ($inactive == 0) {+ if ($cycle != 5) {+ $activeSubscriptions++;+ if (isset($paymentMethodsCount[$paymentMethodId])) {+ $paymentMethodsCount[$paymentMethodId]['count'] += 1;+ }+ }+ $totalCostPerMonth += $price;+ // The price is split evenly between the people paying for it+ $payerShare = count($subscriptionPayerIds) > 0 ? $fullPrice / count($subscriptionPayerIds) : 0;+ foreach ($subscriptionPayerIds as $payerId) {+ if (isset($memberCost[$payerId])) {+ $memberCost[$payerId]['cost'] += $payerShare;+ }+ }+ if (isset($categoryCost[$categoryId])) {+ $categoryCost[$categoryId]['cost'] += $price;+ }+ if ($price > $mostExpensiveSubscription['price']) {+ $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) {+ // Calculate ammount due this month+ $nextPaymentDate = DateTime::createFromFormat('Y-m-d', trim($next_payment));+ $todayVal = new DateTime('today');+ $endOfMonth = new DateTime('last day of this month');++ if ($nextPaymentDate >= $todayVal && $nextPaymentDate <= $endOfMonth) {+ $timesToPay = 1;+ $daysInMonth = $endOfMonth->diff($todayVal)->days + 1;+ $daysRemaining = $endOfMonth->diff($nextPaymentDate)->days + 1;+ if ($cycle == 1) {+ $timesToPay = $daysRemaining / $frequency;+ }+ if ($cycle == 2) {+ $weeksInMonth = ceil($daysInMonth / 7);+ $weeksRemaining = ceil($daysRemaining / 7);+ $timesToPay = $weeksRemaining / $frequency;+ }+ $amountDueThisMonth += $originalSubscriptionPrice * $timesToPay;+ }+ }+ } else {+ $inactiveSubscriptions++;+ $totalSavingsPerMonth += $price;++ // Check if it has a replacement subscription and if it was not already counted+ if ($replacementSubscriptionId && !in_array($replacementSubscriptionId, $replacementSubscriptions)) {+ $query = "SELECT price, currency_id, cycle, frequency FROM subscriptions WHERE id = :replacementSubscriptionId AND user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':replacementSubscriptionId', $replacementSubscriptionId, SQLITE3_INTEGER);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();+ $replacementSubscription = $result->fetchArray(SQLITE3_ASSOC);+ if ($replacementSubscription) {+ $replacementSubscriptionPrice = getPriceConverted($replacementSubscription['price'], $replacementSubscription['currency_id'], $db, $userId);+ $replacementSubscriptionPrice = getPricePerMonth($replacementSubscription['cycle'], $replacementSubscription['frequency'], $replacementSubscriptionPrice);+ $totalCostsInReplacementsPerMonth += $replacementSubscriptionPrice;+ }+ }++ $replacementSubscriptions[] = $replacementSubscriptionId;+ }++ }++ // Subtract the total cost of replacement subscriptions from the total savings+ $totalSavingsPerMonth -= $totalCostsInReplacementsPerMonth;++ // Calculate yearly price+ $totalCostPerYear = $totalCostPerMonth * 12;++ // Calculate average subscription monthly cost+ if ($activeSubscriptions > 0) {+ $averageSubscriptionCost = $totalCostPerMonth / $activeSubscriptions;+ } else {+ $totalCostPerYear = 0;+ $averageSubscriptionCost = 0;+ }+ } else {+ $totalCostPerYear = 0;+ $averageSubscriptionCost = 0;+ }+}++$today = new DateTime('now');+$budgetPeriodType = sanitizeBudgetPeriodType($userData['budget_period_type'] ?? 'monthly');+$budgetPeriodAnchorDate = sanitizeBudgetAnchorDate($userData['budget_period_anchor_date'] ?? getDefaultBudgetAnchorDate());+$activeBudgetPeriod = getActiveBudgetPeriod($today, $budgetPeriodType, $budgetPeriodAnchorDate);+$budgetPeriodStart = $activeBudgetPeriod['start'];+$budgetPeriodEnd = $activeBudgetPeriod['end'];+$budgetPeriodLabel = $activeBudgetPeriod['label'];++// A monthly period whose anchor lands on the calendar month's boundaries is+// identical to the plain monthly budget, so there's nothing distinct to show.+$calendarMonthStart = new DateTime($today->format('Y-m-01'));+$calendarMonthEnd = new DateTime($today->format('Y-m-t'));+$periodDiffersFromCalendarMonth = $budgetPeriodStart->format('Y-m-d') !== $calendarMonthStart->format('Y-m-d')+ || $budgetPeriodEnd->format('Y-m-d') !== $calendarMonthEnd->format('Y-m-d');++$amountNeededThisPeriod = computeAmountNeededInPeriod($subscriptions ?? [], $today, $budgetPeriodEnd, $db, $userId);++$showVsMonthlyBudgetGraph = false;+$vsMonthlyBudgetDataPoints = [];+if (isset($userData['budget']) && $userData['budget'] > 0) {+ $monthlyBudget = $userData['budget'];+ $monthlyBudgetLeft = max(0, $monthlyBudget - $totalCostPerMonth);+ $monthlyBudgetUsed = min(100, ($totalCostPerMonth / $monthlyBudget) * 100);+ if ($totalCostPerMonth > $monthlyBudget) {+ $monthlyOverBudgetAmount = $totalCostPerMonth - $monthlyBudget;+ }+ $showVsMonthlyBudgetGraph = true;+ $vsMonthlyBudgetDataPoints = [+ [+ "label" => translate('budget_remaining', $i18n),+ "y" => $monthlyBudgetLeft,+ ],+ [+ "label" => translate('monthly_cost', $i18n),+ "y" => $totalCostPerMonth,+ ],+ ];+ // Backwards compatibility for pages still referencing legacy monthly budget variables.+ $budget = $monthlyBudget;+ $budgetLeft = $monthlyBudgetLeft;+ $budgetUsed = $monthlyBudgetUsed;+ $overBudgetAmount = $monthlyOverBudgetAmount ?? 0;+}++$showVsPeriodBudgetGraph = false;+$vsPeriodBudgetDataPoints = [];+if ($periodDiffersFromCalendarMonth && isset($userData['period_budget']) && $userData['period_budget'] > 0) {+ $periodBudget = $userData['period_budget'];+ $periodBudgetLeft = max(0, $periodBudget - $amountNeededThisPeriod);+ $periodBudgetUsed = min(100, ($amountNeededThisPeriod / $periodBudget) * 100);+ if ($amountNeededThisPeriod > $periodBudget) {+ $periodOverBudgetAmount = $amountNeededThisPeriod - $periodBudget;+ }+ $showVsPeriodBudgetGraph = true;+ $vsPeriodBudgetDataPoints = [+ [+ "label" => translate('budget_remaining', $i18n),+ "y" => $periodBudgetLeft,+ ],+ [+ "label" => translate('amount_needed_this_period', $i18n),+ "y" => $amountNeededThisPeriod,+ ],+ ];+}++// Backwards compatibility for pages still referencing legacy graph variables.+$showVsBudgetGraph = $showVsMonthlyBudgetGraph;+$vsBudgetDataPoints = $vsMonthlyBudgetDataPoints;++$showCantConverErrorMessage = false;+if ($usesMultipleCurrencies) {+ $query = "SELECT api_key FROM fixer WHERE user_id = :userId";+ $stmt = $db->prepare($query);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();+ if ($result->fetchArray(SQLITE3_ASSOC) === false) {+ $showCantConverErrorMessage = true;+ }+}++$query = "SELECT * FROM total_yearly_cost WHERE user_id = :userId";+$stmt = $db->prepare($query);+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();++$totalMonthlyCostDataPoints = [];+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $totalMonthlyCostDataPoints[] = [+ "label" => html_entity_decode($row['date']),+ "y" => round($row['cost'] / 12, 2),+ ];+}++$showTotalMonthlyCostGraph = count($totalMonthlyCostDataPoints) > 1;+?>\ No newline at end of filediff --git a/includes/subscription_payers.php b/includes/subscription_payers.phpnew file mode 100644index 0000000..f8f4fea--- /dev/null+++ b/includes/subscription_payers.php@@ -0,0 +1,111 @@+<?php++// Helpers for subscriptions paid by several household members.+//+// subscription_payers is the full list. subscriptions.payer_user_id keeps the+// first of them (the primary payer), see migrations/000060.php.++// Accepts an array or a comma separated string, returns unique positive ints+// in the order given.+function parsePayerIds($input)+{+ if (is_string($input)) {+ $input = explode(',', $input);+ }+ if (!is_array($input)) {+ return [];+ }+ $ids = [];+ foreach ($input as $value) {+ if ($value === null || $value === '' || !is_numeric($value)) {+ continue;+ }+ $id = intval($value);+ if ($id > 0 && !in_array($id, $ids, true)) {+ $ids[] = $id;+ }+ }+ return $ids;+}++// True when every id is a household member of this user.+function payersBelongToUser($db, $userId, array $payerIds)+{+ $stmt = $db->prepare("SELECT id FROM household WHERE id = :id AND user_id = :userId");+ foreach ($payerIds as $payerId) {+ $stmt->bindValue(':id', $payerId, SQLITE3_INTEGER);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();+ $found = $result && $result->fetchArray();+ $stmt->reset();+ if (!$found) {+ return false;+ }+ }+ return true;+}++// Replaces the payers of a subscription.+function saveSubscriptionPayers($db, $subscriptionId, array $payerIds)+{+ $delete = $db->prepare("DELETE FROM subscription_payers WHERE subscription_id = :subscriptionId");+ $delete->bindValue(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);+ $delete->execute();++ $insert = $db->prepare("INSERT OR IGNORE INTO subscription_payers (subscription_id, payer_id) VALUES (:subscriptionId, :payerId)");+ foreach ($payerIds as $payerId) {+ $insert->bindValue(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);+ $insert->bindValue(':payerId', $payerId, SQLITE3_INTEGER);+ $insert->execute();+ $insert->reset();+ }+}++// Payer ids per subscription id, in the order they were stored. Subscriptions+// without rows fall back to their primary payer so callers never see an+// empty list for a subscription that has one.+function getPayersBySubscription($db, array $subscriptions)+{+ $payers = [];+ $ids = array_values(array_filter(array_map(fn($s) => isset($s['id']) ? intval($s['id']) : 0, $subscriptions)));+ if (count($ids) > 0) {+ $result = $db->query("SELECT subscription_id, payer_id FROM subscription_payers WHERE subscription_id IN (" . implode(',', $ids) . ") ORDER BY rowid");+ while ($result && ($row = $result->fetchArray(SQLITE3_ASSOC))) {+ $payers[$row['subscription_id']][] = intval($row['payer_id']);+ }+ }+ foreach ($subscriptions as $subscription) {+ $id = $subscription['id'] ?? null;+ if ($id !== null && !isset($payers[$id]) && !empty($subscription['payer_user_id'])) {+ $payers[$id] = [intval($subscription['payer_user_id'])];+ }+ }+ return $payers;+}++// Names of the given payers joined for display, skipping unknown ids.+function payerNamesLabel(array $payerIds, array $nameById, $separator = ', ')+{+ $names = [];+ foreach ($payerIds as $payerId) {+ if (isset($nameById[$payerId]) && $nameById[$payerId] !== '') {+ $names[] = $nameById[$payerId];+ }+ }+ return implode($separator, $names);+}++// SQL condition matching subscriptions paid by any of the given members.+// $column is the subscriptions id column, placeholders are named+// :payerFilter0, :payerFilter1, ... and returned in $params.+function payerFilterCondition(array $memberIds, &$params, $idColumn = 'id')+{+ $placeholders = [];+ foreach (array_values($memberIds) as $i => $memberId) {+ $placeholders[] = ":payerFilter{$i}";+ $params[":payerFilter{$i}"] = intval($memberId);+ }+ return "EXISTS (SELECT 1 FROM subscription_payers sp WHERE sp.subscription_id = {$idColumn} AND sp.payer_id IN (" . implode(',', $placeholders) . "))";+}++?>diff --git a/includes/version.php b/includes/version.phpindex 875982e..072d5cf 100644--- a/includes/version.php+++ b/includes/version.php@@ -1,3 +1,3 @@<?php-$version = "v5.8.4";+$version = "v5.9.0";?>diff --git a/migrations/000060.php b/migrations/000060.phpnew file mode 100644index 0000000..12af233--- /dev/null+++ b/migrations/000060.php@@ -0,0 +1,27 @@+<?php++// A subscription can be paid by more than one household member.+//+// subscription_payers holds one row per (subscription, member). The existing+// subscriptions.payer_user_id column stays and keeps the first selected payer,+// the "primary" one: notifications are grouped by it, and the sort and API+// fields built on it keep working unchanged. The new table is the full list.+//+// Every existing subscription gets one row for the payer it already has, so+// nothing changes for an installation until somebody picks a second payer.++$db->exec("CREATE TABLE IF NOT EXISTS subscription_payers (+ subscription_id INTEGER NOT NULL,+ payer_id INTEGER NOT NULL,+ PRIMARY KEY (subscription_id, payer_id),+ FOREIGN KEY (subscription_id) REFERENCES subscriptions(id) ON DELETE CASCADE,+ FOREIGN KEY (payer_id) REFERENCES household(id)+)");++$db->exec('CREATE INDEX IF NOT EXISTS idx_subscription_payers_payer+ ON subscription_payers (payer_id)');++$db->exec('INSERT OR IGNORE INTO subscription_payers (subscription_id, payer_id)+ SELECT id, payer_user_id FROM subscriptions WHERE payer_user_id IS NOT NULL');++?>diff --git a/scripts/subscription-details.js b/scripts/subscription-details.jsindex d18511a..1b4b01f 100644--- a/scripts/subscription-details.js+++ b/scripts/subscription-details.js@@ -157,7 +157,8 @@ function renderSubscriptionDetails(subscription) {document.querySelector('#details-next-payment').textContent = detailsFormatDate(subscription.next_payment);document.querySelector('#details-start-date').textContent = detailsFormatDate(subscription.start_date) || strings.none;document.querySelector('#details-category').textContent = lookups.categories[subscription.category_id] || strings.none;- document.querySelector('#details-payer').textContent = lookups.members[subscription.payer_user_id] || strings.none;+ const payerIds = subscription.payer_user_ids && subscription.payer_user_ids.length > 0 ? subscription.payer_user_ids : [subscription.payer_user_id];+ document.querySelector('#details-payer').textContent = payerIds.map(id => lookups.members[id]).filter(Boolean).join(', ') || strings.none;const paymentMethod = lookups.paymentMethods[subscription.payment_method_id];const paymentIcon = document.querySelector('#details-payment-icon');diff --git a/scripts/subscriptions.js b/scripts/subscriptions.jsindex d4fb907..aec32c4 100644--- a/scripts/subscriptions.js+++ b/scripts/subscriptions.js@@ -1,1256 +1,1377 @@-let isSortOptionsOpen = false;-let scrollTopBeforeOpening = 0;-const shouldScroll = window.innerWidth <= 768;-function toggleSortOptions() {- const sortOptions = document.querySelector("#sort-options");- sortOptions.classList.toggle("is-open");- isSortOptionsOpen = !isSortOptionsOpen;-}--function toggleNotificationDays() {- const notifyCheckbox = document.querySelector("#notifications");- const notifyDaysBefore = document.querySelector("#notify_days_before");- notifyDaysBefore.disabled = !notifyCheckbox.checked;-}--function resetForm() {- const id = document.querySelector("#id");- id.value = "";- const formTitle = document.querySelector("#form-title");- formTitle.textContent = translate('add_subscription');- const logo = document.querySelector("#form-logo");- logo.src = "";- logo.style = 'display: none';- const logoUrl = document.querySelector("#logo-url");- logoUrl.value = "";- const logoSearchButton = document.querySelector("#logo-search-button");- logoSearchButton.classList.add("disabled");- const submitButton = document.querySelector("#save-button");- submitButton.disabled = false;- const autoRenew = document.querySelector("#auto_renew");- autoRenew.checked = true;- const startDate = document.querySelector("#start_date");- startDate.value = new Date().toISOString().split('T')[0];- const notifyDaysBefore = document.querySelector("#notify_days_before");- notifyDaysBefore.disabled = true;- const replacementSubscriptionIdSelect = document.querySelector("#replacement_subscription_id");- replacementSubscriptionIdSelect.value = "0";- const replacementSubscription = document.querySelector(`#replacement_subscritpion`);- replacementSubscription.classList.add("hide");- const form = document.querySelector("#subs-form");- form.reset();- toggleOneTimeCycleUI(false);- closeLogoSearch();- const deleteButton = document.querySelector("#deletesub");- deleteButton.style = 'display: none';- deleteButton.removeAttribute("onClick");-}--// Picks the logo filename that reads well on the theme currently in use,-// falling back to the original when there's no themed variant for it.-function logoFilenameForCurrentTheme(subscription) {- if (!subscription.logo_text_color || !subscription.logo_variant) {- return subscription.logo;- }- const nativeTheme = subscription.logo_text_color === 'dark' ? 'light' : 'dark';- const currentTheme = document.body.classList.contains('dark') ? 'dark' : 'light';- return currentTheme === nativeTheme ? subscription.logo : subscription.logo_variant;-}--function fillEditFormFields(subscription) {- const formTitle = document.querySelector("#form-title");- formTitle.textContent = translate('edit_subscription');- const logo = document.querySelector("#form-logo");- const logoFile = subscription.logo !== null ? "images/uploads/logos/" + logoFilenameForCurrentTheme(subscription) : "";- if (logoFile) {- logo.src = logoFile;- logo.style = 'display: block';- }- const logoSearchButton = document.querySelector("#logo-search-button");- logoSearchButton.classList.remove("disabled");- const id = document.querySelector("#id");- id.value = subscription.id;- const name = document.querySelector("#name");- name.value = subscription.name;- const price = document.querySelector("#price");- price.value = subscription.price;-- const currencySelect = document.querySelector("#currency");- currencySelect.value = subscription.currency_id.toString();- const frequencySelect = document.querySelector("#frequency");- frequencySelect.value = subscription.frequency;- const cycleSelect = document.querySelector("#cycle");- cycleSelect.value = subscription.cycle;- toggleOneTimeCycleUI(subscription.cycle == 5);- const paymentSelect = document.querySelector("#payment_method");- paymentSelect.value = subscription.payment_method_id;- const categorySelect = document.querySelector("#category");- categorySelect.value = subscription.category_id;- const payerSelect = document.querySelector("#payer_user");- payerSelect.value = subscription.payer_user_id;-- const startDate = document.querySelector("#start_date");- startDate.value = subscription.start_date;- const nextPament = document.querySelector("#next_payment");- nextPament.value = subscription.next_payment;- const cancellationDate = document.querySelector("#cancellation_date");- cancellationDate.value = subscription.cancellation_date;-- const notes = document.querySelector("#notes");- notes.value = subscription.notes;- const inactive = document.querySelector("#inactive");- inactive.checked = subscription.inactive;- const url = document.querySelector("#url");- url.value = subscription.url;-- const autoRenew = document.querySelector("#auto_renew");- if (autoRenew) {- autoRenew.checked = subscription.auto_renew;- }-- const notifications = document.querySelector("#notifications");- if (notifications) {- notifications.checked = subscription.notify;- }-- const notifyDaysBefore = document.querySelector("#notify_days_before");- notifyDaysBefore.value = subscription.notify_days_before ?? 0;- if (subscription.notify === 1) {- notifyDaysBefore.disabled = false;- }-- const replacementSubscriptionIdSelect = document.querySelector("#replacement_subscription_id");- replacementSubscriptionIdSelect.value = subscription.replacement_subscription_id ?? 0;-- const replacementSubscription = document.querySelector(`#replacement_subscritpion`);- if (subscription.inactive) {- replacementSubscription.classList.remove("hide");- } else {- replacementSubscription.classList.add("hide");- }-- const deleteButton = document.querySelector("#deletesub");- deleteButton.style = 'display: block';- deleteButton.setAttribute("onClick", `deleteSubscription(event, ${subscription.id})`);-- const modal = document.getElementById('subscription-form');- modal.classList.add("is-open");-}--function openEditSubscription(event, id) {- event.stopPropagation();- scrollTopBeforeOpening = window.scrollY;- const body = document.querySelector('body');- body.classList.add('no-scroll');- const url = `endpoints/subscription/get.php?id=${id}`;- fetch(url)- .then((response) => {- if (response.ok) {- return response.json();- } else {- showErrorMessage(translate('failed_to_load_subscription'));- }- })- .then((data) => {- if (data.error || data === "Error") {- showErrorMessage(translate('failed_to_load_subscription'));- } else {- const subscription = data;- fillEditFormFields(subscription);- }- })- .catch((error) => {- console.log(error);- showErrorMessage(translate('failed_to_load_subscription'));- });-}--function addSubscription() {- resetForm();- const modal = document.getElementById('subscription-form');-- const startDate = document.querySelector("#start_date");- startDate.value = new Date().toISOString().split('T')[0];-- modal.classList.add("is-open");- const body = document.querySelector('body');- body.classList.add('no-scroll');-}--function closeAddSubscription() {- const modal = document.getElementById('subscription-form');- modal.classList.remove("is-open");- const body = document.querySelector('body');- body.classList.remove('no-scroll');- if (shouldScroll) {- window.scrollTo(0, scrollTopBeforeOpening);- }- resetForm();-}--function handleFileSelect(event) {- const fileInput = event.target;- const logoPreview = document.querySelector('.logo-preview');- const logoImg = logoPreview.querySelector('img');- const logoUrl = document.querySelector("#logo-url");- logoUrl.value = "";-- if (fileInput.files && fileInput.files[0]) {- const reader = new FileReader();-- reader.onload = function (e) {- logoImg.src = e.target.result;- logoImg.style.display = 'block';- };-- reader.readAsDataURL(fileInput.files[0]);- }-}--function deleteSubscription(event, id) {- event.stopPropagation();- event.preventDefault();-- if (!confirm(translate('confirm_delete_subscription'))) {- return;- }-- fetch("endpoints/subscription/delete.php", {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-CSRF-Token": window.csrfToken,- },- body: JSON.stringify({ id: id }),- })- .then((response) => response.json())- .then((data) => {- if (data.success) {- showSuccessMessage(translate('subscription_deleted'));- fetchSubscriptions(null, null, "delete");- closeAddSubscription();- closeSubscriptionDetails();- } else {- showErrorMessage(data.message || translate('error_deleting_subscription'));- }- })- .catch((error) => {- console.error("Error:", error);- showErrorMessage(translate('error_deleting_subscription'));- });-}---function cloneSubscription(event, id) {- event.stopPropagation();- event.preventDefault();-- fetch("endpoints/subscription/clone.php", {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-CSRF-Token": window.csrfToken,- },- body: JSON.stringify({ id: id }),- })- .then((response) => {- if (!response.ok) {- throw new Error(translate("network_response_error"));- }- return response.json();- })- .then((data) => {- if (data.success) {- const newId = data.id;- fetchSubscriptions(newId, event, "clone");- showSuccessMessage(decodeURI(data.message));- } else {- showErrorMessage(data.message || translate("error"));- }- })- .catch((error) => {- showErrorMessage(error.message || translate("error"));- });-}---function renewSubscription(event, id) {- event.stopPropagation();- event.preventDefault();-- fetch("endpoints/subscription/renew.php", {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-CSRF-Token": window.csrfToken,- },- body: JSON.stringify({ id: id }),- })- .then((response) => {- if (!response.ok) {- throw new Error(translate("network_response_error"));- }- return response.json();- })- .then((data) => {- if (data.success) {- const newId = data.id;- fetchSubscriptions(newId, event, "renew");- showSuccessMessage(decodeURI(data.message));- } else {- showErrorMessage(data.message || translate("error"));- }- })- .catch((error) => {- showErrorMessage(error.message || translate("error"));- });-}---function setSearchButtonStatus() {-- const nameInput = document.querySelector("#name");- const hasSearchTerm = nameInput.value.trim().length > 0;- const logoSearchButton = document.querySelector("#logo-search-button");- if (hasSearchTerm) {- logoSearchButton.classList.remove("disabled");- } else {- logoSearchButton.classList.add("disabled");- }--}--function searchLogo() {- const nameInput = document.querySelector("#name");- const searchTerm = nameInput.value.trim();- if (searchTerm === "") {- nameInput.focus();- return;- }-- const logoSearchPopup = document.querySelector("#logo-search-results");- const logoResults = document.querySelector("#logo-search-images");- const logoNav = document.querySelector("#logo-search-nav");- const logoSearchBackdrop = document.querySelector("#logo-search-backdrop");- logoSearchPopup.classList.add("is-open");- if (logoSearchBackdrop) {- logoSearchBackdrop.classList.add("is-open");- }- const subscriptionForm = document.querySelector("#subscription-form");- if (subscriptionForm) {- subscriptionForm.classList.add("scroll-locked");- }-- const queryInput = document.querySelector("#logo-search-query");- queryInput.value = searchTerm;-- runLogoSearch(searchTerm);-}--function submitLogoSearch() {- const queryInput = document.querySelector("#logo-search-query");- const searchTerm = queryInput.value.trim();- if (searchTerm === "") {- queryInput.focus();- return;- }-- runLogoSearch(searchTerm);-}--const logoSearchQueryInput = document.querySelector("#logo-search-query");-const logoSearchSubmitButton = document.querySelector("#logo-search-submit");--if (logoSearchQueryInput && logoSearchSubmitButton) {- logoSearchSubmitButton.addEventListener("click", submitLogoSearch);- logoSearchQueryInput.addEventListener("keydown", function (event) {- if (event.key === "Enter") {- event.preventDefault();- submitLogoSearch();- }- });-}--function runLogoSearch(searchTerm) {- const logoSearchPopup = document.querySelector("#logo-search-results");- const logoResults = document.querySelector("#logo-search-images");- const logoNav = document.querySelector("#logo-search-nav");- const logoSearchTitle = document.querySelector("#logo-search-title");- if (logoSearchTitle) {- const baseTitle = logoSearchTitle.dataset.title;- logoSearchTitle.textContent = `${baseTitle}: ${searchTerm}`;- }-- // One section per source, queried in parallel and filled as each response lands- const encodedSearchTerm = encodeURIComponent(searchTerm);- const sources = [- { label: 'selfh.st', url: `endpoints/logos/icon_search.php?search=${encodedSearchTerm}&source=selfhst` },- { label: 'Dashboard Icons', url: `endpoints/logos/icon_search.php?search=${encodedSearchTerm}&source=dashboardicons` },- { label: 'DuckDuckGo', url: `endpoints/logos/search.php?search=${encodedSearchTerm}&source=duckduckgo` },- { label: 'Brave', url: `endpoints/logos/search.php?search=${encodedSearchTerm}&source=brave` },- ];-- // Google requires user-provided API credentials; the section only exists when configured- if (logoSearchPopup.dataset.googleSearch) {- sources.unshift({ label: 'Google', url: `endpoints/logos/google_search.php?search=${encodedSearchTerm}` });- }-- logoResults.innerHTML = "";- if (logoNav) {- logoNav.innerHTML = "";- }-- sources.forEach(source => {- const section = document.createElement("div");- section.className = "logo-search-section";-- const title = document.createElement("h4");- title.textContent = source.label;- section.appendChild(title);-- const resultsContainer = document.createElement("div");- resultsContainer.className = "logo-search-section-results";- section.appendChild(resultsContainer);-- logoResults.appendChild(section);- showSearchState(resultsContainer, 'loading');-- if (logoNav) {- const navItem = document.createElement("button");- navItem.type = "button";- navItem.className = "logo-search-nav-item";- navItem.textContent = source.label;- navItem.onclick = function () {- const targetTop = section.getBoundingClientRect().top - logoResults.getBoundingClientRect().top + logoResults.scrollTop;- logoResults.scrollTo({ top: targetTop, behavior: 'smooth' });- };- logoNav.appendChild(navItem);- }-- fetchLogoSearchSource(source.url)- .then(data => {- if (data.results && data.results.length > 0) {- displayImageResults(data.results, resultsContainer);- } else if (data.error) {- console.error(source.label, data.error);- showSearchState(resultsContainer, 'error');- } else {- showSearchState(resultsContainer, 'empty');- }- })- .catch(error => {- console.error(translate('error_fetching_image_results'), source.label, error);- showSearchState(resultsContainer, 'error');- });- });-}--function fetchLogoSearchSource(url, retry = true) {- return fetch(url, {- cache: "no-store",- headers: { "Accept": "application/json" },- })- .then(response => {- if (!response.ok) {- throw new Error(`HTTP ${response.status}`);- }- return response.text();- })- .then(body => {- try {- return JSON.parse(body);- } catch (error) {- throw new Error("Invalid JSON response");- }- })- .catch(error => {- if (retry) {- // 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;- });-}--function displayImageResults(imageSources, container) {- container.innerHTML = "";-- imageSources.forEach(src => {- const img = document.createElement("img");- img.src = src.thumbnail || src.image;- img.onclick = function () {- const selectedUrl = getSupportedLogoUrl(src);- if (selectedUrl) {- selectWebLogo(selectedUrl, img.src);- }- };- img.onerror = function () {- this.parentNode.removeChild(this);- };- container.appendChild(img);- });-}--function getSupportedLogoUrl(source) {- if (source.image) {- try {- const imagePath = new URL(source.image, window.location.href).pathname.toLowerCase();- if (/\.(png|jpe?g|gif|webp)$/.test(imagePath)) {- return source.image;- }- } catch (error) {- // Fall through to the raster thumbnail for malformed source URLs.- }- }-- return source.thumbnail || "";-}--function selectWebLogo(url, previewUrl = url) {- closeLogoSearch();- const logoPreview = document.querySelector("#form-logo");- const logoUrl = document.querySelector("#logo-url");- logoPreview.src = previewUrl;- logoPreview.style.display = 'block';- logoUrl.value = url;-}--function closeLogoSearch() {- const logoSearchPopup = document.querySelector("#logo-search-results");- logoSearchPopup.classList.remove("is-open");- const logoSearchBackdrop = document.querySelector("#logo-search-backdrop");- if (logoSearchBackdrop) {- logoSearchBackdrop.classList.remove("is-open");- }- const subscriptionForm = document.querySelector("#subscription-form");- if (subscriptionForm) {- subscriptionForm.classList.remove("scroll-locked");- }- const logoSearchTitle = document.querySelector("#logo-search-title");- if (logoSearchTitle) {- logoSearchTitle.textContent = logoSearchTitle.dataset.title;- }- const logoResults = document.querySelector("#logo-search-images");- logoResults.innerHTML = "";-}--function fetchSubscriptions(id, event, initiator) {- const subscriptionsContainer = document.querySelector("#subscriptions");- let getSubscriptions = "endpoints/subscriptions/get.php";-- if (activeFilters['categories'].length > 0) {- getSubscriptions += `?categories=${activeFilters['categories']}`;- }- if (activeFilters['members'].length > 0) {- getSubscriptions += getSubscriptions.includes("?") ? `&members=${activeFilters['members']}` : `?members=${activeFilters['members']}`;- }- if (activeFilters['payments'].length > 0) {- getSubscriptions += getSubscriptions.includes("?") ? `&payments=${activeFilters['payments']}` : `?payments=${activeFilters['payments']}`;- }- if (activeFilters['state'] !== "") {- getSubscriptions += getSubscriptions.includes("?") ? `&state=${activeFilters['state']}` : `?state=${activeFilters['state']}`;- }- if (activeFilters['renewalType'] !== "") {- getSubscriptions += getSubscriptions.includes("?") ? `&renewalType=${activeFilters['renewalType']}` : `?renewalType=${activeFilters['renewalType']}`;- }- if (activeFilters['notifications'].length > 0) {- getSubscriptions += getSubscriptions.includes("?") ? `¬ifications=${activeFilters['notifications']}` : `?notifications=${activeFilters['notifications']}`;- }-- fetch(getSubscriptions)- .then(response => response.text())- .then(data => {- if (data) {- subscriptionsContainer.innerHTML = data;- const mainActions = document.querySelector("#main-actions");- if (data.includes("no-matching-subscriptions")) {- // mainActions.classList.add("hidden");- } else {- mainActions.classList.remove("hidden");- }- }-- if (initiator == "clone" && id && event) {- openEditSubscription(event, id);- }-- setSwipeElements();- if (initiator === "add") {- if (document.getElementsByClassName('subscription').length === 1) {- setTimeout(() => {- swipeHintAnimation();- }, 1000);- }- }- searchSubscriptions();- })- .catch(error => {- console.error(translate('error_reloading_subscription'), error);- });-}--function setSubscriptionsView(view) {- const subscriptionsContainer = document.querySelector("#subscriptions");- subscriptionsContainer.classList.toggle("grid-view", view === "grid");- document.querySelectorAll('.subscription').forEach((card) => {- setCardFlipped(card, false);- card.style.transform = '';- card.style.transition = '';- card.style.zIndex = '';- });- document.querySelector("#view-list-button").classList.toggle("selected", view !== "grid");- document.querySelector("#view-grid-button").classList.toggle("selected", view === "grid");-- const expirationDate = new Date();- expirationDate.setFullYear(expirationDate.getFullYear() + 1);- document.cookie = "subscriptionsView=" + view + "; expires=" + expirationDate.toUTCString() + "; SameSite=Lax";-}--function setSortOption(sortOption) {- const sortOptionsContainer = document.querySelector("#sort-options");- const sortOptionsList = sortOptionsContainer.querySelectorAll("li");- sortOptionsList.forEach((option) => {- if (option.getAttribute("id") === "sort-" + sortOption) {- option.classList.add("selected");- } else {- option.classList.remove("selected");- }- });- const daysToExpire = 30;- const expirationDate = new Date();- expirationDate.setDate(expirationDate.getDate() + daysToExpire);- const cookieValue = encodeURIComponent(sortOption) + '; expires=' + expirationDate.toUTCString();- document.cookie = 'sortOrder=' + cookieValue + '; SameSite=Lax';- fetchSubscriptions(null, null, "sort");- toggleSortOptions();-}--function convertSvgToPng(file, callback) {- const reader = new FileReader();-- reader.onload = function (e) {- const img = new Image();- img.src = e.target.result;- img.onload = function () {- const canvas = document.createElement('canvas');- canvas.width = img.width;- canvas.height = img.height;- const ctx = canvas.getContext('2d');- ctx.drawImage(img, 0, 0);- const pngDataUrl = canvas.toDataURL('image/png');- const pngFile = dataURLtoFile(pngDataUrl, file.name.replace(".svg", ".png"));- callback(pngFile);- };- };-- reader.readAsDataURL(file);-}--function dataURLtoFile(dataurl, filename) {- let arr = dataurl.split(','),- mime = arr[0].match(/:(.*?);/)[1],- bstr = atob(arr[1]),- n = bstr.length,- u8arr = new Uint8Array(n);-- while (n--) {- u8arr[n] = bstr.charCodeAt(n);- }-- return new File([u8arr], filename, { type: mime });-}--function submitFormData(formData, submitButton, endpoint) {- fetch(endpoint, {- method: "POST",- headers: {- "X-CSRF-Token": window.csrfToken,- },- body: formData,- })- .then((response) => response.json())- .then((data) => {- if (data.status === "Success") {- showSuccessMessage(data.message);- if (data.logo_warning) {- showErrorMessage(data.logo_warning);- }- fetchSubscriptions(null, null, "add");- closeAddSubscription();- } else {- showErrorMessage(data.message || translate("unknown_error"));- }- })- .catch((error) => {- console.error(error);- showErrorMessage(translate("unknown_error"));- })- .finally(() => {- submitButton.disabled = false;- });-}--document.addEventListener('DOMContentLoaded', function () {- const cycleSelectEl = document.querySelector("#cycle");- if (cycleSelectEl) {- cycleSelectEl.addEventListener("change", function () {- toggleOneTimeCycleUI(this.value === "5");- });- }-});--document.addEventListener('DOMContentLoaded', function () {- const subscriptionForm = document.querySelector("#subs-form");- const submitButton = document.querySelector("#save-button");- const endpoint = "endpoints/subscription/add.php";-- subscriptionForm.addEventListener("submit", function (e) {- e.preventDefault();-- submitButton.disabled = true;-- const cycleVal = document.querySelector("#cycle")?.value;- if (cycleVal === "5") {- const freq = document.querySelector("#frequency");- if (freq) freq.value = 1;- const cancellationDate = document.querySelector("#cancellation_date");- if (cancellationDate) cancellationDate.value = "";- const notifyDays = document.querySelector("#notify_days_before");- if (notifyDays) notifyDays.value = -1;- }-- const formData = new FormData(subscriptionForm);-- const fileInput = document.querySelector("#logo");- const file = fileInput.files[0];-- if (file && file.type === "image/svg+xml") {- convertSvgToPng(file, function (pngFile) {- formData.set("logo", pngFile);- submitFormData(formData, submitButton, endpoint);- });- } else {- submitFormData(formData, submitButton, endpoint);- }- });-- document.addEventListener('mousedown', function (event) {- const sortOptions = document.querySelector('#sort-options');- const sortButton = document.querySelector("#sort-button");-- if (!sortOptions.contains(event.target) && !sortButton.contains(event.target) && isSortOptionsOpen) {- sortOptions.classList.remove('is-open');- isSortOptionsOpen = false;- }- });-- document.querySelector('#sort-options').addEventListener('focus', function () {- isSortOptionsOpen = true;- });-});--function searchSubscriptions() {- const searchInput = document.querySelector("#search");- const searchContainer = searchInput.parentElement;- const searchTerm = searchInput.value.trim().toLowerCase();-- if (searchTerm.length > 0) {- searchContainer.classList.add("has-text");- } else {- searchContainer.classList.remove("has-text");- }-- const subscriptions = document.querySelectorAll(".subscription");- subscriptions.forEach(subscription => {- const name = subscription.getAttribute('data-name').toLowerCase();- if (!name.includes(searchTerm)) {- subscription.parentElement.classList.add("hide");- } else {- subscription.parentElement.classList.remove("hide");- }- });-}--function clearSearch() {- const searchInput = document.querySelector("#search");-- searchInput.value = "";- searchInput.parentElement.classList.remove("mobile-expanded");- searchSubscriptions();-}--function toggleMobileSearch() {- const searchContainer = document.querySelector(".top-actions .search");-- searchContainer.classList.add("mobile-expanded");- document.querySelector("#search").focus();-}--function closeSubMenus() {- var subMenus = document.querySelectorAll('.filtermenu-submenu-content');- subMenus.forEach(subMenu => {- subMenu.classList.remove('is-open');- });--}--function setSwipeElements() {- if (window.mobileNavigation) {- const swipeElements = document.querySelectorAll('.subscription');-- swipeElements.forEach((element) => {- let startX = 0;- let startY = 0;- let currentX = 0;- let currentY = 0;- let translateX = 0;- const maxTranslateX = element.classList.contains('manual') ? -240 : -180;-- element.addEventListener('touchstart', (e) => {- if (element.closest('.subscriptions.grid-view')) return; // no swipe actions in grid view- startX = e.touches[0].clientX;- startY = e.touches[0].clientY;- element.style.transition = ''; // Remove transition for smooth dragging- });-- element.addEventListener('touchmove', (e) => {- if (element.closest('.subscriptions.grid-view')) return;- currentX = e.touches[0].clientX;- currentY = e.touches[0].clientY;-- const diffX = currentX - startX;- const diffY = currentY - startY;-- // Check if the swipe is more horizontal than vertical- if (Math.abs(diffX) > Math.abs(diffY)) {- e.preventDefault(); // Prevent vertical scrolling-- // Only update translateX if swiping within allowed range- if (!(translateX === maxTranslateX && diffX < 0)) {- translateX = Math.min(0, Math.max(maxTranslateX, diffX)); // Clamp translateX between -180 and 0- element.style.transform = `translateX(${translateX}px)`;- }- }- });-- element.addEventListener('touchend', () => {- if (element.closest('.subscriptions.grid-view')) return;- // Check the final swipe position to determine snap behavior- if (translateX < maxTranslateX / 2) {- // If more than halfway to the left, snap fully open- translateX = maxTranslateX;- } else {- // If swiped less than halfway left or swiped right, snap back to closed- translateX = 0;- }- element.style.transition = 'transform 0.2s ease'; // Smooth snap effect- element.style.transform = `translateX(${translateX}px)`;- element.style.zIndex = '1';- });- });-- }-}--const activeFilters = [];-activeFilters['categories'] = [];-activeFilters['members'] = [];-activeFilters['payments'] = [];-activeFilters['state'] = "";-activeFilters['renewalType'] = "";-activeFilters['notifications'] = [];--document.addEventListener("DOMContentLoaded", function () {- var filtermenu = document.querySelector('#filtermenu-button');- filtermenu.addEventListener('click', function () {- this.parentElement.querySelector('.filtermenu-content').classList.toggle('is-open');- closeSubMenus();- });-- document.addEventListener('click', function (e) {- var filtermenuContent = document.querySelector('.filtermenu-content');- if (filtermenuContent.classList.contains('is-open')) {- var subMenus = document.querySelectorAll('.filtermenu-submenu');- var clickedInsideSubmenu = Array.from(subMenus).some(subMenu => subMenu.contains(e.target) || subMenu === e.target);-- if (!filtermenu.contains(e.target) && !clickedInsideSubmenu) {- closeSubMenus();- filtermenuContent.classList.remove('is-open');- }- }- });-- setSwipeElements();--});--function toggleSubMenu(subMenu) {- var subMenu = document.getElementById("filter-" + subMenu);- if (subMenu.classList.contains("is-open")) {- closeSubMenus();- } else {- closeSubMenus();- subMenu.classList.add("is-open");- }-}--function toggleReplacementSub() {- const checkbox = document.getElementById('inactive');- const replacementSubscription = document.querySelector(`#replacement_subscritpion`);-- if (checkbox.checked) {- replacementSubscription.classList.remove("hide");- } else {- replacementSubscription.classList.add("hide");- }-}--document.querySelectorAll('.filter-item').forEach(function (item) {- item.addEventListener('click', function (e) {- const searchInput = document.querySelector("#search");- searchInput.value = "";-- if (this.hasAttribute('data-categoryid')) {- const categoryId = this.getAttribute('data-categoryid');- if (activeFilters['categories'].includes(categoryId)) {- const categoryIndex = activeFilters['categories'].indexOf(categoryId);- activeFilters['categories'].splice(categoryIndex, 1);- this.classList.remove('selected');- } else {- activeFilters['categories'].push(categoryId);- this.classList.add('selected');- }- } else if (this.hasAttribute('data-memberid')) {- const memberId = this.getAttribute('data-memberid');- if (activeFilters['members'].includes(memberId)) {- const memberIndex = activeFilters['members'].indexOf(memberId);- activeFilters['members'].splice(memberIndex, 1);- this.classList.remove('selected');- } else {- activeFilters['members'].push(memberId);- this.classList.add('selected');- }- } else if (this.hasAttribute('data-paymentid')) {- const paymentId = this.getAttribute('data-paymentid');- if (activeFilters['payments'].includes(paymentId)) {- const paymentIndex = activeFilters['payments'].indexOf(paymentId);- activeFilters['payments'].splice(paymentIndex, 1);- this.classList.remove('selected');- } else {- activeFilters['payments'].push(paymentId);- this.classList.add('selected');- }- } else if (this.hasAttribute('data-state')) {- const state = this.getAttribute('data-state');- if (activeFilters['state'] === state) {- activeFilters['state'] = "";- this.classList.remove('selected');- } else {- activeFilters['state'] = state;- Array.from(this.parentNode.children).forEach(sibling => {- sibling.classList.remove('selected');- });- this.classList.add('selected');- }- } else if (this.hasAttribute('data-renewaltype')) {- const renewalType = this.getAttribute('data-renewaltype');- if (activeFilters['renewalType'] === renewalType) {- activeFilters['renewalType'] = "";- this.classList.remove('selected');- } else {- activeFilters['renewalType'] = renewalType;- Array.from(this.parentNode.children).forEach(sibling => {- sibling.classList.remove('selected');- });- this.classList.add('selected');- }- } else if (this.hasAttribute('data-notificationtype')) {- const notifType = this.getAttribute('data-notificationtype');- if (activeFilters['notifications'].includes(notifType)) {- const idx = activeFilters['notifications'].indexOf(notifType);- activeFilters['notifications'].splice(idx, 1);- this.classList.remove('selected');- } else {- activeFilters['notifications'].push(notifType);- this.classList.add('selected');- }- }-- if (activeFilters['categories'].length > 0 || activeFilters['members'].length > 0 ||- activeFilters['payments'].length > 0 || activeFilters['state'] !== "" ||- activeFilters['renewalType'] !== "" || activeFilters['notifications'].length > 0) {- document.querySelector('#clear-filters').classList.remove('hide');- } else {- document.querySelector('#clear-filters').classList.add('hide');- }-- fetchSubscriptions(null, null, "filter");- });-});--function clearFilters() {- const searchInput = document.querySelector("#search");- searchInput.value = "";- activeFilters['categories'] = [];- activeFilters['members'] = [];- activeFilters['payments'] = [];- activeFilters['state'] = "";- activeFilters['renewalType'] = "";- activeFilters['notifications'] = [];-- document.querySelectorAll('.filter-item').forEach(function (item) {- item.classList.remove('selected');- });- document.querySelector('#clear-filters').classList.add('hide');- fetchSubscriptions(null, null, "clearfilters");-}--let currentActions = null;--document.addEventListener('click', function (event) {- // Check if click was outside currentActions- if (currentActions && !currentActions.contains(event.target)) {- // Click was outside currentActions, close currentActions- currentActions.classList.remove('is-open');- currentActions = null;- }-});--// A flipped card shows its back face via a CSS 3D transform while the front-// stays in the DOM (and vice versa when unflipped) -- backface-visibility-// only hides a face visually, it doesn't remove it from the tab order. The-// `inert` attribute is what actually keeps focus (and assistive tech) out of-// whichever face is currently turned away from the user.-function setCardFlipped(card, flipped) {- card.classList.toggle('flipped', flipped);- const back = card.querySelector('.subscription-back');- const front = card.querySelector('.subscription-main');- if (back) {- back.inert = !flipped;- }- if (front) {- front.inert = flipped;- }-}--function unflipCard(subscriptionId) {- const card = document.querySelector(`.subscription[data-id="${subscriptionId}"]`);- if (card) {- setCardFlipped(card, false);- }-}--function expandActions(event, subscriptionId) {- event.stopPropagation();- event.preventDefault();- const subscriptionDiv = document.querySelector(`.subscription[data-id="${subscriptionId}"]`);-- // Grid view: flip the card over instead of opening the dropdown- if (subscriptionDiv.closest('.subscriptions.grid-view')) {- document.querySelectorAll('.subscription.flipped').forEach((card) => {- if (card !== subscriptionDiv) {- setCardFlipped(card, false);- }- });- setCardFlipped(subscriptionDiv, !subscriptionDiv.classList.contains('flipped'));- return;- }-- const actions = subscriptionDiv.querySelector('.actions');-- // Close all other open actions- const allActions = document.querySelectorAll('.actions.is-open');- allActions.forEach((openAction) => {- if (openAction !== actions) {- openAction.classList.remove('is-open');- openAction.classList.remove('open-above');- }- });-- // Toggle the clicked actions- actions.classList.toggle('is-open');-- if (actions.classList.contains('is-open')) {- actions.classList.remove('open-above');- const rect = actions.getBoundingClientRect();- if (rect.bottom > window.innerHeight) {- actions.classList.add('open-above');- }- currentActions = actions;- } else {- actions.classList.remove('open-above');- currentActions = null;- }-}--function swipeHintAnimation() {- // The swipe hint only exists in list view: no swipe actions in grid view.- if (!window.mobileNavigation || !window.matchMedia('(max-width: 768px)').matches) {- return;- }-- const firstElement = document.querySelector('.subscription');- if (!firstElement || firstElement.closest('.subscriptions.grid-view')) {- return;- }-- const maxAnimations = 3;- const cookieName = 'swipeHintCount';- let count = parseInt(getCookie(cookieName)) || 0;- if (count >= maxAnimations) {- return;- }-- firstElement.style.transition = 'transform 0.3s ease';- firstElement.style.transform = 'translateX(-80px)';-- setTimeout(() => {- firstElement.style.transform = 'translateX(0px)';- firstElement.style.zIndex = '1';- }, 600);-- count++;- document.cookie = `${cookieName}=${count}; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/; SameSite=Lax`;-}--function toggleOneTimeCycleUI(isOneTime) {- const frequencySelect = document.querySelector("#frequency");- const autoRenewGroup = document.querySelector("#auto-renew-group");- const autoRenewCheckbox = document.querySelector("#auto_renew");- const autofillDesktop = document.querySelector("#autofill-next-payment-button.hideOnMobile");- const labelRecurring = document.querySelector("#next-payment-label-recurring");- const labelOnetime = document.querySelector("#next-payment-label-onetime");- const notificationsGroup = document.querySelector("#notifications-group");- const notifyDaysCancellationGroup = document.querySelector("#notify-days-cancellation-group");- const notificationsCheckbox = document.querySelector("#notifications");-- if (isOneTime) {- if (frequencySelect) frequencySelect.style.display = 'none';- if (autoRenewGroup) autoRenewGroup.style.display = 'none';- if (autoRenewCheckbox) { autoRenewCheckbox.checked = false; autoRenewCheckbox.disabled = true; }- if (autofillDesktop) autofillDesktop.style.display = 'none';- if (labelRecurring) labelRecurring.style.display = 'none';- if (labelOnetime) labelOnetime.style.display = '';- if (notificationsGroup) notificationsGroup.style.display = 'none';- if (notifyDaysCancellationGroup) notifyDaysCancellationGroup.style.display = 'none';- if (notificationsCheckbox) { notificationsCheckbox.checked = false; notificationsCheckbox.disabled = true; }- } else {- if (frequencySelect) frequencySelect.style.display = '';- if (autoRenewGroup) autoRenewGroup.style.display = '';- if (autoRenewCheckbox) autoRenewCheckbox.disabled = false;- if (autofillDesktop) autofillDesktop.style.display = '';- if (labelRecurring) labelRecurring.style.display = '';- if (labelOnetime) labelOnetime.style.display = 'none';- if (notificationsGroup) notificationsGroup.style.display = '';- if (notifyDaysCancellationGroup) notifyDaysCancellationGroup.style.display = '';- if (notificationsCheckbox) notificationsCheckbox.disabled = false;- }-}--function autoFillNextPaymentDate(e) {- e.preventDefault();- const frequencySelect = document.querySelector("#frequency");- const cycleSelect = document.querySelector("#cycle");- const startDate = document.querySelector("#start_date");- const nextPayment = document.querySelector("#next_payment");-- // Do nothing if frequency, cycle, or start date is not set- if (!frequencySelect.value || !cycleSelect.value || !startDate.value || isNaN(Date.parse(startDate.value))) {- console.log(frequencySelect.value, cycleSelect.value, startDate.value);- return;- }-- const today = new Date();- const cycle = cycleSelect.value;- const frequency = Number(frequencySelect.value);-- const nextDate = new Date(startDate.value);- let safetyCounter = 0;- const maxIterations = 1000;-- while (nextDate <= today && safetyCounter < maxIterations) {- switch (cycle) {- case '1': // Days- nextDate.setDate(nextDate.getDate() + frequency);- break;- case '2': // Weeks- nextDate.setDate(nextDate.getDate() + 7 * frequency);- break;- case '3': // Months- nextDate.setMonth(nextDate.getMonth() + frequency);- break;- case '4': // Years- nextDate.setFullYear(nextDate.getFullYear() + frequency);- break;- default:- }- safetyCounter++;- }--if (safetyCounter === maxIterations) {- return;-}--nextPayment.value = toISOStringWithTimezone(nextDate).substring(0, 10);-}--function toISOStringWithTimezone(date) {- const pad = n => String(Math.floor(Math.abs(n))).padStart(2, '0');- const tzOffset = -date.getTimezoneOffset();- const sign = tzOffset >= 0 ? '+' : '-';- const hoursOffset = pad(tzOffset / 60);- const minutesOffset = pad(tzOffset % 60);-- return date.getFullYear() +- '-' + pad(date.getMonth() + 1) +- '-' + pad(date.getDate()) +- 'T' + pad(date.getHours()) +- ':' + pad(date.getMinutes()) +- ':' + pad(date.getSeconds()) +- sign + hoursOffset +- ':' + minutesOffset;-}--function insertMarkdownSyntax(textarea, prefix, suffix, placeholder) {- const start = textarea.selectionStart;- const end = textarea.selectionEnd;- const selected = textarea.value.slice(start, end) || placeholder;-- textarea.setRangeText(prefix + selected + suffix, start, end, 'select');- textarea.focus();- textarea.setSelectionRange(start + prefix.length, start + prefix.length + selected.length);-}--function applyNotesMarkdown(action) {- const textarea = document.querySelector('#notes');- if (!textarea) {- return;- }-- switch (action) {- case 'bold':- insertMarkdownSyntax(textarea, '**', '**', translate('notes_bold'));- break;- case 'italic':- insertMarkdownSyntax(textarea, '_', '_', translate('notes_italic'));- break;- case 'list': {- const start = textarea.selectionStart;- const lineStart = textarea.value.lastIndexOf('\n', start - 1) + 1;- textarea.setRangeText('- ', lineStart, lineStart, 'end');- textarea.focus();- break;- }- case 'link':- insertMarkdownSyntax(textarea, '[', '](https://)', translate('notes_link'));- break;- }-}--window.addEventListener('load', () => {- if (document.querySelector('.subscription')) {- swipeHintAnimation();- }-});+let isSortOptionsOpen = false;+let scrollTopBeforeOpening = 0;+const shouldScroll = window.innerWidth <= 768;+function toggleSortOptions() {+ const sortOptions = document.querySelector("#sort-options");+ sortOptions.classList.toggle("is-open");+ isSortOptionsOpen = !isSortOptionsOpen;+}++function toggleNotificationDays() {+ const notifyCheckbox = document.querySelector("#notifications");+ const notifyDaysBefore = document.querySelector("#notify_days_before");+ notifyDaysBefore.disabled = !notifyCheckbox.checked;+}++// Multi-select for the "Paid by" field. The hidden #payer_user input carries the+// selected member ids as a comma separated list, first one being the primary payer.+function getPayerSelection() {+ const value = document.querySelector("#payer_user").value;+ return value === "" ? [] : value.split(",");+}++function setPayerSelection(ids) {+ const select = document.querySelector("#payer_user_select");+ const options = select.querySelectorAll("li[role='option']");+ const wanted = ids.map(String).filter(id => select.querySelector(`li[data-value="${id}"]`));+ // A subscription always has a payer, default to the first member.+ if (wanted.length === 0 && options.length > 0) {+ wanted.push(options[0].dataset.value);+ }+ options.forEach(option => {+ option.setAttribute("aria-selected", wanted.includes(option.dataset.value) ? "true" : "false");+ });+ document.querySelector("#payer_user").value = wanted.join(",");+ const names = wanted.map(id => select.querySelector(`li[data-value="${id}"] .multi-select-name`).textContent.trim());+ select.querySelector(".multi-select-label").textContent = names.length > 0 ? names.join(", ") : select.dataset.placeholder;+}++function togglePayerOption(option) {+ const current = getPayerSelection();+ const id = option.dataset.value;+ if (current.includes(id)) {+ // Keep at least one payer selected.+ if (current.length === 1) {+ return;+ }+ setPayerSelection(current.filter(value => value !== id));+ } else {+ setPayerSelection([...current, id]);+ }+}++function closePayerSelect() {+ const select = document.querySelector("#payer_user_select");+ select.classList.remove("is-open");+ select.querySelector(".multi-select-options").hidden = true;+ select.querySelector(".multi-select-toggle").setAttribute("aria-expanded", "false");+}++function openPayerSelect() {+ const select = document.querySelector("#payer_user_select");+ select.classList.add("is-open");+ const list = select.querySelector(".multi-select-options");+ list.hidden = false;+ select.querySelector(".multi-select-toggle").setAttribute("aria-expanded", "true");+ const first = list.querySelector("li[aria-selected='true']") || list.querySelector("li");+ if (first) {+ first.focus();+ }+}++function initPayerSelect() {+ const select = document.querySelector("#payer_user_select");+ if (!select) {+ return;+ }+ const toggle = select.querySelector(".multi-select-toggle");+ const list = select.querySelector(".multi-select-options");+ list.querySelectorAll("li").forEach(option => option.tabIndex = -1);++ toggle.addEventListener("click", () => {+ select.classList.contains("is-open") ? closePayerSelect() : openPayerSelect();+ });++ toggle.addEventListener("keydown", event => {+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ openPayerSelect();+ }+ });++ list.addEventListener("click", event => {+ const option = event.target.closest("li[role='option']");+ if (option) {+ togglePayerOption(option);+ option.focus();+ }+ });++ list.addEventListener("keydown", event => {+ const options = Array.from(list.querySelectorAll("li"));+ const index = options.indexOf(document.activeElement);+ if (event.key === "ArrowDown") {+ event.preventDefault();+ options[Math.min(index + 1, options.length - 1)].focus();+ } else if (event.key === "ArrowUp") {+ event.preventDefault();+ options[Math.max(index - 1, 0)].focus();+ } else if (event.key === " " || event.key === "Enter") {+ event.preventDefault();+ if (index >= 0) {+ togglePayerOption(options[index]);+ }+ } else if (event.key === "Escape" || event.key === "Tab") {+ if (event.key === "Escape") {+ event.stopPropagation();+ }+ closePayerSelect();+ toggle.focus();+ }+ });++ document.addEventListener("mousedown", event => {+ if (select.classList.contains("is-open") && !select.contains(event.target)) {+ closePayerSelect();+ }+ });++ setPayerSelection(getPayerSelection());+}++function resetForm() {+ const id = document.querySelector("#id");+ id.value = "";+ const formTitle = document.querySelector("#form-title");+ formTitle.textContent = translate('add_subscription');+ const logo = document.querySelector("#form-logo");+ logo.src = "";+ logo.style = 'display: none';+ const logoUrl = document.querySelector("#logo-url");+ logoUrl.value = "";+ const logoSearchButton = document.querySelector("#logo-search-button");+ logoSearchButton.classList.add("disabled");+ const submitButton = document.querySelector("#save-button");+ submitButton.disabled = false;+ const autoRenew = document.querySelector("#auto_renew");+ autoRenew.checked = true;+ const startDate = document.querySelector("#start_date");+ startDate.value = new Date().toISOString().split('T')[0];+ const notifyDaysBefore = document.querySelector("#notify_days_before");+ notifyDaysBefore.disabled = true;+ const replacementSubscriptionIdSelect = document.querySelector("#replacement_subscription_id");+ replacementSubscriptionIdSelect.value = "0";+ const replacementSubscription = document.querySelector(`#replacement_subscritpion`);+ replacementSubscription.classList.add("hide");+ const form = document.querySelector("#subs-form");+ form.reset();+ setPayerSelection([]);+ closePayerSelect();+ toggleOneTimeCycleUI(false);+ closeLogoSearch();+ const deleteButton = document.querySelector("#deletesub");+ deleteButton.style = 'display: none';+ deleteButton.removeAttribute("onClick");+}++// Picks the logo filename that reads well on the theme currently in use,+// falling back to the original when there's no themed variant for it.+function logoFilenameForCurrentTheme(subscription) {+ if (!subscription.logo_text_color || !subscription.logo_variant) {+ return subscription.logo;+ }+ const nativeTheme = subscription.logo_text_color === 'dark' ? 'light' : 'dark';+ const currentTheme = document.body.classList.contains('dark') ? 'dark' : 'light';+ return currentTheme === nativeTheme ? subscription.logo : subscription.logo_variant;+}++function fillEditFormFields(subscription) {+ const formTitle = document.querySelector("#form-title");+ formTitle.textContent = translate('edit_subscription');+ const logo = document.querySelector("#form-logo");+ const logoFile = subscription.logo !== null ? "images/uploads/logos/" + logoFilenameForCurrentTheme(subscription) : "";+ if (logoFile) {+ logo.src = logoFile;+ logo.style = 'display: block';+ }+ const logoSearchButton = document.querySelector("#logo-search-button");+ logoSearchButton.classList.remove("disabled");+ const id = document.querySelector("#id");+ id.value = subscription.id;+ const name = document.querySelector("#name");+ name.value = subscription.name;+ const price = document.querySelector("#price");+ price.value = subscription.price;++ const currencySelect = document.querySelector("#currency");+ currencySelect.value = subscription.currency_id.toString();+ const frequencySelect = document.querySelector("#frequency");+ frequencySelect.value = subscription.frequency;+ const cycleSelect = document.querySelector("#cycle");+ cycleSelect.value = subscription.cycle;+ toggleOneTimeCycleUI(subscription.cycle == 5);+ const paymentSelect = document.querySelector("#payment_method");+ paymentSelect.value = subscription.payment_method_id;+ const categorySelect = document.querySelector("#category");+ categorySelect.value = subscription.category_id;+ setPayerSelection(subscription.payer_user_ids && subscription.payer_user_ids.length > 0+ ? subscription.payer_user_ids+ : [subscription.payer_user_id]);++ const startDate = document.querySelector("#start_date");+ startDate.value = subscription.start_date;+ const nextPament = document.querySelector("#next_payment");+ nextPament.value = subscription.next_payment;+ const cancellationDate = document.querySelector("#cancellation_date");+ cancellationDate.value = subscription.cancellation_date;++ const notes = document.querySelector("#notes");+ notes.value = subscription.notes;+ const inactive = document.querySelector("#inactive");+ inactive.checked = subscription.inactive;+ const url = document.querySelector("#url");+ url.value = subscription.url;++ const autoRenew = document.querySelector("#auto_renew");+ if (autoRenew) {+ autoRenew.checked = subscription.auto_renew;+ }++ const notifications = document.querySelector("#notifications");+ if (notifications) {+ notifications.checked = subscription.notify;+ }++ const notifyDaysBefore = document.querySelector("#notify_days_before");+ notifyDaysBefore.value = subscription.notify_days_before ?? 0;+ if (subscription.notify === 1) {+ notifyDaysBefore.disabled = false;+ }++ const replacementSubscriptionIdSelect = document.querySelector("#replacement_subscription_id");+ replacementSubscriptionIdSelect.value = subscription.replacement_subscription_id ?? 0;++ const replacementSubscription = document.querySelector(`#replacement_subscritpion`);+ if (subscription.inactive) {+ replacementSubscription.classList.remove("hide");+ } else {+ replacementSubscription.classList.add("hide");+ }++ const deleteButton = document.querySelector("#deletesub");+ deleteButton.style = 'display: block';+ deleteButton.setAttribute("onClick", `deleteSubscription(event, ${subscription.id})`);++ const modal = document.getElementById('subscription-form');+ modal.classList.add("is-open");+}++function openEditSubscription(event, id) {+ event.stopPropagation();+ scrollTopBeforeOpening = window.scrollY;+ const body = document.querySelector('body');+ body.classList.add('no-scroll');+ const url = `endpoints/subscription/get.php?id=${id}`;+ fetch(url)+ .then((response) => {+ if (response.ok) {+ return response.json();+ } else {+ showErrorMessage(translate('failed_to_load_subscription'));+ }+ })+ .then((data) => {+ if (data.error || data === "Error") {+ showErrorMessage(translate('failed_to_load_subscription'));+ } else {+ const subscription = data;+ fillEditFormFields(subscription);+ }+ })+ .catch((error) => {+ console.log(error);+ showErrorMessage(translate('failed_to_load_subscription'));+ });+}++function addSubscription() {+ resetForm();+ const modal = document.getElementById('subscription-form');++ const startDate = document.querySelector("#start_date");+ startDate.value = new Date().toISOString().split('T')[0];++ modal.classList.add("is-open");+ const body = document.querySelector('body');+ body.classList.add('no-scroll');+}++function closeAddSubscription() {+ const modal = document.getElementById('subscription-form');+ modal.classList.remove("is-open");+ const body = document.querySelector('body');+ body.classList.remove('no-scroll');+ if (shouldScroll) {+ window.scrollTo(0, scrollTopBeforeOpening);+ }+ resetForm();+}++function handleFileSelect(event) {+ const fileInput = event.target;+ const logoPreview = document.querySelector('.logo-preview');+ const logoImg = logoPreview.querySelector('img');+ const logoUrl = document.querySelector("#logo-url");+ logoUrl.value = "";++ if (fileInput.files && fileInput.files[0]) {+ const reader = new FileReader();++ reader.onload = function (e) {+ logoImg.src = e.target.result;+ logoImg.style.display = 'block';+ };++ reader.readAsDataURL(fileInput.files[0]);+ }+}++function deleteSubscription(event, id) {+ event.stopPropagation();+ event.preventDefault();++ if (!confirm(translate('confirm_delete_subscription'))) {+ return;+ }++ fetch("endpoints/subscription/delete.php", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-CSRF-Token": window.csrfToken,+ },+ body: JSON.stringify({ id: id }),+ })+ .then((response) => response.json())+ .then((data) => {+ if (data.success) {+ showSuccessMessage(translate('subscription_deleted'));+ fetchSubscriptions(null, null, "delete");+ closeAddSubscription();+ closeSubscriptionDetails();+ } else {+ showErrorMessage(data.message || translate('error_deleting_subscription'));+ }+ })+ .catch((error) => {+ console.error("Error:", error);+ showErrorMessage(translate('error_deleting_subscription'));+ });+}+++function cloneSubscription(event, id) {+ event.stopPropagation();+ event.preventDefault();++ fetch("endpoints/subscription/clone.php", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-CSRF-Token": window.csrfToken,+ },+ body: JSON.stringify({ id: id }),+ })+ .then((response) => {+ if (!response.ok) {+ throw new Error(translate("network_response_error"));+ }+ return response.json();+ })+ .then((data) => {+ if (data.success) {+ const newId = data.id;+ fetchSubscriptions(newId, event, "clone");+ showSuccessMessage(decodeURI(data.message));+ } else {+ showErrorMessage(data.message || translate("error"));+ }+ })+ .catch((error) => {+ showErrorMessage(error.message || translate("error"));+ });+}+++function renewSubscription(event, id) {+ event.stopPropagation();+ event.preventDefault();++ fetch("endpoints/subscription/renew.php", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-CSRF-Token": window.csrfToken,+ },+ body: JSON.stringify({ id: id }),+ })+ .then((response) => {+ if (!response.ok) {+ throw new Error(translate("network_response_error"));+ }+ return response.json();+ })+ .then((data) => {+ if (data.success) {+ const newId = data.id;+ fetchSubscriptions(newId, event, "renew");+ showSuccessMessage(decodeURI(data.message));+ } else {+ showErrorMessage(data.message || translate("error"));+ }+ })+ .catch((error) => {+ showErrorMessage(error.message || translate("error"));+ });+}+++function setSearchButtonStatus() {++ const nameInput = document.querySelector("#name");+ const hasSearchTerm = nameInput.value.trim().length > 0;+ const logoSearchButton = document.querySelector("#logo-search-button");+ if (hasSearchTerm) {+ logoSearchButton.classList.remove("disabled");+ } else {+ logoSearchButton.classList.add("disabled");+ }++}++function searchLogo() {+ const nameInput = document.querySelector("#name");+ const searchTerm = nameInput.value.trim();+ if (searchTerm === "") {+ nameInput.focus();+ return;+ }++ const logoSearchPopup = document.querySelector("#logo-search-results");+ const logoResults = document.querySelector("#logo-search-images");+ const logoNav = document.querySelector("#logo-search-nav");+ const logoSearchBackdrop = document.querySelector("#logo-search-backdrop");+ logoSearchPopup.classList.add("is-open");+ if (logoSearchBackdrop) {+ logoSearchBackdrop.classList.add("is-open");+ }+ const subscriptionForm = document.querySelector("#subscription-form");+ if (subscriptionForm) {+ subscriptionForm.classList.add("scroll-locked");+ }++ const queryInput = document.querySelector("#logo-search-query");+ queryInput.value = searchTerm;++ runLogoSearch(searchTerm);+}++function submitLogoSearch() {+ const queryInput = document.querySelector("#logo-search-query");+ const searchTerm = queryInput.value.trim();+ if (searchTerm === "") {+ queryInput.focus();+ return;+ }++ runLogoSearch(searchTerm);+}++const logoSearchQueryInput = document.querySelector("#logo-search-query");+const logoSearchSubmitButton = document.querySelector("#logo-search-submit");++if (logoSearchQueryInput && logoSearchSubmitButton) {+ logoSearchSubmitButton.addEventListener("click", submitLogoSearch);+ logoSearchQueryInput.addEventListener("keydown", function (event) {+ if (event.key === "Enter") {+ event.preventDefault();+ submitLogoSearch();+ }+ });+}++function runLogoSearch(searchTerm) {+ const logoSearchPopup = document.querySelector("#logo-search-results");+ const logoResults = document.querySelector("#logo-search-images");+ const logoNav = document.querySelector("#logo-search-nav");+ const logoSearchTitle = document.querySelector("#logo-search-title");+ if (logoSearchTitle) {+ const baseTitle = logoSearchTitle.dataset.title;+ logoSearchTitle.textContent = `${baseTitle}: ${searchTerm}`;+ }++ // One section per source, queried in parallel and filled as each response lands+ const encodedSearchTerm = encodeURIComponent(searchTerm);+ const sources = [+ { label: 'selfh.st', url: `endpoints/logos/icon_search.php?search=${encodedSearchTerm}&source=selfhst` },+ { label: 'Dashboard Icons', url: `endpoints/logos/icon_search.php?search=${encodedSearchTerm}&source=dashboardicons` },+ { label: 'DuckDuckGo', url: `endpoints/logos/search.php?search=${encodedSearchTerm}&source=duckduckgo` },+ { label: 'Brave', url: `endpoints/logos/search.php?search=${encodedSearchTerm}&source=brave` },+ ];++ // Google requires user-provided API credentials; the section only exists when configured+ if (logoSearchPopup.dataset.googleSearch) {+ sources.unshift({ label: 'Google', url: `endpoints/logos/google_search.php?search=${encodedSearchTerm}` });+ }++ logoResults.innerHTML = "";+ if (logoNav) {+ logoNav.innerHTML = "";+ }++ sources.forEach(source => {+ const section = document.createElement("div");+ section.className = "logo-search-section";++ const title = document.createElement("h4");+ title.textContent = source.label;+ section.appendChild(title);++ const resultsContainer = document.createElement("div");+ resultsContainer.className = "logo-search-section-results";+ section.appendChild(resultsContainer);++ logoResults.appendChild(section);+ showSearchState(resultsContainer, 'loading');++ if (logoNav) {+ const navItem = document.createElement("button");+ navItem.type = "button";+ navItem.className = "logo-search-nav-item";+ navItem.textContent = source.label;+ navItem.onclick = function () {+ const targetTop = section.getBoundingClientRect().top - logoResults.getBoundingClientRect().top + logoResults.scrollTop;+ logoResults.scrollTo({ top: targetTop, behavior: 'smooth' });+ };+ logoNav.appendChild(navItem);+ }++ fetchLogoSearchSource(source.url)+ .then(data => {+ if (data.results && data.results.length > 0) {+ displayImageResults(data.results, resultsContainer);+ } else if (data.error) {+ console.error(source.label, data.error);+ showSearchState(resultsContainer, 'error');+ } else {+ showSearchState(resultsContainer, 'empty');+ }+ })+ .catch(error => {+ console.error(translate('error_fetching_image_results'), source.label, error);+ showSearchState(resultsContainer, 'error');+ });+ });+}++function fetchLogoSearchSource(url, retry = true) {+ return fetch(url, {+ cache: "no-store",+ headers: { "Accept": "application/json" },+ })+ .then(response => {+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}`);+ }+ return response.text();+ })+ .then(body => {+ try {+ return JSON.parse(body);+ } catch (error) {+ throw new Error("Invalid JSON response");+ }+ })+ .catch(error => {+ if (retry) {+ // 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;+ });+}++function displayImageResults(imageSources, container) {+ container.innerHTML = "";++ imageSources.forEach(src => {+ const img = document.createElement("img");+ img.src = src.thumbnail || src.image;+ img.onclick = function () {+ const selectedUrl = getSupportedLogoUrl(src);+ if (selectedUrl) {+ selectWebLogo(selectedUrl, img.src);+ }+ };+ img.onerror = function () {+ this.parentNode.removeChild(this);+ };+ container.appendChild(img);+ });+}++function getSupportedLogoUrl(source) {+ if (source.image) {+ try {+ const imagePath = new URL(source.image, window.location.href).pathname.toLowerCase();+ if (/\.(png|jpe?g|gif|webp)$/.test(imagePath)) {+ return source.image;+ }+ } catch (error) {+ // Fall through to the raster thumbnail for malformed source URLs.+ }+ }++ return source.thumbnail || "";+}++function selectWebLogo(url, previewUrl = url) {+ closeLogoSearch();+ const logoPreview = document.querySelector("#form-logo");+ const logoUrl = document.querySelector("#logo-url");+ logoPreview.src = previewUrl;+ logoPreview.style.display = 'block';+ logoUrl.value = url;+}++function closeLogoSearch() {+ const logoSearchPopup = document.querySelector("#logo-search-results");+ logoSearchPopup.classList.remove("is-open");+ const logoSearchBackdrop = document.querySelector("#logo-search-backdrop");+ if (logoSearchBackdrop) {+ logoSearchBackdrop.classList.remove("is-open");+ }+ const subscriptionForm = document.querySelector("#subscription-form");+ if (subscriptionForm) {+ subscriptionForm.classList.remove("scroll-locked");+ }+ const logoSearchTitle = document.querySelector("#logo-search-title");+ if (logoSearchTitle) {+ logoSearchTitle.textContent = logoSearchTitle.dataset.title;+ }+ const logoResults = document.querySelector("#logo-search-images");+ logoResults.innerHTML = "";+}++function fetchSubscriptions(id, event, initiator) {+ const subscriptionsContainer = document.querySelector("#subscriptions");+ let getSubscriptions = "endpoints/subscriptions/get.php";++ if (activeFilters['categories'].length > 0) {+ getSubscriptions += `?categories=${activeFilters['categories']}`;+ }+ if (activeFilters['members'].length > 0) {+ getSubscriptions += getSubscriptions.includes("?") ? `&members=${activeFilters['members']}` : `?members=${activeFilters['members']}`;+ }+ if (activeFilters['payments'].length > 0) {+ getSubscriptions += getSubscriptions.includes("?") ? `&payments=${activeFilters['payments']}` : `?payments=${activeFilters['payments']}`;+ }+ if (activeFilters['state'] !== "") {+ getSubscriptions += getSubscriptions.includes("?") ? `&state=${activeFilters['state']}` : `?state=${activeFilters['state']}`;+ }+ if (activeFilters['renewalType'] !== "") {+ getSubscriptions += getSubscriptions.includes("?") ? `&renewalType=${activeFilters['renewalType']}` : `?renewalType=${activeFilters['renewalType']}`;+ }+ if (activeFilters['notifications'].length > 0) {+ getSubscriptions += getSubscriptions.includes("?") ? `¬ifications=${activeFilters['notifications']}` : `?notifications=${activeFilters['notifications']}`;+ }++ fetch(getSubscriptions)+ .then(response => response.text())+ .then(data => {+ if (data) {+ subscriptionsContainer.innerHTML = data;+ const mainActions = document.querySelector("#main-actions");+ if (data.includes("no-matching-subscriptions")) {+ // mainActions.classList.add("hidden");+ } else {+ mainActions.classList.remove("hidden");+ }+ }++ if (initiator == "clone" && id && event) {+ openEditSubscription(event, id);+ }++ setSwipeElements();+ if (initiator === "add") {+ if (document.getElementsByClassName('subscription').length === 1) {+ setTimeout(() => {+ swipeHintAnimation();+ }, 1000);+ }+ }+ searchSubscriptions();+ })+ .catch(error => {+ console.error(translate('error_reloading_subscription'), error);+ });+}++function setSubscriptionsView(view) {+ const subscriptionsContainer = document.querySelector("#subscriptions");+ subscriptionsContainer.classList.toggle("grid-view", view === "grid");+ document.querySelectorAll('.subscription').forEach((card) => {+ setCardFlipped(card, false);+ card.style.transform = '';+ card.style.transition = '';+ card.style.zIndex = '';+ });+ document.querySelector("#view-list-button").classList.toggle("selected", view !== "grid");+ document.querySelector("#view-grid-button").classList.toggle("selected", view === "grid");++ const expirationDate = new Date();+ expirationDate.setFullYear(expirationDate.getFullYear() + 1);+ document.cookie = "subscriptionsView=" + view + "; expires=" + expirationDate.toUTCString() + "; SameSite=Lax";+}++function setSortOption(sortOption) {+ const sortOptionsContainer = document.querySelector("#sort-options");+ const sortOptionsList = sortOptionsContainer.querySelectorAll("li");+ sortOptionsList.forEach((option) => {+ if (option.getAttribute("id") === "sort-" + sortOption) {+ option.classList.add("selected");+ } else {+ option.classList.remove("selected");+ }+ });+ const daysToExpire = 30;+ const expirationDate = new Date();+ expirationDate.setDate(expirationDate.getDate() + daysToExpire);+ const cookieValue = encodeURIComponent(sortOption) + '; expires=' + expirationDate.toUTCString();+ document.cookie = 'sortOrder=' + cookieValue + '; SameSite=Lax';+ fetchSubscriptions(null, null, "sort");+ toggleSortOptions();+}++function convertSvgToPng(file, callback) {+ const reader = new FileReader();++ reader.onload = function (e) {+ const img = new Image();+ img.src = e.target.result;+ img.onload = function () {+ const canvas = document.createElement('canvas');+ canvas.width = img.width;+ canvas.height = img.height;+ const ctx = canvas.getContext('2d');+ ctx.drawImage(img, 0, 0);+ const pngDataUrl = canvas.toDataURL('image/png');+ const pngFile = dataURLtoFile(pngDataUrl, file.name.replace(".svg", ".png"));+ callback(pngFile);+ };+ };++ reader.readAsDataURL(file);+}++function dataURLtoFile(dataurl, filename) {+ let arr = dataurl.split(','),+ mime = arr[0].match(/:(.*?);/)[1],+ bstr = atob(arr[1]),+ n = bstr.length,+ u8arr = new Uint8Array(n);++ while (n--) {+ u8arr[n] = bstr.charCodeAt(n);+ }++ return new File([u8arr], filename, { type: mime });+}++function submitFormData(formData, submitButton, endpoint) {+ fetch(endpoint, {+ method: "POST",+ headers: {+ "X-CSRF-Token": window.csrfToken,+ },+ body: formData,+ })+ .then((response) => response.json())+ .then((data) => {+ if (data.status === "Success") {+ showSuccessMessage(data.message);+ if (data.logo_warning) {+ showErrorMessage(data.logo_warning);+ }+ fetchSubscriptions(null, null, "add");+ closeAddSubscription();+ } else {+ showErrorMessage(data.message || translate("unknown_error"));+ }+ })+ .catch((error) => {+ console.error(error);+ showErrorMessage(translate("unknown_error"));+ })+ .finally(() => {+ submitButton.disabled = false;+ });+}++document.addEventListener('DOMContentLoaded', function () {+ const cycleSelectEl = document.querySelector("#cycle");+ if (cycleSelectEl) {+ cycleSelectEl.addEventListener("change", function () {+ toggleOneTimeCycleUI(this.value === "5");+ });+ }+});++document.addEventListener('DOMContentLoaded', function () {+ initPayerSelect();++ const subscriptionForm = document.querySelector("#subs-form");+ const submitButton = document.querySelector("#save-button");+ const endpoint = "endpoints/subscription/add.php";++ subscriptionForm.addEventListener("submit", function (e) {+ e.preventDefault();++ submitButton.disabled = true;++ const cycleVal = document.querySelector("#cycle")?.value;+ if (cycleVal === "5") {+ const freq = document.querySelector("#frequency");+ if (freq) freq.value = 1;+ const cancellationDate = document.querySelector("#cancellation_date");+ if (cancellationDate) cancellationDate.value = "";+ const notifyDays = document.querySelector("#notify_days_before");+ if (notifyDays) notifyDays.value = -1;+ }++ const formData = new FormData(subscriptionForm);++ const fileInput = document.querySelector("#logo");+ const file = fileInput.files[0];++ if (file && file.type === "image/svg+xml") {+ convertSvgToPng(file, function (pngFile) {+ formData.set("logo", pngFile);+ submitFormData(formData, submitButton, endpoint);+ });+ } else {+ submitFormData(formData, submitButton, endpoint);+ }+ });++ document.addEventListener('mousedown', function (event) {+ const sortOptions = document.querySelector('#sort-options');+ const sortButton = document.querySelector("#sort-button");++ if (!sortOptions.contains(event.target) && !sortButton.contains(event.target) && isSortOptionsOpen) {+ sortOptions.classList.remove('is-open');+ isSortOptionsOpen = false;+ }+ });++ document.querySelector('#sort-options').addEventListener('focus', function () {+ isSortOptionsOpen = true;+ });+});++function searchSubscriptions() {+ const searchInput = document.querySelector("#search");+ const searchContainer = searchInput.parentElement;+ const searchTerm = searchInput.value.trim().toLowerCase();++ if (searchTerm.length > 0) {+ searchContainer.classList.add("has-text");+ } else {+ searchContainer.classList.remove("has-text");+ }++ const subscriptions = document.querySelectorAll(".subscription");+ subscriptions.forEach(subscription => {+ const name = subscription.getAttribute('data-name').toLowerCase();+ if (!name.includes(searchTerm)) {+ subscription.parentElement.classList.add("hide");+ } else {+ subscription.parentElement.classList.remove("hide");+ }+ });+}++function clearSearch() {+ const searchInput = document.querySelector("#search");++ searchInput.value = "";+ searchInput.parentElement.classList.remove("mobile-expanded");+ searchSubscriptions();+}++function toggleMobileSearch() {+ const searchContainer = document.querySelector(".top-actions .search");++ searchContainer.classList.add("mobile-expanded");+ document.querySelector("#search").focus();+}++function closeSubMenus() {+ var subMenus = document.querySelectorAll('.filtermenu-submenu-content');+ subMenus.forEach(subMenu => {+ subMenu.classList.remove('is-open');+ });++}++function setSwipeElements() {+ if (window.mobileNavigation) {+ const swipeElements = document.querySelectorAll('.subscription');++ swipeElements.forEach((element) => {+ let startX = 0;+ let startY = 0;+ let currentX = 0;+ let currentY = 0;+ let translateX = 0;+ const maxTranslateX = element.classList.contains('manual') ? -240 : -180;++ element.addEventListener('touchstart', (e) => {+ if (element.closest('.subscriptions.grid-view')) return; // no swipe actions in grid view+ startX = e.touches[0].clientX;+ startY = e.touches[0].clientY;+ element.style.transition = ''; // Remove transition for smooth dragging+ });++ element.addEventListener('touchmove', (e) => {+ if (element.closest('.subscriptions.grid-view')) return;+ currentX = e.touches[0].clientX;+ currentY = e.touches[0].clientY;++ const diffX = currentX - startX;+ const diffY = currentY - startY;++ // Check if the swipe is more horizontal than vertical+ if (Math.abs(diffX) > Math.abs(diffY)) {+ e.preventDefault(); // Prevent vertical scrolling++ // Only update translateX if swiping within allowed range+ if (!(translateX === maxTranslateX && diffX < 0)) {+ translateX = Math.min(0, Math.max(maxTranslateX, diffX)); // Clamp translateX between -180 and 0+ element.style.transform = `translateX(${translateX}px)`;+ }+ }+ });++ element.addEventListener('touchend', () => {+ if (element.closest('.subscriptions.grid-view')) return;+ // Check the final swipe position to determine snap behavior+ if (translateX < maxTranslateX / 2) {+ // If more than halfway to the left, snap fully open+ translateX = maxTranslateX;+ } else {+ // If swiped less than halfway left or swiped right, snap back to closed+ translateX = 0;+ }+ element.style.transition = 'transform 0.2s ease'; // Smooth snap effect+ element.style.transform = `translateX(${translateX}px)`;+ element.style.zIndex = '1';+ });+ });++ }+}++const activeFilters = [];+activeFilters['categories'] = [];+activeFilters['members'] = [];+activeFilters['payments'] = [];+activeFilters['state'] = "";+activeFilters['renewalType'] = "";+activeFilters['notifications'] = [];++document.addEventListener("DOMContentLoaded", function () {+ var filtermenu = document.querySelector('#filtermenu-button');+ filtermenu.addEventListener('click', function () {+ this.parentElement.querySelector('.filtermenu-content').classList.toggle('is-open');+ closeSubMenus();+ });++ document.addEventListener('click', function (e) {+ var filtermenuContent = document.querySelector('.filtermenu-content');+ if (filtermenuContent.classList.contains('is-open')) {+ var subMenus = document.querySelectorAll('.filtermenu-submenu');+ var clickedInsideSubmenu = Array.from(subMenus).some(subMenu => subMenu.contains(e.target) || subMenu === e.target);++ if (!filtermenu.contains(e.target) && !clickedInsideSubmenu) {+ closeSubMenus();+ filtermenuContent.classList.remove('is-open');+ }+ }+ });++ setSwipeElements();++});++function toggleSubMenu(subMenu) {+ var subMenu = document.getElementById("filter-" + subMenu);+ if (subMenu.classList.contains("is-open")) {+ closeSubMenus();+ } else {+ closeSubMenus();+ subMenu.classList.add("is-open");+ }+}++function toggleReplacementSub() {+ const checkbox = document.getElementById('inactive');+ const replacementSubscription = document.querySelector(`#replacement_subscritpion`);++ if (checkbox.checked) {+ replacementSubscription.classList.remove("hide");+ } else {+ replacementSubscription.classList.add("hide");+ }+}++document.querySelectorAll('.filter-item').forEach(function (item) {+ item.addEventListener('click', function (e) {+ const searchInput = document.querySelector("#search");+ searchInput.value = "";++ if (this.hasAttribute('data-categoryid')) {+ const categoryId = this.getAttribute('data-categoryid');+ if (activeFilters['categories'].includes(categoryId)) {+ const categoryIndex = activeFilters['categories'].indexOf(categoryId);+ activeFilters['categories'].splice(categoryIndex, 1);+ this.classList.remove('selected');+ } else {+ activeFilters['categories'].push(categoryId);+ this.classList.add('selected');+ }+ } else if (this.hasAttribute('data-memberid')) {+ const memberId = this.getAttribute('data-memberid');+ if (activeFilters['members'].includes(memberId)) {+ const memberIndex = activeFilters['members'].indexOf(memberId);+ activeFilters['members'].splice(memberIndex, 1);+ this.classList.remove('selected');+ } else {+ activeFilters['members'].push(memberId);+ this.classList.add('selected');+ }+ } else if (this.hasAttribute('data-paymentid')) {+ const paymentId = this.getAttribute('data-paymentid');+ if (activeFilters['payments'].includes(paymentId)) {+ const paymentIndex = activeFilters['payments'].indexOf(paymentId);+ activeFilters['payments'].splice(paymentIndex, 1);+ this.classList.remove('selected');+ } else {+ activeFilters['payments'].push(paymentId);+ this.classList.add('selected');+ }+ } else if (this.hasAttribute('data-state')) {+ const state = this.getAttribute('data-state');+ if (activeFilters['state'] === state) {+ activeFilters['state'] = "";+ this.classList.remove('selected');+ } else {+ activeFilters['state'] = state;+ Array.from(this.parentNode.children).forEach(sibling => {+ sibling.classList.remove('selected');+ });+ this.classList.add('selected');+ }+ } else if (this.hasAttribute('data-renewaltype')) {+ const renewalType = this.getAttribute('data-renewaltype');+ if (activeFilters['renewalType'] === renewalType) {+ activeFilters['renewalType'] = "";+ this.classList.remove('selected');+ } else {+ activeFilters['renewalType'] = renewalType;+ Array.from(this.parentNode.children).forEach(sibling => {+ sibling.classList.remove('selected');+ });+ this.classList.add('selected');+ }+ } else if (this.hasAttribute('data-notificationtype')) {+ const notifType = this.getAttribute('data-notificationtype');+ if (activeFilters['notifications'].includes(notifType)) {+ const idx = activeFilters['notifications'].indexOf(notifType);+ activeFilters['notifications'].splice(idx, 1);+ this.classList.remove('selected');+ } else {+ activeFilters['notifications'].push(notifType);+ this.classList.add('selected');+ }+ }++ if (activeFilters['categories'].length > 0 || activeFilters['members'].length > 0 ||+ activeFilters['payments'].length > 0 || activeFilters['state'] !== "" ||+ activeFilters['renewalType'] !== "" || activeFilters['notifications'].length > 0) {+ document.querySelector('#clear-filters').classList.remove('hide');+ } else {+ document.querySelector('#clear-filters').classList.add('hide');+ }++ fetchSubscriptions(null, null, "filter");+ });+});++function clearFilters() {+ const searchInput = document.querySelector("#search");+ searchInput.value = "";+ activeFilters['categories'] = [];+ activeFilters['members'] = [];+ activeFilters['payments'] = [];+ activeFilters['state'] = "";+ activeFilters['renewalType'] = "";+ activeFilters['notifications'] = [];++ document.querySelectorAll('.filter-item').forEach(function (item) {+ item.classList.remove('selected');+ });+ document.querySelector('#clear-filters').classList.add('hide');+ fetchSubscriptions(null, null, "clearfilters");+}++let currentActions = null;++document.addEventListener('click', function (event) {+ // Check if click was outside currentActions+ if (currentActions && !currentActions.contains(event.target)) {+ // Click was outside currentActions, close currentActions+ currentActions.classList.remove('is-open');+ currentActions = null;+ }+});++// A flipped card shows its back face via a CSS 3D transform while the front+// stays in the DOM (and vice versa when unflipped) -- backface-visibility+// only hides a face visually, it doesn't remove it from the tab order. The+// `inert` attribute is what actually keeps focus (and assistive tech) out of+// whichever face is currently turned away from the user.+function setCardFlipped(card, flipped) {+ card.classList.toggle('flipped', flipped);+ const back = card.querySelector('.subscription-back');+ const front = card.querySelector('.subscription-main');+ if (back) {+ back.inert = !flipped;+ }+ if (front) {+ front.inert = flipped;+ }+}++function unflipCard(subscriptionId) {+ const card = document.querySelector(`.subscription[data-id="${subscriptionId}"]`);+ if (card) {+ setCardFlipped(card, false);+ }+}++function expandActions(event, subscriptionId) {+ event.stopPropagation();+ event.preventDefault();+ const subscriptionDiv = document.querySelector(`.subscription[data-id="${subscriptionId}"]`);++ // Grid view: flip the card over instead of opening the dropdown+ if (subscriptionDiv.closest('.subscriptions.grid-view')) {+ document.querySelectorAll('.subscription.flipped').forEach((card) => {+ if (card !== subscriptionDiv) {+ setCardFlipped(card, false);+ }+ });+ setCardFlipped(subscriptionDiv, !subscriptionDiv.classList.contains('flipped'));+ return;+ }++ const actions = subscriptionDiv.querySelector('.actions');++ // Close all other open actions+ const allActions = document.querySelectorAll('.actions.is-open');+ allActions.forEach((openAction) => {+ if (openAction !== actions) {+ openAction.classList.remove('is-open');+ openAction.classList.remove('open-above');+ }+ });++ // Toggle the clicked actions+ actions.classList.toggle('is-open');++ if (actions.classList.contains('is-open')) {+ actions.classList.remove('open-above');+ const rect = actions.getBoundingClientRect();+ if (rect.bottom > window.innerHeight) {+ actions.classList.add('open-above');+ }+ currentActions = actions;+ } else {+ actions.classList.remove('open-above');+ currentActions = null;+ }+}++function swipeHintAnimation() {+ // The swipe hint only exists in list view: no swipe actions in grid view.+ if (!window.mobileNavigation || !window.matchMedia('(max-width: 768px)').matches) {+ return;+ }++ const firstElement = document.querySelector('.subscription');+ if (!firstElement || firstElement.closest('.subscriptions.grid-view')) {+ return;+ }++ const maxAnimations = 3;+ const cookieName = 'swipeHintCount';+ let count = parseInt(getCookie(cookieName)) || 0;+ if (count >= maxAnimations) {+ return;+ }++ firstElement.style.transition = 'transform 0.3s ease';+ firstElement.style.transform = 'translateX(-80px)';++ setTimeout(() => {+ firstElement.style.transform = 'translateX(0px)';+ firstElement.style.zIndex = '1';+ }, 600);++ count++;+ document.cookie = `${cookieName}=${count}; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/; SameSite=Lax`;+}++function toggleOneTimeCycleUI(isOneTime) {+ const frequencySelect = document.querySelector("#frequency");+ const autoRenewGroup = document.querySelector("#auto-renew-group");+ const autoRenewCheckbox = document.querySelector("#auto_renew");+ const autofillDesktop = document.querySelector("#autofill-next-payment-button.hideOnMobile");+ const labelRecurring = document.querySelector("#next-payment-label-recurring");+ const labelOnetime = document.querySelector("#next-payment-label-onetime");+ const notificationsGroup = document.querySelector("#notifications-group");+ const notifyDaysCancellationGroup = document.querySelector("#notify-days-cancellation-group");+ const notificationsCheckbox = document.querySelector("#notifications");++ if (isOneTime) {+ if (frequencySelect) frequencySelect.style.display = 'none';+ if (autoRenewGroup) autoRenewGroup.style.display = 'none';+ if (autoRenewCheckbox) { autoRenewCheckbox.checked = false; autoRenewCheckbox.disabled = true; }+ if (autofillDesktop) autofillDesktop.style.display = 'none';+ if (labelRecurring) labelRecurring.style.display = 'none';+ if (labelOnetime) labelOnetime.style.display = '';+ if (notificationsGroup) notificationsGroup.style.display = 'none';+ if (notifyDaysCancellationGroup) notifyDaysCancellationGroup.style.display = 'none';+ if (notificationsCheckbox) { notificationsCheckbox.checked = false; notificationsCheckbox.disabled = true; }+ } else {+ if (frequencySelect) frequencySelect.style.display = '';+ if (autoRenewGroup) autoRenewGroup.style.display = '';+ if (autoRenewCheckbox) autoRenewCheckbox.disabled = false;+ if (autofillDesktop) autofillDesktop.style.display = '';+ if (labelRecurring) labelRecurring.style.display = '';+ if (labelOnetime) labelOnetime.style.display = 'none';+ if (notificationsGroup) notificationsGroup.style.display = '';+ if (notifyDaysCancellationGroup) notifyDaysCancellationGroup.style.display = '';+ if (notificationsCheckbox) notificationsCheckbox.disabled = false;+ }+}++function autoFillNextPaymentDate(e) {+ e.preventDefault();+ const frequencySelect = document.querySelector("#frequency");+ const cycleSelect = document.querySelector("#cycle");+ const startDate = document.querySelector("#start_date");+ const nextPayment = document.querySelector("#next_payment");++ // Do nothing if frequency, cycle, or start date is not set+ if (!frequencySelect.value || !cycleSelect.value || !startDate.value || isNaN(Date.parse(startDate.value))) {+ console.log(frequencySelect.value, cycleSelect.value, startDate.value);+ return;+ }++ const today = new Date();+ const cycle = cycleSelect.value;+ const frequency = Number(frequencySelect.value);++ const nextDate = new Date(startDate.value);+ let safetyCounter = 0;+ const maxIterations = 1000;++ while (nextDate <= today && safetyCounter < maxIterations) {+ switch (cycle) {+ case '1': // Days+ nextDate.setDate(nextDate.getDate() + frequency);+ break;+ case '2': // Weeks+ nextDate.setDate(nextDate.getDate() + 7 * frequency);+ break;+ case '3': // Months+ nextDate.setMonth(nextDate.getMonth() + frequency);+ break;+ case '4': // Years+ nextDate.setFullYear(nextDate.getFullYear() + frequency);+ break;+ default:+ }+ safetyCounter++;+ }++if (safetyCounter === maxIterations) {+ return;+}++nextPayment.value = toISOStringWithTimezone(nextDate).substring(0, 10);+}++function toISOStringWithTimezone(date) {+ const pad = n => String(Math.floor(Math.abs(n))).padStart(2, '0');+ const tzOffset = -date.getTimezoneOffset();+ const sign = tzOffset >= 0 ? '+' : '-';+ const hoursOffset = pad(tzOffset / 60);+ const minutesOffset = pad(tzOffset % 60);++ return date.getFullYear() ++ '-' + pad(date.getMonth() + 1) ++ '-' + pad(date.getDate()) ++ 'T' + pad(date.getHours()) ++ ':' + pad(date.getMinutes()) ++ ':' + pad(date.getSeconds()) ++ sign + hoursOffset ++ ':' + minutesOffset;+}++function insertMarkdownSyntax(textarea, prefix, suffix, placeholder) {+ const start = textarea.selectionStart;+ const end = textarea.selectionEnd;+ const selected = textarea.value.slice(start, end) || placeholder;++ textarea.setRangeText(prefix + selected + suffix, start, end, 'select');+ textarea.focus();+ textarea.setSelectionRange(start + prefix.length, start + prefix.length + selected.length);+}++function applyNotesMarkdown(action) {+ const textarea = document.querySelector('#notes');+ if (!textarea) {+ return;+ }++ switch (action) {+ case 'bold':+ insertMarkdownSyntax(textarea, '**', '**', translate('notes_bold'));+ break;+ case 'italic':+ insertMarkdownSyntax(textarea, '_', '_', translate('notes_italic'));+ break;+ case 'list': {+ const start = textarea.selectionStart;+ const lineStart = textarea.value.lastIndexOf('\n', start - 1) + 1;+ textarea.setRangeText('- ', lineStart, lineStart, 'end');+ textarea.focus();+ break;+ }+ case 'link':+ insertMarkdownSyntax(textarea, '[', '](https://)', translate('notes_link'));+ break;+ }+}++window.addEventListener('load', () => {+ if (document.querySelector('.subscription')) {+ swipeHintAnimation();+ }+});diff --git a/styles/styles.css b/styles/styles.cssindex 5041b41..c058313 100644--- a/styles/styles.css+++ b/styles/styles.css@@ -1637,6 +1637,116 @@ select {padding-left: 40px;}+.multi-select {+ position: relative;+ width: 100%;+}++.multi-select-toggle {+ width: 100%;+ height: 50px;+ padding: 0 40px 0 15px;+ font-size: 16px;+ text-align: left;+ background-color: var(--input-background-color);+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath d='M2.5 4.5 6 8l3.5-3.5' fill='none' stroke='%2364748B' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");+ background-repeat: no-repeat;+ background-position: right 15px center;+ border: 1px solid var(--input-border-color);+ border-radius: 10px;+ color: var(--text-color);+ cursor: pointer;+ box-sizing: border-box;+ outline: none;+ transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;+}++.multi-select-toggle:focus,+.multi-select.is-open .multi-select-toggle {+ border-color: var(--main-color);+ box-shadow: var(--focus-ring);+}++.multi-select-label {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.multi-select-options {+ position: absolute;+ top: calc(100% + 4px);+ left: 0;+ right: 0;+ z-index: 10;+ max-height: 240px;+ margin: 0;+ padding: 4px;+ overflow-y: auto;+ list-style: none;+ background-color: var(--input-background-color);+ border: 1px solid var(--input-border-color);+ border-radius: 10px;+ box-shadow: var(--box-shadow);+ box-sizing: border-box;+}++.multi-select-options[hidden] {+ display: none;+}++.multi-select-options li {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 10px 11px;+ border-radius: 7px;+ cursor: pointer;+ color: var(--text-color);+ outline: none;+ user-select: none;+}++.multi-select-options li:hover,+.multi-select-options li:focus-visible {+ background-color: rgba(var(--main-color-rgb), 0.1);+}++.multi-select-check {+ flex: 0 0 18px;+ width: 18px;+ height: 18px;+ box-sizing: border-box;+ border: 1px solid var(--input-border-color);+ border-radius: 5px;+ background-color: var(--input-background-color);+ position: relative;+}++.multi-select-options li[aria-selected="true"] .multi-select-check {+ background-color: var(--main-color);+ border-color: var(--main-color);+}++.multi-select-options li[aria-selected="true"] .multi-select-check::after {+ content: "";+ position: absolute;+ left: 5px;+ top: 1px;+ width: 4px;+ height: 9px;+ border: solid var(--text-color-inverted);+ border-width: 0 2px 2px 0;+ transform: rotate(45deg);+}++.rtl .multi-select-toggle {+ text-align: right;+ padding: 0 15px 0 40px;+ background-position: left 15px center;+}+.date-wrapper {display: flex;flex-grow: 0;diff --git a/subscriptions.php b/subscriptions.phpindex 87ea31a..906c4a1 100644--- a/subscriptions.php+++ b/subscriptions.php@@ -1,599 +1,607 @@-<?php--require_once 'includes/header.php';-require_once 'includes/getdbkeys.php';-require_once 'includes/logo_theme_variant.php';--include_once 'includes/list_subscriptions.php';--$sort = "next_payment";-$sortOrder = $sort;--if ($settings['disabledToBottom'] === 'true') {- $sql = "SELECT * FROM subscriptions WHERE user_id = :userId ORDER BY inactive ASC, next_payment ASC";-} else {- $sql = "SELECT * FROM subscriptions WHERE user_id = :userId ORDER BY next_payment ASC, inactive ASC";-}--$params = array();--if (isset($_COOKIE['sortOrder']) && $_COOKIE['sortOrder'] != "") {- $sort = $_COOKIE['sortOrder'] ?? 'next_payment';-}--$sortOrder = $sort;-$allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric', 'renewal_type'];-$order = ($sort == "price" || $sort == "id") ? "DESC" : "ASC";--if ($sort == "alphanumeric") {- $sort = "name";-}--if (!in_array($sort, $allowedSortCriteria)) {- $sort = "next_payment";-}--if ($sort == "renewal_type") {- $sort = "auto_renew";-}--$sql = "SELECT * FROM subscriptions WHERE user_id = :userId";--if (isset($_GET['member'])) {- $memberIds = explode(',', $_GET['member']);- $placeholders = array_map(function ($key) {- return ":member{$key}";- }, array_keys($memberIds));-- $sql .= " AND payer_user_id IN (" . implode(',', $placeholders) . ")";-- foreach ($memberIds as $key => $memberId) {- $params[":member{$key}"] = $memberId;- }-}--if (isset($_GET['category'])) {- $categoryIds = explode(',', $_GET['category']);- $placeholders = array_map(function ($key) {- return ":category{$key}";- }, array_keys($categoryIds));-- $sql .= " AND category_id IN (" . implode(',', $placeholders) . ")";-- foreach ($categoryIds as $key => $categoryId) {- $params[":category{$key}"] = $categoryId;- }-}--if (isset($_GET['payment'])) {- $paymentIds = explode(',', $_GET['payment']);- $placeholders = array_map(function ($key) {- return ":payment{$key}";- }, array_keys($paymentIds));-- $sql .= " AND payment_method_id IN (" . implode(',', $placeholders) . ")";-- foreach ($paymentIds as $key => $paymentId) {- $params[":payment{$key}"] = $paymentId;- }-}--if (!isset($settings['hideDisabledSubscriptions']) || $settings['hideDisabledSubscriptions'] !== 'true') {- if (isset($_GET['state']) && $_GET['state'] != "") {- $sql .= " AND inactive = :inactive";- $params[':inactive'] = $_GET['state'];- }-}--$orderByClauses = [];--if ($settings['disabledToBottom'] === 'true') {- if (in_array($sort, ["payer_user_id", "category_id", "payment_method_id"])) {- $orderByClauses[] = "$sort $order";- $orderByClauses[] = "inactive ASC";- } else {- $orderByClauses[] = "inactive ASC";- $orderByClauses[] = "$sort $order";- }-} else {- $orderByClauses[] = "$sort $order";- if ($sort != "inactive") {- $orderByClauses[] = "inactive ASC";- }-}--if ($sort != "next_payment") {- $orderByClauses[] = "next_payment ASC";-}--$sql .= " ORDER BY " . implode(", ", $orderByClauses);--$stmt = $db->prepare($sql);-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);--if (!empty($params)) {- foreach ($params as $key => $value) {- $stmt->bindValue($key, $value, SQLITE3_INTEGER);- }-}--$result = $stmt->execute();-if ($result) {- $subscriptions = array();- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $subscriptions[] = $row;- }-}--foreach ($subscriptions as $subscription) {- $memberId = $subscription['payer_user_id'];- if (isset($members[$memberId ?? ""])) {- $members[$memberId ?? ""]['count']++;- }- $categoryId = $subscription['category_id'];- if (isset($categories[$categoryId ?? ""])) {- $categories[$categoryId ?? ""]['count']++;- }- $paymentMethodId = $subscription['payment_method_id'];- if (isset($payment_methods[$paymentMethodId ?? ""])) {- $payment_methods[$paymentMethodId ?? ""]['count']++;- }-}--if ($sortOrder == "category_id") {- usort($subscriptions, function ($a, $b) use ($categories) {- return ($categories[$a['category_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($categories[$b['category_id'] ?? ""]['order'] ?? PHP_INT_MAX);- });-}--if ($sortOrder == "payment_method_id") {- usort($subscriptions, function ($a, $b) use ($payment_methods) {- return ($payment_methods[$a['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($payment_methods[$b['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX);- });-}--$headerClass = count($subscriptions) > 0 ? "main-actions" : "main-actions hidden";--$subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscriptionsView'] === 'grid') ? 'grid' : 'list';-?>-<style>- .logo-preview:after {- content: '<?= translate('upload_logo', $i18n) ?>';- }-</style>--<section class="contain">- <header class="<?= $headerClass ?>" id="main-actions">- <button class="button" onClick="addSubscription()">- <i class="fa-solid fa-circle-plus"></i>- <?= translate('new_subscription', $i18n) ?>- </button>- <div class="top-actions">- <button class="button secondary-button mobile-search-toggle" id="mobile-search-toggle"- title="<?= translate('search', $i18n) ?>" onClick="toggleMobileSearch()">- <i class="fa-solid fa-magnifying-glass"></i>- </button>- <div class="search">- <input type="text" autocomplete="off" name="search" id="search" placeholder="<?= translate('search', $i18n) ?>"- onkeyup="searchSubscriptions()" />- <span class="fa-solid fa-magnifying-glass search-icon"></span>- <span class="fa-solid fa-xmark clear-search" onClick="clearSearch()"></span>- </div>-- <div class="filtermenu on-dashboard">- <button class="button secondary-button" id="filtermenu-button" title="<?= translate("filter", $i18n) ?>">- <i class="fa-solid fa-filter"></i>- </button>- <?php include 'includes/filters_menu.php'; ?>- </div>-- <div class="sort-container">- <button class="button secondary-button" value="Sort" onClick="toggleSortOptions()" id="sort-button"- title="<?= translate('sort', $i18n) ?>">- <i class="fa-solid fa-arrow-down-wide-short"></i>- </button>- <?php include 'includes/sort_options.php'; ?>- </div>-- <div class="view-toggle" id="view-toggle">- <button type="button" class="view-toggle-button<?= $subscriptionsView === 'list' ? ' selected' : '' ?>"- id="view-list-button" title="<?= translate('list_view', $i18n) ?>" onClick="setSubscriptionsView('list')">- <i class="fa-solid fa-list"></i>- </button>- <button type="button" class="view-toggle-button<?= $subscriptionsView === 'grid' ? ' selected' : '' ?>"- id="view-grid-button" title="<?= translate('grid_view', $i18n) ?>" onClick="setSubscriptionsView('grid')">- <i class="fa-solid fa-table-cells-large"></i>- </button>- </div>- </div>- </header>- <div class="subscriptions<?= $subscriptionsView === 'grid' ? ' grid-view' : '' ?>" id="subscriptions">- <?php- $formatter = new IntlDateFormatter(- 'en', // Force English locale- IntlDateFormatter::SHORT,- IntlDateFormatter::NONE,- null,- null,- 'MMM d, yyyy'- );-- $print = [];- foreach ($subscriptions as $subscription) {- if ($subscription['inactive'] == 1 && isset($settings['hideDisabledSubscriptions']) && $settings['hideDisabledSubscriptions'] === 'true') {- continue;- }- $id = $subscription['id'];- $print[$id]['id'] = $id;- $print[$id]['logo'] = $subscription['logo'] != "" ? "images/uploads/logos/" . $subscription['logo'] : "";- $print[$id]['logo_text_color'] = $subscription['logo_text_color'] ?? null;- $print[$id]['logo_variant'] = !empty($subscription['logo_variant']) ? "images/uploads/logos/" . $subscription['logo_variant'] : null;- $print[$id]['name'] = $subscription['name'];- $cycle = $subscription['cycle'];- $frequency = $subscription['frequency'];- $print[$id]['billing_cycle'] = getBillingCycle($cycle, $frequency, $i18n);- $print[$id]['one_time'] = ($cycle == 5);- $paymentMethodId = $subscription['payment_method_id'];- $print[$id]['currency_code'] = $currencies[$subscription['currency_id']]['code'];- $currencyId = $subscription['currency_id'];- $print[$id]['auto_renew'] = $subscription['auto_renew'];- $next_payment_timestamp = strtotime($subscription['next_payment']);- $formatted_date = $formatter->format($next_payment_timestamp);- $print[$id]['next_payment'] = $formatted_date;- $paymentIcon = $payment_methods[$paymentMethodId ?? ""]['icon'] ?? "";- $paymentIconFolder = (strpos($paymentIcon, 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";- $print[$id]['payment_method_icon'] = $paymentIcon === "" ? "" : $paymentIconFolder . $paymentIcon;- $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId ?? ""]['name'] ?? "";- $print[$id]['payment_method_id'] = $paymentMethodId;- $print[$id]['category_id'] = $subscription['category_id'];- $print[$id]['payer_user_id'] = $subscription['payer_user_id'];- $print[$id]['price'] = floatval($subscription['price']);- $print[$id]['sort_price'] = getSortPrice($subscription['price'], $subscription['currency_id'], $mainCurrencyId, $cycle, $frequency, $settings, $db);- $print[$id]['progress'] = getSubscriptionProgress($cycle, $frequency, $subscription['next_payment']);- $print[$id]['inactive'] = $subscription['inactive'];- $print[$id]['url'] = $subscription['url'];- $print[$id]['notes'] = $subscription['notes'];- $print[$id]['replacement_subscription_id'] = $subscription['replacement_subscription_id'];-- if (isset($settings['convertCurrency']) && $settings['convertCurrency'] === 'true' && $currencyId != $mainCurrencyId) {- $print[$id]['price'] = getPriceConverted($print[$id]['price'], $currencyId, $db);- $print[$id]['currency_code'] = $currencies[$mainCurrencyId]['code'];- }- if (isset($settings['showMonthlyPrice']) && $settings['showMonthlyPrice'] === 'true') {- $print[$id]['price'] = getPricePerMonth($cycle, $frequency, $print[$id]['price']);- }- if (isset($settings['showOriginalPrice']) && $settings['showOriginalPrice'] === 'true') {- $print[$id]['original_price'] = floatval($subscription['price']);- $print[$id]['original_currency_code'] = $currencies[$subscription['currency_id']]['code'];- }- }-- if ($sortOrder == "alphanumeric") {- usort($print, function ($a, $b) {- return strnatcmp(strtolower($a['name']), strtolower($b['name']));- });- if ($settings['disabledToBottom'] === 'true') {- usort($print, function ($a, $b) {- return $a['inactive'] - $b['inactive'];- });- }- }-- if (isset($print)) {- printSubscriptions($print, $sort, $categories, $members, $i18n, $colorTheme, "", $settings['disabledToBottom'], $settings['mobileNavigation'], $settings['showSubscriptionProgress'], $currencies, $lang);- }-- $googleSearchEnabled = false;- if ($db->querySingle("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='google_search'") > 0) {- $googleSearchStmt = $db->prepare("SELECT COUNT(*) AS count FROM google_search WHERE user_id = :userId AND api_key != ''");- $googleSearchStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);- $googleSearchResult = $googleSearchStmt->execute();- if ($googleSearchResult) {- $googleSearchRow = $googleSearchResult->fetchArray(SQLITE3_ASSOC);- $googleSearchEnabled = $googleSearchRow && $googleSearchRow['count'] > 0;- }- }-- $db->close();-- if (count($subscriptions) == 0) {- ?>- <div class="empty-page">- <img src="images/siteimages/empty.png" alt="<?= translate('empty_page', $i18n) ?>" />- <p>- <?= translate('no_subscriptions_yet', $i18n) ?>- </p>- <button class="button" onClick="addSubscription()">- <i class="fa-solid fa-circle-plus"></i>- <?= translate('add_first_subscription', $i18n) ?>- </button>- </div>- <?php- }- ?>- </div>-</section>-<section class="subscription-form" id="subscription-form">- <header>- <h3 id="form-title"><?= translate('add_subscription', $i18n) ?></h3>- <span class="fa-solid fa-xmark close-form" onClick="closeAddSubscription()"></span>- </header>- <form action="endpoints/subscription/add.php" method="post" id="subs-form">-- <div class="form-group-inline">- <input type="text" id="name" name="name" autocomplete="off"- placeholder="<?= translate('subscription_name', $i18n) ?>"- onchange="setSearchButtonStatus()" onkeypress="this.onchange();" onpaste="this.onchange();"- oninput="this.onchange();" required>- <label for="logo" class="logo-preview">- <img src="" alt="<?= translate('logo_preview', $i18n) ?>" id="form-logo">- </label>- <input type="file" id="logo" name="logo" accept="image/jpeg, image/png, image/gif, image/webp, image/svg+xml"- onchange="handleFileSelect(event)" class="hidden-input">- <input type="hidden" id="logo-url" name="logo-url">- <div id="logo-search-button" class="image-button medium disabled" title="<?= translate('search_logo', $i18n) ?>"- onClick="searchLogo()">- <i class="fa-solid fa-magnifying-glass"></i>- </div>- <input type="hidden" id="id" name="id">- <div class="logo-search-backdrop" id="logo-search-backdrop" onClick="closeLogoSearch()"></div>- <div id="logo-search-results" class="logo-search"<?= !empty($googleSearchEnabled) ? ' data-google-search="1"' : '' ?>>- <button type="button" class="close-logo-search" onClick="closeLogoSearch()" title="<?= translate('cancel', $i18n) ?>">- <i class="fa-solid fa-xmark"></i>- </button>- <header>- <h3 id="logo-search-title" data-title="<?= translate('web_search', $i18n) ?>">- <?= translate('web_search', $i18n) ?>- </h3>- </header>- <div class="logo-search-controls">- <div class="logo-search-query">- <input type="text" id="logo-search-query" autocomplete="off" inputmode="search"- placeholder="<?= translate('search_logo', $i18n) ?>"- aria-label="<?= translate('search_logo', $i18n) ?>">- <button type="button" id="logo-search-submit" title="<?= translate('search', $i18n) ?>">- <i class="fa-solid fa-magnifying-glass"></i>- </button>- </div>- <div id="logo-search-nav" class="logo-search-nav"></div>- </div>- <div id="logo-search-images"></div>- </div>- </div>-- <div class="form-group-inline">- <input type="number" step="0.01" id="price" name="price" autocomplete="off"- placeholder="<?= translate('price', $i18n) ?>" required>- <select id="currency" name="currency_id" placeholder="<?= translate('add_subscription', $i18n) ?>">- <?php- foreach ($currencies as $currency) {- $selected = ($currency['id'] == $main_currency) ? 'selected' : '';- ?>- <option value="<?= $currency['id'] ?>" <?= $selected ?>><?= $currency['name'] ?></option>- <?php- }- ?>- </select>- </div>-- <div class="form-group">- <div class="inline">- <div class="split66">- <label for="cycle"><?= translate('payment_every', $i18n) ?></label>- <div class="inline">- <select id="frequency" name="frequency" placeholder="<?= translate('frequency', $i18n) ?>">- <?php- for ($i = 1; $i <= 366; $i++) {- ?>- <option value="<?= $i ?>"><?= $i ?></option>- <?php- }- ?>- </select>- <select id="cycle" name="cycle" placeholder="Cycle">- <?php- foreach ($cycles as $cycle) {- ?>- <option value="<?= $cycle['id'] ?>" <?= $cycle['id'] == 3 ? "selected" : "" ?>>- <?= translate(strtolower($cycle['name']), $i18n) ?>- </option>- <?php- }- ?>- </select>- </div>- </div>- <div class="split33" id="auto-renew-group">- <label><?= translate('auto_renewal', $i18n) ?></label>- <div class="inline height50">- <input type="checkbox" id="auto_renew" name="auto_renew" checked>- <label for="auto_renew"><?= translate('automatically_renews', $i18n) ?></label>- </div>- </div>- </div>- </div>-- <div class="form-group">- <div class="inline">- <div class="split50">- <label for="start_date"><?= translate('start_date', $i18n) ?></label>- <div class="date-wrapper">- <input type="date" id="start_date" name="start_date" autocomplete="off">- </div>- </div>- <button type="button" id="autofill-next-payment-button"- class="button secondary-button autofill-next-payment hideOnMobile"- title="<?= translate('calculate_next_payment_date', $i18n) ?>" onClick="autoFillNextPaymentDate(event)">- <i class="fa-solid fa-wand-magic-sparkles"></i>- </button>- <div class="split50">- <label for="next_payment" class="split-label">- <span id="next-payment-label-recurring"><?= translate('next_payment', $i18n) ?></span>- <span id="next-payment-label-onetime" style="display:none"><?= translate('payment_date', $i18n) ?></span>- <div id="autofill-next-payment-button" class="autofill-next-payment hideOnDesktop"- title="<?= translate('calculate_next_payment_date', $i18n) ?>" onClick="autoFillNextPaymentDate(event)">- <i class="fa-solid fa-wand-magic-sparkles"></i>- </div>- </label>- <div class="date-wrapper">- <input type="date" id="next_payment" name="next_payment" autocomplete="off" required>- </div>- </div>- </div>- </div>-- <div class="form-group">- <div class="inline">- <div class="split50">- <label for="payment_method"><?= translate('payment_method', $i18n) ?></label>- <select id="payment_method" name="payment_method_id">- <?php- foreach ($payment_methods as $payment) {- ?>- <option value="<?= $payment['id'] ?>">- <?= $payment['name'] ?>- </option>- <?php- }- ?>- </select>- </div>- <div class="split50">- <label for="payer_user"><?= translate('paid_by', $i18n) ?></label>- <select id="payer_user" name="payer_user_id">- <?php- foreach ($members as $member) {- ?>- <option value="<?= $member['id'] ?>"><?= $member['name'] ?></option>- <?php- }- ?>- </select>- </div>- </div>- </div>-- <div class="form-group">- <label for="category"><?= translate('category', $i18n) ?></label>- <select id="category" name="category_id">- <?php- foreach ($categories as $category) {- ?>- <option value="<?= $category['id'] ?>">- <?= $category['name'] ?>- </option>- <?php- }- ?>- </select>- </div>-- <div class="form-group-inline grow" id="notifications-group">- <input type="checkbox" id="notifications" name="notifications" onchange="toggleNotificationDays()">- <label for="notifications" class="grow"><?= translate('enable_notifications', $i18n) ?></label>- </div>-- <div class="form-group" id="notify-days-cancellation-group">- <div class="inline">- <div class="split66 mobile-split-50">- <label for="notify_days_before"><?= translate('notify_me', $i18n) ?></label>- <select id="notify_days_before" name="notify_days_before" disabled>- <option value="-1"><?= translate('default_value_from_settings', $i18n) ?></option>- <option value="0"><?= translate('on_due_date', $i18n) ?></option>- <option value="1">1 <?= translate('day_before', $i18n) ?></option>- <?php- for ($i = 2; $i <= 180; $i++) {- ?>- <option value="<?= $i ?>"><?= $i ?> <?= translate('days_before', $i18n) ?></option>- <?php- }- ?>- </select>- </div>- <div class="split33 mobile-split-50">- <label for="cancellation_date"><?= translate('cancellation_notification', $i18n) ?></label>- <div class="date-wrapper">- <input type="date" id="cancellation_date" name="cancellation_date" autocomplete="off">- </div>- </div>- </div>- </div>-- <div class="form-group">- <input type="text" id="url" name="url" autocomplete="off" placeholder="<?= translate('url', $i18n) ?>">- </div>-- <div class="form-group">- <div class="notes-editor">- <div class="notes-toolbar">- <button type="button" class="notes-toolbar-button" title="<?= translate('notes_bold', $i18n) ?>" onClick="applyNotesMarkdown('bold')">- <i class="fa-solid fa-bold"></i>- </button>- <button type="button" class="notes-toolbar-button" title="<?= translate('notes_italic', $i18n) ?>" onClick="applyNotesMarkdown('italic')">- <i class="fa-solid fa-italic"></i>- </button>- <button type="button" class="notes-toolbar-button" title="<?= translate('notes_list', $i18n) ?>" onClick="applyNotesMarkdown('list')">- <i class="fa-solid fa-list-ul"></i>- </button>- <button type="button" class="notes-toolbar-button" title="<?= translate('notes_link', $i18n) ?>" onClick="applyNotesMarkdown('link')">- <i class="fa-solid fa-link"></i>- </button>- </div>- <textarea id="notes" name="notes" class="thin" autocomplete="off" placeholder="<?= translate('notes', $i18n) ?>"></textarea>- </div>- </div>-- <div class="form-group">- <div class="inline grow">- <input type="checkbox" id="inactive" name="inactive" onchange="toggleReplacementSub()">- <label for="inactive" class="grow"><?= translate('inactive', $i18n) ?></label>- </div>- </div>-- <?php- $orderedSubscriptions = $subscriptions;- usort($orderedSubscriptions, function ($a, $b) {- return strnatcmp(strtolower($a['name']), strtolower($b['name']));- });- ?>-- <div class="form-group hide" id="replacement_subscritpion">- <label for="replacement_subscription_id"><?= translate('replaced_with', $i18n) ?>:</label>- <select id="replacement_subscription_id" name="replacement_subscription_id">- <option value="0"><?= translate('none', $i18n) ?></option>- <?php- foreach ($orderedSubscriptions as $sub) {- if ($sub['inactive'] == 0) {- ?>- <option value="<?= htmlspecialchars($sub['id']) ?>"><?= htmlspecialchars($sub['name']) ?>- </option>- <?php- }- }- ?>- </select>- </div>-- <div class="buttons">- <input type="button" value="<?= translate('delete', $i18n) ?>" class="warning-button left thin" id="deletesub"- style="display: none">- <input type="button" value="<?= translate('cancel', $i18n) ?>" class="secondary-button thin"- onClick="closeAddSubscription()">- <input type="submit" value="<?= translate('save', $i18n) ?>" class="thin" id="save-button">- </div>- </form>-</section>--<?php require_once 'includes/subscription_details_popup.php'; ?>-<script src="scripts/subscriptions.js?<?= $version ?>"></script>-<?php-if (isset($_GET['add'])) {- ?>- <script>- addSubscription();- </script>- <?php-}--require_once 'includes/footer.php';-?>+<?php++require_once 'includes/header.php';+require_once 'includes/getdbkeys.php';+require_once 'includes/logo_theme_variant.php';++include_once 'includes/list_subscriptions.php';+require_once 'includes/subscription_payers.php';++$sort = "next_payment";+$sortOrder = $sort;++if ($settings['disabledToBottom'] === 'true') {+ $sql = "SELECT * FROM subscriptions WHERE user_id = :userId ORDER BY inactive ASC, next_payment ASC";+} else {+ $sql = "SELECT * FROM subscriptions WHERE user_id = :userId ORDER BY next_payment ASC, inactive ASC";+}++$params = array();++if (isset($_COOKIE['sortOrder']) && $_COOKIE['sortOrder'] != "") {+ $sort = $_COOKIE['sortOrder'] ?? 'next_payment';+}++$sortOrder = $sort;+$allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric', 'renewal_type'];+$order = ($sort == "price" || $sort == "id") ? "DESC" : "ASC";++if ($sort == "alphanumeric") {+ $sort = "name";+}++if (!in_array($sort, $allowedSortCriteria)) {+ $sort = "next_payment";+}++if ($sort == "renewal_type") {+ $sort = "auto_renew";+}++$sql = "SELECT * FROM subscriptions WHERE user_id = :userId";++if (isset($_GET['member'])) {+ $memberIds = explode(',', $_GET['member']);+ $sql .= " AND " . payerFilterCondition($memberIds, $params);+}++if (isset($_GET['category'])) {+ $categoryIds = explode(',', $_GET['category']);+ $placeholders = array_map(function ($key) {+ return ":category{$key}";+ }, array_keys($categoryIds));++ $sql .= " AND category_id IN (" . implode(',', $placeholders) . ")";++ foreach ($categoryIds as $key => $categoryId) {+ $params[":category{$key}"] = $categoryId;+ }+}++if (isset($_GET['payment'])) {+ $paymentIds = explode(',', $_GET['payment']);+ $placeholders = array_map(function ($key) {+ return ":payment{$key}";+ }, array_keys($paymentIds));++ $sql .= " AND payment_method_id IN (" . implode(',', $placeholders) . ")";++ foreach ($paymentIds as $key => $paymentId) {+ $params[":payment{$key}"] = $paymentId;+ }+}++if (!isset($settings['hideDisabledSubscriptions']) || $settings['hideDisabledSubscriptions'] !== 'true') {+ if (isset($_GET['state']) && $_GET['state'] != "") {+ $sql .= " AND inactive = :inactive";+ $params[':inactive'] = $_GET['state'];+ }+}++$orderByClauses = [];++if ($settings['disabledToBottom'] === 'true') {+ if (in_array($sort, ["payer_user_id", "category_id", "payment_method_id"])) {+ $orderByClauses[] = "$sort $order";+ $orderByClauses[] = "inactive ASC";+ } else {+ $orderByClauses[] = "inactive ASC";+ $orderByClauses[] = "$sort $order";+ }+} else {+ $orderByClauses[] = "$sort $order";+ if ($sort != "inactive") {+ $orderByClauses[] = "inactive ASC";+ }+}++if ($sort != "next_payment") {+ $orderByClauses[] = "next_payment ASC";+}++$sql .= " ORDER BY " . implode(", ", $orderByClauses);++$stmt = $db->prepare($sql);+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);++if (!empty($params)) {+ foreach ($params as $key => $value) {+ $stmt->bindValue($key, $value, SQLITE3_INTEGER);+ }+}++$result = $stmt->execute();+if ($result) {+ $subscriptions = array();+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $subscriptions[] = $row;+ }+}++$payersBySubscription = getPayersBySubscription($db, $subscriptions);++foreach ($subscriptions as $subscription) {+ foreach ($payersBySubscription[$subscription['id']] ?? [] as $memberId) {+ if (isset($members[$memberId])) {+ $members[$memberId]['count']++;+ }+ }+ $categoryId = $subscription['category_id'];+ if (isset($categories[$categoryId ?? ""])) {+ $categories[$categoryId ?? ""]['count']++;+ }+ $paymentMethodId = $subscription['payment_method_id'];+ if (isset($payment_methods[$paymentMethodId ?? ""])) {+ $payment_methods[$paymentMethodId ?? ""]['count']++;+ }+}++if ($sortOrder == "category_id") {+ usort($subscriptions, function ($a, $b) use ($categories) {+ return ($categories[$a['category_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($categories[$b['category_id'] ?? ""]['order'] ?? PHP_INT_MAX);+ });+}++if ($sortOrder == "payment_method_id") {+ usort($subscriptions, function ($a, $b) use ($payment_methods) {+ return ($payment_methods[$a['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($payment_methods[$b['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX);+ });+}++$headerClass = count($subscriptions) > 0 ? "main-actions" : "main-actions hidden";++$subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscriptionsView'] === 'grid') ? 'grid' : 'list';+?>+<style>+ .logo-preview:after {+ content: '<?= translate('upload_logo', $i18n) ?>';+ }+</style>++<section class="contain">+ <header class="<?= $headerClass ?>" id="main-actions">+ <button class="button" onClick="addSubscription()">+ <i class="fa-solid fa-circle-plus"></i>+ <?= translate('new_subscription', $i18n) ?>+ </button>+ <div class="top-actions">+ <button class="button secondary-button mobile-search-toggle" id="mobile-search-toggle"+ title="<?= translate('search', $i18n) ?>" onClick="toggleMobileSearch()">+ <i class="fa-solid fa-magnifying-glass"></i>+ </button>+ <div class="search">+ <input type="text" autocomplete="off" name="search" id="search" placeholder="<?= translate('search', $i18n) ?>"+ onkeyup="searchSubscriptions()" />+ <span class="fa-solid fa-magnifying-glass search-icon"></span>+ <span class="fa-solid fa-xmark clear-search" onClick="clearSearch()"></span>+ </div>++ <div class="filtermenu on-dashboard">+ <button class="button secondary-button" id="filtermenu-button" title="<?= translate("filter", $i18n) ?>">+ <i class="fa-solid fa-filter"></i>+ </button>+ <?php include 'includes/filters_menu.php'; ?>+ </div>++ <div class="sort-container">+ <button class="button secondary-button" value="Sort" onClick="toggleSortOptions()" id="sort-button"+ title="<?= translate('sort', $i18n) ?>">+ <i class="fa-solid fa-arrow-down-wide-short"></i>+ </button>+ <?php include 'includes/sort_options.php'; ?>+ </div>++ <div class="view-toggle" id="view-toggle">+ <button type="button" class="view-toggle-button<?= $subscriptionsView === 'list' ? ' selected' : '' ?>"+ id="view-list-button" title="<?= translate('list_view', $i18n) ?>" onClick="setSubscriptionsView('list')">+ <i class="fa-solid fa-list"></i>+ </button>+ <button type="button" class="view-toggle-button<?= $subscriptionsView === 'grid' ? ' selected' : '' ?>"+ id="view-grid-button" title="<?= translate('grid_view', $i18n) ?>" onClick="setSubscriptionsView('grid')">+ <i class="fa-solid fa-table-cells-large"></i>+ </button>+ </div>+ </div>+ </header>+ <div class="subscriptions<?= $subscriptionsView === 'grid' ? ' grid-view' : '' ?>" id="subscriptions">+ <?php+ $formatter = new IntlDateFormatter(+ 'en', // Force English locale+ IntlDateFormatter::SHORT,+ IntlDateFormatter::NONE,+ null,+ null,+ 'MMM d, yyyy'+ );++ $print = [];+ foreach ($subscriptions as $subscription) {+ if ($subscription['inactive'] == 1 && isset($settings['hideDisabledSubscriptions']) && $settings['hideDisabledSubscriptions'] === 'true') {+ continue;+ }+ $id = $subscription['id'];+ $print[$id]['id'] = $id;+ $print[$id]['logo'] = $subscription['logo'] != "" ? "images/uploads/logos/" . $subscription['logo'] : "";+ $print[$id]['logo_text_color'] = $subscription['logo_text_color'] ?? null;+ $print[$id]['logo_variant'] = !empty($subscription['logo_variant']) ? "images/uploads/logos/" . $subscription['logo_variant'] : null;+ $print[$id]['name'] = $subscription['name'];+ $cycle = $subscription['cycle'];+ $frequency = $subscription['frequency'];+ $print[$id]['billing_cycle'] = getBillingCycle($cycle, $frequency, $i18n);+ $print[$id]['one_time'] = ($cycle == 5);+ $paymentMethodId = $subscription['payment_method_id'];+ $print[$id]['currency_code'] = $currencies[$subscription['currency_id']]['code'];+ $currencyId = $subscription['currency_id'];+ $print[$id]['auto_renew'] = $subscription['auto_renew'];+ $next_payment_timestamp = strtotime($subscription['next_payment']);+ $formatted_date = $formatter->format($next_payment_timestamp);+ $print[$id]['next_payment'] = $formatted_date;+ $paymentIcon = $payment_methods[$paymentMethodId ?? ""]['icon'] ?? "";+ $paymentIconFolder = (strpos($paymentIcon, 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";+ $print[$id]['payment_method_icon'] = $paymentIcon === "" ? "" : $paymentIconFolder . $paymentIcon;+ $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId ?? ""]['name'] ?? "";+ $print[$id]['payment_method_id'] = $paymentMethodId;+ $print[$id]['category_id'] = $subscription['category_id'];+ $print[$id]['payer_user_id'] = $subscription['payer_user_id'];+ $print[$id]['payer_user_ids'] = $payersBySubscription[$id] ?? [];+ $print[$id]['price'] = floatval($subscription['price']);+ $print[$id]['sort_price'] = getSortPrice($subscription['price'], $subscription['currency_id'], $mainCurrencyId, $cycle, $frequency, $settings, $db);+ $print[$id]['progress'] = getSubscriptionProgress($cycle, $frequency, $subscription['next_payment']);+ $print[$id]['inactive'] = $subscription['inactive'];+ $print[$id]['url'] = $subscription['url'];+ $print[$id]['notes'] = $subscription['notes'];+ $print[$id]['replacement_subscription_id'] = $subscription['replacement_subscription_id'];++ if (isset($settings['convertCurrency']) && $settings['convertCurrency'] === 'true' && $currencyId != $mainCurrencyId) {+ $print[$id]['price'] = getPriceConverted($print[$id]['price'], $currencyId, $db);+ $print[$id]['currency_code'] = $currencies[$mainCurrencyId]['code'];+ }+ if (isset($settings['showMonthlyPrice']) && $settings['showMonthlyPrice'] === 'true') {+ $print[$id]['price'] = getPricePerMonth($cycle, $frequency, $print[$id]['price']);+ }+ if (isset($settings['showOriginalPrice']) && $settings['showOriginalPrice'] === 'true') {+ $print[$id]['original_price'] = floatval($subscription['price']);+ $print[$id]['original_currency_code'] = $currencies[$subscription['currency_id']]['code'];+ }+ }++ if ($sortOrder == "alphanumeric") {+ usort($print, function ($a, $b) {+ return strnatcmp(strtolower($a['name']), strtolower($b['name']));+ });+ if ($settings['disabledToBottom'] === 'true') {+ usort($print, function ($a, $b) {+ return $a['inactive'] - $b['inactive'];+ });+ }+ }++ if (isset($print)) {+ printSubscriptions($print, $sort, $categories, $members, $i18n, $colorTheme, "", $settings['disabledToBottom'], $settings['mobileNavigation'], $settings['showSubscriptionProgress'], $currencies, $lang);+ }++ $googleSearchEnabled = false;+ if ($db->querySingle("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='google_search'") > 0) {+ $googleSearchStmt = $db->prepare("SELECT COUNT(*) AS count FROM google_search WHERE user_id = :userId AND api_key != ''");+ $googleSearchStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $googleSearchResult = $googleSearchStmt->execute();+ if ($googleSearchResult) {+ $googleSearchRow = $googleSearchResult->fetchArray(SQLITE3_ASSOC);+ $googleSearchEnabled = $googleSearchRow && $googleSearchRow['count'] > 0;+ }+ }++ $db->close();++ if (count($subscriptions) == 0) {+ ?>+ <div class="empty-page">+ <img src="images/siteimages/empty.png" alt="<?= translate('empty_page', $i18n) ?>" />+ <p>+ <?= translate('no_subscriptions_yet', $i18n) ?>+ </p>+ <button class="button" onClick="addSubscription()">+ <i class="fa-solid fa-circle-plus"></i>+ <?= translate('add_first_subscription', $i18n) ?>+ </button>+ </div>+ <?php+ }+ ?>+ </div>+</section>+<section class="subscription-form" id="subscription-form">+ <header>+ <h3 id="form-title"><?= translate('add_subscription', $i18n) ?></h3>+ <span class="fa-solid fa-xmark close-form" onClick="closeAddSubscription()"></span>+ </header>+ <form action="endpoints/subscription/add.php" method="post" id="subs-form">++ <div class="form-group-inline">+ <input type="text" id="name" name="name" autocomplete="off"+ placeholder="<?= translate('subscription_name', $i18n) ?>"+ onchange="setSearchButtonStatus()" onkeypress="this.onchange();" onpaste="this.onchange();"+ oninput="this.onchange();" required>+ <label for="logo" class="logo-preview">+ <img src="" alt="<?= translate('logo_preview', $i18n) ?>" id="form-logo">+ </label>+ <input type="file" id="logo" name="logo" accept="image/jpeg, image/png, image/gif, image/webp, image/svg+xml"+ onchange="handleFileSelect(event)" class="hidden-input">+ <input type="hidden" id="logo-url" name="logo-url">+ <div id="logo-search-button" class="image-button medium disabled" title="<?= translate('search_logo', $i18n) ?>"+ onClick="searchLogo()">+ <i class="fa-solid fa-magnifying-glass"></i>+ </div>+ <input type="hidden" id="id" name="id">+ <div class="logo-search-backdrop" id="logo-search-backdrop" onClick="closeLogoSearch()"></div>+ <div id="logo-search-results" class="logo-search"<?= !empty($googleSearchEnabled) ? ' data-google-search="1"' : '' ?>>+ <button type="button" class="close-logo-search" onClick="closeLogoSearch()" title="<?= translate('cancel', $i18n) ?>">+ <i class="fa-solid fa-xmark"></i>+ </button>+ <header>+ <h3 id="logo-search-title" data-title="<?= translate('web_search', $i18n) ?>">+ <?= translate('web_search', $i18n) ?>+ </h3>+ </header>+ <div class="logo-search-controls">+ <div class="logo-search-query">+ <input type="text" id="logo-search-query" autocomplete="off" inputmode="search"+ placeholder="<?= translate('search_logo', $i18n) ?>"+ aria-label="<?= translate('search_logo', $i18n) ?>">+ <button type="button" id="logo-search-submit" title="<?= translate('search', $i18n) ?>">+ <i class="fa-solid fa-magnifying-glass"></i>+ </button>+ </div>+ <div id="logo-search-nav" class="logo-search-nav"></div>+ </div>+ <div id="logo-search-images"></div>+ </div>+ </div>++ <div class="form-group-inline">+ <input type="number" step="0.01" id="price" name="price" autocomplete="off"+ placeholder="<?= translate('price', $i18n) ?>" required>+ <select id="currency" name="currency_id" placeholder="<?= translate('add_subscription', $i18n) ?>">+ <?php+ foreach ($currencies as $currency) {+ $selected = ($currency['id'] == $main_currency) ? 'selected' : '';+ ?>+ <option value="<?= $currency['id'] ?>" <?= $selected ?>><?= $currency['name'] ?></option>+ <?php+ }+ ?>+ </select>+ </div>++ <div class="form-group">+ <div class="inline">+ <div class="split66">+ <label for="cycle"><?= translate('payment_every', $i18n) ?></label>+ <div class="inline">+ <select id="frequency" name="frequency" placeholder="<?= translate('frequency', $i18n) ?>">+ <?php+ for ($i = 1; $i <= 366; $i++) {+ ?>+ <option value="<?= $i ?>"><?= $i ?></option>+ <?php+ }+ ?>+ </select>+ <select id="cycle" name="cycle" placeholder="Cycle">+ <?php+ foreach ($cycles as $cycle) {+ ?>+ <option value="<?= $cycle['id'] ?>" <?= $cycle['id'] == 3 ? "selected" : "" ?>>+ <?= translate(strtolower($cycle['name']), $i18n) ?>+ </option>+ <?php+ }+ ?>+ </select>+ </div>+ </div>+ <div class="split33" id="auto-renew-group">+ <label><?= translate('auto_renewal', $i18n) ?></label>+ <div class="inline height50">+ <input type="checkbox" id="auto_renew" name="auto_renew" checked>+ <label for="auto_renew"><?= translate('automatically_renews', $i18n) ?></label>+ </div>+ </div>+ </div>+ </div>++ <div class="form-group">+ <div class="inline">+ <div class="split50">+ <label for="start_date"><?= translate('start_date', $i18n) ?></label>+ <div class="date-wrapper">+ <input type="date" id="start_date" name="start_date" autocomplete="off">+ </div>+ </div>+ <button type="button" id="autofill-next-payment-button"+ class="button secondary-button autofill-next-payment hideOnMobile"+ title="<?= translate('calculate_next_payment_date', $i18n) ?>" onClick="autoFillNextPaymentDate(event)">+ <i class="fa-solid fa-wand-magic-sparkles"></i>+ </button>+ <div class="split50">+ <label for="next_payment" class="split-label">+ <span id="next-payment-label-recurring"><?= translate('next_payment', $i18n) ?></span>+ <span id="next-payment-label-onetime" style="display:none"><?= translate('payment_date', $i18n) ?></span>+ <div id="autofill-next-payment-button" class="autofill-next-payment hideOnDesktop"+ title="<?= translate('calculate_next_payment_date', $i18n) ?>" onClick="autoFillNextPaymentDate(event)">+ <i class="fa-solid fa-wand-magic-sparkles"></i>+ </div>+ </label>+ <div class="date-wrapper">+ <input type="date" id="next_payment" name="next_payment" autocomplete="off" required>+ </div>+ </div>+ </div>+ </div>++ <div class="form-group">+ <div class="inline">+ <div class="split50">+ <label for="payment_method"><?= translate('payment_method', $i18n) ?></label>+ <select id="payment_method" name="payment_method_id">+ <?php+ foreach ($payment_methods as $payment) {+ ?>+ <option value="<?= $payment['id'] ?>">+ <?= $payment['name'] ?>+ </option>+ <?php+ }+ ?>+ </select>+ </div>+ <div class="split50">+ <label for="payer_user_toggle"><?= translate('paid_by', $i18n) ?></label>+ <div class="multi-select" id="payer_user_select" data-placeholder="<?= translate('none', $i18n) ?>">+ <button type="button" class="multi-select-toggle" id="payer_user_toggle" aria-haspopup="listbox"+ aria-expanded="false" aria-controls="payer_user_options">+ <span class="multi-select-label"></span>+ </button>+ <ul class="multi-select-options" id="payer_user_options" role="listbox" aria-multiselectable="true"+ aria-labelledby="payer_user_toggle" tabindex="-1" hidden>+ <?php+ foreach ($members as $member) {+ ?>+ <li role="option" aria-selected="false" data-value="<?= $member['id'] ?>">+ <span class="multi-select-check"></span>+ <span class="multi-select-name"><?= $member['name'] ?></span>+ </li>+ <?php+ }+ ?>+ </ul>+ <input type="hidden" name="payer_user_id" id="payer_user" value="">+ </div>+ </div>+ </div>+ </div>++ <div class="form-group">+ <label for="category"><?= translate('category', $i18n) ?></label>+ <select id="category" name="category_id">+ <?php+ foreach ($categories as $category) {+ ?>+ <option value="<?= $category['id'] ?>">+ <?= $category['name'] ?>+ </option>+ <?php+ }+ ?>+ </select>+ </div>++ <div class="form-group-inline grow" id="notifications-group">+ <input type="checkbox" id="notifications" name="notifications" onchange="toggleNotificationDays()">+ <label for="notifications" class="grow"><?= translate('enable_notifications', $i18n) ?></label>+ </div>++ <div class="form-group" id="notify-days-cancellation-group">+ <div class="inline">+ <div class="split66 mobile-split-50">+ <label for="notify_days_before"><?= translate('notify_me', $i18n) ?></label>+ <select id="notify_days_before" name="notify_days_before" disabled>+ <option value="-1"><?= translate('default_value_from_settings', $i18n) ?></option>+ <option value="0"><?= translate('on_due_date', $i18n) ?></option>+ <option value="1">1 <?= translate('day_before', $i18n) ?></option>+ <?php+ for ($i = 2; $i <= 180; $i++) {+ ?>+ <option value="<?= $i ?>"><?= $i ?> <?= translate('days_before', $i18n) ?></option>+ <?php+ }+ ?>+ </select>+ </div>+ <div class="split33 mobile-split-50">+ <label for="cancellation_date"><?= translate('cancellation_notification', $i18n) ?></label>+ <div class="date-wrapper">+ <input type="date" id="cancellation_date" name="cancellation_date" autocomplete="off">+ </div>+ </div>+ </div>+ </div>++ <div class="form-group">+ <input type="text" id="url" name="url" autocomplete="off" placeholder="<?= translate('url', $i18n) ?>">+ </div>++ <div class="form-group">+ <div class="notes-editor">+ <div class="notes-toolbar">+ <button type="button" class="notes-toolbar-button" title="<?= translate('notes_bold', $i18n) ?>" onClick="applyNotesMarkdown('bold')">+ <i class="fa-solid fa-bold"></i>+ </button>+ <button type="button" class="notes-toolbar-button" title="<?= translate('notes_italic', $i18n) ?>" onClick="applyNotesMarkdown('italic')">+ <i class="fa-solid fa-italic"></i>+ </button>+ <button type="button" class="notes-toolbar-button" title="<?= translate('notes_list', $i18n) ?>" onClick="applyNotesMarkdown('list')">+ <i class="fa-solid fa-list-ul"></i>+ </button>+ <button type="button" class="notes-toolbar-button" title="<?= translate('notes_link', $i18n) ?>" onClick="applyNotesMarkdown('link')">+ <i class="fa-solid fa-link"></i>+ </button>+ </div>+ <textarea id="notes" name="notes" class="thin" autocomplete="off" placeholder="<?= translate('notes', $i18n) ?>"></textarea>+ </div>+ </div>++ <div class="form-group">+ <div class="inline grow">+ <input type="checkbox" id="inactive" name="inactive" onchange="toggleReplacementSub()">+ <label for="inactive" class="grow"><?= translate('inactive', $i18n) ?></label>+ </div>+ </div>++ <?php+ $orderedSubscriptions = $subscriptions;+ usort($orderedSubscriptions, function ($a, $b) {+ return strnatcmp(strtolower($a['name']), strtolower($b['name']));+ });+ ?>++ <div class="form-group hide" id="replacement_subscritpion">+ <label for="replacement_subscription_id"><?= translate('replaced_with', $i18n) ?>:</label>+ <select id="replacement_subscription_id" name="replacement_subscription_id">+ <option value="0"><?= translate('none', $i18n) ?></option>+ <?php+ foreach ($orderedSubscriptions as $sub) {+ if ($sub['inactive'] == 0) {+ ?>+ <option value="<?= htmlspecialchars($sub['id']) ?>"><?= htmlspecialchars($sub['name']) ?>+ </option>+ <?php+ }+ }+ ?>+ </select>+ </div>++ <div class="buttons">+ <input type="button" value="<?= translate('delete', $i18n) ?>" class="warning-button left thin" id="deletesub"+ style="display: none">+ <input type="button" value="<?= translate('cancel', $i18n) ?>" class="secondary-button thin"+ onClick="closeAddSubscription()">+ <input type="submit" value="<?= translate('save', $i18n) ?>" class="thin" id="save-button">+ </div>+ </form>+</section>++<?php require_once 'includes/subscription_details_popup.php'; ?>+<script src="scripts/subscriptions.js?<?= $version ?>"></script>+<?php+if (isset($_GET['add'])) {+ ?>+ <script>+ addSubscription();+ </script>+ <?php+}++require_once 'includes/footer.php';+?>diff --git a/tests/cases/export_missing_relations_test.php b/tests/cases/export_missing_relations_test.phpindex 47aafb3..f957868 100644--- a/tests/cases/export_missing_relations_test.php+++ b/tests/cases/export_missing_relations_test.php@@ -11,6 +11,7 @@ wallos_test('CSV export tolerates subscriptions without payer, payment method or$members = [4 => ['name' => 'Me']];$currencies = [5 => ['symbol' => '£']];$cyclePrint = 'Monthly';+ require_once WALLOS_ROOT . '/includes/subscription_payers.php';$rows = [['name' => 'Full', 'next_payment' => '2026-11-01', 'auto_renew' => 1, 'category_id' => 2, 'payment_method_id' => 3,@@ -25,6 +26,7 @@ wallos_test('CSV export tolerates subscriptions without payer, payment method ortry {$out = [];foreach ($rows as $row) {+ $payerIds = $row['payer_user_id'] === null ? [] : [$row['payer_user_id']];eval($fragment);$out[] = $subscriptionDetails;}diff --git a/tests/cases/subscription_payers_test.php b/tests/cases/subscription_payers_test.phpnew file mode 100644index 0000000..6f28e40--- /dev/null+++ b/tests/cases/subscription_payers_test.php@@ -0,0 +1,133 @@+<?php+/*+ A subscription can be paid by several household members. subscription_payers+ is the full list, subscriptions.payer_user_id keeps the first one.+*/++require_once WALLOS_ROOT . '/includes/subscription_payers.php';++function payers_test_subscription($db, $userId, $payerId)+{+ $stmt = $db->prepare("INSERT INTO subscriptions (name, price, currency_id, next_payment, cycle, frequency, user_id, payer_user_id, inactive) VALUES ('Netflix', 12, 1, '2026-12-01', 3, 1, :userId, :payerId, 0)");+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->bindValue(':payerId', $payerId, SQLITE3_INTEGER);+ $stmt->execute();++ return $db->lastInsertRowID();+}++function payers_test_member($db, $userId, $name)+{+ $stmt = $db->prepare("INSERT INTO household (name, user_id) VALUES (:name, :userId)");+ $stmt->bindValue(':name', $name, SQLITE3_TEXT);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->execute();++ return $db->lastInsertRowID();+}++wallos_test('payer ids are parsed from lists, strings and junk alike', function () {+ assert_same([1, 2], parsePayerIds('1,2'), 'comma separated string');+ assert_same([3, 1], parsePayerIds(['3', 1, '3']), 'array keeps order, drops duplicates');+ assert_same([5], parsePayerIds('5'), 'single id');+ assert_same([], parsePayerIds(''), 'empty string');+ assert_same([], parsePayerIds(null), 'null');+ assert_same([2], parsePayerIds('abc,,0,-4,2'), 'non numeric and non positive values are dropped');+});++wallos_test('the migration gives every existing subscription its current payer, and can run twice', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');+ $memberId = payers_test_member($db, 1, 'Alice');+ $subscriptionId = payers_test_subscription($db, 1, $memberId);+ $withoutPayer = payers_test_subscription($db, 1, null);++ $db->exec('DELETE FROM subscription_payers');+ require WALLOS_ROOT . '/migrations/000060.php';+ require WALLOS_ROOT . '/migrations/000060.php';++ $payers = getPayersBySubscription($db, [['id' => $subscriptionId, 'payer_user_id' => $memberId], ['id' => $withoutPayer, 'payer_user_id' => null]]);+ $rows = $db->querySingle('SELECT COUNT(*) FROM subscription_payers');+ assert_same([$memberId], $payers[$subscriptionId], 'the existing payer is carried over');+ assert_same(false, isset($payers[$withoutPayer]), 'a subscription without payer gets none');+ assert_same(1, $rows, 'running twice does not duplicate rows');++ $db->close();+});++wallos_test('saving payers replaces the list and ownership is checked per member', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');+ wallos_test_create_user($db, 2, 'bob');+ $a = payers_test_member($db, 1, 'Alice');+ $b = payers_test_member($db, 1, 'Ben');+ $other = payers_test_member($db, 2, 'Mallory');+ $subscriptionId = payers_test_subscription($db, 1, $a);++ saveSubscriptionPayers($db, $subscriptionId, [$a, $b]);+ $row = ['id' => $subscriptionId, 'payer_user_id' => $a];+ assert_same([$a, $b], getPayersBySubscription($db, [$row])[$subscriptionId], 'both payers stored in order');++ saveSubscriptionPayers($db, $subscriptionId, [$b]);+ assert_same([$b], getPayersBySubscription($db, [$row])[$subscriptionId], 'the list is replaced, not appended');++ assert_true(payersBelongToUser($db, 1, [$a, $b]), 'own members accepted');+ assert_true(!payersBelongToUser($db, 1, [$a, $other]), 'one foreign member rejects the list');+ assert_true(payersBelongToUser($db, 1, []), 'no payers is not a foreign payer');++ $db->close();+});++wallos_test('filtering by a member finds the subscriptions they share in, not only the ones they lead', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');+ $a = payers_test_member($db, 1, 'Alice');+ $b = payers_test_member($db, 1, 'Ben');+ $shared = payers_test_subscription($db, 1, $a);+ $onlyA = payers_test_subscription($db, 1, $a);+ saveSubscriptionPayers($db, $shared, [$a, $b]);+ saveSubscriptionPayers($db, $onlyA, [$a]);++ $params = [];+ $condition = payerFilterCondition([$b], $params);+ $stmt = $db->prepare("SELECT id FROM subscriptions WHERE user_id = 1 AND $condition");+ foreach ($params as $key => $value) {+ $stmt->bindValue($key, $value, SQLITE3_INTEGER);+ }+ $found = [];+ $result = $stmt->execute();+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $found[] = $row['id'];+ }+ assert_same([$shared], $found, 'only the shared subscription matches the second payer');++ $db->close();+});++wallos_test('payer names are joined for display and unknown ids are skipped', function () {+ assert_same('Alice, Ben', payerNamesLabel([1, 2, 9], [1 => 'Alice', 2 => 'Ben']), 'default separator');+ assert_same('Alice / Ben', payerNamesLabel([1, 2], [1 => 'Alice', 2 => 'Ben'], ' / '), 'custom separator');+ assert_same('', payerNamesLabel([], [1 => 'Alice']), 'no payers');+});++wallos_test('the statistics split a price evenly between its payers and every payer counts it', function () {+ $source = file_get_contents(WALLOS_ROOT . '/includes/stats_calculations.php');+ assert_contains('$fullPrice / count($subscriptionPayerIds)', $source, 'member cost divides by the number of payers');+ assert_contains('$totalCostPerMonth += $price;', $source, 'the total still counts the price once');+});++wallos_test('filtering statistics by member counts that member\'s share of a shared subscription', function () {+ $source = file_get_contents(WALLOS_ROOT . '/includes/stats_calculations.php');+ assert_contains('array_intersect($subscriptionPayerIds, $filteredMemberIds)) / count($subscriptionPayerIds)', $source, 'share is selected payers over all payers');+ assert_contains('$originalSubscriptionPrice *= $memberShare;', $source, 'the amount due this month uses the share too');+});++wallos_test('email reaches every payer while the other channels keep to the primary payer', function () {+ foreach (['sendnotifications.php', 'sendcancellationnotifications.php'] as $file) {+ $source = file_get_contents(WALLOS_ROOT . '/endpoints/cronjobs/' . $file);+ assert_contains('foreach ($notifyEmail as $payerUserId => $perUser)', $source, $file . ' sends email per payer');+ assert_contains('$notify[$rowSubscription[\'payer_user_id\']][$i] = $entry;', $source, $file . ' keeps the primary payer for the other channels');+ assert_contains('$notifyOtherPayers[$extraPayerId][$i] = $entry;', $source, $file . ' collects the other payers');+ assert_contains('No email set for', $source, $file . ' skips extra payers without an address');+ }+});diff --git a/tests/cases/subscription_relations_test.php b/tests/cases/subscription_relations_test.phpindex 75196cc..29847cd 100644--- a/tests/cases/subscription_relations_test.php+++ b/tests/cases/subscription_relations_test.php@@ -15,10 +15,11 @@ wallos_test('subscription relation counts ignore absent and unresolved optional$categories = [8 => ['count' => 0]];$payment_methods = [9 => ['count' => 0]];$subscriptions = [- ['payer_user_id' => null, 'category_id' => null, 'payment_method_id' => null],- ['payer_user_id' => 99, 'category_id' => 99, 'payment_method_id' => 99],- ['payer_user_id' => 7, 'category_id' => 8, 'payment_method_id' => 9],+ ['id' => 1, 'payer_user_id' => null, 'category_id' => null, 'payment_method_id' => null],+ ['id' => 2, 'payer_user_id' => 99, 'category_id' => 99, 'payment_method_id' => 99],+ ['id' => 3, 'payer_user_id' => 7, 'category_id' => 8, 'payment_method_id' => 9],];+ $payersBySubscription = [2 => [99], 3 => [7]];set_error_handler(function ($severity, $message) { throw new ErrorException($message, 0, $severity); });try { eval($fragment); } finally { restore_error_handler(); }assert_same([7 => ['count' => 1]], $members, 'only known payer counted');