Skip to content

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

feat(i18n): an account that changes its language takes its default names with it

thorstenhornung1ebb63b056d1f
diff --git a/endpoints/user/save_user.php b/endpoints/user/save_user.php
index 1c562b8..dc689cd 100644
--- a/endpoints/user/save_user.php
+++ b/endpoints/user/save_user.php
@@ -1,373 +1,379 @@
-<?php
-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);
- mkdir('../../images/uploads/logos/avatars', 0777, true);
-}
-
-function update_exchange_rate($db, $userId)
-{
- $query = "SELECT api_key, provider FROM fixer WHERE user_id = :userId";
- $stmt = $db->prepare($query);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
-
- if ($result) {
- $row = $result->fetchArray(SQLITE3_ASSOC);
-
- if ($row) {
- $apiKey = $row['api_key'];
- $provider = $row['provider'];
-
- $codes = "";
- $query = "SELECT id, name, symbol, code FROM currencies";
- $result = $db->query($query);
- while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
- $codes .= $row['code'] . ",";
- }
- $codes = rtrim($codes, ',');
-
- $query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = :userId";
- $stmt = $db->prepare($query);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
- $mainCurrencyCode = $row['code'];
- $mainCurrencyId = $row['main_currency'];
-
- 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' => [
- 'method' => 'GET',
- 'header' => 'apikey: ' . $apiKey,
- ]
- ]);
- $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);
- }
-
- 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) {
- if ($currencyCode === $mainCurrencyCode) {
- $exchangeRate = 1.0;
- } else {
- $exchangeRate = $rate / $mainCurrencyToEUR;
- }
- $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId";
- $updateStmt = $db->prepare($updateQuery);
- $updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT);
- $updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT);
- $updateStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $updateResult = $updateStmt->execute();
- }
- $currentDate = new DateTime();
- $formattedDate = $currentDate->format('Y-m-d');
-
- $query = "SELECT * FROM last_exchange_update WHERE user_id = :userId";
- $stmt = $db->prepare($query);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $row = $result->fetchArray(SQLITE3_ASSOC);
-
- if ($row) {
- $query = "UPDATE last_exchange_update SET date = :formattedDate WHERE user_id = :userId";
- } else {
- $query = "INSERT INTO last_exchange_update (date, user_id) VALUES (:formattedDate, :userId)";
- }
-
- $stmt = $db->prepare($query);
- $stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $resutl = $stmt->execute();
-
- $db->close();
- }
- }
- }
-}
-
-$demoMode = getenv('DEMO_MODE');
-
-$query = "SELECT main_currency FROM user WHERE id = :userId";
-$stmt = $db->prepare($query);
-$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-$result = $stmt->execute();
-$row = $result->fetchArray(SQLITE3_ASSOC);
-$mainCurrencyId = $row['main_currency'];
-
-function sanitizeFilename($filename)
-{
- $filename = preg_replace("/[^a-zA-Z0-9\s]/", "", $filename);
- $filename = str_replace(" ", "-", $filename);
- $filename = str_replace(".", "", $filename);
- return $filename;
-}
-
-function validateFileExtension($fileExtension)
-{
- $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'jtif', 'webp'];
- return in_array($fileExtension, $allowedExtensions);
-}
-
-function resizeAndUploadAvatar($uploadedFile, $uploadDir, $name)
-{
- $targetWidth = 80;
- $targetHeight = 80;
-
- $timestamp = time();
- $originalFileName = $uploadedFile['name'];
- $fileExtension = strtolower(pathinfo($originalFileName, PATHINFO_EXTENSION));
- $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png';
- $fileName = $timestamp . '-avatars-' . sanitizeFilename($name) . '.' . $fileExtension;
- $uploadFile = $uploadDir . $fileName;
-
- if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) {
- $fileInfo = getimagesize($uploadFile);
-
- if ($fileInfo !== false) {
- $width = $fileInfo[0];
- $height = $fileInfo[1];
-
- // Load the image based on its format
- if ($fileExtension === 'png') {
- $image = imagecreatefrompng($uploadFile);
- } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {
- $image = imagecreatefromjpeg($uploadFile);
- } elseif ($fileExtension === 'gif') {
- $image = imagecreatefromgif($uploadFile);
- } elseif ($fileExtension === 'webp') {
- $image = imagecreatefromwebp($uploadFile);
- } else {
- // Handle other image formats as needed
- return "";
- }
-
- // Enable alpha channel (transparency) for PNG images
- if ($fileExtension === 'png') {
- imagesavealpha($image, true);
- }
-
- $newWidth = $width;
- $newHeight = $height;
-
- if ($width > $targetWidth) {
- $newWidth = (int)$targetWidth;
- $newHeight = (int)(($targetWidth / $width) * $height);
- }
-
- if ($newHeight > $targetHeight) {
- $newWidth = (int)(($targetHeight / $newHeight) * $newWidth);
- $newHeight = (int)$targetHeight;
- }
-
- $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
- imagesavealpha($resizedImage, true);
- $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);
- imagefill($resizedImage, 0, 0, $transparency);
- imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
-
- if ($fileExtension === 'png') {
- imagepng($resizedImage, $uploadFile);
- } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {
- imagejpeg($resizedImage, $uploadFile);
- } elseif ($fileExtension === 'gif') {
- imagegif($resizedImage, $uploadFile);
- } elseif ($fileExtension === 'webp') {
- imagewebp($resizedImage, $uploadFile);
- } else {
- return "";
- }
-
- imagedestroy($image);
- imagedestroy($resizedImage);
- return "images/uploads/logos/avatars/" . $fileName;
- }
- }
-
- return "";
-}
-
-if (
- isset($_SESSION['username'])
- && isset($_POST['firstname'])
- && isset($_POST['lastname'])
- && isset($_POST['email']) && $_POST['email'] !== ""
- && isset($_POST['avatar']) && $_POST['avatar'] !== ""
- && isset($_POST['main_currency']) && $_POST['main_currency'] !== ""
- && isset($_POST['language']) && $_POST['language'] !== ""
-) {
-
- $firstname = validate($_POST['firstname']);
- $lastname = validate($_POST['lastname']);
- $email = validate($_POST['email']);
-
- $query = "SELECT email FROM user WHERE id = :user_id";
- $stmt = $db->prepare($query);
- $stmt->bindValue(':user_id', $userId, SQLITE3_TEXT);
- $result = $stmt->execute();
- $user = $result->fetchArray(SQLITE3_ASSOC);
-
- $oldEmail = $user['email'];
-
- if ($oldEmail != $email) {
- $query = "SELECT email FROM user WHERE email = :email AND id != :userId";
- $stmt = $db->prepare($query);
- $stmt->bindValue(':email', $email, SQLITE3_TEXT);
- $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
- $result = $stmt->execute();
- $otherUser = $result->fetchArray(SQLITE3_ASSOC);
-
- if ($otherUser) {
- $response = [
- "success" => false,
- "message" => translate('email_exists', $i18n)
- ];
- echo json_encode($response);
- exit();
- }
- }
-
- $avatar = filter_var($_POST['avatar'], FILTER_SANITIZE_URL);
- $main_currency = $_POST['main_currency'];
- $language = $_POST['language'];
-
- if (!empty($_FILES['profile_pic']["name"])) {
- $file = $_FILES['profile_pic'];
-
- $fileType = mime_content_type($_FILES['profile_pic']['tmp_name']);
- if (strpos($fileType, 'image') === false) {
- $response = [
- "success" => false,
- "message" => translate('fill_all_fields', $i18n)
- ];
- echo json_encode($response);
- exit();
- }
- $name = $file['name'];
- $avatar = resizeAndUploadAvatar($_FILES['profile_pic'], '../../images/uploads/logos/avatars/', $name);
-
- if ($avatar !== "") {
- $stmt = $db->prepare("INSERT INTO uploaded_avatars (user_id, path) VALUES (:userId, :path)");
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
- $stmt->bindParam(':path', $avatar, SQLITE3_TEXT);
- $stmt->execute();
- }
- }
-
- if (isset($_POST['password']) && $_POST['password'] != "" && !$demoMode) {
- $password = $_POST['password'];
- if (isset($_POST['confirm_password'])) {
- $confirm = $_POST['confirm_password'];
- if ($password != $confirm) {
- $response = [
- "success" => false,
- "message" => translate('passwords_dont_match', $i18n)
- ];
- echo json_encode($response);
- exit();
- }
- } else {
- $response = [
- "success" => false,
- "message" => translate('passwords_dont_match', $i18n)
- ];
- echo json_encode($response);
- exit();
- }
- }
-
- if (isset($_POST['password']) && $_POST['password'] != "" && !$demoMode) {
- $sql = "UPDATE user SET avatar = :avatar, firstname = :firstname, lastname = :lastname, email = :email, password = :password, main_currency = :main_currency, language = :language WHERE id = :userId";
- } else {
- $sql = "UPDATE user SET avatar = :avatar, firstname = :firstname, lastname = :lastname, email = :email, main_currency = :main_currency, language = :language WHERE id = :userId";
- }
-
- $stmt = $db->prepare($sql);
- $stmt->bindParam(':avatar', $avatar, SQLITE3_TEXT);
- $stmt->bindParam(':firstname', $firstname, SQLITE3_TEXT);
- $stmt->bindParam(':lastname', $lastname, SQLITE3_TEXT);
- $stmt->bindParam(':email', $email, SQLITE3_TEXT);
- $stmt->bindParam(':main_currency', $main_currency, SQLITE3_INTEGER);
- $stmt->bindParam(':language', $language, SQLITE3_TEXT);
- $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
-
- if (isset($_POST['password']) && $_POST['password'] != "" && !$demoMode) {
- $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
- $stmt->bindParam(':password', $hashedPassword, SQLITE3_TEXT);
- }
-
- $result = $stmt->execute();
-
- if ($result) {
- $cookieExpire = time() + (30 * 24 * 60 * 60);
- $oldLanguage = isset($_COOKIE['language']) ? $_COOKIE['language'] : "en";
- $root = str_replace('/endpoints/user', '', dirname($_SERVER['PHP_SELF']));
- $root = $root == '' ? '/' : $root;
- setcookie('language', $language, [
- 'path' => $root,
- 'expires' => $cookieExpire,
- 'samesite' => 'Lax'
- ]);
- $_SESSION['firstname'] = $firstname;
- $_SESSION['avatar'] = $avatar;
- $_SESSION['main_currency'] = $main_currency;
-
- if ($main_currency != $mainCurrencyId) {
- update_exchange_rate($db, $userId);
- }
-
- $reload = $oldLanguage != $language;
-
- $response = [
- "success" => true,
- "message" => translate('user_details_saved', $i18n),
- "reload" => $reload
- ];
- echo json_encode($response);
- } else {
- $response = [
- "success" => false,
- "message" => translate('error_updating_user_data', $i18n)
- ];
- echo json_encode($response);
- }
-
- exit();
-} else {
- $response = [
- "success" => false,
- "message" => translate('fill_all_fields', $i18n)
- ];
- echo json_encode($response);
- exit();
-}
+<?php
+require_once '../../includes/connect_endpoint.php';
+require_once '../../includes/inputvalidation.php';
+require_once '../../includes/validate_endpoint.php';
+require_once '../../includes/frankfurter.php';
+require_once '../../includes/default_names.php';
+
+if (!file_exists('../../images/uploads/logos')) {
+ mkdir('../../images/uploads/logos', 0777, true);
+ mkdir('../../images/uploads/logos/avatars', 0777, true);
+}
+
+function update_exchange_rate($db, $userId)
+{
+ $query = "SELECT api_key, provider FROM fixer WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+
+ if ($result) {
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+
+ if ($row) {
+ $apiKey = $row['api_key'];
+ $provider = $row['provider'];
+
+ $codes = "";
+ $query = "SELECT id, name, symbol, code FROM currencies";
+ $result = $db->query($query);
+ while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
+ $codes .= $row['code'] . ",";
+ }
+ $codes = rtrim($codes, ',');
+
+ $query = "SELECT u.main_currency, c.code FROM user u LEFT JOIN currencies c ON u.main_currency = c.id WHERE u.id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+ $mainCurrencyCode = $row['code'];
+ $mainCurrencyId = $row['main_currency'];
+
+ 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' => [
+ 'method' => 'GET',
+ 'header' => 'apikey: ' . $apiKey,
+ ]
+ ]);
+ $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);
+ }
+
+ 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) {
+ if ($currencyCode === $mainCurrencyCode) {
+ $exchangeRate = 1.0;
+ } else {
+ $exchangeRate = $rate / $mainCurrencyToEUR;
+ }
+ $updateQuery = "UPDATE currencies SET rate = :rate WHERE code = :code AND user_id = :userId";
+ $updateStmt = $db->prepare($updateQuery);
+ $updateStmt->bindParam(':rate', $exchangeRate, SQLITE3_TEXT);
+ $updateStmt->bindParam(':code', $currencyCode, SQLITE3_TEXT);
+ $updateStmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $updateResult = $updateStmt->execute();
+ }
+ $currentDate = new DateTime();
+ $formattedDate = $currentDate->format('Y-m-d');
+
+ $query = "SELECT * FROM last_exchange_update WHERE user_id = :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $row = $result->fetchArray(SQLITE3_ASSOC);
+
+ if ($row) {
+ $query = "UPDATE last_exchange_update SET date = :formattedDate WHERE user_id = :userId";
+ } else {
+ $query = "INSERT INTO last_exchange_update (date, user_id) VALUES (:formattedDate, :userId)";
+ }
+
+ $stmt = $db->prepare($query);
+ $stmt->bindParam(':formattedDate', $formattedDate, SQLITE3_TEXT);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $resutl = $stmt->execute();
+
+ $db->close();
+ }
+ }
+ }
+}
+
+$demoMode = getenv('DEMO_MODE');
+
+$query = "SELECT main_currency, language FROM user WHERE id = :userId";
+$stmt = $db->prepare($query);
+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+$result = $stmt->execute();
+$row = $result->fetchArray(SQLITE3_ASSOC);
+$mainCurrencyId = $row['main_currency'];
+$storedLanguage = $row['language'] ?? 'en';
+
+function sanitizeFilename($filename)
+{
+ $filename = preg_replace("/[^a-zA-Z0-9\s]/", "", $filename);
+ $filename = str_replace(" ", "-", $filename);
+ $filename = str_replace(".", "", $filename);
+ return $filename;
+}
+
+function validateFileExtension($fileExtension)
+{
+ $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'jtif', 'webp'];
+ return in_array($fileExtension, $allowedExtensions);
+}
+
+function resizeAndUploadAvatar($uploadedFile, $uploadDir, $name)
+{
+ $targetWidth = 80;
+ $targetHeight = 80;
+
+ $timestamp = time();
+ $originalFileName = $uploadedFile['name'];
+ $fileExtension = strtolower(pathinfo($originalFileName, PATHINFO_EXTENSION));
+ $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png';
+ $fileName = $timestamp . '-avatars-' . sanitizeFilename($name) . '.' . $fileExtension;
+ $uploadFile = $uploadDir . $fileName;
+
+ if (move_uploaded_file($uploadedFile['tmp_name'], $uploadFile)) {
+ $fileInfo = getimagesize($uploadFile);
+
+ if ($fileInfo !== false) {
+ $width = $fileInfo[0];
+ $height = $fileInfo[1];
+
+ // Load the image based on its format
+ if ($fileExtension === 'png') {
+ $image = imagecreatefrompng($uploadFile);
+ } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {
+ $image = imagecreatefromjpeg($uploadFile);
+ } elseif ($fileExtension === 'gif') {
+ $image = imagecreatefromgif($uploadFile);
+ } elseif ($fileExtension === 'webp') {
+ $image = imagecreatefromwebp($uploadFile);
+ } else {
+ // Handle other image formats as needed
+ return "";
+ }
+
+ // Enable alpha channel (transparency) for PNG images
+ if ($fileExtension === 'png') {
+ imagesavealpha($image, true);
+ }
+
+ $newWidth = $width;
+ $newHeight = $height;
+
+ if ($width > $targetWidth) {
+ $newWidth = (int)$targetWidth;
+ $newHeight = (int)(($targetWidth / $width) * $height);
+ }
+
+ if ($newHeight > $targetHeight) {
+ $newWidth = (int)(($targetHeight / $newHeight) * $newWidth);
+ $newHeight = (int)$targetHeight;
+ }
+
+ $resizedImage = imagecreatetruecolor($newWidth, $newHeight);
+ imagesavealpha($resizedImage, true);
+ $transparency = imagecolorallocatealpha($resizedImage, 0, 0, 0, 127);
+ imagefill($resizedImage, 0, 0, $transparency);
+ imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
+
+ if ($fileExtension === 'png') {
+ imagepng($resizedImage, $uploadFile);
+ } elseif ($fileExtension === 'jpg' || $fileExtension === 'jpeg') {
+ imagejpeg($resizedImage, $uploadFile);
+ } elseif ($fileExtension === 'gif') {
+ imagegif($resizedImage, $uploadFile);
+ } elseif ($fileExtension === 'webp') {
+ imagewebp($resizedImage, $uploadFile);
+ } else {
+ return "";
+ }
+
+ imagedestroy($image);
+ imagedestroy($resizedImage);
+ return "images/uploads/logos/avatars/" . $fileName;
+ }
+ }
+
+ return "";
+}
+
+if (
+ isset($_SESSION['username'])
+ && isset($_POST['firstname'])
+ && isset($_POST['lastname'])
+ && isset($_POST['email']) && $_POST['email'] !== ""
+ && isset($_POST['avatar']) && $_POST['avatar'] !== ""
+ && isset($_POST['main_currency']) && $_POST['main_currency'] !== ""
+ && isset($_POST['language']) && $_POST['language'] !== ""
+) {
+
+ $firstname = validate($_POST['firstname']);
+ $lastname = validate($_POST['lastname']);
+ $email = validate($_POST['email']);
+
+ $query = "SELECT email FROM user WHERE id = :user_id";
+ $stmt = $db->prepare($query);
+ $stmt->bindValue(':user_id', $userId, SQLITE3_TEXT);
+ $result = $stmt->execute();
+ $user = $result->fetchArray(SQLITE3_ASSOC);
+
+ $oldEmail = $user['email'];
+
+ if ($oldEmail != $email) {
+ $query = "SELECT email FROM user WHERE email = :email AND id != :userId";
+ $stmt = $db->prepare($query);
+ $stmt->bindValue(':email', $email, SQLITE3_TEXT);
+ $stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
+ $result = $stmt->execute();
+ $otherUser = $result->fetchArray(SQLITE3_ASSOC);
+
+ if ($otherUser) {
+ $response = [
+ "success" => false,
+ "message" => translate('email_exists', $i18n)
+ ];
+ echo json_encode($response);
+ exit();
+ }
+ }
+
+ $avatar = filter_var($_POST['avatar'], FILTER_SANITIZE_URL);
+ $main_currency = $_POST['main_currency'];
+ $language = $_POST['language'];
+
+ if (!empty($_FILES['profile_pic']["name"])) {
+ $file = $_FILES['profile_pic'];
+
+ $fileType = mime_content_type($_FILES['profile_pic']['tmp_name']);
+ if (strpos($fileType, 'image') === false) {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_all_fields', $i18n)
+ ];
+ echo json_encode($response);
+ exit();
+ }
+ $name = $file['name'];
+ $avatar = resizeAndUploadAvatar($_FILES['profile_pic'], '../../images/uploads/logos/avatars/', $name);
+
+ if ($avatar !== "") {
+ $stmt = $db->prepare("INSERT INTO uploaded_avatars (user_id, path) VALUES (:userId, :path)");
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+ $stmt->bindParam(':path', $avatar, SQLITE3_TEXT);
+ $stmt->execute();
+ }
+ }
+
+ if (isset($_POST['password']) && $_POST['password'] != "" && !$demoMode) {
+ $password = $_POST['password'];
+ if (isset($_POST['confirm_password'])) {
+ $confirm = $_POST['confirm_password'];
+ if ($password != $confirm) {
+ $response = [
+ "success" => false,
+ "message" => translate('passwords_dont_match', $i18n)
+ ];
+ echo json_encode($response);
+ exit();
+ }
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('passwords_dont_match', $i18n)
+ ];
+ echo json_encode($response);
+ exit();
+ }
+ }
+
+ if (isset($_POST['password']) && $_POST['password'] != "" && !$demoMode) {
+ $sql = "UPDATE user SET avatar = :avatar, firstname = :firstname, lastname = :lastname, email = :email, password = :password, main_currency = :main_currency, language = :language WHERE id = :userId";
+ } else {
+ $sql = "UPDATE user SET avatar = :avatar, firstname = :firstname, lastname = :lastname, email = :email, main_currency = :main_currency, language = :language WHERE id = :userId";
+ }
+
+ $stmt = $db->prepare($sql);
+ $stmt->bindParam(':avatar', $avatar, SQLITE3_TEXT);
+ $stmt->bindParam(':firstname', $firstname, SQLITE3_TEXT);
+ $stmt->bindParam(':lastname', $lastname, SQLITE3_TEXT);
+ $stmt->bindParam(':email', $email, SQLITE3_TEXT);
+ $stmt->bindParam(':main_currency', $main_currency, SQLITE3_INTEGER);
+ $stmt->bindParam(':language', $language, SQLITE3_TEXT);
+ $stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);
+
+ if (isset($_POST['password']) && $_POST['password'] != "" && !$demoMode) {
+ $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
+ $stmt->bindParam(':password', $hashedPassword, SQLITE3_TEXT);
+ }
+
+ $result = $stmt->execute();
+
+ if ($result) {
+ $cookieExpire = time() + (30 * 24 * 60 * 60);
+ $oldLanguage = isset($_COOKIE['language']) ? $_COOKIE['language'] : "en";
+ $root = str_replace('/endpoints/user', '', dirname($_SERVER['PHP_SELF']));
+ $root = $root == '' ? '/' : $root;
+ setcookie('language', $language, [
+ 'path' => $root,
+ 'expires' => $cookieExpire,
+ 'samesite' => 'Lax'
+ ]);
+ $_SESSION['firstname'] = $firstname;
+ $_SESSION['avatar'] = $avatar;
+ $_SESSION['main_currency'] = $main_currency;
+
+ if ($main_currency != $mainCurrencyId) {
+ update_exchange_rate($db, $userId);
+ }
+
+ // The names this account was seeded with follow the language it just
+ // chose, as far as they are still the seeded ones.
+ localize_default_names_on_language_change($db, $userId, $storedLanguage, $language);
+
+ $reload = $oldLanguage != $language;
+
+ $response = [
+ "success" => true,
+ "message" => translate('user_details_saved', $i18n),
+ "reload" => $reload
+ ];
+ echo json_encode($response);
+ } else {
+ $response = [
+ "success" => false,
+ "message" => translate('error_updating_user_data', $i18n)
+ ];
+ echo json_encode($response);
+ }
+
+ exit();
+} else {
+ $response = [
+ "success" => false,
+ "message" => translate('fill_all_fields', $i18n)
+ ];
+ echo json_encode($response);
+ exit();
+}
diff --git a/includes/default_names.php b/includes/default_names.php
index d9ee016..4387580 100644
--- a/includes/default_names.php
+++ b/includes/default_names.php
@@ -1,298 +1,330 @@
-<?php
-/*
- The categories and payment methods a new account starts with, in the language
- of that account.
-
- The lists were repeated verbatim in every place that creates an account -
- registration.php, endpoints/admin/adduser.php and
- includes/oidc/oidc_create_user.php - and every copy was English. Somebody who
- registered in German got an application that was German everywhere except in
- its own data, on the very first screen they saw.
-
- The categories and the generic payment methods are held here as translation
- keys and resolved once, at the moment the account is created. What is stored
- is ordinary text the owner renames, reorders and deletes like any other row,
- so changing the account language later never rewrites it - the same contract
- the rows have always had.
-
- Brand names - PayPal, SEPA, Klarna - are the same word in every language and
- stay literal.
-
- Currencies are deliberately not here. Their names are a separate list with a
- separate problem (a currency is identified by its ISO code, not by its name),
- and folding them in would make this change about something else.
-*/
-
-/**
- * Translation keys of the default categories, in display order.
- *
- * The keys are the contract; the English strings live in the language files
- * like every other translation. "no_category" is an existing key, translated
- * in every language file already.
- *
- * @var string[]
- */
-const DEFAULT_CATEGORY_KEYS = [
- 'no_category',
- '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',
-];
-
-/**
- * The default payment methods, in display order.
- *
- * A generic term - "Credit Card", "Bank Transfer", "Direct Debit", "Money" -
- * reads differently to a German and to an English speaker, so it carries a
- * translation "key". A brand is the same word in every language, so it keeps a
- * literal "name".
- *
- * @var array<int, array{name?: string, key?: string, icon: string}>
- */
-const DEFAULT_PAYMENT_METHODS = [
- ['name' => 'PayPal', 'icon' => 'images/uploads/icons/paypal.png'],
- ['key' => 'payment_method_credit_card', 'icon' => 'images/uploads/icons/creditcard.png'],
- ['key' => 'payment_method_bank_transfer', 'icon' => 'images/uploads/icons/banktransfer.png'],
- ['key' => 'payment_method_direct_debit', 'icon' => 'images/uploads/icons/directdebit.png'],
- ['key' => 'payment_method_money', 'icon' => 'images/uploads/icons/money.png'],
- ['name' => 'Google Pay', 'icon' => 'images/uploads/icons/googlepay.png'],
- ['name' => 'Samsung Pay', 'icon' => 'images/uploads/icons/samsungpay.png'],
- ['name' => 'Apple Pay', 'icon' => 'images/uploads/icons/applepay.png'],
- ['name' => 'Crypto', 'icon' => 'images/uploads/icons/crypto.png'],
- ['name' => 'Klarna', 'icon' => 'images/uploads/icons/klarna.png'],
- ['name' => 'Amazon Pay', 'icon' => 'images/uploads/icons/amazonpay.png'],
- ['name' => 'SEPA', 'icon' => 'images/uploads/icons/sepa.png'],
- ['name' => 'Skrill', 'icon' => 'images/uploads/icons/skrill.png'],
- ['name' => 'Sofort', 'icon' => 'images/uploads/icons/sofort.png'],
- ['name' => 'Stripe', 'icon' => 'images/uploads/icons/stripe.png'],
- ['name' => 'Affirm', 'icon' => 'images/uploads/icons/affirm.png'],
- ['name' => 'AliPay', 'icon' => 'images/uploads/icons/alipay.png'],
- ['name' => 'Elo', 'icon' => 'images/uploads/icons/elo.png'],
- ['name' => 'Facebook Pay', 'icon' => 'images/uploads/icons/facebookpay.png'],
- ['name' => 'GiroPay', 'icon' => 'images/uploads/icons/giropay.png'],
- ['name' => 'iDeal', 'icon' => 'images/uploads/icons/ideal.png'],
- ['name' => 'Union Pay', 'icon' => 'images/uploads/icons/unionpay.png'],
- ['name' => 'Interac', 'icon' => 'images/uploads/icons/interac.png'],
- ['name' => 'WeChat', 'icon' => 'images/uploads/icons/wechat.png'],
- ['name' => 'Paysafe', 'icon' => 'images/uploads/icons/paysafe.png'],
- ['name' => 'Poli', 'icon' => 'images/uploads/icons/poli.png'],
- ['name' => 'Qiwi', 'icon' => 'images/uploads/icons/qiwi.png'],
- ['name' => 'ShopPay', 'icon' => 'images/uploads/icons/shoppay.png'],
- ['name' => 'Venmo', 'icon' => 'images/uploads/icons/venmo.png'],
- ['name' => 'VeriFone', 'icon' => 'images/uploads/icons/verifone.png'],
- ['name' => 'WebMoney', 'icon' => 'images/uploads/icons/webmoney.png'],
-];
-
-/**
- * The translation table of one specific language.
- *
- * translate() answers in the language of the current request, which is not the
- * language of the account being created: an administrator working in English
- * creates an account for somebody whose language is German, and an identity
- * provider names the language of an account nobody is looking at yet.
- *
- * A key the language file does not carry falls back to English, so a
- * translation that has not been updated yet produces English rather than
- * nothing.
- *
- * @param string $language
- * @return array<string, string>
- */
-function default_names_translations($language)
-{
- static $tables = [];
-
- // The value reaches this from a form field, an OIDC claim or the user
- // table, and it decides a file name, so it is not taken on trust: anything
- // that is not a plain identifier with a translation file is English, which
- // is what the callers stored before.
- $name = strtolower(str_replace('-', '_', trim((string) $language)));
-
- if (preg_match('/^[a-z]{2}(_[a-z]{2,4})?$/', $name) !== 1
- || !is_file(__DIR__ . '/i18n/' . $name . '.php')) {
- $name = 'en';
- }
-
- if (!isset($tables[$name])) {
- // The language files assign $i18n; required from inside a function it
- // stays local, which is what makes loading a second language safe.
- $i18n = [];
- require __DIR__ . '/i18n/' . $name . '.php';
- $table = $i18n;
-
- if ($name !== 'en') {
- $i18n = [];
- require __DIR__ . '/i18n/en.php';
- $table += $i18n;
- }
-
- $tables[$name] = $table;
- }
-
- return $tables[$name];
-}
-
-/**
- * The default categories in one language, in display order.
- *
- * @param string $language
- * @return string[]
- */
-function default_categories($language)
-{
- $translations = default_names_translations($language);
-
- $categories = [];
- foreach (DEFAULT_CATEGORY_KEYS as $key) {
- $categories[] = $translations[$key] ?? $key;
- }
-
- return $categories;
-}
-
-/**
- * The default payment methods in one language, in display order.
- *
- * @param string $language
- * @return array<int, array{name: string, icon: string}>
- */
-function default_payment_methods($language)
-{
- $translations = default_names_translations($language);
-
- $methods = [];
- foreach (DEFAULT_PAYMENT_METHODS as $method) {
- $methods[] = [
- 'name' => isset($method['key'])
- ? ($translations[$method['key']] ?? $method['key'])
- : $method['name'],
- 'icon' => $method['icon'],
- ];
- }
-
- return $methods;
-}
-
-/**
- * Renames the English default rows of the first account into its language.
- *
- * The first account of an installation is the one case where the rows exist
- * before a language does: createdatabase.php seeds the categories and payment
- * methods while the database is being created, and migration 000020 gives them
- * user_id 1, so registration.php never seeds them for that account. Its owner
- * picks a language on the registration form - the first moment anybody states
- * one - and gets English data anyway.
- *
- * Only a row whose name is still exactly the English default is touched, so
- * this cannot rewrite something somebody named themselves, and only the name
- * column changes: subscriptions reference a category and a payment method by
- * id, never by name.
- *
- * @param SQLite3 $db
- * @param int $userId
- * @param string $language
- * @return int how many rows were renamed
- */
-function localize_default_names($db, $userId, $language)
-{
- $renamed = 0;
-
- $renamed += default_names_rename(
- $db,
- $db->prepare('UPDATE categories SET name = :name WHERE user_id = :user_id AND name = :english'),
- $userId,
- default_categories('en'),
- default_categories($language)
- );
-
- $renamed += default_names_rename(
- $db,
- $db->prepare('UPDATE payment_methods SET name = :name WHERE user_id = :user_id AND name = :english'),
- $userId,
- array_column(default_payment_methods('en'), 'name'),
- array_column(default_payment_methods($language), 'name')
- );
-
- return $renamed;
-}
-
-/**
- * Runs one prepared rename over a pair of equally ordered name lists.
- *
- * @param SQLite3 $db
- * @param SQLite3Stmt|false $stmt
- * @param int $userId
- * @param string[] $english the name a still-default row carries
- * @param string[] $localized what it should say instead
- * @return int how many rows were renamed
- */
-function default_names_rename($db, $stmt, $userId, $english, $localized)
-{
- if ($stmt === false) {
- return 0;
- }
-
- $renamed = 0;
-
- foreach ($english as $index => $englishName) {
- // A brand, or a language that has no translation for this name yet.
- if ($localized[$index] === $englishName) {
- continue;
- }
-
- $stmt->bindValue(':name', $localized[$index], SQLITE3_TEXT);
- $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
- $stmt->bindValue(':english', $englishName, SQLITE3_TEXT);
-
- if ($stmt->execute() !== false) {
- $renamed += $db->changes();
- }
-
- $stmt->reset();
- }
-
- return $renamed;
-}
-
-/**
- * The "No category" text a fresh account in the given language got as its
- * untouched placeholder name.
- *
- * categories.id is one global sequence shared by every account, not one per
- * user, so only the very first row this application ever created is actually
- * id 1 - nothing here can tell "the placeholder row" apart from an ordinary
- * category by id. Comparing against the literal English string had the same
- * problem the other way once this file gave every language its own default:
- * a category still carrying its untouched default name no longer answers
- * "No category" for anybody who registered in a language other than English,
- * so it stopped being recognised as the placeholder at all.
- *
- * What a display site actually wants to know is whether this row is still
- * exactly what the account was seeded with, so it compares against that
- * account's own creation-language default, not a literal English string, and
- * re-translates it into whichever language is being viewed right now. A
- * category the owner has renamed matches neither and is shown as stored,
- * same as before this existed.
- *
- * @param string $language
- * @return string
- */
-function default_no_category_name($language)
-{
- $translations = default_names_translations($language);
-
- return $translations['no_category'] ?? 'No category';
-}
+<?php
+/*
+ The categories and payment methods a new account starts with, in the language
+ of that account.
+
+ The lists were repeated verbatim in every place that creates an account -
+ registration.php, endpoints/admin/adduser.php and
+ includes/oidc/oidc_create_user.php - and every copy was English. Somebody who
+ registered in German got an application that was German everywhere except in
+ its own data, on the very first screen they saw.
+
+ The categories and the generic payment methods are held here as translation
+ keys and resolved once, at the moment the account is created. What is stored
+ is ordinary text the owner renames, reorders and deletes like any other row,
+ so changing the account language later never rewrites it - the same contract
+ the rows have always had.
+
+ Brand names - PayPal, SEPA, Klarna - are the same word in every language and
+ stay literal.
+
+ Currencies are deliberately not here. Their names are a separate list with a
+ separate problem (a currency is identified by its ISO code, not by its name),
+ and folding them in would make this change about something else.
+*/
+
+/**
+ * Translation keys of the default categories, in display order.
+ *
+ * The keys are the contract; the English strings live in the language files
+ * like every other translation. "no_category" is an existing key, translated
+ * in every language file already.
+ *
+ * @var string[]
+ */
+const DEFAULT_CATEGORY_KEYS = [
+ 'no_category',
+ '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',
+];
+
+/**
+ * The default payment methods, in display order.
+ *
+ * A generic term - "Credit Card", "Bank Transfer", "Direct Debit", "Money" -
+ * reads differently to a German and to an English speaker, so it carries a
+ * translation "key". A brand is the same word in every language, so it keeps a
+ * literal "name".
+ *
+ * @var array<int, array{name?: string, key?: string, icon: string}>
+ */
+const DEFAULT_PAYMENT_METHODS = [
+ ['name' => 'PayPal', 'icon' => 'images/uploads/icons/paypal.png'],
+ ['key' => 'payment_method_credit_card', 'icon' => 'images/uploads/icons/creditcard.png'],
+ ['key' => 'payment_method_bank_transfer', 'icon' => 'images/uploads/icons/banktransfer.png'],
+ ['key' => 'payment_method_direct_debit', 'icon' => 'images/uploads/icons/directdebit.png'],
+ ['key' => 'payment_method_money', 'icon' => 'images/uploads/icons/money.png'],
+ ['name' => 'Google Pay', 'icon' => 'images/uploads/icons/googlepay.png'],
+ ['name' => 'Samsung Pay', 'icon' => 'images/uploads/icons/samsungpay.png'],
+ ['name' => 'Apple Pay', 'icon' => 'images/uploads/icons/applepay.png'],
+ ['name' => 'Crypto', 'icon' => 'images/uploads/icons/crypto.png'],
+ ['name' => 'Klarna', 'icon' => 'images/uploads/icons/klarna.png'],
+ ['name' => 'Amazon Pay', 'icon' => 'images/uploads/icons/amazonpay.png'],
+ ['name' => 'SEPA', 'icon' => 'images/uploads/icons/sepa.png'],
+ ['name' => 'Skrill', 'icon' => 'images/uploads/icons/skrill.png'],
+ ['name' => 'Sofort', 'icon' => 'images/uploads/icons/sofort.png'],
+ ['name' => 'Stripe', 'icon' => 'images/uploads/icons/stripe.png'],
+ ['name' => 'Affirm', 'icon' => 'images/uploads/icons/affirm.png'],
+ ['name' => 'AliPay', 'icon' => 'images/uploads/icons/alipay.png'],
+ ['name' => 'Elo', 'icon' => 'images/uploads/icons/elo.png'],
+ ['name' => 'Facebook Pay', 'icon' => 'images/uploads/icons/facebookpay.png'],
+ ['name' => 'GiroPay', 'icon' => 'images/uploads/icons/giropay.png'],
+ ['name' => 'iDeal', 'icon' => 'images/uploads/icons/ideal.png'],
+ ['name' => 'Union Pay', 'icon' => 'images/uploads/icons/unionpay.png'],
+ ['name' => 'Interac', 'icon' => 'images/uploads/icons/interac.png'],
+ ['name' => 'WeChat', 'icon' => 'images/uploads/icons/wechat.png'],
+ ['name' => 'Paysafe', 'icon' => 'images/uploads/icons/paysafe.png'],
+ ['name' => 'Poli', 'icon' => 'images/uploads/icons/poli.png'],
+ ['name' => 'Qiwi', 'icon' => 'images/uploads/icons/qiwi.png'],
+ ['name' => 'ShopPay', 'icon' => 'images/uploads/icons/shoppay.png'],
+ ['name' => 'Venmo', 'icon' => 'images/uploads/icons/venmo.png'],
+ ['name' => 'VeriFone', 'icon' => 'images/uploads/icons/verifone.png'],
+ ['name' => 'WebMoney', 'icon' => 'images/uploads/icons/webmoney.png'],
+];
+
+/**
+ * The translation table of one specific language.
+ *
+ * translate() answers in the language of the current request, which is not the
+ * language of the account being created: an administrator working in English
+ * creates an account for somebody whose language is German, and an identity
+ * provider names the language of an account nobody is looking at yet.
+ *
+ * A key the language file does not carry falls back to English, so a
+ * translation that has not been updated yet produces English rather than
+ * nothing.
+ *
+ * @param string $language
+ * @return array<string, string>
+ */
+function default_names_translations($language)
+{
+ static $tables = [];
+
+ // The value reaches this from a form field, an OIDC claim or the user
+ // table, and it decides a file name, so it is not taken on trust: anything
+ // that is not a plain identifier with a translation file is English, which
+ // is what the callers stored before.
+ $name = strtolower(str_replace('-', '_', trim((string) $language)));
+
+ if (preg_match('/^[a-z]{2}(_[a-z]{2,4})?$/', $name) !== 1
+ || !is_file(__DIR__ . '/i18n/' . $name . '.php')) {
+ $name = 'en';
+ }
+
+ if (!isset($tables[$name])) {
+ // The language files assign $i18n; required from inside a function it
+ // stays local, which is what makes loading a second language safe.
+ $i18n = [];
+ require __DIR__ . '/i18n/' . $name . '.php';
+ $table = $i18n;
+
+ if ($name !== 'en') {
+ $i18n = [];
+ require __DIR__ . '/i18n/en.php';
+ $table += $i18n;
+ }
+
+ $tables[$name] = $table;
+ }
+
+ return $tables[$name];
+}
+
+/**
+ * The default categories in one language, in display order.
+ *
+ * @param string $language
+ * @return string[]
+ */
+function default_categories($language)
+{
+ $translations = default_names_translations($language);
+
+ $categories = [];
+ foreach (DEFAULT_CATEGORY_KEYS as $key) {
+ $categories[] = $translations[$key] ?? $key;
+ }
+
+ return $categories;
+}
+
+/**
+ * The default payment methods in one language, in display order.
+ *
+ * @param string $language
+ * @return array<int, array{name: string, icon: string}>
+ */
+function default_payment_methods($language)
+{
+ $translations = default_names_translations($language);
+
+ $methods = [];
+ foreach (DEFAULT_PAYMENT_METHODS as $method) {
+ $methods[] = [
+ 'name' => isset($method['key'])
+ ? ($translations[$method['key']] ?? $method['key'])
+ : $method['name'],
+ 'icon' => $method['icon'],
+ ];
+ }
+
+ return $methods;
+}
+
+/**
+ * Renames the English default rows of the first account into its language.
+ *
+ * The first account of an installation is the one case where the rows exist
+ * before a language does: createdatabase.php seeds the categories and payment
+ * methods while the database is being created, and migration 000020 gives them
+ * user_id 1, so registration.php never seeds them for that account. Its owner
+ * picks a language on the registration form - the first moment anybody states
+ * one - and gets English data anyway.
+ *
+ * Only a row whose name is still exactly the English default is touched, so
+ * this cannot rewrite something somebody named themselves, and only the name
+ * column changes: subscriptions reference a category and a payment method by
+ * id, never by name.
+ *
+ * @param SQLite3 $db
+ * @param int $userId
+ * @param string $language
+ * @return int how many rows were renamed
+ */
+function localize_default_names($db, $userId, $language)
+{
+ $renamed = 0;
+
+ $renamed += default_names_rename(
+ $db,
+ $db->prepare('UPDATE categories SET name = :name WHERE user_id = :user_id AND name = :english'),
+ $userId,
+ default_categories('en'),
+ default_categories($language)
+ );
+
+ $renamed += default_names_rename(
+ $db,
+ $db->prepare('UPDATE payment_methods SET name = :name WHERE user_id = :user_id AND name = :english'),
+ $userId,
+ array_column(default_payment_methods('en'), 'name'),
+ array_column(default_payment_methods($language), 'name')
+ );
+
+ return $renamed;
+}
+
+/**
+ * Renames an account's still-default names when it changes its language.
+ *
+ * Seeding in the account's language covers accounts that are created after it
+ * existed; an account that switches its language later kept the names it was
+ * seeded with, so a household that moved Wallos to German went on reading
+ * "Entertainment" and "Credit Card" in a German interface.
+ *
+ * The guard is here rather than at the call site so it can be tested: a save
+ * that does not touch the language must not rename anything, and neither must
+ * a save that "changes" it to the value it already had.
+ *
+ * Only rows that still carry the English default are renamed, which is
+ * localize_default_names()'s own promise: a name somebody chose is never
+ * rewritten, and subscriptions reference a category or payment method by id,
+ * so nothing but the name column moves.
+ *
+ * @param SQLite3 $db
+ * @param int $userId
+ * @param string $before The language the account had.
+ * @param string $after The language it has now.
+ * @return int how many rows were renamed
+ */
+function localize_default_names_on_language_change($db, $userId, $before, $after)
+{
+ if ($after === '' || $before === $after) {
+ return 0;
+ }
+
+ return localize_default_names($db, $userId, $after);
+}
+
+/**
+ * Runs one prepared rename over a pair of equally ordered name lists.
+ *
+ * @param SQLite3 $db
+ * @param SQLite3Stmt|false $stmt
+ * @param int $userId
+ * @param string[] $english the name a still-default row carries
+ * @param string[] $localized what it should say instead
+ * @return int how many rows were renamed
+ */
+function default_names_rename($db, $stmt, $userId, $english, $localized)
+{
+ if ($stmt === false) {
+ return 0;
+ }
+
+ $renamed = 0;
+
+ foreach ($english as $index => $englishName) {
+ // A brand, or a language that has no translation for this name yet.
+ if ($localized[$index] === $englishName) {
+ continue;
+ }
+
+ $stmt->bindValue(':name', $localized[$index], SQLITE3_TEXT);
+ $stmt->bindValue(':user_id', $userId, SQLITE3_INTEGER);
+ $stmt->bindValue(':english', $englishName, SQLITE3_TEXT);
+
+ if ($stmt->execute() !== false) {
+ $renamed += $db->changes();
+ }
+
+ $stmt->reset();
+ }
+
+ return $renamed;
+}
+
+/**
+ * The "No category" text a fresh account in the given language got as its
+ * untouched placeholder name.
+ *
+ * categories.id is one global sequence shared by every account, not one per
+ * user, so only the very first row this application ever created is actually
+ * id 1 - nothing here can tell "the placeholder row" apart from an ordinary
+ * category by id. Comparing against the literal English string had the same
+ * problem the other way once this file gave every language its own default:
+ * a category still carrying its untouched default name no longer answers
+ * "No category" for anybody who registered in a language other than English,
+ * so it stopped being recognised as the placeholder at all.
+ *
+ * What a display site actually wants to know is whether this row is still
+ * exactly what the account was seeded with, so it compares against that
+ * account's own creation-language default, not a literal English string, and
+ * re-translates it into whichever language is being viewed right now. A
+ * category the owner has renamed matches neither and is shown as stored,
+ * same as before this existed.
+ *
+ * @param string $language
+ * @return string
+ */
+function default_no_category_name($language)
+{
+ $translations = default_names_translations($language);
+
+ return $translations['no_category'] ?? 'No category';
+}
diff --git a/tests/cases/default_names_test.php b/tests/cases/default_names_test.php
index ebe6708..f5c5012 100644
--- a/tests/cases/default_names_test.php
+++ b/tests/cases/default_names_test.php
@@ -378,3 +378,53 @@ wallos_test('every display site recognises the placeholder by language, not by a
$path . ' no longer compares against the English literal');
}
});
+
+wallos_test('an account that changes its language takes its default names with it', function () {
+ $db = wallos_test_open_database();
+ wallos_test_create_user($db, 1, 'alice');
+
+ // A name of her own, to stay as it is.
+ $statement = $db->prepare('UPDATE categories SET name = :name WHERE user_id = 1 AND name = :english');
+ $statement->bindValue(':name', 'Kids', SQLITE3_TEXT);
+ $statement->bindValue(':english', 'Gaming', SQLITE3_TEXT);
+ $statement->execute();
+
+ $renamed = localize_default_names_on_language_change($db, 1, 'en', 'de');
+
+ assert_true($renamed > 0, 'the switch renames the seeded names');
+
+ $categories = default_names_test_rows($db, 'categories', 1);
+ assert_true(in_array('Unterhaltung', $categories, true), 'a seeded category now reads in German');
+ assert_true(in_array('Kids', $categories, true), 'and the one she named herself is untouched');
+ assert_true(!in_array('Entertainment', $categories, true), 'nothing seeded is left in English');
+
+ $methods = default_names_test_rows($db, 'payment_methods', 1);
+ assert_true(in_array('Kreditkarte', $methods, true), 'the generic payment methods follow too');
+ assert_true(in_array('PayPal', $methods, true), 'and a brand stays a brand');
+
+ $db->close();
+});
+
+wallos_test('a save that does not change the language renames nothing', function () {
+ $db = wallos_test_open_database();
+ wallos_test_create_user($db, 1, 'alice');
+
+ assert_same(0, localize_default_names_on_language_change($db, 1, 'de', 'de'),
+ 'the same language twice is not a change');
+ assert_same(0, localize_default_names_on_language_change($db, 1, 'en', ''),
+ 'and neither is a save that carries no language at all');
+
+ assert_same('Entertainment', default_names_test_rows($db, 'categories', 1)[1],
+ 'so the rows are as they were');
+
+ $db->close();
+});
+
+wallos_test('the endpoint that saves a language is the one that applies it', function () {
+ $source = file_get_contents(WALLOS_ROOT . '/endpoints/user/save_user.php');
+
+ assert_contains('localize_default_names_on_language_change($db, $userId, $storedLanguage, $language)', $source,
+ 'save_user.php applies the change through the guarded helper');
+ assert_contains('SELECT main_currency, language FROM user WHERE id = :userId', $source,
+ 'and it reads the language it had, in the query it already ran');
+});