Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
feat(currency): add frankfurter.dev as a provider that needs no account
thorstenhornung1dd7cf87d5a0b
diff --git a/api/fixer/get_fixer.php b/api/fixer/get_fixer.phpindex 7ca1971..433d929 100644--- a/api/fixer/get_fixer.php+++ b/api/fixer/get_fixer.php@@ -62,8 +62,9 @@ if ($_SERVER["REQUEST_METHOD"] === "POST" || $_SERVER["REQUEST_METHOD"] === "GET$userId = $user['id'];$providers = [0 => "Fixer.io",- 1 => "APILayer.com"- ];+ 1 => "APILayer.com",+ 2 => "Frankfurter"+ ];$query = "SELECT * FROM fixer WHERE user_id = :userId";$stmt = $db->prepare($query);diff --git a/api/fixer/set_fixer.php b/api/fixer/set_fixer.phpindex d9cada8..353da42 100644--- a/api/fixer/set_fixer.php+++ b/api/fixer/set_fixer.php@@ -4,7 +4,9 @@ This API Endpoint accepts POST requests only.It receives the following parameters:- api_key: the API key of the user (for Wallos authentication).- fixer_api_key: the Fixer.io or APILayer API key to save (optional; if empty/omitted, clears the key).-- provider: the provider type (optional; '0' for Fixer.io, '1' for APILayer.com, defaults to '0').+ Not read for provider '2', which needs no account.+- provider: the provider type (optional; '0' for Fixer.io, '1' for APILayer.com, '2' for+ Frankfurter, defaults to '0').It returns a JSON object with the following properties:- success: whether the request was successful (boolean).@@ -63,16 +65,73 @@ $userId = $user['id'];$fixerApiKey = isset($_POST['fixer_api_key']) ? trim($_POST['fixer_api_key']) : '';$provider = $_POST['provider'] ?? '0';-if (!in_array($provider, ['0', '1', 0, 1], true)) {+if (!in_array($provider, ['0', '1', '2', 0, 1, 2], true)) {echo json_encode(['success' => false,'title' => 'Invalid provider',- 'message' => 'Provider must be 0 (Fixer.io) or 1 (APILayer.com).'+ 'message' => 'Provider must be 0 (Fixer.io), 1 (APILayer.com) or 2 (Frankfurter).']);exit;}$provider = intval($provider);+// frankfurter.dev publishes the ECB reference rates without an account, so an+// empty key on this provider is not an unconfigured one: choosing it is the+// whole configuration, and there is nothing to send anywhere to validate.+//+// Which is why it has to be decided before the clearing path below, where an+// empty key means "remove my settings" - the two would otherwise read the same+// request in opposite ways.+//+// The row is updated rather than deleted and reinserted, so that a key stored+// for one of the other two providers is still there to switch back to.+if ($provider === 2) {+ $updateSql = "UPDATE fixer SET provider = :provider WHERE user_id = :userId";+ $updateStmt = $db->prepare($updateSql);+ $updateStmt->bindValue(':provider', 2, SQLITE3_INTEGER);+ $updateStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $updateResult = $updateStmt->execute();++ if ($updateResult === false) {+ echo json_encode([+ 'success' => false,+ 'title' => 'Database error',+ 'message' => 'Failed to save Fixer API settings.'+ ]);+ $db->close();+ exit;+ }++ if ($db->changes() === 0) {+ // Nothing stored yet: the account that never registered anywhere, which+ // is the case this provider exists for. An empty api_key goes in, and+ // the row is what every reader takes for "a provider is configured".+ $insertSql = "INSERT INTO fixer (api_key, provider, user_id) VALUES (:api_key, :provider, :userId)";+ $insertStmt = $db->prepare($insertSql);+ $insertStmt->bindValue(':api_key', '', SQLITE3_TEXT);+ $insertStmt->bindValue(':provider', 2, SQLITE3_INTEGER);+ $insertStmt->bindValue(':userId', $userId, SQLITE3_INTEGER);++ if ($insertStmt->execute() === false) {+ echo json_encode([+ 'success' => false,+ 'title' => 'Database error',+ 'message' => 'Failed to save Fixer API settings.'+ ]);+ $db->close();+ exit;+ }+ }++ echo json_encode([+ 'success' => true,+ 'title' => 'Fixer settings updated',+ 'message' => 'Frankfurter is now the currency rate provider. It needs no API key.'+ ]);+ $db->close();+ exit;+}+// If key is empty, clear the settingsif ($fixerApiKey === '') {$removeSql = "DELETE FROM fixer WHERE user_id = :userId";diff --git a/endpoints/cronjobs/updateexchange.php b/endpoints/cronjobs/updateexchange.phpindex e1bd456..9211550 100644--- a/endpoints/cronjobs/updateexchange.php+++ b/endpoints/cronjobs/updateexchange.php@@ -2,6 +2,7 @@require_once 'validate.php';require_once __DIR__ . '/../../includes/connect_endpoint_crontabs.php';require_once __DIR__ . '/../../includes/exchange_rate_freshness.php';+require_once __DIR__ . '/../../includes/frankfurter.php';require 'settimezone.php';@@ -58,7 +59,18 @@ while ($userToUpdateExchange = $usersToUpdateExchange->fetchArray(SQLITE3_ASSOC)$mainCurrencyCode = $row['code'];$mainCurrencyId = $row['main_currency'];- if ($provider === 1) {+ if ((int) $provider === 2) {+ // frankfurter.dev publishes the ECB reference rates without an+ // account, and prices in any currency it lists, so it is asked+ // in the user's own main currency and the conversion below has+ // nothing left to do. No key, no header, and https, because+ // there is no account behind it to authenticate.+ //+ // The helper answers in the same {"rates": ...} shape the two+ // providers below do, so everything after this branch is+ // unchanged.+ $apiData = frankfurter_latest_rates($mainCurrencyCode, $codes);+ } elseif ($provider === 1) {$api_url = "https://api.apilayer.com/fixer/latest?base=EUR&symbols=" . $codes;$context = stream_context_create(['http' => [@@ -67,14 +79,22 @@ while ($userToUpdateExchange = $usersToUpdateExchange->fetchArray(SQLITE3_ASSOC)]]);$response = file_get_contents($api_url, false, $context);+ $apiData = json_decode($response, true);} else {$api_url = "http://data.fixer.io/api/latest?access_key=" . $apiKey . "&base=EUR&symbols=" . $codes;$response = file_get_contents($api_url);+ $apiData = json_decode($response, true);}- $apiData = json_decode($response, true);-- $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];+ if ((int) $provider === 2) {+ // The answer already is in the main currency, so there is+ // nothing to divide through by. The loop below still writes the+ // main currency's own row as 1.0, which is a rule of this+ // application rather than a number read out of a response.+ $mainCurrencyToEUR = 1.0;+ } else {+ $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];+ }if ($apiData !== null && isset($apiData['rates'])) {// One user's rates and their refresh date are one unit of work:@@ -130,6 +150,23 @@ while ($userToUpdateExchange = $usersToUpdateExchange->fetchArray(SQLITE3_ASSOC)echo "Rates updated successfully!<br />";}+ } else {+ // A refresh that stored nothing must not pass for one that+ // worked. This branch had no else at all, so a provider+ // answering with no rates moved on to the next user without a+ // word, and the only trace left was that the stored rates had+ // not moved.+ $failureMessage = "Exchange rates update failed. The currency provider returned no rates.";++ if (is_array($apiData) && isset($apiData['message']) && is_string($apiData['message'])) {+ // frankfurter.dev explains itself in the body - it answers+ // 422 with {"message":"invalid currency: XYZ"} and names the+ // one code it objected to - and its own wording says more+ // than a guess made here would.+ $failureMessage .= " " . htmlspecialchars($apiData['message']);+ }++ echo $failureMessage . "<br />";}} else {echo "Exchange rates update skipped. No fixer.io api key provided<br />";diff --git a/endpoints/currency/fixer_api_key.php b/endpoints/currency/fixer_api_key.phpindex 5696fa2..331616f 100644--- a/endpoints/currency/fixer_api_key.php+++ b/endpoints/currency/fixer_api_key.php@@ -5,6 +5,57 @@ require_once '../../includes/validate_endpoint.php';$newApiKey = isset($_POST["api_key"]) ? trim($_POST["api_key"]) : "";$provider = isset($_POST["provider"]) ? $_POST["provider"] : 0;+// frankfurter.dev serves the ECB reference rates without an account, so there+// is no key to check and nothing to ask it: choosing it is the whole+// configuration, and a validation request here would only be a request spent+// proving that an empty string is still empty - and one that fails the save+// whenever the provider happens to be down.+//+// The row is updated rather than replaced. The key stored in it belongs to the+// provider the user is switching away from and is the one they switch back to,+// so the delete below - which runs before anything is known about whether the+// save will succeed - must not be on this path.+if ($provider == 2) {+ $setProvider = "UPDATE fixer SET provider = :provider WHERE user_id = :userId";+ $stmt = $db->prepare($setProvider);+ $stmt->bindValue(":provider", 2, SQLITE3_INTEGER);+ $stmt->bindValue(":userId", $userId, SQLITE3_INTEGER);++ if ($stmt->execute() === false) {+ echo json_encode([+ "success" => false,+ "message" => translate('failed_to_store_api_key', $i18n)+ ]);+ exit;+ }++ if ($db->changes() === 0) {+ // Nothing stored yet. This is the account that never registered+ // anywhere, which is the case this provider exists for, so an empty+ // api_key is written and counts as configured from here on. The posted+ // key is not read on this path at all, so it is not carried in either.+ $insertProvider = "INSERT INTO fixer (api_key, provider, user_id) VALUES (:api_key, :provider, :userId)";+ $stmt = $db->prepare($insertProvider);+ $stmt->bindValue(":api_key", "", SQLITE3_TEXT);+ $stmt->bindValue(":provider", 2, SQLITE3_INTEGER);+ $stmt->bindValue(":userId", $userId, SQLITE3_INTEGER);++ if ($stmt->execute() === false) {+ echo json_encode([+ "success" => false,+ "message" => translate('failed_to_store_api_key', $i18n)+ ]);+ exit;+ }+ }++ echo json_encode([+ "success" => true,+ "message" => translate('currency_provider_saved', $i18n)+ ]);+ exit;+}+// The insert further down replaces this row and its result decides the answer;// this one's was dropped. Two rows in fixer for one user means the exchange// rate update reads whichever key it is handed first, which can be the one thediff --git a/endpoints/currency/update_exchange.php b/endpoints/currency/update_exchange.phpindex 1fb0c03..efa6875 100644--- a/endpoints/currency/update_exchange.php+++ b/endpoints/currency/update_exchange.php@@ -2,6 +2,7 @@require_once '../../includes/connect_endpoint.php';require_once '../../includes/validate_endpoint.php';require_once '../../includes/exchange_rate_freshness.php';+require_once '../../includes/frankfurter.php';$shouldUpdate = true;@@ -49,7 +50,17 @@ if ($result) {$mainCurrencyCode = $row['code'];$mainCurrencyId = $row['main_currency'];- if ($provider === 1) {+ if ((int) $provider === 2) {+ // frankfurter.dev publishes the ECB reference rates without an+ // account, and prices in any currency it lists, so it is asked in+ // the user's own main currency and the conversion below has nothing+ // left to do. No key, no header, and https, because there is no+ // account behind it to authenticate.+ //+ // The helper answers in the same {"rates": ...} shape the two+ // providers below do, so everything after this branch is unchanged.+ $apiData = frankfurter_latest_rates($mainCurrencyCode, $codes);+ } elseif ($provider === 1) {$api_url = "https://api.apilayer.com/fixer/latest?base=EUR&symbols=" . $codes;$context = stream_context_create(['http' => [@@ -58,6 +69,7 @@ if ($result) {]]);$response = file_get_contents($api_url, false, $context);+ $apiData = json_decode($response, true);// Piggyback on this request to record the monthly quota apilayer// reports in its response headers (shown on the settings page).@@ -84,11 +96,18 @@ if ($result) {} else {$api_url = "http://data.fixer.io/api/latest?access_key=" . $apiKey . "&base=EUR&symbols=" . $codes;$response = file_get_contents($api_url);+ $apiData = json_decode($response, true);}- $apiData = json_decode($response, true);-- $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];+ if ((int) $provider === 2) {+ // The answer already is in the main currency, so there is nothing+ // to divide through by. The loop below still writes the main+ // currency's own row as 1.0, which is a rule of this application+ // rather than a number read out of a response.+ $mainCurrencyToEUR = 1.0;+ } else {+ $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];+ }if ($apiData !== null && isset($apiData['rates'])) {// The rates and the refresh date are one unit of work: a failure@@ -139,6 +158,22 @@ if ($result) {$db->close();echo "Rates updated successfully!";}+ } else {+ // A refresh that stored nothing must not pass for one that worked.+ // This branch had no else at all, so a provider answering with no+ // rates ended the request without a word, and the only trace left+ // was that the stored rates had not moved.+ $failureMessage = "Exchange rates update failed. The currency provider returned no rates.";++ if (is_array($apiData) && isset($apiData['message']) && is_string($apiData['message'])) {+ // frankfurter.dev explains itself in the body - it answers 422+ // with {"message":"invalid currency: XYZ"} and names the one+ // code it objected to - and its own wording says more than a+ // guess made here would.+ $failureMessage .= " " . htmlspecialchars($apiData['message']);+ }++ echo $failureMessage;}} else {echo "Exchange rates update skipped. No fixer.io api key provided";diff --git a/endpoints/user/save_user.php b/endpoints/user/save_user.phpindex e4948d6..1c562b8 100644--- a/endpoints/user/save_user.php+++ b/endpoints/user/save_user.php@@ -2,6 +2,7 @@require_once '../../includes/connect_endpoint.php';require_once '../../includes/inputvalidation.php';require_once '../../includes/validate_endpoint.php';+require_once '../../includes/frankfurter.php';if (!file_exists('../../images/uploads/logos')) {mkdir('../../images/uploads/logos', 0777, true);@@ -38,7 +39,18 @@ function update_exchange_rate($db, $userId)$mainCurrencyCode = $row['code'];$mainCurrencyId = $row['main_currency'];- if ($provider === 1) {+ if ((int) $provider === 2) {+ // frankfurter.dev publishes the ECB reference rates without an+ // account, and prices in any currency it lists, so it is asked+ // in the user's own main currency and the conversion below has+ // nothing left to do. No key, no header, and https, because+ // there is no account behind it to authenticate.+ //+ // The helper answers in the same {"rates": ...} shape the two+ // providers below do, so everything after this branch is+ // unchanged.+ $apiData = frankfurter_latest_rates($mainCurrencyCode, $codes);+ } elseif ($provider === 1) {$api_url = "https://api.apilayer.com/fixer/latest?base=EUR&symbols=" . $codes;$context = stream_context_create(['http' => [@@ -47,14 +59,22 @@ function update_exchange_rate($db, $userId)]]);$response = file_get_contents($api_url, false, $context);+ $apiData = json_decode($response, true);} else {$api_url = "http://data.fixer.io/api/latest?access_key=" . $apiKey . "&base=EUR&symbols=" . $codes;$response = file_get_contents($api_url);+ $apiData = json_decode($response, true);}- $apiData = json_decode($response, true);-- $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];+ if ((int) $provider === 2) {+ // The answer already is in the main currency, so there is+ // nothing to divide through by. The loop below still writes the+ // main currency's own row as 1.0, which is a rule of this+ // application rather than a number read out of a response.+ $mainCurrencyToEUR = 1.0;+ } else {+ $mainCurrencyToEUR = $apiData['rates'][$mainCurrencyCode];+ }if ($apiData !== null && isset($apiData['rates'])) {foreach ($apiData['rates'] as $currencyCode => $rate) {diff --git a/includes/frankfurter.php b/includes/frankfurter.phpnew file mode 100644index 0000000..0e63b90--- /dev/null+++ b/includes/frankfurter.php@@ -0,0 +1,257 @@+<?php+/*+ frankfurter.dev, the exchange rate provider that needs no account.++ Both providers Wallos had before are reached with a key the user has to+ register for. Until somebody does, a household running one subscription in+ CHF and one in EUR has no converted total at all: the rate rows keep whatever+ they were seeded with, and the statistics quietly add francs to euros.+ frankfurter.dev publishes the ECB reference rates over https with no account,+ which makes it a provider that is configured by being chosen.++ Three places fetch rates - the manual endpoint, the scheduled job, and the+ save that runs when the main currency changes - and all three read the+ {"rates": {CODE: rate}} shape the other two providers answer in. Frankfurter's+ v2 API does not answer in that shape, so the translation lives here once+ rather than three times, and frankfurter_latest_rates() hands the call sites+ back the shape they already speak.++ Everything below the request is a pure function of the decoded body, so the+ behaviour can be tested without a socket.+*/++if (!function_exists('frankfurter_http_get')) {+ /**+ * The one network touch in this file, separated so a test can stand in for+ * the provider without making a request. A test defines its own version+ * before this file is loaded; the guard lets that stand.+ *+ * @param string $url+ * @param resource $context+ * @return array{body: string|false, headers: array|null}+ */+ function frankfurter_http_get($url, $context)+ {+ $body = @file_get_contents($url, false, $context);++ // PHP populates this only when an HTTP response actually arrived, which+ // is what separates a refusal from an outage.+ return [+ 'body' => $body,+ 'headers' => isset($http_response_header) ? $http_response_header : null,+ ];+ }+}++/**+ * The status code of the response that finally answered.+ *+ * @param array|null $headers Typically $http_response_header.+ * @return int|null Null when no HTTP response arrived at all.+ */+function frankfurter_status_code($headers)+{+ if (!is_array($headers)) {+ return null;+ }++ $status = null;++ foreach ($headers as $header) {+ // Redirects append each hop's headers to the same array, so the last+ // status line is the one describing the response actually received.+ if (preg_match('#^HTTP/\d(?:\.\d)?\s+(\d{3})#i', (string) $header, $match)) {+ $status = (int) $match[1];+ }+ }++ return $status;+}++/**+ * Turns the /v2/rates answer into the code => rate map the call sites read.+ *+ * v2 answers with a flat array of records - [{"date":"2026-09-13","base":"CHF",+ * "quote":"EUR","rate":1.0593}, ...] - rather than with the {"rates":{...}}+ * object of the retired api.frankfurter.app, which answers 301 now.+ *+ * An empty array is the trap worth naming. An unknown base is not an error+ * there, it is HTTP 200 with `[]` (measured 2026-09-13 with base=BTC). That+ * decodes to a perfectly good array, so a caller checking only is_array() calls+ * it a success, stores nothing, and marks the rates refreshed - after which the+ * freshness check hides it until tomorrow. Null here, and the caller treats it+ * as the refusal it is.+ *+ * @param mixed $decoded json_decode(..., true) of the response body.+ * @return array<string, float>|null Null when the answer is not usable.+ */+function frankfurter_rates($decoded)+{+ if (!is_array($decoded) || $decoded === []) {+ return null;+ }++ $rates = [];++ foreach ($decoded as $record) {+ if (!is_array($record) || !isset($record['quote'], $record['rate'])) {+ // Not the shape v2 documents. One malformed record is not a reason+ // to discard the rest, but a body made entirely of them leaves+ // $rates empty and is refused below.+ continue;+ }++ $rates[strtoupper((string) $record['quote'])] = (float) $record['rate'];+ }++ return $rates === [] ? null : $rates;+}++/**+ * The explanation Frankfurter puts in its own body.+ *+ * Its errors are {"status":422,"message":"invalid currency: TOOLONG"}, which is+ * neither the {"error":{"info":...}} of fixer nor the {"success":false} the+ * save endpoints look for. The provider names the one code it objected to, and+ * that is the only thing in the whole response that says which currency row is+ * the reason nothing refreshed.+ *+ * @param mixed $decoded json_decode(..., true) of the response body.+ * @return string Empty when the body says nothing useful.+ */+function frankfurter_detail($decoded)+{+ if (!is_array($decoded) || !isset($decoded['message']) || !is_string($decoded['message'])) {+ return '';+ }++ return trim($decoded['message']);+}++/**+ * The currency codes safe to put in a request, and the ones left behind.+ *+ * Measured 2026-09-13: a single malformed code answers 422 and takes the whole+ * request with it - `quotes=USD,XX!` returns nothing at all, not USD. A+ * currency in Wallos is three free-text fields, so an invented code is accepted+ * and stored, and one of those would otherwise stop every other currency in the+ * same account from refreshing. So the malformed codes are held back before the+ * request rather than being allowed to refuse it.+ *+ * This is a filter on the shape of the code, not on the catalogue: a+ * well-formed code Frankfurter does not price is left in, because it cannot be+ * recognised from here. What happens to it then is the provider's business, and+ * it goes both ways - measured on the same day, `quotes=EUR,BTC` answers 200+ * with EUR alone and drops BTC in silence, while `quotes=EUR,ETH` answers 422+ * and names ETH. The first leaves that currency at the rate it already had; the+ * second is why the message from the body is worth reporting.+ *+ * @param string[] $codes+ * @return array{0: string[], 1: string[]} Accepted codes, then rejected ones.+ */+function frankfurter_partition_codes($codes)+{+ $accepted = [];+ $rejected = [];++ foreach ($codes as $code) {+ if (preg_match('/^[A-Za-z]{3}$/', (string) $code)) {+ $accepted[] = strtoupper((string) $code);+ } else {+ $rejected[] = (string) $code;+ }+ }++ return [$accepted, $rejected];+}++/**+ * Why a request failed, in terms the person reading the refresh output can act+ * on.+ *+ * @param int|null $status Result of frankfurter_status_code().+ * @param mixed $decoded json_decode(..., true) of the response body.+ * @param string $base The base currency the request asked for.+ * @return string+ */+function frankfurter_failure_message($status, $decoded, $base)+{+ $detail = frankfurter_detail($decoded);++ if ($status === null) {+ // No response at all: DNS, a refused connection, a timeout.+ return 'The currency provider could not be reached.';+ }++ if ($status >= 500) {+ $message = 'The currency provider reported a fault of its own (HTTP ' . $status . ').';+ } elseif ($status >= 400) {+ $message = 'The currency provider refused the request (HTTP ' . $status . ').';+ } elseif ($detail === '') {+ // A 200 with an empty list is what a base it does not price answers+ // with. The generic wording would send the reader looking for an outage+ // instead of at the one currency that caused it.+ return 'The currency provider does not price ' . $base . ' as a base currency.';+ } else {+ $message = 'The currency provider returned an error.';+ }++ if ($detail !== '') {+ $message .= ' It said: ' . $detail;+ }++ return $message;+}++/**+ * Today's rates for one base currency, in the shape the fetch sites read.+ *+ * The provider prices in any currency it lists, so it is asked in the user's+ * own main currency and there is nothing left to convert afterwards - unlike+ * fixer's free tier, which prices in EUR whatever it is asked for and leaves+ * every caller to divide through by the main currency's own rate.+ *+ * @param string $base The user's main currency code.+ * @param string $codes Comma separated currency codes.+ * @return array{rates?: array<string, float>, message?: string} 'rates' on+ * success, 'message' on a refusal - the two keys the callers already+ * branch on.+ */+function frankfurter_latest_rates($base, $codes)+{+ $base = strtoupper(trim((string) $base));+ $requested = array_filter(array_map('trim', explode(',', (string) $codes)), 'strlen');+ list($askFor, $rejected) = frankfurter_partition_codes($requested);++ if ($askFor === []) {+ // Nothing the provider could be asked about. Sent anyway, an empty+ // quotes list answers 200 with `[]`, which is the same body an unknown+ // base returns and would be reported as one.+ return [+ 'message' => 'No currency code in this account can be asked of the currency provider'+ . ($rejected === [] ? '.' : ': ' . implode(', ', $rejected) . '.'),+ ];+ }++ $apiUrl = 'https://api.frankfurter.dev/v2/rates?base=' . rawurlencode($base)+ . '"es=' . rawurlencode(implode(',', $askFor));+ $context = stream_context_create([+ 'http' => [+ 'method' => 'GET',+ // Without this a 422 arrives as false and is indistinguishable from+ // the network being down, and the provider's own explanation of+ // which currency it objected to is lost with the body.+ 'ignore_errors' => true,+ ]+ ]);++ $http = frankfurter_http_get($apiUrl, $context);+ $decoded = json_decode((string) $http['body'], true);+ $rates = frankfurter_rates($decoded);++ if ($rates === null) {+ return ['message' => frankfurter_failure_message(frankfurter_status_code($http['headers']), $decoded, $base)];+ }++ return ['rates' => $rates];+}diff --git a/includes/i18n/en.php b/includes/i18n/en.phpindex e1d214d..a016790 100644--- a/includes/i18n/en.php+++ b/includes/i18n/en.php@@ -295,6 +295,7 @@ $i18n = ["get_key" => "Get your key at","get_free_fixer_api_key" => "Get free Fixer API Key","get_key_alternative" => "Alternatively, you can get a free fixer api key from",+ "no_api_key_provider" => "Or select a provider that needs no account and no API key, and leave the key empty:","ai_model" => "AI Model","select_ai_model" => "Select AI Model","run_schedule" => "Run Schedule",@@ -397,6 +398,7 @@ $i18n = ["failed_to_store_api_key" => "Failed to store API Key on the Database.","invalid_api_key" => "Invalid API Key.","api_key_saved" => "API key saved successfully",+ "currency_provider_saved" => "Currency provider saved successfully","currency_removed" => "Currency removed",// Household"failed_add_household" => "Failed to add household member",diff --git a/settings.php b/settings.phpindex 93c00d0..ede5b51 100644--- a/settings.php+++ b/settings.php@@ -1157,6 +1157,7 @@ $upcomingPaymentsLimit = normalize_upcoming_payments_limit($settings['upcoming_p<select name="fixer-provider" id="fixerProvider"><option value="0" <?= $provider == 0 ? 'selected' : '' ?>>fixer.io</option><option value="1" <?= $provider == 1 ? 'selected' : '' ?>>apilayer.com</option>+ <option value="2" <?= $provider == 2 ? 'selected' : '' ?>>frankfurter.dev</option></select></div><div class="buttons">@@ -1193,6 +1194,15 @@ $upcomingPaymentsLimit = normalize_upcoming_payments_limit($settings['upcoming_p</a></span></p>+ <p>+ <?= translate("no_api_key_provider", $i18n) ?>+ <span>+ https://frankfurter.dev+ <a href="https://frankfurter.dev" title="Frankfurter" target="_blank">+ <i class="fa-solid fa-arrow-up-right-from-square"></i>+ </a>+ </span>+ </p></div></div></section>diff --git a/tests/cases/currency_provider_frankfurter_test.php b/tests/cases/currency_provider_frankfurter_test.phpnew file mode 100644index 0000000..478859c--- /dev/null+++ b/tests/cases/currency_provider_frankfurter_test.php@@ -0,0 +1,631 @@+<?php+/*+ A currency provider that needs no account.++ Both existing providers are reached with a key the user has to register for.+ Until somebody does, a household running one subscription in CHF and one in+ EUR has no converted total at all - the rate rows keep whatever they were+ seeded with, and the statistics quietly add francs to euros.++ frankfurter.dev publishes the ECB reference rates over https with no account+ and no key, which makes it a provider that is configured by being chosen.+ That is one half of what is guarded here, because every assumption around the+ fixer table is the opposite one: a key is what is saved, a key is what is+ validated, and a row exists because a key was pasted into it.++ The other half is the answer itself. Frankfurter's v2 API does not speak the+ {"rates":{...}} object the two fixer paths do, and the three ways it differs+ are all silent ones:++ - it answers with a flat list of one record per quote, so a reader looking for+ a "rates" key finds nothing and a reader handed the list finds no codes;+ - an unknown base is not an error, it is HTTP 200 with `[]`, which is a+ perfectly good array and passes for a successful refresh that stored+ nothing;+ - a single code it will not accept refuses the whole request with 422, so one+ invented currency in one account stops every other currency in it from+ refreshing.++ All three are measured behaviour, and each has a case below. The request+ itself is stubbed: no test in this suite makes one.+*/++$GLOBALS['frankfurter_test_urls'] = [];+$GLOBALS['frankfurter_test_answers'] = [];++/**+ * Stands in for the provider. Defined before the file under test is loaded, so+ * the guard there leaves it alone and nothing in this suite opens a socket.+ *+ * @param string $url+ * @param resource $context+ * @return array{body: string|false, headers: array|null}+ */+function frankfurter_http_get($url, $context)+{+ $GLOBALS['frankfurter_test_urls'][] = $url;++ if ($GLOBALS['frankfurter_test_answers'] === []) {+ return ['body' => false, 'headers' => null];+ }++ return array_shift($GLOBALS['frankfurter_test_answers']);+}++require_once WALLOS_ROOT . '/includes/frankfurter.php';++/**+ * Queues one provider answer and forgets the requests made so far.+ *+ * @param string|false $body+ * @param int|null $status Null for a request that got no response at all.+ */+function frankfurter_expect($body, $status = 200)+{+ $GLOBALS['frankfurter_test_urls'] = [];+ $GLOBALS['frankfurter_test_answers'] = [[+ 'body' => $body,+ 'headers' => $status === null ? null : ['HTTP/1.1 ' . $status . ' Something'],+ ]];+}++/**+ * The URL the code under test asked for, or null when it asked for nothing.+ *+ * @return string|null+ */+function frankfurter_asked()+{+ return $GLOBALS['frankfurter_test_urls'][0] ?? null;+}++/**+ * @param SQLite3 $db+ * @param int $userId+ * @return array|false+ */+function frankfurter_fixer_row($db, $userId)+{+ $stmt = $db->prepare('SELECT api_key, provider FROM fixer WHERE user_id = :userId');+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $result = $stmt->execute();++ return $result ? $result->fetchArray(SQLITE3_ASSOC) : false;+}++/**+ * @param SQLite3 $db+ * @param int $userId+ * @param string $code+ * @return float+ */+function frankfurter_stored_rate($db, $userId, $code)+{+ $stmt = $db->prepare('SELECT rate FROM currencies WHERE user_id = :userId AND code = :code');+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->bindValue(':code', $code, SQLITE3_TEXT);+ $result = $stmt->execute();+ $row = $result ? $result->fetchArray(SQLITE3_ASSOC) : false;++ return $row ? (float) $row['rate'] : 0.0;+}++/**+ * The statements the keyless save path runs: set the provider on the row that+ * is there, and only write a row when there is none.+ *+ * @param SQLite3 $db+ * @param int $userId+ */+function frankfurter_save_provider($db, $userId)+{+ $stmt = $db->prepare('UPDATE fixer SET provider = :provider WHERE user_id = :userId');+ $stmt->bindValue(':provider', 2, SQLITE3_INTEGER);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->execute();++ if ($db->changes() === 0) {+ $stmt = $db->prepare('INSERT INTO fixer (api_key, provider, user_id) VALUES (:api_key, :provider, :userId)');+ $stmt->bindValue(':api_key', '', SQLITE3_TEXT);+ $stmt->bindValue(':provider', 2, SQLITE3_INTEGER);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->execute();+ }+}++/**+ * The write the three fetch paths make, replayed against a real database.+ *+ * Spelled out rather than approximated, because the assertions in+ * "the fetch paths write the provider's own numbers" only mean something while+ * the endpoints still run these two lines - which the source assertions in the+ * same test check.+ *+ * @param SQLite3 $db+ * @param int $userId+ * @param string $mainCurrencyCode+ * @param array<string, float> $rates+ */+function frankfurter_write_rates($db, $userId, $mainCurrencyCode, $rates)+{+ $mainCurrencyToEUR = 1.0;+ $stmt = $db->prepare('UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId');++ foreach ($rates as $currencyCode => $rate) {+ if ($currencyCode === $mainCurrencyCode) {+ $exchangeRate = 1.0;+ } else {+ $exchangeRate = $rate / $mainCurrencyToEUR;+ }++ $stmt->bindValue(':rate', $exchangeRate, SQLITE3_TEXT);+ $stmt->bindValue(':code', $currencyCode, SQLITE3_TEXT);+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+ $stmt->execute();+ $stmt->reset();+ }+}++/**+ * @param string $path Relative to the application root.+ * @return string+ */+function frankfurter_source($path)+{+ return file_get_contents(WALLOS_ROOT . '/' . $path);+}++/**+ * The brace balanced block a header line opens.+ *+ * @param string $source+ * @param string $header Text of the opening line, up to and including its brace.+ * @return string|null+ */+function frankfurter_block($source, $header)+{+ $start = strpos($source, $header);++ if ($start === false) {+ return null;+ }++ $depth = 0;+ $length = strlen($source);++ for ($i = $start; $i < $length; $i++) {+ if ($source[$i] === '{') {+ $depth++;+ } elseif ($source[$i] === '}') {+ $depth--;++ if ($depth === 0) {+ return substr($source, $start, $i - $start + 1);+ }+ }+ }++ return null;+}++/**+ * Where the keyless branch starts in each of the two save endpoints.+ *+ * @return array<string, string> path => header line+ */+function frankfurter_save_paths()+{+ return [+ // Posted from the settings page, where the provider arrives as a string.+ 'endpoints/currency/fixer_api_key.php' => 'if ($provider == 2) {',+ // The REST equivalent, which has already cast it.+ 'api/fixer/set_fixer.php' => 'if ($provider === 2) {',+ ];+}++/**+ * The three places that fetch rates from a provider.+ *+ * @return string[]+ */+function frankfurter_fetch_paths()+{+ return [+ 'endpoints/currency/update_exchange.php',+ 'endpoints/cronjobs/updateexchange.php',+ // Runs when the main currency changes, so the rates are recomputed+ // against the new one.+ 'endpoints/user/save_user.php',+ ];+}++wallos_test('the v2 answer is a flat list of records, not a rates object', function () {+ // Measured 2026-09-13, base=CHF, quotes=EUR,USD. One record per quote, with+ // the code in a "quote" field rather than as the key of a "rates" object.+ $body = '[{"date":"2026-09-13","base":"CHF","quote":"EUR","rate":1.0593},'+ . '{"date":"2026-09-13","base":"CHF","quote":"USD","rate":1.2304}]';++ $rates = frankfurter_rates(json_decode($body, true));++ assert_true(is_array($rates), 'the flat list becomes a map');+ assert_same(['EUR' => 1.0593, 'USD' => 1.2304], $rates,+ 'keyed by the quote code, which is where v2 puts the currency');++ // The shape of the API this provider retired. api.frankfurter.app answers+ // 301 now, and anything written against that shape reads nothing out of a+ // v2 body without noticing.+ assert_same(null, frankfurter_rates(json_decode('{"amount":1.0,"base":"CHF","rates":{"EUR":1.0581}}', true)),+ 'an object with a rates key is not a v2 answer and is refused rather than half read');+});++wallos_test('an empty answer is a refusal, not a refresh that priced nothing', function () {+ // Measured 2026-09-13: base=BTC answers HTTP 200 with `[]`. That decodes to+ // a perfectly good array, so a caller checking only is_array() calls it a+ // success, stores nothing, and stamps the rates as refreshed - after which+ // the freshness check hides it until tomorrow.+ assert_same(null, frankfurter_rates(json_decode('[]', true)),+ 'an empty list is not a set of rates that happens to be empty');++ frankfurter_expect('[]', 200);+ $answer = frankfurter_latest_rates('BTC', 'EUR,USD');++ assert_true(!isset($answer['rates']),+ 'and the fetch hands the caller nothing it could mistake for rates');+ assert_contains('does not price BTC as a base currency', $answer['message'] ?? '',+ 'the message names the base, rather than sending the reader after an outage');+});++wallos_test('a malformed code is held back before the request is made', function () {+ // Measured 2026-09-13: `quotes=USD,XX!` answers 422 and returns nothing at+ // all, not USD. A currency in Wallos is three free-text fields, so an+ // invented code is accepted and stored, and one of those would otherwise+ // stop every other currency in the same account from refreshing.+ list($accepted, $rejected) = frankfurter_partition_codes(['usd', 'XX!', 'TOOLONG', 'EUR', '']);++ assert_same(['USD', 'EUR'], $accepted, 'three letter codes are asked for, upper cased');+ assert_same(['XX!', 'TOOLONG', ''], $rejected, 'anything else is held back');++ frankfurter_expect('[{"date":"2026-09-13","base":"CHF","quote":"USD","rate":1.2304}]', 200);+ frankfurter_latest_rates('CHF', 'USD,XX!');++ assert_contains('quotes=USD', frankfurter_asked(),+ 'the request carries the code the provider can answer for');+ assert_not_contains('XX', frankfurter_asked(),+ 'and not the one that would have refused the whole request');+});++wallos_test('the provider explains which currency it objected to, and that is what is reported', function () {+ // Its errors are {"status":422,"message":"invalid currency: XYZ"}, which is+ // neither the {"error":{"info":...}} of fixer nor the {"success":false} the+ // save endpoints look for. The named code is the only thing in the whole+ // response that says which currency row is the reason nothing refreshed.+ assert_same('invalid currency: XYZ',+ frankfurter_detail(json_decode('{"status":422,"message":"invalid currency: XYZ"}', true)),+ 'the body says which code it was');+ assert_same('', frankfurter_detail(json_decode('[]', true)),+ 'and an empty list says nothing, so nothing is invented for it');++ frankfurter_expect('{"status":422,"message":"invalid currency: XYZ"}', 422);+ $answer = frankfurter_latest_rates('CHF', 'EUR,XYZ');++ assert_true(!isset($answer['rates']), 'a 422 is not a set of rates');+ assert_contains('invalid currency: XYZ', $answer['message'] ?? '',+ 'and the provider\'s own wording reaches the person reading the refresh output');+ assert_contains('422', $answer['message'] ?? '', 'alongside the status it came with');+});++wallos_test('the request is the v2 one, in the account\'s own currency', function () {+ frankfurter_expect('[{"date":"2026-09-13","base":"CHF","quote":"EUR","rate":1.0593}]', 200);+ $answer = frankfurter_latest_rates('chf', 'EUR,CHF');++ assert_contains('https://api.frankfurter.dev/v2/rates?base=CHF', frankfurter_asked(),+ 'the v2 endpoint, asked in the user\'s own main currency rather than in EUR');+ assert_contains('quotes=', frankfurter_asked(),+ 'v2 names the wanted codes with quotes; symbols is the parameter of the v1 API');+ assert_not_contains('/v1/', frankfurter_asked(), 'and not the v1 path');+ // api.frankfurter.app is retired and answers 301, and a redirect is the+ // only warning anyone would get.+ assert_not_contains('frankfurter.app', frankfurter_asked(),+ 'and the current host rather than the one that answers with a redirect');+ assert_same(['EUR' => 1.0593], $answer['rates'] ?? [], 'the answer comes back as a map');+});++wallos_test('nothing is asked when no code could be asked about', function () {+ // An empty quotes list is not refused: measured 2026-09-13 it answers 200+ // with `[]`, which is the same body an unknown base returns and would be+ // reported as one.+ frankfurter_expect('[]', 200);+ $answer = frankfurter_latest_rates('CHF', 'XX!,TOOLONG');++ assert_same(null, frankfurter_asked(), 'no request is made at all');+ assert_true(!isset($answer['rates']), 'and nothing is reported as rates');+ assert_contains('XX!', $answer['message'] ?? '', 'the codes that could not be asked about are named');+});++wallos_test('an outage is reported as an outage', function () {+ // Without ignore_errors a 422 would arrive here as false too, and the two+ // would be indistinguishable. This is the case where there genuinely was no+ // response: PHP leaves the header array unset for it.+ frankfurter_expect(false, null);+ $answer = frankfurter_latest_rates('CHF', 'EUR');++ assert_contains('could not be reached', $answer['message'] ?? '',+ 'no response at all is a network problem, not a base the provider will not price');+ assert_not_contains('does not price', $answer['message'] ?? '',+ 'and is not reported as the one thing it is not');+});++wallos_test('every fetch path goes through the one shared helper', function () {+ foreach (frankfurter_fetch_paths() as $path) {+ $source = frankfurter_source($path);++ assert_contains('includes/frankfurter.php', $source, $path . ' loads the shared helper');+ assert_contains('frankfurter_latest_rates(', $source, $path . ' fetches through it');+ assert_not_contains('api.frankfurter', $source,+ $path . ' builds no provider URL of its own, so there is one place where the API'+ . ' version and its parameters are decided');+ }++ $helper = frankfurter_source('includes/frankfurter.php');++ assert_contains("'https://api.frankfurter.dev/v2/rates?base='", $helper,+ 'and that place asks the v2 API');+ assert_contains("'"es='", $helper,+ 'with the parameter v2 names the wanted codes by; symbols belongs to the v1 API, which'+ . ' answers a different shape');+ assert_contains("'ignore_errors' => true", $helper,+ 'keeping the error body, without which a 422 arrives as false and cannot be told apart'+ . ' from the network being down');+});++wallos_test('the fetch paths write the provider\'s own numbers, undivided', function () {+ // The provider prices in any currency it lists, so it is asked in the+ // user's own main currency. Nothing is divided afterwards; leaving the+ // fixer arithmetic in place would divide by the main currency's own rate,+ // which an answer already based on it does not contain.+ foreach (frankfurter_fetch_paths() as $path) {+ $source = frankfurter_source($path);+ $block = frankfurter_block($source, 'if ((int) $provider === 2) {');++ assert_true($block !== null, $path . ': the keyless fetch branch was found');+ assert_contains('frankfurter_latest_rates($mainCurrencyCode, $codes)', $block,+ $path . ' asks for the rates in the user\'s main currency');+ assert_not_contains('base=EUR', $block,+ $path . ' does not ask this provider for a base it was not told to use');+ assert_contains('$mainCurrencyToEUR = 1.0;', $source,+ $path . ' makes no conversion on an answer that already is in the main currency');+ assert_contains('$exchangeRate = 1.0;', $source,+ $path . ' still writes the main currency\'s own row as 1.0, which is a rule of this'+ . ' application rather than a number read out of a response');+ }++ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ // A third currency the provider will not price. Measured 2026-09-13,+ // quotes=EUR,BTC answers 200 with EUR alone and drops BTC in silence.+ $stmt = $db->prepare('INSERT INTO currencies (id, name, symbol, code, rate, user_id)+ VALUES (9101, :name, :symbol, :code, 0.000012, 1)');+ $stmt->bindValue(':name', 'Bitcoin', SQLITE3_TEXT);+ $stmt->bindValue(':symbol', 'B', SQLITE3_TEXT);+ $stmt->bindValue(':code', 'BTC', SQLITE3_TEXT);+ $stmt->execute();++ $before = frankfurter_stored_rate($db, 1, 'BTC');++ frankfurter_expect('[{"date":"2026-09-13","base":"EUR","quote":"EUR","rate":1.0},'+ . '{"date":"2026-09-13","base":"EUR","quote":"USD","rate":1.1612}]', 200);+ $answer = frankfurter_latest_rates('EUR', 'EUR,USD,BTC');++ frankfurter_write_rates($db, 1, 'EUR', $answer['rates']);++ assert_same(1.1612, frankfurter_stored_rate($db, 1, 'USD'),+ 'the rate is stored exactly as the provider priced it, with no division by a base rate');+ assert_same(1.0, frankfurter_stored_rate($db, 1, 'EUR'), 'the main currency is stored as 1.0');+ assert_same($before, frankfurter_stored_rate($db, 1, 'BTC'),+ 'and the one it does not price keeps its previous rate rather than failing the refresh');++ $db->close();+});++wallos_test('a refresh that priced nothing is reported instead of passing in silence', function () {+ // An unknown base and a code the provider refuses both leave a body with no+ // rates in it, and the branch that stores rates simply did not run - ending+ // the request with nothing said at all, which reads exactly like the+ // refresh that worked.+ foreach (['endpoints/currency/update_exchange.php', 'endpoints/cronjobs/updateexchange.php'] as $path) {+ $source = frankfurter_source($path);+ $header = 'if ($apiData !== null && isset($apiData[\'rates\'])) {';+ $block = frankfurter_block($source, $header);++ assert_true($block !== null, $path . ': the storing branch was found');++ $after = substr($source, strpos($source, $header) + strlen($block));++ assert_same('else', substr(ltrim($after), 0, 4),+ $path . ' says something when the provider returned no rates, rather than ending the'+ . ' request with an empty body that cannot be told from a successful refresh');+ assert_contains('Exchange rates update failed', $after, $path . ' names the failure');+ // The whole expression, not just the array read: an isset() guard left+ // standing over a branch that no longer echoes anything mentions the+ // same key and would satisfy a looser match.+ assert_contains('htmlspecialchars($apiData[\'message\'])', $after,+ $path . ' passes on the provider\'s own explanation, which is the only thing that'+ . ' names the currency row that caused it');+ }+});++wallos_test('a refresh that priced nothing leaves the last update date alone', function () {+ // The date is what the freshness check reads to skip a refresh for the rest+ // of the day. Stamping it on a failed refresh would hide the failure until+ // tomorrow.+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ foreach (['endpoints/currency/update_exchange.php', 'endpoints/cronjobs/updateexchange.php'] as $path) {+ $block = frankfurter_block(frankfurter_source($path), 'if ($apiData !== null && isset($apiData[\'rates\'])) {');++ assert_true($block !== null, $path . ': the storing branch was found');+ assert_contains('last_exchange_update', $block,+ $path . ' writes the refresh date inside the branch that stored the rates, so a'+ . ' provider answer with no rates in it does not mark them fresh');+ }++ assert_same(0, (int) $db->querySingle('SELECT COUNT(*) FROM last_exchange_update WHERE user_id = 1'),+ 'and nothing has stamped a date for a user whose rates were never refreshed');++ $db->close();+});++wallos_test('choosing the keyless provider keeps the key of the one before it', function () {+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ $stmt = $db->prepare("INSERT INTO fixer (api_key, provider, user_id) VALUES ('kept-fixer-key', 0, 1)");+ $stmt->execute();++ frankfurter_save_provider($db, 1);++ $row = frankfurter_fixer_row($db, 1);++ assert_true($row !== false, 'the row survives the switch');+ assert_same('kept-fixer-key', $row['api_key'],+ 'the key of the provider switched away from is still there to switch back to');+ assert_same(2, (int) $row['provider'], 'the provider is the keyless one');+ assert_same(1, (int) $db->querySingle('SELECT COUNT(*) FROM fixer WHERE user_id = 1'),+ 'and there is still exactly one row for the user');++ $db->close();+});++wallos_test('replacing the row instead of updating it is what loses the key', function () {+ // Guards the regression itself. The save endpoints delete the row before+ // they write the new one, and the key field is empty while a keyless+ // provider is selected, so taking that path here is how the key goes.+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ $stmt = $db->prepare("INSERT INTO fixer (api_key, provider, user_id) VALUES ('kept-fixer-key', 0, 1)");+ $stmt->execute();++ $db->query('DELETE FROM fixer WHERE user_id = 1');+ $stmt = $db->prepare("INSERT INTO fixer (api_key, provider, user_id) VALUES ('', 2, 1)");+ $stmt->execute();++ assert_same('', frankfurter_fixer_row($db, 1)['api_key'],+ 'the delete and reinsert shape leaves nothing to go back to');++ $db->close();+});++wallos_test('an update that changes nothing still counts as a row', function () {+ // frankfurter_save_provider() only inserts when the update matched no row,+ // and SQLite counting a same value update as a change is what carries that.+ // If it ever stopped, saving the provider twice would add a second row for+ // the user.+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ frankfurter_save_provider($db, 1);+ frankfurter_save_provider($db, 1);++ assert_same(1, (int) $db->querySingle('SELECT COUNT(*) FROM fixer WHERE user_id = 1'),+ 'saving the same provider twice leaves one row');++ $db->close();+});++wallos_test('both save endpoints settle the keyless provider before the delete', function () {+ foreach (frankfurter_save_paths() as $path => $header) {+ $source = frankfurter_source($path);+ $branch = strpos($source, $header);+ $delete = strpos($source, 'DELETE FROM fixer');++ assert_true($branch !== false, $path . ' has a branch for the keyless provider');+ assert_true($delete !== false, $path . ' still has the replace path for the other two');+ assert_true($branch !== false && $delete !== false && $branch < $delete,+ $path . ' decides the keyless provider before it deletes the row, so the stored key'+ . ' is not already gone by the time the decision is made');++ $block = frankfurter_block($source, $header);++ assert_true($block !== null, $path . ': the keyless branch is brace balanced');+ assert_not_contains('DELETE FROM fixer', $block,+ $path . ' does not delete the row on the keyless path');+ // The last statement of the branch, not merely one somewhere inside it:+ // the error paths in the same branch exit too, so a branch that has+ // lost the exit after its success answer still contains the word.+ $tail = rtrim(rtrim(rtrim($block), '}'));++ assert_same('exit;', substr($tail, -5),+ $path . ' answers from the keyless branch and stops there, instead of falling'+ . ' through into the path that deletes the row and validates a key');++ // Spelled out rather than matched loosely, because+ // frankfurter_save_provider() above replays exactly these two statements+ // and the assertions that run against it are only worth anything while+ // the endpoints still run them.+ assert_contains('UPDATE fixer SET provider = :provider WHERE user_id = :userId', $block,+ $path . ' updates the row rather than replacing it');+ assert_contains('$db->changes() === 0', $block,+ $path . ' only writes a row when the update found none to change');+ assert_contains('INSERT INTO fixer (api_key, provider, user_id)', $block,+ $path . ' writes a row for the account that has none, which is every account that'+ . ' never registered with either of the other two providers');+ }+});++wallos_test('saving the keyless provider sends nothing over the wire', function () {+ // There is no key to check, so a validation request would be a round trip+ // spent confirming that an empty string is empty - and one that fails the+ // save when the provider happens to be down.+ foreach (frankfurter_save_paths() as $path => $header) {+ $block = frankfurter_block(frankfurter_source($path), $header);++ assert_true($block !== null, $path . ': the keyless branch was found');++ foreach (['file_get_contents', 'curl_init', 'stream_context_create', 'fopen',+ 'frankfurter_latest_rates'] as $call) {+ assert_not_contains($call, $block,+ $path . ' makes no request when it saves a provider that has nothing to validate');+ }+ }+});++wallos_test('an empty key on the keyless provider counts as a configured provider', function () {+ // calendar.php and includes/stats_calculations.php decide whether to warn+ // that currencies cannot be converted, and they decide it on the row, not on+ // the key. The saved row therefore has to exist even though there is nothing+ // to put in api_key.+ $db = wallos_test_open_database();+ wallos_test_create_user($db, 1, 'alice');++ frankfurter_save_provider($db, 1);++ $stmt = $db->prepare('SELECT api_key FROM fixer WHERE user_id = :userId');+ $stmt->bindValue(':userId', 1, SQLITE3_INTEGER);+ $configured = $stmt->execute()->fetchArray(SQLITE3_ASSOC);++ assert_true($configured !== false,+ 'a user who never registered anywhere still has a provider as far as the pages can tell');+ assert_same('', $configured['api_key'], 'and it is configured with no key at all');++ foreach (['calendar.php', 'includes/stats_calculations.php'] as $path) {+ assert_contains('fetchArray(SQLITE3_ASSOC) === false', frankfurter_source($path),+ $path . ' asks whether a provider row exists, not whether a key is stored');+ }++ $db->close();+});++wallos_test('the keyless provider is offered and named', function () {+ assert_contains('<option value="2"', frankfurter_source('settings.php'),+ 'the settings page offers the third provider');+ assert_contains('frankfurter.dev', frankfurter_source('settings.php'),+ 'and says which one it is');++ // Without an entry here the API answers with an undefined index where the+ // provider name should be.+ assert_contains('2 => "Frankfurter"', frankfurter_source('api/fixer/get_fixer.php'),+ 'the read API can name the provider it may now be asked about');+});