Skip to content

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

style: restore CRLF line endings in files converted by earlier commits

Miguel Ribeirob2347526814c
diff --git a/api/categories/get_categories.php b/api/categories/get_categories.php
index 962a85e..317b51f 100644
--- a/api/categories/get_categories.php
+++ b/api/categories/get_categories.php
@@ -1,125 +1,125 @@
-<?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).
-- categories: an array of categories.
-- notes: warning messages or additional information (array).
-
-Example response:
-{
- "success": true,
- "title": "categories",
- "categories": [
- {
- "id": 1,
- "name": "General",
- "order": 1,
- "in_use": true
- },
- {
- "id": 2,
- "name": "Entertainment",
- "order": 2,
- "in_use": true
- },
- {
- "id": 3,
- "name": "Music",
- "order": 3,
- "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 categories WHERE user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId);
- $result = $stmt->execute();
- $categories = [];
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $categories[] = $row;
- }
-
- foreach ($categories as $key => $value) {
- unset($categories[$key]['user_id']);
- // Check if it's in use in any subscription
- $categoryId = $categories[$key]['id'];
- $sql = "SELECT COUNT(*) as count FROM subscriptions WHERE user_id = :userId AND (category_id = :categoryId OR id IN (SELECT subscription_id FROM subscription_categories WHERE category_id = :categoryId))";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':categoryId', $categoryId);
- $stmt->bindValue(':userId', $userId);
- $result = $stmt->execute();
- $count = $result->fetchArray(SQLITE3_ASSOC);
- if ($count['count'] > 0) {
- $categories[$key]['in_use'] = true;
- } else {
- $categories[$key]['in_use'] = false;
- }
- }
-
- $response = [
- "success" => true,
- "title" => "categories",
- "categories" => $categories,
- "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).
+- categories: an array of categories.
+- notes: warning messages or additional information (array).
+
+Example response:
+{
+ "success": true,
+ "title": "categories",
+ "categories": [
+ {
+ "id": 1,
+ "name": "General",
+ "order": 1,
+ "in_use": true
+ },
+ {
+ "id": 2,
+ "name": "Entertainment",
+ "order": 2,
+ "in_use": true
+ },
+ {
+ "id": 3,
+ "name": "Music",
+ "order": 3,
+ "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 categories WHERE user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId);
+ $result = $stmt->execute();
+ $categories = [];
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $categories[] = $row;
+ }
+
+ foreach ($categories as $key => $value) {
+ unset($categories[$key]['user_id']);
+ // Check if it's in use in any subscription
+ $categoryId = $categories[$key]['id'];
+ $sql = "SELECT COUNT(*) as count FROM subscriptions WHERE user_id = :userId AND (category_id = :categoryId OR id IN (SELECT subscription_id FROM subscription_categories WHERE category_id = :categoryId))";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':categoryId', $categoryId);
+ $stmt->bindValue(':userId', $userId);
+ $result = $stmt->execute();
+ $count = $result->fetchArray(SQLITE3_ASSOC);
+ if ($count['count'] > 0) {
+ $categories[$key]['in_use'] = true;
+ } else {
+ $categories[$key]['in_use'] = false;
+ }
+ }
+
+ $response = [
+ "success" => true,
+ "title" => "categories",
+ "categories" => $categories,
+ "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 file
diff --git a/api/household/get_household.php b/api/household/get_household.php
index 487f975..d3f860c 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 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;
-}
-
+<?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 file
diff --git a/api/subscriptions/get_ical_feed.php b/api/subscriptions/get_ical_feed.php
index f03d2d0..95a13b9 100644
--- a/api/subscriptions/get_ical_feed.php
+++ b/api/subscriptions/get_ical_feed.php
@@ -1,228 +1,228 @@
-<?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';
-require_once '../../includes/subscription_categories.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);
- $categoriesBySubscription = getCategoriesBySubscription($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'];
- }
-
- $categoryLabel = payerNamesLabel($categoriesBySubscription[$subscription['id']] ?? [], $categories);
- $subscriptionToReturn['category_name'] = $categoryLabel !== '' ? $categoryLabel : '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;
-}
-
-
-?>
+<?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';
+require_once '../../includes/subscription_categories.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);
+ $categoriesBySubscription = getCategoriesBySubscription($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'];
+ }
+
+ $categoryLabel = payerNamesLabel($categoriesBySubscription[$subscription['id']] ?? [], $categories);
+ $subscriptionToReturn['category_name'] = $categoryLabel !== '' ? $categoryLabel : '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_subscriptions.php b/api/subscriptions/get_subscriptions.php
index 9da3b52..9faad40 100644
--- a/api/subscriptions/get_subscriptions.php
+++ b/api/subscriptions/get_subscriptions.php
@@ -1,358 +1,358 @@
-<?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",
- "category_ids": [1, 2],
- "category_names": ["General", "Entertainment"],
- "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';
-require_once '../../includes/subscription_categories.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']);
- $sql .= " AND " . categoryFilterCondition($categoryIds, $params);
- }
- 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);
- $categoriesBySubscription = getCategoriesBySubscription($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'];
- }
- $categoryIdsForSubscription = $categoriesBySubscription[$subscription['id']] ?? [];
- $subscriptionToReturn['category_ids'] = $categoryIdsForSubscription;
- $subscriptionToReturn['category_names'] = array_map(fn($categoryId) => $categories[$categoryId] ?? 'No category', $categoryIdsForSubscription);
- $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;
+<?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",
+ "category_ids": [1, 2],
+ "category_names": ["General", "Entertainment"],
+ "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';
+require_once '../../includes/subscription_categories.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']);
+ $sql .= " AND " . categoryFilterCondition($categoryIds, $params);
+ }
+ 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);
+ $categoriesBySubscription = getCategoriesBySubscription($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'];
+ }
+ $categoryIdsForSubscription = $categoriesBySubscription[$subscription['id']] ?? [];
+ $subscriptionToReturn['category_ids'] = $categoryIdsForSubscription;
+ $subscriptionToReturn['category_names'] = array_map(fn($categoryId) => $categories[$categoryId] ?? 'No category', $categoryIdsForSubscription);
+ $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 file
diff --git a/endpoints/admin/deleteuser.php b/endpoints/admin/deleteuser.php
index 0268450..75ee8ac 100644
--- a/endpoints/admin/deleteuser.php
+++ b/endpoints/admin/deleteuser.php
@@ -1,222 +1,222 @@
-<?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_categories 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 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)
- ]));
-
+<?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_categories 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 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 file
diff --git a/endpoints/categories/category.php b/endpoints/categories/category.php
index f931a23..0aa24e6 100644
--- a/endpoints/categories/category.php
+++ b/endpoints/categories/category.php
@@ -1,165 +1,165 @@
-<?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":
- handleAddCategory($db, $userId, $i18n);
- break;
- case "edit":
- handleEditCategory($db, $userId, $i18n);
- break;
- case "delete":
- handleDeleteCategory($db, $userId, $i18n);
- break;
- case "sort":
- handleSortCategories($db, $userId, $i18n);
- break;
- default:
- echo json_encode(["success" => false, "message" => translate('error', $i18n)]);
- break;
-}
-
-function handleAddCategory($db, $userId, $i18n)
-{
- $stmt = $db->prepare('SELECT MAX("order") as maxOrder FROM categories WHERE user_id = :userId');
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $maxOrder = $row['maxOrder'];
-
- if ($maxOrder === NULL) {
- $maxOrder = 0;
- }
-
- $order = $maxOrder + 1;
-
- $categoryName = "Category";
- $sqlInsert = 'INSERT INTO categories ("name", "order", "user_id") VALUES (:name, :order, :userId)';
- $stmtInsert = $db->prepare($sqlInsert);
- $stmtInsert->bindParam(':name', $categoryName, SQLITE3_TEXT);
- $stmtInsert->bindParam(':order', $order, SQLITE3_INTEGER);
- $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $resultInsert = $stmtInsert->execute();
-
- if ($resultInsert) {
- $categoryId = $db->lastInsertRowID();
- $response = [
- "success" => true,
- "categoryId" => $categoryId
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('failed_add_category', $i18n)
- ];
- echo json_encode($response);
- }
-}
-
-function handleEditCategory($db, $userId, $i18n)
-{
- if (isset($_POST['categoryId']) && $_POST['categoryId'] != "" && isset($_POST['name']) && $_POST['name'] != "") {
- $categoryId = $_POST['categoryId'];
- $name = validate($_POST['name']);
- $sql = "UPDATE categories SET name = :name WHERE id = :categoryId AND user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':name', $name, SQLITE3_TEXT);
- $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- if ($result) {
- $response = [
- "success" => true,
- "message" => translate('category_saved', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('failed_edit_category', $i18n)
- ];
- echo json_encode($response);
- }
- } else {
- $response = [
- "success" => false,
- "message" => translate('fill_all_fields', $i18n)
- ];
- echo json_encode($response);
- }
-}
-
-function handleDeleteCategory($db, $userId, $i18n)
-{
- if (isset($_POST['categoryId']) && $_POST['categoryId'] != "" && $_POST['categoryId'] != 1) {
- $categoryId = $_POST['categoryId'];
- $checkCategory = "SELECT COUNT(*) FROM subscriptions WHERE (category_id = :categoryId OR id IN (SELECT subscription_id FROM subscription_categories WHERE category_id = :categoryId)) AND user_id = :userId";
- $checkStmt = $db->prepare($checkCategory);
- $checkStmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
- $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $checkResult = $checkStmt->execute();
- $row = $checkResult->fetchArray();
- $count = $row[0];
-
- if ($count > 0) {
- $response = [
- "success" => false,
- "message" => translate('category_in_use', $i18n)
- ];
- echo json_encode($response);
- } else {
- $sql = "DELETE FROM categories WHERE id = :categoryId AND user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- if ($result) {
- $response = [
- "success" => true,
- "message" => translate('category_removed', $i18n)
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('failed_remove_category', $i18n)
- ];
- echo json_encode($response);
- }
- }
- } else {
- $response = [
- "success" => false,
- "message" => translate('failed_remove_category', $i18n)
- ];
- echo json_encode($response);
- }
-}
-
-function handleSortCategories($db, $userId, $i18n)
-{
- $categories = $_POST['categoryIds'];
- $order = 2;
-
- foreach ($categories as $categoryId) {
- $sql = "UPDATE categories SET `order` = :order WHERE id = :categoryId AND user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':order', $order, SQLITE3_INTEGER);
- $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $order++;
- }
-
- $response = [
- "success" => true,
- "message" => translate("sort_order_saved", $i18n)
- ];
- echo json_encode($response);
+<?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":
+ handleAddCategory($db, $userId, $i18n);
+ break;
+ case "edit":
+ handleEditCategory($db, $userId, $i18n);
+ break;
+ case "delete":
+ handleDeleteCategory($db, $userId, $i18n);
+ break;
+ case "sort":
+ handleSortCategories($db, $userId, $i18n);
+ break;
+ default:
+ echo json_encode(["success" => false, "message" => translate('error', $i18n)]);
+ break;
+}
+
+function handleAddCategory($db, $userId, $i18n)
+{
+ $stmt = $db->prepare('SELECT MAX("order") as maxOrder FROM categories WHERE user_id = :userId');
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $maxOrder = $row['maxOrder'];
+
+ if ($maxOrder === NULL) {
+ $maxOrder = 0;
+ }
+
+ $order = $maxOrder + 1;
+
+ $categoryName = "Category";
+ $sqlInsert = 'INSERT INTO categories ("name", "order", "user_id") VALUES (:name, :order, :userId)';
+ $stmtInsert = $db->prepare($sqlInsert);
+ $stmtInsert->bindParam(':name', $categoryName, SQLITE3_TEXT);
+ $stmtInsert->bindParam(':order', $order, SQLITE3_INTEGER);
+ $stmtInsert->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $resultInsert = $stmtInsert->execute();
+
+ if ($resultInsert) {
+ $categoryId = $db->lastInsertRowID();
+ $response = [
+ "success" => true,
+ "categoryId" => $categoryId
+ ];
+ echo json_encode($response);
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('failed_add_category', $i18n)
+ ];
+ echo json_encode($response);
+ }
+}
+
+function handleEditCategory($db, $userId, $i18n)
+{
+ if (isset($_POST['categoryId']) && $_POST['categoryId'] != "" && isset($_POST['name']) && $_POST['name'] != "") {
+ $categoryId = $_POST['categoryId'];
+ $name = validate($_POST['name']);
+ $sql = "UPDATE categories SET name = :name WHERE id = :categoryId AND user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':name', $name, SQLITE3_TEXT);
+ $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result) {
+ $response = [
+ "success" => true,
+ "message" => translate('category_saved', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('failed_edit_category', $i18n)
+ ];
+ echo json_encode($response);
+ }
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_all_fields', $i18n)
+ ];
+ echo json_encode($response);
+ }
+}
+
+function handleDeleteCategory($db, $userId, $i18n)
+{
+ if (isset($_POST['categoryId']) && $_POST['categoryId'] != "" && $_POST['categoryId'] != 1) {
+ $categoryId = $_POST['categoryId'];
+ $checkCategory = "SELECT COUNT(*) FROM subscriptions WHERE (category_id = :categoryId OR id IN (SELECT subscription_id FROM subscription_categories WHERE category_id = :categoryId)) AND user_id = :userId";
+ $checkStmt = $db->prepare($checkCategory);
+ $checkStmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
+ $checkStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $checkResult = $checkStmt->execute();
+ $row = $checkResult->fetchArray();
+ $count = $row[0];
+
+ if ($count > 0) {
+ $response = [
+ "success" => false,
+ "message" => translate('category_in_use', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
+ $sql = "DELETE FROM categories WHERE id = :categoryId AND user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ if ($result) {
+ $response = [
+ "success" => true,
+ "message" => translate('category_removed', $i18n)
+ ];
+ echo json_encode($response);
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('failed_remove_category', $i18n)
+ ];
+ echo json_encode($response);
+ }
+ }
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('failed_remove_category', $i18n)
+ ];
+ echo json_encode($response);
+ }
+}
+
+function handleSortCategories($db, $userId, $i18n)
+{
+ $categories = $_POST['categoryIds'];
+ $order = 2;
+
+ foreach ($categories as $categoryId) {
+ $sql = "UPDATE categories SET `order` = :order WHERE id = :categoryId AND user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':order', $order, SQLITE3_INTEGER);
+ $stmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $order++;
+ }
+
+ $response = [
+ "success" => true,
+ "message" => translate("sort_order_saved", $i18n)
+ ];
+ echo json_encode($response);
}
\ No newline at end of file
diff --git a/endpoints/household/household.php b/endpoints/household/household.php
index aa2af0b..ec4c4af 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 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);
- }
-}
-
+<?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 file
diff --git a/endpoints/settings/deleteaccount.php b/endpoints/settings/deleteaccount.php
index afc5021..3c4b624 100644
--- a/endpoints/settings/deleteaccount.php
+++ b/endpoints/settings/deleteaccount.php
@@ -1,222 +1,222 @@
-<?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_categories 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 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)
- ]));
-
+<?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_categories 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 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 file
diff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.php
index 60f5ab5..385b14b 100644
--- a/endpoints/subscription/add.php
+++ b/endpoints/subscription/add.php
@@ -1,481 +1,481 @@
-<?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';
-require_once '../../includes/subscription_categories.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;
-$categoryIds = parsePayerIds($_POST['category_id'] ?? "");
-$categoryId = $categoryIds[0] ?? null;
-$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 (!categoriesBelongToUser($db, $userId, $categoryIds)) {
- 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);
- saveSubscriptionCategories($db, $savedSubscriptionId, $categoryIds);
-
- // 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';
+require_once '../../includes/subscription_categories.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;
+$categoryIds = parsePayerIds($_POST['category_id'] ?? "");
+$categoryId = $categoryIds[0] ?? null;
+$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 (!categoriesBelongToUser($db, $userId, $categoryIds)) {
+ 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);
+ saveSubscriptionCategories($db, $savedSubscriptionId, $categoryIds);
+
+ // 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 file
diff --git a/endpoints/subscription/clone.php b/endpoints/subscription/clone.php
index 3e9bfa1..7f8d880 100644
--- a/endpoints/subscription/clone.php
+++ b/endpoints/subscription/clone.php
@@ -1,65 +1,65 @@
-<?php
-require_once '../../includes/connect_endpoint.php';
-require_once '../../includes/validate_endpoint.php';
-require_once '../../includes/subscription_payers.php';
-require_once '../../includes/subscription_categories.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']] ?? []);
- saveSubscriptionCategories($db, $clonedId, getCategoriesBySubscription($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();
+<?php
+require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
+require_once '../../includes/subscription_payers.php';
+require_once '../../includes/subscription_categories.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']] ?? []);
+ saveSubscriptionCategories($db, $clonedId, getCategoriesBySubscription($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 file
diff --git a/endpoints/subscription/delete.php b/endpoints/subscription/delete.php
index 55d0769..cb03770 100644
--- a/endpoints/subscription/delete.php
+++ b/endpoints/subscription/delete.php
@@ -1,54 +1,54 @@
-<?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();
-
-$categoriesStmt = $db->prepare("DELETE FROM subscription_categories WHERE subscription_id IN (SELECT id FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId)");
-$categoriesStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
-$categoriesStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-$categoriesStmt->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();
+<?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();
+
+$categoriesStmt = $db->prepare("DELETE FROM subscription_categories WHERE subscription_id IN (SELECT id FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId)");
+$categoriesStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
+$categoriesStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+$categoriesStmt->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.php
index 24616c8..bad3d40 100644
--- a/endpoints/subscription/exportcalendar.php
+++ b/endpoints/subscription/exportcalendar.php
@@ -1,92 +1,92 @@
-<?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/subscription_categories.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'] = payerNamesLabel(getCategoriesBySubscription($db, [$subscription])[$subscription['id']] ?? [], array_map(fn($c) => $c['name'] ?? '', $categories));
- $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/subscription_categories.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'] = payerNamesLabel(getCategoriesBySubscription($db, [$subscription])[$subscription['id']] ?? [], array_map(fn($c) => $c['name'] ?? '', $categories));
+ $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 file
diff --git a/endpoints/subscription/get.php b/endpoints/subscription/get.php
index cd8209e..e8e3b3f 100644
--- a/endpoints/subscription/get.php
+++ b/endpoints/subscription/get.php
@@ -1,60 +1,60 @@
-<?php
-require_once '../../includes/connect_endpoint.php';
-require_once '../../includes/markdown.php';
-require_once '../../includes/subscription_payers.php';
-require_once '../../includes/subscription_categories.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['category_ids'] = getCategoriesBySubscription($db, [$row])[$row['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';
+require_once '../../includes/subscription_categories.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['category_ids'] = getCategoriesBySubscription($db, [$row])[$row['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 file
diff --git a/endpoints/subscription/getcalendar.php b/endpoints/subscription/getcalendar.php
index 2dddddb..33d8e86 100644
--- a/endpoints/subscription/getcalendar.php
+++ b/endpoints/subscription/getcalendar.php
@@ -1,53 +1,53 @@
-<?php
-require_once '../../includes/connect_endpoint.php';
-require_once '../../includes/getdbkeys.php';
-require_once '../../includes/subscription_payers.php';
-require_once '../../includes/subscription_categories.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'] = payerNamesLabel(getCategoriesBySubscription($db, [$subscription])[$subscription['id']] ?? [], array_map(fn($c) => $c['name'] ?? '', $categories));
- $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';
+require_once '../../includes/subscription_categories.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'] = payerNamesLabel(getCategoriesBySubscription($db, [$subscription])[$subscription['id']] ?? [], array_map(fn($c) => $c['name'] ?? '', $categories));
+ $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 file
diff --git a/endpoints/subscriptions/export.php b/endpoints/subscriptions/export.php
index d87dad4..5cd4aa6 100644
--- a/endpoints/subscriptions/export.php
+++ b/endpoints/subscriptions/export.php
@@ -1,68 +1,68 @@
-<?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';
-require_once '../../includes/subscription_categories.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']] ?? [];
- $categoryIds = getCategoriesBySubscription($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(',', ' ', payerNamesLabel($categoryIds, array_map(fn($c) => $c['name'] ?? '', $categories), ' / ')),
- '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
-]));
-
-
-?>
+<?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';
+require_once '../../includes/subscription_categories.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']] ?? [];
+ $categoryIds = getCategoriesBySubscription($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(',', ' ', payerNamesLabel($categoryIds, array_map(fn($c) => $c['name'] ?? '', $categories), ' / ')),
+ '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.php
index 33898d8..2b46c31 100644
--- a/endpoints/subscriptions/get.php
+++ b/endpoints/subscriptions/get.php
@@ -1,262 +1,262 @@
-<?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/subscription_categories.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']);
- $sql .= " AND " . categoryFilterCondition($allCategories, $params);
- }
-
- 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);
- $categoriesBySubscription = getCategoriesBySubscription($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]['category_ids'] = $categoriesBySubscription[$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();
+<?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/subscription_categories.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']);
+ $sql .= " AND " . categoryFilterCondition($allCategories, $params);
+ }
+
+ 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);
+ $categoriesBySubscription = getCategoriesBySubscription($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]['category_ids'] = $categoriesBySubscription[$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 file
diff --git a/includes/stats_calculations.php b/includes/stats_calculations.php
index 3cb95ee..e8160aa 100644
--- a/includes/stats_calculations.php
+++ b/includes/stats_calculations.php
@@ -1,417 +1,417 @@
-<?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';
-require_once __DIR__ . '/subscription_categories.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 sc.category_id AS category_id, COUNT(*) as cnt FROM subscription_categories sc JOIN subscriptions s ON s.id = sc.subscription_id WHERE s.user_id = :userId GROUP BY sc.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 = [];
-$filteredCategoryIds = [];
-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']));
- $filteredCategoryIds = $categoryIds;
- $conditions[] = categoryFilterCondition($categoryIds, $params);
- // 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);
- $categoriesBySubscription = getCategoriesBySubscription($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;
- }
- }
- $subscriptionCategoryIds = $categoriesBySubscription[$subscription['id']] ?? [];
- foreach ($subscriptionCategoryIds as $categoryId) {
- 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);
- }
- // The same goes for a subscription in several categories
- if (!empty($filteredCategoryIds) && count($subscriptionCategoryIds) > 0) {
- $memberShare *= count(array_intersect($subscriptionCategoryIds, $filteredCategoryIds)) / count($subscriptionCategoryIds);
- }
- $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;
- }
- }
- // The price is split evenly between its categories too, so the
- // category costs add up to the total instead of exceeding it
- $categoryShare = count($subscriptionCategoryIds) > 0 ? $fullPrice / count($subscriptionCategoryIds) : 0;
- foreach ($subscriptionCategoryIds as $categoryId) {
- if (isset($categoryCost[$categoryId])) {
- $categoryCost[$categoryId]['cost'] += $categoryShare;
- }
- }
- 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';
+require_once __DIR__ . '/subscription_categories.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 sc.category_id AS category_id, COUNT(*) as cnt FROM subscription_categories sc JOIN subscriptions s ON s.id = sc.subscription_id WHERE s.user_id = :userId GROUP BY sc.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 = [];
+$filteredCategoryIds = [];
+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']));
+ $filteredCategoryIds = $categoryIds;
+ $conditions[] = categoryFilterCondition($categoryIds, $params);
+ // 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);
+ $categoriesBySubscription = getCategoriesBySubscription($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;
+ }
+ }
+ $subscriptionCategoryIds = $categoriesBySubscription[$subscription['id']] ?? [];
+ foreach ($subscriptionCategoryIds as $categoryId) {
+ 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);
+ }
+ // The same goes for a subscription in several categories
+ if (!empty($filteredCategoryIds) && count($subscriptionCategoryIds) > 0) {
+ $memberShare *= count(array_intersect($subscriptionCategoryIds, $filteredCategoryIds)) / count($subscriptionCategoryIds);
+ }
+ $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;
+ }
+ }
+ // The price is split evenly between its categories too, so the
+ // category costs add up to the total instead of exceeding it
+ $categoryShare = count($subscriptionCategoryIds) > 0 ? $fullPrice / count($subscriptionCategoryIds) : 0;
+ foreach ($subscriptionCategoryIds as $categoryId) {
+ if (isset($categoryCost[$categoryId])) {
+ $categoryCost[$categoryId]['cost'] += $categoryShare;
+ }
+ }
+ 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 file
diff --git a/scripts/subscriptions.js b/scripts/subscriptions.js
index d095847..3c7e540 100644
--- a/scripts/subscriptions.js
+++ b/scripts/subscriptions.js
@@ -1,1393 +1,1393 @@
-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 used by the "Paid by" and "Category" fields. The hidden input
-// carries the selected ids as a comma separated list, first one being the
-// primary one. At least one option always stays selected.
-function multiSelectElements(wrapperId) {
- const wrapper = document.querySelector(`#${wrapperId}`);
- return {
- wrapper,
- toggle: wrapper.querySelector(".multi-select-toggle"),
- list: wrapper.querySelector(".multi-select-options"),
- input: wrapper.querySelector("input[type='hidden']"),
- };
-}
-
-function getMultiSelection(wrapperId) {
- const { input } = multiSelectElements(wrapperId);
- return input.value === "" ? [] : input.value.split(",");
-}
-
-function setMultiSelection(wrapperId, ids) {
- const { wrapper, list, input } = multiSelectElements(wrapperId);
- const options = list.querySelectorAll("li[role='option']");
- const wanted = ids.map(String).filter(id => list.querySelector(`li[data-value="${id}"]`));
- 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");
- });
- input.value = wanted.join(",");
- const names = wanted.map(id => list.querySelector(`li[data-value="${id}"] .multi-select-name`).textContent.trim());
- wrapper.querySelector(".multi-select-label").textContent = names.length > 0 ? names.join(", ") : wrapper.dataset.placeholder;
-}
-
-function toggleMultiOption(wrapperId, option) {
- const current = getMultiSelection(wrapperId);
- const id = option.dataset.value;
- if (current.includes(id)) {
- if (current.length === 1) {
- return;
- }
- setMultiSelection(wrapperId, current.filter(value => value !== id));
- } else {
- setMultiSelection(wrapperId, [...current, id]);
- }
-}
-
-function closeMultiSelect(wrapperId) {
- const { wrapper, toggle, list } = multiSelectElements(wrapperId);
- wrapper.classList.remove("is-open");
- list.hidden = true;
- toggle.setAttribute("aria-expanded", "false");
-}
-
-function openMultiSelect(wrapperId) {
- const { wrapper, toggle, list } = multiSelectElements(wrapperId);
- wrapper.classList.add("is-open");
- list.hidden = false;
- toggle.setAttribute("aria-expanded", "true");
- const first = list.querySelector("li[aria-selected='true']") || list.querySelector("li");
- if (first) {
- first.focus();
- }
-}
-
-function initMultiSelect(wrapperId) {
- const { wrapper, toggle, list } = multiSelectElements(wrapperId);
- list.querySelectorAll("li").forEach(option => option.tabIndex = -1);
-
- toggle.addEventListener("click", () => {
- wrapper.classList.contains("is-open") ? closeMultiSelect(wrapperId) : openMultiSelect(wrapperId);
- });
-
- toggle.addEventListener("keydown", event => {
- if (event.key === "ArrowDown" || event.key === "ArrowUp") {
- event.preventDefault();
- openMultiSelect(wrapperId);
- }
- });
-
- list.addEventListener("click", event => {
- const option = event.target.closest("li[role='option']");
- if (option) {
- toggleMultiOption(wrapperId, 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) {
- toggleMultiOption(wrapperId, options[index]);
- }
- } else if (event.key === "Escape" || event.key === "Tab") {
- if (event.key === "Escape") {
- event.stopPropagation();
- }
- closeMultiSelect(wrapperId);
- toggle.focus();
- }
- });
-
- document.addEventListener("mousedown", event => {
- if (wrapper.classList.contains("is-open") && !wrapper.contains(event.target)) {
- closeMultiSelect(wrapperId);
- }
- });
-
- setMultiSelection(wrapperId, getMultiSelection(wrapperId));
-}
-
-const multiSelectIds = ["payer_user_select", "category_select"];
-
-function initMultiSelects() {
- multiSelectIds.forEach(id => {
- if (document.querySelector(`#${id}`)) {
- initMultiSelect(id);
- }
- });
-}
-
-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();
- multiSelectIds.forEach(id => {
- setMultiSelection(id, []);
- closeMultiSelect(id);
- });
- 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;
- setMultiSelection("category_select", subscription.category_ids && subscription.category_ids.length > 0
- ? subscription.category_ids
- : [subscription.category_id]);
- setMultiSelection("payer_user_select", 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("?") ? `&notifications=${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 () {
- initMultiSelects();
-
- 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 used by the "Paid by" and "Category" fields. The hidden input
+// carries the selected ids as a comma separated list, first one being the
+// primary one. At least one option always stays selected.
+function multiSelectElements(wrapperId) {
+ const wrapper = document.querySelector(`#${wrapperId}`);
+ return {
+ wrapper,
+ toggle: wrapper.querySelector(".multi-select-toggle"),
+ list: wrapper.querySelector(".multi-select-options"),
+ input: wrapper.querySelector("input[type='hidden']"),
+ };
+}
+
+function getMultiSelection(wrapperId) {
+ const { input } = multiSelectElements(wrapperId);
+ return input.value === "" ? [] : input.value.split(",");
+}
+
+function setMultiSelection(wrapperId, ids) {
+ const { wrapper, list, input } = multiSelectElements(wrapperId);
+ const options = list.querySelectorAll("li[role='option']");
+ const wanted = ids.map(String).filter(id => list.querySelector(`li[data-value="${id}"]`));
+ 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");
+ });
+ input.value = wanted.join(",");
+ const names = wanted.map(id => list.querySelector(`li[data-value="${id}"] .multi-select-name`).textContent.trim());
+ wrapper.querySelector(".multi-select-label").textContent = names.length > 0 ? names.join(", ") : wrapper.dataset.placeholder;
+}
+
+function toggleMultiOption(wrapperId, option) {
+ const current = getMultiSelection(wrapperId);
+ const id = option.dataset.value;
+ if (current.includes(id)) {
+ if (current.length === 1) {
+ return;
+ }
+ setMultiSelection(wrapperId, current.filter(value => value !== id));
+ } else {
+ setMultiSelection(wrapperId, [...current, id]);
+ }
+}
+
+function closeMultiSelect(wrapperId) {
+ const { wrapper, toggle, list } = multiSelectElements(wrapperId);
+ wrapper.classList.remove("is-open");
+ list.hidden = true;
+ toggle.setAttribute("aria-expanded", "false");
+}
+
+function openMultiSelect(wrapperId) {
+ const { wrapper, toggle, list } = multiSelectElements(wrapperId);
+ wrapper.classList.add("is-open");
+ list.hidden = false;
+ toggle.setAttribute("aria-expanded", "true");
+ const first = list.querySelector("li[aria-selected='true']") || list.querySelector("li");
+ if (first) {
+ first.focus();
+ }
+}
+
+function initMultiSelect(wrapperId) {
+ const { wrapper, toggle, list } = multiSelectElements(wrapperId);
+ list.querySelectorAll("li").forEach(option => option.tabIndex = -1);
+
+ toggle.addEventListener("click", () => {
+ wrapper.classList.contains("is-open") ? closeMultiSelect(wrapperId) : openMultiSelect(wrapperId);
+ });
+
+ toggle.addEventListener("keydown", event => {
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ event.preventDefault();
+ openMultiSelect(wrapperId);
+ }
+ });
+
+ list.addEventListener("click", event => {
+ const option = event.target.closest("li[role='option']");
+ if (option) {
+ toggleMultiOption(wrapperId, 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) {
+ toggleMultiOption(wrapperId, options[index]);
+ }
+ } else if (event.key === "Escape" || event.key === "Tab") {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ }
+ closeMultiSelect(wrapperId);
+ toggle.focus();
+ }
+ });
+
+ document.addEventListener("mousedown", event => {
+ if (wrapper.classList.contains("is-open") && !wrapper.contains(event.target)) {
+ closeMultiSelect(wrapperId);
+ }
+ });
+
+ setMultiSelection(wrapperId, getMultiSelection(wrapperId));
+}
+
+const multiSelectIds = ["payer_user_select", "category_select"];
+
+function initMultiSelects() {
+ multiSelectIds.forEach(id => {
+ if (document.querySelector(`#${id}`)) {
+ initMultiSelect(id);
+ }
+ });
+}
+
+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();
+ multiSelectIds.forEach(id => {
+ setMultiSelection(id, []);
+ closeMultiSelect(id);
+ });
+ 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;
+ setMultiSelection("category_select", subscription.category_ids && subscription.category_ids.length > 0
+ ? subscription.category_ids
+ : [subscription.category_id]);
+ setMultiSelection("payer_user_select", 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("?") ? `&notifications=${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 () {
+ initMultiSelects();
+
+ 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/service-worker.php b/service-worker.php
index 8ae45fc..bc7c3ef 100644
--- a/service-worker.php
+++ b/service-worker.php
@@ -1,368 +1,368 @@
-<?php
-require_once __DIR__ . '/includes/version.php';
-$assetsStamp = 0;
-foreach (array_merge(glob(__DIR__ . '/scripts/*.js') ?: [], glob(__DIR__ . '/scripts/i18n/*.js') ?: [], glob(__DIR__ . '/styles/*.css') ?: [], glob(__DIR__ . '/styles/themes/*.css') ?: []) as $assetFile) {
- $assetsStamp = max($assetsStamp, (int) filemtime($assetFile));
-}
-if (!headers_sent()) {
- header('Content-Type: text/javascript; charset=utf-8');
- header('Cache-Control: no-cache');
-}
-?>
-// STATIC_CACHE is tied to the app version (rather than a hand-bumped literal)
-// so every release invalidates stale precached assets automatically - a release
-// that changed JS/CSS without remembering to bump a hardcoded cache version
-// used to leave already-visited browsers stuck on old cached files indefinitely.
-//
-// The version alone only changes at a release, so the newest modification time
-// of the precached scripts and styles is part of the name as well: a changed
-// file changes this worker, the browser installs it and drops the old cache,
-// instead of serving the previous copy until the version is bumped.
-const STATIC_CACHE = 'static-cache-<?= $version ?>-<?= $assetsStamp ?>';
-const PAGES_CACHE = 'pages-cache-v1';
-const LOGOS_CACHE = 'logos-cache-v2';
-
-// manifest.php is intentionally not precached here: it's per-user (theme
-// cookie dependent), so it falls through to the network-first handler below
-// instead of being served stale from a cache-first bucket forever.
-const staticAssets = [
- 'styles/styles.css',
- 'styles/theme.css',
- 'styles/dark-theme.css',
- 'styles/login.css',
- 'styles/login-dark-theme.css',
- 'styles/font-awesome.min.css',
- 'styles/brands.css',
- 'styles/barlow.css',
- 'styles/themes/red.css',
- 'styles/themes/green.css',
- 'styles/themes/yellow.css',
- 'styles/themes/purple.css',
- 'webfonts/fa-solid-900.woff2',
- 'webfonts/fa-solid-900.ttf',
- 'webfonts/fa-brands-400.woff2',
- 'webfonts/fa-brands-400.ttf',
- 'webfonts/fa-regular-400.woff2',
- 'webfonts/fa-regular-400.ttf',
- 'scripts/all.js',
- 'scripts/common.js',
- 'scripts/dashboard.js',
- 'scripts/subscriptions.js',
- 'scripts/subscription-details.js',
- 'scripts/password-toggle.js',
- 'scripts/stats.js',
- 'scripts/settings.js',
- 'scripts/profile.js',
- 'scripts/theme.js',
- 'scripts/auth-theme.js',
- 'scripts/notifications.js',
- 'scripts/registration.js',
- 'scripts/login.js',
- 'scripts/admin.js',
- 'scripts/calendar.js',
- 'scripts/i18n/ar.js',
- 'scripts/i18n/az.js',
- 'scripts/i18n/ca.js',
- 'scripts/i18n/cs.js',
- 'scripts/i18n/da.js',
- 'scripts/i18n/de.js',
- 'scripts/i18n/el.js',
- 'scripts/i18n/en.js',
- 'scripts/i18n/es.js',
- 'scripts/i18n/fr.js',
- 'scripts/i18n/hu.js',
- 'scripts/i18n/id.js',
- 'scripts/i18n/it.js',
- 'scripts/i18n/ja.js',
- 'scripts/i18n/ko.js',
- 'scripts/i18n/nl.js',
- 'scripts/i18n/pl.js',
- 'scripts/i18n/pt.js',
- 'scripts/i18n/pt_br.js',
- 'scripts/i18n/ro.js',
- 'scripts/i18n/ru.js',
- 'scripts/i18n/sl.js',
- 'scripts/i18n/sr_lat.js',
- 'scripts/i18n/sr.js',
- 'scripts/i18n/tr.js',
- 'scripts/i18n/uk.js',
- 'scripts/i18n/vi.js',
- 'scripts/i18n/zh_cn.js',
- 'scripts/i18n/zh_tw.js',
- 'scripts/i18n/getlang.js',
- 'scripts/libs/apexcharts.min.js',
- 'scripts/libs/sortable.min.js',
- 'scripts/libs/qrcode.min.js',
- 'images/icon/favicon.ico',
- 'images/icon/favicon-16x16.png',
- 'images/icon/favicon-32x32.png',
- 'images/icon/android-chrome-192x192.png',
- 'images/icon/android-chrome-512x512.png',
- 'images/icon/maskable_icon_x192.png',
- 'images/icon/maskable_icon_x512.png',
- 'images/icon/apple-touch-icon-180.png',
- 'images/icon/apple-touch-icon-152.png',
- 'images/icon/apple-touch-icon.png',
- 'images/screenshots/desktop.png',
- 'images/siteicons/wallos.png',
- 'images/siteicons/walloswhite.png',
- 'images/siteimages/empty.png',
- 'images/siteimages/mobilenav.png',
- 'images/siteimages/mobilenavdark.png',
- 'images/avatars/1.svg',
- 'images/avatars/2.svg',
- 'images/avatars/3.svg',
- 'images/avatars/4.svg',
- 'images/avatars/5.svg',
- 'images/avatars/6.svg',
- 'images/avatars/7.svg',
- 'images/avatars/8.svg',
- 'images/avatars/9.svg',
- 'images/siteicons/svg/logo.php',
- 'images/siteicons/svg/automatic.php',
- 'images/siteicons/svg/manual.php',
- 'images/siteicons/svg/export_ical.php',
- 'images/siteicons/svg/check.php',
- 'images/siteicons/svg/mobile-menu/calendar.php',
- 'images/siteicons/svg/mobile-menu/home.php',
- 'images/siteicons/svg/mobile-menu/profile.php',
- 'images/siteicons/svg/mobile-menu/settings.php',
- 'images/siteicons/svg/mobile-menu/statistics.php',
- 'images/siteicons/svg/mobile-menu/subscriptions.php',
- 'images/siteicons/svg/mobile-menu/about.php',
- 'images/siteicons/svg/mobile-menu/admin.php',
- 'images/siteicons/svg/mobile-menu/logout.php',
- 'images/siteicons/svg/mobile-menu/clone.php',
- 'images/siteicons/svg/mobile-menu/delete.php',
- 'images/siteicons/svg/mobile-menu/edit.php',
- 'images/siteicons/svg/mobile-menu/renew.php',
- 'images/siteicons/pwa/stats.png',
- 'images/siteicons/pwa/settings.png',
- 'images/siteicons/pwa/about.png',
- 'images/siteicons/pwa/calendar.png',
- 'images/siteicons/pwa/subscriptions.png',
- 'images/siteicons/pwa/dashboard.png',
- 'images/uploads/icons/paypal.png',
- 'images/uploads/icons/creditcard.png',
- 'images/uploads/icons/banktransfer.png',
- 'images/uploads/icons/directdebit.png',
- 'images/uploads/icons/money.png',
- 'images/uploads/icons/googlepay.png',
- 'images/uploads/icons/samsungpay.png',
- 'images/uploads/icons/applepay.png',
- 'images/uploads/icons/crypto.png',
- 'images/uploads/icons/klarna.png',
- 'images/uploads/icons/amazonpay.png',
- 'images/uploads/icons/sepa.png',
- 'images/uploads/icons/skrill.png',
- 'images/uploads/icons/sofort.png',
- 'images/uploads/icons/stripe.png',
- 'images/uploads/icons/affirm.png',
- 'images/uploads/icons/alipay.png',
- 'images/uploads/icons/elo.png',
- 'images/uploads/icons/facebookpay.png',
- 'images/uploads/icons/giropay.png',
- 'images/uploads/icons/ideal.png',
- 'images/uploads/icons/unionpay.png',
- 'images/uploads/icons/interac.png',
- 'images/uploads/icons/wechat.png',
- 'images/uploads/icons/paysafe.png',
- 'images/uploads/icons/poli.png',
- 'images/uploads/icons/qiwi.png',
- 'images/uploads/icons/shoppay.png',
- 'images/uploads/icons/venmo.png',
- 'images/uploads/icons/verifone.png',
- 'images/uploads/icons/webmoney.png',
-];
-
-const pagesToPrefetch = [
- 'index.php',
- 'subscriptions.php',
- 'profile.php',
- 'calendar.php',
- 'settings.php',
- 'stats.php',
- 'about.php',
- 'login.php',
- 'admin.php',
-];
-
-// Install: cache static assets in small batches. Firing all ~150 fetches at
-// once starves large files (apexcharts is 600KB) of connections on HTTP/1.1
-// origins, and a dropped one is silently skipped - see the static-asset
-// fetch handler, which backfills anything that slips through here.
-self.addEventListener('install', function (event) {
- event.waitUntil(
- caches.open(STATIC_CACHE).then(async function (cache) {
- const BATCH_SIZE = 12;
- for (let i = 0; i < staticAssets.length; i += BATCH_SIZE) {
- await Promise.allSettled(
- staticAssets.slice(i, i + BATCH_SIZE).map(url =>
- fetch(url, { cache: 'reload' }).then(response => {
- if (response.ok) return cache.put(url, response);
- }).catch(() => {}) // silently skip missing files
- )
- );
- }
- })
- );
- self.skipWaiting();
-});
-
-// Activate: clean up old caches
-self.addEventListener('activate', function (event) {
- const validCaches = [STATIC_CACHE, PAGES_CACHE, LOGOS_CACHE];
- event.waitUntil(
- caches.keys().then(keys =>
- Promise.all(
- keys.filter(key => !validCaches.includes(key))
- .map(key => caches.delete(key))
- )
- )
- );
- self.clients.claim();
-});
-
-// Message: prefetch pages after login
-self.addEventListener('message', function (event) {
- if (event.data && event.data.type === 'PREFETCH_PAGES') {
- caches.open(PAGES_CACHE).then(cache => {
- pagesToPrefetch.forEach(url => {
- fetch(url).then(response => {
- // Only cache if user is actually logged in (no redirect)
- if (response.ok && !response.redirected) {
- cache.put(url, response);
- }
- }).catch(() => {});
- });
- });
- }
-});
-
-// Fetch: single handler for all requests
-self.addEventListener('fetch', function (event) {
- const request = event.request;
- const url = new URL(request.url);
-
- // Never intercept non-GET requests (POST, etc.)
- if (request.method !== 'GET') return;
-
- // Search endpoints must always return their current JSON response. Falling
- // back to a cached PHP page (especially with ignoreSearch) makes the client
- // try to parse HTML or another query's data as JSON.
- if (url.pathname.includes('/endpoints/logos/')) {
- event.respondWith(fetch(request));
- return;
- }
-
- // Logo images: use cache-first, but cache only successful image responses.
- // This prevents temporary 404/HTML responses from becoming permanent
- // broken images. Bumping LOGOS_CACHE removes previously poisoned entries.
- if (url.pathname.includes('images/uploads/logos')) {
- event.respondWith(
- caches.match(request).then(response => {
- return response || fetch(request).then(networkResponse => {
- const contentType = networkResponse.headers.get('content-type') || '';
- if (networkResponse.ok && contentType.startsWith('image/')) {
- return caches.open(LOGOS_CACHE).then(cache => {
- cache.put(request, networkResponse.clone());
- return networkResponse;
- });
- }
- return networkResponse;
- });
- })
- );
- return;
- }
-
- // Static assets: cache-first (they only change on deploy). ignoreSearch
- // because the pages request these with a "?<version>" cache-buster, while
- // they're precached under the bare path - without it every asset misses
- // the cache and the page renders unstyled offline.
- //
- // On a miss, fetch AND store the result: the install step fires ~150
- // parallel fetches and any that fail (a large file like apexcharts, a
- // dropped connection) are silently skipped, so without this backfill a
- // once-missed asset would never get cached and its feature (e.g. the
- // stats charts) would stay broken offline forever.
- if (staticAssets.some(asset => url.pathname.endsWith(asset))) {
- event.respondWith(
- caches.match(request, { ignoreSearch: true }).then(cached => {
- if (cached) return cached;
- return fetch(request).then(networkResponse => {
- if (networkResponse.ok) {
- const clone = networkResponse.clone();
- caches.open(STATIC_CACHE).then(cache => cache.put(request, clone));
- }
- return networkResponse;
- });
- })
- );
- return;
- }
-
- // PHP pages and everything else: network-first, cache as fallback
- // Also update the pages cache on every successful load
- event.respondWith(
- fetch(request).then(response => {
- if (response.ok && !response.redirected) {
- const responseClone = response.clone(); // clone before any async operation
- caches.open(PAGES_CACHE).then(cache => {
- cache.put(request, responseClone);
- });
- }
- return response;
- }).catch(() => {
- return caches.match(request, { ignoreSearch: true });
- })
- );
-});
-
-// Web Push (RFC 8291/8292): the payload includes/webpush_helper.php sends is
-// {"title": ..., "body": ...} JSON, decrypted by the browser itself before
-// this handler ever sees it - nothing here has to know that aes128gcm
-// happened at all.
-self.addEventListener('push', function (event) {
- let data = {};
-
- if (event.data) {
- try {
- data = event.data.json();
- } catch (e) {
- data = { title: 'Wallos', body: event.data.text() };
- }
- }
-
- const title = data.title || 'Wallos';
- const options = {
- body: data.body || '',
- icon: 'images/icon/android-chrome-192x192.png',
- badge: 'images/icon/android-chrome-192x192.png',
- data: { url: data.url || './' },
- };
-
- event.waitUntil(self.registration.showNotification(title, options));
-});
-
-self.addEventListener('notificationclick', function (event) {
- event.notification.close();
-
- const targetUrl = (event.notification.data && event.notification.data.url) || './';
-
- event.waitUntil(
- clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (windowClients) {
- // Focus a tab that already has the app open, rather than piling
- // up a new one every time a notification is tapped.
- for (const client of windowClients) {
- if (client.url.includes(self.registration.scope) && 'focus' in client) {
- return client.focus();
- }
- }
-
- if (clients.openWindow) {
- return clients.openWindow(targetUrl);
- }
- })
- );
-});
+<?php
+require_once __DIR__ . '/includes/version.php';
+$assetsStamp = 0;
+foreach (array_merge(glob(__DIR__ . '/scripts/*.js') ?: [], glob(__DIR__ . '/scripts/i18n/*.js') ?: [], glob(__DIR__ . '/styles/*.css') ?: [], glob(__DIR__ . '/styles/themes/*.css') ?: []) as $assetFile) {
+ $assetsStamp = max($assetsStamp, (int) filemtime($assetFile));
+}
+if (!headers_sent()) {
+ header('Content-Type: text/javascript; charset=utf-8');
+ header('Cache-Control: no-cache');
+}
+?>
+// STATIC_CACHE is tied to the app version (rather than a hand-bumped literal)
+// so every release invalidates stale precached assets automatically - a release
+// that changed JS/CSS without remembering to bump a hardcoded cache version
+// used to leave already-visited browsers stuck on old cached files indefinitely.
+//
+// The version alone only changes at a release, so the newest modification time
+// of the precached scripts and styles is part of the name as well: a changed
+// file changes this worker, the browser installs it and drops the old cache,
+// instead of serving the previous copy until the version is bumped.
+const STATIC_CACHE = 'static-cache-<?= $version ?>-<?= $assetsStamp ?>';
+const PAGES_CACHE = 'pages-cache-v1';
+const LOGOS_CACHE = 'logos-cache-v2';
+
+// manifest.php is intentionally not precached here: it's per-user (theme
+// cookie dependent), so it falls through to the network-first handler below
+// instead of being served stale from a cache-first bucket forever.
+const staticAssets = [
+ 'styles/styles.css',
+ 'styles/theme.css',
+ 'styles/dark-theme.css',
+ 'styles/login.css',
+ 'styles/login-dark-theme.css',
+ 'styles/font-awesome.min.css',
+ 'styles/brands.css',
+ 'styles/barlow.css',
+ 'styles/themes/red.css',
+ 'styles/themes/green.css',
+ 'styles/themes/yellow.css',
+ 'styles/themes/purple.css',
+ 'webfonts/fa-solid-900.woff2',
+ 'webfonts/fa-solid-900.ttf',
+ 'webfonts/fa-brands-400.woff2',
+ 'webfonts/fa-brands-400.ttf',
+ 'webfonts/fa-regular-400.woff2',
+ 'webfonts/fa-regular-400.ttf',
+ 'scripts/all.js',
+ 'scripts/common.js',
+ 'scripts/dashboard.js',
+ 'scripts/subscriptions.js',
+ 'scripts/subscription-details.js',
+ 'scripts/password-toggle.js',
+ 'scripts/stats.js',
+ 'scripts/settings.js',
+ 'scripts/profile.js',
+ 'scripts/theme.js',
+ 'scripts/auth-theme.js',
+ 'scripts/notifications.js',
+ 'scripts/registration.js',
+ 'scripts/login.js',
+ 'scripts/admin.js',
+ 'scripts/calendar.js',
+ 'scripts/i18n/ar.js',
+ 'scripts/i18n/az.js',
+ 'scripts/i18n/ca.js',
+ 'scripts/i18n/cs.js',
+ 'scripts/i18n/da.js',
+ 'scripts/i18n/de.js',
+ 'scripts/i18n/el.js',
+ 'scripts/i18n/en.js',
+ 'scripts/i18n/es.js',
+ 'scripts/i18n/fr.js',
+ 'scripts/i18n/hu.js',
+ 'scripts/i18n/id.js',
+ 'scripts/i18n/it.js',
+ 'scripts/i18n/ja.js',
+ 'scripts/i18n/ko.js',
+ 'scripts/i18n/nl.js',
+ 'scripts/i18n/pl.js',
+ 'scripts/i18n/pt.js',
+ 'scripts/i18n/pt_br.js',
+ 'scripts/i18n/ro.js',
+ 'scripts/i18n/ru.js',
+ 'scripts/i18n/sl.js',
+ 'scripts/i18n/sr_lat.js',
+ 'scripts/i18n/sr.js',
+ 'scripts/i18n/tr.js',
+ 'scripts/i18n/uk.js',
+ 'scripts/i18n/vi.js',
+ 'scripts/i18n/zh_cn.js',
+ 'scripts/i18n/zh_tw.js',
+ 'scripts/i18n/getlang.js',
+ 'scripts/libs/apexcharts.min.js',
+ 'scripts/libs/sortable.min.js',
+ 'scripts/libs/qrcode.min.js',
+ 'images/icon/favicon.ico',
+ 'images/icon/favicon-16x16.png',
+ 'images/icon/favicon-32x32.png',
+ 'images/icon/android-chrome-192x192.png',
+ 'images/icon/android-chrome-512x512.png',
+ 'images/icon/maskable_icon_x192.png',
+ 'images/icon/maskable_icon_x512.png',
+ 'images/icon/apple-touch-icon-180.png',
+ 'images/icon/apple-touch-icon-152.png',
+ 'images/icon/apple-touch-icon.png',
+ 'images/screenshots/desktop.png',
+ 'images/siteicons/wallos.png',
+ 'images/siteicons/walloswhite.png',
+ 'images/siteimages/empty.png',
+ 'images/siteimages/mobilenav.png',
+ 'images/siteimages/mobilenavdark.png',
+ 'images/avatars/1.svg',
+ 'images/avatars/2.svg',
+ 'images/avatars/3.svg',
+ 'images/avatars/4.svg',
+ 'images/avatars/5.svg',
+ 'images/avatars/6.svg',
+ 'images/avatars/7.svg',
+ 'images/avatars/8.svg',
+ 'images/avatars/9.svg',
+ 'images/siteicons/svg/logo.php',
+ 'images/siteicons/svg/automatic.php',
+ 'images/siteicons/svg/manual.php',
+ 'images/siteicons/svg/export_ical.php',
+ 'images/siteicons/svg/check.php',
+ 'images/siteicons/svg/mobile-menu/calendar.php',
+ 'images/siteicons/svg/mobile-menu/home.php',
+ 'images/siteicons/svg/mobile-menu/profile.php',
+ 'images/siteicons/svg/mobile-menu/settings.php',
+ 'images/siteicons/svg/mobile-menu/statistics.php',
+ 'images/siteicons/svg/mobile-menu/subscriptions.php',
+ 'images/siteicons/svg/mobile-menu/about.php',
+ 'images/siteicons/svg/mobile-menu/admin.php',
+ 'images/siteicons/svg/mobile-menu/logout.php',
+ 'images/siteicons/svg/mobile-menu/clone.php',
+ 'images/siteicons/svg/mobile-menu/delete.php',
+ 'images/siteicons/svg/mobile-menu/edit.php',
+ 'images/siteicons/svg/mobile-menu/renew.php',
+ 'images/siteicons/pwa/stats.png',
+ 'images/siteicons/pwa/settings.png',
+ 'images/siteicons/pwa/about.png',
+ 'images/siteicons/pwa/calendar.png',
+ 'images/siteicons/pwa/subscriptions.png',
+ 'images/siteicons/pwa/dashboard.png',
+ 'images/uploads/icons/paypal.png',
+ 'images/uploads/icons/creditcard.png',
+ 'images/uploads/icons/banktransfer.png',
+ 'images/uploads/icons/directdebit.png',
+ 'images/uploads/icons/money.png',
+ 'images/uploads/icons/googlepay.png',
+ 'images/uploads/icons/samsungpay.png',
+ 'images/uploads/icons/applepay.png',
+ 'images/uploads/icons/crypto.png',
+ 'images/uploads/icons/klarna.png',
+ 'images/uploads/icons/amazonpay.png',
+ 'images/uploads/icons/sepa.png',
+ 'images/uploads/icons/skrill.png',
+ 'images/uploads/icons/sofort.png',
+ 'images/uploads/icons/stripe.png',
+ 'images/uploads/icons/affirm.png',
+ 'images/uploads/icons/alipay.png',
+ 'images/uploads/icons/elo.png',
+ 'images/uploads/icons/facebookpay.png',
+ 'images/uploads/icons/giropay.png',
+ 'images/uploads/icons/ideal.png',
+ 'images/uploads/icons/unionpay.png',
+ 'images/uploads/icons/interac.png',
+ 'images/uploads/icons/wechat.png',
+ 'images/uploads/icons/paysafe.png',
+ 'images/uploads/icons/poli.png',
+ 'images/uploads/icons/qiwi.png',
+ 'images/uploads/icons/shoppay.png',
+ 'images/uploads/icons/venmo.png',
+ 'images/uploads/icons/verifone.png',
+ 'images/uploads/icons/webmoney.png',
+];
+
+const pagesToPrefetch = [
+ 'index.php',
+ 'subscriptions.php',
+ 'profile.php',
+ 'calendar.php',
+ 'settings.php',
+ 'stats.php',
+ 'about.php',
+ 'login.php',
+ 'admin.php',
+];
+
+// Install: cache static assets in small batches. Firing all ~150 fetches at
+// once starves large files (apexcharts is 600KB) of connections on HTTP/1.1
+// origins, and a dropped one is silently skipped - see the static-asset
+// fetch handler, which backfills anything that slips through here.
+self.addEventListener('install', function (event) {
+ event.waitUntil(
+ caches.open(STATIC_CACHE).then(async function (cache) {
+ const BATCH_SIZE = 12;
+ for (let i = 0; i < staticAssets.length; i += BATCH_SIZE) {
+ await Promise.allSettled(
+ staticAssets.slice(i, i + BATCH_SIZE).map(url =>
+ fetch(url, { cache: 'reload' }).then(response => {
+ if (response.ok) return cache.put(url, response);
+ }).catch(() => {}) // silently skip missing files
+ )
+ );
+ }
+ })
+ );
+ self.skipWaiting();
+});
+
+// Activate: clean up old caches
+self.addEventListener('activate', function (event) {
+ const validCaches = [STATIC_CACHE, PAGES_CACHE, LOGOS_CACHE];
+ event.waitUntil(
+ caches.keys().then(keys =>
+ Promise.all(
+ keys.filter(key => !validCaches.includes(key))
+ .map(key => caches.delete(key))
+ )
+ )
+ );
+ self.clients.claim();
+});
+
+// Message: prefetch pages after login
+self.addEventListener('message', function (event) {
+ if (event.data && event.data.type === 'PREFETCH_PAGES') {
+ caches.open(PAGES_CACHE).then(cache => {
+ pagesToPrefetch.forEach(url => {
+ fetch(url).then(response => {
+ // Only cache if user is actually logged in (no redirect)
+ if (response.ok && !response.redirected) {
+ cache.put(url, response);
+ }
+ }).catch(() => {});
+ });
+ });
+ }
+});
+
+// Fetch: single handler for all requests
+self.addEventListener('fetch', function (event) {
+ const request = event.request;
+ const url = new URL(request.url);
+
+ // Never intercept non-GET requests (POST, etc.)
+ if (request.method !== 'GET') return;
+
+ // Search endpoints must always return their current JSON response. Falling
+ // back to a cached PHP page (especially with ignoreSearch) makes the client
+ // try to parse HTML or another query's data as JSON.
+ if (url.pathname.includes('/endpoints/logos/')) {
+ event.respondWith(fetch(request));
+ return;
+ }
+
+ // Logo images: use cache-first, but cache only successful image responses.
+ // This prevents temporary 404/HTML responses from becoming permanent
+ // broken images. Bumping LOGOS_CACHE removes previously poisoned entries.
+ if (url.pathname.includes('images/uploads/logos')) {
+ event.respondWith(
+ caches.match(request).then(response => {
+ return response || fetch(request).then(networkResponse => {
+ const contentType = networkResponse.headers.get('content-type') || '';
+ if (networkResponse.ok && contentType.startsWith('image/')) {
+ return caches.open(LOGOS_CACHE).then(cache => {
+ cache.put(request, networkResponse.clone());
+ return networkResponse;
+ });
+ }
+ return networkResponse;
+ });
+ })
+ );
+ return;
+ }
+
+ // Static assets: cache-first (they only change on deploy). ignoreSearch
+ // because the pages request these with a "?<version>" cache-buster, while
+ // they're precached under the bare path - without it every asset misses
+ // the cache and the page renders unstyled offline.
+ //
+ // On a miss, fetch AND store the result: the install step fires ~150
+ // parallel fetches and any that fail (a large file like apexcharts, a
+ // dropped connection) are silently skipped, so without this backfill a
+ // once-missed asset would never get cached and its feature (e.g. the
+ // stats charts) would stay broken offline forever.
+ if (staticAssets.some(asset => url.pathname.endsWith(asset))) {
+ event.respondWith(
+ caches.match(request, { ignoreSearch: true }).then(cached => {
+ if (cached) return cached;
+ return fetch(request).then(networkResponse => {
+ if (networkResponse.ok) {
+ const clone = networkResponse.clone();
+ caches.open(STATIC_CACHE).then(cache => cache.put(request, clone));
+ }
+ return networkResponse;
+ });
+ })
+ );
+ return;
+ }
+
+ // PHP pages and everything else: network-first, cache as fallback
+ // Also update the pages cache on every successful load
+ event.respondWith(
+ fetch(request).then(response => {
+ if (response.ok && !response.redirected) {
+ const responseClone = response.clone(); // clone before any async operation
+ caches.open(PAGES_CACHE).then(cache => {
+ cache.put(request, responseClone);
+ });
+ }
+ return response;
+ }).catch(() => {
+ return caches.match(request, { ignoreSearch: true });
+ })
+ );
+});
+
+// Web Push (RFC 8291/8292): the payload includes/webpush_helper.php sends is
+// {"title": ..., "body": ...} JSON, decrypted by the browser itself before
+// this handler ever sees it - nothing here has to know that aes128gcm
+// happened at all.
+self.addEventListener('push', function (event) {
+ let data = {};
+
+ if (event.data) {
+ try {
+ data = event.data.json();
+ } catch (e) {
+ data = { title: 'Wallos', body: event.data.text() };
+ }
+ }
+
+ const title = data.title || 'Wallos';
+ const options = {
+ body: data.body || '',
+ icon: 'images/icon/android-chrome-192x192.png',
+ badge: 'images/icon/android-chrome-192x192.png',
+ data: { url: data.url || './' },
+ };
+
+ event.waitUntil(self.registration.showNotification(title, options));
+});
+
+self.addEventListener('notificationclick', function (event) {
+ event.notification.close();
+
+ const targetUrl = (event.notification.data && event.notification.data.url) || './';
+
+ event.waitUntil(
+ clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (windowClients) {
+ // Focus a tab that already has the app open, rather than piling
+ // up a new one every time a notification is tapped.
+ for (const client of windowClients) {
+ if (client.url.includes(self.registration.scope) && 'focus' in client) {
+ return client.focus();
+ }
+ }
+
+ if (clients.openWindow) {
+ return clients.openWindow(targetUrl);
+ }
+ })
+ );
+});
diff --git a/settings.php b/settings.php
index dfd4579..f85f755 100644
--- a/settings.php
+++ b/settings.php
@@ -1,1792 +1,1792 @@
-<?php
-require_once 'includes/header.php';
-require_once 'includes/upcoming_payments.php';
-require_once 'includes/webpush_helper.php';
-
-$currencies = array();
-$query = "SELECT * FROM currencies WHERE user_id = :userId";
-$query = $db->prepare($query);
-$query->bindValue(':userId', $userId, SQLITE3_INTEGER);
-$result = $query->execute();
-while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $currencyId = $row['id'];
- $currencies[$currencyId] = $row;
-}
-$userData['currency_symbol'] = $currencies[$main_currency]['symbol'];
-$budgetPeriodType = $userData['budget_period_type'] ?? 'monthly';
-$budgetPeriodAnchorDate = $userData['budget_period_anchor_date'] ?? date('Y-m-d');
-if ($budgetPeriodAnchorDate === '1970-01-01' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $budgetPeriodAnchorDate)) {
- $budgetPeriodAnchorDate = date('Y-m-d');
-}
-$upcomingPaymentsLimit = normalize_upcoming_payments_limit($settings['upcoming_payments_limit'] ?? 3);
-
-?>
-
-<script src="scripts/libs/sortable.min.js"></script>
-<style>
- .logo-preview:after {
- content: '<?= translate('upload_logo', $i18n) ?>';
- }
-
- .period-budget-controls {
- align-items: flex-end;
- flex-wrap: wrap;
- gap: 12px 15px;
- }
-
- .period-budget-controls .period-budget-field {
- display: flex;
- flex-direction: column;
- flex: 1 1 180px;
- min-width: 160px;
- gap: 8px;
- }
-
- .period-budget-controls .period-budget-field label {
- margin-bottom: 0;
- line-height: 1.2;
- }
-
- .period-budget-controls .period-budget-save {
- flex: 0 0 auto;
- }
-
- .period-budget-controls #budget_period_anchor_date {
- display: block;
- height: 50px;
- min-height: 50px;
- }
-
- @media (min-width: 421px) and (max-width: 768px) {
- .period-budget-controls .period-budget-field {
- flex: 1 1 calc(50% - 8px);
- min-width: 0;
- }
-
- .period-budget-controls .period-budget-save {
- width: 100%;
- }
- }
-
- @media (max-width: 420px) {
- .period-budget-controls .period-budget-field {
- flex: 1 1 100%;
- min-width: 0;
- }
-
- .period-budget-controls .period-budget-save {
- width: 100%;
- }
- }
-</style>
-<section class="contain settings">
-
- <section class="account-section">
- <header>
- <h2><?= translate('monthly_budget', $i18n) ?></h2>
- </header>
- <div class="account-budget">
- <div class="form-group-inline">
- <label for="monthly_budget"><?= $userData['currency_symbol'] ?></label>
- <input type="number" id="monthly_budget" name="monthly_budget" autocomplete="off" value="<?= $userData['budget'] ?>"
- placeholder="Budget">
- <input type="submit" value="<?= translate('save', $i18n) ?>" id="saveMonthlyBudget" onClick="saveMonthlyBudget()" />
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i> <?= translate('monthly_budget_info', $i18n) ?>
- </p>
- </div>
- </div>
- </section>
-
- <section class="account-section">
- <header>
- <h2><?= translate('period_budget', $i18n) ?></h2>
- </header>
- <div class="account-budget">
- <div class="form-group-inline">
- <label for="period_budget"><?= $userData['currency_symbol'] ?></label>
- <input type="number" id="period_budget" name="period_budget" autocomplete="off" value="<?= $userData['period_budget'] ?? 0 ?>"
- placeholder="Budget">
- </div>
- <div class="form-group-inline period-budget-controls">
- <div class="period-budget-field">
- <label for="budget_period_type"><?= translate('budget_period', $i18n) ?></label>
- <select id="budget_period_type" name="budget_period_type">
- <option value="weekly" <?= $budgetPeriodType === 'weekly' ? 'selected' : '' ?>><?= translate('weekly', $i18n) ?></option>
- <option value="fortnightly" <?= $budgetPeriodType === 'fortnightly' ? 'selected' : '' ?>><?= translate('fortnightly', $i18n) ?></option>
- <option value="monthly" <?= $budgetPeriodType === 'monthly' ? 'selected' : '' ?>><?= translate('monthly', $i18n) ?></option>
- </select>
- </div>
- <div class="period-budget-field">
- <label for="budget_period_anchor_date"><?= translate('budget_anchor_date', $i18n) ?></label>
- <input type="date" id="budget_period_anchor_date" name="budget_period_anchor_date"
- value="<?= htmlspecialchars($budgetPeriodAnchorDate, ENT_QUOTES, 'UTF-8') ?>">
- </div>
- <input type="submit" value="<?= translate('save', $i18n) ?>" id="savePeriodBudget" class="period-budget-save" onClick="savePeriodBudget()" />
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i> <?= translate('period_budget_info', $i18n) ?>
- </p>
- </div>
- </div>
- </section>
-
- <?php
- $sql = "SELECT * FROM household WHERE user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- if ($result) {
- $household = array();
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $household[] = $row;
- }
- }
- ?>
-
- <section class="account-section">
- <header>
- <h2><?= translate('household', $i18n) ?></h2>
- </header>
- <div class="account-members">
- <div id="householdMembers">
- <?php
- foreach ($household as $index => $member) {
- ?>
- <div class="form-group-inline" data-memberid="<?= $member['id'] ?>">
- <input type="text" name="member" autocomplete="off" value="<?= htmlspecialchars($member['name']) ?>"
- placeholder="Member">
- <?php
- if ($index !== 0) {
- ?>
- <input type="text" name="email" autocomplete="off" value="<?= htmlspecialchars($member['email'] ?? "") ?>"
- placeholder="<?= translate("email", $i18n) ?>">
- <?php
- }
- ?>
- <button class="image-button medium" onClick="editMember(<?= $member['id'] ?>)" name="save"
- title="<?= translate('save_member', $i18n) ?>">
- <i class="fa-solid fa-check"></i>
- </button>
- <?php
- if ($index !== 0) {
- ?>
- <button class="image-button medium" onClick="removeMember(<?= $member['id'] ?>)"
- title="<?= translate('delete_member', $i18n) ?>">
- <i class="fa-solid fa-trash-can"></i>
- </button>
- <?php
- } else {
- ?>
- <button class="image-button medium disabled" title="<?= translate('cant_delete_member', $i18n) ?>">
- <i class="fa-solid fa-trash-can"></i>
- </button>
- <?php
- }
- ?>
- </div>
- <?php
- }
- ?>
- </div>
- <div class="buttons">
- <input type="submit" value="<?= translate('add', $i18n) ?>" id="addMember" onClick="addMemberButton()"
- class="thin mobile-grow" />
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i> <?= translate('household_info', $i18n) ?>
- </p>
- <p>
- </div>
- </div>
- </section>
-
- <?php
- // Notification settings
- $sql = "SELECT * FROM notification_settings WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notifications = $row;
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notifications['days'] = 1;
- $notifications['period_summary_at_period_start'] = 0;
- } else if (!isset($notifications['period_summary_at_period_start'])) {
- $notifications['period_summary_at_period_start'] = 0;
- }
-
- // Email notifications
- $sql = "SELECT * FROM email_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsEmail['enabled'] = $row['enabled'];
- $notificationsEmail['smtp_address'] = $row['smtp_address'];
- $notificationsEmail['smtp_port'] = $row['smtp_port'];
- $notificationsEmail['encryption'] = $row['encryption'];
- $notificationsEmail['smtp_username'] = $row['smtp_username'];
- $notificationsEmail['smtp_password'] = $row['smtp_password'];
- $notificationsEmail['from_email'] = $row['from_email'];
- $notificationsEmail['other_emails'] = $row['other_emails'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsEmail['enabled'] = 0;
- $notificationsEmail['smtp_address'] = "";
- $notificationsEmail['smtp_port'] = 587;
- $notificationsEmail['encryption'] = "tls";
- $notificationsEmail['smtp_username'] = "";
- $notificationsEmail['smtp_password'] = "";
- $notificationsEmail['from_email'] = "";
- $notificationsEmail['other_emails'] = "";
- }
-
- // Discord notifications
- $sql = "SELECT * FROM discord_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsDiscord['enabled'] = $row['enabled'];
- $notificationsDiscord['webhook_url'] = $row['webhook_url'];
- $notificationsDiscord['bot_username'] = $row['bot_username'];
- $notificationsDiscord['bot_avatar'] = $row['bot_avatar_url'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsDiscord['enabled'] = 0;
- $notificationsDiscord['webhook_url'] = "";
- $notificationsDiscord['bot_username'] = "";
- $notificationsDiscord['bot_avatar'] = "";
- }
-
- // Pushover notifications
- $sql = "SELECT * FROM pushover_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsPushover['enabled'] = $row['enabled'];
- $notificationsPushover['token'] = $row['token'];
- $notificationsPushover['user_key'] = $row['user_key'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsPushover['enabled'] = 0;
- $notificationsPushover['token'] = "";
- $notificationsPushover['user_key'] = "";
- }
-
- // Telegram notifications
- $sql = "SELECT * FROM telegram_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsTelegram['enabled'] = $row['enabled'];
- $notificationsTelegram['bot_token'] = $row['bot_token'];
- $notificationsTelegram['chat_id'] = $row['chat_id'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsTelegram['enabled'] = 0;
- $notificationsTelegram['bot_token'] = "";
- $notificationsTelegram['chat_id'] = "";
- }
-
-
- // PushPlus notifications
- $sql = "SELECT * FROM pushplus_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsPushPlus['enabled'] = $row['enabled'];
- $notificationsPushPlus['token'] = $row['token'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsPushPlus['enabled'] = 0;
- $notificationsPushPlus['token'] = "";
- }
-
- // Mattermost notifications
- $sql = "SELECT * FROM mattermost_notifications WHERE user_id = :userID LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userID', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsMattermost['enabled'] = $row['enabled'];
- $notificationsMattermost['webhook_url'] = $row['webhook_url'];
- $notificationsMattermost['bot_username'] = $row['bot_username'];
- $notificationsMattermost['bot_icon_emoji'] = $row['bot_icon_emoji'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsMattermost['enabled'] = 0;
- $notificationsMattermost['webhook_url'] = "";
- $notificationsMattermost['bot_username'] = "";
- $notificationsMattermost['bot_icon_emoji'] = "";
- }
-
- // Serverchan notifications
- $sql = "SELECT * FROM serverchan_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsServerchan['enabled'] = $row['enabled'];
- $notificationsServerchan['sendkey'] = $row['sendkey'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsServerchan['enabled'] = 0;
- $notificationsServerchan['sendkey'] = "";
- }
-
- // Ntfy notifications
- $sql = "SELECT * FROM ntfy_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsNtfy['enabled'] = $row['enabled'];
- $notificationsNtfy['host'] = $row['host'];
- $notificationsNtfy['topic'] = $row['topic'];
- $notificationsNtfy['headers'] = $row['headers'];
- $notificationsNtfy['ignore_ssl'] = $row['ignore_ssl'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsNtfy['enabled'] = 0;
- $notificationsNtfy['host'] = "";
- $notificationsNtfy['topic'] = "";
- $notificationsNtfy['headers'] = "";
- $notificationsNtfy['ignore_ssl'] = 0;
- }
-
- // Push notifications
- $sql = "SELECT * FROM push_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsPush['enabled'] = $row['enabled'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsPush['enabled'] = 0;
- }
-
- $pushSubscriptions = [];
- $sql = "SELECT id, user_agent, created_at FROM push_subscriptions WHERE user_id = :userId ORDER BY id";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $pushSubscriptions[] = $row;
- }
-
- // Generated lazily on first visit to this page for an installation that
- // has never needed one before - see webpush_get_vapid_keys()'s own
- // comment for why this lives on the admin row rather than per user.
- $vapidPublicKey = '';
- $vapidKeys = webpush_get_vapid_keys($db);
- if ($vapidKeys !== false) {
- $vapidPublicKey = $vapidKeys['public'];
- }
-
- // Webhook notifications
- $sql = "SELECT * FROM webhook_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsWebhook['enabled'] = $row['enabled'];
- $notificationsWebhook['url'] = $row['url'];
- $notificationsWebhook['request_method'] = $row['request_method'];
- $notificationsWebhook['headers'] = $row['headers'];
- $notificationsWebhook['payload'] = $row['payload'];
- $notificationsWebhook['cancelation_payload'] = $row['cancelation_payload'];
- $notificationsWebhook['ignore_ssl'] = $row['ignore_ssl'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsWebhook['enabled'] = 0;
- $notificationsWebhook['url'] = "";
- $notificationsWebhook['request_method'] = "POST";
- $notificationsWebhook['headers'] = "";
- $notificationsWebhook['payload'] = '
-{
- "name": "{{subscription_name}}",
- "price": "{{subscription_price}}",
- "currency": "{{subscription_currency}}",
- "category": "{{subscription_category}}",
- "date": "{{subscription_date}}",
- "payer": "{{subscription_payer}}",
- "days": "{{subscription_days_until_payment}}",
- "notes": "{{subscription_notes}}",
- "url": "{{subscription_url}}"
-}';
- $notificationsWebhook['cancelation_payload'] = "";
- $notificationsWebhook['ignore_ssl'] = 0;
- }
-
- // Gotify notifications
- $sql = "SELECT * FROM gotify_notifications WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $rowCount = 0;
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $notificationsGotify['enabled'] = $row['enabled'];
- $notificationsGotify['url'] = $row['url'];
- $notificationsGotify['token'] = $row['token'];
- $notificationsGotify['ignore_ssl'] = $row['ignore_ssl'];
- $rowCount++;
- }
-
- if ($rowCount == 0) {
- $notificationsGotify['enabled'] = 0;
- $notificationsGotify['url'] = "";
- $notificationsGotify['token'] = "";
- $notificationsGotify['ignore_ssl'] = 0;
- }
-
- ?>
-
- <section class="account-section">
- <header>
- <h2><?= translate('notifications', $i18n) ?></h2>
- </header>
- <div class="account-notifications">
- <section>
- <label for="days"><?= translate('notify_me', $i18n) ?>:</label>
- <div class="form-group-inline">
- <select name="days" id="days">
- <option value="0" <?= $notifications['days'] == 0 ? "selected" : "" ?>>
- <?= translate('on_due_date', $i18n) ?>
- </option>
- <option value="1" <?= $notifications['days'] == 1 ? "selected" : "" ?>>
- 1 <?= translate('day_before', $i18n) ?>
- </option>
- <?php
- for ($i = 2; $i <= 7; $i++) {
- $selected = $i == $notifications['days'] ? "selected" : "";
- ?>
- <option value="<?= $i ?>" <?= $selected ?>>
- <?= $i ?> <?= translate('days_before', $i18n) ?>
- </option>
- <?php
- }
- ?>
- </select>
- <input type="submit" class="thin" value="<?= translate('save', $i18n) ?>" id="saveNotifications"
- onClick="saveNotifications()" />
- </div>
- <div class="form-group-inline">
- <input type="checkbox" id="period_summary_at_period_start" name="period_summary_at_period_start"
- <?= !empty($notifications['period_summary_at_period_start']) ? "checked" : "" ?>>
- <label for="period_summary_at_period_start">
- <?= translate('send_period_summary_at_period_start', $i18n) ?>
- </label>
- </div>
- </section>
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('email')">
- <h3>
- <i class="fa-solid fa-envelope"></i>
- <?= translate('email', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="email">
- <div class="form-group-inline">
- <input type="checkbox" id="emailenabled" name="emailenabled" <?= $notificationsEmail['enabled'] ? "checked" : "" ?>>
- <label for="emailenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group-inline">
- <input type="text" name="smtpaddress" id="smtpaddress" autocomplete="off"
- placeholder="<?= translate('smtp_address', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsEmail['smtp_address']) ?>" />
- <input type="text" name="smtpport" id="smtpport" autocomplete="off"
- placeholder="<?= translate('port', $i18n) ?>" class="one-third"
- value="<?= htmlspecialchars($notificationsEmail['smtp_port']) ?>" />
- </div>
- <div class="form-group-inline">
- <div>
- <input type="radio" name="encryption" id="encryptionnone" value="none"
- <?= $notificationsEmail['encryption'] == "none" ? "checked" : "" ?> />
- <label for="encryptionnone"><?= translate('none', $i18n) ?></label>
- </div>
- <div>
- <input type="radio" name="encryption" id="encryptiontls" value="tls"
- <?= $notificationsEmail['encryption'] == "tls" ? "checked" : "" ?> />
- <label for="encryptiontls"><?= translate('tls', $i18n) ?></label>
- </div>
- <div>
- <input type="radio" name="encryption" id="encryptionssl" value="ssl"
- <?= $notificationsEmail['encryption'] == "ssl" ? "checked" : "" ?> />
- <label for="encryptionssl"><?= translate('ssl', $i18n) ?></label>
- </div>
-
-
- </div>
- <div class="form-group-inline">
- <input type="text" name="smtpusername" id="smtpusername" autocomplete="off"
- placeholder="<?= translate('smtp_username', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsEmail['smtp_username']) ?>" />
- </div>
- <div class="form-group-inline">
- <input type="password" name="smtppassword" id="smtppassword" autocomplete="off"
- placeholder="<?= translate('smtp_password', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsEmail['smtp_password']) ?>" />
- </div>
- <div class="form-group-inline">
- <input type="text" name="fromemail" id="fromemail" autocomplete="off"
- placeholder="<?= translate('from_email', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsEmail['from_email']) ?>" />
- </div>
- <label for="otheremails"><?= translate('send_to_other_emails', $i18n) ?></label>
- <div class="form-group-inline">
- <input type="text" name="otheremails" id="otheremails" autocomplete="off"
- placeholder="<?= translate('other_emails_placeholder', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsEmail['other_emails']) ?>" />
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsEmail"
- onClick="testNotificationEmailButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsEmail" onClick="saveNotificationsEmailButton()" />
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i> <?= translate('smtp_info', $i18n) ?>
- </p>
- <p>
- </div>
- </div>
- </section>
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('discord');">
- <h3>
- <i class="fa-brands fa-discord"></i>
- <?= translate('discord', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="discord">
- <div class="form-group-inline">
- <input type="checkbox" id="discordenabled" name="discordenabled"
- <?= $notificationsDiscord['enabled'] ? "checked" : "" ?>>
- <label for="discordenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group-inline">
- <input type="text" name="discordurl" id="discordurl" autocomplete="off"
- placeholder="<?= translate('webhook_url', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsDiscord['webhook_url']) ?>" />
- </div>
- <div class="form-group-inline">
- <input type="text" name="discordbotusername" id="discordbotusername" autocomplete="off"
- placeholder="<?= translate('discord_bot_username', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsDiscord['bot_username']) ?>" />
- </div>
- <div class="form-group-inline">
- <input type="text" name="discordbotavatar" id="discordbotavatar" autocomplete="off"
- placeholder="<?= translate('discord_bot_avatar_url', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsDiscord['bot_avatar']) ?>" />
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsDiscord"
- onClick="testNotificationsDiscordButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsDiscord" onClick="saveNotificationsDiscordButton()" />
- </div>
- </div>
- </section>
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('gotify');">
- <h3>
- <i class="fa-solid fa-envelopes-bulk"></i>
- <?= translate('gotify', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="gotify">
- <div class="form-group-inline">
- <input type="checkbox" id="gotifyenabled" name="gotifyenabled"
- <?= $notificationsGotify['enabled'] ? "checked" : "" ?>>
- <label for="gotifyenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group-inline">
- <input type="text" name="gotifyurl" id="gotifyurl" autocomplete="off"
- placeholder="<?= translate('url', $i18n) ?>" value="<?= htmlspecialchars($notificationsGotify['url']) ?>" />
- </div>
- <div class="form-group-inline">
- <input type="text" name="gotifytoken" id="gotifytoken" autocomplete="off"
- placeholder="<?= translate('token', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsGotify['token']) ?>" />
- </div>
- <div class="form-group-inline">
- <input type="checkbox" id="gotifyignoressl" name="gotifyignoressl"
- <?= $notificationsGotify['ignore_ssl'] ? "checked" : "" ?>>
- <label for="gotifyignoressl"><?= translate('ignore_ssl_errors', $i18n) ?></label>
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsGotify"
- onClick="testNotificationsGotifyButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsGotify" onClick="saveNotificationsGotifyButton()" />
- </div>
- </div>
- </section>
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('pushover');">
- <h3>
- <i class="fa-brands fa-pinterest-p"></i>
- <?= translate('pushover', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="pushover">
- <div class="form-group-inline">
- <input type="checkbox" id="pushoverenabled" name="pushoverenabled"
- <?= $notificationsPushover['enabled'] ? "checked" : "" ?>>
- <label for="pushoverenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group-inline">
- <input type="text" name="pushoveruserkey" id="pushoveruserkey" autocomplete="off"
- placeholder="<?= translate('pushover_user_key', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsPushover['user_key']) ?>" />
- </div>
- <div class="form-group-inline">
- <input type="text" name="pushovertoken" id="pushovertoken" autocomplete="off"
- placeholder="<?= translate('token', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsPushover['token']) ?>" />
- </div>
-
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsPushover"
- onClick="testNotificationsPushoverButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsPushover" onClick="saveNotificationsPushoverButton()" />
- </div>
- </div>
- </section>
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('telegram');">
- <h3>
- <i class="fa-solid fa-paper-plane"></i>
- <?= translate('telegram', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="telegram">
- <div class="form-group-inline">
- <input type="checkbox" id="telegramenabled" name="telegramenabled"
- <?= $notificationsTelegram['enabled'] ? "checked" : "" ?>>
- <label for="telegramenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group-inline">
- <input type="text" name="telegrambottoken" id="telegrambottoken" autocomplete="off"
- placeholder="<?= translate('telegram_bot_token', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsTelegram['bot_token'] ? $notificationsTelegram['bot_token'] : "") ?>" />
- </div>
- <div class="form-group-inline">
- <input type="text" name="telegramchatid" id="telegramchatid" autocomplete="off"
- placeholder="<?= translate('telegram_chat_id', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsTelegram['chat_id']) ?>" />
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsTelegram"
- onClick="testNotificationsTelegramButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsTelegram" onClick="saveNotificationsTelegramButton()" />
- </div>
- </div>
- </section>
-
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('pushplus');">
- <h3>
- <i class="fa-solid fa-bell"></i>
- <?= translate('pushplus', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="pushplus">
- <div class="form-group-inline">
- <input type="checkbox" id="pushplusenabled" name="pushplusenabled"
- <?= $notificationsPushPlus['enabled'] ? "checked" : "" ?>>
- <label for="pushplusenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group-inline">
- <input type="text" name="pushplustoken" id="pushplustoken" autocomplete="off"
- placeholder="<?= translate('pushplus_token', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsPushPlus['token'] ? $notificationsPushPlus['token'] : '') ?>" />
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsPushPlus"
- onClick="testNotificationsPushPlusButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsPushPlus" onClick="saveNotificationsPushPlusButton()" />
- </div>
- </div>
- </section>
-
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('mattermost');">
- <h3>
- <i class="fa-solid fa-gauge-simple-high"></i>
- <?= translate('mattermost', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="mattermost">
- <div class="form-group-inline">
- <input type="checkbox" id="mattermostenabled" name="mattermostenabled"
- <?= $notificationsMattermost['enabled'] ? "checked" : "" ?>>
- <label for="mattermostenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group-inline">
- <input type="text" name="mattermostwebhookurl" id="mattermostwebhookurl"
- placeholder="<?= translate('mattermost_webhook_url', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsMattermost['webhook_url'] ? $notificationsMattermost['webhook_url'] : '') ?>" />
- </div>
- <div class="form-group-inline">
- <input type="text" name="mattermostbotusername" id="mattermostbotusername"
- placeholder="<?= translate('mattermost_bot_username', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsMattermost['bot_username'] ? $notificationsMattermost['bot_username'] : '') ?>" />
- </div>
- <div class="form-group-inline">
- <input type="text" name="mattermostboticonemoji" id="mattermostboticonemoji"
- placeholder="<?= translate('mattermost_bot_icon_emoji', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsMattermost['bot_icon_emoji'] ? $notificationsMattermost['bot_icon_emoji'] : '') ?>" />
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsMattermost"
- onClick="testNotificationsMattermostButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsMattermost" onClick="saveNotificationsMattermostButton()" />
- </div>
- </div>
- </section>
-
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('ntfy');">
- <h3>
- <i class="fa-solid fa-terminal"></i> Ntfy
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="ntfy">
- <div class="form-group-inline">
- <input type="checkbox" id="ntfyenabled" name="ntfyenabled" <?= $notificationsNtfy['enabled'] ? "checked" : "" ?>>
- <label for="ntfyenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group-inline">
- <input type="text" name="ntfyhost" id="ntfyhost" autocomplete="off"
- placeholder="<?= translate('host', $i18n) ?>" value="<?= htmlspecialchars($notificationsNtfy['host']) ?>" />
- </div>
- <div class="form-group-inline">
- <input type="text" name="ntfytopic" id="ntfytopic" autocomplete="off"
- placeholder="<?= translate('topic', $i18n) ?>" value="<?= htmlspecialchars($notificationsNtfy['topic']) ?>" />
- </div>
- <div class="form-group-inline">
- <textarea class="thin" name="ntfyheaders" id="ntfyheaders"
- placeholder="<?= translate('custom_headers', $i18n) ?>"><?= htmlspecialchars($notificationsNtfy['headers']) ?></textarea>
- </div>
- <div class="form-grpup-inline">
- <input type="checkbox" id="ntfyignoressl" name="ntfyignoressl"
- <?= $notificationsNtfy['ignore_ssl'] ? "checked" : "" ?>>
- <label for="ntfyignoressl"><?= translate('ignore_ssl_errors', $i18n) ?></label>
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsNtfy"
- onClick="testNotificationsNtfyButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsNtfy" onClick="saveNotificationsNtfyButton()" />
- </div>
- </section>
-
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('push');">
- <h3>
- <i class="fa-solid fa-bell"></i> <?= translate('push_notifications', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="push">
- <div class="form-group-inline">
- <input type="checkbox" id="pushenabled" name="pushenabled" <?= $notificationsPush['enabled'] ? "checked" : "" ?>>
- <label for="pushenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="push-devices-list" id="pushDevicesList">
- <?php if (empty($pushSubscriptions)): ?>
- <p id="noPushDevices" class="push-no-devices"><?= translate('no_devices_registered', $i18n) ?></p>
- <?php else: ?>
- <?php foreach ($pushSubscriptions as $subscription): ?>
- <div class="push-device-row" data-subscriptionid="<?= (int) $subscription['id'] ?>">
- <span class="push-device-name">
- <?= htmlspecialchars($subscription['user_agent'] !== '' ? $subscription['user_agent'] : translate('unknown_device', $i18n)) ?>
- </span>
- <button type="button" class="secondary-button thin" onclick="removePushSubscriptionButton(<?= (int) $subscription['id'] ?>)">
- <?= translate('delete', $i18n) ?>
- </button>
- </div>
- <?php endforeach; ?>
- <?php endif; ?>
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i>
- <?= translate('push_notifications_info', $i18n) ?>
- </p>
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsPush"
- onClick="testNotificationsPushButton()" />
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('enable_on_this_device', $i18n) ?>" id="subscribePushButton"
- onClick="subscribePushButtonClick()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsPush" onClick="saveNotificationsPushButton()" />
- </div>
- </div>
- </section>
-
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('serverchan');">
- <h3>
- <i class="fa-solid fa-code"></i>
- <?= translate('serverchan', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="serverchan">
- <div class="form-group-inline">
- <input type="checkbox" id="serverchanenabled" name="serverchanenabled"
- <?= $notificationsServerchan['enabled'] ? "checked" : "" ?>>
- <label for="serverchanenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group-inline">
- <input type="text" name="serverchansendkey" id="serverchansendkey" autocomplete="off"
- placeholder="<?= translate('serverchan_sendkey', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsServerchan['sendkey'] ? $notificationsServerchan['sendkey'] : '') ?>" />
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsServerchan"
- onClick="testNotificationsServerchanButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsServerchan" onClick="saveNotificationsServerchanButton()" />
- </div>
- </div>
- </section>
-
- <section class="account-notifications-section">
- <header class="account-notification-section-header" onclick="openNotificationsSettings('webhook');">
- <h3>
- <i class="fa-solid fa-bolt"></i>
- <?= translate('webhook', $i18n) ?>
- </h3>
- </header>
- <div class="account-notification-section-settings" data-type="webhook">
- <div class="form-group-inline">
- <input type="checkbox" id="webhookenabled" name="webhookenabled"
- <?= $notificationsWebhook['enabled'] ? "checked" : "" ?>>
- <label for="webhookenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div>
- <label for="webhookrequestmethod"
- class="capitalize"><?= translate('request_method', $i18n) ?>:</label>
- <div class="form-group-inline">
- <select name="webhookrequestmethod" id="webhookrequestmethod">
- <option value="GET" <?= $notificationsWebhook['request_method'] == 'GET' ? 'selected' : '' ?>>GET</option>
- <option value="POST" <?= $notificationsWebhook['request_method'] == 'POST' ? 'selected' : '' ?>>POST</option>
- <option value="PUT" <?= $notificationsWebhook['request_method'] == 'PUT' ? 'selected' : '' ?>>PUT</option>
- </select>
- </div>
- </div>
- <div class="form-group-inline">
- <input type="text" name="webhookurl" id="webhookurl" autocomplete="off"
- placeholder="<?= translate('webhook_url', $i18n) ?>"
- value="<?= htmlspecialchars($notificationsWebhook['url']) ?>" />
- </div>
- <div class="form-group-inline">
- <textarea class="thin" name="webhookcustomheaders" id="webhookcustomheaders"
- placeholder="<?= translate('custom_headers', $i18n) ?>"><?= htmlspecialchars($notificationsWebhook['headers']) ?></textarea>
- </div>
- <div class="form-group-inline">
- <textarea name="webhookpayload" id="webhookpayload"
- placeholder="<?= translate('payment_notifications_payload', $i18n) ?>"><?= htmlspecialchars($notificationsWebhook['payload']) ?></textarea>
- </div>
- <div class="form-group-inline">
- <textarea name="webhookcancelationpayload" id="webhookcancelationpayload"
- placeholder="<?= translate('cancelation_notification_payload', $i18n) ?>"><?= htmlspecialchars($notificationsWebhook['cancelation_payload']) ?></textarea>
- </div>
- <div class="form-group-inline">
- <input type="checkbox" id="webhookignoressl" name="webhookignoressl"
- <?= $notificationsWebhook['ignore_ssl'] ? "checked" : "" ?>>
- <label for="webhookignoressl"><?= translate('ignore_ssl_errors', $i18n) ?></label>
- </div>
- <div class="buttons">
- <input type="button" class="secondary-button thin mobile-grow"
- value="<?= translate('test', $i18n) ?>" id="testNotificationsWebhook"
- onClick="testNotificationsWebhookButton()" />
- <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
- id="saveNotificationsWebhook" onClick="saveNotificationsWebhookButton()" />
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i> <?= translate('variables_available', $i18n) ?>:
- {{days_until}}, {{subscription_name}}, {{subscription_price}}, {{subscription_currency}},
- {{subscription_category}}, {{subscription_date}}, {{subscription_payer}},
- {{subscription_days_until_payment}}, {{subscription_notes}}, {{subscription_url}}
- </p>
- <p>
- </div>
- </div>
- </section>
- </div>
- </section>
-
- <?php
- $sql = "SELECT * FROM categories WHERE user_id = :userId ORDER BY `order` ASC";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- if ($result) {
- $categories = array();
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $categories[] = $row;
- }
- }
- ?>
-
- <?php
- $sql = "SELECT * FROM ai_settings WHERE user_id = :userId LIMIT 1";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- $aiSettings = [];
- if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $aiSettings = $row;
- }
-
- $canTranslateCategories = !empty($aiSettings['enabled']) && !empty($aiSettings['model']) && $lang != 'en';
- ?>
-
- <section class="account-section">
- <header>
- <h2><?= translate('categories', $i18n) ?></h2>
- </header>
- <div class="account-categories">
- <div id="categories" class="sortable-list">
- <?php
- foreach ($categories as $category) {
- if ($category['id'] != 1) {
- $canDelete = true;
-
- $query = "SELECT COUNT(*) as count FROM subscriptions WHERE (category_id = :categoryId OR id IN (SELECT subscription_id FROM subscription_categories WHERE category_id = :categoryId)) AND user_id = :userId";
- $stmt = $db->prepare($query);
- $stmt->bindParam(':categoryId', $category['id'], SQLITE3_INTEGER);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $isUsed = $row['count'];
-
- if ($isUsed > 0) {
- $canDelete = false;
- }
- ?>
- <div class="form-group-inline" data-categoryid="<?= $category['id'] ?>">
- <div class=" drag-icon"><i class="fa-solid fa-grip-vertical"></i></div>
- <input type="text" name="category" autocomplete="off" value="<?= htmlspecialchars($category['name']) ?>"
- placeholder="Category">
- <button class="image-button medium" onClick="editCategory(<?= $category['id'] ?>)" name="save"
- title="<?= translate('save_category', $i18n) ?>">
- <i class="fa-solid fa-check"></i>
- </button>
- <?php
- if ($canDelete) {
- ?>
- <button class="image-button medium" onClick="removeCategory(<?= $category['id'] ?>)"
- title="<?= translate('delete_category', $i18n) ?>">
- <i class="fa-solid fa-trash-can"></i>
- </button>
- <?php
- } else {
- ?>
- <button class="image-button medium disabled"
- title="<?= translate('cant_delete_category_in_use', $i18n) ?>">
- <i class="fa-solid fa-trash-can"></i>
- </button>
- <?php
- }
- ?>
- </div>
- <?php
- }
- }
- ?>
- </div>
- <div class="buttons">
- <input type="submit" value="<?= translate('add', $i18n) ?>" id="addCategory"
- onClick="addCategoryButton()" class="thin mobile-grow" />
- <?php
- if ($canTranslateCategories) {
- ?>
- <button type="button" class="button secondary-button thin mobile-grow" id="translateCategories"
- onClick="translateCategories()">
- <i class="fa-solid fa-language"></i>
- <?= translate('translate_categories', $i18n) ?>
- </button>
- <?php
- }
- ?>
- </div>
- </div>
- </section>
-
- <?php
- $sql = "SELECT * FROM currencies WHERE user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- if ($result) {
- $currencies = array();
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $currencies[] = $row;
- }
- }
-
- $query = "SELECT main_currency FROM user WHERE id = :userId";
- $stmt = $db->prepare($query);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $mainCurrencyId = $row['main_currency'];
-
- $query = "SELECT date FROM last_exchange_update";
- $exchange_rates_last_updated = $db->querySingle($query);
-
- ?>
-
- <section class="account-section">
- <header>
- <h2><?= translate('currencies', $i18n) ?></h2>
- </header>
- <div class="account-currencies">
- <div id="currencies">
- <?php
- foreach ($currencies as $currency) {
- $canDelete = true;
- $isMainCurrency = false;
- if ($currency['id'] === $mainCurrencyId) {
- $canDelete = false;
- $isMainCurrency = true;
- } else {
- $query = "SELECT COUNT(*) as count FROM subscriptions WHERE currency_id = :currencyId";
- $stmt = $db->prepare($query);
- $stmt->bindParam(':currencyId', $currency['id'], SQLITE3_INTEGER);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $isUsed = $row['count'];
-
- if ($isUsed > 0) {
- $canDelete = false;
- }
- }
- ?>
-
- <div class="form-group-inline" data-currencyid="<?= $currency['id'] ?>">
- <input type="text" class="short" name="symbol" autocomplete="off" value="<?= htmlspecialchars($currency['symbol']) ?>"
- placeholder="$">
- <input type="text" name="currency" autocomplete="off" value="<?= htmlspecialchars($currency['name']) ?>"
- placeholder="Currency Name">
- <input type="text" name="code" autocomplete="off" value="<?= htmlspecialchars($currency['code']) ?>"
- placeholder="Currency Code" <?= !$canDelete ? 'disabled' : '' ?>>
- <button class="image-button medium" onClick="editCurrency(<?= $currency['id'] ?>)" name="save"
- title="<?= translate('save_currency', $i18n) ?>">
- <i class="fa-solid fa-check"></i>
- </button>
- <?php
- if ($canDelete) {
- ?>
- <button class="image-button medium" onClick="removeCurrency(<?= $currency['id'] ?>)"
- title="<?= translate('delete_currency', $i18n) ?>">
- <i class="fa-solid fa-trash-can"></i>
- </button>
- <?php
- } else {
- $cantDeleteMessage = $isMainCurrency ? translate('cant_delete_main_currency', $i18n) : translate('cant_delete_currency_in_use', $i18n);
- ?>
- <button class="image-button medium disabled" title="<?= $cantDeleteMessage ?>">
- <i class="fa-solid fa-trash-can"></i>
- </button>
- <?php
- }
- ?>
-
- </div>
- <?php
- }
- ?>
- </div>
- <div class="buttons">
- <input type="submit" value="<?= translate('add', $i18n) ?>" id="addCurrency"
- onClick="addCurrencyButton()" class="thin mobile-grow" />
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i>
- <?= translate('exchange_update', $i18n) ?>
- <span>
- <?= $exchange_rates_last_updated ?>
- </span>
- </p>
- <p>
- <i class="fa-solid fa-circle-info"></i>
- <?= translate('currency_info', $i18n) ?>
- <span>
- fixer.io
- <a href="https://fixer.io/symbols" target="_blank" title="Currency codes">
- <i class="fa-solid fa-arrow-up-right-from-square"></i>
- </a>
- </span>
- </p>
- <p>
- <?= translate('currency_performance', $i18n) ?>
- </p>
- </div>
- </div>
- </section>
-
- <?php
- $apiKey = "";
- $sql = "SELECT api_key, provider FROM fixer WHERE user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- if ($result) {
- $row = $result->fetchArray(SQLITE3_ASSOC);
- if ($row) {
- $apiKey = $row['api_key'];
- $provider = $row['provider'];
- } else {
- $provider = 0;
- }
- }
- ?>
-
- <section class="account-section">
- <header>
- <h2>Fixer API Key</h2>
- </header>
- <div class="account-fixer">
- <div class="form-group">
- <input type="text" name="fixer-key" id="fixerKey" autocomplete="off" value="<?= htmlspecialchars($apiKey) ?>"
- placeholder="<?= translate('api_key', $i18n) ?>" <?= $demoMode ? 'disabled title="Not available on Demo Mode"' : '' ?>>
- </div>
- <div class="form-group">
- <label for="fixerProvider"><?= translate('provider', $i18n) ?>:</label>
- <select name="fixer-provider" id="fixerProvider">
- <option value="0" <?= $provider == 0 ? 'selected' : '' ?>>fixer.io</option>
- <option value="1" <?= $provider == 1 ? 'selected' : '' ?>>apilayer.com</option>
- <option value="2" <?= $provider == 2 ? 'selected' : '' ?>>frankfurter.dev</option>
- </select>
- </div>
- <div class="buttons">
- <input type="submit" value="<?= translate('save', $i18n) ?>" id="addFixerKey"
- onClick="addFixerKeyButton()" class="thin mobile-grow" />
- </div>
- <div class="api-usage" id="fixerUsage" style="display: none;">
- <div class="api-usage-label">
- <span><?= translate('monthly_requests_used', $i18n) ?></span>
- <span id="fixerUsageCount"></span>
- </div>
- <div class="api-usage-track">
- <span class="api-usage-fill" id="fixerUsageFill"></span>
- </div>
- </div>
- <div class="settings-notes">
- <p><i class="fa-solid fa-circle-info"></i><?= translate('fixer_info', $i18n) ?></p>
- <p><?= translate('get_key', $i18n) ?>:
- <span>
- https://fixer.io/
- <a href="https://fixer.io/#pricing_plan"
- title="<?= translate("get_free_fixer_api_key", $i18n) ?>" target="_blank">
- <i class="fa-solid fa-arrow-up-right-from-square"></i>
- </a>
- </span>
- </p>
- <p>
- <?= translate("get_key_alternative", $i18n) ?>
- <span>
- https://apilayer.com
- <a href="https://apilayer.com/marketplace/fixer-api" title="Get free fixer api key"
- target="_blank">
- <i class="fa-solid fa-arrow-up-right-from-square"></i>
- </a>
- </span>
- </p>
- <p>
- <?= translate("no_api_key_provider", $i18n) ?>
- <span>
- https://frankfurter.dev
- <a href="https://frankfurter.dev" title="Frankfurter" target="_blank">
- <i class="fa-solid fa-arrow-up-right-from-square"></i>
- </a>
- </span>
- </p>
- </div>
- </div>
- </section>
-
- <?php
- $googleSearchApiKey = "";
- if ($db->querySingle("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='google_search'") > 0) {
- $sql = "SELECT api_key FROM google_search WHERE user_id = :userId";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- if ($result && ($row = $result->fetchArray(SQLITE3_ASSOC))) {
- $googleSearchApiKey = $row['api_key'];
- }
- }
- ?>
-
- <section class="account-section">
- <header>
- <h2>Google Search (SerpAPI)</h2>
- </header>
- <div class="account-google-search">
- <div class="form-group">
- <input type="text" name="google-search-key" id="googleSearchKey" autocomplete="off"
- value="<?= htmlspecialchars($googleSearchApiKey) ?>" placeholder="<?= translate('api_key', $i18n) ?>"
- <?= $demoMode ? 'disabled title="Not available on Demo Mode"' : '' ?>>
- </div>
- <div class="buttons">
- <input type="submit" value="<?= translate('save', $i18n) ?>" id="saveGoogleSearch"
- onClick="saveGoogleSearchButton()" class="thin mobile-grow" />
- </div>
- <div class="api-usage" id="googleSearchUsage" style="display: none;">
- <div class="api-usage-label">
- <span><?= translate('monthly_searches_used', $i18n) ?></span>
- <span id="googleSearchUsageCount"></span>
- </div>
- <div class="api-usage-track">
- <span class="api-usage-fill" id="googleSearchUsageFill"></span>
- </div>
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i>
- <?= translate('google_search_info', $i18n) ?>
- </p>
- <p><?= translate('get_key', $i18n) ?>:
- <span>
- https://serpapi.com/
- <a href="https://serpapi.com/users/sign_up?plan=free" title="SerpAPI"
- target="_blank" rel="noreferrer">
- <i class="fa-solid fa-arrow-up-right-from-square"></i>
- </a>
- </span>
- </p>
- </div>
- </div>
- </section>
-
- <section class="account-section">
- <header>
- <h2><?= translate('ai_recommendations', $i18n) ?></h2>
- </header>
- <div class="account-ai-settings">
- <div class="form-group-inline">
- <input type="checkbox" id="ai_enabled" name="ai_enabled" <?= isset($aiSettings['enabled']) && $aiSettings['enabled'] ? "checked" : "" ?>>
- <label for="ai_enabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
- </div>
- <div class="form-group">
- <label for="ai_type"><?= translate('provider', $i18n) ?>:</label>
- <select id="ai_type" name="ai_type" onchange="toggleAiInputs()">
- <option value="chatgpt" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'chatgpt') ? 'selected' : '' ?>>ChatGPT</option>
- <option value="gemini" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'gemini') ? 'selected' : '' ?>>Gemini</option>
- <option value="openrouter" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'openrouter') ? 'selected' : '' ?>>OpenRouter</option>
- <option value="ollama" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'ollama') ? 'selected' : '' ?>>Local Ollama</option>
- <option value="openai-compatible" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'openai-compatible') ? 'selected' : '' ?>>OpenAI Compatible</option>
- </select>
- </div>
- <div class="form-group-inline" id="ai_url_group"
- <?= (!isset($aiSettings['type']) || !in_array($aiSettings['type'], ['ollama', 'openai-compatible'])) ? 'style="display:none"' : '' ?>>
- <input type="text" id="ai_ollama_host" name="ai_ollama_host" autocomplete="off"
- placeholder="<?= (isset($aiSettings['type']) && $aiSettings['type'] == 'openai-compatible') ? 'http://localhost:11434/v1' : 'http://localhost:11434' ?>"
- value="<?= isset($aiSettings['url']) ? htmlspecialchars($aiSettings['url']) : '' ?>" />
- <button type="button" id="fetchModelsButton2"
- class="button thin <?= (!isset($aiSettings['type']) || $aiSettings['type'] != 'ollama') ? 'hidden' : '' ?>"
- onclick="fetch_ai_models()">
- <?= translate('test', $i18n) ?>
- </button>
- </div>
- <div class="form-group-inline">
- <input type="password" id="ai_api_key" name="ai_api_key" autocomplete="off"
- class="<?= (isset($aiSettings['type']) && $aiSettings['type'] == 'ollama') ? 'hidden' : '' ?>"
- placeholder="<?= translate('api_key', $i18n) ?>"
- value="<?= isset($aiSettings['api_key']) ? htmlspecialchars($aiSettings['api_key']) : '' ?>" />
- <button type="button" id="fetchModelsButton" class="button thin" onclick="fetch_ai_models()">
- <?= translate('test', $i18n) ?>
- </button>
- </div>
- <div class="form-group">
- <label for="ai_model"><?= translate('ai_model', $i18n) ?>:</label>
- <select id="ai_model" name="ai_model">
- <option value=""><?= translate('select_ai_model', $i18n) ?></option>
- <?php if (!empty($aiSettings['model'])): ?>
- <option value="<?= htmlspecialchars($aiSettings['model']) ?>" selected>
- <?= htmlspecialchars($aiSettings['model']) ?>
- </option>
- <?php endif; ?>
- </select>
- </div>
- <div class="form-group">
- <label for="ai_run_schedule" class="flex"><?= translate('run_schedule', $i18n) ?>:</label>
- <select id="ai_run_schedule" name="ai_run_schedule">
- <option value="manual" <?= (isset($aiSettings['run_schedule']) && $aiSettings['run_schedule'] == 'manual') ? 'selected' : '' ?>><?= translate('manually', $i18n) ?>
- </option>
- <option value="weekly" <?= (isset($aiSettings['run_schedule']) && $aiSettings['run_schedule'] == 'weekly') ? 'selected' : '' ?>><?= translate('Weekly', $i18n) ?>
- </option>
- <option value="monthly" <?= (isset($aiSettings['run_schedule']) && $aiSettings['run_schedule'] == 'monthly') ? 'selected' : '' ?>><?= translate('Monthly', $i18n) ?>
- </option>
- </select>
- </div>
- <div class="buttons wrap mobile-reverse">
- <?php
- $canBeExecuted = !empty($aiSettings['model']) && !empty($aiSettings['enabled']) && $aiSettings['enabled'] == 1;
- ?>
- <input type="button" id="runAiRecommendations"
- class="secondary-button thin mobile-grow-force <?= !$canBeExecuted ? 'hidden' : '' ?>"
- onclick="runAiRecommendations()" value="<?= translate('generate_recommendations', $i18n) ?>" />
- <div id="aiSpinner" class="spinner ai-spinner hidden"></div>
-
- <input type="submit" class="thin mobile-grow-force" value="<?= translate('save', $i18n) ?>"
- id="saveAiSettings" onClick="saveAiSettingsButton()" />
- </div>
- <div class="settings-notes">
- <p><i class="fa-solid fa-circle-info"></i><?= translate('ai_recommendations_info', $i18n) ?></p>
- <p><i class="fa-solid fa-circle-info"></i><?= translate('may_take_time', $i18n) ?></p>
- <p><i
- class="fa-solid fa-circle-info"></i><?= translate('recommendations_visible_on_dashboard', $i18n) ?>
- </p>
- </div>
- </div>
- </section>
-
- <?php
- $sql = "SELECT * FROM payment_methods WHERE user_id = :userId ORDER BY `order` ASC";
- $stmt = $db->prepare($sql);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- if ($result) {
- $payments = array();
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $payments[] = $row;
- }
- }
- ?>
-
- <section class="account-section">
- <header>
- <h2><?= translate('payment_methods', $i18n) ?></h2>
- </header>
- <div class="payments-list" id="payments-list">
- <?php
- $paymentsInUseQuery = $db->prepare('SELECT id FROM payment_methods WHERE user_id = :userId AND id IN (SELECT DISTINCT payment_method_id FROM subscriptions WHERE user_id = :userId)');
- $paymentsInUseQuery->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $paymentsInUseQuery->execute();
-
- $paymentsInUse = [];
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $paymentsInUse[] = $row['id'];
- }
-
- foreach ($payments as $payment) {
- $paymentIconFolder = (strpos($payment['icon'], 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";
-
- $inUse = in_array($payment['id'], $paymentsInUse);
- ?>
- <div class="payments-payment" data-enabled="<?= $payment['enabled']; ?>"
- data-in-use="<?= $inUse ? 'yes' : 'no' ?>" data-paymentid="<?= $payment['id'] ?>"
- title="<?= $inUse ? translate('cant_delete_payment_method_in_use', $i18n) : ($payment['enabled'] ? translate('disable', $i18n) : translate('enable', $i18n)) ?>">
- <div class="drag-icon" title="">
- <i class="fa-solid fa-grip-vertical"></i>
- </div>
- <img src="<?= $paymentIconFolder . $payment['icon'] ?>" alt="Logo" />
- <span class="payment-name" contenteditable="true"
- title="<?= translate("rename_payment_method", $i18n) ?>"><?= htmlspecialchars($payment['name']) ?></span>
- <?php
- if (!$inUse) {
- ?>
- <div class="delete-payment-method" title="<?= translate('delete', $i18n) ?>"
- data-paymentid="<?= $payment['id'] ?>">x</div>
- <?php
- }
- ?>
- </div>
- <?php
- }
- ?>
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i>
- <?= translate('payment_methods_info', $i18n) ?>
- </p>
- <p>
- <i class="fa-solid fa-circle-info"></i>
- <?= translate('rename_payment_methods_info', $i18n) ?>
- </p>
- </div>
- <header>
- <h2 class="second-header"><?= translate("add_custom_payment", $i18n) ?></h2>
- </header>
- <div>
- <form id="payments-form">
- <div class="form-group-inline">
- <input type="text" name="paymentname" id="paymentname" autocomplete="off"
- placeholder="<?= translate('payment_method_name', $i18n) ?>" onchange="setSearchButtonStatus()"
- onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" />
- <label for="paymenticon" class="icon-preview">
- <img src="" alt="<?= translate('logo_preview', $i18n) ?>" id="form-icon">
- </label>
- <div class="form-icon-search">
- <input type="file" id="paymenticon" name="paymenticon"
- accept="image/jpeg, image/png, image/gif, image/webp" onchange="handleFileSelect(event)"
- class="hidden-input">
- <input type="hidden" id="icon-url" name="icon-url">
- <div id="icon-search-button" class="image-button medium disabled"
- title="<?= translate('search_logo', $i18n) ?>" onClick="searchPaymentIcon()">
- <i class="fa-solid fa-magnifying-glass"></i>
- </div>
- <div class="icon-search-backdrop" id="icon-search-backdrop" onClick="closeIconSearch()"></div>
- <div id="icon-search-results" class="icon-search">
- <button type="button" class="close-icon-search" onClick="closeIconSearch()" title="<?= translate('cancel', $i18n) ?>">
- <i class="fa-solid fa-xmark"></i>
- </button>
- <header>
- <h3 id="icon-search-title" data-title="<?= translate('web_search', $i18n) ?>">
- <?= translate('web_search', $i18n) ?>
- </h3>
- </header>
- <div id="icon-search-images"></div>
- </div>
- </div>
-
- <input type="button" class="button thin" id="add-payment-button" value="+"
- title="<?= translate('add', $i18n) ?>" id="addPayment" onClick="addPaymentMethod()" />
- </div>
- </form>
- </div>
- </section>
-
- <section class="account-section">
- <header>
- <h2><?= translate('theme_settings', $i18n) ?></h2>
- </header>
- <div class="account-settings-theme">
- <div>
- <h3><?= translate('theme', $i18n) ?></h3>
- <div class="form-group-inline wrap">
- <button type="button"
- class="dark-theme-button capitalize <?= $settings['dark_theme'] == '0' ? 'selected' : '' ?>"
- onClick="setDarkTheme('0')" id="theme-light">
- <i class="fa-solid fa-sun"></i> <?= translate('light_theme', $i18n) ?>
- </button>
- <button type="button"
- class="dark-theme-button capitalize <?= $settings['dark_theme'] == '1' ? 'selected' : '' ?>"
- onClick="setDarkTheme('1')" id="theme-dark">
- <i class="fa-solid fa-moon"></i> <?= translate('dark_theme', $i18n) ?>
- </button>
- <button type="button"
- class="dark-theme-button capitalize <?= $settings['dark_theme'] == '2' ? 'selected' : '' ?>"
- onClick="setDarkTheme('2')" id="theme-automatic">
- <i class="fa-solid fa-circle-half-stroke"></i> <?= translate('automatic', $i18n) ?>
- </button>
- </div>
- </div>
- <div>
- <form class="theme-selector">
- <h3><?= translate('colors', $i18n) ?></h3>
- <div class="form-group-inline wrap">
- <div class="theme">
- <input type="radio" name="theme" id="theme-blue" value="blue" onClick="setTheme('blue')"
- <?= $settings['color_theme'] == 'blue' ? 'checked' : '' ?>>
- <label for="theme-blue"
- class="theme-preview blue <?= $settings['color_theme'] == 'blue' ? 'is-selected' : '' ?>">
- <span class="main-color"></span>
- <span class="accent-color"></span>
- <span class="hover-color"></span>
- </label>
- </div>
- <div class="theme">
- <input type="radio" name="theme" id="theme-green" value="green" onClick="setTheme('green')"
- <?= $settings['color_theme'] == 'green' ? 'checked' : '' ?>>
- <label for="theme-green"
- class="theme-preview green <?= $settings['color_theme'] == 'green' ? 'is-selected' : '' ?>">
- <span class="main-color"></span>
- <span class="accent-color"></span>
- <span class="hover-color"></span>
- </label>
- </div>
- <div class="theme">
- <input type="radio" name="theme" id="theme-red" value="red" onClick="setTheme('red')"
- <?= $settings['color_theme'] == 'red' ? 'checked' : '' ?>>
- <label for="theme-red"
- class="theme-preview red <?= $settings['color_theme'] == 'red' ? 'is-selected' : '' ?>">
- <span class="main-color"></span>
- <span class="accent-color"></span>
- <span class="hover-color"></span>
- </label>
- </div>
- <div class="theme">
- <input type="radio" name="theme" id="theme-yellow" value="yellow"
- onClick="setTheme('yellow')" <?= $settings['color_theme'] == 'yellow' ? 'checked' : '' ?>>
- <label for="theme-yellow"
- class="theme-preview yellow <?= $settings['color_theme'] == 'yellow' ? 'is-selected' : '' ?>">
- <span class="main-color"></span>
- <span class="accent-color"></span>
- <span class="hover-color"></span>
- </label>
- </div>
- <div class="theme">
- <input type="radio" name="theme" id="theme-purple" value="purple"
- onClick="setTheme('purple')" <?= $settings['color_theme'] == 'purple' ? 'checked' : '' ?>>
- <label for="theme-purple"
- class="theme-preview purple <?= $settings['color_theme'] == 'purple' ? 'is-selected' : '' ?>">
- <span class="main-color"></span>
- <span class="accent-color"></span>
- <span class="hover-color"></span>
- </label>
- </div>
- </div>
- </form>
- </div>
- <div>
- <h3><?= translate('custom_colors', $i18n) ?></h3>
- <div class="custom-colors wrap">
- <div class="form-group-inline mobile-grow color-picker-button">
- <input type="color" id="mainColor" name="mainColor"
- value="<?= isset($settings['customColors']['main_color']) ? $settings['customColors']['main_color'] : '#FFFFFF' ?>"
- class="color-picker fa-solid fa-eye-dropper">
- <label for="mainColor"><?= translate('main_color', $i18n) ?></label>
- </div>
- <div class="form-group-inline mobile-grow color-picker-button">
- <input type="color" id="accentColor" name="accentColor"
- value="<?= isset($settings['customColors']['accent_color']) ? $settings['customColors']['accent_color'] : '#FFFFFF' ?>"
- class="color-picker fa-solid fa-eye-dropper">
- <label for="accentColor"><?= translate('accent_color', $i18n) ?></label>
- </div>
- <div class="form-group-inline mobile-grow color-picker-button">
- <input type="color" id="hoverColor" name="hoverColor"
- value="<?= isset($settings['customColors']['hover_color']) ? $settings['customColors']['hover_color'] : '#FFFFFF' ?>"
- class="color-picker fa-solid fa-eye-dropper">
- <label for="hoverColor"><?= translate('hover_color', $i18n) ?></label>
- </div>
- </div>
- <div class="custom-colors wrap">
- <input type="button" value="<?= translate('reset_custom_colors', $i18n) ?>"
- onClick="resetCustomColors()" class="secondary-button thin mobile-grow" id="reset-colors">
- <input type="button" value="<?= translate('save_custom_colors', $i18n) ?>"
- onClick="saveCustomColors()" class="buton thin mobile-grow" id="save-colors">
- </div>
- </div>
- <?php
- if (!$demoMode) {
- ?>
- <div>
- <h3><?= translate('custom_css', $i18n) ?></h3>
- <div class="form-group">
- <div class="form-group-inline">
- <textarea name="customCss" id="customCss" placeholder="<?= translate('custom_css', $i18n) ?>"
- class="thin"><?= $settings['customCss'] ?? "" ?></textarea>
- </div>
- <div class="form-group-inline">
- <input type="button" value="<?= translate('save_custom_css', $i18n) ?>"
- onClick="saveCustomCss()" class="buton thin mobile-grow" id="save-css">
- </div>
- </div>
- </div>
- <?php
- }
- ?>
- </section>
-
- <section class="account-section">
- <header>
- <h2><?= translate('display_settings', $i18n) ?></h2>
- </header>
- <div class="account-settings-list">
- <h3><?= translate('price', $i18n) ?></h3>
- <div>
- <div class="form-group-inline">
- <input type="checkbox" id="monthlyprice" name="monthlyprice" onChange="setShowMonthlyPrice()" <?php if ($settings['monthly_price'])
- echo 'checked'; ?>>
- <label for="monthlyprice"><?= translate('calculate_monthly_price', $i18n) ?></label>
- </div>
- </div>
- <div>
- <div class="form-group-inline">
- <input type="checkbox" id="convertcurrency" name="convertcurrency" onChange="setConvertCurrency()"
- <?php
- if ($settings['convert_currency'])
- echo ' checked';
- if ($apiKey == "")
- echo ' disabled';
- ?>>
- <label for="convertcurrency"><?= translate('convert_prices', $i18n) ?></label>
- </div>
- </div>
- <div>
- <div class="form-group-inline">
- <input type="checkbox" id="showoriginalprice" name="showoriginalprice"
- onChange="setShowOriginalPrice()" <?= $settings['show_original_price'] ? 'checked' : '' ?>>
- <label for="showoriginalprice"><?= translate('show_original_price', $i18n) ?></label>
- </div>
- </div>
- <div>
- <div class="form-group">
- <label for="upcomingpaymentslimit"><?= translate('upcoming_payments_to_show', $i18n) ?></label>
- <select id="upcomingpaymentslimit" name="upcomingpaymentslimit" onChange="setUpcomingPaymentsLimit()">
- <option value="3" <?= $upcomingPaymentsLimit === 3 ? 'selected' : '' ?>>3</option>
- <option value="5" <?= $upcomingPaymentsLimit === 5 ? 'selected' : '' ?>>5</option>
- <option value="10" <?= $upcomingPaymentsLimit === 10 ? 'selected' : '' ?>>10</option>
- <option value="20" <?= $upcomingPaymentsLimit === 20 ? 'selected' : '' ?>>20</option>
- </select>
- </div>
- </div>
- <h3><?= translate('experience', $i18n) ?></h3>
- <div>
- <div class="form-group-inline">
- <input type="checkbox" id="mobilenavigation" name="mobilenavigation"
- onChange="setMobileNavigation()" <?= $settings['mobile_nav'] ? 'checked' : '' ?>>
- <label for="mobilenavigation"><?= translate('use_mobile_navigation_bar', $i18n) ?></label>
- </div>
- <div class="mobile-nav-image">
- </div>
- </div>
- <div>
- <div class="form-group-inline">
- <input type="checkbox" id="showsubscriptionprogress" name="showsubscriptionprogress"
- onChange="setShowSubscriptionProgress()" <?= $settings['show_subscription_progress'] ? 'checked' : '' ?>>
- <label for="showsubscriptionprogress"><?= translate('show_subscription_progress', $i18n) ?></label>
- </div>
- </div>
- <div>
- <div class="form-group-inline">
- <input type="checkbox" id="weekstartssunday" name="weekstartssunday"
- onChange="setWeekStartsSunday()" <?= !empty($settings['week_starts_sunday']) ? 'checked' : '' ?>>
- <label for="weekstartssunday"><?= translate('week_starts_on_sunday', $i18n) ?></label>
- </div>
- </div>
- <h3><?= translate('disabled_subscriptions', $i18n) ?></h3>
- <div>
- <div class="form-group-inline">
- <input type="checkbox" id="disabledtobottom" name="disabledtobottom"
- onChange="setDisabledToBottom()" <?= $settings['disabled_to_bottom'] ? 'checked' : '' ?>>
- <label
- for="disabledtobottom"><?= translate('show_disabled_subscriptions_at_the_bottom', $i18n) ?></label>
- </div>
- </div>
- <div>
- <div class="form-group-inline">
- <input type="checkbox" id="hidedisabled" name="hidedisabled" onChange="setHideDisabled()"
- <?= $settings['hide_disabled'] ? 'checked' : '' ?>>
- <label for="hidedisabled"><?= translate('hide_disabled_subscriptions', $i18n) ?></label>
- </div>
- </div>
- </div>
- </section>
-
- <section class="account-section">
- <header>
- <h2><?= translate('experimental_settings', $i18n) ?></h2>
- </header>
- <div class="account-settings-list">
- <div>
- <div class="form-group-inline">
- <input type="checkbox" id="removebackground" name="removebackground"
- onChange="setRemoveBackground()" <?= $settings['remove_background'] ? 'checked' : '' ?>>
- <label for="removebackground"><?= translate('remove_background', $i18n) ?></label>
- </div>
- </div>
- </div>
- <div class="settings-notes">
- <p>
- <i class="fa-solid fa-circle-info"></i>
- <?= translate('remove_background_info', $i18n) ?>
- </p>
- <p>
- <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i>
- <?= translate('experimental_info', $i18n) ?>
- </p>
- </div>
- </section>
-
-</section>
-<script>
- // The raw applicationServerKey bytes pushManager.subscribe() needs -
- // not a secret, the same value every push service and the VAPID
- // Authorization header's "k=" parameter are handed too.
- window.vapidPublicKey = "<?= htmlspecialchars($vapidPublicKey, ENT_QUOTES, 'UTF-8') ?>";
-</script>
-<script src="scripts/settings.js?<?= $version ?>"></script>
-<script src="scripts/theme.js?<?= $version ?>"></script>
-<script src="scripts/notifications.js?<?= $version ?>"></script>
-
-<?php
-require_once 'includes/footer.php';
-?>
+<?php
+require_once 'includes/header.php';
+require_once 'includes/upcoming_payments.php';
+require_once 'includes/webpush_helper.php';
+
+$currencies = array();
+$query = "SELECT * FROM currencies WHERE user_id = :userId";
+$query = $db->prepare($query);
+$query->bindValue(':userId', $userId, SQLITE3_INTEGER);
+$result = $query->execute();
+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $currencyId = $row['id'];
+ $currencies[$currencyId] = $row;
+}
+$userData['currency_symbol'] = $currencies[$main_currency]['symbol'];
+$budgetPeriodType = $userData['budget_period_type'] ?? 'monthly';
+$budgetPeriodAnchorDate = $userData['budget_period_anchor_date'] ?? date('Y-m-d');
+if ($budgetPeriodAnchorDate === '1970-01-01' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $budgetPeriodAnchorDate)) {
+ $budgetPeriodAnchorDate = date('Y-m-d');
+}
+$upcomingPaymentsLimit = normalize_upcoming_payments_limit($settings['upcoming_payments_limit'] ?? 3);
+
+?>
+
+<script src="scripts/libs/sortable.min.js"></script>
+<style>
+ .logo-preview:after {
+ content: '<?= translate('upload_logo', $i18n) ?>';
+ }
+
+ .period-budget-controls {
+ align-items: flex-end;
+ flex-wrap: wrap;
+ gap: 12px 15px;
+ }
+
+ .period-budget-controls .period-budget-field {
+ display: flex;
+ flex-direction: column;
+ flex: 1 1 180px;
+ min-width: 160px;
+ gap: 8px;
+ }
+
+ .period-budget-controls .period-budget-field label {
+ margin-bottom: 0;
+ line-height: 1.2;
+ }
+
+ .period-budget-controls .period-budget-save {
+ flex: 0 0 auto;
+ }
+
+ .period-budget-controls #budget_period_anchor_date {
+ display: block;
+ height: 50px;
+ min-height: 50px;
+ }
+
+ @media (min-width: 421px) and (max-width: 768px) {
+ .period-budget-controls .period-budget-field {
+ flex: 1 1 calc(50% - 8px);
+ min-width: 0;
+ }
+
+ .period-budget-controls .period-budget-save {
+ width: 100%;
+ }
+ }
+
+ @media (max-width: 420px) {
+ .period-budget-controls .period-budget-field {
+ flex: 1 1 100%;
+ min-width: 0;
+ }
+
+ .period-budget-controls .period-budget-save {
+ width: 100%;
+ }
+ }
+</style>
+<section class="contain settings">
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('monthly_budget', $i18n) ?></h2>
+ </header>
+ <div class="account-budget">
+ <div class="form-group-inline">
+ <label for="monthly_budget"><?= $userData['currency_symbol'] ?></label>
+ <input type="number" id="monthly_budget" name="monthly_budget" autocomplete="off" value="<?= $userData['budget'] ?>"
+ placeholder="Budget">
+ <input type="submit" value="<?= translate('save', $i18n) ?>" id="saveMonthlyBudget" onClick="saveMonthlyBudget()" />
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i> <?= translate('monthly_budget_info', $i18n) ?>
+ </p>
+ </div>
+ </div>
+ </section>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('period_budget', $i18n) ?></h2>
+ </header>
+ <div class="account-budget">
+ <div class="form-group-inline">
+ <label for="period_budget"><?= $userData['currency_symbol'] ?></label>
+ <input type="number" id="period_budget" name="period_budget" autocomplete="off" value="<?= $userData['period_budget'] ?? 0 ?>"
+ placeholder="Budget">
+ </div>
+ <div class="form-group-inline period-budget-controls">
+ <div class="period-budget-field">
+ <label for="budget_period_type"><?= translate('budget_period', $i18n) ?></label>
+ <select id="budget_period_type" name="budget_period_type">
+ <option value="weekly" <?= $budgetPeriodType === 'weekly' ? 'selected' : '' ?>><?= translate('weekly', $i18n) ?></option>
+ <option value="fortnightly" <?= $budgetPeriodType === 'fortnightly' ? 'selected' : '' ?>><?= translate('fortnightly', $i18n) ?></option>
+ <option value="monthly" <?= $budgetPeriodType === 'monthly' ? 'selected' : '' ?>><?= translate('monthly', $i18n) ?></option>
+ </select>
+ </div>
+ <div class="period-budget-field">
+ <label for="budget_period_anchor_date"><?= translate('budget_anchor_date', $i18n) ?></label>
+ <input type="date" id="budget_period_anchor_date" name="budget_period_anchor_date"
+ value="<?= htmlspecialchars($budgetPeriodAnchorDate, ENT_QUOTES, 'UTF-8') ?>">
+ </div>
+ <input type="submit" value="<?= translate('save', $i18n) ?>" id="savePeriodBudget" class="period-budget-save" onClick="savePeriodBudget()" />
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i> <?= translate('period_budget_info', $i18n) ?>
+ </p>
+ </div>
+ </div>
+ </section>
+
+ <?php
+ $sql = "SELECT * FROM household WHERE user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result) {
+ $household = array();
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $household[] = $row;
+ }
+ }
+ ?>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('household', $i18n) ?></h2>
+ </header>
+ <div class="account-members">
+ <div id="householdMembers">
+ <?php
+ foreach ($household as $index => $member) {
+ ?>
+ <div class="form-group-inline" data-memberid="<?= $member['id'] ?>">
+ <input type="text" name="member" autocomplete="off" value="<?= htmlspecialchars($member['name']) ?>"
+ placeholder="Member">
+ <?php
+ if ($index !== 0) {
+ ?>
+ <input type="text" name="email" autocomplete="off" value="<?= htmlspecialchars($member['email'] ?? "") ?>"
+ placeholder="<?= translate("email", $i18n) ?>">
+ <?php
+ }
+ ?>
+ <button class="image-button medium" onClick="editMember(<?= $member['id'] ?>)" name="save"
+ title="<?= translate('save_member', $i18n) ?>">
+ <i class="fa-solid fa-check"></i>
+ </button>
+ <?php
+ if ($index !== 0) {
+ ?>
+ <button class="image-button medium" onClick="removeMember(<?= $member['id'] ?>)"
+ title="<?= translate('delete_member', $i18n) ?>">
+ <i class="fa-solid fa-trash-can"></i>
+ </button>
+ <?php
+ } else {
+ ?>
+ <button class="image-button medium disabled" title="<?= translate('cant_delete_member', $i18n) ?>">
+ <i class="fa-solid fa-trash-can"></i>
+ </button>
+ <?php
+ }
+ ?>
+ </div>
+ <?php
+ }
+ ?>
+ </div>
+ <div class="buttons">
+ <input type="submit" value="<?= translate('add', $i18n) ?>" id="addMember" onClick="addMemberButton()"
+ class="thin mobile-grow" />
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i> <?= translate('household_info', $i18n) ?>
+ </p>
+ <p>
+ </div>
+ </div>
+ </section>
+
+ <?php
+ // Notification settings
+ $sql = "SELECT * FROM notification_settings WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notifications = $row;
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notifications['days'] = 1;
+ $notifications['period_summary_at_period_start'] = 0;
+ } else if (!isset($notifications['period_summary_at_period_start'])) {
+ $notifications['period_summary_at_period_start'] = 0;
+ }
+
+ // Email notifications
+ $sql = "SELECT * FROM email_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsEmail['enabled'] = $row['enabled'];
+ $notificationsEmail['smtp_address'] = $row['smtp_address'];
+ $notificationsEmail['smtp_port'] = $row['smtp_port'];
+ $notificationsEmail['encryption'] = $row['encryption'];
+ $notificationsEmail['smtp_username'] = $row['smtp_username'];
+ $notificationsEmail['smtp_password'] = $row['smtp_password'];
+ $notificationsEmail['from_email'] = $row['from_email'];
+ $notificationsEmail['other_emails'] = $row['other_emails'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsEmail['enabled'] = 0;
+ $notificationsEmail['smtp_address'] = "";
+ $notificationsEmail['smtp_port'] = 587;
+ $notificationsEmail['encryption'] = "tls";
+ $notificationsEmail['smtp_username'] = "";
+ $notificationsEmail['smtp_password'] = "";
+ $notificationsEmail['from_email'] = "";
+ $notificationsEmail['other_emails'] = "";
+ }
+
+ // Discord notifications
+ $sql = "SELECT * FROM discord_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsDiscord['enabled'] = $row['enabled'];
+ $notificationsDiscord['webhook_url'] = $row['webhook_url'];
+ $notificationsDiscord['bot_username'] = $row['bot_username'];
+ $notificationsDiscord['bot_avatar'] = $row['bot_avatar_url'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsDiscord['enabled'] = 0;
+ $notificationsDiscord['webhook_url'] = "";
+ $notificationsDiscord['bot_username'] = "";
+ $notificationsDiscord['bot_avatar'] = "";
+ }
+
+ // Pushover notifications
+ $sql = "SELECT * FROM pushover_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsPushover['enabled'] = $row['enabled'];
+ $notificationsPushover['token'] = $row['token'];
+ $notificationsPushover['user_key'] = $row['user_key'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsPushover['enabled'] = 0;
+ $notificationsPushover['token'] = "";
+ $notificationsPushover['user_key'] = "";
+ }
+
+ // Telegram notifications
+ $sql = "SELECT * FROM telegram_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsTelegram['enabled'] = $row['enabled'];
+ $notificationsTelegram['bot_token'] = $row['bot_token'];
+ $notificationsTelegram['chat_id'] = $row['chat_id'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsTelegram['enabled'] = 0;
+ $notificationsTelegram['bot_token'] = "";
+ $notificationsTelegram['chat_id'] = "";
+ }
+
+
+ // PushPlus notifications
+ $sql = "SELECT * FROM pushplus_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsPushPlus['enabled'] = $row['enabled'];
+ $notificationsPushPlus['token'] = $row['token'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsPushPlus['enabled'] = 0;
+ $notificationsPushPlus['token'] = "";
+ }
+
+ // Mattermost notifications
+ $sql = "SELECT * FROM mattermost_notifications WHERE user_id = :userID LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userID', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsMattermost['enabled'] = $row['enabled'];
+ $notificationsMattermost['webhook_url'] = $row['webhook_url'];
+ $notificationsMattermost['bot_username'] = $row['bot_username'];
+ $notificationsMattermost['bot_icon_emoji'] = $row['bot_icon_emoji'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsMattermost['enabled'] = 0;
+ $notificationsMattermost['webhook_url'] = "";
+ $notificationsMattermost['bot_username'] = "";
+ $notificationsMattermost['bot_icon_emoji'] = "";
+ }
+
+ // Serverchan notifications
+ $sql = "SELECT * FROM serverchan_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsServerchan['enabled'] = $row['enabled'];
+ $notificationsServerchan['sendkey'] = $row['sendkey'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsServerchan['enabled'] = 0;
+ $notificationsServerchan['sendkey'] = "";
+ }
+
+ // Ntfy notifications
+ $sql = "SELECT * FROM ntfy_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsNtfy['enabled'] = $row['enabled'];
+ $notificationsNtfy['host'] = $row['host'];
+ $notificationsNtfy['topic'] = $row['topic'];
+ $notificationsNtfy['headers'] = $row['headers'];
+ $notificationsNtfy['ignore_ssl'] = $row['ignore_ssl'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsNtfy['enabled'] = 0;
+ $notificationsNtfy['host'] = "";
+ $notificationsNtfy['topic'] = "";
+ $notificationsNtfy['headers'] = "";
+ $notificationsNtfy['ignore_ssl'] = 0;
+ }
+
+ // Push notifications
+ $sql = "SELECT * FROM push_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsPush['enabled'] = $row['enabled'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsPush['enabled'] = 0;
+ }
+
+ $pushSubscriptions = [];
+ $sql = "SELECT id, user_agent, created_at FROM push_subscriptions WHERE user_id = :userId ORDER BY id";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $pushSubscriptions[] = $row;
+ }
+
+ // Generated lazily on first visit to this page for an installation that
+ // has never needed one before - see webpush_get_vapid_keys()'s own
+ // comment for why this lives on the admin row rather than per user.
+ $vapidPublicKey = '';
+ $vapidKeys = webpush_get_vapid_keys($db);
+ if ($vapidKeys !== false) {
+ $vapidPublicKey = $vapidKeys['public'];
+ }
+
+ // Webhook notifications
+ $sql = "SELECT * FROM webhook_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsWebhook['enabled'] = $row['enabled'];
+ $notificationsWebhook['url'] = $row['url'];
+ $notificationsWebhook['request_method'] = $row['request_method'];
+ $notificationsWebhook['headers'] = $row['headers'];
+ $notificationsWebhook['payload'] = $row['payload'];
+ $notificationsWebhook['cancelation_payload'] = $row['cancelation_payload'];
+ $notificationsWebhook['ignore_ssl'] = $row['ignore_ssl'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsWebhook['enabled'] = 0;
+ $notificationsWebhook['url'] = "";
+ $notificationsWebhook['request_method'] = "POST";
+ $notificationsWebhook['headers'] = "";
+ $notificationsWebhook['payload'] = '
+{
+ "name": "{{subscription_name}}",
+ "price": "{{subscription_price}}",
+ "currency": "{{subscription_currency}}",
+ "category": "{{subscription_category}}",
+ "date": "{{subscription_date}}",
+ "payer": "{{subscription_payer}}",
+ "days": "{{subscription_days_until_payment}}",
+ "notes": "{{subscription_notes}}",
+ "url": "{{subscription_url}}"
+}';
+ $notificationsWebhook['cancelation_payload'] = "";
+ $notificationsWebhook['ignore_ssl'] = 0;
+ }
+
+ // Gotify notifications
+ $sql = "SELECT * FROM gotify_notifications WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $rowCount = 0;
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $notificationsGotify['enabled'] = $row['enabled'];
+ $notificationsGotify['url'] = $row['url'];
+ $notificationsGotify['token'] = $row['token'];
+ $notificationsGotify['ignore_ssl'] = $row['ignore_ssl'];
+ $rowCount++;
+ }
+
+ if ($rowCount == 0) {
+ $notificationsGotify['enabled'] = 0;
+ $notificationsGotify['url'] = "";
+ $notificationsGotify['token'] = "";
+ $notificationsGotify['ignore_ssl'] = 0;
+ }
+
+ ?>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('notifications', $i18n) ?></h2>
+ </header>
+ <div class="account-notifications">
+ <section>
+ <label for="days"><?= translate('notify_me', $i18n) ?>:</label>
+ <div class="form-group-inline">
+ <select name="days" id="days">
+ <option value="0" <?= $notifications['days'] == 0 ? "selected" : "" ?>>
+ <?= translate('on_due_date', $i18n) ?>
+ </option>
+ <option value="1" <?= $notifications['days'] == 1 ? "selected" : "" ?>>
+ 1 <?= translate('day_before', $i18n) ?>
+ </option>
+ <?php
+ for ($i = 2; $i <= 7; $i++) {
+ $selected = $i == $notifications['days'] ? "selected" : "";
+ ?>
+ <option value="<?= $i ?>" <?= $selected ?>>
+ <?= $i ?> <?= translate('days_before', $i18n) ?>
+ </option>
+ <?php
+ }
+ ?>
+ </select>
+ <input type="submit" class="thin" value="<?= translate('save', $i18n) ?>" id="saveNotifications"
+ onClick="saveNotifications()" />
+ </div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="period_summary_at_period_start" name="period_summary_at_period_start"
+ <?= !empty($notifications['period_summary_at_period_start']) ? "checked" : "" ?>>
+ <label for="period_summary_at_period_start">
+ <?= translate('send_period_summary_at_period_start', $i18n) ?>
+ </label>
+ </div>
+ </section>
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('email')">
+ <h3>
+ <i class="fa-solid fa-envelope"></i>
+ <?= translate('email', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="email">
+ <div class="form-group-inline">
+ <input type="checkbox" id="emailenabled" name="emailenabled" <?= $notificationsEmail['enabled'] ? "checked" : "" ?>>
+ <label for="emailenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="smtpaddress" id="smtpaddress" autocomplete="off"
+ placeholder="<?= translate('smtp_address', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsEmail['smtp_address']) ?>" />
+ <input type="text" name="smtpport" id="smtpport" autocomplete="off"
+ placeholder="<?= translate('port', $i18n) ?>" class="one-third"
+ value="<?= htmlspecialchars($notificationsEmail['smtp_port']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <div>
+ <input type="radio" name="encryption" id="encryptionnone" value="none"
+ <?= $notificationsEmail['encryption'] == "none" ? "checked" : "" ?> />
+ <label for="encryptionnone"><?= translate('none', $i18n) ?></label>
+ </div>
+ <div>
+ <input type="radio" name="encryption" id="encryptiontls" value="tls"
+ <?= $notificationsEmail['encryption'] == "tls" ? "checked" : "" ?> />
+ <label for="encryptiontls"><?= translate('tls', $i18n) ?></label>
+ </div>
+ <div>
+ <input type="radio" name="encryption" id="encryptionssl" value="ssl"
+ <?= $notificationsEmail['encryption'] == "ssl" ? "checked" : "" ?> />
+ <label for="encryptionssl"><?= translate('ssl', $i18n) ?></label>
+ </div>
+
+
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="smtpusername" id="smtpusername" autocomplete="off"
+ placeholder="<?= translate('smtp_username', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsEmail['smtp_username']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="password" name="smtppassword" id="smtppassword" autocomplete="off"
+ placeholder="<?= translate('smtp_password', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsEmail['smtp_password']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="fromemail" id="fromemail" autocomplete="off"
+ placeholder="<?= translate('from_email', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsEmail['from_email']) ?>" />
+ </div>
+ <label for="otheremails"><?= translate('send_to_other_emails', $i18n) ?></label>
+ <div class="form-group-inline">
+ <input type="text" name="otheremails" id="otheremails" autocomplete="off"
+ placeholder="<?= translate('other_emails_placeholder', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsEmail['other_emails']) ?>" />
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsEmail"
+ onClick="testNotificationEmailButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsEmail" onClick="saveNotificationsEmailButton()" />
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i> <?= translate('smtp_info', $i18n) ?>
+ </p>
+ <p>
+ </div>
+ </div>
+ </section>
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('discord');">
+ <h3>
+ <i class="fa-brands fa-discord"></i>
+ <?= translate('discord', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="discord">
+ <div class="form-group-inline">
+ <input type="checkbox" id="discordenabled" name="discordenabled"
+ <?= $notificationsDiscord['enabled'] ? "checked" : "" ?>>
+ <label for="discordenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="discordurl" id="discordurl" autocomplete="off"
+ placeholder="<?= translate('webhook_url', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsDiscord['webhook_url']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="discordbotusername" id="discordbotusername" autocomplete="off"
+ placeholder="<?= translate('discord_bot_username', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsDiscord['bot_username']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="discordbotavatar" id="discordbotavatar" autocomplete="off"
+ placeholder="<?= translate('discord_bot_avatar_url', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsDiscord['bot_avatar']) ?>" />
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsDiscord"
+ onClick="testNotificationsDiscordButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsDiscord" onClick="saveNotificationsDiscordButton()" />
+ </div>
+ </div>
+ </section>
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('gotify');">
+ <h3>
+ <i class="fa-solid fa-envelopes-bulk"></i>
+ <?= translate('gotify', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="gotify">
+ <div class="form-group-inline">
+ <input type="checkbox" id="gotifyenabled" name="gotifyenabled"
+ <?= $notificationsGotify['enabled'] ? "checked" : "" ?>>
+ <label for="gotifyenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="gotifyurl" id="gotifyurl" autocomplete="off"
+ placeholder="<?= translate('url', $i18n) ?>" value="<?= htmlspecialchars($notificationsGotify['url']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="gotifytoken" id="gotifytoken" autocomplete="off"
+ placeholder="<?= translate('token', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsGotify['token']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="gotifyignoressl" name="gotifyignoressl"
+ <?= $notificationsGotify['ignore_ssl'] ? "checked" : "" ?>>
+ <label for="gotifyignoressl"><?= translate('ignore_ssl_errors', $i18n) ?></label>
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsGotify"
+ onClick="testNotificationsGotifyButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsGotify" onClick="saveNotificationsGotifyButton()" />
+ </div>
+ </div>
+ </section>
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('pushover');">
+ <h3>
+ <i class="fa-brands fa-pinterest-p"></i>
+ <?= translate('pushover', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="pushover">
+ <div class="form-group-inline">
+ <input type="checkbox" id="pushoverenabled" name="pushoverenabled"
+ <?= $notificationsPushover['enabled'] ? "checked" : "" ?>>
+ <label for="pushoverenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="pushoveruserkey" id="pushoveruserkey" autocomplete="off"
+ placeholder="<?= translate('pushover_user_key', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsPushover['user_key']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="pushovertoken" id="pushovertoken" autocomplete="off"
+ placeholder="<?= translate('token', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsPushover['token']) ?>" />
+ </div>
+
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsPushover"
+ onClick="testNotificationsPushoverButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsPushover" onClick="saveNotificationsPushoverButton()" />
+ </div>
+ </div>
+ </section>
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('telegram');">
+ <h3>
+ <i class="fa-solid fa-paper-plane"></i>
+ <?= translate('telegram', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="telegram">
+ <div class="form-group-inline">
+ <input type="checkbox" id="telegramenabled" name="telegramenabled"
+ <?= $notificationsTelegram['enabled'] ? "checked" : "" ?>>
+ <label for="telegramenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="telegrambottoken" id="telegrambottoken" autocomplete="off"
+ placeholder="<?= translate('telegram_bot_token', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsTelegram['bot_token'] ? $notificationsTelegram['bot_token'] : "") ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="telegramchatid" id="telegramchatid" autocomplete="off"
+ placeholder="<?= translate('telegram_chat_id', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsTelegram['chat_id']) ?>" />
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsTelegram"
+ onClick="testNotificationsTelegramButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsTelegram" onClick="saveNotificationsTelegramButton()" />
+ </div>
+ </div>
+ </section>
+
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('pushplus');">
+ <h3>
+ <i class="fa-solid fa-bell"></i>
+ <?= translate('pushplus', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="pushplus">
+ <div class="form-group-inline">
+ <input type="checkbox" id="pushplusenabled" name="pushplusenabled"
+ <?= $notificationsPushPlus['enabled'] ? "checked" : "" ?>>
+ <label for="pushplusenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="pushplustoken" id="pushplustoken" autocomplete="off"
+ placeholder="<?= translate('pushplus_token', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsPushPlus['token'] ? $notificationsPushPlus['token'] : '') ?>" />
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsPushPlus"
+ onClick="testNotificationsPushPlusButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsPushPlus" onClick="saveNotificationsPushPlusButton()" />
+ </div>
+ </div>
+ </section>
+
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('mattermost');">
+ <h3>
+ <i class="fa-solid fa-gauge-simple-high"></i>
+ <?= translate('mattermost', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="mattermost">
+ <div class="form-group-inline">
+ <input type="checkbox" id="mattermostenabled" name="mattermostenabled"
+ <?= $notificationsMattermost['enabled'] ? "checked" : "" ?>>
+ <label for="mattermostenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="mattermostwebhookurl" id="mattermostwebhookurl"
+ placeholder="<?= translate('mattermost_webhook_url', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsMattermost['webhook_url'] ? $notificationsMattermost['webhook_url'] : '') ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="mattermostbotusername" id="mattermostbotusername"
+ placeholder="<?= translate('mattermost_bot_username', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsMattermost['bot_username'] ? $notificationsMattermost['bot_username'] : '') ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="mattermostboticonemoji" id="mattermostboticonemoji"
+ placeholder="<?= translate('mattermost_bot_icon_emoji', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsMattermost['bot_icon_emoji'] ? $notificationsMattermost['bot_icon_emoji'] : '') ?>" />
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsMattermost"
+ onClick="testNotificationsMattermostButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsMattermost" onClick="saveNotificationsMattermostButton()" />
+ </div>
+ </div>
+ </section>
+
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('ntfy');">
+ <h3>
+ <i class="fa-solid fa-terminal"></i> Ntfy
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="ntfy">
+ <div class="form-group-inline">
+ <input type="checkbox" id="ntfyenabled" name="ntfyenabled" <?= $notificationsNtfy['enabled'] ? "checked" : "" ?>>
+ <label for="ntfyenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="ntfyhost" id="ntfyhost" autocomplete="off"
+ placeholder="<?= translate('host', $i18n) ?>" value="<?= htmlspecialchars($notificationsNtfy['host']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="ntfytopic" id="ntfytopic" autocomplete="off"
+ placeholder="<?= translate('topic', $i18n) ?>" value="<?= htmlspecialchars($notificationsNtfy['topic']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <textarea class="thin" name="ntfyheaders" id="ntfyheaders"
+ placeholder="<?= translate('custom_headers', $i18n) ?>"><?= htmlspecialchars($notificationsNtfy['headers']) ?></textarea>
+ </div>
+ <div class="form-grpup-inline">
+ <input type="checkbox" id="ntfyignoressl" name="ntfyignoressl"
+ <?= $notificationsNtfy['ignore_ssl'] ? "checked" : "" ?>>
+ <label for="ntfyignoressl"><?= translate('ignore_ssl_errors', $i18n) ?></label>
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsNtfy"
+ onClick="testNotificationsNtfyButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsNtfy" onClick="saveNotificationsNtfyButton()" />
+ </div>
+ </section>
+
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('push');">
+ <h3>
+ <i class="fa-solid fa-bell"></i> <?= translate('push_notifications', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="push">
+ <div class="form-group-inline">
+ <input type="checkbox" id="pushenabled" name="pushenabled" <?= $notificationsPush['enabled'] ? "checked" : "" ?>>
+ <label for="pushenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="push-devices-list" id="pushDevicesList">
+ <?php if (empty($pushSubscriptions)): ?>
+ <p id="noPushDevices" class="push-no-devices"><?= translate('no_devices_registered', $i18n) ?></p>
+ <?php else: ?>
+ <?php foreach ($pushSubscriptions as $subscription): ?>
+ <div class="push-device-row" data-subscriptionid="<?= (int) $subscription['id'] ?>">
+ <span class="push-device-name">
+ <?= htmlspecialchars($subscription['user_agent'] !== '' ? $subscription['user_agent'] : translate('unknown_device', $i18n)) ?>
+ </span>
+ <button type="button" class="secondary-button thin" onclick="removePushSubscriptionButton(<?= (int) $subscription['id'] ?>)">
+ <?= translate('delete', $i18n) ?>
+ </button>
+ </div>
+ <?php endforeach; ?>
+ <?php endif; ?>
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i>
+ <?= translate('push_notifications_info', $i18n) ?>
+ </p>
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsPush"
+ onClick="testNotificationsPushButton()" />
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('enable_on_this_device', $i18n) ?>" id="subscribePushButton"
+ onClick="subscribePushButtonClick()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsPush" onClick="saveNotificationsPushButton()" />
+ </div>
+ </div>
+ </section>
+
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('serverchan');">
+ <h3>
+ <i class="fa-solid fa-code"></i>
+ <?= translate('serverchan', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="serverchan">
+ <div class="form-group-inline">
+ <input type="checkbox" id="serverchanenabled" name="serverchanenabled"
+ <?= $notificationsServerchan['enabled'] ? "checked" : "" ?>>
+ <label for="serverchanenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="serverchansendkey" id="serverchansendkey" autocomplete="off"
+ placeholder="<?= translate('serverchan_sendkey', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsServerchan['sendkey'] ? $notificationsServerchan['sendkey'] : '') ?>" />
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsServerchan"
+ onClick="testNotificationsServerchanButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsServerchan" onClick="saveNotificationsServerchanButton()" />
+ </div>
+ </div>
+ </section>
+
+ <section class="account-notifications-section">
+ <header class="account-notification-section-header" onclick="openNotificationsSettings('webhook');">
+ <h3>
+ <i class="fa-solid fa-bolt"></i>
+ <?= translate('webhook', $i18n) ?>
+ </h3>
+ </header>
+ <div class="account-notification-section-settings" data-type="webhook">
+ <div class="form-group-inline">
+ <input type="checkbox" id="webhookenabled" name="webhookenabled"
+ <?= $notificationsWebhook['enabled'] ? "checked" : "" ?>>
+ <label for="webhookenabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div>
+ <label for="webhookrequestmethod"
+ class="capitalize"><?= translate('request_method', $i18n) ?>:</label>
+ <div class="form-group-inline">
+ <select name="webhookrequestmethod" id="webhookrequestmethod">
+ <option value="GET" <?= $notificationsWebhook['request_method'] == 'GET' ? 'selected' : '' ?>>GET</option>
+ <option value="POST" <?= $notificationsWebhook['request_method'] == 'POST' ? 'selected' : '' ?>>POST</option>
+ <option value="PUT" <?= $notificationsWebhook['request_method'] == 'PUT' ? 'selected' : '' ?>>PUT</option>
+ </select>
+ </div>
+ </div>
+ <div class="form-group-inline">
+ <input type="text" name="webhookurl" id="webhookurl" autocomplete="off"
+ placeholder="<?= translate('webhook_url', $i18n) ?>"
+ value="<?= htmlspecialchars($notificationsWebhook['url']) ?>" />
+ </div>
+ <div class="form-group-inline">
+ <textarea class="thin" name="webhookcustomheaders" id="webhookcustomheaders"
+ placeholder="<?= translate('custom_headers', $i18n) ?>"><?= htmlspecialchars($notificationsWebhook['headers']) ?></textarea>
+ </div>
+ <div class="form-group-inline">
+ <textarea name="webhookpayload" id="webhookpayload"
+ placeholder="<?= translate('payment_notifications_payload', $i18n) ?>"><?= htmlspecialchars($notificationsWebhook['payload']) ?></textarea>
+ </div>
+ <div class="form-group-inline">
+ <textarea name="webhookcancelationpayload" id="webhookcancelationpayload"
+ placeholder="<?= translate('cancelation_notification_payload', $i18n) ?>"><?= htmlspecialchars($notificationsWebhook['cancelation_payload']) ?></textarea>
+ </div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="webhookignoressl" name="webhookignoressl"
+ <?= $notificationsWebhook['ignore_ssl'] ? "checked" : "" ?>>
+ <label for="webhookignoressl"><?= translate('ignore_ssl_errors', $i18n) ?></label>
+ </div>
+ <div class="buttons">
+ <input type="button" class="secondary-button thin mobile-grow"
+ value="<?= translate('test', $i18n) ?>" id="testNotificationsWebhook"
+ onClick="testNotificationsWebhookButton()" />
+ <input type="submit" class="thin mobile-grow" value="<?= translate('save', $i18n) ?>"
+ id="saveNotificationsWebhook" onClick="saveNotificationsWebhookButton()" />
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i> <?= translate('variables_available', $i18n) ?>:
+ {{days_until}}, {{subscription_name}}, {{subscription_price}}, {{subscription_currency}},
+ {{subscription_category}}, {{subscription_date}}, {{subscription_payer}},
+ {{subscription_days_until_payment}}, {{subscription_notes}}, {{subscription_url}}
+ </p>
+ <p>
+ </div>
+ </div>
+ </section>
+ </div>
+ </section>
+
+ <?php
+ $sql = "SELECT * FROM categories WHERE user_id = :userId ORDER BY `order` ASC";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result) {
+ $categories = array();
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $categories[] = $row;
+ }
+ }
+ ?>
+
+ <?php
+ $sql = "SELECT * FROM ai_settings WHERE user_id = :userId LIMIT 1";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ $aiSettings = [];
+ if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $aiSettings = $row;
+ }
+
+ $canTranslateCategories = !empty($aiSettings['enabled']) && !empty($aiSettings['model']) && $lang != 'en';
+ ?>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('categories', $i18n) ?></h2>
+ </header>
+ <div class="account-categories">
+ <div id="categories" class="sortable-list">
+ <?php
+ foreach ($categories as $category) {
+ if ($category['id'] != 1) {
+ $canDelete = true;
+
+ $query = "SELECT COUNT(*) as count FROM subscriptions WHERE (category_id = :categoryId OR id IN (SELECT subscription_id FROM subscription_categories WHERE category_id = :categoryId)) AND user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(':categoryId', $category['id'], SQLITE3_INTEGER);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $isUsed = $row['count'];
+
+ if ($isUsed > 0) {
+ $canDelete = false;
+ }
+ ?>
+ <div class="form-group-inline" data-categoryid="<?= $category['id'] ?>">
+ <div class=" drag-icon"><i class="fa-solid fa-grip-vertical"></i></div>
+ <input type="text" name="category" autocomplete="off" value="<?= htmlspecialchars($category['name']) ?>"
+ placeholder="Category">
+ <button class="image-button medium" onClick="editCategory(<?= $category['id'] ?>)" name="save"
+ title="<?= translate('save_category', $i18n) ?>">
+ <i class="fa-solid fa-check"></i>
+ </button>
+ <?php
+ if ($canDelete) {
+ ?>
+ <button class="image-button medium" onClick="removeCategory(<?= $category['id'] ?>)"
+ title="<?= translate('delete_category', $i18n) ?>">
+ <i class="fa-solid fa-trash-can"></i>
+ </button>
+ <?php
+ } else {
+ ?>
+ <button class="image-button medium disabled"
+ title="<?= translate('cant_delete_category_in_use', $i18n) ?>">
+ <i class="fa-solid fa-trash-can"></i>
+ </button>
+ <?php
+ }
+ ?>
+ </div>
+ <?php
+ }
+ }
+ ?>
+ </div>
+ <div class="buttons">
+ <input type="submit" value="<?= translate('add', $i18n) ?>" id="addCategory"
+ onClick="addCategoryButton()" class="thin mobile-grow" />
+ <?php
+ if ($canTranslateCategories) {
+ ?>
+ <button type="button" class="button secondary-button thin mobile-grow" id="translateCategories"
+ onClick="translateCategories()">
+ <i class="fa-solid fa-language"></i>
+ <?= translate('translate_categories', $i18n) ?>
+ </button>
+ <?php
+ }
+ ?>
+ </div>
+ </div>
+ </section>
+
+ <?php
+ $sql = "SELECT * FROM currencies WHERE user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result) {
+ $currencies = array();
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $currencies[] = $row;
+ }
+ }
+
+ $query = "SELECT main_currency FROM user WHERE id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $mainCurrencyId = $row['main_currency'];
+
+ $query = "SELECT date FROM last_exchange_update";
+ $exchange_rates_last_updated = $db->querySingle($query);
+
+ ?>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('currencies', $i18n) ?></h2>
+ </header>
+ <div class="account-currencies">
+ <div id="currencies">
+ <?php
+ foreach ($currencies as $currency) {
+ $canDelete = true;
+ $isMainCurrency = false;
+ if ($currency['id'] === $mainCurrencyId) {
+ $canDelete = false;
+ $isMainCurrency = true;
+ } else {
+ $query = "SELECT COUNT(*) as count FROM subscriptions WHERE currency_id = :currencyId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(':currencyId', $currency['id'], SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $isUsed = $row['count'];
+
+ if ($isUsed > 0) {
+ $canDelete = false;
+ }
+ }
+ ?>
+
+ <div class="form-group-inline" data-currencyid="<?= $currency['id'] ?>">
+ <input type="text" class="short" name="symbol" autocomplete="off" value="<?= htmlspecialchars($currency['symbol']) ?>"
+ placeholder="$">
+ <input type="text" name="currency" autocomplete="off" value="<?= htmlspecialchars($currency['name']) ?>"
+ placeholder="Currency Name">
+ <input type="text" name="code" autocomplete="off" value="<?= htmlspecialchars($currency['code']) ?>"
+ placeholder="Currency Code" <?= !$canDelete ? 'disabled' : '' ?>>
+ <button class="image-button medium" onClick="editCurrency(<?= $currency['id'] ?>)" name="save"
+ title="<?= translate('save_currency', $i18n) ?>">
+ <i class="fa-solid fa-check"></i>
+ </button>
+ <?php
+ if ($canDelete) {
+ ?>
+ <button class="image-button medium" onClick="removeCurrency(<?= $currency['id'] ?>)"
+ title="<?= translate('delete_currency', $i18n) ?>">
+ <i class="fa-solid fa-trash-can"></i>
+ </button>
+ <?php
+ } else {
+ $cantDeleteMessage = $isMainCurrency ? translate('cant_delete_main_currency', $i18n) : translate('cant_delete_currency_in_use', $i18n);
+ ?>
+ <button class="image-button medium disabled" title="<?= $cantDeleteMessage ?>">
+ <i class="fa-solid fa-trash-can"></i>
+ </button>
+ <?php
+ }
+ ?>
+
+ </div>
+ <?php
+ }
+ ?>
+ </div>
+ <div class="buttons">
+ <input type="submit" value="<?= translate('add', $i18n) ?>" id="addCurrency"
+ onClick="addCurrencyButton()" class="thin mobile-grow" />
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i>
+ <?= translate('exchange_update', $i18n) ?>
+ <span>
+ <?= $exchange_rates_last_updated ?>
+ </span>
+ </p>
+ <p>
+ <i class="fa-solid fa-circle-info"></i>
+ <?= translate('currency_info', $i18n) ?>
+ <span>
+ fixer.io
+ <a href="https://fixer.io/symbols" target="_blank" title="Currency codes">
+ <i class="fa-solid fa-arrow-up-right-from-square"></i>
+ </a>
+ </span>
+ </p>
+ <p>
+ <?= translate('currency_performance', $i18n) ?>
+ </p>
+ </div>
+ </div>
+ </section>
+
+ <?php
+ $apiKey = "";
+ $sql = "SELECT api_key, provider FROM fixer WHERE user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ if ($result) {
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ if ($row) {
+ $apiKey = $row['api_key'];
+ $provider = $row['provider'];
+ } else {
+ $provider = 0;
+ }
+ }
+ ?>
+
+ <section class="account-section">
+ <header>
+ <h2>Fixer API Key</h2>
+ </header>
+ <div class="account-fixer">
+ <div class="form-group">
+ <input type="text" name="fixer-key" id="fixerKey" autocomplete="off" value="<?= htmlspecialchars($apiKey) ?>"
+ placeholder="<?= translate('api_key', $i18n) ?>" <?= $demoMode ? 'disabled title="Not available on Demo Mode"' : '' ?>>
+ </div>
+ <div class="form-group">
+ <label for="fixerProvider"><?= translate('provider', $i18n) ?>:</label>
+ <select name="fixer-provider" id="fixerProvider">
+ <option value="0" <?= $provider == 0 ? 'selected' : '' ?>>fixer.io</option>
+ <option value="1" <?= $provider == 1 ? 'selected' : '' ?>>apilayer.com</option>
+ <option value="2" <?= $provider == 2 ? 'selected' : '' ?>>frankfurter.dev</option>
+ </select>
+ </div>
+ <div class="buttons">
+ <input type="submit" value="<?= translate('save', $i18n) ?>" id="addFixerKey"
+ onClick="addFixerKeyButton()" class="thin mobile-grow" />
+ </div>
+ <div class="api-usage" id="fixerUsage" style="display: none;">
+ <div class="api-usage-label">
+ <span><?= translate('monthly_requests_used', $i18n) ?></span>
+ <span id="fixerUsageCount"></span>
+ </div>
+ <div class="api-usage-track">
+ <span class="api-usage-fill" id="fixerUsageFill"></span>
+ </div>
+ </div>
+ <div class="settings-notes">
+ <p><i class="fa-solid fa-circle-info"></i><?= translate('fixer_info', $i18n) ?></p>
+ <p><?= translate('get_key', $i18n) ?>:
+ <span>
+ https://fixer.io/
+ <a href="https://fixer.io/#pricing_plan"
+ title="<?= translate("get_free_fixer_api_key", $i18n) ?>" target="_blank">
+ <i class="fa-solid fa-arrow-up-right-from-square"></i>
+ </a>
+ </span>
+ </p>
+ <p>
+ <?= translate("get_key_alternative", $i18n) ?>
+ <span>
+ https://apilayer.com
+ <a href="https://apilayer.com/marketplace/fixer-api" title="Get free fixer api key"
+ target="_blank">
+ <i class="fa-solid fa-arrow-up-right-from-square"></i>
+ </a>
+ </span>
+ </p>
+ <p>
+ <?= translate("no_api_key_provider", $i18n) ?>
+ <span>
+ https://frankfurter.dev
+ <a href="https://frankfurter.dev" title="Frankfurter" target="_blank">
+ <i class="fa-solid fa-arrow-up-right-from-square"></i>
+ </a>
+ </span>
+ </p>
+ </div>
+ </div>
+ </section>
+
+ <?php
+ $googleSearchApiKey = "";
+ if ($db->querySingle("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='google_search'") > 0) {
+ $sql = "SELECT api_key FROM google_search WHERE user_id = :userId";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ if ($result && ($row = $result->fetchArray(SQLITE3_ASSOC))) {
+ $googleSearchApiKey = $row['api_key'];
+ }
+ }
+ ?>
+
+ <section class="account-section">
+ <header>
+ <h2>Google Search (SerpAPI)</h2>
+ </header>
+ <div class="account-google-search">
+ <div class="form-group">
+ <input type="text" name="google-search-key" id="googleSearchKey" autocomplete="off"
+ value="<?= htmlspecialchars($googleSearchApiKey) ?>" placeholder="<?= translate('api_key', $i18n) ?>"
+ <?= $demoMode ? 'disabled title="Not available on Demo Mode"' : '' ?>>
+ </div>
+ <div class="buttons">
+ <input type="submit" value="<?= translate('save', $i18n) ?>" id="saveGoogleSearch"
+ onClick="saveGoogleSearchButton()" class="thin mobile-grow" />
+ </div>
+ <div class="api-usage" id="googleSearchUsage" style="display: none;">
+ <div class="api-usage-label">
+ <span><?= translate('monthly_searches_used', $i18n) ?></span>
+ <span id="googleSearchUsageCount"></span>
+ </div>
+ <div class="api-usage-track">
+ <span class="api-usage-fill" id="googleSearchUsageFill"></span>
+ </div>
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i>
+ <?= translate('google_search_info', $i18n) ?>
+ </p>
+ <p><?= translate('get_key', $i18n) ?>:
+ <span>
+ https://serpapi.com/
+ <a href="https://serpapi.com/users/sign_up?plan=free" title="SerpAPI"
+ target="_blank" rel="noreferrer">
+ <i class="fa-solid fa-arrow-up-right-from-square"></i>
+ </a>
+ </span>
+ </p>
+ </div>
+ </div>
+ </section>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('ai_recommendations', $i18n) ?></h2>
+ </header>
+ <div class="account-ai-settings">
+ <div class="form-group-inline">
+ <input type="checkbox" id="ai_enabled" name="ai_enabled" <?= isset($aiSettings['enabled']) && $aiSettings['enabled'] ? "checked" : "" ?>>
+ <label for="ai_enabled" class="capitalize"><?= translate('enabled', $i18n) ?></label>
+ </div>
+ <div class="form-group">
+ <label for="ai_type"><?= translate('provider', $i18n) ?>:</label>
+ <select id="ai_type" name="ai_type" onchange="toggleAiInputs()">
+ <option value="chatgpt" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'chatgpt') ? 'selected' : '' ?>>ChatGPT</option>
+ <option value="gemini" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'gemini') ? 'selected' : '' ?>>Gemini</option>
+ <option value="openrouter" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'openrouter') ? 'selected' : '' ?>>OpenRouter</option>
+ <option value="ollama" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'ollama') ? 'selected' : '' ?>>Local Ollama</option>
+ <option value="openai-compatible" <?= (isset($aiSettings['type']) && $aiSettings['type'] == 'openai-compatible') ? 'selected' : '' ?>>OpenAI Compatible</option>
+ </select>
+ </div>
+ <div class="form-group-inline" id="ai_url_group"
+ <?= (!isset($aiSettings['type']) || !in_array($aiSettings['type'], ['ollama', 'openai-compatible'])) ? 'style="display:none"' : '' ?>>
+ <input type="text" id="ai_ollama_host" name="ai_ollama_host" autocomplete="off"
+ placeholder="<?= (isset($aiSettings['type']) && $aiSettings['type'] == 'openai-compatible') ? 'http://localhost:11434/v1' : 'http://localhost:11434' ?>"
+ value="<?= isset($aiSettings['url']) ? htmlspecialchars($aiSettings['url']) : '' ?>" />
+ <button type="button" id="fetchModelsButton2"
+ class="button thin <?= (!isset($aiSettings['type']) || $aiSettings['type'] != 'ollama') ? 'hidden' : '' ?>"
+ onclick="fetch_ai_models()">
+ <?= translate('test', $i18n) ?>
+ </button>
+ </div>
+ <div class="form-group-inline">
+ <input type="password" id="ai_api_key" name="ai_api_key" autocomplete="off"
+ class="<?= (isset($aiSettings['type']) && $aiSettings['type'] == 'ollama') ? 'hidden' : '' ?>"
+ placeholder="<?= translate('api_key', $i18n) ?>"
+ value="<?= isset($aiSettings['api_key']) ? htmlspecialchars($aiSettings['api_key']) : '' ?>" />
+ <button type="button" id="fetchModelsButton" class="button thin" onclick="fetch_ai_models()">
+ <?= translate('test', $i18n) ?>
+ </button>
+ </div>
+ <div class="form-group">
+ <label for="ai_model"><?= translate('ai_model', $i18n) ?>:</label>
+ <select id="ai_model" name="ai_model">
+ <option value=""><?= translate('select_ai_model', $i18n) ?></option>
+ <?php if (!empty($aiSettings['model'])): ?>
+ <option value="<?= htmlspecialchars($aiSettings['model']) ?>" selected>
+ <?= htmlspecialchars($aiSettings['model']) ?>
+ </option>
+ <?php endif; ?>
+ </select>
+ </div>
+ <div class="form-group">
+ <label for="ai_run_schedule" class="flex"><?= translate('run_schedule', $i18n) ?>:</label>
+ <select id="ai_run_schedule" name="ai_run_schedule">
+ <option value="manual" <?= (isset($aiSettings['run_schedule']) && $aiSettings['run_schedule'] == 'manual') ? 'selected' : '' ?>><?= translate('manually', $i18n) ?>
+ </option>
+ <option value="weekly" <?= (isset($aiSettings['run_schedule']) && $aiSettings['run_schedule'] == 'weekly') ? 'selected' : '' ?>><?= translate('Weekly', $i18n) ?>
+ </option>
+ <option value="monthly" <?= (isset($aiSettings['run_schedule']) && $aiSettings['run_schedule'] == 'monthly') ? 'selected' : '' ?>><?= translate('Monthly', $i18n) ?>
+ </option>
+ </select>
+ </div>
+ <div class="buttons wrap mobile-reverse">
+ <?php
+ $canBeExecuted = !empty($aiSettings['model']) && !empty($aiSettings['enabled']) && $aiSettings['enabled'] == 1;
+ ?>
+ <input type="button" id="runAiRecommendations"
+ class="secondary-button thin mobile-grow-force <?= !$canBeExecuted ? 'hidden' : '' ?>"
+ onclick="runAiRecommendations()" value="<?= translate('generate_recommendations', $i18n) ?>" />
+ <div id="aiSpinner" class="spinner ai-spinner hidden"></div>
+
+ <input type="submit" class="thin mobile-grow-force" value="<?= translate('save', $i18n) ?>"
+ id="saveAiSettings" onClick="saveAiSettingsButton()" />
+ </div>
+ <div class="settings-notes">
+ <p><i class="fa-solid fa-circle-info"></i><?= translate('ai_recommendations_info', $i18n) ?></p>
+ <p><i class="fa-solid fa-circle-info"></i><?= translate('may_take_time', $i18n) ?></p>
+ <p><i
+ class="fa-solid fa-circle-info"></i><?= translate('recommendations_visible_on_dashboard', $i18n) ?>
+ </p>
+ </div>
+ </div>
+ </section>
+
+ <?php
+ $sql = "SELECT * FROM payment_methods WHERE user_id = :userId ORDER BY `order` ASC";
+ $stmt = $db->prepare($sql);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result) {
+ $payments = array();
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $payments[] = $row;
+ }
+ }
+ ?>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('payment_methods', $i18n) ?></h2>
+ </header>
+ <div class="payments-list" id="payments-list">
+ <?php
+ $paymentsInUseQuery = $db->prepare('SELECT id FROM payment_methods WHERE user_id = :userId AND id IN (SELECT DISTINCT payment_method_id FROM subscriptions WHERE user_id = :userId)');
+ $paymentsInUseQuery->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $paymentsInUseQuery->execute();
+
+ $paymentsInUse = [];
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $paymentsInUse[] = $row['id'];
+ }
+
+ foreach ($payments as $payment) {
+ $paymentIconFolder = (strpos($payment['icon'], 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";
+
+ $inUse = in_array($payment['id'], $paymentsInUse);
+ ?>
+ <div class="payments-payment" data-enabled="<?= $payment['enabled']; ?>"
+ data-in-use="<?= $inUse ? 'yes' : 'no' ?>" data-paymentid="<?= $payment['id'] ?>"
+ title="<?= $inUse ? translate('cant_delete_payment_method_in_use', $i18n) : ($payment['enabled'] ? translate('disable', $i18n) : translate('enable', $i18n)) ?>">
+ <div class="drag-icon" title="">
+ <i class="fa-solid fa-grip-vertical"></i>
+ </div>
+ <img src="<?= $paymentIconFolder . $payment['icon'] ?>" alt="Logo" />
+ <span class="payment-name" contenteditable="true"
+ title="<?= translate("rename_payment_method", $i18n) ?>"><?= htmlspecialchars($payment['name']) ?></span>
+ <?php
+ if (!$inUse) {
+ ?>
+ <div class="delete-payment-method" title="<?= translate('delete', $i18n) ?>"
+ data-paymentid="<?= $payment['id'] ?>">x</div>
+ <?php
+ }
+ ?>
+ </div>
+ <?php
+ }
+ ?>
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i>
+ <?= translate('payment_methods_info', $i18n) ?>
+ </p>
+ <p>
+ <i class="fa-solid fa-circle-info"></i>
+ <?= translate('rename_payment_methods_info', $i18n) ?>
+ </p>
+ </div>
+ <header>
+ <h2 class="second-header"><?= translate("add_custom_payment", $i18n) ?></h2>
+ </header>
+ <div>
+ <form id="payments-form">
+ <div class="form-group-inline">
+ <input type="text" name="paymentname" id="paymentname" autocomplete="off"
+ placeholder="<?= translate('payment_method_name', $i18n) ?>" onchange="setSearchButtonStatus()"
+ onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" />
+ <label for="paymenticon" class="icon-preview">
+ <img src="" alt="<?= translate('logo_preview', $i18n) ?>" id="form-icon">
+ </label>
+ <div class="form-icon-search">
+ <input type="file" id="paymenticon" name="paymenticon"
+ accept="image/jpeg, image/png, image/gif, image/webp" onchange="handleFileSelect(event)"
+ class="hidden-input">
+ <input type="hidden" id="icon-url" name="icon-url">
+ <div id="icon-search-button" class="image-button medium disabled"
+ title="<?= translate('search_logo', $i18n) ?>" onClick="searchPaymentIcon()">
+ <i class="fa-solid fa-magnifying-glass"></i>
+ </div>
+ <div class="icon-search-backdrop" id="icon-search-backdrop" onClick="closeIconSearch()"></div>
+ <div id="icon-search-results" class="icon-search">
+ <button type="button" class="close-icon-search" onClick="closeIconSearch()" title="<?= translate('cancel', $i18n) ?>">
+ <i class="fa-solid fa-xmark"></i>
+ </button>
+ <header>
+ <h3 id="icon-search-title" data-title="<?= translate('web_search', $i18n) ?>">
+ <?= translate('web_search', $i18n) ?>
+ </h3>
+ </header>
+ <div id="icon-search-images"></div>
+ </div>
+ </div>
+
+ <input type="button" class="button thin" id="add-payment-button" value="+"
+ title="<?= translate('add', $i18n) ?>" id="addPayment" onClick="addPaymentMethod()" />
+ </div>
+ </form>
+ </div>
+ </section>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('theme_settings', $i18n) ?></h2>
+ </header>
+ <div class="account-settings-theme">
+ <div>
+ <h3><?= translate('theme', $i18n) ?></h3>
+ <div class="form-group-inline wrap">
+ <button type="button"
+ class="dark-theme-button capitalize <?= $settings['dark_theme'] == '0' ? 'selected' : '' ?>"
+ onClick="setDarkTheme('0')" id="theme-light">
+ <i class="fa-solid fa-sun"></i> <?= translate('light_theme', $i18n) ?>
+ </button>
+ <button type="button"
+ class="dark-theme-button capitalize <?= $settings['dark_theme'] == '1' ? 'selected' : '' ?>"
+ onClick="setDarkTheme('1')" id="theme-dark">
+ <i class="fa-solid fa-moon"></i> <?= translate('dark_theme', $i18n) ?>
+ </button>
+ <button type="button"
+ class="dark-theme-button capitalize <?= $settings['dark_theme'] == '2' ? 'selected' : '' ?>"
+ onClick="setDarkTheme('2')" id="theme-automatic">
+ <i class="fa-solid fa-circle-half-stroke"></i> <?= translate('automatic', $i18n) ?>
+ </button>
+ </div>
+ </div>
+ <div>
+ <form class="theme-selector">
+ <h3><?= translate('colors', $i18n) ?></h3>
+ <div class="form-group-inline wrap">
+ <div class="theme">
+ <input type="radio" name="theme" id="theme-blue" value="blue" onClick="setTheme('blue')"
+ <?= $settings['color_theme'] == 'blue' ? 'checked' : '' ?>>
+ <label for="theme-blue"
+ class="theme-preview blue <?= $settings['color_theme'] == 'blue' ? 'is-selected' : '' ?>">
+ <span class="main-color"></span>
+ <span class="accent-color"></span>
+ <span class="hover-color"></span>
+ </label>
+ </div>
+ <div class="theme">
+ <input type="radio" name="theme" id="theme-green" value="green" onClick="setTheme('green')"
+ <?= $settings['color_theme'] == 'green' ? 'checked' : '' ?>>
+ <label for="theme-green"
+ class="theme-preview green <?= $settings['color_theme'] == 'green' ? 'is-selected' : '' ?>">
+ <span class="main-color"></span>
+ <span class="accent-color"></span>
+ <span class="hover-color"></span>
+ </label>
+ </div>
+ <div class="theme">
+ <input type="radio" name="theme" id="theme-red" value="red" onClick="setTheme('red')"
+ <?= $settings['color_theme'] == 'red' ? 'checked' : '' ?>>
+ <label for="theme-red"
+ class="theme-preview red <?= $settings['color_theme'] == 'red' ? 'is-selected' : '' ?>">
+ <span class="main-color"></span>
+ <span class="accent-color"></span>
+ <span class="hover-color"></span>
+ </label>
+ </div>
+ <div class="theme">
+ <input type="radio" name="theme" id="theme-yellow" value="yellow"
+ onClick="setTheme('yellow')" <?= $settings['color_theme'] == 'yellow' ? 'checked' : '' ?>>
+ <label for="theme-yellow"
+ class="theme-preview yellow <?= $settings['color_theme'] == 'yellow' ? 'is-selected' : '' ?>">
+ <span class="main-color"></span>
+ <span class="accent-color"></span>
+ <span class="hover-color"></span>
+ </label>
+ </div>
+ <div class="theme">
+ <input type="radio" name="theme" id="theme-purple" value="purple"
+ onClick="setTheme('purple')" <?= $settings['color_theme'] == 'purple' ? 'checked' : '' ?>>
+ <label for="theme-purple"
+ class="theme-preview purple <?= $settings['color_theme'] == 'purple' ? 'is-selected' : '' ?>">
+ <span class="main-color"></span>
+ <span class="accent-color"></span>
+ <span class="hover-color"></span>
+ </label>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div>
+ <h3><?= translate('custom_colors', $i18n) ?></h3>
+ <div class="custom-colors wrap">
+ <div class="form-group-inline mobile-grow color-picker-button">
+ <input type="color" id="mainColor" name="mainColor"
+ value="<?= isset($settings['customColors']['main_color']) ? $settings['customColors']['main_color'] : '#FFFFFF' ?>"
+ class="color-picker fa-solid fa-eye-dropper">
+ <label for="mainColor"><?= translate('main_color', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline mobile-grow color-picker-button">
+ <input type="color" id="accentColor" name="accentColor"
+ value="<?= isset($settings['customColors']['accent_color']) ? $settings['customColors']['accent_color'] : '#FFFFFF' ?>"
+ class="color-picker fa-solid fa-eye-dropper">
+ <label for="accentColor"><?= translate('accent_color', $i18n) ?></label>
+ </div>
+ <div class="form-group-inline mobile-grow color-picker-button">
+ <input type="color" id="hoverColor" name="hoverColor"
+ value="<?= isset($settings['customColors']['hover_color']) ? $settings['customColors']['hover_color'] : '#FFFFFF' ?>"
+ class="color-picker fa-solid fa-eye-dropper">
+ <label for="hoverColor"><?= translate('hover_color', $i18n) ?></label>
+ </div>
+ </div>
+ <div class="custom-colors wrap">
+ <input type="button" value="<?= translate('reset_custom_colors', $i18n) ?>"
+ onClick="resetCustomColors()" class="secondary-button thin mobile-grow" id="reset-colors">
+ <input type="button" value="<?= translate('save_custom_colors', $i18n) ?>"
+ onClick="saveCustomColors()" class="buton thin mobile-grow" id="save-colors">
+ </div>
+ </div>
+ <?php
+ if (!$demoMode) {
+ ?>
+ <div>
+ <h3><?= translate('custom_css', $i18n) ?></h3>
+ <div class="form-group">
+ <div class="form-group-inline">
+ <textarea name="customCss" id="customCss" placeholder="<?= translate('custom_css', $i18n) ?>"
+ class="thin"><?= $settings['customCss'] ?? "" ?></textarea>
+ </div>
+ <div class="form-group-inline">
+ <input type="button" value="<?= translate('save_custom_css', $i18n) ?>"
+ onClick="saveCustomCss()" class="buton thin mobile-grow" id="save-css">
+ </div>
+ </div>
+ </div>
+ <?php
+ }
+ ?>
+ </section>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('display_settings', $i18n) ?></h2>
+ </header>
+ <div class="account-settings-list">
+ <h3><?= translate('price', $i18n) ?></h3>
+ <div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="monthlyprice" name="monthlyprice" onChange="setShowMonthlyPrice()" <?php if ($settings['monthly_price'])
+ echo 'checked'; ?>>
+ <label for="monthlyprice"><?= translate('calculate_monthly_price', $i18n) ?></label>
+ </div>
+ </div>
+ <div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="convertcurrency" name="convertcurrency" onChange="setConvertCurrency()"
+ <?php
+ if ($settings['convert_currency'])
+ echo ' checked';
+ if ($apiKey == "")
+ echo ' disabled';
+ ?>>
+ <label for="convertcurrency"><?= translate('convert_prices', $i18n) ?></label>
+ </div>
+ </div>
+ <div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="showoriginalprice" name="showoriginalprice"
+ onChange="setShowOriginalPrice()" <?= $settings['show_original_price'] ? 'checked' : '' ?>>
+ <label for="showoriginalprice"><?= translate('show_original_price', $i18n) ?></label>
+ </div>
+ </div>
+ <div>
+ <div class="form-group">
+ <label for="upcomingpaymentslimit"><?= translate('upcoming_payments_to_show', $i18n) ?></label>
+ <select id="upcomingpaymentslimit" name="upcomingpaymentslimit" onChange="setUpcomingPaymentsLimit()">
+ <option value="3" <?= $upcomingPaymentsLimit === 3 ? 'selected' : '' ?>>3</option>
+ <option value="5" <?= $upcomingPaymentsLimit === 5 ? 'selected' : '' ?>>5</option>
+ <option value="10" <?= $upcomingPaymentsLimit === 10 ? 'selected' : '' ?>>10</option>
+ <option value="20" <?= $upcomingPaymentsLimit === 20 ? 'selected' : '' ?>>20</option>
+ </select>
+ </div>
+ </div>
+ <h3><?= translate('experience', $i18n) ?></h3>
+ <div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="mobilenavigation" name="mobilenavigation"
+ onChange="setMobileNavigation()" <?= $settings['mobile_nav'] ? 'checked' : '' ?>>
+ <label for="mobilenavigation"><?= translate('use_mobile_navigation_bar', $i18n) ?></label>
+ </div>
+ <div class="mobile-nav-image">
+ </div>
+ </div>
+ <div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="showsubscriptionprogress" name="showsubscriptionprogress"
+ onChange="setShowSubscriptionProgress()" <?= $settings['show_subscription_progress'] ? 'checked' : '' ?>>
+ <label for="showsubscriptionprogress"><?= translate('show_subscription_progress', $i18n) ?></label>
+ </div>
+ </div>
+ <div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="weekstartssunday" name="weekstartssunday"
+ onChange="setWeekStartsSunday()" <?= !empty($settings['week_starts_sunday']) ? 'checked' : '' ?>>
+ <label for="weekstartssunday"><?= translate('week_starts_on_sunday', $i18n) ?></label>
+ </div>
+ </div>
+ <h3><?= translate('disabled_subscriptions', $i18n) ?></h3>
+ <div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="disabledtobottom" name="disabledtobottom"
+ onChange="setDisabledToBottom()" <?= $settings['disabled_to_bottom'] ? 'checked' : '' ?>>
+ <label
+ for="disabledtobottom"><?= translate('show_disabled_subscriptions_at_the_bottom', $i18n) ?></label>
+ </div>
+ </div>
+ <div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="hidedisabled" name="hidedisabled" onChange="setHideDisabled()"
+ <?= $settings['hide_disabled'] ? 'checked' : '' ?>>
+ <label for="hidedisabled"><?= translate('hide_disabled_subscriptions', $i18n) ?></label>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="account-section">
+ <header>
+ <h2><?= translate('experimental_settings', $i18n) ?></h2>
+ </header>
+ <div class="account-settings-list">
+ <div>
+ <div class="form-group-inline">
+ <input type="checkbox" id="removebackground" name="removebackground"
+ onChange="setRemoveBackground()" <?= $settings['remove_background'] ? 'checked' : '' ?>>
+ <label for="removebackground"><?= translate('remove_background', $i18n) ?></label>
+ </div>
+ </div>
+ </div>
+ <div class="settings-notes">
+ <p>
+ <i class="fa-solid fa-circle-info"></i>
+ <?= translate('remove_background_info', $i18n) ?>
+ </p>
+ <p>
+ <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i>
+ <?= translate('experimental_info', $i18n) ?>
+ </p>
+ </div>
+ </section>
+
+</section>
+<script>
+ // The raw applicationServerKey bytes pushManager.subscribe() needs -
+ // not a secret, the same value every push service and the VAPID
+ // Authorization header's "k=" parameter are handed too.
+ window.vapidPublicKey = "<?= htmlspecialchars($vapidPublicKey, ENT_QUOTES, 'UTF-8') ?>";
+</script>
+<script src="scripts/settings.js?<?= $version ?>"></script>
+<script src="scripts/theme.js?<?= $version ?>"></script>
+<script src="scripts/notifications.js?<?= $version ?>"></script>
+
+<?php
+require_once 'includes/footer.php';
+?>
diff --git a/subscriptions.php b/subscriptions.php
index 8d26eda..0676da2 100644
--- a/subscriptions.php
+++ b/subscriptions.php
@@ -1,612 +1,612 @@
-<?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';
-require_once 'includes/subscription_categories.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']);
- $sql .= " AND " . categoryFilterCondition($categoryIds, $params);
-}
-
-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);
-$categoriesBySubscription = getCategoriesBySubscription($db, $subscriptions);
-
-foreach ($subscriptions as $subscription) {
- foreach ($payersBySubscription[$subscription['id']] ?? [] as $memberId) {
- if (isset($members[$memberId])) {
- $members[$memberId]['count']++;
- }
- }
- foreach ($categoriesBySubscription[$subscription['id']] ?? [] as $categoryId) {
- 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]['category_ids'] = $categoriesBySubscription[$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_toggle"><?= translate('category', $i18n) ?></label>
- <div class="multi-select" id="category_select" data-placeholder="<?= translate('none', $i18n) ?>">
- <button type="button" class="multi-select-toggle" id="category_toggle" aria-haspopup="listbox"
- aria-expanded="false" aria-controls="category_options">
- <span class="multi-select-label"></span>
- </button>
- <ul class="multi-select-options" id="category_options" role="listbox" aria-multiselectable="true"
- aria-labelledby="category_toggle" tabindex="-1" hidden>
- <?php
- foreach ($categories as $category) {
- ?>
- <li role="option" aria-selected="false" data-value="<?= $category['id'] ?>">
- <span class="multi-select-check"></span>
- <span class="multi-select-name"><?= $category['name'] ?></span>
- </li>
- <?php
- }
- ?>
- </ul>
- <input type="hidden" name="category_id" id="category" value="">
- </div>
- </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';
+require_once 'includes/subscription_categories.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']);
+ $sql .= " AND " . categoryFilterCondition($categoryIds, $params);
+}
+
+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);
+$categoriesBySubscription = getCategoriesBySubscription($db, $subscriptions);
+
+foreach ($subscriptions as $subscription) {
+ foreach ($payersBySubscription[$subscription['id']] ?? [] as $memberId) {
+ if (isset($members[$memberId])) {
+ $members[$memberId]['count']++;
+ }
+ }
+ foreach ($categoriesBySubscription[$subscription['id']] ?? [] as $categoryId) {
+ 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]['category_ids'] = $categoriesBySubscription[$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_toggle"><?= translate('category', $i18n) ?></label>
+ <div class="multi-select" id="category_select" data-placeholder="<?= translate('none', $i18n) ?>">
+ <button type="button" class="multi-select-toggle" id="category_toggle" aria-haspopup="listbox"
+ aria-expanded="false" aria-controls="category_options">
+ <span class="multi-select-label"></span>
+ </button>
+ <ul class="multi-select-options" id="category_options" role="listbox" aria-multiselectable="true"
+ aria-labelledby="category_toggle" tabindex="-1" hidden>
+ <?php
+ foreach ($categories as $category) {
+ ?>
+ <li role="option" aria-selected="false" data-value="<?= $category['id'] ?>">
+ <span class="multi-select-check"></span>
+ <span class="multi-select-name"><?= $category['name'] ?></span>
+ </li>
+ <?php
+ }
+ ?>
+ </ul>
+ <input type="hidden" name="category_id" id="category" value="">
+ </div>
+ </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';
+?>