Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
v5_10_4 (#1298)
Miguel Ribeiro121801febefd
diff --git a/endpoints/payments/get.php b/endpoints/payments/get.phpindex f6348db..face511 100644--- a/endpoints/payments/get.php+++ b/endpoints/payments/get.php@@ -1,6 +1,9 @@<?phprequire_once '../../includes/connect_endpoint.php';+require_once '../../includes/html_text.php';++header('Content-Type: application/json; charset=utf-8');if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {$paymentsInUseQuery = $db->prepare('SELECT id FROM payment_methods WHERE id IN (SELECT DISTINCT payment_method_id FROM subscriptions) AND user_id = :userId');@@ -28,31 +31,30 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {exit();}+ $items = [];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)) ?>"- onClick="togglePayment(<?= $payment['id'] ?>)">- <img src="<?= $paymentIconFolder . $payment['icon'] ?>" alt="Logo" />- <span class="payment-name">- <?= $payment['name'] ?>- </span>- <?php- if (!$inUse) {- ?>- <div class="delete-payment-method" title="<?= translate('delete', $i18n) ?>" data-paymentid="<?= $payment['id'] ?>"- onclick="deletePaymentMethod(<?= $payment['id'] ?>)">- x- </div>- <?php- }- ?>- </div>- <?php+ $items[] = [+ 'id' => (int) $payment['id'],+ 'name' => htmlToText($payment['name']),+ 'icon' => $paymentIconFolder . $payment['icon'],+ 'enabled' => (int) $payment['enabled'],+ 'in_use' => $inUse,+ 'title' => htmlToText($inUse+ ? translate('cant_delete_payment_method_in_use', $i18n)+ : ($payment['enabled'] ? translate('disable', $i18n) : translate('enable', $i18n))),+ ];}++ echo json_encode([+ 'success' => true,+ 'payments' => $items,+ 'labels' => [+ 'rename_payment_method' => htmlToText(translate('rename_payment_method', $i18n)),+ 'delete' => htmlToText(translate('delete', $i18n)),+ ],+ ], JSON_INVALID_UTF8_SUBSTITUTE);} else {http_response_code(401);echo json_encode(array("message" => translate('error', $i18n)));diff --git a/endpoints/subscriptions/get.php b/endpoints/subscriptions/get.phpindex 2b46c31..fe64f83 100644--- a/endpoints/subscriptions/get.php+++ b/endpoints/subscriptions/get.php@@ -1,6 +1,16 @@<?phprequire_once '../../includes/connect_endpoint.php';+header('Content-Type: application/json; charset=utf-8');++if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {+ // Answer before the list helpers load: they query on behalf of a user.+ http_response_code(401);+ echo json_encode(['success' => false, 'message' => html_entity_decode(translate('session_expired', $i18n), ENT_QUOTES | ENT_HTML5, 'UTF-8')], JSON_INVALID_UTF8_SUBSTITUTE);+ $db->close();+ exit;+}+require_once '../../includes/currency_formatter.php';require_once '../../includes/getdbkeys.php';require_once '../../includes/logo_theme_variant.php';@@ -233,29 +243,51 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {});}- if (isset($print)) {- printSubscriptions($print, $sort, $categories, $members, $i18n, $colorTheme, "../../", $settings['disabledToBottom'], $settings['mobileNavigation'], $settings['showSubscriptionProgress'], $currencies, $lang);+ $iconDir = '../../images/siteicons/svg/';+ $readIcon = function ($name) use ($iconDir) {+ return trim(file_get_contents($iconDir . $name . '.php'));+ };+ $mobileNavigation = $settings['mobileNavigation'] === 'true';++ $icons = [+ 'logo' => $readIcon('logo'),+ 'automatic' => $readIcon('automatic'),+ 'manual' => $readIcon('manual'),+ ];+ if ($mobileNavigation) {+ foreach (['clone', 'delete', 'renew', 'edit'] as $name) {+ $icons[$name] = $readIcon('mobile-menu/' . $name);+ }}- if (count($subscriptions) == 0) {- ?>- <div class="no-matching-subscriptions">- <p>- <?= translate('no_matching_subscriptions', $i18n) ?>- </p>- <button class="button" onClick="clearFilters()">- <span clasS="fa-solid fa-minus-circle"></span>- <?= translate('clear_filters', $i18n) ?>- </button>- <img src="images/siteimages/empty.png" alt="<?= translate('empty_page', $i18n) ?>" />- </div>- <?php+ $labels = [];+ foreach (['payment_method', 'edit_subscription', 'edit', 'delete', 'clone', 'renew', 'cancel'] as $key) {+ $labels[$key] = htmlToText(translate($key, $i18n));}-} else {- http_response_code(401);- ?>- <p class="no-matching-subscriptions"><?= translate('session_expired', $i18n) ?></p>- <?php++ echo json_encode([+ 'success' => true,+ 'total' => count($subscriptions),+ 'mobile_navigation' => $mobileNavigation,+ 'subscriptions' => buildSubscriptionsPayload(+ $print ?? [],+ $sort,+ $categories,+ $members,+ $i18n,+ $settings['disabledToBottom'],+ $settings['showSubscriptionProgress'],+ $currencies,+ $lang+ ),+ 'labels' => $labels,+ 'icons' => $icons,+ 'messages' => [+ 'no_matching_subscriptions' => htmlToText(translate('no_matching_subscriptions', $i18n)),+ 'clear_filters' => htmlToText(translate('clear_filters', $i18n)),+ 'empty_page' => htmlToText(translate('empty_page', $i18n)),+ ],+ ], JSON_INVALID_UTF8_SUBSTITUTE);}$db->close();diff --git a/includes/filters_menu.php b/includes/filters_menu.phpindex a071878..fb84ff6 100644--- a/includes/filters_menu.php+++ b/includes/filters_menu.php@@ -19,7 +19,7 @@}}?>- <div class="filter-item <?= $selectedClass ?>" data-memberid="<?= $member['id'] ?>"><?= $member['name'] ?>+ <div class="filter-item <?= $selectedClass ?>" data-memberid="<?= $member['id'] ?>"><?= htmlSafe($member['name']) ?></div><?php}@@ -58,7 +58,7 @@}?><div class="filter-item <?= $selectedClass ?>" data-categoryid="<?= $category['id'] ?>">- <?= $category['name'] ?>+ <?= htmlSafe($category['name']) ?></div><?php}@@ -88,7 +88,7 @@}?><div class="filter-item <?= $selectedClass ?>" data-paymentid="<?= $payment['id'] ?>">- <?= $payment['name'] ?>+ <?= htmlSafe($payment['name']) ?></div><?php}diff --git a/includes/html_text.php b/includes/html_text.phpnew file mode 100644index 0000000..4d4c0e3--- /dev/null+++ b/includes/html_text.php@@ -0,0 +1,22 @@+<?php++/**+ * Names and labels reach the templates as HTML (they are stored HTML-escaped and+ * echoed as-is). JSON carries plain text, which the client escapes once itself.+ */+function htmlToText($value)+{+ return html_entity_decode((string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8');+}++/**+ * A stored name made safe for HTML output. Stored values may or may not already+ * be escaped, so decode first and escape exactly once: this neither double-escapes+ * ordinary names nor lets a raw payload through.+ */+function htmlSafe($value)+{+ return htmlspecialchars(htmlToText($value), ENT_QUOTES, 'UTF-8');+}++?>diff --git a/includes/list_subscriptions.php b/includes/list_subscriptions.phpindex d9dc7cd..8748af6 100644--- a/includes/list_subscriptions.php+++ b/includes/list_subscriptions.php@@ -2,6 +2,7 @@require_once 'i18n/getlang.php';require_once __DIR__ . '/currency_rates.php';+require_once __DIR__ . '/html_text.php';function getBillingCycle($cycle, $frequency, $i18n){@@ -184,7 +185,15 @@ function formatDate($date, $lang = 'en')return $formattedDate;}-function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n, $colorTheme, $imagePath, $disabledToBottom, $mobileNavigation, $showSubscriptionProgress, $currencies, $lang)+/**+ * Orders the list the way it is displayed and works out the section headings+ * that precede each subscription (lifetime purchases, or the category / payer /+ * payment-method group, depending on the sort). Shared by the server-rendered+ * list and the JSON endpoint so both stay in the same order.+ *+ * Each returned subscription gets a 'headings' array of plain-text titles.+ */+function prepareSubscriptionsForDisplay($subscriptions, $sort, $categories, $members, $i18n, $disabledToBottom){if ($sort === "price") {// Ranked by the main-currency value (sort_price), not the raw number (#861).@@ -198,44 +207,87 @@ function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n,$currentPayerUserId = 0;$currentPaymentMethodId = 0;$oneTimeSectionShown = false;- foreach ($subscriptions as $subscription) {+ foreach ($subscriptions as $index => $subscription) {+ $headings = [];if ($subscription['one_time'] && !$oneTimeSectionShown) {- ?>- <div class="subscription-list-title">- <?= translate('lifetime_purchases', $i18n) ?>- </div>- <?php+ $headings[] = translate('lifetime_purchases', $i18n);$oneTimeSectionShown = true;}if ($sort == "category_id" && $subscription['category_id'] != $currentCategory) {- ?>- <div class="subscription-list-title">- <?php- if ($subscription['category_id'] == 1) {- echo translate('no_category', $i18n);- } else {- echo $categories[$subscription['category_id'] ?? ""]['name'] ?? "";- }- ?>- </div>- <?php+ $headings[] = $subscription['category_id'] == 1+ ? translate('no_category', $i18n)+ : ($categories[$subscription['category_id'] ?? ""]['name'] ?? "");$currentCategory = $subscription['category_id'];}if ($sort == "payer_user_id" && $subscription['payer_user_id'] != $currentPayerUserId) {- ?>- <div class="subscription-list-title">- <?= $members[$subscription['payer_user_id'] ?? ""]['name'] ?? "" ?>- </div>- <?php+ $headings[] = $members[$subscription['payer_user_id'] ?? ""]['name'] ?? "";$currentPayerUserId = $subscription['payer_user_id'];}if ($sort == "payment_method_id" && $subscription['payment_method_id'] != $currentPaymentMethodId) {+ $headings[] = $subscription['payment_method_name'];+ $currentPaymentMethodId = $subscription['payment_method_id'];+ }+ $subscriptions[$index]['headings'] = $headings;+ }++ return $subscriptions;+}++/**+ * The list as plain data, for the JSON endpoint: the same order and headings as+ * printSubscriptions(), with display strings (formatted price and date, resolved+ * titles) already worked out so the client only has to lay them out.+ */+function buildSubscriptionsPayload($subscriptions, $sort, $categories, $members, $i18n, $disabledToBottom, $showSubscriptionProgress, $currencies, $lang)+{+ $items = [];+ foreach (prepareSubscriptionsForDisplay($subscriptions, $sort, $categories, $members, $i18n, $disabledToBottom) as $subscription) {+ $oneTime = (bool) $subscription['one_time'];+ $autoRenew = (int) $subscription['auto_renew'] === 1;+ $hasOriginal = isset($subscription['original_price']) && $subscription['original_price'] != $subscription['price'];++ $items[] = [+ 'id' => (int) $subscription['id'],+ 'name' => htmlToText($subscription['name']),+ 'headings' => array_map('htmlToText', $subscription['headings']),+ 'logo' => $subscription['logo'] !== "" ? $subscription['logo'] : null,+ 'logo_variant' => $subscription['logo_variant'] ?? null,+ 'logo_text_color' => $subscription['logo_text_color'] ?? null,+ 'inactive' => (bool) $subscription['inactive'],+ 'one_time' => $oneTime,+ 'auto_renew' => $autoRenew,+ 'can_renew' => !$autoRenew && !$oneTime,+ 'billing_cycle' => htmlToText($subscription['billing_cycle']),+ 'cycle_title' => htmlToText($oneTime+ ? $subscription['billing_cycle']+ : ($subscription['auto_renew'] ? translate("automatically_renews", $i18n) : translate("manual_renewal", $i18n))),+ 'next_payment' => formatDate($subscription['next_payment'], $lang),+ 'price' => formatPrice($subscription['price'], $subscription['currency_code'], $currencies),+ 'original_price' => $hasOriginal+ ? formatPrice($subscription['original_price'], $subscription['original_currency_code'], $currencies)+ : null,+ 'payment_method_icon' => $subscription['payment_method_icon'] !== "" ? $subscription['payment_method_icon'] : null,+ 'payment_method_name' => htmlToText($subscription['payment_method_name']),+ 'progress' => ($showSubscriptionProgress === 'true' && !$subscription['inactive'])+ ? min(100, $subscription['progress'])+ : null,+ ];+ }++ return $items;+}++function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n, $colorTheme, $imagePath, $disabledToBottom, $mobileNavigation, $showSubscriptionProgress, $currencies, $lang)+{+ $subscriptions = prepareSubscriptionsForDisplay($subscriptions, $sort, $categories, $members, $i18n, $disabledToBottom);++ foreach ($subscriptions as $subscription) {+ foreach ($subscription['headings'] as $heading) {?><div class="subscription-list-title">- <?= $subscription['payment_method_name'] ?>+ <?= htmlSafe($heading) ?></div><?php- $currentPaymentMethodId = $subscription['payment_method_id'];}?><div class="subscription-container">@@ -291,7 +343,7 @@ function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n,</label><div class="subscription<?= $subscriptionExtraClasses ?>"onClick="showSubscriptionDetails(event, <?= $subscription['id'] ?>)" data-id="<?= $subscription['id'] ?>"- data-name="<?= $subscription['name'] ?>">+ data-name="<?= htmlSafe($subscription['name']) ?>"><div class="subscription-main"><span class="logo <?= !$hasLogo ? 'hideOnMobile' : '' ?>"><?php@@ -302,7 +354,7 @@ function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n,}?></span>- <span class="name <?= $hasLogo ? 'hideOnMobile' : '' ?>"><?= $subscription['name'] ?></span>+ <span class="name <?= $hasLogo ? 'hideOnMobile' : '' ?>"><?= htmlSafe($subscription['name']) ?></span><span class="cycle"title="<?= $subscription['one_time'] ? $subscription['billing_cycle'] : ($subscription['auto_renew'] ? translate("automatically_renews", $i18n) : translate("manual_renewal", $i18n)) ?>"><?php@@ -334,7 +386,7 @@ function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n,<span class="payment_method"><?php if (!empty($subscription['payment_method_icon'])) { ?><img src="<?= $subscription['payment_method_icon'] ?>"- title="<?= translate('payment_method', $i18n) ?>: <?= $subscription['payment_method_name'] ?>" />+ title="<?= htmlSafe(translate('payment_method', $i18n) . ': ' . $subscription['payment_method_name']) ?>" /><?php } ?></span><?php@@ -379,7 +431,7 @@ function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n,</div><div class="subscription-back" inert><div class="subscription-back-header">- <span class="subscription-back-title"><?= $subscription['name'] ?></span>+ <span class="subscription-back-title"><?= htmlSafe($subscription['name']) ?></span><button type="button" class="subscription-back-close"onClick="event.stopPropagation(); unflipCard(<?= $subscription['id'] ?>)"title="<?= translate('cancel', $i18n) ?>">diff --git a/includes/version.php b/includes/version.phpindex 990d454..b6580d6 100644--- a/includes/version.php+++ b/includes/version.php@@ -1,3 +1,3 @@<?php-$version = "v5.10.3";+$version = "v5.10.4";?>diff --git a/index.php b/index.phpindex fb10c28..5697872 100644--- a/index.php+++ b/index.php@@ -3,6 +3,7 @@require_once 'includes/header.php';require_once 'includes/getdbkeys.php';require_once 'includes/logo_theme_variant.php';+require_once 'includes/html_text.php';require_once 'includes/upcoming_payments.php';require_once 'includes/upcoming_cancellations.php';@@ -161,7 +162,7 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {<?phpforeach ($overdueSubscriptions as $subscription) {- $subscriptionName = htmlspecialchars($subscription['name']);+ $subscriptionName = htmlSafe($subscription['name']);$subscriptionPrice = $subscription['price'];$subscriptionCurrency = $subscription['currency_id'];$subscriptionNextPayment = $subscription['next_payment'];@@ -208,7 +209,7 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {<?php} else {foreach ($upcomingSubscriptions as $subscription) {- $subscriptionName = htmlspecialchars($subscription['name']);+ $subscriptionName = htmlSafe($subscription['name']);$subscriptionPrice = $subscription['price'];$subscriptionCurrency = $subscription['currency_id'];$subscriptionNextPayment = $subscription['next_payment'];@@ -247,7 +248,7 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {<div class="dashboard-subscriptions-list"><?phpforeach ($upcomingCancellations as $subscription) {- $subscriptionName = htmlspecialchars($subscription['name']);+ $subscriptionName = htmlSafe($subscription['name']);$subscriptionPrice = $subscription['price'];$subscriptionCurrency = $subscription['currency_id'];$subscriptionDisplayCancellationDate = formatDate($subscription['cancellation_date'], $lang);diff --git a/scripts/common.js b/scripts/common.jsindex 4e69dd4..aceb35e 100644--- a/scripts/common.js+++ b/scripts/common.js@@ -1,3 +1,31 @@+function escapeHtml(value) {+ return String(value ?? "")+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'");+}++// Chrome on Android opens its "Touch to Search" panel when a tap on plain text+// is not acted on by the page, and most of Wallos is plain text (headings,+// labels, card text). Chrome treats a tap as handled when the page touches the+// DOM while handling it, so every click marks a hidden element.+(function () {+ const tapHandledMarker = document.createElement('span');+ tapHandledMarker.hidden = true;+ tapHandledMarker.setAttribute('aria-hidden', 'true');++ const attachMarker = () => document.body.appendChild(tapHandledMarker);+ if (document.body) {+ attachMarker();+ } else {+ document.addEventListener('DOMContentLoaded', attachMarker);+ }++ document.addEventListener('click', () => tapHandledMarker.classList.add('tap-handled'));+})();+let isDropdownOpen = false;// Shared loading/empty/error states for the logo & payment icon search popupsdiff --git a/scripts/settings.js b/scripts/settings.jsindex 79a24a7..1231126 100644--- a/scripts/settings.js+++ b/scripts/settings.js@@ -825,14 +825,42 @@ function resetFormIcon() {iconPreview.style.display = 'none';}+// Same markup settings.php prints on first load; click, rename and drag are+// handled by the delegated listeners and by Sortable on #payments-list.+function renderPaymentMethods(data) {+ return data.payments.map(payment => `+ <div class="payments-payment" data-enabled="${Number(payment.enabled)}" data-in-use="${payment.in_use ? "yes" : "no"}" data-paymentid="${Number(payment.id)}" title="${escapeHtml(payment.title)}">+ <div class="drag-icon" title="">+ <i class="fa-solid fa-grip-vertical"></i>+ </div>+ <img src="${escapeHtml(payment.icon)}" alt="Logo" />+ <span class="payment-name" contenteditable="true" title="${escapeHtml(data.labels.rename_payment_method)}">${escapeHtml(payment.name)}</span>+ ${payment.in_use ? "" : `<div class="delete-payment-method" title="${escapeHtml(data.labels.delete)}" data-paymentid="${Number(payment.id)}">x</div>`}+ </div>`).join("");+}+function reloadPaymentMethods() {const paymentsContainer = document.querySelector("#payments-list");const paymentMethodsEndpoint = "endpoints/payments/get.php";fetch(paymentMethodsEndpoint)- .then(response => response.text())+ .then(response => response.json()).then(data => {- paymentsContainer.innerHTML = data;+ if (!data.payments) {+ throw new Error(data.message || translate("unknown_error"));+ }+ paymentsContainer.innerHTML = renderPaymentMethods(data);+ paymentsContainer.querySelectorAll(".delete-payment-method").forEach(button => {+ button.addEventListener("click", function (event) {+ event.preventDefault();+ event.stopPropagation();+ deletePaymentMethod(button.dataset.paymentid);+ });+ });+ })+ .catch(error => {+ console.error(error);+ showErrorMessage(translate("unknown_error"));});}diff --git a/scripts/stats.js b/scripts/stats.jsindex cfdd041..fc140d7 100644--- a/scripts/stats.js+++ b/scripts/stats.js@@ -59,7 +59,10 @@ function loadGraph(container, dataPoints, currency, run) {dataPoints.forEach((p, i) => {const item = document.createElement('button');item.className = 'graph-legend-item';- item.innerHTML = `<span class="graph-legend-dot" style="background:${CHART_PALETTE[i % CHART_PALETTE.length]}"></span>${p.label} (${fmt(p.y)})`;+ const dot = document.createElement('span');+ dot.className = 'graph-legend-dot';+ dot.style.background = CHART_PALETTE[i % CHART_PALETTE.length];+ item.append(dot, `${p.label} (${fmt(p.y)})`);item.addEventListener('click', () => {hidden[i] = !hidden[i];item.classList.toggle('graph-legend-item--off', hidden[i]);diff --git a/scripts/subscriptions.js b/scripts/subscriptions.jsindex f0a1600..eee3baa 100644--- a/scripts/subscriptions.js+++ b/scripts/subscriptions.js@@ -671,6 +671,118 @@ function closeLogoSearch() {logoResults.innerHTML = "";}+function renderSubscriptionLogo(subscription) {+ if (!subscription.logo) {+ return "";+ }+ if (!subscription.logo_text_color || !subscription.logo_variant) {+ return `<img src="${escapeHtml(subscription.logo)}" class="">`;+ }+ // The theme the original file already reads well on; styles.css shows the matching image.+ const nativeTheme = subscription.logo_text_color === "dark" ? "light" : "dark";+ return `<img src="${escapeHtml(subscription.logo)}" class="logo-theme-original" data-native-theme="${nativeTheme}">`+ + `<img src="${escapeHtml(subscription.logo_variant)}" class="logo-theme-variant" data-native-theme="${nativeTheme}">`;+}++function renderSubscription(subscription, data) {+ const id = subscription.id;+ const labels = data.labels;+ const icons = data.icons;+ const hasLogo = !!subscription.logo;+ const extraClasses = (subscription.inactive ? " inactive" : "") + (subscription.auto_renew ? "" : " manual");++ let mobileActions = "";+ if (data.mobile_navigation) {+ mobileActions = `+ <div class="mobile-actions" data-id="${id}">+ <button class="mobile-action-clone"></button>+ <button class="mobile-action-clone" onClick="cloneSubscription(event, ${id})">${icons.clone} Clone</button>+ <button class="mobile-action-delete" onClick="deleteSubscription(event, ${id})">${icons.delete} Delete</button>+ ${subscription.can_renew ? `<button class="mobile-action-renew" onClick="renewSubscription(event, ${id})">${icons.renew} Renew</button>` : ""}+ <button class="mobile-action-edit" onClick="openEditSubscription(event, ${id})">${icons.edit} Edit</button>+ </div>`;+ }++ const cycleIcon = subscription.one_time ? "" : (subscription.auto_renew ? icons.automatic : icons.manual);+ const originalPrice = subscription.original_price+ ? `<span class="original_price">(${escapeHtml(subscription.original_price)})</span>`+ : "";+ const paymentIcon = subscription.payment_method_icon+ ? `<img src="${escapeHtml(subscription.payment_method_icon)}" title="${escapeHtml(labels.payment_method)}: ${escapeHtml(subscription.payment_method_name)}" />`+ : "";+ const expandClass = data.mobile_navigation ? "mobileNavigationHideOnMobile" : "";+ const renewItem = subscription.can_renew+ ? `<li class="renew" title="${escapeHtml(labels.renew)}" onClick="renewSubscription(event, ${id})"><i class="fa-solid fa-rotate-right"></i> ${escapeHtml(labels.renew)}</li>`+ : "";+ const renewBackAction = subscription.can_renew+ ? `<button type="button" class="back-action" onClick="unflipCard(${id}); renewSubscription(event, ${id})"><i class="fa-solid fa-rotate-right"></i> ${escapeHtml(labels.renew)}</button>`+ : "";+ const progress = subscription.progress !== null+ ? `<div class="subscription-progress-container"><span class="subscription-progress" style="width: ${Number(subscription.progress)}%;"></span></div>`+ : "";++ return `+ <div class="subscription-container">+ ${mobileActions}+ <label class="bulk-select">+ <input type="checkbox" class="bulk-select-checkbox" value="${id}" onChange="updateBulkSelection()">+ </label>+ <div class="subscription${extraClasses}" onClick="showSubscriptionDetails(event, ${id})" data-id="${id}" data-name="${escapeHtml(subscription.name)}">+ <div class="subscription-main">+ <span class="logo ${hasLogo ? "" : "hideOnMobile"}">${hasLogo ? renderSubscriptionLogo(subscription) : icons.logo}</span>+ <span class="name ${hasLogo ? "hideOnMobile" : ""}">${escapeHtml(subscription.name)}</span>+ <span class="cycle" title="${escapeHtml(subscription.cycle_title)}">${cycleIcon} ${escapeHtml(subscription.billing_cycle)}</span>+ <span class="next">${escapeHtml(subscription.next_payment)}</span>+ <span class="price"><span class="value">${escapeHtml(subscription.price)} ${originalPrice}</span></span>+ <span class="payment_method">${paymentIcon}</span>+ <button type="button" class="actions-expand ${expandClass}" onClick="expandActions(event, ${id})">+ <i class="fas fa-ellipsis-v"></i>+ </button>+ <ul class="actions">+ <li class="edit" title="${escapeHtml(labels.edit_subscription)}" onClick="openEditSubscription(event, ${id})"><i class="fa-solid fa-pen-to-square"></i> ${escapeHtml(labels.edit_subscription)}</li>+ <li class="delete" title="${escapeHtml(labels.delete)}" onClick="deleteSubscription(event, ${id})"><i class="fa-solid fa-trash-can"></i> ${escapeHtml(labels.delete)}</li>+ <li class="clone" title="${escapeHtml(labels.clone)}" onClick="cloneSubscription(event, ${id})"><i class="fa-solid fa-copy"></i> ${escapeHtml(labels.clone)}</li>+ ${renewItem}+ </ul>+ </div>+ <div class="subscription-back" inert>+ <div class="subscription-back-header">+ <span class="subscription-back-title">${escapeHtml(subscription.name)}</span>+ <button type="button" class="subscription-back-close" onClick="event.stopPropagation(); unflipCard(${id})" title="${escapeHtml(labels.cancel)}">+ <i class="fa-solid fa-xmark"></i>+ </button>+ </div>+ <button type="button" class="back-action" onClick="unflipCard(${id}); openEditSubscription(event, ${id})"><i class="fa-solid fa-pen-to-square"></i> ${escapeHtml(labels.edit)}</button>+ <button type="button" class="back-action" onClick="unflipCard(${id}); cloneSubscription(event, ${id})"><i class="fa-solid fa-copy"></i> ${escapeHtml(labels.clone)}</button>+ ${renewBackAction}+ <button type="button" class="back-action delete" onClick="unflipCard(${id}); deleteSubscription(event, ${id})"><i class="fa-solid fa-trash-can"></i> ${escapeHtml(labels.delete)}</button>+ </div>+ </div>+ ${progress}+ </div>`;+}++function renderSubscriptions(data) {+ if (data.subscriptions.length === 0 && data.total === 0) {+ const messages = data.messages;+ return `+ <div class="no-matching-subscriptions">+ <p>${escapeHtml(messages.no_matching_subscriptions)}</p>+ <button class="button" onClick="clearFilters()">+ <span class="fa-solid fa-minus-circle"></span> ${escapeHtml(messages.clear_filters)}+ </button>+ <img src="images/siteimages/empty.png" alt="${escapeHtml(messages.empty_page)}" />+ </div>`;+ }++ return data.subscriptions.map(subscription => {+ const headings = subscription.headings+ .map(heading => `<div class="subscription-list-title">${escapeHtml(heading)}</div>`)+ .join("");+ return headings + renderSubscription(subscription, data);+ }).join("");+}+function fetchSubscriptions(id, event, initiator) {const subscriptionsContainer = document.querySelector("#subscriptions");let getSubscriptions = "endpoints/subscriptions/get.php";@@ -695,16 +807,19 @@ function fetchSubscriptions(id, event, initiator) {}fetch(getSubscriptions)- .then(response => response.text())- .then(data => {- if (data) {- subscriptionsContainer.innerHTML = data;+ .then(response => response.json().catch(() => null).then(data => ({ response, data })))+ .then(({ response, data }) => {+ if (!data) {+ throw new Error(`Unexpected response (${response.status})`);+ }+ if (data.success) {+ subscriptionsContainer.innerHTML = renderSubscriptions(data);const mainActions = document.querySelector("#main-actions");- if (data.includes("no-matching-subscriptions")) {- // mainActions.classList.add("hidden");- } else {+ if (data.total > 0 || data.subscriptions.length > 0) {mainActions.classList.remove("hidden");}+ } else {+ subscriptionsContainer.innerHTML = `<p class="no-matching-subscriptions">${escapeHtml(data.message || "")}</p>`;}if (initiator == "clone" && id && event) {diff --git a/stats.php b/stats.phpindex d8454e8..e1b0f5c 100644--- a/stats.php+++ b/stats.php@@ -2,6 +2,7 @@require_once 'includes/header.php';require_once 'includes/logo_theme_variant.php';require_once 'includes/default_names.php';+require_once 'includes/html_text.php';// Get code of main currency to display on statistics@@ -61,7 +62,7 @@ $potentialMonthlySavings = get_upcoming_cancellations_monthly_value($upcomingCan}$selectedClass = $isSelected ? 'selected' : '';?>- <div class="filter-item <?= $selectedClass ?>" data-memberid="<?= $member['id'] ?>"><?= $member['name'] ?>+ <div class="filter-item <?= $selectedClass ?>" data-memberid="<?= $member['id'] ?>"><?= htmlSafe($member['name']) ?></div><?php}@@ -97,7 +98,7 @@ $potentialMonthlySavings = get_upcoming_cancellations_monthly_value($upcomingCan$selectedClass = $isSelected ? 'selected' : '';?><div class="filter-item <?= $selectedClass ?>" data-categoryid="<?= $category['id'] ?>">- <?= $categoryName ?>+ <?= htmlSafe($categoryName) ?></div><?php}@@ -126,7 +127,7 @@ $potentialMonthlySavings = get_upcoming_cancellations_monthly_value($upcomingCan$selectedClass = $isSelected ? 'selected' : '';?><div class="filter-item <?= $selectedClass ?>" data-paymentid="<?= $payment['id'] ?>">- <?= $payment['name'] ?>+ <?= htmlSafe($payment['name']) ?></div><?php}@@ -246,12 +247,12 @@ $potentialMonthlySavings = get_upcoming_cancellations_monthly_value($upcomingCan$mostExpensiveLogoVariantSrc = !empty($mostExpensiveSubscription['logo_variant']) ? "images/uploads/logos/" . $mostExpensiveSubscription['logo_variant'] : null;?><div class="subtitle">- <?= renderThemedLogoImg($mostExpensiveLogoSrc, $mostExpensiveLogoVariantSrc, $mostExpensiveSubscription['logo_text_color'] ?? null, '', 'alt="' . $mostExpensiveSubscription['name'] . '" title="' . $mostExpensiveSubscription['name'] . '"') ?>+ <?= renderThemedLogoImg($mostExpensiveLogoSrc, $mostExpensiveLogoVariantSrc, $mostExpensiveSubscription['logo_text_color'] ?? null, '', 'alt="' . htmlSafe($mostExpensiveSubscription['name']) . '" title="' . htmlSafe($mostExpensiveSubscription['name']) . '"') ?></div><?php} else if (isset($mostExpensiveSubscription['name']) && $mostExpensiveSubscription['name'] != '') {?>- <div class="subtitle"><?= $mostExpensiveSubscription['name'] ?></div>+ <div class="subtitle"><?= htmlSafe($mostExpensiveSubscription['name']) ?></div><?php}?>@@ -268,12 +269,12 @@ $potentialMonthlySavings = get_upcoming_cancellations_monthly_value($upcomingCan$cheapestLogoVariantSrc = !empty($cheapestSubscription['logo_variant']) ? "images/uploads/logos/" . $cheapestSubscription['logo_variant'] : null;?><div class="subtitle">- <?= renderThemedLogoImg($cheapestLogoSrc, $cheapestLogoVariantSrc, $cheapestSubscription['logo_text_color'] ?? null, '', 'alt="' . $cheapestSubscription['name'] . '" title="' . $cheapestSubscription['name'] . '"') ?>+ <?= renderThemedLogoImg($cheapestLogoSrc, $cheapestLogoVariantSrc, $cheapestSubscription['logo_text_color'] ?? null, '', 'alt="' . htmlSafe($cheapestSubscription['name']) . '" title="' . htmlSafe($cheapestSubscription['name']) . '"') ?></div><?php} else if (!empty($cheapestSubscription['name'])) {?>- <div class="subtitle"><?= $cheapestSubscription['name'] ?></div>+ <div class="subtitle"><?= htmlSafe($cheapestSubscription['name']) ?></div><?php}?>@@ -573,12 +574,12 @@ $potentialMonthlySavings = get_upcoming_cancellations_monthly_value($upcomingCan$oldestLogoVariantSrc = !empty($oldestSubscription['logo_variant']) ? "images/uploads/logos/" . $oldestSubscription['logo_variant'] : null;?><div class="subtitle">- <?= renderThemedLogoImg($oldestLogoSrc, $oldestLogoVariantSrc, $oldestSubscription['logo_text_color'] ?? null, '', 'alt="' . $oldestSubscription['name'] . '" title="' . $oldestSubscription['name'] . '"') ?>+ <?= renderThemedLogoImg($oldestLogoSrc, $oldestLogoVariantSrc, $oldestSubscription['logo_text_color'] ?? null, '', 'alt="' . htmlSafe($oldestSubscription['name']) . '" title="' . htmlSafe($oldestSubscription['name']) . '"') ?></div><?php} else if (!empty($oldestSubscription['name'])) {?>- <div class="subtitle"><?= $oldestSubscription['name'] ?></div>+ <div class="subtitle"><?= htmlSafe($oldestSubscription['name']) ?></div><?php}?>diff --git a/subscriptions.php b/subscriptions.phpindex 289a7ce..fc56dce 100644--- a/subscriptions.php+++ b/subscriptions.php@@ -240,7 +240,7 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip<?phpforeach ($categories as $category) {?>- <option value="<?= $category['id'] ?>"><?= $category['name'] ?></option>+ <option value="<?= $category['id'] ?>"><?= htmlSafe($category['name']) ?></option><?php}?>@@ -249,7 +249,7 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip<?phpforeach ($payment_methods as $payment) {?>- <option value="<?= $payment['id'] ?>"><?= $payment['name'] ?></option>+ <option value="<?= $payment['id'] ?>"><?= htmlSafe($payment['name']) ?></option><?php}?>@@ -503,7 +503,7 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscripforeach ($payment_methods as $payment) {?><option value="<?= $payment['id'] ?>">- <?= $payment['name'] ?>+ <?= htmlSafe($payment['name']) ?></option><?php}@@ -524,7 +524,7 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip?><li role="option" aria-selected="false" data-value="<?= $member['id'] ?>"><span class="multi-select-check"></span>- <span class="multi-select-name"><?= $member['name'] ?></span>+ <span class="multi-select-name"><?= htmlSafe($member['name']) ?></span></li><?php}@@ -550,7 +550,7 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip?><li role="option" aria-selected="false" data-value="<?= $category['id'] ?>"><span class="multi-select-check"></span>- <span class="multi-select-name"><?= $category['name'] ?></span>+ <span class="multi-select-name"><?= htmlSafe($category['name']) ?></span></li><?php}diff --git a/tests/cases/subscription_list_xss_test.php b/tests/cases/subscription_list_xss_test.phpnew file mode 100644index 0000000..cbb8dc3--- /dev/null+++ b/tests/cases/subscription_list_xss_test.php@@ -0,0 +1,45 @@+<?php+/* The escaping helpers live in a dependency-free include. */+function list_xss_load_helpers() {+ if (function_exists('htmlSafe')) {+ return;+ }+ require_once WALLOS_ROOT . '/includes/html_text.php';+}++wallos_test('stored names are escaped exactly once, whether or not they were stored escaped', function () {+ list_xss_load_helpers();+ assert_same('Cloud & Co', htmlSafe('Cloud & Co'), 'raw ampersand escaped');+ assert_same('Cloud & Co', htmlSafe('Cloud & Co'), 'already-escaped value not escaped twice');+ assert_same('<img src=x onerror="alert(1)">', htmlSafe('<img src=x onerror="alert(1)">'), 'raw tag neutralised');+ assert_same('<img src=x onerror="alert(1)">', htmlSafe('<img src=x onerror="alert(1)">'), 'escaped tag stays inert text');+ assert_same('"><svg onload=x>', htmlSafe('"><svg onload=x>'), 'attribute breakout neutralised');+ assert_same('', htmlSafe(null), 'null is empty');+});++wallos_test('the subscription list page escapes every stored name it prints', function () {+ $patterns = [+ 'includes/list_subscriptions.php' => ["htmlSafe(\$heading)", "htmlSafe(\$subscription['name'])", "htmlSafe(translate('payment_method'"],+ 'subscriptions.php' => ["htmlSafe(\$category['name'])", "htmlSafe(\$payment['name'])", "htmlSafe(\$member['name'])"],+ 'includes/filters_menu.php' => ["htmlSafe(\$member['name'])", "htmlSafe(\$category['name'])", "htmlSafe(\$payment['name'])"],+ ];+ foreach ($patterns as $file => $needles) {+ $source = file_get_contents(WALLOS_ROOT . '/' . $file);+ foreach ($needles as $needle) {+ assert_true(strpos($source, $needle) !== false, $file . ' escapes ' . $needle);+ }+ assert_true(!preg_match('/<\?= \$(subscription|member|category|payment)\[\'name\'\] \?>/', $source), $file . ' has no unescaped name echo');+ }+});++wallos_test('the statistics page and chart legend escape stored names', function () {+ $stats = file_get_contents(WALLOS_ROOT . '/stats.php');+ foreach (["htmlSafe(\$member['name'])", "htmlSafe(\$categoryName)", "htmlSafe(\$payment['name'])",+ "htmlSafe(\$mostExpensiveSubscription['name'])", "htmlSafe(\$cheapestSubscription['name'])", "htmlSafe(\$oldestSubscription['name'])"] as $needle) {+ assert_true(strpos($stats, $needle) !== false, 'stats.php escapes ' . $needle);+ }+ assert_true(!preg_match('/<\?= \$\w*Subscription\[\'name\'\] \?>/', $stats), 'stats.php has no unescaped subscription name echo');+ assert_true(!preg_match('/alt="\' \. \$\w+\[\'name\'\]/', $stats), 'stats.php has no unescaped name in alt/title attributes');+ $js = file_get_contents(WALLOS_ROOT . '/scripts/stats.js');+ assert_true(!preg_match('/innerHTML\s*=.*p\.label/', $js), 'the chart legend never writes labels with innerHTML');+});