Skip to content

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

feat(subscriptions): allow several categories per subscription

Miguel Ribeirod750eacc6b6b
diff --git a/api/categories/get_categories.php b/api/categories/get_categories.php
index ea6f598..962a85e 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";
- $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/categories/set_categories.php b/api/categories/set_categories.php
index 59982d5..23ef1c4 100644
--- a/api/categories/set_categories.php
+++ b/api/categories/set_categories.php
@@ -216,7 +216,7 @@ switch ($action) {
}
// Check if category is in use
- $checkUseSql = "SELECT COUNT(*) FROM subscriptions WHERE category_id = :categoryId AND user_id = :userId";
+ $checkUseSql = "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";
$checkUseStmt = $db->prepare($checkUseSql);
$checkUseStmt->bindParam(':categoryId', $categoryId, SQLITE3_INTEGER);
$checkUseStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
diff --git a/api/subscriptions/get_ical_feed.php b/api/subscriptions/get_ical_feed.php
index 9a02acf..f03d2d0 100644
--- a/api/subscriptions/get_ical_feed.php
+++ b/api/subscriptions/get_ical_feed.php
@@ -12,6 +12,7 @@ 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');
@@ -129,6 +130,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET
}
$payersBySubscription = getPayersBySubscription($db, $subscriptions);
+ $categoriesBySubscription = getCategoriesBySubscription($db, $subscriptions);
foreach ($subscriptions as $subscription) {
$subscriptionToReturn = $subscription;
@@ -143,7 +145,8 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET
$subscriptionToReturn['price'] = $subscription['price'];
}
- $subscriptionToReturn['category_name'] = isset($categories[$subscription['category_id']]) ? $categories[$subscription['category_id']] : 'No category';
+ $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';
diff --git a/api/subscriptions/get_subscription.php b/api/subscriptions/get_subscription.php
index 1311203..598ee5a 100644
--- a/api/subscriptions/get_subscription.php
+++ b/api/subscriptions/get_subscription.php
@@ -39,6 +39,8 @@ Example response:
"cancelation_date": null,
"cancellation_date": "",
"category_name": "Entertainment",
+ "category_ids": [3],
+ "category_names": ["Entertainment"],
"payer_user_name": "John Doe",
"payer_user_ids": [1, 2],
"payer_user_names": ["John Doe", "Jane Doe"],
@@ -51,6 +53,7 @@ Example response:
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');
@@ -114,6 +117,17 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET
$categoryRow = $catResult->fetchArray(SQLITE3_ASSOC);
$subscription['category_name'] = $categoryRow ? $categoryRow['name'] : 'No category';
+ // All categories, the primary one first
+ $subscription['category_ids'] = getCategoriesBySubscription($db, [$subscription])[$subscription['id']] ?? [];
+ $subscription['category_names'] = [];
+ foreach ($subscription['category_ids'] as $categoryId) {
+ $namesStmt = $db->prepare("SELECT name FROM categories WHERE id = :categoryId AND user_id = :userId");
+ $namesStmt->bindValue(':categoryId', $categoryId, SQLITE3_INTEGER);
+ $namesStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $nameRow = $namesStmt->execute()->fetchArray(SQLITE3_ASSOC);
+ $subscription['category_names'][] = $nameRow ? $nameRow['name'] : 'No category';
+ }
+
// Resolve Payer Name
$payerSql = "SELECT name FROM household WHERE id = :payerId AND user_id = :userId";
$payerStmt = $db->prepare($payerSql);
diff --git a/api/subscriptions/get_subscriptions.php b/api/subscriptions/get_subscriptions.php
index 7c45076..9da3b52 100644
--- a/api/subscriptions/get_subscriptions.php
+++ b/api/subscriptions/get_subscriptions.php
@@ -47,6 +47,8 @@ Example response:
"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"],
@@ -99,6 +101,7 @@ Example response:
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');
@@ -225,13 +228,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET
}
if (isset($_REQUEST['category'])) {
$categoryIds = explode(',', $_REQUEST['category']);
- $placeholders = array_map(function ($key) {
- return ":category{$key}";
- }, array_keys($categoryIds));
- $sql .= " AND category_id IN (" . implode(',', $placeholders) . ")";
- foreach ($categoryIds as $key => $categoryId) {
- $params[":category{$key}"] = $categoryId;
- }
+ $sql .= " AND " . categoryFilterCondition($categoryIds, $params);
}
if (isset($_REQUEST['payment'])) {
$paymentIds = explode(',', $_REQUEST['payment']);
@@ -291,6 +288,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET
}
$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) {
@@ -298,6 +296,9 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET
} 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;
diff --git a/api/subscriptions/set_subscriptions.php b/api/subscriptions/set_subscriptions.php
index 5725772..844f1b3 100644
--- a/api/subscriptions/set_subscriptions.php
+++ b/api/subscriptions/set_subscriptions.php
@@ -18,7 +18,8 @@ For 'add' and 'edit' actions (all optional for 'edit'):
- payment_method_id: the payment method ID (integer).
- payer_user_id: the household member payer ID (integer), or several IDs separated by commas (1,2) / as an array
(payer_user_id[]=1&payer_user_id[]=2) when the subscription is shared. The first one is the primary payer.
-- category_id: the category ID (integer).
+- category_id: the category ID (integer), or several IDs separated by commas (1,2) / as an array
+ (category_id[]=1&category_id[]=2) when the subscription belongs to more than one. The first one is the primary category.
- notes: subscription notes (string, Markdown supported).
- url: subscription URL (string).
- logo_url: an image URL to download as the logo (string).
@@ -51,6 +52,7 @@ require_once '../../includes/inputvalidation.php';
require_once '../../includes/ssrf_helper.php';
require_once '../../includes/logo_theme_variant.php';
require_once '../../includes/subscription_payers.php';
+require_once '../../includes/subscription_categories.php';
header('Content-Type: application/json; charset=UTF-8');
@@ -376,7 +378,8 @@ switch ($action) {
$paymentMethodId = $_POST['payment_method_id'] ?? null;
$payerIds = parsePayerIds($_POST['payer_user_id'] ?? []);
$payerUserId = $payerIds[0] ?? null;
- $categoryId = $_POST['category_id'] ?? null;
+ $categoryIds = parsePayerIds($_POST['category_id'] ?? []);
+ $categoryId = $categoryIds[0] ?? null;
$notes = isset($_POST['notes']) ? validate_markdown($_POST['notes']) : '';
$url = isset($_POST['url']) ? validate($_POST['url']) : '';
@@ -465,20 +468,13 @@ switch ($action) {
}
// Category
- if ($categoryId !== null) {
- $categoryId = intval($categoryId);
- $catStmt = $db->prepare("SELECT id FROM categories WHERE id = :id AND user_id = :userId");
- $catStmt->bindValue(':id', $categoryId, SQLITE3_INTEGER);
- $catStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $catRes = $catStmt->execute()->fetchArray();
- if (!$catRes) {
- echo json_encode([
- 'success' => false,
- 'title' => 'Invalid category ID',
- 'message' => 'The specified category does not exist or does not belong to you.'
- ]);
- exit;
- }
+ if (!categoriesBelongToUser($db, $userId, $categoryIds)) {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Invalid category ID',
+ 'message' => 'The specified category does not exist or does not belong to you.'
+ ]);
+ exit;
}
// Payer user
@@ -582,6 +578,7 @@ switch ($action) {
if ($stmtInsert->execute()) {
$newSubscriptionId = $db->lastInsertRowID();
saveSubscriptionPayers($db, $newSubscriptionId, $payerIds);
+ saveSubscriptionCategories($db, $newSubscriptionId, $categoryIds);
$addResponse = [
'success' => true,
'title' => 'Subscription added',
@@ -658,9 +655,12 @@ switch ($action) {
$payerUserId = $payerIds[0] ?? null;
}
+ // null means the categories were not sent and stay as they are
+ $categoryIds = null;
$categoryId = $subscription['category_id'];
if (isset($_POST['category_id'])) {
- $categoryId = $_POST['category_id'] === '' ? null : intval($_POST['category_id']);
+ $categoryIds = parsePayerIds($_POST['category_id']);
+ $categoryId = $categoryIds[0] ?? null;
}
$notes = isset($_POST['notes']) ? validate_markdown($_POST['notes']) : $subscription['notes'];
@@ -757,19 +757,13 @@ switch ($action) {
}
// Category
- if ($categoryId !== null) {
- $catStmt = $db->prepare("SELECT id FROM categories WHERE id = :id AND user_id = :userId");
- $catStmt->bindValue(':id', $categoryId, SQLITE3_INTEGER);
- $catStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $catRes = $catStmt->execute()->fetchArray();
- if (!$catRes) {
- echo json_encode([
- 'success' => false,
- 'title' => 'Invalid category ID',
- 'message' => 'The specified category does not exist or does not belong to you.'
- ]);
- exit;
- }
+ if ($categoryIds !== null && !categoriesBelongToUser($db, $userId, $categoryIds)) {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Invalid category ID',
+ 'message' => 'The specified category does not exist or does not belong to you.'
+ ]);
+ exit;
}
// Payer
@@ -903,6 +897,9 @@ switch ($action) {
if ($payerIds !== null) {
saveSubscriptionPayers($db, $subscriptionId, $payerIds);
}
+ if ($categoryIds !== null) {
+ saveSubscriptionCategories($db, $subscriptionId, $categoryIds);
+ }
$updateResponse = [
'success' => true,
'title' => 'Subscription updated',
@@ -955,6 +952,10 @@ switch ($action) {
$stmtPayers->bindParam(':subId', $subscriptionId, SQLITE3_INTEGER);
$stmtPayers->execute();
+ $stmtCategories = $db->prepare("DELETE FROM subscription_categories WHERE subscription_id = :subId");
+ $stmtCategories->bindParam(':subId', $subscriptionId, SQLITE3_INTEGER);
+ $stmtCategories->execute();
+
$sqlDelete = "DELETE FROM subscriptions WHERE id = :subId AND user_id = :userId";
$stmtDelete = $db->prepare($sqlDelete);
$stmtDelete->bindParam(':subId', $subscriptionId, SQLITE3_INTEGER);
diff --git a/endpoints/admin/deleteuser.php b/endpoints/admin/deleteuser.php
index dd36474..0268450 100644
--- a/endpoints/admin/deleteuser.php
+++ b/endpoints/admin/deleteuser.php
@@ -38,6 +38,10 @@ if ($userId == 1) {
$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();
diff --git a/endpoints/categories/category.php b/endpoints/categories/category.php
index 4de84bf..f931a23 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 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/cronjobs/sendcancellationnotifications.php b/endpoints/cronjobs/sendcancellationnotifications.php
index f80baef..790c8e3 100644
--- a/endpoints/cronjobs/sendcancellationnotifications.php
+++ b/endpoints/cronjobs/sendcancellationnotifications.php
@@ -15,6 +15,7 @@ require __DIR__ . '/../../libs/PHPMailer/Exception.php';
require 'settimezone.php';
require_once __DIR__ . '/../../includes/webhook_headers.php';
require_once __DIR__ . '/../../includes/subscription_payers.php';
+require_once __DIR__ . '/../../includes/subscription_categories.php';
// Get all user ids
$query = "SELECT id, username FROM user";
@@ -201,7 +202,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
'name' => $rowSubscription['name'],
'price' => $rowSubscription['price'] . $currencies[$rowSubscription['currency_id']]['symbol'],
'currency' => $currencies[$rowSubscription['currency_id']]['name'],
- 'category' => $categories[$rowSubscription['category_id']]['name'],
+ 'category' => payerNamesLabel(getCategoriesBySubscription($db, [$rowSubscription])[$rowSubscription['id']] ?? [], array_map(fn($category) => $category['name'], $categories)) ?: $categories[$rowSubscription['category_id']]['name'],
'payer' => payerNamesLabel($allPayerIds, array_map(fn($member) => $member['name'], $household)) ?: $household[$rowSubscription['payer_user_id']]['name'],
'date' => $rowSubscription['next_payment'],
'url' => $rowSubscription['url'],
diff --git a/endpoints/cronjobs/sendnotifications.php b/endpoints/cronjobs/sendnotifications.php
index 48b126b..a08f003 100644
--- a/endpoints/cronjobs/sendnotifications.php
+++ b/endpoints/cronjobs/sendnotifications.php
@@ -20,6 +20,7 @@ require __DIR__ . '/../../includes/budget_period_calculations.php';
require 'settimezone.php';
require_once __DIR__ . '/../../includes/webhook_headers.php';
require_once __DIR__ . '/../../includes/subscription_payers.php';
+require_once __DIR__ . '/../../includes/subscription_categories.php';
if (php_sapi_name() == 'cli') {
$date = new DateTime('now');
@@ -396,7 +397,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
'currency' => $currencies[$rowSubscription['currency_id']]['name'],
'currency_symbol' => $currencies[$rowSubscription['currency_id']]['symbol'],
'formatted_price' => formatPrice($rowSubscription['price'], $currencies[$rowSubscription['currency_id']]['code'], $currencies[$rowSubscription['currency_id']]['symbol']),
- 'category' => $categories[$rowSubscription['category_id']]['name'],
+ 'category' => payerNamesLabel(getCategoriesBySubscription($db, [$rowSubscription])[$rowSubscription['id']] ?? [], array_map(fn($category) => $category['name'], $categories)) ?: $categories[$rowSubscription['category_id']]['name'],
'payer' => payerNamesLabel($allPayerIds, array_map(fn($member) => $member['name'], $household)) ?: $household[$rowSubscription['payer_user_id']]['name'],
'date' => $rowSubscription['next_payment'],
'days' => $daysToCompare,
diff --git a/endpoints/settings/deleteaccount.php b/endpoints/settings/deleteaccount.php
index 4d37009..afc5021 100644
--- a/endpoints/settings/deleteaccount.php
+++ b/endpoints/settings/deleteaccount.php
@@ -38,6 +38,10 @@ if ($userIdToDelete == 1 || $userIdToDelete != $userId) {
$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();
diff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.php
index bcec7f2..60f5ab5 100644
--- a/endpoints/subscription/add.php
+++ b/endpoints/subscription/add.php
@@ -8,6 +8,7 @@ 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);
@@ -245,7 +246,8 @@ $startDate = $_POST["start_date"];
$paymentMethodId = $_POST["payment_method_id"];
$payerIds = parsePayerIds($_POST["payer_user_id"] ?? "");
$payerUserId = $payerIds[0] ?? null;
-$categoryId = $_POST['category_id'];
+$categoryIds = parsePayerIds($_POST['category_id'] ?? "");
+$categoryId = $categoryIds[0] ?? null;
$notes = validate_markdown($_POST["notes"]);
$url = validate($_POST['url']);
$logoUrl = validate($_POST['logo-url']);
@@ -290,14 +292,8 @@ if (!$currResult || !$currResult->fetchArray()) {
rejectForeignId('The specified currency does not exist or does not belong to you.');
}
-if ($categoryId !== null && $categoryId !== '') {
- $catStmt = $db->prepare("SELECT id FROM categories WHERE id = :id AND user_id = :userId");
- $catStmt->bindParam(':id', $categoryId, SQLITE3_INTEGER);
- $catStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $catResult = $catStmt->execute();
- if (!$catResult || !$catResult->fetchArray()) {
- rejectForeignId('The specified category does not exist or does not belong to you.');
- }
+if (!categoriesBelongToUser($db, $userId, $categoryIds)) {
+ rejectForeignId('The specified category does not exist or does not belong to you.');
}
if (!payersBelongToUser($db, $userId, $payerIds)) {
@@ -463,6 +459,7 @@ if ($stmt->execute()) {
$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 != "") {
diff --git a/endpoints/subscription/clone.php b/endpoints/subscription/clone.php
index 4403417..3e9bfa1 100644
--- a/endpoints/subscription/clone.php
+++ b/endpoints/subscription/clone.php
@@ -2,6 +2,7 @@
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);
@@ -46,6 +47,7 @@ $cloneStmt->bindValue(':replacement_subscription_id', $subscriptionToClone['repl
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),
diff --git a/endpoints/subscription/delete.php b/endpoints/subscription/delete.php
index 5f1dd5a..55d0769 100644
--- a/endpoints/subscription/delete.php
+++ b/endpoints/subscription/delete.php
@@ -19,6 +19,11 @@ $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);
diff --git a/endpoints/subscription/exportcalendar.php b/endpoints/subscription/exportcalendar.php
index a442fc5..24616c8 100644
--- a/endpoints/subscription/exportcalendar.php
+++ b/endpoints/subscription/exportcalendar.php
@@ -3,6 +3,7 @@ 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");
@@ -26,7 +27,7 @@ $subscription = $result->fetchArray(SQLITE3_ASSOC); // Fetch the subscription de
if ($subscription) {
$subscription['payer_user'] = payerNamesLabel(getPayersBySubscription($db, [$subscription])[$subscription['id']] ?? [], array_map(fn($m) => $m['name'] ?? '', $members));
- $subscription['category'] = $categories[$subscription['category_id']]['name'];
+ $subscription['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;
diff --git a/endpoints/subscription/get.php b/endpoints/subscription/get.php
index 95a1ea5..cd8209e 100644
--- a/endpoints/subscription/get.php
+++ b/endpoints/subscription/get.php
@@ -2,6 +2,7 @@
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'] != "") {
@@ -33,6 +34,7 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
$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'] ?? "");
diff --git a/endpoints/subscription/getcalendar.php b/endpoints/subscription/getcalendar.php
index 27bade3..2dddddb 100644
--- a/endpoints/subscription/getcalendar.php
+++ b/endpoints/subscription/getcalendar.php
@@ -2,6 +2,7 @@
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([
@@ -33,7 +34,7 @@ if ($_SERVER["REQUEST_METHOD"] === "POST") {
if ($subscription) {
// get payer name from household object
$subscription['payer_user'] = payerNamesLabel(getPayersBySubscription($db, [$subscription])[$subscription['id']] ?? [], array_map(fn($m) => $m['name'] ?? '', $members));
- $subscription['category'] = $categories[$subscription['category_id']]['name'];
+ $subscription['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);
diff --git a/endpoints/subscriptions/export.php b/endpoints/subscriptions/export.php
index b050c80..d87dad4 100644
--- a/endpoints/subscriptions/export.php
+++ b/endpoints/subscriptions/export.php
@@ -10,6 +10,7 @@ if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
require_once '../../includes/getdbkeys.php';
require_once '../../includes/subscription_payers.php';
+require_once '../../includes/subscription_categories.php';
$subscriptions = array();
@@ -36,13 +37,14 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
}
$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(',', ' ', $categories[$row['category_id'] ?? '']['name'] ?? ''),
+ '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'],
diff --git a/endpoints/subscriptions/get.php b/endpoints/subscriptions/get.php
index 7158754..33898d8 100644
--- a/endpoints/subscriptions/get.php
+++ b/endpoints/subscriptions/get.php
@@ -7,6 +7,7 @@ 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';
@@ -41,17 +42,7 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if (isset($_GET['categories']) && $_GET['categories'] != "") {
$allCategories = explode(',', $_GET['categories']);
- $placeholders = array_map(function ($idx) {
- return ":categories{$idx}";
- }, array_keys($allCategories));
-
- $sql .= " AND (" . implode(' OR ', array_map(function ($placeholder) {
- return "category_id = {$placeholder}";
- }, $placeholders)) . ")";
-
- foreach ($allCategories as $idx => $category) {
- $params[":categories{$idx}"] = $category;
- }
+ $sql .= " AND " . categoryFilterCondition($allCategories, $params);
}
if (isset($_GET['payments']) && $_GET['payments'] !== "") {
@@ -166,6 +157,7 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
}
$payersBySubscription = getPayersBySubscription($db, $subscriptions);
+ $categoriesBySubscription = getCategoriesBySubscription($db, $subscriptions);
foreach ($subscriptions as $subscription) {
if ($subscription['inactive'] == 1 && isset($settings['hideDisabledSubscriptions']) && $settings['hideDisabledSubscriptions'] === 'true') {
@@ -194,6 +186,7 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
$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']);
diff --git a/includes/stats_calculations.php b/includes/stats_calculations.php
index c5d6751..3cb95ee 100644
--- a/includes/stats_calculations.php
+++ b/includes/stats_calculations.php
@@ -3,6 +3,7 @@ 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)
{
@@ -72,7 +73,7 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
}
// Unfiltered counts for filter menu display (so non-selected items remain visible when a filter is active)
-$stmt = $db->prepare("SELECT category_id, COUNT(*) as cnt FROM subscriptions WHERE user_id = :userId GROUP BY category_id");
+$stmt = $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 = [];
@@ -112,6 +113,7 @@ $conditions = [];
$params = [];
$filteredMemberIds = [];
+$filteredCategoryIds = [];
if (isset($_GET['member']) && $_GET['member'] !== '') {
$memberIds = array_map('intval', explode(',', $_GET['member']));
$filteredMemberIds = $memberIds;
@@ -125,7 +127,8 @@ if (isset($_GET['member']) && $_GET['member'] !== '') {
if (isset($_GET['category']) && $_GET['category'] !== '') {
$categoryIds = array_map('intval', explode(',', $_GET['category']));
- $conditions[] = "category_id IN (" . implode(',', $categoryIds) . ")";
+ $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
@@ -173,6 +176,7 @@ if ($result) {
if (isset($subscriptions)) {
$replacementSubscriptions = array();
$payersBySubscription = getPayersBySubscription($db, $subscriptions);
+ $categoriesBySubscription = getCategoriesBySubscription($db, $subscriptions);
foreach ($subscriptions as $subscription) {
$name = $subscription['name'];
@@ -191,9 +195,11 @@ if ($result) {
$members[$payerId]['count'] += 1;
}
}
- $categoryId = $subscription['category_id'];
- if (isset($categories[$categoryId])) {
- $categories[$categoryId]['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])) {
@@ -210,6 +216,10 @@ if ($result) {
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;
@@ -228,8 +238,13 @@ if ($result) {
$memberCost[$payerId]['cost'] += $payerShare;
}
}
- if (isset($categoryCost[$categoryId])) {
- $categoryCost[$categoryId]['cost'] += $price;
+ // 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;
diff --git a/includes/subscription_categories.php b/includes/subscription_categories.php
new file mode 100644
index 0000000..629fe7b
--- /dev/null
+++ b/includes/subscription_categories.php
@@ -0,0 +1,75 @@
+<?php
+
+// Helpers for subscriptions in several categories, the counterpart of
+// subscription_payers.php. subscription_categories is the full list,
+// subscriptions.category_id keeps the first of them (see migrations/000061.php).
+
+require_once __DIR__ . '/subscription_payers.php';
+
+// True when every id is a category of this user.
+function categoriesBelongToUser($db, $userId, array $categoryIds)
+{
+ $stmt = $db->prepare("SELECT id FROM categories WHERE id = :id AND user_id = :userId");
+ foreach ($categoryIds as $categoryId) {
+ $stmt->bindValue(':id', $categoryId, SQLITE3_INTEGER);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $found = $result && $result->fetchArray();
+ $stmt->reset();
+ if (!$found) {
+ return false;
+ }
+ }
+ return true;
+}
+
+// Replaces the categories of a subscription.
+function saveSubscriptionCategories($db, $subscriptionId, array $categoryIds)
+{
+ $delete = $db->prepare("DELETE FROM subscription_categories WHERE subscription_id = :subscriptionId");
+ $delete->bindValue(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
+ $delete->execute();
+
+ $insert = $db->prepare("INSERT OR IGNORE INTO subscription_categories (subscription_id, category_id) VALUES (:subscriptionId, :categoryId)");
+ foreach ($categoryIds as $categoryId) {
+ $insert->bindValue(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);
+ $insert->bindValue(':categoryId', $categoryId, SQLITE3_INTEGER);
+ $insert->execute();
+ $insert->reset();
+ }
+}
+
+// Category ids per subscription id, in the order they were stored.
+// Subscriptions without rows fall back to their primary category.
+function getCategoriesBySubscription($db, array $subscriptions)
+{
+ $categories = [];
+ $ids = array_values(array_filter(array_map(fn($s) => isset($s['id']) ? intval($s['id']) : 0, $subscriptions)));
+ if (count($ids) > 0) {
+ $result = $db->query("SELECT subscription_id, category_id FROM subscription_categories WHERE subscription_id IN (" . implode(',', $ids) . ") ORDER BY rowid");
+ while ($result && ($row = $result->fetchArray(SQLITE3_ASSOC))) {
+ $categories[$row['subscription_id']][] = intval($row['category_id']);
+ }
+ }
+ foreach ($subscriptions as $subscription) {
+ $id = $subscription['id'] ?? null;
+ if ($id !== null && !isset($categories[$id]) && !empty($subscription['category_id'])) {
+ $categories[$id] = [intval($subscription['category_id'])];
+ }
+ }
+ return $categories;
+}
+
+// SQL condition matching subscriptions in any of the given categories.
+// Placeholders are named :categoryFilter0, :categoryFilter1, ... and returned in $params.
+function categoryFilterCondition(array $categoryIds, &$params, $idColumn = 'id')
+{
+ $placeholders = [];
+ foreach (array_values($categoryIds) as $i => $categoryId) {
+ $placeholders[] = ":categoryFilter{$i}";
+ $params[":categoryFilter{$i}"] = intval($categoryId);
+ }
+ return "EXISTS (SELECT 1 FROM subscription_categories sc WHERE sc.subscription_id = {$idColumn} AND sc.category_id IN (" . implode(',', $placeholders) . "))";
+}
+
+?>
diff --git a/migrations/000061.php b/migrations/000061.php
new file mode 100644
index 0000000..1cfd099
--- /dev/null
+++ b/migrations/000061.php
@@ -0,0 +1,27 @@
+<?php
+
+// A subscription can belong to more than one category.
+//
+// subscription_categories holds one row per (subscription, category).
+// subscriptions.category_id stays and keeps the first selected category, the
+// "primary" one: sorting and grouping the list, the notifications and the
+// API fields built on it keep working unchanged. The new table is the full
+// list. It mirrors subscription_payers (migration 000060).
+//
+// Every existing subscription gets one row for the category it already has.
+
+$db->exec("CREATE TABLE IF NOT EXISTS subscription_categories (
+ subscription_id INTEGER NOT NULL,
+ category_id INTEGER NOT NULL,
+ PRIMARY KEY (subscription_id, category_id),
+ FOREIGN KEY (subscription_id) REFERENCES subscriptions(id) ON DELETE CASCADE,
+ FOREIGN KEY (category_id) REFERENCES categories(id)
+)");
+
+$db->exec('CREATE INDEX IF NOT EXISTS idx_subscription_categories_category
+ ON subscription_categories (category_id)');
+
+$db->exec('INSERT OR IGNORE INTO subscription_categories (subscription_id, category_id)
+ SELECT id, category_id FROM subscriptions WHERE category_id IS NOT NULL');
+
+?>
diff --git a/scripts/subscription-details.js b/scripts/subscription-details.js
index 1b4b01f..684cd1a 100644
--- a/scripts/subscription-details.js
+++ b/scripts/subscription-details.js
@@ -156,7 +156,8 @@ function renderSubscriptionDetails(subscription) {
document.querySelector('#details-next-payment').textContent = detailsFormatDate(subscription.next_payment);
document.querySelector('#details-start-date').textContent = detailsFormatDate(subscription.start_date) || strings.none;
- document.querySelector('#details-category').textContent = lookups.categories[subscription.category_id] || strings.none;
+ const categoryIds = subscription.category_ids && subscription.category_ids.length > 0 ? subscription.category_ids : [subscription.category_id];
+ document.querySelector('#details-category').textContent = categoryIds.map(id => lookups.categories[id]).filter(Boolean).join(', ') || strings.none;
const payerIds = subscription.payer_user_ids && subscription.payer_user_ids.length > 0 ? subscription.payer_user_ids : [subscription.payer_user_id];
document.querySelector('#details-payer').textContent = payerIds.map(id => lookups.members[id]).filter(Boolean).join(', ') || strings.none;
diff --git a/scripts/subscriptions.js b/scripts/subscriptions.js
index aec32c4..d095847 100644
--- a/scripts/subscriptions.js
+++ b/scripts/subscriptions.js
@@ -13,86 +13,89 @@ function toggleNotificationDays() {
notifyDaysBefore.disabled = !notifyCheckbox.checked;
}
-// Multi-select for the "Paid by" field. The hidden #payer_user input carries the
-// selected member ids as a comma separated list, first one being the primary payer.
-function getPayerSelection() {
- const value = document.querySelector("#payer_user").value;
- return value === "" ? [] : value.split(",");
+// 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 setPayerSelection(ids) {
- const select = document.querySelector("#payer_user_select");
- const options = select.querySelectorAll("li[role='option']");
- const wanted = ids.map(String).filter(id => select.querySelector(`li[data-value="${id}"]`));
- // A subscription always has a payer, default to the first member.
+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");
});
- document.querySelector("#payer_user").value = wanted.join(",");
- const names = wanted.map(id => select.querySelector(`li[data-value="${id}"] .multi-select-name`).textContent.trim());
- select.querySelector(".multi-select-label").textContent = names.length > 0 ? names.join(", ") : select.dataset.placeholder;
+ 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 togglePayerOption(option) {
- const current = getPayerSelection();
+function toggleMultiOption(wrapperId, option) {
+ const current = getMultiSelection(wrapperId);
const id = option.dataset.value;
if (current.includes(id)) {
- // Keep at least one payer selected.
if (current.length === 1) {
return;
}
- setPayerSelection(current.filter(value => value !== id));
+ setMultiSelection(wrapperId, current.filter(value => value !== id));
} else {
- setPayerSelection([...current, id]);
+ setMultiSelection(wrapperId, [...current, id]);
}
}
-function closePayerSelect() {
- const select = document.querySelector("#payer_user_select");
- select.classList.remove("is-open");
- select.querySelector(".multi-select-options").hidden = true;
- select.querySelector(".multi-select-toggle").setAttribute("aria-expanded", "false");
+function closeMultiSelect(wrapperId) {
+ const { wrapper, toggle, list } = multiSelectElements(wrapperId);
+ wrapper.classList.remove("is-open");
+ list.hidden = true;
+ toggle.setAttribute("aria-expanded", "false");
}
-function openPayerSelect() {
- const select = document.querySelector("#payer_user_select");
- select.classList.add("is-open");
- const list = select.querySelector(".multi-select-options");
+function openMultiSelect(wrapperId) {
+ const { wrapper, toggle, list } = multiSelectElements(wrapperId);
+ wrapper.classList.add("is-open");
list.hidden = false;
- select.querySelector(".multi-select-toggle").setAttribute("aria-expanded", "true");
+ toggle.setAttribute("aria-expanded", "true");
const first = list.querySelector("li[aria-selected='true']") || list.querySelector("li");
if (first) {
first.focus();
}
}
-function initPayerSelect() {
- const select = document.querySelector("#payer_user_select");
- if (!select) {
- return;
- }
- const toggle = select.querySelector(".multi-select-toggle");
- const list = select.querySelector(".multi-select-options");
+function initMultiSelect(wrapperId) {
+ const { wrapper, toggle, list } = multiSelectElements(wrapperId);
list.querySelectorAll("li").forEach(option => option.tabIndex = -1);
toggle.addEventListener("click", () => {
- select.classList.contains("is-open") ? closePayerSelect() : openPayerSelect();
+ wrapper.classList.contains("is-open") ? closeMultiSelect(wrapperId) : openMultiSelect(wrapperId);
});
toggle.addEventListener("keydown", event => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
- openPayerSelect();
+ openMultiSelect(wrapperId);
}
});
list.addEventListener("click", event => {
const option = event.target.closest("li[role='option']");
if (option) {
- togglePayerOption(option);
+ toggleMultiOption(wrapperId, option);
option.focus();
}
});
@@ -109,24 +112,34 @@ function initPayerSelect() {
} else if (event.key === " " || event.key === "Enter") {
event.preventDefault();
if (index >= 0) {
- togglePayerOption(options[index]);
+ toggleMultiOption(wrapperId, options[index]);
}
} else if (event.key === "Escape" || event.key === "Tab") {
if (event.key === "Escape") {
event.stopPropagation();
}
- closePayerSelect();
+ closeMultiSelect(wrapperId);
toggle.focus();
}
});
document.addEventListener("mousedown", event => {
- if (select.classList.contains("is-open") && !select.contains(event.target)) {
- closePayerSelect();
+ if (wrapper.classList.contains("is-open") && !wrapper.contains(event.target)) {
+ closeMultiSelect(wrapperId);
}
});
- setPayerSelection(getPayerSelection());
+ setMultiSelection(wrapperId, getMultiSelection(wrapperId));
+}
+
+const multiSelectIds = ["payer_user_select", "category_select"];
+
+function initMultiSelects() {
+ multiSelectIds.forEach(id => {
+ if (document.querySelector(`#${id}`)) {
+ initMultiSelect(id);
+ }
+ });
}
function resetForm() {
@@ -155,8 +168,10 @@ function resetForm() {
replacementSubscription.classList.add("hide");
const form = document.querySelector("#subs-form");
form.reset();
- setPayerSelection([]);
- closePayerSelect();
+ multiSelectIds.forEach(id => {
+ setMultiSelection(id, []);
+ closeMultiSelect(id);
+ });
toggleOneTimeCycleUI(false);
closeLogoSearch();
const deleteButton = document.querySelector("#deletesub");
@@ -202,9 +217,10 @@ function fillEditFormFields(subscription) {
toggleOneTimeCycleUI(subscription.cycle == 5);
const paymentSelect = document.querySelector("#payment_method");
paymentSelect.value = subscription.payment_method_id;
- const categorySelect = document.querySelector("#category");
- categorySelect.value = subscription.category_id;
- setPayerSelection(subscription.payer_user_ids && subscription.payer_user_ids.length > 0
+ 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]);
@@ -821,7 +837,7 @@ document.addEventListener('DOMContentLoaded', function () {
});
document.addEventListener('DOMContentLoaded', function () {
- initPayerSelect();
+ initMultiSelects();
const subscriptionForm = document.querySelector("#subs-form");
const submitButton = document.querySelector("#save-button");
diff --git a/settings.php b/settings.php
index 3ccfd00..dfd4579 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 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 906c4a1..8d26eda 100644
--- a/subscriptions.php
+++ b/subscriptions.php
@@ -6,6 +6,7 @@ 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;
@@ -47,15 +48,7 @@ if (isset($_GET['member'])) {
if (isset($_GET['category'])) {
$categoryIds = explode(',', $_GET['category']);
- $placeholders = array_map(function ($key) {
- return ":category{$key}";
- }, array_keys($categoryIds));
-
- $sql .= " AND category_id IN (" . implode(',', $placeholders) . ")";
-
- foreach ($categoryIds as $key => $categoryId) {
- $params[":category{$key}"] = $categoryId;
- }
+ $sql .= " AND " . categoryFilterCondition($categoryIds, $params);
}
if (isset($_GET['payment'])) {
@@ -119,6 +112,7 @@ if ($result) {
}
$payersBySubscription = getPayersBySubscription($db, $subscriptions);
+$categoriesBySubscription = getCategoriesBySubscription($db, $subscriptions);
foreach ($subscriptions as $subscription) {
foreach ($payersBySubscription[$subscription['id']] ?? [] as $memberId) {
@@ -126,9 +120,10 @@ foreach ($subscriptions as $subscription) {
$members[$memberId]['count']++;
}
}
- $categoryId = $subscription['category_id'];
- if (isset($categories[$categoryId ?? ""])) {
- $categories[$categoryId ?? ""]['count']++;
+ foreach ($categoriesBySubscription[$subscription['id']] ?? [] as $categoryId) {
+ if (isset($categories[$categoryId])) {
+ $categories[$categoryId]['count']++;
+ }
}
$paymentMethodId = $subscription['payment_method_id'];
if (isset($payment_methods[$paymentMethodId ?? ""])) {
@@ -242,6 +237,7 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip
$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']);
@@ -482,18 +478,27 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip
</div>
<div class="form-group">
- <label for="category"><?= translate('category', $i18n) ?></label>
- <select id="category" name="category_id">
- <?php
- foreach ($categories as $category) {
- ?>
- <option value="<?= $category['id'] ?>">
- <?= $category['name'] ?>
- </option>
+ <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
- }
- ?>
- </select>
+ 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">
diff --git a/tests/cases/export_missing_relations_test.php b/tests/cases/export_missing_relations_test.php
index f957868..11e3b5a 100644
--- a/tests/cases/export_missing_relations_test.php
+++ b/tests/cases/export_missing_relations_test.php
@@ -27,6 +27,7 @@ wallos_test('CSV export tolerates subscriptions without payer, payment method or
$out = [];
foreach ($rows as $row) {
$payerIds = $row['payer_user_id'] === null ? [] : [$row['payer_user_id']];
+ $categoryIds = [$row['category_id']];
eval($fragment);
$out[] = $subscriptionDetails;
}
diff --git a/tests/cases/subscription_payers_test.php b/tests/cases/subscription_payers_test.php
index 6f28e40..b78a6e5 100644
--- a/tests/cases/subscription_payers_test.php
+++ b/tests/cases/subscription_payers_test.php
@@ -131,3 +131,75 @@ wallos_test('email reaches every payer while the other channels keep to the prim
assert_contains('No email set for', $source, $file . ' skips extra payers without an address');
}
});
+
+/* Categories work the same way, see migrations/000061.php. */
+
+require_once WALLOS_ROOT . '/includes/subscription_categories.php';
+
+function categories_test_category($db, $userId, $name)
+{
+ $stmt = $db->prepare("INSERT INTO categories (name, user_id) VALUES (:name, :userId)");
+ $stmt->bindValue(':name', $name, SQLITE3_TEXT);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $stmt->execute();
+
+ return $db->lastInsertRowID();
+}
+
+wallos_test('the categories migration carries each subscription\'s category over, and can run twice', function () {
+ $db = wallos_test_open_database();
+ wallos_test_create_user($db, 1, 'alice');
+ $categoryId = categories_test_category($db, 1, 'Video');
+ $subscriptionId = payers_test_subscription($db, 1, null);
+ $db->exec("UPDATE subscriptions SET category_id = $categoryId WHERE id = $subscriptionId");
+
+ $db->exec('DELETE FROM subscription_categories');
+ require WALLOS_ROOT . '/migrations/000061.php';
+ require WALLOS_ROOT . '/migrations/000061.php';
+
+ $found = getCategoriesBySubscription($db, [['id' => $subscriptionId, 'category_id' => $categoryId]]);
+ assert_same([$categoryId], $found[$subscriptionId], 'the existing category is carried over');
+ assert_same(1, $db->querySingle("SELECT COUNT(*) FROM subscription_categories WHERE subscription_id = $subscriptionId"), 'running twice does not duplicate rows');
+
+ $db->close();
+});
+
+wallos_test('categories are saved as a list, checked for ownership and filterable by any of them', function () {
+ $db = wallos_test_open_database();
+ wallos_test_create_user($db, 1, 'alice');
+ wallos_test_create_user($db, 2, 'bob');
+ $video = categories_test_category($db, 1, 'Video');
+ $music = categories_test_category($db, 1, 'Music');
+ $foreign = categories_test_category($db, 2, 'Other');
+ $shared = payers_test_subscription($db, 1, null);
+ $videoOnly = payers_test_subscription($db, 1, null);
+
+ saveSubscriptionCategories($db, $shared, [$video, $music]);
+ saveSubscriptionCategories($db, $videoOnly, [$video]);
+ $row = ['id' => $shared, 'category_id' => $video];
+ assert_same([$video, $music], getCategoriesBySubscription($db, [$row])[$shared], 'both categories stored in order');
+
+ assert_true(categoriesBelongToUser($db, 1, [$video, $music]), 'own categories accepted');
+ assert_true(!categoriesBelongToUser($db, 1, [$video, $foreign]), 'one foreign category rejects the list');
+
+ $params = [];
+ $condition = categoryFilterCondition([$music], $params);
+ $stmt = $db->prepare("SELECT id FROM subscriptions WHERE user_id = 1 AND $condition");
+ foreach ($params as $key => $value) {
+ $stmt->bindValue($key, $value, SQLITE3_INTEGER);
+ }
+ $found = [];
+ $result = $stmt->execute();
+ while ($r = $result->fetchArray(SQLITE3_ASSOC)) {
+ $found[] = $r['id'];
+ }
+ assert_same([$shared], $found, 'filtering by the second category finds the shared subscription');
+
+ $db->close();
+});
+
+wallos_test('the statistics split a price evenly between its categories, so they add up to the total', function () {
+ $source = file_get_contents(WALLOS_ROOT . '/includes/stats_calculations.php');
+ assert_contains('$fullPrice / count($subscriptionCategoryIds)', $source, 'category cost divides by the number of categories');
+ assert_contains('array_intersect($subscriptionCategoryIds, $filteredCategoryIds)) / count($subscriptionCategoryIds)', $source, 'a category filter counts that category\'s share');
+});
diff --git a/tests/cases/subscription_relations_test.php b/tests/cases/subscription_relations_test.php
index 29847cd..c2d427f 100644
--- a/tests/cases/subscription_relations_test.php
+++ b/tests/cases/subscription_relations_test.php
@@ -20,6 +20,7 @@ wallos_test('subscription relation counts ignore absent and unresolved optional
['id' => 3, 'payer_user_id' => 7, 'category_id' => 8, 'payment_method_id' => 9],
];
$payersBySubscription = [2 => [99], 3 => [7]];
+ $categoriesBySubscription = [2 => [99], 3 => [8]];
set_error_handler(function ($severity, $message) { throw new ErrorException($message, 0, $severity); });
try { eval($fragment); } finally { restore_error_handler(); }
assert_same([7 => ['count' => 1]], $members, 'only known payer counted');