Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
fix: cleanup unused logos when deleting or editing subscriptions
Miguel Ribeiro20d23db12eec
diff --git a/endpoints/admin/deleteuser.php b/endpoints/admin/deleteuser.phpindex 209b2f5..93edfee 100644--- a/endpoints/admin/deleteuser.php+++ b/endpoints/admin/deleteuser.php@@ -2,6 +2,7 @@require_once '../../includes/connect_endpoint.php';require_once '../../includes/validate_endpoint_admin.php';+require_once '../../includes/logo_cleanup.php';$postData = file_get_contents("php://input");$data = json_decode($postData, true);@@ -14,6 +15,23 @@ if ($userId == 1) {"message" => translate('error', $i18n)]));} else {+ // Collect this account's uploaded logo files before its rows go, so they+ // can be removed from disk afterwards if nothing else references them.+ $logoFilesToCheck = [];+ $logoQuery = $db->prepare('SELECT logo, logo_variant FROM subscriptions WHERE user_id = :id');+ $logoQuery->bindValue(':id', $userId, SQLITE3_INTEGER);+ $logoResult = $logoQuery->execute();+ while ($logoResult && ($logoRow = $logoResult->fetchArray(SQLITE3_ASSOC))) {+ $logoFilesToCheck[] = $logoRow['logo'];+ $logoFilesToCheck[] = $logoRow['logo_variant'];+ }+ $iconQuery = $db->prepare("SELECT icon FROM payment_methods WHERE user_id = :id AND icon NOT LIKE 'images/uploads/icons/%'");+ $iconQuery->bindValue(':id', $userId, SQLITE3_INTEGER);+ $iconResult = $iconQuery->execute();+ while ($iconResult && ($iconRow = $iconResult->fetchArray(SQLITE3_ASSOC))) {+ $logoFilesToCheck[] = $iconRow['icon'];+ }+// Delete user$stmt = $db->prepare('DELETE FROM user WHERE id = :id');$stmt->bindValue(':id', $userId, SQLITE3_INTEGER);@@ -110,10 +128,9 @@ if ($userId == 1) {$result = $stmt->execute();// The twelve tables this used to leave behind. Two of them hold- // credentials — a remember-me token and a password reset token — and- // the user table has no AUTOINCREMENT, so SQLite hands a deleted id- // straight back to the next account created. That account inherited- // them.+ // credentials (a remember-me token and a password reset token) and the+ // user table has no AUTOINCREMENT, so SQLite hands a deleted id straight+ // back to the next account created. That account inherited them.// Delete login tokens$stmt = $db->prepare('DELETE FROM login_tokens WHERE user_id = :id');@@ -175,6 +192,11 @@ if ($userId == 1) {$stmt->bindValue(':id', $userId, SQLITE3_INTEGER);$result = $stmt->execute();+ // The account's rows are gone; drop its logo files that nothing else uses.+ foreach (array_unique(array_filter($logoFilesToCheck)) as $logoFile) {+ deleteLogoFileIfUnused($db, $logoFile, '../../images/uploads/logos/');+ }+die(json_encode(["success" => true,"message" => translate('success', $i18n)diff --git a/endpoints/settings/deleteaccount.php b/endpoints/settings/deleteaccount.phpindex 78a6a88..03ff39f 100644--- a/endpoints/settings/deleteaccount.php+++ b/endpoints/settings/deleteaccount.php@@ -2,6 +2,7 @@require_once '../../includes/connect_endpoint.php';require_once '../../includes/validate_endpoint.php';+require_once '../../includes/logo_cleanup.php';$postData = file_get_contents("php://input");$data = json_decode($postData, true);@@ -14,6 +15,23 @@ if ($userIdToDelete == 1 || $userIdToDelete != $userId) {"message" => translate('error', $i18n)]));} else {+ // Collect this account's uploaded logo files before its rows go, so they+ // can be removed from disk afterwards if nothing else references them.+ $logoFilesToCheck = [];+ $logoQuery = $db->prepare('SELECT logo, logo_variant FROM subscriptions WHERE user_id = :id');+ $logoQuery->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $logoResult = $logoQuery->execute();+ while ($logoResult && ($logoRow = $logoResult->fetchArray(SQLITE3_ASSOC))) {+ $logoFilesToCheck[] = $logoRow['logo'];+ $logoFilesToCheck[] = $logoRow['logo_variant'];+ }+ $iconQuery = $db->prepare("SELECT icon FROM payment_methods WHERE user_id = :id AND icon NOT LIKE 'images/uploads/icons/%'");+ $iconQuery->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);+ $iconResult = $iconQuery->execute();+ while ($iconResult && ($iconRow = $iconResult->fetchArray(SQLITE3_ASSOC))) {+ $logoFilesToCheck[] = $iconRow['icon'];+ }+// Delete user$stmt = $db->prepare('DELETE FROM user WHERE id = :id');$stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);@@ -110,10 +128,9 @@ if ($userIdToDelete == 1 || $userIdToDelete != $userId) {$result = $stmt->execute();// The twelve tables this used to leave behind. Two of them hold- // credentials — a remember-me token and a password reset token — and- // the user table has no AUTOINCREMENT, so SQLite hands a deleted id- // straight back to the next account created. That account inherited- // them.+ // credentials (a remember-me token and a password reset token) and the+ // user table has no AUTOINCREMENT, so SQLite hands a deleted id straight+ // back to the next account created. That account inherited them.// Delete login tokens$stmt = $db->prepare('DELETE FROM login_tokens WHERE user_id = :id');@@ -175,6 +192,11 @@ if ($userIdToDelete == 1 || $userIdToDelete != $userId) {$stmt->bindValue(':id', $userIdToDelete, SQLITE3_INTEGER);$result = $stmt->execute();+ // The account's rows are gone; drop its logo files that nothing else uses.+ foreach (array_unique(array_filter($logoFilesToCheck)) as $logoFile) {+ deleteLogoFileIfUnused($db, $logoFile, '../../images/uploads/logos/');+ }+die(json_encode(["success" => true,"message" => translate('success', $i18n)diff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.phpindex 48b7722..e9d41a8 100644--- a/endpoints/subscription/add.php+++ b/endpoints/subscription/add.php@@ -6,6 +6,7 @@ require_once '../../includes/inputvalidation.php';require_once '../../includes/getsettings.php';require_once '../../includes/ssrf_helper.php';require_once '../../includes/logo_theme_variant.php';+require_once '../../includes/logo_cleanup.php';if (!file_exists('../../images/uploads/logos')) {mkdir('../../images/uploads/logos', 0777, true);@@ -335,11 +336,27 @@ if (!$isEdit) {)";} else {$id = $_POST['id'];- $sql = "UPDATE subscriptions SET- name = :name,- price = :price,++ // When the logo is being replaced, remember the old files so they can be+ // removed after the update instead of lingering as orphans.+ $oldLogo = null;+ $oldLogoVariant = null;+ if ($logo != "") {+ $oldLogoStmt = $db->prepare("SELECT logo, logo_variant FROM subscriptions WHERE id = :id AND user_id = :userId");+ $oldLogoStmt->bindParam(':id', $id, SQLITE3_INTEGER);+ $oldLogoStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+ $oldLogoResult = $oldLogoStmt->execute();+ if ($oldLogoResult && ($oldLogoRow = $oldLogoResult->fetchArray(SQLITE3_ASSOC))) {+ $oldLogo = $oldLogoRow['logo'];+ $oldLogoVariant = $oldLogoRow['logo_variant'];+ }+ }++ $sql = "UPDATE subscriptions SET+ name = :name,+ price = :price,currency_id = :currencyId,- next_payment = :nextPayment,+ next_payment = :nextPayment,auto_renew = :autoRenew,start_date = :startDate,cycle = :cycle,@@ -398,6 +415,17 @@ if ($stmt->execute()) {if ($logoError !== "") {$success['logo_warning'] = $logoError;}++ // The logo was just replaced: drop the previous files if nothing else uses them.+ if ($isEdit && $logo != "") {+ if ($oldLogo !== null && $oldLogo !== $logo) {+ deleteLogoFileIfUnused($db, $oldLogo, '../../images/uploads/logos/');+ }+ if ($oldLogoVariant !== null && $oldLogoVariant !== $logoVariant) {+ deleteLogoFileIfUnused($db, $oldLogoVariant, '../../images/uploads/logos/');+ }+ }+header('Content-Type: application/json');echo json_encode($success);exit();diff --git a/endpoints/subscription/delete.php b/endpoints/subscription/delete.phpindex e8d7cf0..46ee68e 100644--- a/endpoints/subscription/delete.php+++ b/endpoints/subscription/delete.php@@ -1,11 +1,19 @@<?phprequire_once '../../includes/connect_endpoint.php';require_once '../../includes/validate_endpoint.php';+require_once '../../includes/logo_cleanup.php';$postData = file_get_contents("php://input");$data = json_decode($postData, true);$subscriptionId = $data["id"];++$logoStmt = $db->prepare("SELECT logo, logo_variant FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId");+$logoStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);+$logoStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+$logoResult = $logoStmt->execute();+$logoRow = $logoResult ? $logoResult->fetchArray(SQLITE3_ASSOC) : false;+$deleteQuery = "DELETE FROM subscriptions WHERE id = :subscriptionId AND user_id = :userId";$deleteStmt = $db->prepare($deleteQuery);$deleteStmt->bindParam(':subscriptionId', $subscriptionId, SQLITE3_INTEGER);@@ -18,6 +26,11 @@ if ($deleteStmt->execute()) {$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);$stmt->execute();+ if ($logoRow !== false) {+ deleteLogoFileIfUnused($db, $logoRow['logo'], '../../images/uploads/logos/');+ deleteLogoFileIfUnused($db, $logoRow['logo_variant'], '../../images/uploads/logos/');+ }+echo json_encode(["success" => true,"message" => translate('subscription_deleted', $i18n)@@ -28,4 +41,4 @@ if ($deleteStmt->execute()) {"message" => translate('error_deleting_subscription', $i18n)]);}-$db->close();\ No newline at end of file+$db->close();\ No newline at end of filediff --git a/includes/logo_cleanup.php b/includes/logo_cleanup.phpnew file mode 100644index 0000000..fdbb229--- /dev/null+++ b/includes/logo_cleanup.php@@ -0,0 +1,39 @@+<?php++// Deletes a logo file from the logos directory unless a subscription (logo or+// logo_variant) or a payment method (icon) still names it. clone.php copies a+// logo filename into a second row, so a file detached from one row can still+// be in use; the check runs across all users since the directory is shared.+// $filename is the bare name as stored (e.g. "1712-netflix.png"); $logosDir+// may or may not have a trailing slash.+function deleteLogoFileIfUnused($db, $filename, $logosDir)+{+ $filename = trim((string) $filename);+ if ($filename === '') {+ return;+ }++ // Never step outside the logos directory, whatever the stored value is.+ $filename = basename($filename);+ if ($filename === '' || $filename === '.' || $filename === '..') {+ return;+ }++ $stmt = $db->prepare(+ 'SELECT 1 FROM subscriptions WHERE logo = :name OR logo_variant = :name+ UNION ALL+ SELECT 1 FROM payment_methods WHERE icon = :name+ LIMIT 1'+ );+ $stmt->bindValue(':name', $filename, SQLITE3_TEXT);+ $result = $stmt->execute();++ if ($result && $result->fetchArray(SQLITE3_ASSOC)) {+ return; // still in use+ }++ $path = rtrim($logosDir, '/') . '/' . $filename;+ if (is_file($path)) {+ unlink($path);+ }+}diff --git a/tests/cases/account_deletion_test.php b/tests/cases/account_deletion_test.phpindex bf5cb7f..3b82ede 100644--- a/tests/cases/account_deletion_test.php+++ b/tests/cases/account_deletion_test.php@@ -2,14 +2,14 @@/*Deleting an account removes what belongs to it.- Both deletion paths — the self-service one and the administrator one — named+ Both deletion paths (the self-service one and the administrator one) namedtheir tables by hand, and the hand-written list had fallen twelve tablesbehind the schema. Two of the twelve hold credentials: `login_tokens` and`password_resets`.That is not only untidiness. The `user` table is declared`id INTEGER PRIMARY KEY` with no AUTOINCREMENT, so SQLite hands a deleted id- straight back to the next account created — and that account inherited the+ straight back to the next account created, and that account inherited theleftovers, including a remember-me token that still worked.The list below is read from the schema rather than written down again, so adiff --git a/tests/cases/logo_cleanup_test.php b/tests/cases/logo_cleanup_test.phpnew file mode 100644index 0000000..a9ca22c--- /dev/null+++ b/tests/cases/logo_cleanup_test.php@@ -0,0 +1,154 @@+<?php+// deleteLogoFileIfUnused() removes a detached logo file, but only when no other+// row still names it (clone.php shares a filename between two subscriptions).++require_once WALLOS_ROOT . '/includes/logo_cleanup.php';++// A logos directory holding the given files, under the test tmp tree.+function logo_cleanup_dir($files)+{+ $dir = WALLOS_TEST_TMP . '/logos-' . uniqid('', true) . '/';+ mkdir($dir, 0777, true);+ foreach ($files as $name) {+ file_put_contents($dir . $name, 'x');+ }+ return $dir;+}++function logo_cleanup_add_subscription($db, $userId, $logo, $variant = null)+{+ $stmt = $db->prepare('INSERT INTO subscriptions (user_id, name, price, currency_id, next_payment, cycle, frequency, inactive, logo, logo_variant)+ VALUES (:userId, :name, 1, :currencyId, :next, 3, 1, 0, :logo, :variant)');+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->bindValue(':name', 'sub-' . $logo, SQLITE3_TEXT);+ $stmt->bindValue(':currencyId', wallos_test_currency_id($userId, 0), SQLITE3_INTEGER);+ $stmt->bindValue(':next', date('Y-m-d', strtotime('+10 days')), SQLITE3_TEXT);+ $stmt->bindValue(':logo', $logo, SQLITE3_TEXT);+ $stmt->bindValue(':variant', $variant, $variant === null ? SQLITE3_NULL : SQLITE3_TEXT);+ $stmt->execute();+}++wallos_test('an unreferenced logo file is deleted', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ $dir = logo_cleanup_dir(['orphan.png']);+ deleteLogoFileIfUnused($db, 'orphan.png', $dir);++ assert_true(!file_exists($dir . 'orphan.png'), 'the orphan was removed');+ $db->close();+});++wallos_test('a logo still used by a subscription is kept', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');+ logo_cleanup_add_subscription($db, 1, 'used.png');++ $dir = logo_cleanup_dir(['used.png']);+ deleteLogoFileIfUnused($db, 'used.png', $dir);++ assert_true(file_exists($dir . 'used.png'), 'a referenced logo is not touched');+ $db->close();+});++wallos_test('a file still used only as a themed variant is kept', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');+ logo_cleanup_add_subscription($db, 1, 'logo.png', 'logo-variant.png');++ $dir = logo_cleanup_dir(['logo-variant.png']);+ deleteLogoFileIfUnused($db, 'logo-variant.png', $dir);++ assert_true(file_exists($dir . 'logo-variant.png'), 'the variant is still referenced');+ $db->close();+});++wallos_test('a logo shared by a clone survives deleting the original', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');+ // Two subscriptions naming the same file, as clone.php leaves them.+ logo_cleanup_add_subscription($db, 1, 'shared.png');+ logo_cleanup_add_subscription($db, 1, 'shared.png');++ // First one is deleted, then the endpoint asks to clean its logo.+ $db->exec("DELETE FROM subscriptions WHERE id = (SELECT MIN(id) FROM subscriptions WHERE logo = 'shared.png')");++ $dir = logo_cleanup_dir(['shared.png']);+ deleteLogoFileIfUnused($db, 'shared.png', $dir);+ assert_true(file_exists($dir . 'shared.png'), 'the clone still uses it');++ // Now the clone goes too.+ $db->exec("DELETE FROM subscriptions WHERE logo = 'shared.png'");+ deleteLogoFileIfUnused($db, 'shared.png', $dir);+ assert_true(!file_exists($dir . 'shared.png'), 'nothing references it any more');++ $db->close();+});++wallos_test('a logo still used by a payment method is kept', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');+ $db->exec("INSERT INTO payment_methods (name, icon, enabled, user_id) VALUES ('Card', 'pm-icon.png', 1, 1)");++ $dir = logo_cleanup_dir(['pm-icon.png']);+ deleteLogoFileIfUnused($db, 'pm-icon.png', $dir);++ assert_true(file_exists($dir . 'pm-icon.png'), 'a payment method icon is not an orphan');+ $db->close();+});++wallos_test('deleting an account clears its logos but not another account\'s', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 2, 'alice');+ wallos_test_create_user($db, 3, 'bob');++ logo_cleanup_add_subscription($db, 2, 'alice-1.png', 'alice-1-variant.png');+ logo_cleanup_add_subscription($db, 2, 'alice-2.png');+ logo_cleanup_add_subscription($db, 3, 'bob-1.png');+ $db->exec("INSERT INTO payment_methods (name, icon, enabled, user_id) VALUES ('Card', 'alice-pm.png', 1, 2)");+ $db->exec("INSERT INTO payment_methods (name, icon, enabled, user_id) VALUES ('Cash', 'images/uploads/icons/cash.png', 1, 2)");++ $dir = logo_cleanup_dir(['alice-1.png', 'alice-1-variant.png', 'alice-2.png', 'alice-pm.png', 'bob-1.png']);++ // What endpoints/settings/deleteaccount.php does: gather, delete rows, sweep.+ $files = [];+ $r = $db->query('SELECT logo, logo_variant FROM subscriptions WHERE user_id = 2');+ while ($row = $r->fetchArray(SQLITE3_ASSOC)) {+ $files[] = $row['logo'];+ $files[] = $row['logo_variant'];+ }+ $r = $db->query("SELECT icon FROM payment_methods WHERE user_id = 2 AND icon NOT LIKE 'images/uploads/icons/%'");+ while ($row = $r->fetchArray(SQLITE3_ASSOC)) {+ $files[] = $row['icon'];+ }+ $db->exec('DELETE FROM subscriptions WHERE user_id = 2');+ $db->exec('DELETE FROM payment_methods WHERE user_id = 2');+ foreach (array_unique(array_filter($files)) as $file) {+ deleteLogoFileIfUnused($db, $file, $dir);+ }++ assert_true(!file_exists($dir . 'alice-1.png'), 'account logo removed');+ assert_true(!file_exists($dir . 'alice-1-variant.png'), 'account logo variant removed');+ assert_true(!file_exists($dir . 'alice-2.png'), 'second account logo removed');+ assert_true(!file_exists($dir . 'alice-pm.png'), 'account payment method icon removed');+ assert_true(file_exists($dir . 'bob-1.png'), 'the other account keeps its logo');++ $db->close();+});++wallos_test('the helper stays inside the logos directory', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ $dir = logo_cleanup_dir([]);+ $outside = dirname(rtrim($dir, '/')) . '/keep.png';+ file_put_contents($outside, 'x');++ deleteLogoFileIfUnused($db, '../keep.png', $dir);+ assert_true(file_exists($outside), 'a traversal path does not escape the directory');++ deleteLogoFileIfUnused($db, '', $dir);+ deleteLogoFileIfUnused($db, null, $dir);++ $db->close();+});diff --git a/tests/cases/theme_cookie_test.php b/tests/cases/theme_cookie_test.phpindex 0ebea66..80fb917 100644--- a/tests/cases/theme_cookie_test.php+++ b/tests/cases/theme_cookie_test.php@@ -8,7 +8,7 @@window.colorTheme = "<?= $colorTheme ?>";a cookie value containing a double quote closes the string and the rest is- script — reflected XSS against anyone who can put a cookie on the origin.+ script: reflected XSS against anyone who can put a cookie on the origin.5.5.0 fixed this by validating both cookies against a fixed list and encodingwhat is emitted, in login.php, totp.php and includes/header.php.