Skip to content

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

Bugfix session 2026 10 15 (#1267)

Miguel Ribeiroc36e2f4fe107
diff --git a/.dockerignore b/.dockerignore
index bb235ce..b7ec598 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,13 +1,31 @@
-# Exclude .vscode directory
-.vscode/
-
-# Exclude .git directory
-.git/
-.github/
-
-*.md
-.gitignore
-.dockerignore
-
-# README screenshots and capture script; not used at runtime
-/screenshots/
\ No newline at end of file
+# Exclude .vscode directory
+.vscode/
+
+# Exclude .git directory
+.git/
+.github/
+
+*.md
+.gitignore
+.dockerignore
+
+# README screenshots and capture script; not used at runtime
+/screenshots/
+
+# AI assistant files
+CLAUDE.md
+CLAUDE.local.md
+.claude/
+AGENTS.md
+GEMINI.md
+.gemini/
+.cursor/
+.cursorrules
+.cursorignore
+.windsurf/
+.windsurfrules
+.aider*
+.continue/
+.codex/
+.antigravitycli
+plan.html
diff --git a/.github/workflows/build-release.yaml b/.github/workflows/build-release.yaml
index 9b7e9e2..4e03993 100644
--- a/.github/workflows/build-release.yaml
+++ b/.github/workflows/build-release.yaml
@@ -100,7 +100,9 @@ jobs:
context: .
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
- outputs: type=image,"name=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }},ghcr.io/ellite/wallos",push-by-digest=true,name-canonical=true,push=${{ github.event_name != 'pull_request' }}
+ # PRs never push and never log into a registry, so don't build image
+ # refs from vars.DOCKERHUB_TAG - it is empty for fork PRs.
+ outputs: ${{ github.event_name == 'pull_request' && 'type=cacheonly' || format('type=image,"name={0}/{1},ghcr.io/ellite/wallos",push-by-digest=true,name-canonical=true,push=true', env.REGISTRY, env.IMAGE_NAME) }}
# Scope cache per platform to prevent architecture-mismatched layers
cache-from: type=gha,scope=${{ github.workflow }}-${{ matrix.platform }}
cache-to: type=gha,mode=max,scope=${{ github.workflow }}-${{ matrix.platform }}
diff --git a/.gitignore b/.gitignore
index 4bc93ab..9835338 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,26 @@
-/db/*
-!/db/wallos.empty.db
-/images/uploads/logos/*
-!/images/uploads/logos/wallos.png
-.DS_Store
-.idea/
-.vscode/
-AGENTS.md
-.antigravitycli
-plan.html
+/db/*
+!/db/wallos.empty.db
+/images/uploads/logos/*
+!/images/uploads/logos/wallos.png
+.DS_Store
+.idea/
+.vscode/
+
+# AI assistant files
+CLAUDE.md
+CLAUDE.local.md
+.claude/
+AGENTS.md
+GEMINI.md
+.gemini/
+.cursor/
+.cursorrules
+.cursorignore
+.windsurf/
+.windsurfrules
+.aider*
+.continue/
+.codex/
+.github/copilot-instructions.md
+.antigravitycli
+plan.html
diff --git a/BUGFIXSESSION.md b/BUGFIXSESSION.md
new file mode 100644
index 0000000..2a22b36
--- /dev/null
+++ b/BUGFIXSESSION.md
@@ -0,0 +1,58 @@
+# Bugfix session — 2026-10-15
+
+Branch: `bugfix-session-2026-10-15` (based on `main` @ cc9677a, v5.8.3). Nothing pushed.
+Version: `includes/version.php` bumped 5.8.3 → 5.8.4 (fixes only, no `feat:` merged).
+Test suite: `php tests/run.php` (PHP) and `node --test tests/<file>.test.js` (JS).
+
+PR branches were merged with `-Xignore-cr-at-eol` because several PRs converted CRLF files to LF
+(whole-file diffs); CRLF was restored where it had been lost (`includes/checksession.php`).
+
+## Fixed — merged from PRs (reviewed: diff read in full, tests run)
+
+| PR | Issue | Review notes |
+|----|-------|--------------|
+| #1260 | #1259 | Missing payer / payment method / category no longer warn in list views and sorts. Null-safe `??` lookups, missing sort last. Tests cover NULL and unresolved ids. OK. |
+| #1180 | #1179-style | `isset()` guards on payment-method counters in `stats_calculations.php`. Minimal, OK. |
+| #1240 | #1239 (part 1) | OIDC state is persisted to disk *before* the token exchange so a retried callback cannot redeem the same code twice. Test reads the session file from outside during the exchange. Restored CRLF in `checksession.php`. See "Needs decision" for part 2. |
+| #1229 | — | VAPID keypair write made conditional + read back, so two first-use requests cannot replace the key (silent 403 for all subscribed devices). OK. |
+| #1228 | #1212 | Notification cron fatal (TypeError on `CURLOPT_HTTPHEADER` null). **Changed during review:** the shared `webhook_custom_headers()` only accepted JSON, which would have silently dropped the newline-separated format the cancellation job used to read. Added a line-based fallback (kept backward compatible), and CR/LF stripping so a header value cannot smuggle another header. One of the PR's assertions was updated accordingly. |
+| #1230 | — | CI only: `type=cacheonly` for PR builds, fixes red checks on fork PRs. OK. |
+| #1263 | — | Theme switch no longer wipes `mobile-navigation` / `rtl` body classes. JS node test passes (4 cases). OK. |
+| #1237 | — | Backup zip removed via shutdown function even if the download is abandoned. Tests only pin the shape (cannot cut a stream in the harness) — noted. OK. |
+| #1236 | — | Settings API now reports failure when the CSS / colour DELETE or INSERT fails, rather than "success". OK. |
+| #1252 | — | Japanese translations: 504/504 keys now match `en.php`; `ja.php` and `ja.js` lint clean. Did not review the Japanese wording itself. |
+
+## Fixed — written in this session
+
+| Issue | Fix | Tests |
+|-------|-----|-------|
+| #863 CSV export shows `£` | `scripts/profile.js`: CSV is prefixed with a UTF-8 BOM and served as `text/csv`, so Excel reads UTF-8. | `tests/csv_export.test.js` |
+| #990 Webhook body sent as form data | JSON payloads now get `Content-Type: application/json` unless the user set their own Content-Type. Applied to both crons and the test button. `webhook_headers_with_content_type()` in `includes/webhook_headers.php`. | `tests/cases/webhook_headers_test.php` |
+| #891 OIDC logout "Missing parameters: id_token_hint" | ID token kept in the session at OIDC login; logout redirect now sends `id_token_hint`, `client_id` and `post_logout_redirect_uri` (`includes/oidc/logout_url.php`). Also handles logout URLs that already contain `?`. | `tests/cases/oidc_logout_url_test.php` |
+| #861 Sort by price ignores currency | Price sort ranks by the main-currency (and per-month, if that setting is on) value. `printSubscriptions()` used to re-sort by the displayed price and overrode any earlier ordering, so the fix lives there (`sortSubscriptionsByPrice()` + `sort_price`), covering both `subscriptions.php` and the filter endpoint. Ties keep DB order; disabled-to-bottom respected. Verified live on devhub (EUR 50 > JPY 3000 ≈ 18.75 > USD 20 ≈ 18.18). | `tests/cases/price_sort_test.php` |
+| (found while testing #1259 on devhub) CSV export emitted PHP warnings inside the JSON for subscriptions with no payer / payment method / known category | `endpoints/subscriptions/export.php`: null-safe lookups, so API-created subscriptions export cleanly. | `tests/cases/export_missing_relations_test.php` |
+
+## Needs your input / not done
+
+| Item | Why |
+|------|-----|
+| PR #1238 (non-200 status for refused endpoint requests) | Not merged. Changes every refusal to 401/403/405. About 18 JS callers do `if (!response.ok) throw/show generic error` *before* reading the body, so the user would see a generic "failed" instead of the server's "session expired" message. Needs a decision, and a pass over `scripts/*.js` if wanted. |
+| PR #1249 (grid layout for #1149 column alignment) | Not merged. Large CSS change to the main list, also hides the renewal icon on mobile. I cannot judge it without looking at it in a browser. Worth a visual check on devhub. |
+| #1239 part 2 | The second half (don't delete the old session on `session_regenerate_id`, leave a short-lived pointer so the retry lands in the new session) touches the whole sign-in path. The reporter offered to do it; I did not, since it is a design decision. |
+| #1142 dashboard currency | The maintainer says it is intentional (next payments show the real amount). It is a feature request, not a bug. |
+| #930 custom payment method | Reporter found the cause: SMB-mounted logos folder. Environment problem, not code. |
+| #862 502 behind nginx | Reporter's IPv6 setup; `nginx.default.conf` already uses `ipv6only=off`. No repro, no change. |
+
+| PR #1258 (Dockerfile / .dockerignore rewrite, chore) | Not merged. Full multi-stage Dockerfile rewrite plus build-arg changes in the release workflow. I cannot build/publish images unattended and it is not a bug fix. |
+| PR #1264 (e2e tests) | Not merged. Large addition; deserves its own review of what it needs in CI. |
+| Feature PRs #1262, #1261, #1256, #1255, #1253, #1248, #1241, #1235, #1234, #1233, #1232, #1231, #1213, #1156, #1139 | Deliberately left out: you asked for only one release and a `feat:` would force a 0.1.0 bump. They are untouched on their own branches; none were reviewed in depth. |
+| #867 notifications not translated | Real, but it is a feature-sized change: the notification strings are hardcoded English in the cron jobs and there is no i18n loading per user in those scripts. Not started. |
+| #958, #956, #1096, #921, #979 | Not reproducible from code: cron not running in the reporter's container (#958), SMTP/spam setup (#956), proxy timeouts (#1096), very old SQLite 3.7.17 (#921), and PHP 8.4/8.5 (#979) reported fine by a user. #979 may be closable — the 8.5 / 8.4 reports suggest it works; I only have PHP 8.2 locally. |
+
+## Verification
+
+- `php tests/run.php`: 179 cases, 2905 assertions, all passing.
+- `node --test tests/theme_body_classes.test.js tests/csv_export.test.js`: 6 cases passing.
+- devhub (`wallos-dev`, port 8282, project dir is bind-mounted): logged in as `agent`; with NULL payer/payment method rows the subscriptions page renders without warnings, the price sort order is correct and CSV export returns clean JSON.
+- Side effects on devhub: I added three `ZZ-*` test subscriptions for the `agent` user and deleted them again. I also set the agent user's EUR/USD/JPY `rate` values to 1 / 1.1 / 160 to test conversion; the originals were not recorded, so the next exchange-rate refresh will overwrite them.
+- Not tested live: OIDC logout (no provider available), webhook Content-Type against a real receiver, Excel's BOM handling, push/Pushover paths, PR #1237's abandoned download.
diff --git a/api/settings/set_settings.php b/api/settings/set_settings.php
index 95122a3..fd33952 100644
--- a/api/settings/set_settings.php
+++ b/api/settings/set_settings.php
@@ -82,14 +82,38 @@ $userId = $user['id'];
if (isset($_POST['css'])) {
$customCss = $_POST['css'];
+ // Both halves are read, and the delete as much as the insert. A delete
+ // that fails while the insert succeeds leaves two rows for one user, and
+ // every reader of this table takes whichever row it is handed first - so
+ // the page can go on serving the css this request replaced, after the
+ // answer below said it was saved.
$stmtDelCss = $db->prepare('DELETE FROM custom_css_style WHERE user_id = :userId');
- $stmtDelCss->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $stmtDelCss->execute();
+ $cssStored = $stmtDelCss !== false;
- $stmtInsCss = $db->prepare('INSERT INTO custom_css_style (css, user_id) VALUES (:customCss, :userId)');
- $stmtInsCss->bindValue(':customCss', $customCss, SQLITE3_TEXT);
- $stmtInsCss->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $stmtInsCss->execute();
+ if ($cssStored) {
+ $stmtDelCss->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $cssStored = $stmtDelCss->execute() !== false;
+ }
+
+ if ($cssStored) {
+ $stmtInsCss = $db->prepare('INSERT INTO custom_css_style (css, user_id) VALUES (:customCss, :userId)');
+ $cssStored = $stmtInsCss !== false;
+
+ if ($cssStored) {
+ $stmtInsCss->bindValue(':customCss', $customCss, SQLITE3_TEXT);
+ $stmtInsCss->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $cssStored = $stmtInsCss->execute() !== false;
+ }
+ }
+
+ if (!$cssStored) {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Database error',
+ 'message' => 'Failed to save settings to the database.'
+ ]);
+ exit;
+ }
}
// 2. Process Custom Colors
@@ -131,17 +155,38 @@ if (isset($_POST['main_color']) || isset($_POST['accent_color']) || isset($_POST
exit;
}
- // Delete & Insert
+ // Delete & Insert, both read. Same shape as the custom css above and the
+ // same consequence: two colour rows for one user, and the page keeps the
+ // theme this request was meant to replace.
$delColors = $db->prepare('DELETE FROM custom_colors WHERE user_id = :userId');
- $delColors->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $delColors->execute();
-
- $insColors = $db->prepare('INSERT INTO custom_colors (main_color, accent_color, hover_color, user_id) VALUES (:main_color, :accent_color, :hover_color, :userId)');
- $insColors->bindValue(':main_color', $main_color, SQLITE3_TEXT);
- $insColors->bindValue(':accent_color', $accent_color, SQLITE3_TEXT);
- $insColors->bindValue(':hover_color', $hover_color, SQLITE3_TEXT);
- $insColors->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $insColors->execute();
+ $colorsStored = $delColors !== false;
+
+ if ($colorsStored) {
+ $delColors->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $colorsStored = $delColors->execute() !== false;
+ }
+
+ if ($colorsStored) {
+ $insColors = $db->prepare('INSERT INTO custom_colors (main_color, accent_color, hover_color, user_id) VALUES (:main_color, :accent_color, :hover_color, :userId)');
+ $colorsStored = $insColors !== false;
+
+ if ($colorsStored) {
+ $insColors->bindValue(':main_color', $main_color, SQLITE3_TEXT);
+ $insColors->bindValue(':accent_color', $accent_color, SQLITE3_TEXT);
+ $insColors->bindValue(':hover_color', $hover_color, SQLITE3_TEXT);
+ $insColors->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $colorsStored = $insColors->execute() !== false;
+ }
+ }
+
+ if (!$colorsStored) {
+ echo json_encode([
+ 'success' => false,
+ 'title' => 'Database error',
+ 'message' => 'Failed to save settings to the database.'
+ ]);
+ exit;
+ }
}
// 3. Process Settings table updates
diff --git a/endpoints/cronjobs/sendcancellationnotifications.php b/endpoints/cronjobs/sendcancellationnotifications.php
index a2f0c1e..76b0244 100644
--- a/endpoints/cronjobs/sendcancellationnotifications.php
+++ b/endpoints/cronjobs/sendcancellationnotifications.php
@@ -13,6 +13,7 @@ require __DIR__ . '/../../libs/PHPMailer/SMTP.php';
require __DIR__ . '/../../libs/PHPMailer/Exception.php';
require 'settimezone.php';
+require_once __DIR__ . '/../../includes/webhook_headers.php';
// Get all user ids
$query = "SELECT id, username FROM user";
@@ -522,10 +523,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
$message .= $subscription['name'] . " for " . $subscription['price'] . "\n";
}
- $headers = json_decode($ntfy["headers"], true);
- $customheaders = array_map(function ($key, $value) {
- return "$key: $value";
- }, array_keys($headers), $headers);
+ $customheaders = webhook_custom_headers($ntfy["headers"]);
$ch = curl_init();
@@ -594,9 +592,13 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $webhook['request_method']);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- // Add headers if they exist
- if (!empty($webhook['headers'])) {
- $customheaders = preg_split("/\r\n|\n|\r/", $webhook['headers']);
+ // Add headers if they exist. The same reading as
+ // every other job: this one used to split the field
+ // into lines, so a value that worked here was a
+ // value that ended the other run, and the other way
+ // round.
+ $customheaders = webhook_headers_with_content_type(webhook_custom_headers($webhook['headers']), $payload);
+ if (!empty($customheaders)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
}
diff --git a/endpoints/cronjobs/sendnotifications.php b/endpoints/cronjobs/sendnotifications.php
index 7a225d2..e700dcb 100644
--- a/endpoints/cronjobs/sendnotifications.php
+++ b/endpoints/cronjobs/sendnotifications.php
@@ -18,6 +18,7 @@ require __DIR__ . '/../../includes/currency_formatter.php';
require __DIR__ . '/../../includes/budget_period_calculations.php';
require 'settimezone.php';
+require_once __DIR__ . '/../../includes/webhook_headers.php';
if (php_sapi_name() == 'cli') {
$date = new DateTime('now');
@@ -855,14 +856,7 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
continue;
}
- $headers = json_decode($ntfy["headers"], true);
- $customheaders = [];
-
- if (is_array($headers)) {
- $customheaders = array_map(function ($key, $value) {
- return "$key: $value";
- }, array_keys($headers), $headers);
- }
+ $customheaders = webhook_custom_headers($ntfy["headers"]);
$ch = curl_init();
@@ -936,8 +930,8 @@ while ($userToNotify = $usersToNotify->fetchArray(SQLITE3_ASSOC)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Add headers if they exist
- if (!empty($webhook['headers'])) {
- $customheaders = json_decode($webhook["headers"], true);
+ $customheaders = webhook_headers_with_content_type(webhook_custom_headers($webhook['headers']), $payload);
+ if (!empty($customheaders)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
}
diff --git a/endpoints/db/backup.php b/endpoints/db/backup.php
index 257d0fb..14b2fe7 100644
--- a/endpoints/db/backup.php
+++ b/endpoints/db/backup.php
@@ -1,87 +1,103 @@
-<?php
-require_once '../../includes/connect_endpoint.php';
-require_once '../../includes/validate_endpoint_admin.php';
-
-function addFolderToZip($dir, $zipArchive, $zipdir = '')
-{
- if (is_dir($dir)) {
- if ($dh = opendir($dir)) {
- //Add the directory
- if (!empty($zipdir))
- $zipArchive->addEmptyDir($zipdir);
- while (($file = readdir($dh)) !== false) {
- // Skip '.' and '..'
- if ($file == "." || $file == "..") {
- continue;
- }
- //If it's a folder, run the function again!
- if (is_dir($dir . $file)) {
- $newdir = $dir . $file . '/';
- addFolderToZip($newdir, $zipArchive, $zipdir . $file . '/');
- } else {
- //Add the files
- $zipArchive->addFile($dir . $file, $zipdir . $file);
- }
- }
- }
- } else {
- die(json_encode([
- "success" => false,
- "message" => "Directory does not exist: $dir"
- ]));
- }
-}
-
-// Build the archive OUTSIDE the web root. Previously it was written to
-// ../../.tmp/ with a uniqid()-based name and served statically by nginx, which
-// let anyone who could guess the (timestamp-derived, low-entropy) filename
-// download the full database unauthenticated. The backup is now streamed
-// directly to the authenticated admin below and never persists in a
-// web-accessible location.
-$zipname = tempnam(sys_get_temp_dir(), 'wallos_backup_');
-if ($zipname === false) {
- die(json_encode([
- "success" => false,
- "message" => translate('cannot_open_zip', $i18n)
- ]));
-}
-
-$zip = new ZipArchive();
-if ($zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
- @unlink($zipname);
- die(json_encode([
- "success" => false,
- "message" => translate('cannot_open_zip', $i18n)
- ]));
-}
-
-addFolderToZip('../../db/', $zip);
-addFolderToZip('../../images/uploads/', $zip);
-
-if ($zip->close() === false) {
- @unlink($zipname);
- die(json_encode([
- "success" => false,
- "message" => "Failed to finalize the zip file"
- ]));
-}
-
-// Discard any buffered output (e.g. a stray newline from an included file)
-// so it cannot corrupt the binary archive that follows.
-while (ob_get_level() > 0) {
- ob_end_clean();
-}
-
-// ZipArchive wrote through its own handle after tempnam() created the file at
-// 0 bytes, so clear the stat cache before reading its size for Content-Length.
-clearstatcache(true, $zipname);
-
-$downloadName = 'Wallos-Backup-' . date('Ymd-His') . '.zip';
-header('Content-Type: application/zip');
-header('Content-Disposition: attachment; filename="' . $downloadName . '"');
-header('Content-Length: ' . filesize($zipname));
-header('Cache-Control: no-store');
-
-readfile($zipname);
-unlink($zipname);
+<?php
+require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint_admin.php';
+
+function addFolderToZip($dir, $zipArchive, $zipdir = '')
+{
+ if (is_dir($dir)) {
+ if ($dh = opendir($dir)) {
+ //Add the directory
+ if (!empty($zipdir))
+ $zipArchive->addEmptyDir($zipdir);
+ while (($file = readdir($dh)) !== false) {
+ // Skip '.' and '..'
+ if ($file == "." || $file == "..") {
+ continue;
+ }
+ //If it's a folder, run the function again!
+ if (is_dir($dir . $file)) {
+ $newdir = $dir . $file . '/';
+ addFolderToZip($newdir, $zipArchive, $zipdir . $file . '/');
+ } else {
+ //Add the files
+ $zipArchive->addFile($dir . $file, $zipdir . $file);
+ }
+ }
+ }
+ } else {
+ die(json_encode([
+ "success" => false,
+ "message" => "Directory does not exist: $dir"
+ ]));
+ }
+}
+
+// Build the archive OUTSIDE the web root. Previously it was written to
+// ../../.tmp/ with a uniqid()-based name and served statically by nginx, which
+// let anyone who could guess the (timestamp-derived, low-entropy) filename
+// download the full database unauthenticated. The backup is now streamed
+// directly to the authenticated admin below and never persists in a
+// web-accessible location.
+$zipname = tempnam(sys_get_temp_dir(), 'wallos_backup_');
+if ($zipname === false) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('cannot_open_zip', $i18n)
+ ]));
+}
+
+$zip = new ZipArchive();
+if ($zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
+ @unlink($zipname);
+ die(json_encode([
+ "success" => false,
+ "message" => translate('cannot_open_zip', $i18n)
+ ]));
+}
+
+addFolderToZip('../../db/', $zip);
+addFolderToZip('../../images/uploads/', $zip);
+
+if ($zip->close() === false) {
+ @unlink($zipname);
+ die(json_encode([
+ "success" => false,
+ "message" => "Failed to finalize the zip file"
+ ]));
+}
+
+// Discard any buffered output (e.g. a stray newline from an included file)
+// so it cannot corrupt the binary archive that follows.
+while (ob_get_level() > 0) {
+ ob_end_clean();
+}
+
+// ZipArchive wrote through its own handle after tempnam() created the file at
+// 0 bytes, so clear the stat cache before reading its size for Content-Length.
+clearstatcache(true, $zipname);
+
+$downloadName = 'Wallos-Backup-' . date('Ymd-His') . '.zip';
+header('Content-Type: application/zip');
+header('Content-Disposition: attachment; filename="' . $downloadName . '"');
+header('Content-Length: ' . filesize($zipname));
+header('Cache-Control: no-store');
+
+// Removed on the way out rather than after readfile(), because a download the
+// browser abandons - a closed tab, a lost connection, a proxy timing out - ends
+// this script inside readfile(). The unlink below it then never runs, and a
+// complete copy of the database and every uploaded file stays in the system
+// temp directory until something else clears it. The shutdown function runs on
+// that path too.
+//
+// Registered here rather than at tempnam() so the failure branches above keep
+// their own unlink and their own message.
+register_shutdown_function(function () use ($zipname) {
+ if (is_file($zipname)) {
+ @unlink($zipname);
+ }
+});
+
+// An abandoned download does not need the rest of the file read into memory
+// first; ignore_user_abort stays off, so PHP stops at the next write.
+readfile($zipname);
exit;
\ No newline at end of file
diff --git a/endpoints/notifications/testntfynotifications.php b/endpoints/notifications/testntfynotifications.php
index 0773786..74cc699 100644
--- a/endpoints/notifications/testntfynotifications.php
+++ b/endpoints/notifications/testntfynotifications.php
@@ -1,87 +1,82 @@
-<?php
-
-require_once '../../includes/connect_endpoint.php';
-require_once '../../includes/validate_endpoint.php';
-require_once '../../includes/ssrf_helper.php';
-
-$postData = file_get_contents("php://input");
-$data = json_decode($postData, true);
-
-if (
- !isset($data["host"]) || $data["host"] == "" ||
- !isset($data["topic"]) || $data["topic"] == ""
-) {
- $response = [
- "success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- echo json_encode($response);
-} else {
- $host = rtrim($data["host"], '/');
- $topic = $data["topic"];
- $headers = json_decode($data["headers"], true);
- if ($headers === null) {
- $headers = [];
- }
- $customheaders = array_map(function ($key, $value) {
- return "$key: $value";
- }, array_keys($headers), $headers);
-
- $url = rtrim($host, '/') . '/' . ltrim($topic, '/');
- $ignore_ssl = $data["ignore_ssl"];
-
- // Validate URL scheme
- $parsedUrl = parse_url($url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $ssrf = validate_webhook_url_for_ssrf($url, $db, $i18n, $userId);
-
- // Set the message parameters
- $message = translate('test_notification', $i18n);
-
- $ch = curl_init();
-
- // Set the URL and other options
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
- curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
- curl_setopt($ch, CURLOPT_TIMEOUT, 15);
-
- if ($ignore_ssl) {
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- }
-
- // Execute the request
- $response = curl_exec($ch);
-
- // Close the cURL session
- unset($ch);
-
- // Check if the message was sent successfully
- if ($response === false) {
- die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n)
- ]));
- }
-
- die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n)
- ]));
+<?php
+
+require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
+require_once '../../includes/ssrf_helper.php';
+require_once '../../includes/webhook_headers.php';
+
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["host"]) || $data["host"] == "" ||
+ !isset($data["topic"]) || $data["topic"] == ""
+) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ echo json_encode($response);
+} else {
+ $host = rtrim($data["host"], '/');
+ $topic = $data["topic"];
+ $customheaders = webhook_custom_headers($data["headers"]);
+
+ $url = rtrim($host, '/') . '/' . ltrim($topic, '/');
+ $ignore_ssl = $data["ignore_ssl"];
+
+ // Validate URL scheme
+ $parsedUrl = parse_url($url);
+ if (
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($url, FILTER_VALIDATE_URL)
+ ) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+ }
+
+ $ssrf = validate_webhook_url_for_ssrf($url, $db, $i18n, $userId);
+
+ // Set the message parameters
+ $message = translate('test_notification', $i18n);
+
+ $ch = curl_init();
+
+ // Set the URL and other options
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);
+
+ if ($ignore_ssl) {
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+ }
+
+ // Execute the request
+ $response = curl_exec($ch);
+
+ // Close the cURL session
+ unset($ch);
+
+ // Check if the message was sent successfully
+ if ($response === false) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('notification_failed', $i18n)
+ ]));
+ }
+
+ die(json_encode([
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n)
+ ]));
}
\ No newline at end of file
diff --git a/endpoints/notifications/testwebhooknotifications.php b/endpoints/notifications/testwebhooknotifications.php
index 7245650..9d49a7c 100644
--- a/endpoints/notifications/testwebhooknotifications.php
+++ b/endpoints/notifications/testwebhooknotifications.php
@@ -1,105 +1,106 @@
-<?php
-
-require_once '../../includes/connect_endpoint.php';
-require_once '../../includes/validate_endpoint.php';
-require_once '../../includes/ssrf_helper.php';
-
-// Variables available: {{days_until}}, {{subscription_name}}, {{subscription_price}}, {{subscription_currency}}, {{subscription_category}}, {{subscription_date}}, {{subscription_payer}}, {{subscription_days_until_payment}}, {{subscription_notes}}, {{subscription_url}}
-$fakeSubscription = [
- "days_until" => 5,
- "subscription_name" => "Test Subscription",
- "subscription_price" => 10.00,
- "subscription_currency" => "USD",
- "subscription_category" => "Test Category",
- "subscription_date" => date("Y-m-d H:i:s"),
- "subscription_payer" => "Test Payer",
- "subscription_days_until_payment" => 30,
- "subscription_notes" => "Test Notes",
- "subscription_url" => "https://example.com/test-subscription"
-];
-
-$postData = file_get_contents("php://input");
-$data = json_decode($postData, true);
-
-if (
- !isset($data["requestmethod"]) || $data["requestmethod"] == "" ||
- !isset($data["url"]) || $data["url"] == "" ||
- !isset($data["payload"]) || $data["payload"] == ""
-) {
- $response = [
- "success" => false,
- "message" => translate('fill_mandatory_fields', $i18n)
- ];
- die(json_encode($response));
-} else {
- $requestmethod = $data["requestmethod"];
- $url = $data["url"];
- $payload = $data["payload"];
-
- // Validate URL scheme
- $parsedUrl = parse_url($url);
- if (
- !isset($parsedUrl['scheme']) ||
- !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
- !filter_var($url, FILTER_VALIDATE_URL)
- ) {
- die(json_encode([
- "success" => false,
- "message" => translate("error", $i18n)
- ]));
- }
-
- $ssrf = validate_webhook_url_for_ssrf($url, $db, $i18n, $userId);
-
- // Replace placeholders in the payload with fake subscription data
- foreach ($fakeSubscription as $key => $value) {
- $placeholder = "{{" . $key . "}}";
- $payload = str_replace($placeholder, $value, $payload);
- }
-
- $customheaders = json_decode($data["customheaders"], true);
- $ignore_ssl = $data["ignore_ssl"];
-
- $ch = curl_init();
-
- // Set the URL and other options
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
- curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestmethod);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- if (!empty($customheaders)) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
- }
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
- curl_setopt($ch, CURLOPT_TIMEOUT, 15);
-
- if ($ignore_ssl) {
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- }
-
- // Execute the request
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $curlError = curl_error($ch);
-
- // Close the cURL session
- unset($ch);
-
- // Check if the message was sent successfully
- if ($response === false || $httpCode >= 400) {
- die(json_encode([
- "success" => false,
- "message" => translate('notification_failed', $i18n),
- "response" => $curlError ? $curlError : $response
- ]));
- } else {
- die(json_encode([
- "success" => true,
- "message" => translate('notification_sent_successfuly', $i18n),
- "response" => $response
- ]));
- }
+<?php
+
+require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/validate_endpoint.php';
+require_once '../../includes/ssrf_helper.php';
+require_once '../../includes/webhook_headers.php';
+
+// Variables available: {{days_until}}, {{subscription_name}}, {{subscription_price}}, {{subscription_currency}}, {{subscription_category}}, {{subscription_date}}, {{subscription_payer}}, {{subscription_days_until_payment}}, {{subscription_notes}}, {{subscription_url}}
+$fakeSubscription = [
+ "days_until" => 5,
+ "subscription_name" => "Test Subscription",
+ "subscription_price" => 10.00,
+ "subscription_currency" => "USD",
+ "subscription_category" => "Test Category",
+ "subscription_date" => date("Y-m-d H:i:s"),
+ "subscription_payer" => "Test Payer",
+ "subscription_days_until_payment" => 30,
+ "subscription_notes" => "Test Notes",
+ "subscription_url" => "https://example.com/test-subscription"
+];
+
+$postData = file_get_contents("php://input");
+$data = json_decode($postData, true);
+
+if (
+ !isset($data["requestmethod"]) || $data["requestmethod"] == "" ||
+ !isset($data["url"]) || $data["url"] == "" ||
+ !isset($data["payload"]) || $data["payload"] == ""
+) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_mandatory_fields', $i18n)
+ ];
+ die(json_encode($response));
+} else {
+ $requestmethod = $data["requestmethod"];
+ $url = $data["url"];
+ $payload = $data["payload"];
+
+ // Validate URL scheme
+ $parsedUrl = parse_url($url);
+ if (
+ !isset($parsedUrl['scheme']) ||
+ !in_array(strtolower($parsedUrl['scheme']), ['http', 'https']) ||
+ !filter_var($url, FILTER_VALIDATE_URL)
+ ) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate("error", $i18n)
+ ]));
+ }
+
+ $ssrf = validate_webhook_url_for_ssrf($url, $db, $i18n, $userId);
+
+ // Replace placeholders in the payload with fake subscription data
+ foreach ($fakeSubscription as $key => $value) {
+ $placeholder = "{{" . $key . "}}";
+ $payload = str_replace($placeholder, $value, $payload);
+ }
+
+ $customheaders = webhook_headers_with_content_type(webhook_custom_headers($data["customheaders"]), $payload);
+ $ignore_ssl = $data["ignore_ssl"];
+
+ $ch = curl_init();
+
+ // Set the URL and other options
+ curl_setopt($ch, CURLOPT_URL, $url);
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
+ curl_setopt($ch, CURLOPT_RESOLVE, ["{$ssrf['host']}:{$ssrf['port']}:{$ssrf['ip']}"]);
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestmethod);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
+ if (!empty($customheaders)) {
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $customheaders);
+ }
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
+ curl_setopt($ch, CURLOPT_TIMEOUT, 15);
+
+ if ($ignore_ssl) {
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+ }
+
+ // Execute the request
+ $response = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ $curlError = curl_error($ch);
+
+ // Close the cURL session
+ unset($ch);
+
+ // Check if the message was sent successfully
+ if ($response === false || $httpCode >= 400) {
+ die(json_encode([
+ "success" => false,
+ "message" => translate('notification_failed', $i18n),
+ "response" => $curlError ? $curlError : $response
+ ]));
+ } else {
+ die(json_encode([
+ "success" => true,
+ "message" => translate('notification_sent_successfuly', $i18n),
+ "response" => $response
+ ]));
+ }
}
\ No newline at end of file
diff --git a/endpoints/subscriptions/export.php b/endpoints/subscriptions/export.php
index ef10f91..fd50369 100644
--- a/endpoints/subscriptions/export.php
+++ b/endpoints/subscriptions/export.php
@@ -39,11 +39,11 @@ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
'Payment Cycle' => $cyclePrint,
'Next Payment' => $row['next_payment'],
'Renewal' => $row['auto_renew'] ? 'Automatic' : 'Manual',
- 'Category' => str_replace(',', ' ', $categories[$row['category_id']]['name']),
- 'Payment Method' => str_replace(',', ' ', $payment_methods[$row['payment_method_id']]['name']),
- 'Paid By' => str_replace(',', ' ', $members[$row['payer_user_id']]['name']),
- 'Price' => $currencies[$row['currency_id']]['symbol'] . $row['price'],
- 'Notes' => str_replace(',', ' ', $row['notes']),
+ 'Category' => str_replace(',', ' ', $categories[$row['category_id'] ?? '']['name'] ?? ''),
+ 'Payment Method' => str_replace(',', ' ', $payment_methods[$row['payment_method_id'] ?? '']['name'] ?? ''),
+ 'Paid By' => str_replace(',', ' ', $members[$row['payer_user_id'] ?? '']['name'] ?? ''),
+ 'Price' => ($currencies[$row['currency_id'] ?? '']['symbol'] ?? '') . $row['price'],
+ 'Notes' => str_replace(',', ' ', $row['notes'] ?? ''),
'URL' => $row['url'],
'State' => $row['inactive'] ? 'Disabled' : 'Enabled',
'Notifications' => $row['notify'] ? 'Enabled' : 'Disabled',
diff --git a/endpoints/subscriptions/get.php b/endpoints/subscriptions/get.php
index 6d4d7cb..d2ae10d 100644
--- a/endpoints/subscriptions/get.php
+++ b/endpoints/subscriptions/get.php
@@ -195,13 +195,15 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
$formatted_date = $formatter->format($next_payment_timestamp);
$print[$id]['next_payment'] = $formatted_date;
$print[$id]['auto_renew'] = $subscription['auto_renew'];
- $paymentIconFolder = (strpos($payment_methods[$paymentMethodId]['icon'], 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";
- $print[$id]['payment_method_icon'] = $paymentIconFolder . $payment_methods[$paymentMethodId]['icon'];
- $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId]['name'];
+ $paymentIcon = $payment_methods[$paymentMethodId ?? ""]['icon'] ?? "";
+ $paymentIconFolder = (strpos($paymentIcon, 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";
+ $print[$id]['payment_method_icon'] = $paymentIcon === "" ? "" : $paymentIconFolder . $paymentIcon;
+ $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId ?? ""]['name'] ?? "";
$print[$id]['payment_method_id'] = $paymentMethodId;
$print[$id]['category_id'] = $subscription['category_id'];
$print[$id]['payer_user_id'] = $subscription['payer_user_id'];
$print[$id]['price'] = floatval($subscription['price']);
+ $print[$id]['sort_price'] = getSortPrice($subscription['price'], $subscription['currency_id'], $mainCurrencyId, $cycle, $frequency, $settings, $db);
$print[$id]['progress'] = getSubscriptionProgress($cycle, $frequency, $subscription['next_payment']);
$print[$id]['inactive'] = $subscription['inactive'];
$print[$id]['url'] = $subscription['url'] ?? "";
@@ -234,13 +236,13 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
if ($sortOrder == "category_id") {
usort($print, function ($a, $b) use ($categories) {
- return $categories[$a['category_id']]['order'] - $categories[$b['category_id']]['order'];
+ return ($categories[$a['category_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($categories[$b['category_id'] ?? ""]['order'] ?? PHP_INT_MAX);
});
}
if ($sortOrder == "payment_method_id") {
usort($print, function ($a, $b) use ($payment_methods) {
- return $payment_methods[$a['payment_method_id']]['order'] - $payment_methods[$b['payment_method_id']]['order'];
+ return ($payment_methods[$a['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($payment_methods[$b['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX);
});
}
diff --git a/includes/checksession.php b/includes/checksession.php
index 124d1e5..aae3ca7 100644
--- a/includes/checksession.php
+++ b/includes/checksession.php
@@ -12,6 +12,8 @@ if (session_status() === PHP_SESSION_NONE) {
session_start();
}
+require_once __DIR__ . '/oidc/session_persist.php';
+
if (isset($_GET['code']) && isset($_GET['state'])) {
// This request is coming from the OIDC login flow
$code = $_GET['code'];
@@ -25,12 +27,25 @@ if (isset($_GET['code']) && isset($_GET['state'])) {
!hash_equals($expectedState, $state)
) {
unset($_SESSION['oidc_state']);
+ oidc_persist_session();
$db->close();
header("Location: login.php?error=oidc_invalid_state");
exit();
}
+ // Removed, and written to disk before the exchange begins (#1239).
+ //
+ // The token exchange below takes a second or two, and PHP writes the
+ // session at the end of the request - by which time oidc_login.php has
+ // called session_regenerate_id(true), which deletes the file this removal
+ // would have been written to. A second request carrying the same callback,
+ // which is what a browser on an unstable connection produces, waits on the
+ // session lock and is then handed the state as it stood before, passes the
+ // check above, and redeems the same authorization code again. The provider
+ // refuses it, and the person is shown a failure for a login that
+ // succeeded.
unset($_SESSION['oidc_state']);
+ oidc_persist_session();
require_once 'includes/oidc/handle_oidc_callback.php';
@@ -78,4 +93,4 @@ if (isset($_GET['code']) && isset($_GET['state'])) {
}
-?>
\ No newline at end of file
+?>
\ No newline at end of file
diff --git a/includes/i18n/ja.php b/includes/i18n/ja.php
index 72215f8..760bd07 100644
--- a/includes/i18n/ja.php
+++ b/includes/i18n/ja.php
@@ -2,12 +2,14 @@
$i18n = [
// Registration page
+ "auth_tagline" => "お金の行き先を把握しましょう。",
+ "auth_tagline_sub" => "サブスクリプションを管理し、支出を確認し、更新を見逃さないようにしましょう。",
"create_account" => "ログインする前にアカウントを作成する必要があります",
"username" => "ユーザー名",
"password" => "パスワード",
- "email" => "メール",
"firstname" => "名",
"lastname" => "苗字",
+ "email" => "メール",
"confirm_password" => "パスワードの確認",
"main_currency" => "主要通貨",
"language" => "言語",
@@ -26,7 +28,7 @@ $i18n = [
"please_login" => "ログインしてください",
"stay_logged_in" => "ログインしたままにする (30日)",
"login" => "ログイン",
- "login_with" => "ログインする",
+ "login_with" => "次の方法でログイン",
"or" => "または",
"login_failed" => "ログイン情報が間違っています",
"registration_successful" => "登録に成功",
@@ -43,7 +45,7 @@ $i18n = [
"stats" => "統計",
"settings" => "設定",
"admin" => "管理者",
- "about" => "About",
+ "about" => "概要",
"logout" => "ログアウト",
// Dashboard
"hello" => "こんにちは",
@@ -78,7 +80,7 @@ $i18n = [
"manual_renewal" => "手動更新",
"start_date" => "開始日",
"inactive" => "サブスクリプションを無効にする",
- "replaced_with" => "置き換えられた",
+ "replaced_with" => "置き換え先",
"none" => "なし",
"reminder" => "リマインダー",
"cancellation" => "キャンセル",
@@ -120,9 +122,9 @@ $i18n = [
"frequency" => "頻度",
"cycle" => "サイクル",
"no_category" => "カテゴリなし",
- "paid_by" => "支払い元",
+ "paid_by" => "支払い者",
"url" => "URL",
- "notes" => "注釈",
+ "notes" => "メモ",
"notes_bold" => "太字",
"notes_italic" => "斜体",
"notes_list" => "リスト",
@@ -156,6 +158,27 @@ $i18n = [
"payment_method_split" => "支払い方法別",
"total_cost_trend" => "合計費用のトレンド",
"cost_vs_budget" => "費用対予算",
+ "overview" => "概要",
+ "trends_and_forecast" => "傾向と予測",
+ "history_and_lifetime" => "履歴と累計",
+ "cost_per_day" => "1日あたりのコスト",
+ "median_monthly_cost" => "月額サブスクリプション費用の中央値",
+ "cheapest_subscription" => "最も安いサブスクリプション",
+ "vs_last_month" => "前月比",
+ "heaviest_month" => "今後最も高額な月",
+ "months_over_budget" => "予算超過の月(今後12か月)",
+ "manual_renewals" => "手動更新",
+ "all_time_spend" => "累計支出(推定)",
+ "oldest_subscription" => "最も古いサブスクリプション(年)",
+ "average_subscription_age" => "サブスクリプションの平均利用年数(年)",
+ "projected_cost" => "予測コスト(今後12か月)",
+ "lifetime_spend" => "累計支出(上位10件、推定)",
+ "billing_cycle_split" => "請求サイクル別の内訳",
+ "currency_split" => "通貨別の内訳",
+ "price_distribution" => "価格分布",
+ "subscriptions_count" => "サブスクリプション数",
+ "new_subscriptions_per_year" => "年間の新規サブスクリプション",
+ "estimated_from_current_prices" => "現在の価格に基づく推定",
// About page
"about_and_credits" => "概要とクレジット",
"credits" => "クレジット",
@@ -176,6 +199,7 @@ $i18n = [
"enable_two_factor_authentication" => "二要素認証を有効にする",
"2fa_already_enabled" => "2要素認証は既に有効です",
"totp_code_incorrect" => "TOTPコードが正しくありません",
+ "totp_too_many_attempts" => "試行回数が多すぎます。しばらく待ってから、もう一度お試しください。",
"backup_codes" => "バックアップコード",
"download_backup_codes" => "バックアップコードをダウンロード",
"copy_to_clipboard" => "クリップボードにコピー",
@@ -204,8 +228,8 @@ $i18n = [
"household" => "世帯",
"save_member" => "世帯員を保存",
"delete_member" => "世帯員を削除",
- "cant_delete_member" => "世帯主は削除出ません",
- "cant_delete_member_in_use" => "定期購入を使用中の世帯員は削除できません",
+ "cant_delete_member" => "世帯主は削除できません",
+ "cant_delete_member_in_use" => "定期購入で使用中の世帯員は削除できません",
"household_info" => "Eメールフィールドでは、世帯のメンバーに購読期限が近づいたことを通知することができます。",
"notifications" => "通知",
"enable_email_notifications" => "電子メール通知を有効にする",
@@ -258,6 +282,7 @@ $i18n = [
"unknown_device" => "不明なデバイス",
"enable_on_this_device" => "このデバイスで有効にする",
"categories" => "カテゴリ",
+ "translate_categories" => "AIで翻訳",
"save_category" => "カテゴリを保存",
"delete_category" => "カテゴリを削除",
"cant_delete_category_in_use" => "定期購入で使用中のカテゴリは削除できません",
@@ -268,13 +293,13 @@ $i18n = [
"cant_delete_currency_in_use" => "定期購入で使用中の通貨は削除できません",
"exchange_update" => "為替レートの最終更新日",
"currency_info" => "サポートされている通貨と正しい通貨コードを見つける",
- "currency_performance" => "Fパフォーマンスを向上させるには、使用する通貨のみを保持してください。",
+ "currency_performance" => "パフォーマンスを向上させるには、使用する通貨のみを保持してください。",
"fixer_api_key" => "FixerのAPIキー",
"provider" => "プロバイダ",
"fixer_info" => "複数の通貨を使用し、定期購入に関する正確な統計と並べ替えが必要な場合は、Fixerからの無料APIキーが必要です。",
"get_key" => "キーを入手する",
"get_free_fixer_api_key" => "無料のFixer APIキーを取得",
- "get_key_alternative" => "または、以下のサイトから無料のフィクサーapiキーを入手することもできます。",
+ "get_key_alternative" => "または、以下のサイトから無料のFixer APIキーを入手することもできます。",
"no_api_key_provider" => "または、アカウントもAPIキーも不要なプロバイダーを選択し、キーは空のままにしてください:",
"ai_model" => "AIモデル",
"select_ai_model" => "AIモデルを選択",
@@ -309,6 +334,7 @@ $i18n = [
"show_original_price" => "変換や計算が行われるときに元の価格も表示する",
"experience" => "体験",
"show_subscription_progress" => "定期購入の進捗を表示する",
+ "week_starts_on_sunday" => "カレンダーの週を日曜日から開始",
"disabled_subscriptions" => "無効な定期購入",
"hide_disabled_subscriptions" => "無効な定期購入を非表示にする",
"show_disabled_subscriptions_at_the_bottom" => "無効な定期購入を一番下に表示する",
@@ -348,6 +374,8 @@ $i18n = [
"delete_account_info" => "アカウントを削除するとすべてのサブスクリプションと設定も削除されます。",
// Filters menu
"filter" => "フィルタ",
+ "list_view" => "リスト表示",
+ "grid_view" => "グリッド表示",
"clear" => "クリア",
// Toast
"success" => "成功",
@@ -381,7 +409,7 @@ $i18n = [
"failed_add_household" => "世帯員の追加に失敗",
"failed_edit_household" => "世帯員の編集に失敗",
"failed_remove_household" => "世帯員の削除に失敗",
- "household_in_use" => "定期購入を使用中の世帯員は削除できません",
+ "household_in_use" => "定期購入で使用中の世帯員は削除できません",
"member_saved" => "世帯員を保存",
"member_removed" => "世帯員を削除",
// Notifications
@@ -393,12 +421,13 @@ $i18n = [
"notifications_settings_saved" => "通知設定の保存に成功",
"notification_failed" => "通知の送信に失敗",
// Payments
- "payment_in_use" => "使用中の支払い方法は削除できません",
- "failed_update_payment" => "データーベースの支払い方法の更新に失敗しました",
+ "payment_in_use" => "使用中の支払い方法は無効にできません",
+ "failed_update_payment" => "データベースの支払い方法の更新に失敗しました",
"enabled" => "有効",
"disabled" => "無効",
// Subscription
"error_fetching_image" => "画像の取得エラー",
+ "error_saving_logo" => "ロゴ画像の保存エラー",
"subscription_updated_successfuly" => "定期購入の更新成功",
"subscription_added_successfuly" => "定期購入の追加成功",
"error_deleting_subscription" => "定期購入の削除エラー",
@@ -417,7 +446,7 @@ $i18n = [
"server_url_password_reset" => "設定すると、パスワードリセット機能も有効になる。",
"disable_login" => "ログインを無効にする",
"disable_login_info" => "ログインをバイパスします。サーバーをローカルネットワークのみで運用し、外部からのアクセスがない場合、ログインを無効にすることができます。これにより、管理者ユーザが自動的にログインします。",
- "disable_login_info2" => "この設定を有効にできるのは、ユーザー登録がオフで、管理者以上のユーザーアカウントが存在しない場合のみです。",
+ "disable_login_info2" => "この設定を有効にできるのは、ユーザー登録がオフで、管理者以外のユーザーアカウントが存在しない場合のみです。",
"max_users_info" => "0に設定すると無制限になります",
"registrations_disable_login_info" => "ユーザー登録を有効にすると、ログインを無効にする設定は利用できなくなります。",
"user_management" => "ユーザー管理",
@@ -425,7 +454,7 @@ $i18n = [
"delete_user_info" => "ユーザーを削除すると、そのユーザーのサブスクリプションと設定もすべて削除されます。",
"create_user" => "ユーザーを作成",
"oidc_settings" => "OIDC設定",
- "oidc_auth_enabled" => "OIDC認証を有効にする",
+ "oidc_oauth_enabled" => "OIDC/OAuthを有効にする",
"create_user_automatically" => "OIDCユーザーを自動的に作成する",
"disable_password_login" => "パスワードログインを無効にする",
"require_email_verified_linking" => "アカウント連携には確認済みメールアドレスが必要",
@@ -473,44 +502,41 @@ $i18n = [
"month-12" => "12月",
"total_cost" => "合計費用",
"export_icalendar" => "iCalendarをエクスポート",
- "over_budget_warning" => "予算オーバーだ",
+ "over_budget_warning" => "予算を超えています",
// TOTP Page
"insert_totp_code" => "TOTPコードを入力してください",
-
- "auth_tagline" => "お金の行き先を把握しましょう。",
- "auth_tagline_sub" => "サブスクリプションを管理し、支出を確認し、更新を見逃さないようにしましょう。",
- "overview" => "概要",
- "trends_and_forecast" => "傾向と予測",
- "history_and_lifetime" => "履歴と累計",
- "cost_per_day" => "1日あたりのコスト",
- "median_monthly_cost" => "月額サブスクリプション費用の中央値",
- "cheapest_subscription" => "最も安いサブスクリプション",
- "vs_last_month" => "前月比",
- "heaviest_month" => "今後最も高額な月",
- "months_over_budget" => "予算超過の月(今後12か月)",
- "manual_renewals" => "手動更新",
- "all_time_spend" => "累計支出(推定)",
- "oldest_subscription" => "最も古いサブスクリプション(年)",
- "average_subscription_age" => "サブスクリプションの平均利用年数(年)",
- "projected_cost" => "予測コスト(今後12か月)",
- "lifetime_spend" => "累計支出(上位10件、推定)",
- "billing_cycle_split" => "請求サイクル別の内訳",
- "currency_split" => "通貨別の内訳",
- "price_distribution" => "価格分布",
- "subscriptions_count" => "サブスクリプション数",
- "new_subscriptions_per_year" => "年間の新規サブスクリプション",
- "estimated_from_current_prices" => "現在の価格に基づく推定",
- "translate_categories" => "AIで翻訳",
- "week_starts_on_sunday" => "カレンダーの週を日曜日から開始",
- "list_view" => "リスト表示",
- "grid_view" => "グリッド表示",
- "oidc_oauth_enabled" => "OIDC/OAuthを有効にする",
+
"no_account_yet" => "アカウントをお持ちではありませんか?",
"already_have_account" => "すでにアカウントをお持ちですか?",
"google_search_info" => "Google画像検索の結果(SerpAPI経由)をロゴ検索の追加ソースとして加えます。無料のSerpAPIアカウントを作成し、APIキーをここに貼り付けてください。",
"monthly_searches_used" => "今月の使用済み検索回数",
"monthly_requests_used" => "今月の使用済みAPIリクエスト数",
+
+ // Default categories a new account is created with. The list also starts
+ // with "no_category", which is translated further up.
+ "category_entertainment" => "エンターテインメント",
+ "category_music" => "音楽",
+ "category_utilities" => "公共料金",
+ "category_food_and_beverages" => "食品・飲料",
+ "category_health_and_wellbeing" => "健康・ウェルビーイング",
+ "category_productivity" => "仕事効率化",
+ "category_banking" => "銀行",
+ "category_transport" => "交通",
+ "category_education" => "教育",
+ "category_insurance" => "保険",
+ "category_gaming" => "ゲーム",
+ "category_news_and_magazines" => "ニュース・雑誌",
+ "category_software" => "ソフトウェア",
+ "category_technology" => "テクノロジー",
+ "category_cloud_services" => "クラウドサービス",
+ "category_charity_and_donations" => "慈善・寄付",
+ // Default payment methods a new account is created with. Only the generic
+ // ones are translated; a brand is the same word in every language.
+ "payment_method_credit_card" => "クレジットカード",
+ "payment_method_bank_transfer" => "銀行振込",
+ "payment_method_direct_debit" => "口座振替",
+ "payment_method_money" => "現金",
];
diff --git a/includes/list_subscriptions.php b/includes/list_subscriptions.php
index ba8e8e9..9a3e7d5 100644
--- a/includes/list_subscriptions.php
+++ b/includes/list_subscriptions.php
@@ -88,6 +88,41 @@ function getPriceConverted($price, $currency, $database)
return wallos_convert_price($price, $currency, $database);
}
+/**
+ * The value a subscription is ranked by when the list is sorted by price: its
+ * price in the main currency, so AED 71.00 does not outrank GBP 55.00 just
+ * because 71 > 55 (#861). Follows the monthly-price display setting, so the
+ * order matches the figures that are shown.
+ */
+function getSortPrice($rawPrice, $currencyId, $mainCurrencyId, $cycle, $frequency, $settings, $database)
+{
+ $price = floatval($rawPrice);
+ if ($currencyId != $mainCurrencyId) {
+ $price = floatval(getPriceConverted($price, $currencyId, $database));
+ }
+ if (isset($settings['showMonthlyPrice']) && $settings['showMonthlyPrice'] === 'true') {
+ $price = getPricePerMonth($cycle, $frequency, $price);
+ }
+ return $price;
+}
+
+/**
+ * Orders the printable list by sort_price, highest first. usort() is stable,
+ * so ties keep the order the database gave them.
+ */
+function sortSubscriptionsByPrice(&$print, $disabledToBottom)
+{
+ usort($print, function ($a, $b) use ($disabledToBottom) {
+ if ($disabledToBottom) {
+ $byInactive = ($a['inactive'] ?? 0) <=> ($b['inactive'] ?? 0);
+ if ($byInactive !== 0) {
+ return $byInactive;
+ }
+ }
+ return ($b['sort_price'] ?? $b['price'] ?? 0) <=> ($a['sort_price'] ?? $a['price'] ?? 0);
+ });
+}
+
function formatPrice($price, $currencyCode, $currencies)
{
$formattedPrice = CurrencyFormatter::format($price, $currencyCode);
@@ -152,14 +187,8 @@ function formatDate($date, $lang = 'en')
function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n, $colorTheme, $imagePath, $disabledToBottom, $mobileNavigation, $showSubscriptionProgress, $currencies, $lang)
{
if ($sort === "price") {
- usort($subscriptions, function ($a, $b) {
- return $a['price'] < $b['price'] ? 1 : -1;
- });
- if ($disabledToBottom === 'true') {
- usort($subscriptions, function ($a, $b) {
- return $a['inactive'] - $b['inactive'];
- });
- }
+ // Ranked by the main-currency value (sort_price), not the raw number (#861).
+ sortSubscriptionsByPrice($subscriptions, $disabledToBottom === 'true');
}
// One-time purchases always go to the bottom regardless of sort order
@@ -185,7 +214,7 @@ function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n,
if ($subscription['category_id'] == 1) {
echo translate('no_category', $i18n);
} else {
- echo $categories[$subscription['category_id']]['name'];
+ echo $categories[$subscription['category_id'] ?? ""]['name'] ?? "";
}
?>
</div>
@@ -195,7 +224,7 @@ function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n,
if ($sort == "payer_user_id" && $subscription['payer_user_id'] != $currentPayerUserId) {
?>
<div class="subscription-list-title">
- <?= $members[$subscription['payer_user_id']]['name'] ?>
+ <?= $members[$subscription['payer_user_id'] ?? ""]['name'] ?? "" ?>
</div>
<?php
$currentPayerUserId = $subscription['payer_user_id'];
@@ -299,8 +328,10 @@ function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n,
</span>
<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'] ?>" />
+ <?php } ?>
</span>
<?php
$desktopMenuButtonClass = ""; {
diff --git a/includes/oidc/logout_url.php b/includes/oidc/logout_url.php
new file mode 100644
index 0000000..76f3b34
--- /dev/null
+++ b/includes/oidc/logout_url.php
@@ -0,0 +1,43 @@
+<?php
+
+/*
+ The RP-initiated logout URL (OpenID Connect RP-Initiated Logout 1.0).
+
+ Providers such as Keycloak refuse a logout request that does not identify
+ the session being ended: without id_token_hint they show an error page
+ ("Missing parameters: id_token_hint") instead of logging the user out
+ (#891). client_id is sent as well, which is what providers accept in place
+ of the hint when the ID token is no longer known.
+*/
+
+/**
+ * @param string $logoutUrl The provider's end-session endpoint.
+ * @param string $returnTo post_logout_redirect_uri, or '' for none.
+ * @param string|null $idToken The ID token issued at login, if known.
+ * @param string|null $clientId The client id Wallos is registered with.
+ * @return string
+ */
+function oidc_build_logout_url($logoutUrl, $returnTo, $idToken = null, $clientId = null)
+{
+ $params = [];
+
+ if (is_string($idToken) && $idToken !== '') {
+ $params['id_token_hint'] = $idToken;
+ }
+
+ if (is_string($clientId) && $clientId !== '') {
+ $params['client_id'] = $clientId;
+ }
+
+ if (is_string($returnTo) && $returnTo !== '') {
+ $params['post_logout_redirect_uri'] = $returnTo;
+ }
+
+ if (empty($params)) {
+ return $logoutUrl;
+ }
+
+ $separator = strpos($logoutUrl, '?') === false ? '?' : '&';
+
+ return $logoutUrl . $separator . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
+}
diff --git a/includes/oidc/oidc_login.php b/includes/oidc/oidc_login.php
index 82a4662..f4dcdc3 100644
--- a/includes/oidc/oidc_login.php
+++ b/includes/oidc/oidc_login.php
@@ -16,6 +16,11 @@ $_SESSION['main_currency'] = $main_currency;
$_SESSION['userId'] = $userId;
$_SESSION['from_oidc'] = true; // Indicate this session is from OIDC login
+// Kept for RP-initiated logout, which providers like Keycloak require (#891).
+if (isset($tokenData['id_token']) && is_string($tokenData['id_token'])) {
+ $_SESSION['oidc_id_token'] = $tokenData['id_token'];
+}
+
$cookieExpire = time() + (86400 * 30); // 30 days
// generate remember token
diff --git a/includes/oidc/session_persist.php b/includes/oidc/session_persist.php
new file mode 100644
index 0000000..f52feac
--- /dev/null
+++ b/includes/oidc/session_persist.php
@@ -0,0 +1,36 @@
+<?php
+
+/**
+ * Writes the session to disk now, and reopens it.
+ *
+ * The OIDC callback consumes the state and then spends a second or two at the
+ * provider's token endpoint. PHP writes the session at the end of the request,
+ * and the sign-in calls session_regenerate_id(true) before that, which deletes
+ * the file the consumption would have been written to.
+ *
+ * So a second request carrying the same callback - which is what a browser on
+ * an unstable connection produces - waits on the session lock, is handed the
+ * state as it stood before it was consumed, and redeems the same authorization
+ * code again. An authorization code is single-use, so the provider refuses the
+ * second attempt and the person is shown a failure for a login that had in fact
+ * succeeded (#1239).
+ *
+ * @return bool whether the session was written
+ */
+function oidc_persist_session()
+{
+ if (session_status() !== PHP_SESSION_ACTIVE) {
+ return false;
+ }
+
+ $id = session_id();
+
+ session_write_close();
+
+ // Same id, so the client keeps the session it already has. Reopened
+ // because everything after this point still writes to it.
+ session_id($id);
+ session_start();
+
+ return true;
+}
diff --git a/includes/version.php b/includes/version.php
index 3c718cf..875982e 100644
--- a/includes/version.php
+++ b/includes/version.php
@@ -1,3 +1,3 @@
<?php
-$version = "v5.8.3";
+$version = "v5.8.4";
?>
diff --git a/includes/webhook_headers.php b/includes/webhook_headers.php
new file mode 100644
index 0000000..bebae7a
--- /dev/null
+++ b/includes/webhook_headers.php
@@ -0,0 +1,113 @@
+<?php
+
+/*
+ The custom headers a user stored for a webhook or an ntfy topic, as request
+ header lines.
+
+ One field, five readers, and they did not agree. sendnotifications.php read
+ it as JSON and handed the result straight to cURL; sendcancellationnotifications.php
+ read the same field as newline-separated text; the two ntfy blocks decoded it
+ as JSON and mapped key => value into "Key: value"; the test button decoded it
+ and only used the result when it was non-empty. So the same stored value
+ behaved differently depending on which job happened to read it, and two of
+ the readers crashed on a value the others merely ignored.
+
+ What the readers agree on once the disagreement is removed: the field holds
+ JSON, because that is what the settings page's own test button has always
+ assumed and what three of the four jobs did. A JSON object is the shape the
+ ntfy blocks documented by example - {"Authorization": "Bearer ..."} - and a
+ JSON array of complete header lines is what a value handed straight to cURL
+ had to be. Both are accepted here; anything else yields no headers rather
+ than ending the run that was reading it.
+*/
+
+/**
+ * Turns a stored headers value into request header lines.
+ *
+ * Nothing decodable produces an empty list. That matters more than it looks:
+ * on PHP 8 curl_setopt(CURLOPT_HTTPHEADER) with anything but an array is a
+ * TypeError, and in a cron job a TypeError is a fatal that ends the whole run
+ * - every channel after it and every account after this one included. A
+ * notification nobody receives because a header field holds a typo is a bad
+ * trade for a feature nobody set.
+ *
+ * @param mixed $stored The value as it came out of the database or a form.
+ * @return string[] Complete "Name: value" lines, possibly empty.
+ */
+function webhook_custom_headers($stored)
+{
+ if (!is_string($stored) || trim($stored) === '') {
+ return [];
+ }
+
+ $decoded = json_decode($stored, true);
+
+ if (!is_array($decoded)) {
+ // Not JSON: sendcancellationnotifications.php used to read this field
+ // as one "Name: value" per line, so existing values may be stored
+ // that way. Keep them working.
+ $decoded = [];
+ foreach (preg_split("/\r\n|\n|\r/", $stored) as $line) {
+ $line = trim($line);
+ if ($line !== '' && preg_match('/^[A-Za-z0-9!#$%&\'*+.^_`|~-]+:/', $line)) {
+ $decoded[] = $line;
+ }
+ }
+ }
+
+ $headers = [];
+
+ foreach ($decoded as $key => $value) {
+ // Anything that cannot be written as one header line is skipped rather
+ // than being stringified into something a push service would reject.
+ if (is_array($value) || is_object($value) || $value === null) {
+ continue;
+ }
+
+ if (is_int($key)) {
+ // A list: the entries are already complete header lines.
+ $line = trim((string) $value);
+ } else {
+ $line = trim((string) $key) . ': ' . trim((string) $value);
+ }
+
+ // A header line is one line: never let a value smuggle in another.
+ $line = preg_replace('/[\r\n]+/', ' ', $line);
+
+ if ($line !== '' && strpos($line, ':') !== false) {
+ $headers[] = $line;
+ }
+ }
+
+ return $headers;
+}
+
+/**
+ * Adds "Content-Type: application/json" when the payload is JSON and the user
+ * did not set a Content-Type of their own (#990).
+ *
+ * Without it cURL announces application/x-www-form-urlencoded for a string
+ * body, and a receiver such as n8n parses the whole JSON document as the name
+ * of a single form field.
+ *
+ * @param string[] $headers Header lines as returned by webhook_custom_headers().
+ * @param mixed $payload The request body.
+ * @return string[]
+ */
+function webhook_headers_with_content_type($headers, $payload)
+{
+ foreach ($headers as $line) {
+ if (stripos($line, 'content-type:') === 0) {
+ return $headers;
+ }
+ }
+
+ if (is_string($payload) && trim($payload) !== '') {
+ $decoded = json_decode($payload);
+ if (json_last_error() === JSON_ERROR_NONE && (is_array($decoded) || is_object($decoded))) {
+ $headers[] = 'Content-Type: application/json';
+ }
+ }
+
+ return $headers;
+}
diff --git a/includes/webpush_helper.php b/includes/webpush_helper.php
index c1a53b3..6015129 100644
--- a/includes/webpush_helper.php
+++ b/includes/webpush_helper.php
@@ -341,10 +341,50 @@ function webpush_get_vapid_keys($db)
return false;
}
- $stmt = $db->prepare('UPDATE admin SET vapid_public_key = :public, vapid_private_key = :private');
+ return webpush_store_vapid_keys($db, $keys);
+}
+
+/**
+ * Persists a freshly generated keypair, unless the installation has one by
+ * now, and answers with whichever pair is stored afterwards.
+ *
+ * The write has to be conditional, and the row has to be read back, because a
+ * push subscription is bound to the applicationServerKey the browser saw when
+ * it subscribed. Two first uses at once - the settings page of one household
+ * member and the notification cron, say - each find the columns empty, each
+ * generate a pair, and with an unconditional UPDATE the second write wins.
+ * Every device that had already subscribed with the first key is then answered
+ * 403 by its push service from that moment on, and 403 is not 404/410, so the
+ * cron prunes nothing, the settings page still lists the device, and the
+ * notifications simply stop with nothing anywhere to say why.
+ *
+ * @param SQLite3 $db
+ * @param array{public: string, private_pem: string} $keys
+ * @return array{public: string, private_pem: string}|false
+ */
+function webpush_store_vapid_keys($db, $keys)
+{
+ $stmt = $db->prepare("UPDATE admin SET vapid_public_key = :public, vapid_private_key = :private
+ WHERE vapid_public_key IS NULL OR vapid_public_key = ''
+ OR vapid_private_key IS NULL OR vapid_private_key = ''");
+ if ($stmt === false) {
+ return false;
+ }
+
$stmt->bindValue(':public', $keys['public'], SQLITE3_TEXT);
$stmt->bindValue(':private', $keys['private_pem'], SQLITE3_TEXT);
- $stmt->execute();
+
+ if ($stmt->execute() === false) {
+ return false;
+ }
+
+ // Read back rather than returning what was generated: when the UPDATE
+ // matched nothing, the pair that matters is the one already in the row.
+ $row = $db->querySingle('SELECT vapid_public_key, vapid_private_key FROM admin LIMIT 1', true);
+
+ if ($row !== false && !empty($row['vapid_public_key']) && !empty($row['vapid_private_key'])) {
+ return ['public' => $row['vapid_public_key'], 'private_pem' => $row['vapid_private_key']];
+ }
return $keys;
}
diff --git a/logout.php b/logout.php
index e8475bd..d9738a7 100644
--- a/logout.php
+++ b/logout.php
@@ -1,6 +1,7 @@
<?php
require_once 'includes/connect.php';
require_once 'includes/oidc_settings.php';
+require_once 'includes/oidc/logout_url.php';
$secondsInMonth = 30 * 24 * 60 * 60;
if (session_status() === PHP_SESSION_NONE) {
session_set_cookie_params([
@@ -19,6 +20,7 @@ if (isset($_SESSION['from_oidc']) && $_SESSION['from_oidc'] === true) {
$oidcConfiguration = wallos_get_effective_oidc_configuration($db);
$oidcSettings = $oidcConfiguration['settings'];
$logoutUrl = $oidcSettings['logout_url'] ?? '';
+ $oidcIdToken = $_SESSION['oidc_id_token'] ?? null;
}
// get token from cookie to remove from DB
@@ -56,8 +58,12 @@ setcookie('wallos_login', '', $cookieExpire);
$db->close();
if ($logoutOIDC && !empty($logoutUrl)) {
- $returnTo = urlencode($oidcSettings['redirect_url'] ?? '');
- header("Location: $logoutUrl?post_logout_redirect_uri=$returnTo");
+ header('Location: ' . oidc_build_logout_url(
+ $logoutUrl,
+ $oidcSettings['redirect_url'] ?? '',
+ $oidcIdToken,
+ $oidcSettings['client_id'] ?? ''
+ ));
exit();
}
diff --git a/scripts/i18n/ja.js b/scripts/i18n/ja.js
index 040d1c2..1ad5f26 100644
--- a/scripts/i18n/ja.js
+++ b/scripts/i18n/ja.js
@@ -18,7 +18,7 @@ let i18n = {
save_member: "世帯員の保存",
delete_member: "世帯員の削除",
failed_remove_member: "世帯員の削除に失敗",
- failed_save_member: "世帯員の削除に失敗",
+ failed_save_member: "世帯員の保存に失敗",
failed_add_category: "カテゴリの追加に失敗",
category: "カテゴリ",
save_category: "カテゴリの保存",
@@ -46,10 +46,10 @@ let i18n = {
payment_method: "支払い方法",
notes: "メモ",
export: "エクスポート",
+ no_results_found: "結果が見つかりません",
invalid_budget: "予算は0以上の数値である必要があります",
invalid_budget_period: "選択した予算期間が無効です",
invalid_budget_anchor_date: "基準日は有効な日付である必要があります",
- no_results_found: "結果が見つかりません",
push_not_supported: "このブラウザではプッシュ通知に対応していません。",
push_permission_denied: "通知の許可が得られませんでした。",
delete: "削除",
diff --git a/scripts/profile.js b/scripts/profile.js
index bfe84c6..fce0a81 100644
--- a/scripts/profile.js
+++ b/scripts/profile.js
@@ -1,392 +1,398 @@
-document.addEventListener('DOMContentLoaded', function () {
-
- document.getElementById("userForm").addEventListener("submit", function (event) {
- event.preventDefault();
- const submitButton = document.getElementById("userSubmit");
- submitButton.disabled = true;
-
- const formData = new FormData(event.target);
- formData.append("action", "save");
-
- fetch("endpoints/user/save_user.php", {
- method: "POST",
- headers: {
- "X-CSRF-Token": window.csrfToken,
- },
- body: formData,
- })
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- document.getElementById("avatar").src = document.getElementById("avatarImg").src;
- const newUsername = document.getElementById("username").value;
- document.getElementById("user").textContent = newUsername;
- document.getElementById("profile_pic").value = "";
- showSuccessMessage(data.message);
-
- if (data.reload) {
- location.reload();
- }
- } else {
- showErrorMessage(data.message || translate("failed_save_user"));
- }
- })
- .catch(error => {
- console.error(error);
- showErrorMessage(translate("unknown_error"));
- })
- .finally(() => {
- submitButton.disabled = false;
- });
- });
-
-});
-
-function toggleAvatarSelect() {
- var avatarSelect = document.getElementById("avatarSelect");
- if (avatarSelect.classList.contains("is-open")) {
- avatarSelect.classList.remove("is-open");
- } else {
- avatarSelect.classList.add("is-open");
- }
-}
-
-function closeAvatarSelect() {
- var avatarSelect = document.getElementById("avatarSelect");
- avatarSelect.classList.remove("is-open");
-}
-
-document.querySelectorAll('.avatar-option').forEach((avatar) => {
- avatar.addEventListener("click", () => {
- changeAvatar(avatar.src);
- document.getElementById('avatarUser').value = avatar.getAttribute('data-src');
- closeAvatarSelect();
- })
-});
-
-function changeAvatar(src) {
- document.getElementById("avatarImg").src = src;
-}
-
-function successfulUpload(field, msg) {
- var reader = new FileReader();
-
- if (field.files.length === 0) {
- return;
- }
-
- if (!['image/jpeg', 'image/png', 'image/gif', 'image/jtif', 'image/webp'].includes(field.files[0]['type'])) {
- showErrorMessage(msg);
- return;
- }
-
- reader.onload = function () {
- changeAvatar(reader.result);
- };
-
- reader.readAsDataURL(field.files[0]);
- closeAvatarSelect();
-}
-
-function deleteAvatar(path) {
- fetch('endpoints/user/delete_avatar.php', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- "X-CSRF-Token": window.csrfToken,
- },
- body: JSON.stringify({ avatar: path }),
- })
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- var avatarContainer = document.querySelector(`.avatar-container[data-src="${path}"]`);
- if (avatarContainer) {
- avatarContainer.remove();
- }
- showSuccessMessage();
- } else {
- showErrorMessage(data.message || "");
- }
- })
- .catch((error) => {
- console.error('Error:', error);
- });
-}
-
-function enableTotp() {
- const totpSecret = document.querySelector("#totp-secret");
- const totpSecretCode = document.querySelector("#totp-secret-code");
- const qrCode = document.getElementById("totp-qr-code");
- totpSecret.value = "";
- totpSecretCode.textContent = "";
- qrCode.innerHTML = "";
-
- fetch("endpoints/user/enable_totp.php", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-CSRF-Token": window.csrfToken,
- },
- body: JSON.stringify({ action: "generate" }),
- })
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- totpSecret.value = data.secret;
- totpSecretCode.textContent = data.secret;
- new QRCode(qrCode, data.qrCodeUrl);
- openTotpPopup();
- } else {
- showErrorMessage(data.message);
- }
- })
- .catch(error => {
- console.error(error);
- showErrorMessage(translate("unknown_error"));
- });
-}
-
-function openTotpPopup() {
- const enableTotpButton = document.getElementById('enableTotp');
- enableTotpButton.disabled = true;
-
- const totpPopup = document.getElementById('totp-popup');
- totpPopup.classList.add('is-open');
-}
-
-function closeTotpPopup() {
- const enableTotpButton = document.getElementById('enableTotp');
- enableTotpButton.disabled = false;
- const totpPopup = document.getElementById('totp-popup');
- totpPopup.classList.remove('is-open');
-
- const totpBackupCodes = document.getElementById('totp-backup-codes');
- if (!totpBackupCodes.classList.contains('hide')) {
- location.reload();
- }
-}
-
-function submitTotp() {
- const totpCode = document.getElementById('totp').value;
- const totpSecret = document.getElementById('totp-secret').value;
-
- fetch('endpoints/user/enable_totp.php', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- "X-CSRF-Token": window.csrfToken,
- },
- body: JSON.stringify({ totpCode: totpCode, totpSecret: totpSecret, action: 'verify' }),
- })
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- showSuccessMessage(data.message);
- const backupCodes = data.backupCodes;
- const backupCodesList = document.getElementById('backup-codes');
- backupCodesList.innerHTML = '';
- backupCodes.forEach(code => {
- const li = document.createElement('li');
- li.textContent = code;
- backupCodesList.appendChild(li);
- });
-
- const totpSetup = document.getElementById('totp-setup');
- const totpBackupCodes = document.getElementById('totp-backup-codes');
-
- totpSetup.classList.add('hide');
- totpBackupCodes.classList.remove('hide');
- } else {
- showErrorMessage(data.message);
- }
- })
- .catch(error => {
- showErrorMessage(error);
- console.log(error);
- });
-}
-
-function copyBackupCodes() {
- const backupCodes = document.querySelectorAll('#backup-codes li');
- const codes = Array.from(backupCodes).map(code => code.textContent).join('\n');
-
- navigator.clipboard.writeText(codes)
- .then(() => {
- showSuccessMessage(translate('copied_to_clipboard'));
- })
- .catch(() => {
- showErrorMessage(translate('unknown_error'));
- });
-}
-
-function downloadBackupCodes() {
- const backupCodes = document.querySelectorAll('#backup-codes li');
- const codes = Array.from(backupCodes).map(code => code.textContent).join('\n');
- const element = document.createElement('a');
-
- element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(codes));
- element.setAttribute('download', 'wallos-backup-codes.txt');
- element.style.display = 'none';
- document.body.appendChild(element);
-
- element.click();
-
- document.body.removeChild(element);
-}
-
-function closeTotpDisablePopup() {
- const totpPopup = document.getElementById('totp-disable-popup');
- totpPopup.classList.remove('is-open');
-}
-
-function disableTotp() {
- const totpPopup = document.getElementById('totp-disable-popup');
- totpPopup.classList.add('is-open');
-}
-
-function submitDisableTotp() {
- const totpCode = document.getElementById('totp-disable').value;
-
- fetch('endpoints/user/disable_totp.php', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- "X-CSRF-Token": window.csrfToken,
- },
- body: JSON.stringify({ totpCode: totpCode }),
- })
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- showSuccessMessage(data.message);
- if (data.reload) {
- location.reload();
- }
- } else {
- showErrorMessage(data.message);
- }
- })
- .catch(error => {
- showErrorMessage(error);
- });
-}
-
-function regenerateApiKey() {
- const regenerateButton = document.getElementById("regenerateApiKey");
- regenerateButton.disabled = true;
-
- fetch("endpoints/user/regenerateapikey.php", {
- method: "POST",
- headers: {
- "X-CSRF-Token": window.csrfToken,
- },
- })
- .then(response => response.json())
- .then(data => {
- regenerateButton.disabled = false;
- if (data.success) {
- const newApiKey = data.apiKey;
- document.getElementById("apikey").value = newApiKey;
- showSuccessMessage(data.message);
- } else {
- showErrorMessage(data.message || translate("failed_regenerate_api_key"));
- }
- })
- .catch(error => {
- console.error(error);
- regenerateButton.disabled = false;
- showErrorMessage(translate("unknown_error"));
- });
-}
-
-
-function exportAsJson() {
- fetch("endpoints/subscriptions/export.php")
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- const subscriptions = JSON.stringify(data.subscriptions);
- const element = document.createElement('a');
- element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(subscriptions));
- element.setAttribute('download', 'subscriptions.json');
- element.style.display = 'none';
- document.body.appendChild(element);
- element.click();
- document.body.removeChild(element);
- } else {
- showErrorMessage(data.message);
- }
- })
- .catch(error => {
- console.log(error);
- showErrorMessage(translate('unknown_error'));
- });
-}
-
-function csvField(value) {
- const stringValue = String(value ?? '');
- // Notes can now be multi-paragraph Markdown, so a field with an embedded
- // newline is common, not an edge case - quote (RFC 4180) whenever a
- // comma, quote, or newline would otherwise corrupt the row structure.
- if (/[",\r\n]/.test(stringValue)) {
- return '"' + stringValue.replace(/"/g, '""') + '"';
- }
- return stringValue;
-}
-
-function exportAsCsv() {
- fetch("endpoints/subscriptions/export.php")
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- const subscriptions = data.subscriptions;
- const header = Object.keys(subscriptions[0]).map(csvField).join(',');
- const csv = subscriptions.map(subscription => Object.values(subscription).map(csvField).join(',')).join('\n');
- const csvWithHeader = header + '\n' + csv;
- const element = document.createElement('a');
- element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csvWithHeader));
- element.setAttribute('download', 'subscriptions.csv');
- element.style.display = 'none';
- document.body.appendChild(element);
- element.click();
- document.body.removeChild(element);
- } else {
- showErrorMessage(data.message);
- }
- })
- .catch(error => {
- showErrorMessage(translate('unknown_error'));
- });
-}
-
-function deleteAccount(userId) {
- if (!confirm(translate('delete_account_confirmation'))) {
- return;
- }
-
- if (!confirm(translate('this_will_delete_all_data'))) {
- return;
- }
-
- fetch('endpoints/settings/deleteaccount.php', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- "X-CSRF-Token": window.csrfToken,
- },
- body: JSON.stringify({ userId: userId }),
- })
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- window.location.href = 'logout.php';
- } else {
- showErrorMessage(data.message);
- }
- })
- .catch((error) => {
- showErrorMessage(translate('unknown_error'));
- });
-}
-
+document.addEventListener('DOMContentLoaded', function () {
+
+ document.getElementById("userForm").addEventListener("submit", function (event) {
+ event.preventDefault();
+ const submitButton = document.getElementById("userSubmit");
+ submitButton.disabled = true;
+
+ const formData = new FormData(event.target);
+ formData.append("action", "save");
+
+ fetch("endpoints/user/save_user.php", {
+ method: "POST",
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: formData,
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ document.getElementById("avatar").src = document.getElementById("avatarImg").src;
+ const newUsername = document.getElementById("username").value;
+ document.getElementById("user").textContent = newUsername;
+ document.getElementById("profile_pic").value = "";
+ showSuccessMessage(data.message);
+
+ if (data.reload) {
+ location.reload();
+ }
+ } else {
+ showErrorMessage(data.message || translate("failed_save_user"));
+ }
+ })
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ })
+ .finally(() => {
+ submitButton.disabled = false;
+ });
+ });
+
+});
+
+function toggleAvatarSelect() {
+ var avatarSelect = document.getElementById("avatarSelect");
+ if (avatarSelect.classList.contains("is-open")) {
+ avatarSelect.classList.remove("is-open");
+ } else {
+ avatarSelect.classList.add("is-open");
+ }
+}
+
+function closeAvatarSelect() {
+ var avatarSelect = document.getElementById("avatarSelect");
+ avatarSelect.classList.remove("is-open");
+}
+
+document.querySelectorAll('.avatar-option').forEach((avatar) => {
+ avatar.addEventListener("click", () => {
+ changeAvatar(avatar.src);
+ document.getElementById('avatarUser').value = avatar.getAttribute('data-src');
+ closeAvatarSelect();
+ })
+});
+
+function changeAvatar(src) {
+ document.getElementById("avatarImg").src = src;
+}
+
+function successfulUpload(field, msg) {
+ var reader = new FileReader();
+
+ if (field.files.length === 0) {
+ return;
+ }
+
+ if (!['image/jpeg', 'image/png', 'image/gif', 'image/jtif', 'image/webp'].includes(field.files[0]['type'])) {
+ showErrorMessage(msg);
+ return;
+ }
+
+ reader.onload = function () {
+ changeAvatar(reader.result);
+ };
+
+ reader.readAsDataURL(field.files[0]);
+ closeAvatarSelect();
+}
+
+function deleteAvatar(path) {
+ fetch('endpoints/user/delete_avatar.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ avatar: path }),
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ var avatarContainer = document.querySelector(`.avatar-container[data-src="${path}"]`);
+ if (avatarContainer) {
+ avatarContainer.remove();
+ }
+ showSuccessMessage();
+ } else {
+ showErrorMessage(data.message || "");
+ }
+ })
+ .catch((error) => {
+ console.error('Error:', error);
+ });
+}
+
+function enableTotp() {
+ const totpSecret = document.querySelector("#totp-secret");
+ const totpSecretCode = document.querySelector("#totp-secret-code");
+ const qrCode = document.getElementById("totp-qr-code");
+ totpSecret.value = "";
+ totpSecretCode.textContent = "";
+ qrCode.innerHTML = "";
+
+ fetch("endpoints/user/enable_totp.php", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ action: "generate" }),
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ totpSecret.value = data.secret;
+ totpSecretCode.textContent = data.secret;
+ new QRCode(qrCode, data.qrCodeUrl);
+ openTotpPopup();
+ } else {
+ showErrorMessage(data.message);
+ }
+ })
+ .catch(error => {
+ console.error(error);
+ showErrorMessage(translate("unknown_error"));
+ });
+}
+
+function openTotpPopup() {
+ const enableTotpButton = document.getElementById('enableTotp');
+ enableTotpButton.disabled = true;
+
+ const totpPopup = document.getElementById('totp-popup');
+ totpPopup.classList.add('is-open');
+}
+
+function closeTotpPopup() {
+ const enableTotpButton = document.getElementById('enableTotp');
+ enableTotpButton.disabled = false;
+ const totpPopup = document.getElementById('totp-popup');
+ totpPopup.classList.remove('is-open');
+
+ const totpBackupCodes = document.getElementById('totp-backup-codes');
+ if (!totpBackupCodes.classList.contains('hide')) {
+ location.reload();
+ }
+}
+
+function submitTotp() {
+ const totpCode = document.getElementById('totp').value;
+ const totpSecret = document.getElementById('totp-secret').value;
+
+ fetch('endpoints/user/enable_totp.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ totpCode: totpCode, totpSecret: totpSecret, action: 'verify' }),
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ showSuccessMessage(data.message);
+ const backupCodes = data.backupCodes;
+ const backupCodesList = document.getElementById('backup-codes');
+ backupCodesList.innerHTML = '';
+ backupCodes.forEach(code => {
+ const li = document.createElement('li');
+ li.textContent = code;
+ backupCodesList.appendChild(li);
+ });
+
+ const totpSetup = document.getElementById('totp-setup');
+ const totpBackupCodes = document.getElementById('totp-backup-codes');
+
+ totpSetup.classList.add('hide');
+ totpBackupCodes.classList.remove('hide');
+ } else {
+ showErrorMessage(data.message);
+ }
+ })
+ .catch(error => {
+ showErrorMessage(error);
+ console.log(error);
+ });
+}
+
+function copyBackupCodes() {
+ const backupCodes = document.querySelectorAll('#backup-codes li');
+ const codes = Array.from(backupCodes).map(code => code.textContent).join('\n');
+
+ navigator.clipboard.writeText(codes)
+ .then(() => {
+ showSuccessMessage(translate('copied_to_clipboard'));
+ })
+ .catch(() => {
+ showErrorMessage(translate('unknown_error'));
+ });
+}
+
+function downloadBackupCodes() {
+ const backupCodes = document.querySelectorAll('#backup-codes li');
+ const codes = Array.from(backupCodes).map(code => code.textContent).join('\n');
+ const element = document.createElement('a');
+
+ element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(codes));
+ element.setAttribute('download', 'wallos-backup-codes.txt');
+ element.style.display = 'none';
+ document.body.appendChild(element);
+
+ element.click();
+
+ document.body.removeChild(element);
+}
+
+function closeTotpDisablePopup() {
+ const totpPopup = document.getElementById('totp-disable-popup');
+ totpPopup.classList.remove('is-open');
+}
+
+function disableTotp() {
+ const totpPopup = document.getElementById('totp-disable-popup');
+ totpPopup.classList.add('is-open');
+}
+
+function submitDisableTotp() {
+ const totpCode = document.getElementById('totp-disable').value;
+
+ fetch('endpoints/user/disable_totp.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ totpCode: totpCode }),
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ showSuccessMessage(data.message);
+ if (data.reload) {
+ location.reload();
+ }
+ } else {
+ showErrorMessage(data.message);
+ }
+ })
+ .catch(error => {
+ showErrorMessage(error);
+ });
+}
+
+function regenerateApiKey() {
+ const regenerateButton = document.getElementById("regenerateApiKey");
+ regenerateButton.disabled = true;
+
+ fetch("endpoints/user/regenerateapikey.php", {
+ method: "POST",
+ headers: {
+ "X-CSRF-Token": window.csrfToken,
+ },
+ })
+ .then(response => response.json())
+ .then(data => {
+ regenerateButton.disabled = false;
+ if (data.success) {
+ const newApiKey = data.apiKey;
+ document.getElementById("apikey").value = newApiKey;
+ showSuccessMessage(data.message);
+ } else {
+ showErrorMessage(data.message || translate("failed_regenerate_api_key"));
+ }
+ })
+ .catch(error => {
+ console.error(error);
+ regenerateButton.disabled = false;
+ showErrorMessage(translate("unknown_error"));
+ });
+}
+
+
+function exportAsJson() {
+ fetch("endpoints/subscriptions/export.php")
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ const subscriptions = JSON.stringify(data.subscriptions);
+ const element = document.createElement('a');
+ element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(subscriptions));
+ element.setAttribute('download', 'subscriptions.json');
+ element.style.display = 'none';
+ document.body.appendChild(element);
+ element.click();
+ document.body.removeChild(element);
+ } else {
+ showErrorMessage(data.message);
+ }
+ })
+ .catch(error => {
+ console.log(error);
+ showErrorMessage(translate('unknown_error'));
+ });
+}
+
+function csvField(value) {
+ const stringValue = String(value ?? '');
+ // Notes can now be multi-paragraph Markdown, so a field with an embedded
+ // newline is common, not an edge case - quote (RFC 4180) whenever a
+ // comma, quote, or newline would otherwise corrupt the row structure.
+ if (/[",\r\n]/.test(stringValue)) {
+ return '"' + stringValue.replace(/"/g, '""') + '"';
+ }
+ return stringValue;
+}
+
+// The BOM tells Excel the file is UTF-8; without it, "£" is read as Windows-1252
+// and shows up as "£" (#863).
+function csvDataUri(csv) {
+ return 'data:text/csv;charset=utf-8,' + encodeURIComponent('\uFEFF' + csv);
+}
+
+function exportAsCsv() {
+ fetch("endpoints/subscriptions/export.php")
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ const subscriptions = data.subscriptions;
+ const header = Object.keys(subscriptions[0]).map(csvField).join(',');
+ const csv = subscriptions.map(subscription => Object.values(subscription).map(csvField).join(',')).join('\n');
+ const csvWithHeader = header + '\n' + csv;
+ const element = document.createElement('a');
+ element.setAttribute('href', csvDataUri(csvWithHeader));
+ element.setAttribute('download', 'subscriptions.csv');
+ element.style.display = 'none';
+ document.body.appendChild(element);
+ element.click();
+ document.body.removeChild(element);
+ } else {
+ showErrorMessage(data.message);
+ }
+ })
+ .catch(error => {
+ showErrorMessage(translate('unknown_error'));
+ });
+}
+
+function deleteAccount(userId) {
+ if (!confirm(translate('delete_account_confirmation'))) {
+ return;
+ }
+
+ if (!confirm(translate('this_will_delete_all_data'))) {
+ return;
+ }
+
+ fetch('endpoints/settings/deleteaccount.php', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ "X-CSRF-Token": window.csrfToken,
+ },
+ body: JSON.stringify({ userId: userId }),
+ })
+ .then(response => response.json())
+ .then(data => {
+ if (data.success) {
+ window.location.href = 'logout.php';
+ } else {
+ showErrorMessage(data.message);
+ }
+ })
+ .catch((error) => {
+ showErrorMessage(translate('unknown_error'));
+ });
+}
+
diff --git a/scripts/theme.js b/scripts/theme.js
index 7c09d01..ab4720a 100644
--- a/scripts/theme.js
+++ b/scripts/theme.js
@@ -66,19 +66,22 @@ function setDarkTheme(theme) {
if (theme == 0) {
darkThemeCss.disabled = true;
- document.body.className = 'light';
+ document.body.classList.remove('dark', 'automatic');
+ document.body.classList.add('light');
lightThemeButton.classList.add('selected');
}
if (theme == 1) {
darkThemeCss.disabled = false;
- document.body.className = 'dark';
+ document.body.classList.remove('light', 'automatic');
+ document.body.classList.add('dark');
darkThemeButton.classList.add('selected');
}
if (theme == 2) {
darkThemeCss.disabled = !prefersDarkMode;
- document.body.className = prefersDarkMode ? 'dark' : 'light';
+ document.body.classList.remove('light', 'dark', 'automatic');
+ document.body.classList.add(prefersDarkMode ? 'dark' : 'light');
automaticThemeButton.classList.add('selected');
document.cookie = `inUseTheme=${prefersDarkMode ? 'dark' : 'light'}; expires=Fri, 31 Dec 9999 23:59:59 GMT; SameSite=Lax`;
}
diff --git a/subscriptions.php b/subscriptions.php
index 2a66892..87ea31a 100644
--- a/subscriptions.php
+++ b/subscriptions.php
@@ -127,22 +127,28 @@ if ($result) {
foreach ($subscriptions as $subscription) {
$memberId = $subscription['payer_user_id'];
- $members[$memberId]['count']++;
+ if (isset($members[$memberId ?? ""])) {
+ $members[$memberId ?? ""]['count']++;
+ }
$categoryId = $subscription['category_id'];
- $categories[$categoryId]['count']++;
+ if (isset($categories[$categoryId ?? ""])) {
+ $categories[$categoryId ?? ""]['count']++;
+ }
$paymentMethodId = $subscription['payment_method_id'];
- $payment_methods[$paymentMethodId]['count']++;
+ if (isset($payment_methods[$paymentMethodId ?? ""])) {
+ $payment_methods[$paymentMethodId ?? ""]['count']++;
+ }
}
if ($sortOrder == "category_id") {
usort($subscriptions, function ($a, $b) use ($categories) {
- return $categories[$a['category_id']]['order'] - $categories[$b['category_id']]['order'];
+ return ($categories[$a['category_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($categories[$b['category_id'] ?? ""]['order'] ?? PHP_INT_MAX);
});
}
if ($sortOrder == "payment_method_id") {
usort($subscriptions, function ($a, $b) use ($payment_methods) {
- return $payment_methods[$a['payment_method_id']]['order'] - $payment_methods[$b['payment_method_id']]['order'];
+ return ($payment_methods[$a['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX) <=> ($payment_methods[$b['payment_method_id'] ?? ""]['order'] ?? PHP_INT_MAX);
});
}
@@ -234,13 +240,15 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip
$next_payment_timestamp = strtotime($subscription['next_payment']);
$formatted_date = $formatter->format($next_payment_timestamp);
$print[$id]['next_payment'] = $formatted_date;
- $paymentIconFolder = (strpos($payment_methods[$paymentMethodId]['icon'], 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";
- $print[$id]['payment_method_icon'] = $paymentIconFolder . $payment_methods[$paymentMethodId]['icon'];
- $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId]['name'];
+ $paymentIcon = $payment_methods[$paymentMethodId ?? ""]['icon'] ?? "";
+ $paymentIconFolder = (strpos($paymentIcon, 'images/uploads/icons/') !== false) ? "" : "images/uploads/logos/";
+ $print[$id]['payment_method_icon'] = $paymentIcon === "" ? "" : $paymentIconFolder . $paymentIcon;
+ $print[$id]['payment_method_name'] = $payment_methods[$paymentMethodId ?? ""]['name'] ?? "";
$print[$id]['payment_method_id'] = $paymentMethodId;
$print[$id]['category_id'] = $subscription['category_id'];
$print[$id]['payer_user_id'] = $subscription['payer_user_id'];
$print[$id]['price'] = floatval($subscription['price']);
+ $print[$id]['sort_price'] = getSortPrice($subscription['price'], $subscription['currency_id'], $mainCurrencyId, $cycle, $frequency, $settings, $db);
$print[$id]['progress'] = getSubscriptionProgress($cycle, $frequency, $subscription['next_payment']);
$print[$id]['inactive'] = $subscription['inactive'];
$print[$id]['url'] = $subscription['url'];
diff --git a/tests/cases/backup_cleanup_test.php b/tests/cases/backup_cleanup_test.php
new file mode 100644
index 0000000..8659cd1
--- /dev/null
+++ b/tests/cases/backup_cleanup_test.php
@@ -0,0 +1,47 @@
+<?php
+/*
+ The backup archive is removed even when the download is not finished.
+
+ endpoints/db/backup.php builds a zip of the database and every uploaded file
+ in the system temp directory, streams it to the admin who asked, and deletes
+ it on the line after readfile(). A download the browser abandons - a closed
+ tab, a lost connection, a proxy timing out - ends the script inside
+ readfile(), so that line never runs and a complete copy of the installation
+ stays behind until something else clears it.
+
+ The archive is not web-accessible, which is what the comment at the top of
+ that file is about. This is the smaller version of the same thing: a file
+ that should have lived for the length of one request and instead lives until
+ something else clears the temp directory.
+
+ These cases pin the shape rather than the behaviour. Proving the removal for
+ a download that is abandoned would need an HTTP stream cut in the middle,
+ which this harness has no way to do.
+*/
+
+wallos_test('the archive is removed on every path out of the request', function () {
+ $source = file_get_contents(WALLOS_ROOT . '/endpoints/db/backup.php');
+
+ assert_contains('register_shutdown_function', $source,
+ 'the removal is registered rather than written after readfile()');
+
+ // The point of the change: nothing relies on reaching the line after the
+ // stream any more.
+ assert_true(
+ strpos($source, 'register_shutdown_function') < strpos($source, 'readfile($zipname);'),
+ 'and it is registered before the stream starts, not after it'
+ );
+ assert_not_contains("readfile(\$zipname);\nunlink(\$zipname);", $source,
+ 'the unlink that only ran on a completed download is gone');
+});
+
+wallos_test('a failure before the stream still removes the archive itself', function () {
+ // The branches that give up before streaming keep their own unlink and
+ // their own message; the shutdown function is a second answer for the path
+ // that has none, not a replacement for the ones that do.
+ $source = file_get_contents(WALLOS_ROOT . '/endpoints/db/backup.php');
+
+ assert_same(2, substr_count($source, '@unlink($zipname);
+ die(json_encode(['),
+ 'both give-up branches still clean up and report');
+});
diff --git a/tests/cases/export_missing_relations_test.php b/tests/cases/export_missing_relations_test.php
new file mode 100644
index 0000000..47aafb3
--- /dev/null
+++ b/tests/cases/export_missing_relations_test.php
@@ -0,0 +1,41 @@
+<?php
+wallos_test('CSV export tolerates subscriptions without payer, payment method or a known category', function () {
+ $source = file_get_contents(WALLOS_ROOT . '/endpoints/subscriptions/export.php');
+ $start = strpos($source, '$subscriptionDetails = array(');
+ $end = strpos($source, ');', $start) + 2;
+ assert_true($start !== false && $end > $start, 'details fragment found');
+ $fragment = substr($source, $start, $end - $start);
+
+ $categories = [2 => ['name' => 'Streaming']];
+ $payment_methods = [3 => ['name' => 'Visa']];
+ $members = [4 => ['name' => 'Me']];
+ $currencies = [5 => ['symbol' => '£']];
+ $cyclePrint = 'Monthly';
+
+ $rows = [
+ ['name' => 'Full', 'next_payment' => '2026-11-01', 'auto_renew' => 1, 'category_id' => 2, 'payment_method_id' => 3,
+ 'payer_user_id' => 4, 'currency_id' => 5, 'price' => 10, 'notes' => 'n', 'url' => '', 'inactive' => 0, 'notify' => 0,
+ 'cancellation_date' => null],
+ ['name' => 'API', 'next_payment' => '2026-11-01', 'auto_renew' => 0, 'category_id' => 99, 'payment_method_id' => null,
+ 'payer_user_id' => null, 'currency_id' => 5, 'price' => 5, 'notes' => null, 'url' => '', 'inactive' => 0, 'notify' => 0,
+ 'cancellation_date' => null],
+ ];
+
+ set_error_handler(function ($severity, $message) { throw new ErrorException($message, 0, $severity); });
+ try {
+ $out = [];
+ foreach ($rows as $row) {
+ eval($fragment);
+ $out[] = $subscriptionDetails;
+ }
+ } finally {
+ restore_error_handler();
+ }
+
+ assert_same('Visa', $out[0]['Payment Method'], 'known payment method kept');
+ assert_same('£10', $out[0]['Price'], 'price with symbol');
+ assert_same('', $out[1]['Payment Method'], 'missing payment method is empty');
+ assert_same('', $out[1]['Paid By'], 'missing payer is empty');
+ assert_same('', $out[1]['Category'], 'unknown category is empty');
+ assert_same('', $out[1]['Notes'], 'null notes are empty');
+});
diff --git a/tests/cases/oidc_logout_url_test.php b/tests/cases/oidc_logout_url_test.php
new file mode 100644
index 0000000..97decbe
--- /dev/null
+++ b/tests/cases/oidc_logout_url_test.php
@@ -0,0 +1,24 @@
+<?php
+require_once WALLOS_ROOT . '/includes/oidc/logout_url.php';
+
+wallos_test('OIDC logout URL carries id_token_hint, client_id and the return address (#891)', function () {
+ $url = oidc_build_logout_url('https://idp.example/realms/x/protocol/openid-connect/logout', 'https://wallos.example/', 'a.b.c', 'wallos');
+ $query = [];
+ parse_str(parse_url($url, PHP_URL_QUERY), $query);
+ assert_same('a.b.c', $query['id_token_hint'], 'hint');
+ assert_same('wallos', $query['client_id'], 'client id');
+ assert_same('https://wallos.example/', $query['post_logout_redirect_uri'], 'return');
+ assert_true(strpos($url, 'https://idp.example/realms/x/protocol/openid-connect/logout?') === 0, 'base kept');
+});
+
+wallos_test('OIDC logout URL tolerates a missing token and a URL that already has a query', function () {
+ assert_same('https://idp/logout?post_logout_redirect_uri=https%3A%2F%2Fw%2F',
+ oidc_build_logout_url('https://idp/logout', 'https://w/', null, null), 'no token');
+ assert_same('https://idp/logout?a=1&client_id=c', oidc_build_logout_url('https://idp/logout?a=1', '', '', 'c'), 'existing query');
+ assert_same('https://idp/logout', oidc_build_logout_url('https://idp/logout', '', null, null), 'nothing to add');
+});
+
+wallos_test('logout.php and the OIDC login keep the ID token for the logout', function () {
+ assert_true(strpos(file_get_contents(WALLOS_ROOT . '/includes/oidc/oidc_login.php'), "\$_SESSION['oidc_id_token']") !== false, 'stored at login');
+ assert_true(strpos(file_get_contents(WALLOS_ROOT . '/logout.php'), 'oidc_build_logout_url(') !== false, 'used at logout');
+});
diff --git a/tests/cases/oidc_state_persisted_test.php b/tests/cases/oidc_state_persisted_test.php
new file mode 100644
index 0000000..2cc9b1a
--- /dev/null
+++ b/tests/cases/oidc_state_persisted_test.php
@@ -0,0 +1,100 @@
+<?php
+/*
+ The OIDC state is consumed on disk before the token exchange (#1239).
+
+ The callback validates the state, removes it, and then spends a second or two
+ at the provider's token endpoint. PHP writes the session at the end of the
+ request, and the sign-in regenerates the session id before that, which
+ deletes the file the removal would have been written to.
+
+ So a second request carrying the same callback - which is what a browser on
+ an unstable connection produces, and what was measured on a real instance:
+ two callbacks 61 ms apart, the first abandoned - waits on the session lock,
+ is handed the state as it stood before, and redeems the same authorization
+ code again. The provider refuses it, and the person is shown a failure for a
+ login that had succeeded.
+
+ The case below reads the session file from outside while the exchange is
+ still running, because that is exactly what the second request is handed.
+*/
+
+/**
+ * Runs PHP in its own process against a fixed session directory and id,
+ * without waiting for it.
+ *
+ * @return string the file its output will appear in
+ */
+function oidc_state_spawn($sessionDir, $sessionId, $body)
+{
+ $script = tempnam(sys_get_temp_dir(), 'wallos_oidc_state_');
+ $out = $script . '.out';
+
+ file_put_contents($script,
+ '<?php' . "\n"
+ . 'ini_set("session.save_path", ' . var_export($sessionDir, true) . ');' . "\n"
+ . 'ini_set("session.use_cookies", "0");' . "\n"
+ . 'session_id(' . var_export($sessionId, true) . ');' . "\n"
+ . 'session_start();' . "\n"
+ . 'require ' . var_export(WALLOS_ROOT . '/includes/oidc/session_persist.php', true) . ';' . "\n"
+ . $body . "\n");
+
+ exec('php ' . escapeshellarg($script) . ' > ' . escapeshellarg($out) . ' 2>&1 &');
+
+ return $out;
+}
+
+wallos_test('the state is gone from the session file before the exchange finishes', function () {
+ $dir = sys_get_temp_dir() . '/wallos-oidc-state-' . bin2hex(random_bytes(6));
+ mkdir($dir, 0700, true);
+ $sessionId = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa';
+
+ // The session as it stands when the provider redirects back.
+ $prepare = oidc_state_spawn($dir, $sessionId, '
+ $_SESSION["oidc_state"] = "state-1";
+ session_write_close();
+ echo "prepared\n";
+ ');
+ sleep(1);
+ @unlink($prepare);
+
+ $file = $dir . '/sess_' . $sessionId;
+ assert_contains('state-1', file_get_contents($file), 'the state is in the session file');
+
+ // The callback: the same sequence checksession.php performs, then the
+ // exchange it performs it for.
+ $out = oidc_state_spawn($dir, $sessionId, '
+ unset($_SESSION["oidc_state"]);
+ oidc_persist_session();
+
+ echo "consumed\n";
+ usleep(1500000); // the token exchange
+ ');
+
+ // Read it while that exchange is still running. This is what a second
+ // callback carrying the same code is handed.
+ usleep(600000);
+ $duringExchange = file_get_contents($file);
+
+ sleep(2);
+ $callback = file_get_contents($out);
+ @unlink($out);
+
+ assert_contains('consumed', $callback, 'the callback consumed the state');
+ assert_true(strpos($duringExchange, 'state-1') === false,
+ 'and it is gone from the session file while the exchange is still running');
+
+ array_map('unlink', glob($dir . '/sess_*'));
+ rmdir($dir);
+});
+
+wallos_test('both places that consume the state write it out', function () {
+ // The refusal path removes the state too. Left in memory there, a retry of
+ // a callback that was already refused would be checked against a state
+ // that should no longer exist.
+ $source = file_get_contents(WALLOS_ROOT . '/includes/checksession.php');
+
+ assert_same(2, substr_count($source, "unset(\$_SESSION['oidc_state']);"),
+ 'the state is consumed in two places');
+ assert_same(2, substr_count($source, 'oidc_persist_session();'),
+ 'and both of them write the session out');
+});
diff --git a/tests/cases/price_sort_test.php b/tests/cases/price_sort_test.php
new file mode 100644
index 0000000..1476265
--- /dev/null
+++ b/tests/cases/price_sort_test.php
@@ -0,0 +1,52 @@
+<?php
+/* list_subscriptions.php runs queries at include time, so evaluate only the
+ two sorting helpers out of it. */
+function price_sort_load_helpers() {
+ if (function_exists('sortSubscriptionsByPrice')) {
+ return;
+ }
+ $source = file_get_contents(WALLOS_ROOT . '/includes/list_subscriptions.php');
+ foreach (['getSortPrice', 'sortSubscriptionsByPrice'] as $name) {
+ $start = strpos($source, 'function ' . $name . '(');
+ assert_true($start !== false, $name . ' found');
+ $end = strpos($source, "\n}", $start);
+ eval(substr($source, $start, $end - $start + 2));
+ }
+}
+
+wallos_test('sorting by price ranks by the main-currency value, not the raw number (#861)', function () {
+ price_sort_load_helpers();
+ // AED 71.00 (~GBP 15) must come after GBP 55.00.
+ $print = [
+ ['id' => 1, 'inactive' => 0, 'sort_price' => 15.2],
+ ['id' => 2, 'inactive' => 0, 'sort_price' => 55.0],
+ ['id' => 3, 'inactive' => 0, 'sort_price' => 20.0],
+ ];
+ sortSubscriptionsByPrice($print, false);
+ assert_same([2, 3, 1], array_column($print, 'id'), 'highest converted price first');
+});
+
+wallos_test('price sort keeps ties in database order and honours disabled-to-bottom', function () {
+ price_sort_load_helpers();
+ $print = [
+ ['id' => 1, 'inactive' => 1, 'sort_price' => 90.0],
+ ['id' => 2, 'inactive' => 0, 'sort_price' => 10.0],
+ ['id' => 3, 'inactive' => 0, 'sort_price' => 10.0],
+ ];
+ sortSubscriptionsByPrice($print, true);
+ assert_same([2, 3, 1], array_column($print, 'id'), 'inactive last, ties stable');
+ sortSubscriptionsByPrice($print, false);
+ assert_same([1, 2, 3], array_column($print, 'id'), 'inactive mixed in when the setting is off');
+});
+
+wallos_test('getSortPrice converts other currencies and leaves the main currency alone', function () {
+ price_sort_load_helpers();
+ assert_same(55.0, getSortPrice('55', 2, 2, 4, 1, [], null), 'same currency untouched');
+ $source = file_get_contents(WALLOS_ROOT . '/includes/list_subscriptions.php');
+ assert_true(strpos($source, 'getPriceConverted($price, $currencyId, $database)') !== false, 'other currencies are converted');
+ foreach (['subscriptions.php', 'endpoints/subscriptions/get.php'] as $file) {
+ $page = file_get_contents(WALLOS_ROOT . '/' . $file);
+ assert_true(strpos($page, 'sort_price') !== false, $file . ' computes the converted price');
+ }
+ assert_true(strpos($source, 'sortSubscriptionsByPrice($subscriptions') !== false, 'the list printer ranks by converted price');
+});
diff --git a/tests/cases/settings_api_writes_test.php b/tests/cases/settings_api_writes_test.php
new file mode 100644
index 0000000..c21f2f0
--- /dev/null
+++ b/tests/cases/settings_api_writes_test.php
@@ -0,0 +1,129 @@
+<?php
+/*
+ The settings API answers for the writes it made, not for the ones it attempted.
+
+ `api/settings/set_settings.php` contradicted itself. The settings UPDATE near
+ the end reads its own result and answers "Database error" when it fails. The
+ four writes above it — the delete and insert that replace the custom css, and
+ the pair that replace the custom colours — discarded theirs, and the file
+ finished with `success: true` either way.
+
+ The consequence is not a lost setting. It is two rows where there should be
+ one: a delete that fails while the insert succeeds leaves both, and every
+ reader of these tables selects by user_id and takes the first row it is
+ handed. Which of the two that is, is decided by nothing. So the page can go on
+ serving the css or the theme this request was meant to replace, after the API
+ has said it was saved.
+
+ The delete-before-replace gate does not catch this one, and says why in its
+ own comment: it governs a pair only when the insert is read, because adding a
+ check to the delete alone would not make the file honest. Reading both is what
+ brings this pair under that gate — after this change the pair is governed, and
+ a future edit that drops either check fails there too.
+*/
+
+/**
+ * @return string
+ */
+function settings_api_source()
+{
+ return file_get_contents(WALLOS_ROOT . '/api/settings/set_settings.php');
+}
+
+wallos_test('no write in the settings API is discarded', function () {
+ // The whole file rather than the four lines that had it: a fifth write
+ // added later is caught by the same rule, without anybody remembering to
+ // come back here.
+ $lines = preg_split('/\R/', settings_api_source());
+ $discarded = [];
+
+ foreach ($lines as $number => $line) {
+ // A statement of its own, with nothing done to what it returns.
+ if (preg_match('/^\s*\$\w+->execute\(\)\s*;\s*$/', $line) === 1) {
+ $discarded[] = $number + 1;
+ }
+ }
+
+ assert_same([], $discarded,
+ 'every execute() in api/settings/set_settings.php is read (lines with a '
+ . 'discarded one: ' . implode(', ', $discarded) . ')');
+});
+
+wallos_test('a failure in either replacement is answered, not reported as saved', function () {
+ // The file already knew how to say this; it simply did not say it here.
+ $source = settings_api_source();
+
+ assert_true(substr_count($source, "'title' => 'Database error'") >= 3,
+ 'the custom css, the custom colours and the settings update all answer '
+ . 'the same way when a write fails');
+
+ $success = strpos($source, "'title' => 'Settings updated'");
+ $cssGuard = strpos($source, '$cssStored');
+ $colorGuard = strpos($source, '$colorsStored');
+
+ assert_true($cssGuard !== false && $cssGuard < $success,
+ 'the css result is known before the success answer is written');
+ assert_true($colorGuard !== false && $colorGuard < $success,
+ 'and so is the colour result');
+});
+
+wallos_test('the second row really does get in, and reading the result is what stops it', function () {
+ // Not a demonstration of the file — a demonstration of what its previous
+ // shape allowed, against the real schema. A trigger refuses the delete,
+ // which is how a locked database or a read-only disk looks from here:
+ // SQLite reports all of them through the statement result, and through
+ // nothing else.
+ $db = wallos_test_open_database();
+ wallos_test_create_user($db, 1, 'alice');
+
+ $save = function ($css) use ($db) {
+ $stmt = $db->prepare('INSERT INTO custom_css_style (css, user_id) VALUES (:css, 1)');
+ $stmt->bindValue(':css', $css, SQLITE3_TEXT);
+ $stmt->execute();
+ };
+
+ $rows = function () use ($db) {
+ return (int) $db->querySingle('SELECT COUNT(*) FROM custom_css_style WHERE user_id = 1');
+ };
+
+ $refuseDeletes = function () use ($db) {
+ $db->query("CREATE TRIGGER settings_api_refuse_delete BEFORE DELETE ON custom_css_style
+ BEGIN SELECT RAISE(ABORT, 'refused'); END");
+ };
+
+ $save('body { color: black }');
+ $refuseDeletes();
+
+ // The shape the file had. The @ only silences the warning SQLite prints
+ // beside the return value the caller is about to ignore.
+ $stmt = $db->prepare('DELETE FROM custom_css_style WHERE user_id = 1');
+ $dropped = @$stmt->execute();
+ $save('body { color: red }');
+
+ assert_true($dropped === false, 'the delete did fail, so the rest of this means something');
+ assert_same(2, $rows(),
+ 'unchecked, a failed delete leaves the replacement beside the row it should have replaced');
+
+ // Which of the two any page gets is decided by nothing: every reader of
+ // this table selects by user_id and takes the first row of the result.
+ $reader = $db->query('SELECT css FROM custom_css_style WHERE user_id = 1');
+ assert_true($reader->fetchArray(SQLITE3_ASSOC) !== false,
+ 'and a reader answers with one of them without being able to say which');
+
+ // Back to one row, then the shape the file has now.
+ $db->query('DROP TRIGGER settings_api_refuse_delete');
+ $db->query('DELETE FROM custom_css_style WHERE user_id = 1');
+ $save('body { color: black }');
+ $refuseDeletes();
+
+ $stmt = $db->prepare('DELETE FROM custom_css_style WHERE user_id = 1');
+
+ if (@$stmt->execute() !== false) {
+ $save('body { color: red }');
+ }
+
+ assert_same(1, $rows(),
+ 'read, the request stops instead of adding a second row, and the caller is told');
+
+ $db->close();
+});
diff --git a/tests/cases/subscription_relations_test.php b/tests/cases/subscription_relations_test.php
new file mode 100644
index 0000000..75196cc
--- /dev/null
+++ b/tests/cases/subscription_relations_test.php
@@ -0,0 +1,67 @@
+<?php
+/* Exercise the actual page/endpoint fragments: both require a live session,
+ so execute only their relation lookups with warnings promoted to errors. */
+function subscription_relations_source($file) {
+ return file_get_contents(WALLOS_ROOT . '/' . $file);
+}
+
+wallos_test('subscription relation counts ignore absent and unresolved optional IDs', function () {
+ $source = subscription_relations_source('subscriptions.php');
+ $start = strpos($source, 'foreach ($subscriptions as $subscription) {');
+ $end = strpos($source, 'if ($sortOrder == "category_id")', $start);
+ assert_true($start !== false && $end !== false, 'counting fragment found');
+ $fragment = substr($source, $start, $end - $start);
+ $members = [7 => ['count' => 0]];
+ $categories = [8 => ['count' => 0]];
+ $payment_methods = [9 => ['count' => 0]];
+ $subscriptions = [
+ ['payer_user_id' => null, 'category_id' => null, 'payment_method_id' => null],
+ ['payer_user_id' => 99, 'category_id' => 99, 'payment_method_id' => 99],
+ ['payer_user_id' => 7, 'category_id' => 8, 'payment_method_id' => 9],
+ ];
+ 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');
+ assert_same([8 => ['count' => 1]], $categories, 'only known category counted');
+ assert_same([9 => ['count' => 1]], $payment_methods, 'only known payment method counted');
+});
+
+wallos_test('initial and filtered lists preserve known payment methods and omit missing metadata', function () {
+ foreach (['subscriptions.php', 'endpoints/subscriptions/get.php'] as $file) {
+ $source = subscription_relations_source($file);
+ // Start at the icon lookup, ending before unrelated subscription fields.
+ $start = strpos($source, '$paymentIcon =');
+ $end = strpos($source, '$print[$id][\'payment_method_id\']', $start ?: 0);
+ assert_true($start !== false && $end !== false, 'metadata fragment found in ' . $file);
+ $fragment = substr($source, $start, $end - $start);
+ $payment_methods = [9 => ['icon' => 'visa.png', 'name' => 'Visa'],
+ 10 => ['icon' => 'images/uploads/icons/custom.png', 'name' => 'Custom']];
+ foreach ([null, 99, 9, 10] as $paymentMethodId) {
+ $id = 1; $print = [];
+ set_error_handler(function ($severity, $message) { throw new ErrorException($message, 0, $severity); });
+ try { eval($fragment); } finally { restore_error_handler(); }
+ $expectedIcon = $paymentMethodId === 9 ? 'images/uploads/logos/visa.png'
+ : ($paymentMethodId === 10 ? 'images/uploads/icons/custom.png' : '');
+ assert_same($expectedIcon, $print[1]['payment_method_icon'], $file . ' icon');
+ assert_same($payment_methods[$paymentMethodId ?? '']['name'] ?? '', $print[1]['payment_method_name'], $file . ' name');
+ }
+ }
+});
+
+wallos_test('relation sort puts missing IDs last without changing configured order', function () {
+ foreach (['subscriptions.php', 'endpoints/subscriptions/get.php'] as $file) {
+ $source = subscription_relations_source($file);
+ foreach (['categories' => 'category_id', 'payment_methods' => 'payment_method_id'] as $lookup => $key) {
+ preg_match('/return (\(\$' . $lookup . '\[\$a[^;]+);/', $source, $match);
+ assert_true(isset($match[1]), 'sort expression found in ' . $file);
+ $categories = $payment_methods = [9 => ['order' => 2], 7 => ['order' => 1]];
+ $compare = function ($a, $b) use ($match, $categories, $payment_methods) {
+ return eval('return ' . $match[1] . ';');
+ };
+ $rows = [[$key => null], [$key => 9], [$key => 99], [$key => 7]];
+ set_error_handler(function ($severity, $message) { throw new ErrorException($message, 0, $severity); });
+ try { usort($rows, $compare); } finally { restore_error_handler(); }
+ assert_same([7, 9, null, 99], array_column($rows, $key), $file . ' configured order then missing');
+ }
+ }
+});
diff --git a/tests/cases/webhook_headers_test.php b/tests/cases/webhook_headers_test.php
new file mode 100644
index 0000000..0e2ff3b
--- /dev/null
+++ b/tests/cases/webhook_headers_test.php
@@ -0,0 +1,124 @@
+<?php
+/*
+ The custom headers field of a webhook or an ntfy topic.
+
+ The case this file exists for was reported in #1212: notifications stopped
+ arriving while the Test button reported success. The cron log held
+
+ Fatal error: Uncaught TypeError: curl_setopt(): The CURLOPT_HTTPHEADER
+ option must have an array value ... sendnotifications.php:931
+
+ because the job checked whether the field had something in it, then decoded
+ it as JSON and handed the result to cURL without looking. A value that is not
+ JSON decodes to null, and on PHP 8 that is a fatal - so the run ended there,
+ taking every channel after it and every account after that one with it.
+
+ The reader disagreed with itself elsewhere too: the cancellation job split the
+ same field into lines rather than decoding it, and two ntfy blocks mapped a
+ decoded object into header lines, one of them without checking the decode
+ either. One reader now answers for all of them.
+*/
+
+require_once WALLOS_ROOT . '/includes/webhook_headers.php';
+
+wallos_test('a value that is not JSON yields no headers instead of ending the run', function () {
+ // What somebody types who reads "Custom headers" and writes a header.
+ assert_same(['Content-Type: application/json'], webhook_custom_headers('Content-Type: application/json'),
+ 'a plain header line is read as one header, as the cancellation job always did');
+ assert_same([], webhook_custom_headers('{"Authorization": '), 'truncated JSON yields nothing');
+ assert_same([], webhook_custom_headers('null'), 'the literal null yields nothing');
+ assert_same([], webhook_custom_headers('"a string"'), 'a JSON string is not a header list');
+ assert_same([], webhook_custom_headers('42'), 'nor is a number');
+ assert_same([], webhook_custom_headers(''), 'an empty field yields nothing');
+ assert_same([], webhook_custom_headers(' '), 'and neither does whitespace');
+ assert_same([], webhook_custom_headers(null), 'a column that is NULL yields nothing');
+});
+
+wallos_test('the two shapes that were already in use both produce header lines', function () {
+ // The shape the ntfy blocks documented by example.
+ assert_same(['Authorization: Bearer tk_123'],
+ webhook_custom_headers('{"Authorization": "Bearer tk_123"}'),
+ 'an object becomes "Name: value"');
+
+ // The shape a value handed straight to cURL had to be.
+ assert_same(['Content-Type: application/json', 'X-Wallos: 1'],
+ webhook_custom_headers('["Content-Type: application/json", "X-Wallos: 1"]'),
+ 'a list is taken as complete header lines');
+
+ assert_same(['A: 1', 'B: 2'], webhook_custom_headers('{"A": "1", "B": "2"}'),
+ 'every pair of an object is used, in order');
+});
+
+wallos_test('an entry that cannot be one header line is skipped, not stringified', function () {
+ assert_same(['Ok: 1'], webhook_custom_headers('{"Ok": "1", "Nested": {"a": "b"}}'),
+ 'a nested object is skipped rather than written as "Array"');
+ assert_same(['Ok: 1'], webhook_custom_headers('{"Ok": "1", "Empty": null}'),
+ 'a null value is skipped');
+ assert_same([], webhook_custom_headers('["no colon here"]'),
+ 'a list entry that is not a header line is skipped');
+ assert_same(['X: 1'], webhook_custom_headers('{" X ": " 1 "}'),
+ 'surrounding space is not part of the name or the value');
+});
+
+wallos_test('every reader of the field goes through the one function', function () {
+ // The defect was not the decode; it was that five places decided
+ // separately what the field means. A new reader that decodes on its own is
+ // the same defect again.
+ $readers = [
+ 'endpoints/cronjobs/sendnotifications.php',
+ 'endpoints/cronjobs/sendcancellationnotifications.php',
+ 'endpoints/notifications/testwebhooknotifications.php',
+ 'endpoints/notifications/testntfynotifications.php',
+ ];
+
+ foreach ($readers as $path) {
+ $source = file_get_contents(WALLOS_ROOT . '/' . $path);
+
+ assert_contains('webhook_custom_headers(', $source, $path . ' reads the field through the helper');
+ assert_not_contains('json_decode($webhook["headers"]', $source,
+ $path . ' does not decode the webhook field on its own');
+ assert_not_contains('json_decode($ntfy["headers"]', $source,
+ $path . ' does not decode the ntfy field on its own');
+ }
+});
+
+wallos_test('cURL never sees anything but an array of lines', function () {
+ // The direct statement of the crash: whatever the field holds, what
+ // reaches CURLOPT_HTTPHEADER is a list of strings.
+ foreach ([
+ 'Content-Type: application/json',
+ '{"Authorization": "Bearer tk"}',
+ '["X: 1"]',
+ 'null',
+ '',
+ '{"broken": ',
+ ] as $stored) {
+ $headers = webhook_custom_headers($stored);
+
+ assert_true(is_array($headers), 'an array for ' . var_export($stored, true));
+
+ foreach ($headers as $line) {
+ assert_true(is_string($line), 'every entry is a string for ' . var_export($stored, true));
+ }
+ }
+});
+
+wallos_test('newline-separated headers (the old cancellation format) still work, and values cannot inject lines', function () {
+ require_once WALLOS_ROOT . '/includes/webhook_headers.php';
+ assert_same(['X-Token: abc', 'Accept: text/plain'], webhook_custom_headers("X-Token: abc\r\nAccept: text/plain"), 'lines read');
+ assert_same([], webhook_custom_headers('not a header at all'), 'garbage yields nothing');
+ assert_same(['X-A: one X-Injected: two'], webhook_custom_headers(json_encode(['X-A' => "one\r\nX-Injected: two"])), 'CR/LF neutralised');
+});
+
+wallos_test('a JSON payload is announced as JSON unless the user set a Content-Type (#990)', function () {
+ require_once WALLOS_ROOT . '/includes/webhook_headers.php';
+ $json = '{"name": "Test", "price": "10"}';
+ assert_same(['Content-Type: application/json'], webhook_headers_with_content_type([], $json), 'added for JSON body');
+ assert_same(['X-A: 1', 'Content-Type: application/json'], webhook_headers_with_content_type(['X-A: 1'], $json), 'appended');
+ assert_same(['content-type: text/plain'], webhook_headers_with_content_type(['content-type: text/plain'], $json), 'user value wins, any case');
+ assert_same([], webhook_headers_with_content_type([], 'plain text body'), 'non-JSON untouched');
+ assert_same([], webhook_headers_with_content_type([], ''), 'empty body untouched');
+ foreach (['endpoints/cronjobs/sendnotifications.php', 'endpoints/cronjobs/sendcancellationnotifications.php', 'endpoints/notifications/testwebhooknotifications.php'] as $file) {
+ assert_true(strpos(file_get_contents(WALLOS_ROOT . '/' . $file), 'webhook_headers_with_content_type(webhook_custom_headers(') !== false, $file . ' applies it');
+ }
+});
diff --git a/tests/cases/webpush_test.php b/tests/cases/webpush_test.php
index d74ad09..374d4ca 100644
--- a/tests/cases/webpush_test.php
+++ b/tests/cases/webpush_test.php
@@ -307,3 +307,47 @@ wallos_test('webpush_send() reports 404/410 as prune, and everything else as not
assert_same($expectedPrune, $prune, "status $status prunes: " . ($expectedPrune ? 'yes' : 'no'));
}
});
+
+wallos_test('a second first-use does not replace the keypair the browsers already know', function () {
+ $db = wallos_test_open_database();
+
+ // Two requests find the columns empty at the same moment and each
+ // generates a pair. Whichever writes first is the one a browser may
+ // already have subscribed with, so the second must not replace it: a
+ // subscription is bound to the applicationServerKey it saw, and a push
+ // service answers 403 for it forever afterwards, which prunes nothing and
+ // shows nothing.
+ $first = webpush_generate_vapid_keypair();
+ $second = webpush_generate_vapid_keypair();
+
+ assert_true($first !== false && $second !== false, 'two keypairs were generated');
+ assert_true($first['public'] !== $second['public'], 'and they really are different');
+
+ $stored = webpush_store_vapid_keys($db, $first);
+ assert_same($first['public'], $stored['public'], 'the first write is stored');
+
+ $answered = webpush_store_vapid_keys($db, $second);
+
+ assert_same($first['public'], $answered['public'],
+ 'the second caller is answered with the stored pair, not its own');
+ assert_same($first['private_pem'], $answered['private_pem'],
+ 'including the private half, so what it signs with matches what it sends');
+
+ $row = $db->querySingle('SELECT vapid_public_key FROM admin LIMIT 1', true);
+ assert_same($first['public'], $row['vapid_public_key'], 'and the row still holds the first pair');
+
+ $db->close();
+});
+
+wallos_test('an installation with no keypair yet still gets one', function () {
+ $db = wallos_test_open_database();
+
+ $keys = webpush_get_vapid_keys($db);
+ assert_true($keys !== false, 'the first use generates and stores a pair');
+
+ $row = $db->querySingle('SELECT vapid_public_key, vapid_private_key FROM admin LIMIT 1', true);
+ assert_same($keys['public'], $row['vapid_public_key'], 'the row holds what the caller was given');
+ assert_true(!empty($row['vapid_private_key']), 'both halves are stored');
+
+ $db->close();
+});
diff --git a/tests/csv_export.test.js b/tests/csv_export.test.js
new file mode 100644
index 0000000..381e358
--- /dev/null
+++ b/tests/csv_export.test.js
@@ -0,0 +1,23 @@
+// Run with: node --test tests/csv_export.test.js
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const path = require('node:path');
+
+const source = fs.readFileSync(path.join(__dirname, '../scripts/profile.js'), 'utf8');
+const match = source.match(/function csvDataUri\(csv\) \{[\s\S]*?\n\}/);
+assert.ok(match, 'csvDataUri found in profile.js');
+const context = vm.createContext({});
+vm.runInContext(match[0], context);
+
+test('CSV export is prefixed with a UTF-8 BOM so Excel does not show £ as £', () => {
+ const uri = context.csvDataUri('name,price\nTest,£29.84');
+ assert.ok(uri.startsWith('data:text/csv;charset=utf-8,%EF%BB%BF'), uri);
+ const decoded = decodeURIComponent(uri.split(',').slice(1).join(','));
+ assert.equal(decoded, 'name,price\nTest,£29.84');
+});
+
+test('exportAsCsv builds its link with csvDataUri', () => {
+ assert.match(source, /setAttribute\('href', csvDataUri\(csvWithHeader\)\)/);
+});
diff --git a/tests/theme_body_classes.test.js b/tests/theme_body_classes.test.js
new file mode 100644
index 0000000..4c02d07
--- /dev/null
+++ b/tests/theme_body_classes.test.js
@@ -0,0 +1,59 @@
+// Run with: node --test tests/theme_body_classes.test.js
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const vm = require('node:vm');
+const path = require('node:path');
+
+const source = fs.readFileSync(path.join(__dirname, '../scripts/theme.js'), 'utf8');
+
+for (const direction of ['ltr', 'rtl']) {
+ for (const prefersDark of [false, true]) {
+ test(`theme changes preserve ${direction} and mobile navigation (system dark: ${prefersDark})`, async () => {
+ const classes = new Set([prefersDark ? 'automatic' : 'light', direction, 'mobile-navigation', 'custom-class']);
+ const body = {
+ get className() { return [...classes].join(' '); },
+ set className(value) { classes.clear(); value.split(/\s+/).forEach(c => classes.add(c)); },
+ classList: {
+ remove: (...names) => names.forEach(name => classes.delete(name)),
+ add: (...names) => names.forEach(name => classes.add(name)),
+ },
+ };
+ const buttons = Object.fromEntries(['#theme-light', '#theme-dark', '#theme-automatic'].map(id => [
+ id, { disabled: false, classList: { remove() {}, add() {} } },
+ ]));
+ const stylesheet = { disabled: true };
+ const requests = [];
+ const context = vm.createContext({
+ document: {
+ body,
+ cookie: '',
+ querySelector: id => id === '#dark-theme' ? stylesheet : buttons[id],
+ },
+ window: { csrfToken: 'synthetic-token', matchMedia: () => ({ matches: prefersDark }) },
+ fetch: async (url, options) => {
+ requests.push({ url, options });
+ return { json: async () => ({ success: true, message: 'Success' }) };
+ },
+ showSuccessMessage() {},
+ showErrorMessage() { assert.fail('unexpected error'); },
+ });
+ vm.runInContext(source, context);
+
+ // Exercise repeated changes without reloading, including Automatic.
+ for (const choice of ['1', '0', '2', '1', '2', '0']) {
+ context.setDarkTheme(choice);
+ await new Promise(resolve => setImmediate(resolve));
+ const expected = choice === '2' ? (prefersDark ? 'dark' : 'light') : (choice === '1' ? 'dark' : 'light');
+ assert.deepEqual([...classes].sort(), [direction, 'mobile-navigation', 'custom-class', expected].sort());
+ assert.equal(stylesheet.disabled, expected === 'light');
+ assert.match(context.document.cookie, choice === '2' ? /inUseTheme=/ : /theme=/);
+ const request = requests.at(-1);
+ assert.equal(request.url, 'endpoints/settings/theme.php');
+ assert.equal(request.options.headers['X-CSRF-Token'], 'synthetic-token');
+ assert.equal(JSON.parse(request.options.body).theme, choice);
+ assert.ok(Object.values(buttons).every(button => !button.disabled));
+ }
+ });
+ }
+}