Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
fix(payments): report why a logo could not be fetched instead of "Unknown error" (#1200)
thorstenhornung1a0bf7e70fd15
diff --git a/api/payment_methods/set_payment_methods.php b/api/payment_methods/set_payment_methods.phpindex d4f3379..c00742f 100644--- a/api/payment_methods/set_payment_methods.php+++ b/api/payment_methods/set_payment_methods.php@@ -149,7 +149,7 @@ function getLogoFromUrl($url, $uploadDir, $name, $settings)if (saveLogo($imageData, $uploadFile, $name, $settings)) {unset($ch);- return $fileName;+ return ["success" => true, "filename" => $fileName];}}@@ -157,7 +157,7 @@ function getLogoFromUrl($url, $uploadDir, $name, $settings)break;}- return "";+ return ["success" => false, "message" => "Failed to fetch image."];}function saveLogo($imageData, $uploadFile, $name, $settings)@@ -283,7 +283,24 @@ switch ($action) {$icon = "";if ($iconUrl !== "") {- $icon = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name, $settings);+ // Three return types out of one function: a filename on success, an+ // array on two of the failure paths and an empty string on the+ // third. Unchecked, the array reached bindParam() as the icon and+ // the insert failed. Both subscription copies of this helper answer+ // ['success' => bool, 'filename'|'message'] and are checked; this is+ // that shape (closes #1185).+ $result = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name, $settings);++ if (empty($result['success'])) {+ echo json_encode([+ 'success' => false,+ 'title' => 'Icon could not be fetched',+ 'message' => $result['message'] ?? 'The icon URL could not be fetched.'+ ]);+ exit;+ }++ $icon = $result['filename'];} elseif (!empty($_FILES['paymenticon']['name'])) {$fileType = mime_content_type($_FILES['paymenticon']['tmp_name']);if (strpos($fileType, 'image') === false) {@@ -392,7 +409,21 @@ switch ($action) {$iconUrl = $_POST['icon_url'] ?? $_POST['icon-url'] ?? '';if ($iconUrl !== "") {- $icon = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name, $settings);+ // The worst of the three: $icon holds the method's current icon at+ // this point, so an unchecked failure did not merely fail to fetch+ // a new one, it overwrote a working icon with the failure array.+ $result = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name, $settings);++ if (empty($result['success'])) {+ echo json_encode([+ 'success' => false,+ 'title' => 'Icon could not be fetched',+ 'message' => $result['message'] ?? 'The icon URL could not be fetched.'+ ]);+ exit;+ }++ $icon = $result['filename'];} elseif (!empty($_FILES['paymenticon']['name'])) {$fileType = mime_content_type($_FILES['paymenticon']['tmp_name']);if (strpos($fileType, 'image') === false) {diff --git a/endpoints/payments/add.php b/endpoints/payments/add.phpindex 3374b3d..8e083a4 100644--- a/endpoints/payments/add.php+++ b/endpoints/payments/add.php@@ -75,7 +75,7 @@ function getLogoFromUrl($url, $uploadDir, $name, $i18n, $settings)if (saveLogo($imageData, $uploadFile, $name, $settings)) {unset($ch);- return $fileName;+ return ["success" => true, "filename" => $fileName];}}@@ -217,7 +217,28 @@ if ($name === "" || ($iconUrl === "" && empty($_FILES['paymenticon']['name'])))$icon = "";if ($iconUrl !== "") {- $icon = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name, $i18n, $settings);+ // getLogoFromUrl() reported failure as an array and success as a bare+ // string, and neither the caller nor the bind below looked. The array went+ // into the icon column, the insert failed, and this endpoint answered with+ // a plain-text error the page cannot read, so the user saw "Unknown+ // error, please try again" while the reason the helper had already worked+ // out was thrown away, and error_reporting above kept the warning out of+ // the log (closes #1185).+ //+ // Both subscription copies of this helper already answer+ // ['success' => bool, 'filename'|'message'] and are checked at the call+ // site; this is that shape.+ $result = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name, $i18n, $settings);++ if (empty($result['success'])) {+ echo json_encode([+ "success" => false,+ "message" => $result['message'] ?? translate('error', $i18n)+ ]);+ exit();+ }++ $icon = $result['filename'];} else {if (!empty($_FILES['paymenticon']['name'])) {$fileType = mime_content_type($_FILES['paymenticon']['tmp_name']);diff --git a/tests/cases/logo_fetch_result_test.php b/tests/cases/logo_fetch_result_test.phpnew file mode 100644index 0000000..97fd908--- /dev/null+++ b/tests/cases/logo_fetch_result_test.php@@ -0,0 +1,119 @@+<?php+/*+ One answer shape for getLogoFromUrl(), and a caller that reads it.++ Four files carry their own copy of this helper. The two subscription copies+ answered ['success' => bool, 'filename'|'message'] and were checked at the+ call site. The two payment copies answered a bare filename on success, an+ array on some failures and an empty string on another, and no caller looked.+ The array was bound as the icon column, the insert failed, and the endpoint+ answered with text the page cannot parse, so the user saw "Unknown error,+ please try again" with nothing in the log (#1185).++ A structural guard rather than a behavioural one: the helper needs a network+ and an image library to run, and the defect was never in the fetching. It was+ in the shape of the answer and in nobody reading it. That is visible in the+ source, and it is what a fifth copy would get wrong too.+*/++/**+ * The files that carry a copy of the helper.+ *+ * @return string[]+ */+function logo_fetch_files()+{+ return [+ 'endpoints/payments/add.php',+ 'endpoints/subscription/add.php',+ 'api/payment_methods/set_payment_methods.php',+ 'api/subscriptions/set_subscriptions.php',+ ];+}++/**+ * The body of getLogoFromUrl() alone.+ *+ * Scoped deliberately: these files also hold resizeAndUploadLogo(), which+ * returns a bare filename and is right to; it is not the function whose+ * answer nobody could read. A file-wide search flagged all four copies,+ * including the two that were already correct.+ *+ * @param string $source+ * @return string+ */+function logo_fetch_helper_body($source)+{+ $start = strpos($source, 'function getLogoFromUrl(');++ if ($start === false) {+ return '';+ }++ // Up to the next brace in the first column, which closes the function:+ // everything inside it is indented.+ $end = strpos($source, "\n}", $start);++ return $end === false ? substr($source, $start) : substr($source, $start, $end - $start);+}++wallos_test('every copy of the logo fetch answers in the same shape', function () {+ $checked = 0;++ foreach (logo_fetch_files() as $path) {+ $source = file_get_contents(WALLOS_ROOT . '/' . $path);+ $body = logo_fetch_helper_body($source);++ assert_true($body !== '', $path . ' carries a copy of the helper');+ $checked++;++ // Success says so, and names the file it saved under.+ assert_true(preg_match('/["\']success["\']\s*=>\s*true/', $body) === 1,+ $path . ' answers success as ["success" => true, "filename" => ...]');++ // The two shapes that cannot be told apart by the caller.+ assert_true(preg_match('/return\s+\$fileName\s*;/', $body) !== 1,+ $path . ' does not return a bare filename, which a caller cannot '+ . 'distinguish from a failure array');+ assert_true(preg_match('/return\s+["\']{2}\s*;/', $body) !== 1,+ $path . ' does not return an empty string, which a caller reads as '+ . 'a logo it successfully did not fetch');+ }++ // A guard that finds nothing passes every assertion above it.+ assert_same(4, $checked, 'all four copies were found and checked');+});++wallos_test('every caller reads the answer before using it', function () {+ $callSites = 0;++ foreach (logo_fetch_files() as $path) {+ $source = file_get_contents(WALLOS_ROOT . '/' . $path);+ $lines = preg_split('/\R/', $source);++ foreach ($lines as $number => $line) {+ // The definition is not a call site.+ if (strpos($line, 'function getLogoFromUrl(') !== false) {+ continue;+ }++ if (preg_match('/(\$[A-Za-z_][A-Za-z0-9_]*)\s*=\s*getLogoFromUrl\s*\(/', $line, $match) !== 1) {+ continue;+ }++ $callSites++;+ $variable = $match[1];++ // The check has to come before the value is used, and the value is+ // used within a few lines everywhere this appears.+ $window = implode("\n", array_slice($lines, $number, 14));+ $quoted = preg_quote($variable, '/');++ assert_true(preg_match('/' . $quoted . '\s*\[\s*["\']success["\']\s*\]/', $window) === 1,+ $path . ' line ' . ($number + 1) . ': ' . $variable+ . " is checked for ['success'] before it is used");+ }+ }++ assert_same(6, $callSites, 'all six call sites were found and checked');+});