Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.
feat: create dark and light theme versions of the logos when removing background
Miguel Ribeiro8d22f0435372
diff --git a/Dockerfile b/Dockerfileindex fff5e57..95f4930 100644--- a/Dockerfile+++ b/Dockerfile@@ -6,15 +6,11 @@ WORKDIR /var/www/html# Update packages and install dependenciesRUN apk upgrade --no-cache && \- apk add --no-cache dumb-init shadow sqlite-dev libpng libpng-dev libjpeg-turbo libjpeg-turbo-dev freetype freetype-dev curl autoconf libgomp icu-dev icu-data-full nginx dcron tzdata imagemagick imagemagick-dev libzip-dev sqlite libwebp-dev && \+ apk add --no-cache dumb-init shadow sqlite-dev libpng libpng-dev libjpeg-turbo libjpeg-turbo-dev freetype freetype-dev curl autoconf libgomp icu-dev icu-data-full nginx dcron tzdata libzip-dev sqlite libwebp-dev && \docker-php-ext-install pdo pdo_sqlite calendar && \docker-php-ext-enable pdo pdo_sqlite && \docker-php-ext-configure gd --with-freetype --with-jpeg --with-webp && \- docker-php-ext-install -j$(nproc) gd intl zip && \- apk add --no-cache --virtual .build-deps $PHPIZE_DEPS && \- pecl install imagick && \- docker-php-ext-enable imagick && \- apk del .build-deps+ docker-php-ext-install -j$(nproc) gd intl zip# Copy your PHP application files into the containerCOPY . .diff --git a/README.md b/README.mdindex 9033bee..dd37b12 100644--- a/README.md+++ b/README.md@@ -84,7 +84,6 @@ See instructions to run Wallos below.- curl- dom- gd- - imagick- intl- openssl- sqlite3diff --git a/admin.php b/admin.phpindex 0d6fb39..d2604f7 100644--- a/admin.php+++ b/admin.php@@ -93,7 +93,6 @@ $loginDisabledAllowed = $userCount == 1 && $settings['registrations_open'] == 0;<?= translate('server_url_password_reset', $i18n) ?></p></div>- <hr><div class="form-group-inline"><input type="checkbox" id="disableLogin" <?= $settings['login_disabled'] ? 'checked' : '' ?><?= $loginDisabledAllowed ? '' : 'disabled' ?> />diff --git a/api/payment_methods/set_payment_methods.php b/api/payment_methods/set_payment_methods.phpindex 48f8d16..9f029e4 100644--- a/api/payment_methods/set_payment_methods.php+++ b/api/payment_methods/set_payment_methods.php@@ -169,30 +169,15 @@ function saveLogo($imageData, $uploadFile, $name, $settings)imagepng($image, $tempFile);imagedestroy($image);- if (extension_loaded('imagick')) {- $imagick = new Imagick($tempFile);- if ($removeBackground) {- $fuzz = Imagick::getQuantum() * 0.1; // 10%- $imagick->transparentPaintImage("rgb(247, 247, 247)", 0, $fuzz, false);- }- $imagick->trimImage(0);- $imagick->setImagePage(0, 0, 0, 0);- $imagick->borderImage(new ImagickPixel('transparent'), 2, 2);- $imagick->setImageFormat('png');- $imagick->writeImage($uploadFile);- $imagick->clear();- $imagick->destroy();- } else {- $newImage = imagecreatefrompng($tempFile);- if ($removeBackground) {- require_once __DIR__ . '/../../includes/gd_background_removal.php';- gdRemoveBackgroundColor($newImage, 247, 247, 247);- }+ $newImage = imagecreatefrompng($tempFile);+ if ($removeBackground) {require_once __DIR__ . '/../../includes/gd_background_removal.php';- $newImage = gdCropTransparent($newImage, 2);- imagepng($newImage, $uploadFile);- imagedestroy($newImage);+ gdRemoveBackgroundColor($newImage, 247, 247, 247);}+ require_once __DIR__ . '/../../includes/gd_background_removal.php';+ $newImage = gdCropTransparent($newImage, 2);+ imagepng($newImage, $uploadFile);+ imagedestroy($newImage);unlink($tempFile);return true;}diff --git a/api/subscriptions/set_subscriptions.php b/api/subscriptions/set_subscriptions.phpindex 26ae205..b8cc34e 100644--- a/api/subscriptions/set_subscriptions.php+++ b/api/subscriptions/set_subscriptions.php@@ -190,54 +190,31 @@ function saveLogo($imageData, $uploadFile, $name, $settings)imagepng($image, $tempFile);imagedestroy($image);- if (extension_loaded('imagick')) {- $imagick = new Imagick($tempFile);+ $newImage = imagecreatefrompng($tempFile);+ if ($newImage !== false) {+ imagealphablending($newImage, false);+ imagesavealpha($newImage, true);if ($removeBackground) {- $imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);- $pixel = $imagick->getImagePixelColor(0, 0);- $color = $pixel->getColor();- if ($color['a'] > 0) {- $bgColor = "rgb({$color['r']},{$color['g']},{$color['b']})";- $fuzz = Imagick::getQuantum() * 0.1;- $imagick->transparentPaintImage($bgColor, 0, $fuzz, false);+ require_once __DIR__ . '/../../includes/gd_background_removal.php';+ if (!imageistruecolor($newImage)) {+ imagepalettetotruecolor($newImage);+ imagealphablending($newImage, false);+ imagesavealpha($newImage, true);+ }+ $corner = imagecolorat($newImage, 0, 0);+ if ((($corner >> 24) & 0x7F) !== 127) {+ gdRemoveBackgroundColor($newImage, ($corner >> 16) & 0xFF, ($corner >> 8) & 0xFF, $corner & 0xFF);}}- $imagick->trimImage(0);- $imagick->setImagePage(0, 0, 0, 0);- $imagick->borderImage(new ImagickPixel('transparent'), 2, 2);- $imagick->setImageFormat('png');- $imagick->writeImage($uploadFile);- $imagick->clear();- $imagick->destroy();+ require_once __DIR__ . '/../../includes/gd_background_removal.php';+ $newImage = gdCropTransparent($newImage, 2);+ imagepng($newImage, $uploadFile);+ imagedestroy($newImage);} else {- $newImage = imagecreatefrompng($tempFile);- if ($newImage !== false) {- imagealphablending($newImage, false);- imagesavealpha($newImage, true);-- if ($removeBackground) {- require_once __DIR__ . '/../../includes/gd_background_removal.php';- if (!imageistruecolor($newImage)) {- imagepalettetotruecolor($newImage);- imagealphablending($newImage, false);- imagesavealpha($newImage, true);- }- $corner = imagecolorat($newImage, 0, 0);- if ((($corner >> 24) & 0x7F) !== 127) {- gdRemoveBackgroundColor($newImage, ($corner >> 16) & 0xFF, ($corner >> 8) & 0xFF, $corner & 0xFF);- }- }-- require_once __DIR__ . '/../../includes/gd_background_removal.php';- $newImage = gdCropTransparent($newImage, 2);- imagepng($newImage, $uploadFile);- imagedestroy($newImage);- } else {- unlink($tempFile);- return false;- }+ unlink($tempFile);+ return false;}unlink($tempFile);diff --git a/endpoints/payments/add.php b/endpoints/payments/add.phpindex 96a59c4..3374b3d 100644--- a/endpoints/payments/add.php+++ b/endpoints/payments/add.php@@ -96,37 +96,18 @@ function saveLogo($imageData, $uploadFile, $name, $settings)imagepng($image, $tempFile);imagedestroy($image);- if (extension_loaded('imagick')) {- $imagick = new Imagick($tempFile);- if ($removeBackground) {- $fuzz = Imagick::getQuantum() * 0.1; // 10%- $imagick->transparentPaintImage("rgb(247, 247, 247)", 0, $fuzz, false);- }- // Crop/trim transparent margins (with 2px transparent padding added back to avoid touching the borders)- $imagick->trimImage(0);- $imagick->setImagePage(0, 0, 0, 0);- $imagick->borderImage(new ImagickPixel('transparent'), 2, 2);-- $imagick->setImageFormat('png');- $imagick->writeImage($uploadFile);-- $imagick->clear();- $imagick->destroy();- } else {- // Alternative method if Imagick is not available- $newImage = imagecreatefrompng($tempFile);- if ($removeBackground) {- require_once __DIR__ . '/../../includes/gd_background_removal.php';- // Match the Imagick branch: paint out the same near-white background with ~10% fuzz- gdRemoveBackgroundColor($newImage, 247, 247, 247);- }- // Crop/trim transparent margins+ $newImage = imagecreatefrompng($tempFile);+ if ($removeBackground) {require_once __DIR__ . '/../../includes/gd_background_removal.php';- $newImage = gdCropTransparent($newImage, 2);-- imagepng($newImage, $uploadFile);- imagedestroy($newImage);+ // Paint out the near-white background with ~10% fuzz+ gdRemoveBackgroundColor($newImage, 247, 247, 247);}+ // Crop/trim transparent margins+ require_once __DIR__ . '/../../includes/gd_background_removal.php';+ $newImage = gdCropTransparent($newImage, 2);++ imagepng($newImage, $uploadFile);+ imagedestroy($newImage);unlink($tempFile);return true;diff --git a/endpoints/subscription/add.php b/endpoints/subscription/add.phpindex f4c83ab..6e6e5e1 100644--- a/endpoints/subscription/add.php+++ b/endpoints/subscription/add.php@@ -5,6 +5,7 @@ require_once '../../includes/validate_endpoint.php';require_once '../../includes/inputvalidation.php';require_once '../../includes/getsettings.php';require_once '../../includes/ssrf_helper.php';+require_once '../../includes/logo_theme_variant.php';if (!file_exists('../../images/uploads/logos')) {mkdir('../../images/uploads/logos', 0777, true);@@ -100,62 +101,35 @@ function saveLogo($imageData, $uploadFile, $name, $settings)imagepng($image, $tempFile);imagedestroy($image);- if (extension_loaded('imagick')) {- $imagick = new Imagick($tempFile);+ $newImage = imagecreatefrompng($tempFile);+ if ($newImage !== false) {+ imagealphablending($newImage, false);+ imagesavealpha($newImage, true);if ($removeBackground) {- $imagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_ACTIVATE);-- $pixel = $imagick->getImagePixelColor(0, 0);- $color = $pixel->getColor();- if ($color['a'] > 0) {- $bgColor = "rgb({$color['r']},{$color['g']},{$color['b']})";- $fuzz = Imagick::getQuantum() * 0.1;- $imagick->transparentPaintImage($bgColor, 0, $fuzz, false);+ require_once __DIR__ . '/../../includes/gd_background_removal.php';+ // On palette images imagecolorat() returns palette indexes, not RGB values+ if (!imageistruecolor($newImage)) {+ imagepalettetotruecolor($newImage);+ imagealphablending($newImage, false);+ imagesavealpha($newImage, true);+ }+ // Paint out the corner color with ~10% fuzz+ $corner = imagecolorat($newImage, 0, 0);+ if ((($corner >> 24) & 0x7F) !== 127) {+ gdRemoveBackgroundColor($newImage, ($corner >> 16) & 0xFF, ($corner >> 8) & 0xFF, $corner & 0xFF);}}- // Crop/trim transparent margins (with 2px transparent padding added back to avoid touching the borders)- $imagick->trimImage(0);- $imagick->setImagePage(0, 0, 0, 0);- $imagick->borderImage(new ImagickPixel('transparent'), 2, 2);-- $imagick->setImageFormat('png');- $imagick->writeImage($uploadFile);- $imagick->clear();- $imagick->destroy();+ // Crop/trim transparent margins+ require_once __DIR__ . '/../../includes/gd_background_removal.php';+ $newImage = gdCropTransparent($newImage, 2);+ imagepng($newImage, $uploadFile);+ imagedestroy($newImage);} else {- $newImage = imagecreatefrompng($tempFile);- if ($newImage !== false) {- imagealphablending($newImage, false);- imagesavealpha($newImage, true);-- if ($removeBackground) {- require_once __DIR__ . '/../../includes/gd_background_removal.php';- // On palette images imagecolorat() returns palette indexes, not RGB values- if (!imageistruecolor($newImage)) {- imagepalettetotruecolor($newImage);- imagealphablending($newImage, false);- imagesavealpha($newImage, true);- }- // Match the Imagick branch: paint out the corner color with ~10% fuzz- $corner = imagecolorat($newImage, 0, 0);- if ((($corner >> 24) & 0x7F) !== 127) {- gdRemoveBackgroundColor($newImage, ($corner >> 16) & 0xFF, ($corner >> 8) & 0xFF, $corner & 0xFF);- }- }-- // Crop/trim transparent margins- require_once __DIR__ . '/../../includes/gd_background_removal.php';- $newImage = gdCropTransparent($newImage, 2);-- imagepng($newImage, $uploadFile);- imagedestroy($newImage);- } else {- unlink($tempFile);- return false;- }+ unlink($tempFile);+ return false;}unlink($tempFile);@@ -302,17 +276,49 @@ if ($logoUrl !== "") {}}+$logoTextColor = null;+$logoVariant = null;+$removeBackgroundEnabled = isset($settings['removeBackground']) && $settings['removeBackground'] === 'true';++// Themed variant generation piggybacks on the same "remove background"+// setting: both only make sense for logos we're already reprocessing, and+// this avoids running pixel classification on every single upload.+if ($logo !== "" && $removeBackgroundEnabled) {+ $logoExtension = strtolower(pathinfo($logo, PATHINFO_EXTENSION));+ $logoPath = '../../images/uploads/logos/' . $logo;++ if ($logoExtension === 'png' || $logoExtension === 'webp') {+ $sourceImage = $logoExtension === 'png' ? imagecreatefrompng($logoPath) : imagecreatefromwebp($logoPath);++ if ($sourceImage !== false) {+ imagealphablending($sourceImage, false);+ imagesavealpha($sourceImage, true);++ $logoTextColor = classifyLogoTextColor($sourceImage);++ if ($logoTextColor !== null) {+ $variantImage = generateThemedLogoVariant($sourceImage);+ $logoVariant = pathinfo($logo, PATHINFO_FILENAME) . '-variant.png';+ imagepng($variantImage, '../../images/uploads/logos/' . $logoVariant);+ imagedestroy($variantImage);+ }++ imagedestroy($sourceImage);+ }+ }+}+if (!$isEdit) {$sql = "INSERT INTO subscriptions (- name, logo, price, currency_id, next_payment, cycle, frequency, notes,- payment_method_id, payer_user_id, category_id, notify, inactive, url,+ name, logo, price, currency_id, next_payment, cycle, frequency, notes,+ payment_method_id, payer_user_id, category_id, notify, inactive, url,notify_days_before, user_id, cancellation_date, replacement_subscription_id,- auto_renew, start_date+ auto_renew, start_date, logo_text_color, logo_variant) VALUES (- :name, :logo, :price, :currencyId, :nextPayment, :cycle, :frequency, :notes,- :paymentMethodId, :payerUserId, :categoryId, :notify, :inactive, :url,+ :name, :logo, :price, :currencyId, :nextPayment, :cycle, :frequency, :notes,+ :paymentMethodId, :payerUserId, :categoryId, :notify, :inactive, :url,:notifyDaysBefore, :userId, :cancellationDate, :replacement_subscription_id,- :autoRenew, :startDate+ :autoRenew, :startDate, :logoTextColor, :logoVariant)";} else {$id = $_POST['id'];@@ -337,7 +343,7 @@ if (!$isEdit) {replacement_subscription_id = :replacement_subscription_id";if ($logo != "") {- $sql .= ", logo = :logo";+ $sql .= ", logo = :logo, logo_text_color = :logoTextColor, logo_variant = :logoVariant";}$sql .= " WHERE id = :id AND user_id = :userId";@@ -347,6 +353,8 @@ $stmt = $db->prepare($sql);$stmt->bindParam(':name', $name, SQLITE3_TEXT);if ($logo != "") {$stmt->bindParam(':logo', $logo, SQLITE3_TEXT);+ $stmt->bindParam(':logoTextColor', $logoTextColor, SQLITE3_TEXT);+ $stmt->bindParam(':logoVariant', $logoVariant, SQLITE3_TEXT);}$stmt->bindParam(':price', $price, SQLITE3_FLOAT);$stmt->bindParam(':currencyId', $currencyId, SQLITE3_INTEGER);diff --git a/endpoints/subscription/get.php b/endpoints/subscription/get.phpindex 31bd2bf..9e6cfd1 100644--- a/endpoints/subscription/get.php+++ b/endpoints/subscription/get.php@@ -16,6 +16,8 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {$subscriptionData['id'] = $subscriptionId;$subscriptionData['name'] = htmlspecialchars_decode($row['name'] ?? "");$subscriptionData['logo'] = $row['logo'];+ $subscriptionData['logo_text_color'] = $row['logo_text_color'];+ $subscriptionData['logo_variant'] = $row['logo_variant'];$subscriptionData['price'] = $row['price'];$subscriptionData['currency_id'] = $row['currency_id'];$subscriptionData['auto_renew'] = $row['auto_renew'];@@ -43,6 +45,10 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {} else {echo translate('error', $i18n);}+} else {+ http_response_code(401);+ header('Content-Type: application/json');+ echo json_encode(['error' => translate('session_expired', $i18n)]);}$db->close();?>\ No newline at end of filediff --git a/endpoints/subscriptions/get.php b/endpoints/subscriptions/get.phpindex bdf1f9a..d14be44 100644--- a/endpoints/subscriptions/get.php+++ b/endpoints/subscriptions/get.php@@ -3,6 +3,7 @@ require_once '../../includes/connect_endpoint.php';require_once '../../includes/currency_formatter.php';require_once '../../includes/getdbkeys.php';+require_once '../../includes/logo_theme_variant.php';include_once '../../includes/list_subscriptions.php';@@ -178,6 +179,8 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {$id = $subscription['id'];$print[$id]['id'] = $id;$print[$id]['logo'] = $subscription['logo'] != "" ? "images/uploads/logos/" . $subscription['logo'] : "";+ $print[$id]['logo_text_color'] = $subscription['logo_text_color'] ?? null;+ $print[$id]['logo_variant'] = !empty($subscription['logo_variant']) ? "images/uploads/logos/" . $subscription['logo_variant'] : null;$print[$id]['name'] = $subscription['name'] ?? "";$cycle = $subscription['cycle'];$frequency = $subscription['frequency'];@@ -257,6 +260,11 @@ if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {</div><?php}+} else {+ http_response_code(401);+ ?>+ <p class="no-matching-subscriptions"><?= translate('session_expired', $i18n) ?></p>+ <?php}$db->close();diff --git a/includes/checksession.php b/includes/checksession.phpindex c07df87..124d1e5 100644--- a/includes/checksession.php+++ b/includes/checksession.php@@ -1,4 +1,6 @@<?php+require_once 'remember_me.php';+// Handle OIDC first$secondsInMonth = 30 * 24 * 60 * 60;if (session_status() === PHP_SESSION_NONE) {@@ -54,72 +56,24 @@ if (isset($_GET['code']) && isset($_GET['state'])) {$userData['avatar'] = "0";}} else {-- if (isset($_COOKIE['wallos_login'])) {- $cookie = explode('|', $_COOKIE['wallos_login'], 3);- $username = $cookie[0];- $token = $cookie[1];- $main_currency = $cookie[2];-- $sql = "SELECT * FROM user WHERE username = :username";- $stmt = $db->prepare($sql);- $stmt->bindValue(':username', $username, SQLITE3_TEXT);- $result = $stmt->execute();-- if ($result) {- $userData = $result->fetchArray(SQLITE3_ASSOC);- if (!isset($userData['id'])) {- $db->close();- header("Location: logout.php");- exit();- }-- if ($userData['avatar'] == "") {- $userData['avatar'] = "0";- }- $userId = $userData['id'];- $main_currency = $userData['main_currency'];-- $adminQuery = "SELECT login_disabled FROM admin";- $adminResult = $db->query($adminQuery);- $adminRow = $adminResult->fetchArray(SQLITE3_ASSOC);- if ($adminRow['login_disabled'] == 1) {- $sql = "SELECT * FROM login_tokens WHERE user_id = :userId";- $stmt = $db->prepare($sql);- $stmt->bindParam(':userId', $userId, SQLITE3_TEXT);- } else {- $sql = "SELECT * FROM login_tokens WHERE user_id = :userId AND token = :token";- $stmt = $db->prepare($sql);- $stmt->bindParam(':userId', $userId, SQLITE3_TEXT);- $stmt->bindParam(':token', $token, SQLITE3_TEXT);- }- $result = $stmt->execute();- $row = $result->fetchArray(SQLITE3_ASSOC);-- if ($row != false) {- session_regenerate_id(true);- $_SESSION['username'] = $username;- $_SESSION['token'] = $token;- $_SESSION['loggedin'] = true;- $_SESSION['main_currency'] = $main_currency;- $_SESSION['userId'] = $userId;- } else {- $db->close();- header("Location: logout.php");- exit();- }- } else {- $db->close();- header("Location: logout.php");- exit();- }--- } else {+ if (!isset($_COOKIE['wallos_login'])) {$db->close();header("Location: login.php");exit();}++ $userData = restoreSessionFromRememberMeCookie($db);+ if ($userData === false) {+ $db->close();+ header("Location: logout.php");+ exit();+ }++ if ($userData['avatar'] == "") {+ $userData['avatar'] = "0";+ }+ $userId = $userData['id'];+ $main_currency = $userData['main_currency'];}}diff --git a/includes/connect_endpoint.php b/includes/connect_endpoint.phpindex a0a431e..e291647 100644--- a/includes/connect_endpoint.php+++ b/includes/connect_endpoint.php@@ -11,13 +11,14 @@ if (!$db) {require_once 'i18n/languages.php';require_once 'i18n/getlang.php';require_once 'i18n/' . $lang . '.php';+require_once 'remember_me.php';$secondsInMonth = 30 * 24 * 60 * 60;if (session_status() === PHP_SESSION_NONE) {session_set_cookie_params([- 'lifetime' => $secondsInMonth,- 'httponly' => true,- 'samesite' => 'Lax'+ 'lifetime' => $secondsInMonth,+ 'httponly' => true,+ 'samesite' => 'Lax']);session_start();}@@ -25,7 +26,12 @@ if (session_status() === PHP_SESSION_NONE) {if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {$userId = $_SESSION['userId'];} else {- $userId = 0;+ // The PHP session can be garbage-collected (default ~24 min) long before+ // the "remember me" cookie should expire (30 days). Fall back to it here,+ // the same way full page loads do via checksession.php, so AJAX/API+ // endpoints don't silently behave as logged-out after an idle period.+ $restoredUser = restoreSessionFromRememberMeCookie($db);+ $userId = $restoredUser !== false ? $restoredUser['id'] : 0;}?>\ No newline at end of filediff --git a/includes/gd_background_removal.php b/includes/gd_background_removal.phpindex b7f0375..d30d7cd 100644--- a/includes/gd_background_removal.php+++ b/includes/gd_background_removal.php@@ -1,8 +1,7 @@<?php/*- GD fallback equivalent of Imagick::transparentPaintImage() with fuzz:- makes every pixel within the tolerance of the given color fully transparent.- Used by the logo/icon upload endpoints when the imagick extension is missing.+ Makes every pixel within the tolerance of the given color fully transparent.+ Used by the logo/icon upload endpoints for background removal.*/function gdRemoveBackgroundColor($image, $backgroundRed, $backgroundGreen, $backgroundBlue, $fuzz = 0.1){@@ -45,8 +44,24 @@ function gdCropTransparent($image, $padding = 2)imagepalettetotruecolor($image);}+ // imagecrop() (called below) doesn't reliably preserve the alpha channel+ // on images that went through imagepalettetotruecolor() at any point --+ // even once imageistruecolor() reports true and imagecolorat() reads+ // back the correct alpha, imagecrop() can still flatten transparent+ // pixels to opaque black. Re-copying onto a freshly created truecolor++ // alpha canvas unconditionally sidesteps this, since a "genuinely native"+ // truecolor image doesn't have the issue.$width = imagesx($image);$height = imagesy($image);+ $fixed = imagecreatetruecolor($width, $height);+ imagealphablending($fixed, false);+ imagesavealpha($fixed, true);+ $transparent = imagecolorallocatealpha($fixed, 0, 0, 0, 127);+ imagefill($fixed, 0, 0, $transparent);+ imagealphablending($fixed, false);+ imagecopy($fixed, $image, 0, 0, 0, 0, $width, $height);+ imagedestroy($image);+ $image = $fixed;$top = null;$bottom = null;diff --git a/includes/i18n/ca.php b/includes/i18n/ca.phpindex 351519f..8c8f95d 100644--- a/includes/i18n/ca.php+++ b/includes/i18n/ca.php@@ -285,6 +285,7 @@ $i18n = ["experimental_settings" => "Configuracions Experimentals","remove_background" => "Intentar eliminar el fons dels logotips quan es fa la cerca d'imatges","use_mobile_navigation_bar" => "Utilitzar la barra de navegació mòbil",+ "remove_background_info" => "Això també genera una segona versió, amb els colors ajustats, del logotip perquè es mantingui llegible en canviar entre el tema clar i el fosc.","experimental_info" => "És possible que les configuracions experimentals no funcionin perfectament.","payment_methods" => "Mètodes de Pagament","payment_methods_info" => "Fes clic en un mètode de pagament per desactivar-lo/activar-lo.",diff --git a/includes/i18n/cs.php b/includes/i18n/cs.phpindex 254ad40..8acbe71 100644--- a/includes/i18n/cs.php+++ b/includes/i18n/cs.php@@ -285,6 +285,7 @@ $i18n = ["experimental_settings" => "Experimentální nastavení","remove_background" => "Pokusit se odstranit pozadí log z vyhledávání obrázků","use_mobile_navigation_bar" => "Použít mobilní navigační panel",+ "remove_background_info" => "Tím se také vytvoří druhá, přebarvená verze loga, aby zůstalo čitelné při přepínání mezi světlým a tmavým motivem.","experimental_info" => "Experimentální nastavení pravděpodobně nebude fungovat dokonale.","payment_methods" => "Platební metody","payment_methods_info" => "Kliknutím na platební metodu ji zakážete nebo povolíte.",diff --git a/includes/i18n/da.php b/includes/i18n/da.phpindex 1cdac47..8bdc7d2 100644--- a/includes/i18n/da.php+++ b/includes/i18n/da.php@@ -285,6 +285,7 @@ $i18n = ["experimental_settings" => "Eksperimentelle indstillinger","remove_background" => "Forsøg at fjerne baggrund på logoer ved billedsøgning","use_mobile_navigation_bar" => "Brug mobil navigationsbjælke",+ "remove_background_info" => "Dette genererer også en anden, omfarvet version af logoet, så det forbliver læsbart, når du skifter mellem lyst og mørkt tema.","experimental_info" => "Eksperimentelle indstillinger fungerer sandsynligvis ikke perfekt.","payment_methods" => "Betalingsmetoder","payment_methods_info" => "Klik på en betalingsmetode for at deaktivere / aktivere den.",diff --git a/includes/i18n/de.php b/includes/i18n/de.phpindex 5fac00a..6b8fb63 100644--- a/includes/i18n/de.php+++ b/includes/i18n/de.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Experimentelle Einstellungen","remove_background" => "Versuchen den Hintergrund von Logos aus der Bildersuche zu entfernen","use_mobile_navigation_bar" => "Mobile Navigationsleiste verwenden",+ "remove_background_info" => "Dadurch wird außerdem eine zweite, umgefärbte Version des Logos erstellt, damit es beim Wechsel zwischen hellem und dunklem Design lesbar bleibt.","experimental_info" => "Experimentelle Einstellungen funktionieren möglicherweise nicht perfekt.","payment_methods" => "Zahlungsmethoden","payment_methods_info" => "Zahlungsmethode zum (de-)aktivieren anklicken.",diff --git a/includes/i18n/el.php b/includes/i18n/el.phpindex 3b33626..42af006 100644--- a/includes/i18n/el.php+++ b/includes/i18n/el.php@@ -282,6 +282,7 @@ $i18n = ["experimental_settings" => "Πειραματικές ρυθμίσεις","remove_background" => "Προσπάθεια αφαίρεσης του φόντου των λογότυπων από την αναζήτηση εικόνας","use_mobile_navigation_bar" => "Χρήση μπάρας πλοήγησης για κινητά",+ "remove_background_info" => "Αυτό δημιουργεί επίσης μια δεύτερη, επαναχρωματισμένη έκδοση του λογότυπου, ώστε να παραμένει ευανάγνωστο όταν εναλλάσσετε ανάμεσα σε ανοιχτό και σκούρο θέμα.","experimental_info" => "Οι πειραματικές ρυθμίσεις πιθανότατα δεν θα λειτουργούν τέλεια.","payment_methods" => "Τρόποι πληρωμής","payment_methods_info" => "Κάνε κλικ σε μια μέθοδο πληρωμής για να την απενεργοποιήσεις/ενεργοποιήσεις.",diff --git a/includes/i18n/en.php b/includes/i18n/en.phpindex f510a46..a3aa411 100644--- a/includes/i18n/en.php+++ b/includes/i18n/en.php@@ -310,6 +310,7 @@ $i18n = ["experimental_settings" => "Experimental Settings","remove_background" => "Attempt to remove background of logos from image search","use_mobile_navigation_bar" => "Use mobile navigation bar",+ "remove_background_info" => "This also generates a second, recolored version of the logo so it stays legible when you switch between light and dark theme.","experimental_info" => "Experimental settings will probably not work perfectly.","payment_methods" => "Payment Methods","payment_methods_info" => "Click a payment method to disable / enable it.",diff --git a/includes/i18n/es.php b/includes/i18n/es.phpindex 870b272..1ffcbb7 100644--- a/includes/i18n/es.php+++ b/includes/i18n/es.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Configuraciones Experimentales","remove_background" => "Intentar quitar el fondo de los logotipos de la búsqueda de imágenes","use_mobile_navigation_bar" => "Usar barra de navegación móvil",+ "remove_background_info" => "Esto también genera una segunda versión del logotipo, con los colores ajustados, para que siga siendo legible al cambiar entre el tema claro y el oscuro.","experimental_info" => "Las configuraciones experimentales probablemente no funcionarán perfectamente.","payment_methods" => "Métodos de Pago","payment_methods_info" => "Haz clic en un método de pago para deshabilitarlo/habilitarlo.",diff --git a/includes/i18n/fr.php b/includes/i18n/fr.phpindex c401d5e..9f82fcb 100644--- a/includes/i18n/fr.php+++ b/includes/i18n/fr.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Paramètres expérimentaux","remove_background" => "Tenter de supprimer l'arrière-plan des logos de la recherche d'images","use_mobile_navigation_bar" => "Utiliser la barre de navigation mobile",+ "remove_background_info" => "Cela génère également une seconde version, recolorée, du logo afin qu'il reste lisible lors du passage du thème clair au thème sombre.","experimental_info" => "Les paramètres expérimentaux ne fonctionneront probablement pas parfaitement.","payment_methods" => "Méthodes de paiement","payment_methods_info" => "Cliquez sur une méthode de paiement pour la désactiver / l'activer.",diff --git a/includes/i18n/hu.php b/includes/i18n/hu.phpindex 6fb6fbb..d3efd2b 100644--- a/includes/i18n/hu.php+++ b/includes/i18n/hu.php@@ -285,7 +285,8 @@ $i18n = ["experimental_settings" => "Kísérleti beállítások","remove_background" => "Kísérlet a logók hátterének eltávolítására a képkeresésből","use_mobile_navigation_bar" => "Mobil navigációs sáv használata",- "experimental_info" => "A kísérleti beállítások valószínűleg nem fognak tökéletesen működni.",+ "remove_background_info" => "Ez egy második, átszínezett verzióját is létrehozza a logónak, hogy az világos és sötét téma között váltva is olvasható maradjon.",+ "experimental_info" => "A kísérleti beállítások valószínűleg nem fognak tökéletesen működni.","payment_methods" => "Fizetési módok","payment_methods_info" => "Kattintson egy fizetési módra a letiltásához / engedélyezéséhez.","rename_payment_methods_info" => "Kattintson egy fizetési mód nevére az átnevezéséhez.",diff --git a/includes/i18n/id.php b/includes/i18n/id.phpindex fa33afc..4086719 100644--- a/includes/i18n/id.php+++ b/includes/i18n/id.php@@ -285,6 +285,7 @@ $i18n = ["experimental_settings" => "Pengaturan Eksperimental","remove_background" => "Coba hapus latar belakang logo dari pencarian gambar","use_mobile_navigation_bar" => "Gunakan bilah navigasi seluler",+ "remove_background_info" => "Ini juga menghasilkan versi kedua logo dengan warna yang disesuaikan, agar tetap terbaca saat Anda beralih antara tema terang dan gelap.","experimental_info" => "Pengaturan eksperimental mungkin tidak akan berfungsi dengan sempurna.","payment_methods" => "Metode Pembayaran","payment_methods_info" => "Klik metode pembayaran untuk menonaktifkan / mengaktifkannya.",diff --git a/includes/i18n/it.php b/includes/i18n/it.phpindex bd8f595..87b3613 100644--- a/includes/i18n/it.php+++ b/includes/i18n/it.php@@ -290,6 +290,7 @@ $i18n = ["experimental_settings" => 'Impostazioni sperimentali',"remove_background" => 'Prova a rimuovere lo sfondo dei loghi dalla ricerca delle immagini',"use_mobile_navigation_bar" => "Utilizza la barra di navigazione mobile",+ "remove_background_info" => 'Questo genera anche una seconda versione, ricolorata, del logo in modo che rimanga leggibile quando passi dal tema chiaro a quello scuro.',"experimental_info" => 'Le impostazioni sperimentali potrebbero non funzioneranno perfettamente.',"payment_methods" => 'Metodi di pagamento',"payment_methods_info" => 'Fai clic su un metodo di pagamento per abilitarlo/disabilitarlo.',diff --git a/includes/i18n/ja.php b/includes/i18n/ja.phpindex 8bb94de..95acc12 100644--- a/includes/i18n/ja.php+++ b/includes/i18n/ja.php@@ -285,6 +285,7 @@ $i18n = ["experimental_settings" => "実験的な設定","remove_background" => "画像検索からロゴの背景を削除する","use_mobile_navigation_bar" => "モバイルナビゲーションバーを使用する",+ "remove_background_info" => "これにより、ライトテーマとダークテーマを切り替えても読みやすいように、色を調整したロゴの2つ目のバージョンも生成されます。","experimental_info" => "実験的な設定は、おそらく完全には機能しません。","payment_methods" => "支払い方法","payment_methods_info" => "支払い方法をクリックして無効/有効を切り替えます。",diff --git a/includes/i18n/ko.php b/includes/i18n/ko.phpindex a16ca7d..08c0da3 100644--- a/includes/i18n/ko.php+++ b/includes/i18n/ko.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "실험적 설정","remove_background" => "로고 이미지 검색에서 배경 삭제","use_mobile_navigation_bar" => "모바일 네비게이션 바 사용",+ "remove_background_info" => "이렇게 하면 라이트 테마와 다크 테마를 전환해도 로고가 잘 보이도록 색상을 조정한 두 번째 버전도 생성됩니다.","experimental_info" => "실험적 설정은 제대로 작동하지 않을 수 있습니다.","payment_methods" => "결제 수단","payment_methods_info" => "결제 수단을 클릭하여 활성화/비활성화 할 수 있습니다.",diff --git a/includes/i18n/nl.php b/includes/i18n/nl.phpindex 9c57780..5208c24 100644--- a/includes/i18n/nl.php+++ b/includes/i18n/nl.php@@ -285,6 +285,7 @@ $i18n = ["experimental_settings" => "Experimentele instellingen","remove_background" => "Probeer achtergrond van logo's uit afbeelding zoekresultaten te verwijderen","use_mobile_navigation_bar" => "Gebruik mobiele navigatiebalk",+ "remove_background_info" => "Dit genereert ook een tweede, herkleurde versie van het logo, zodat het leesbaar blijft wanneer je wisselt tussen het lichte en donkere thema.","experimental_info" => "Experimentele instellingen werken waarschijnlijk niet perfect.","payment_methods" => "Betaalmethoden","payment_methods_info" => "Klik op een betaalmethode om deze uit/in te schakelen.",diff --git a/includes/i18n/pl.php b/includes/i18n/pl.phpindex cda8d6f..17dedae 100644--- a/includes/i18n/pl.php+++ b/includes/i18n/pl.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Ustawienia eksperymentalne","remove_background" => "Próba usunięcia tła logo z wyszukiwania obrazów","use_mobile_navigation_bar" => "Użyj paska nawigacyjnego na urządzeniach mobilnych",+ "remove_background_info" => "Spowoduje to również utworzenie drugiej, przekolorowanej wersji logo, aby pozostało czytelne po przełączeniu między jasnym a ciemnym motywem.","experimental_info" => "Ustawienia eksperymentalne prawdopodobnie nie będą działać idealnie.","payment_methods" => "Metody płatności","payment_methods_info" => "Kliknij metodę płatności, aby ją wyłączyć/włączyć..",diff --git a/includes/i18n/pt.php b/includes/i18n/pt.phpindex fc92a9c..706fca1 100644--- a/includes/i18n/pt.php+++ b/includes/i18n/pt.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Definições Experimentais","remove_background" => "Tentar remover o fundo dos logos na pesquisa de imagem","use_mobile_navigation_bar" => "Usar barra de navegação móvel",+ "remove_background_info" => "Isto também gera uma segunda versão do logótipo, com as cores ajustadas, para que se mantenha legível ao alternar entre o tema claro e o escuro.","experimental_info" => "Definições experimentais provavelmente não funcionarão correctamente.","payment_methods" => "Métodos de Pagamento","payment_methods_info" => "Clique num método de pagamento para o activar / desactivar.",diff --git a/includes/i18n/pt_br.php b/includes/i18n/pt_br.phpindex db12449..68eac03 100644--- a/includes/i18n/pt_br.php+++ b/includes/i18n/pt_br.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Configurações experimentais","remove_background" => "Tentar remover o fundo de logos na pesquisa de imagem","use_mobile_navigation_bar" => "Usar barra de navegação móvel",+ "remove_background_info" => "Isso também gera uma segunda versão do logotipo, com as cores ajustadas, para que ele continue legível ao alternar entre o tema claro e o escuro.","experimental_info" => "As configurações experimentais provavelmente não funcionarão corretamente","payment_methods" => "Métodos de pagamento","payment_methods_info" => "Clique em um método de pagamento para ativá-lo ou desativá-lo",diff --git a/includes/i18n/ro.php b/includes/i18n/ro.phpindex 8b7f103..ee3154c 100644--- a/includes/i18n/ro.php+++ b/includes/i18n/ro.php@@ -285,6 +285,7 @@ $i18n = ["experimental_settings" => "Setări experimentale","remove_background" => "Încearcă să elimini fundalul logo-urilor din căutarea de imagini","use_mobile_navigation_bar" => "Folosește bara de navigare mobilă",+ "remove_background_info" => "Aceasta generează și o a doua versiune, recolorată, a logo-ului, astfel încât să rămână lizibil atunci când comuți între tema deschisă și cea întunecată.","experimental_info" => "Setările experimentale probabil nu vor funcționa perfect.","payment_methods" => "Metode de plată","payment_methods_info" => "Faceți clic pe o metodă de plată pentru a o dezactiva/activa.",diff --git a/includes/i18n/ru.php b/includes/i18n/ru.phpindex 104393c..cd221af 100644--- a/includes/i18n/ru.php+++ b/includes/i18n/ru.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Экспериментальные настройки","remove_background" => "Попытка удалить фон логотипов из поиска изображений.","use_mobile_navigation_bar" => "Использовать мобильную панель навигации",+ "remove_background_info" => "Это также создаёт вторую, перекрашенную версию логотипа, чтобы он оставался читаемым при переключении между светлой и тёмной темой.","experimental_info" => "Экспериментальные настройки, вероятно, не будут работать идеально.","payment_methods" => "Способы оплаты","payment_methods_info" => "Нажмите на способ оплаты, чтобы отключить/включить его.",diff --git a/includes/i18n/sl.php b/includes/i18n/sl.phpindex 15eaed0..f465072 100644--- a/includes/i18n/sl.php+++ b/includes/i18n/sl.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Eksperimentalne nastavitve","remove_background" => "Poskusi odstraniti ozadje logotipov iz iskanja slik","use_mobile_navigation_bar" => "Uporabi mobilno navigacijsko vrstico",+ "remove_background_info" => "To ustvari tudi drugo, prebarvano različico logotipa, da ostane berljiv ob preklopu med svetlo in temno temo.","experimental_info" => "Poskusne nastavitve verjetno ne bodo popolnoma delovale.","payment_methods" => "Načini plačila","payment_methods_info" => "Kliknite način plačila, da ga onemogočite/omogočite.",diff --git a/includes/i18n/sr.php b/includes/i18n/sr.phpindex db9999f..2ed03da 100644--- a/includes/i18n/sr.php+++ b/includes/i18n/sr.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Експериментална подешавања","remove_background" => "Покушајте уклонити позадину логотипа са слика претраге","use_mobile_navigation_bar" => "Користите мобилну навигациону траку",+ "remove_background_info" => "Ово такође прави другу, прекројену верзију логотипа, како би остао читљив приликом преласка између светле и тамне теме.","experimental_info" => "Експериментална подешавања вероватно неће радити савршено.","payment_methods" => "Начини плаћања","payment_methods_info" => "Кликните на начин плаћања да бисте га онемогућили / омогућили.",diff --git a/includes/i18n/sr_lat.php b/includes/i18n/sr_lat.phpindex ccf94be..51f3e59 100644--- a/includes/i18n/sr_lat.php+++ b/includes/i18n/sr_lat.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Eksperimentalna podešavanja","remove_background" => "Pokušajte ukloniti pozadinu logotipa sa pretrage slika","use_mobile_navigation_bar" => "Koristi navigacionu traku za mobilne uređaje",+ "remove_background_info" => "Ovo takođe pravi drugu, prekrojenu verziju logotipa, kako bi ostao čitljiv prilikom prelaska između svetle i tamne teme.","experimental_info" => "Eksperimentalna podešavanja verovatno neće savršeno funkcionisati.","payment_methods" => "Načini plaćanja","payment_methods_info" => "Kliknite na način plaćanja da biste ga onemogućili / omogućili.",diff --git a/includes/i18n/tr.php b/includes/i18n/tr.phpindex f53cfa9..6dc61a9 100644--- a/includes/i18n/tr.php+++ b/includes/i18n/tr.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Deneysel Ayarlar","remove_background" => "Görsel aramadan logoların arka planını kaldırmayı deneyin","use_mobile_navigation_bar" => "Mobil cihazlarda gezinme çubuğunu kullan",+ "remove_background_info" => "Bu ayrıca, açık ve koyu tema arasında geçiş yaptığınızda okunabilir kalması için logonun yeniden renklendirilmiş ikinci bir sürümünü de oluşturur.","experimental_info" => "Deneysel ayarlar muhtemelen mükemmel çalışmayacak.","payment_methods" => "Ödeme Yöntemleri","payment_methods_info" => "Bir ödeme yöntemini devre dışı bırakmak / etkinleştirmek için tıklayın.",diff --git a/includes/i18n/uk.php b/includes/i18n/uk.phpindex 9d3cc21..419960d 100644--- a/includes/i18n/uk.php+++ b/includes/i18n/uk.php@@ -284,6 +284,7 @@ $i18n = ["experimental_settings" => "Експериментальні налаштування","remove_background" => "Спроба видалити фон логотипів із пошуку зображень.","use_mobile_navigation_bar" => "Використовувати мобільну панель навігації",+ "remove_background_info" => "Це також створює другу, перефарбовану версію логотипу, щоб він залишався читабельним під час перемикання між світлою та темною темами.","experimental_info" => "Експериментальні налаштування, ймовірно, не будуть працювати ідеально.","payment_methods" => "Способи оплати","payment_methods_info" => "Натисніть на спосіб оплати, щоб відключити/включити його.",diff --git a/includes/i18n/vi.php b/includes/i18n/vi.phpindex a859b60..24f12d0 100644--- a/includes/i18n/vi.php+++ b/includes/i18n/vi.php@@ -285,6 +285,7 @@ $i18n = ["experimental_settings" => "Cài đặt thử nghiệm","remove_background" => "Cố gắng loại bỏ nền của logo từ tìm kiếm hình ảnh","use_mobile_navigation_bar" => "Sử dụng thanh điều hướng di động",+ "remove_background_info" => "Điều này cũng tạo ra phiên bản thứ hai của logo với màu sắc được điều chỉnh, để logo vẫn rõ ràng khi bạn chuyển đổi giữa giao diện sáng và tối.","experimental_info" => "Cài đặt thử nghiệm có thể không hoạt động hoàn hảo.","payment_methods" => "Phương thức thanh toán","payment_methods_info" => "Nhấp vào phương thức thanh toán để vô hiệu hóa / bật nó.",diff --git a/includes/i18n/zh_cn.php b/includes/i18n/zh_cn.phpindex 1d7e14c..dea491f 100644--- a/includes/i18n/zh_cn.php+++ b/includes/i18n/zh_cn.php@@ -292,6 +292,7 @@ $i18n = ["experimental_settings" => "实验性设置","remove_background" => "尝试从图片搜索中移除标志的背景","use_mobile_navigation_bar" => "使用移动导航栏",+ "remove_background_info" => "这还会生成一个重新配色的第二版本徽标,以便在浅色和深色主题之间切换时仍然清晰可辨。","experimental_info" => "实验性设置,可能存在问题。","payment_methods" => "支付方式","payment_methods_info" => "点击支付方式以禁用/启用。",diff --git a/includes/i18n/zh_tw.php b/includes/i18n/zh_tw.phpindex a470444..3a4bff6 100644--- a/includes/i18n/zh_tw.php+++ b/includes/i18n/zh_tw.php@@ -285,6 +285,7 @@ $i18n = ["experimental_settings" => "實驗性功能","remove_background" => "嘗試從圖片搜尋中移除搜尋結果的背景","use_mobile_navigation_bar" => "使用行動版導覽列",+ "remove_background_info" => "這也會產生第二個重新上色的標誌版本,讓您在淺色與深色主題之間切換時仍保持清晰可辨。","experimental_info" => "實驗性功能可能無法完美運作。","payment_methods" => "付款方式","payment_methods_info" => "點選付款方式以停用/啟用。",diff --git a/includes/list_subscriptions.php b/includes/list_subscriptions.phpindex eca4301..0ce45b8 100644--- a/includes/list_subscriptions.php+++ b/includes/list_subscriptions.php@@ -264,9 +264,7 @@ function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n,<span class="logo <?= !$hasLogo ? 'hideOnMobile' : '' ?>"><?phpif ($hasLogo) {- ?>- <img src="<?= $subscription['logo'] ?>">- <?php+ echo renderThemedLogoImg($subscription['logo'], $subscription['logo_variant'] ?? null, $subscription['logo_text_color'] ?? null);} else {include $imagePath . "images/siteicons/svg/logo.php";}diff --git a/includes/logo_theme_variant.php b/includes/logo_theme_variant.phpnew file mode 100644index 0000000..7fd8355--- /dev/null+++ b/includes/logo_theme_variant.php@@ -0,0 +1,178 @@+<?php+/*+ Detects whether a logo's ink is plain black/near-black or white/near-white+ text (as opposed to a colorful icon mark, which is left untouched), and+ generates a themed variant with just that ink recolored for the opposite+ theme -- so a black-text logo stays legible on the dark theme, and a+ white-text logo stays legible on the light theme.++ Colored pixels (a logo's icon mark) are never touched -- only pixels close+ to black or close to white get remapped, and each such pixel is blended+ toward its OWN color inversion (not a single flat target color), which+ keeps whatever anti-aliasing/gradient variation the original ink had+ instead of flattening it into one solid tone.+*/++const LOGO_THEME_BLACK_LIGHTNESS_MAX = 60; // 0-255; at/below this is "near black"+const LOGO_THEME_WHITE_LIGHTNESS_MIN = 200; // 0-255; at/above this is "near white"+const LOGO_THEME_MAX_CHANNEL_SPREAD = 20; // max(r,g,b) - min(r,g,b); low spread = grayscale-ish+const LOGO_THEME_SIGNIFICANT_RATIO = 0.05; // at least 5% of opaque pixels to count as "has text"+const LOGO_THEME_DOMINANCE_RATIO = 0.3; // if both black & white are present, min/max above this = genuinely ambiguous++/**+ * Classifies a logo's ink color by sampling its opaque pixels.+ *+ * @return 'dark'|'light'|null 'dark' if it has near-black text (light-theme+ * native), 'light' if it has near-white text (dark-theme native), or null+ * if neither is significant, or both are (ambiguous -- e.g. a+ * deliberately two-tone logo we shouldn't mangle).+ */+function classifyLogoTextColor($image)+{+ $width = imagesx($image);+ $height = imagesy($image);++ $blackPixels = 0;+ $whitePixels = 0;+ $opaquePixels = 0;++ for ($y = 0; $y < $height; $y++) {+ for ($x = 0; $x < $width; $x++) {+ $color = imagecolorat($image, $x, $y);+ $alpha = ($color >> 24) & 0x7F; // 0 = fully opaque, 127 = fully transparent+ if ($alpha >= 125) {+ continue;+ }++ $opaquePixels++;++ $red = ($color >> 16) & 0xFF;+ $green = ($color >> 8) & 0xFF;+ $blue = $color & 0xFF;++ $spread = max($red, $green, $blue) - min($red, $green, $blue);+ if ($spread > LOGO_THEME_MAX_CHANNEL_SPREAD) {+ continue; // saturated/colored pixel: part of an icon mark, leave alone+ }++ $lightness = ($red + $green + $blue) / 3;+ if ($lightness <= LOGO_THEME_BLACK_LIGHTNESS_MAX) {+ $blackPixels++;+ } elseif ($lightness >= LOGO_THEME_WHITE_LIGHTNESS_MIN) {+ $whitePixels++;+ }+ }+ }++ if ($opaquePixels === 0) {+ return null;+ }++ $isDark = ($blackPixels / $opaquePixels) >= LOGO_THEME_SIGNIFICANT_RATIO;+ $isLight = ($whitePixels / $opaquePixels) >= LOGO_THEME_SIGNIFICANT_RATIO;++ if (!$isDark && !$isLight) {+ return null; // colorful logo, no significant black/white ink at all+ }++ if ($isDark && $isLight) {+ // Both present: background removal often leaves a thin, fully-opaque+ // residue of dark (or light) edge pixels that don't get cleared+ // because they fall just outside the fuzz tolerance -- that's noise,+ // not a second ink color. Only treat this as a genuinely ambiguous+ // two-tone logo (skip) when the smaller amount is comparable in size+ // to the larger one; otherwise the dominant color wins.+ $minCount = min($blackPixels, $whitePixels);+ $maxCount = max($blackPixels, $whitePixels);+ if ($minCount / $maxCount > LOGO_THEME_DOMINANCE_RATIO) {+ return null;+ }+ }++ return $blackPixels > $whitePixels ? 'dark' : 'light';+}++/**+ * Generates a themed variant of $image by inverting every low-saturation+ * (grayscale-ish) pixel's color -- not just pixels near the dominant+ * black/white extreme. Anti-aliasing and background-removal residue can+ * leave faint ink-colored specks anywhere across the lightness range (not+ * only at the extremes); inverting the whole grayscale region flips those+ * along too, so nothing is left stuck in the old theme's tone. Colored+ * pixels (an icon mark) are identified the same way as in+ * classifyLogoTextColor() and are always copied through untouched; alpha+ * is preserved exactly.+ *+ * @return resource|GdImage a new true color image with alpha+ */+function generateThemedLogoVariant($image)+{+ $width = imagesx($image);+ $height = imagesy($image);++ $variant = imagecreatetruecolor($width, $height);+ imagealphablending($variant, false);+ imagesavealpha($variant, true);++ for ($y = 0; $y < $height; $y++) {+ for ($x = 0; $x < $width; $x++) {+ $color = imagecolorat($image, $x, $y);+ $alpha = ($color >> 24) & 0x7F;+ $red = ($color >> 16) & 0xFF;+ $green = ($color >> 8) & 0xFF;+ $blue = $color & 0xFF;++ if ($alpha < 125) {+ $spread = max($red, $green, $blue) - min($red, $green, $blue);+ if ($spread <= LOGO_THEME_MAX_CHANNEL_SPREAD) {+ $red = 255 - $red;+ $green = 255 - $green;+ $blue = 255 - $blue;+ }+ }++ $newColor = imagecolorallocatealpha($variant, $red, $green, $blue, $alpha);+ imagesetpixel($variant, $x, $y, $newColor);+ }+ }++ return $variant;+}++/**+ * Renders a subscription's logo <img> tag(s), given already-resolved image+ * URLs. When a themed variant exists, renders both the original and the+ * variant image, each tagged with the theme the *original* already reads+ * well on (data-native-theme); a small CSS rule (see styles.css) shows only+ * the one matching the current theme so the swap works instantly, including+ * live theme toggles with no page reload -- see the body.dark/body.light+ * classes set in scripts/theme.js and scripts/common.js.+ *+ * @param string $originalSrc Resolved URL of the original logo (caller's own path convention)+ * @param string|null $variantSrc Resolved URL of the themed variant, or empty/null if none+ * @param string|null $textColor 'dark'/'light'/null, as stored in logo_text_color+ * @param string $class Classes to apply to the image(s) (e.g. sizing/positioning)+ * @param string $extraAttrs Extra raw HTML attributes (e.g. alt="", title="")+ * @return string HTML for the logo image(s), or '' if there's no original logo+ */+function renderThemedLogoImg($originalSrc, $variantSrc, $textColor, $class = '', $extraAttrs = '')+{+ if (empty($originalSrc)) {+ return '';+ }++ if (empty($textColor) || empty($variantSrc)) {+ return '<img src="' . htmlspecialchars($originalSrc) . '" class="' . htmlspecialchars($class) . '" ' . $extraAttrs . '>';+ }++ // The theme the ORIGINAL logo file already reads well on.+ $nativeTheme = $textColor === 'dark' ? 'light' : 'dark';++ $originalClass = htmlspecialchars(trim($class . ' logo-theme-original'));+ $variantClass = htmlspecialchars(trim($class . ' logo-theme-variant'));++ return '<img src="' . htmlspecialchars($originalSrc) . '" class="' . $originalClass . '" data-native-theme="' . $nativeTheme . '" ' . $extraAttrs . '>'+ . '<img src="' . htmlspecialchars($variantSrc) . '" class="' . $variantClass . '" data-native-theme="' . $nativeTheme . '" ' . $extraAttrs . '>';+}++?>diff --git a/includes/remember_me.php b/includes/remember_me.phpnew file mode 100644index 0000000..77f8189--- /dev/null+++ b/includes/remember_me.php@@ -0,0 +1,77 @@+<?php++/**+ * Attempts to restore a logged-in session from the persistent "remember me"+ * login cookie (set at login when "stay logged in" is checked).+ *+ * PHP's session data can be garbage-collected (default ~24 minutes of+ * inactivity) long before the remember-me cookie's 30-day lifetime expires.+ * Full page loads recover from this transparently; this function lets+ * AJAX/API endpoints (via connect_endpoint.php) do the same instead of+ * silently behaving as logged-out after an idle period.+ *+ * On success, populates $_SESSION (regenerating the session id) and+ * returns the user's row. On any failure, returns false and leaves+ * $_SESSION untouched.+ */+function restoreSessionFromRememberMeCookie($db)+{+ if (!isset($_COOKIE['wallos_login'])) {+ return false;+ }++ $cookie = explode('|', $_COOKIE['wallos_login'], 3);+ if (count($cookie) !== 3) {+ return false;+ }+ [$username, $token, $main_currency] = $cookie;++ $sql = "SELECT * FROM user WHERE username = :username";+ $stmt = $db->prepare($sql);+ $stmt->bindValue(':username', $username, SQLITE3_TEXT);+ $result = $stmt->execute();++ if (!$result) {+ return false;+ }++ $userData = $result->fetchArray(SQLITE3_ASSOC);+ if (!isset($userData['id'])) {+ return false;+ }++ $userId = $userData['id'];+ $main_currency = $userData['main_currency'];++ $adminQuery = "SELECT login_disabled FROM admin";+ $adminResult = $db->query($adminQuery);+ $adminRow = $adminResult->fetchArray(SQLITE3_ASSOC);++ if ($adminRow['login_disabled'] == 1) {+ $sql = "SELECT * FROM login_tokens WHERE user_id = :userId";+ $stmt = $db->prepare($sql);+ $stmt->bindParam(':userId', $userId, SQLITE3_TEXT);+ } else {+ $sql = "SELECT * FROM login_tokens WHERE user_id = :userId AND token = :token";+ $stmt = $db->prepare($sql);+ $stmt->bindParam(':userId', $userId, SQLITE3_TEXT);+ $stmt->bindParam(':token', $token, SQLITE3_TEXT);+ }+ $result = $stmt->execute();+ $row = $result->fetchArray(SQLITE3_ASSOC);++ if ($row == false) {+ return false;+ }++ session_regenerate_id(true);+ $_SESSION['username'] = $username;+ $_SESSION['token'] = $token;+ $_SESSION['loggedin'] = true;+ $_SESSION['main_currency'] = $main_currency;+ $_SESSION['userId'] = $userId;++ return $userData;+}++?>diff --git a/index.php b/index.phpindex d23ba55..2871bb4 100644--- a/index.php+++ b/index.php@@ -1,416 +1,413 @@-<?php--require_once 'includes/header.php';-require_once 'includes/getdbkeys.php';--function formatPrice($price, $currencyCode, $currencies)-{- $formattedPrice = CurrencyFormatter::format($price, $currencyCode);- if (strstr($formattedPrice, $currencyCode)) {- $symbol = $currencyCode;-- foreach ($currencies as $currency) {-- if ($currency['code'] === $currencyCode) {- if ($currency['symbol'] != "") {- $symbol = $currency['symbol'];- }- break;- }- }- $formattedPrice = str_replace($currencyCode, $symbol, $formattedPrice);- }-- return $formattedPrice;-}--function formatDate($date, $lang = 'en')-{- $currentYear = date('Y');- $dateYear = date('Y', strtotime($date));-- // Determine the date format based on whether the year matches the current year- $dateFormat = ($currentYear == $dateYear) ? 'MMM d' : 'MMM yyyy';-- // Try to create an IntlDateFormatter; if it fails, fallback to 'en'- try {- $formatter = new IntlDateFormatter(- $lang,- IntlDateFormatter::SHORT,- IntlDateFormatter::NONE,- null,- null,- $dateFormat- );-- if (!$formatter) {- throw new Exception('Failed to create IntlDateFormatter with language: ' . $lang);- }- } catch (Throwable $e) {- $lang = 'en'; // Fallback to English on error- $formatter = new IntlDateFormatter(- $lang,- IntlDateFormatter::SHORT,- IntlDateFormatter::NONE,- null,- null,- $dateFormat- );- }-- // Format the date- $formattedDate = $formatter->format(new DateTime($date));-- return $formattedDate;-}--// Get the first name of the user-$stmt = $db->prepare("SELECT username, firstname FROM user WHERE id = :userId");-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();-$user = $result->fetchArray(SQLITE3_ASSOC);-$first_name = $user['firstname'] ?? $user['username'] ?? '';--// Fetch the next 3 enabled subscriptions up for payment-$stmt = $db->prepare("SELECT id, logo, name, price, currency_id, next_payment, inactive FROM subscriptions WHERE user_id = :userId AND next_payment >= date('now') AND inactive = 0 AND cycle != 5 ORDER BY next_payment ASC LIMIT 3");-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();-$upcomingSubscriptions = [];-while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $upcomingSubscriptions[] = $row;-}--// Fetch enabled subscriptions with manual renewal that are overdue-$stmt = $db->prepare("SELECT id, logo, name, price, currency_id, next_payment, inactive, auto_renew FROM subscriptions WHERE user_id = :userId AND next_payment < date('now') AND auto_renew = 0 AND inactive = 0 AND cycle != 5 ORDER BY next_payment ASC");-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();-$overdueSubscriptions = [];-while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $overdueSubscriptions[] = $row;-}-$hasOverdueSubscriptions = !empty($overdueSubscriptions);--require_once 'includes/stats_calculations.php';--// Get AI Recommendations for user-$stmt = $db->prepare("SELECT * FROM ai_recommendations WHERE user_id = :userId");-$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();-$aiRecommendations = [];-while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $aiRecommendations[] = $row;-}--?>--<section class="contain dashboard">- <?php- if ($isAdmin && $settings['update_notification']) {- if (!is_null($settings['latest_version'])) {- $latestVersion = $settings['latest_version'];- if (version_compare($version, $latestVersion) == -1) {- ?>- <div class="update-banner">- <?= translate('new_version_available', $i18n) ?>:- <span><a href="https://github.com/ellite/Wallos/releases/tag/<?= htmlspecialchars($latestVersion) ?>"- target="_blank" rel="noreferer">- <?= htmlspecialchars($latestVersion) ?>- </a></span>- </div>- <?php- }- }- }- if ($demoMode) {- ?>- <div class="demo-banner">- Running in <b>Demo Mode</b>, certain actions and settings are disabled.<br>- The database will be reset every 120 minutes.- </div>- <?php- }- ?>- <h1><?= translate('hello', $i18n) ?> <?= htmlspecialchars($first_name) ?></h1>-- <?php- // If there are overdue subscriptions, display them- if ($hasOverdueSubscriptions) {- ?>- <div class="overdue-subscriptions">- <h2><?= translate('overdue_renewals', $i18n) ?></h2>- <div class="dashboard-subscriptions-container">- <div class="dashboard-subscriptions-list">- <?php-- foreach ($overdueSubscriptions as $subscription) {- $subscriptionLogo = "images/uploads/logos/" . $subscription['logo'];- $subscriptionName = htmlspecialchars($subscription['name']);- $subscriptionPrice = $subscription['price'];- $subscriptionCurrency = $subscription['currency_id'];- $subscriptionNextPayment = $subscription['next_payment'];- $subscriptionDisplayNextPayment = formatDate($subscriptionNextPayment, $lang);- $subscriptionDisplayPrice = formatPrice($subscriptionPrice, $currencies[$subscriptionCurrency]['code'], $currencies);-- ?>- <div class="subscription-item" onClick="showSubscriptionDetails(event, <?= $subscription['id'] ?>)" data-id="<?= $subscription['id'] ?>">- <?php- if (empty($subscription['logo'])) {- ?>- <p class="subscription-item-title"><?= $subscriptionName ?></p>- <?php- } else {- ?>- <img src="<?= $subscriptionLogo ?>" alt="<?= $subscriptionName ?> logo"- class="subscription-item-logo" title="<?= $subscriptionName ?>">- <?php- }- ?>- <div class="subscription-item-info">- <p class="subscription-item-date"> <?= $subscriptionDisplayNextPayment ?>- </p>- <p class="subscription-item-price"> <?= $subscriptionDisplayPrice ?></p>- </div>- </div>- <?php- }- ?>- </div>- </div>- </div>- <?php- }- ?>-- <div class="upcoming-subscriptions">- <h2><?= translate('upcoming_payments', $i18n) ?></h2>- <div class="dashboard-subscriptions-container">- <div class="dashboard-subscriptions-list">- <?php- if (empty($upcomingSubscriptions)) {- ?>- <p><?= translate('no_upcoming_payments', $i18n) ?></p>- <?php- } else {- foreach ($upcomingSubscriptions as $subscription) {- $subscriptionLogo = "images/uploads/logos/" . $subscription['logo'];- $subscriptionName = htmlspecialchars($subscription['name']);- $subscriptionPrice = $subscription['price'];- $subscriptionCurrency = $subscription['currency_id'];- $subscriptionNextPayment = $subscription['next_payment'];- $subscriptionDisplayNextPayment = formatDate($subscriptionNextPayment, $lang);- $subscriptionDisplayPrice = formatPrice($subscriptionPrice, $currencies[$subscriptionCurrency]['code'], $currencies);-- ?>- <div class="subscription-item" onClick="showSubscriptionDetails(event, <?= $subscription['id'] ?>)" data-id="<?= $subscription['id'] ?>">- <?php- if (empty($subscription['logo'])) {- ?>- <p class="subscription-item-title"><?= $subscriptionName ?></p>- <?php- } else {- ?>- <img src="<?= $subscriptionLogo ?>" alt="<?= $subscriptionName ?> logo"- class="subscription-item-logo" title="<?= $subscriptionName ?>">- <?php- }- ?>- <div class="subscription-item-info">- <p class="subscription-item-date"> <?= $subscriptionDisplayNextPayment ?></p>- <p class="subscription-item-price"> <?= $subscriptionDisplayPrice ?></p>- </div>- </div>- <?php- }- }- ?>- </div>- </div>-- <?php if (!empty($aiRecommendations)) { ?>- <div class="ai-recommendations">- <h2><?= translate('ai_recommendations', $i18n) ?></h2>- <div class="ai-recommendations-container">- <ul class="ai-recommendations-list">- <?php-- foreach ($aiRecommendations as $key => $recommendation) { ?>- <li class="ai-recommendation-item" data-id="<?= $recommendation['id'] ?>">- <div class="ai-recommendation-header">- <h3>- <span><?= ($key + 1) . ". " ?></span>- <?= htmlspecialchars($recommendation['title']) ?>- </h3>- <span class="item-arrow-down fa fa-caret-down"></span>- </div>- <p class="collapsible"><?= htmlspecialchars($recommendation['description']) ?></p>- <p class="ai-recommendation-savings">- <?= htmlspecialchars($recommendation['savings']) ?>- <span>- <a href="#" class="delete-ai-recommendation" title="<?= translate('delete', $i18n) ?>">- <i class="fa fa-trash"></i>- </a>- </span>- </p>- </li>- <?php } ?>- </ul>- </div>- </div>-- <?php } ?>-- <?php if (isset($amountDueThisMonth) || isset($budget) || isset($budgetUsed) || isset($budgetLeft) || isset($overBudgetAmount)) { ?>- <div class="budget-subscriptions">- <h2><?= translate('your_budget', $i18n) ?></h2>- <div class="dashboard-subscriptions-container">- <div class="dashboard-subscriptions-list">- <?php if (isset($amountDueThisMonth)) { ?>- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate("amount_due", $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value">- <?= CurrencyFormatter::format($amountDueThisMonth, $currencies[$userData['main_currency']]['code']) ?>- </p>- </div>- </div>- <?php } ?>- <?php if (isset($budget) && $budget > 0) { ?>- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate("budget", $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value">- <?= formatPrice($budget, $currencies[$userData['main_currency']]['code'], $currencies) ?>- </p>- </div>- </div>- <?php } ?>- <?php if (isset($budgetUsed)) { ?>- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate("budget_used", $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value">- <?= number_format($budgetUsed, 2) ?>%- </p>- </div>- </div>- <?php } ?>- <?php if (isset($budgetLeft)) { ?>- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate("budget_remaining", $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value">- <?= formatPrice($budgetLeft, $currencies[$userData['main_currency']]['code'], $currencies) ?>- </p>- </div>- </div>- <?php } ?>- <?php if (isset($overBudgetAmount) && $overBudgetAmount > 0) { ?>- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate("over_budget", $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value">- <?= formatPrice($overBudgetAmount, $currencies[$userData['main_currency']]['code'], $currencies) ?>- </p>- </div>- </div>- <?php } ?>- </div>- </div>- </div>- <?php } ?>- </div>-- <?php if (isset($activeSubscriptions) && $activeSubscriptions > 0) { ?>- <div class="current-subscriptions">- <h2><?= translate('your_subscriptions', $i18n) ?></h2>- <div class="dashboard-subscriptions-container">- <div class="dashboard-subscriptions-list">- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate('active_subscriptions', $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value"><?= $activeSubscriptions ?></p>- </div>- </div>-- <?php if (isset($totalCostPerMonth)) { ?>- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate('monthly_cost', $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value">- <?= CurrencyFormatter::format($totalCostPerMonth, $currencies[$userData['main_currency']]['code']) ?>- </p>- </div>- </div>- <?php } ?>-- <?php if (isset($totalCostPerYear)) { ?>- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate('yearly_cost', $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value">- <?= CurrencyFormatter::format($totalCostPerYear, $currencies[$userData['main_currency']]['code']) ?>- </p>- </div>- </div>- <?php } ?>- </div>- </div>- </div>- <?php } ?>-- <?php if (isset($inactiveSubscriptions) && $inactiveSubscriptions > 0) { ?>- <div class="savings-subscriptions">- <h2><?= translate('your_savings', $i18n) ?></h2>- <div class="dashboard-subscriptions-container">- <div class="dashboard-subscriptions-list">- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate('inactive_subscriptions', $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value"><?= $inactiveSubscriptions ?></p>- </div>- </div>-- <?php if (isset($totalSavingsPerMonth) && $totalSavingsPerMonth > 0) { ?>- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate('monthly_savings', $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value">- <?= CurrencyFormatter::format($totalSavingsPerMonth, $currencies[$userData['main_currency']]['code']) ?>- </p>- </div>- </div>-- <div class="subscription-item thin">- <p class="subscription-item-title"><?= translate('yearly_savings', $i18n) ?></p>- <div class="subscription-item-info">- <p class="subscription-item-value">- <?= CurrencyFormatter::format($totalSavingsPerMonth * 12, $currencies[$userData['main_currency']]['code']) ?>- </p>- </div>- </div>- <?php } ?>- </div>- </div>- </div>- <?php } ?>--</section>--<?php-// Get all subscriptions for user details lookup-$query = 'SELECT * FROM subscriptions WHERE user_id = :userId';-$stmt = $db->prepare($query);-$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);-$result = $stmt->execute();-$subscriptions = [];-while ($row = $result->fetchArray(SQLITE3_ASSOC)) {- $subscriptions[] = $row;-}-require_once 'includes/subscription_details_popup.php';-?>--<script src="scripts/dashboard.js?<?= $version ?>"></script>--<?php-require_once 'includes/footer.php';+<?php++require_once 'includes/header.php';+require_once 'includes/getdbkeys.php';+require_once 'includes/logo_theme_variant.php';++function formatPrice($price, $currencyCode, $currencies)+{+ $formattedPrice = CurrencyFormatter::format($price, $currencyCode);+ if (strstr($formattedPrice, $currencyCode)) {+ $symbol = $currencyCode;++ foreach ($currencies as $currency) {++ if ($currency['code'] === $currencyCode) {+ if ($currency['symbol'] != "") {+ $symbol = $currency['symbol'];+ }+ break;+ }+ }+ $formattedPrice = str_replace($currencyCode, $symbol, $formattedPrice);+ }++ return $formattedPrice;+}++function formatDate($date, $lang = 'en')+{+ $currentYear = date('Y');+ $dateYear = date('Y', strtotime($date));++ // Determine the date format based on whether the year matches the current year+ $dateFormat = ($currentYear == $dateYear) ? 'MMM d' : 'MMM yyyy';++ // Try to create an IntlDateFormatter; if it fails, fallback to 'en'+ try {+ $formatter = new IntlDateFormatter(+ $lang,+ IntlDateFormatter::SHORT,+ IntlDateFormatter::NONE,+ null,+ null,+ $dateFormat+ );++ if (!$formatter) {+ throw new Exception('Failed to create IntlDateFormatter with language: ' . $lang);+ }+ } catch (Throwable $e) {+ $lang = 'en'; // Fallback to English on error+ $formatter = new IntlDateFormatter(+ $lang,+ IntlDateFormatter::SHORT,+ IntlDateFormatter::NONE,+ null,+ null,+ $dateFormat+ );+ }++ // Format the date+ $formattedDate = $formatter->format(new DateTime($date));++ return $formattedDate;+}++// Get the first name of the user+$stmt = $db->prepare("SELECT username, firstname FROM user WHERE id = :userId");+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();+$user = $result->fetchArray(SQLITE3_ASSOC);+$first_name = $user['firstname'] ?? $user['username'] ?? '';++// Fetch the next 3 enabled subscriptions up for payment+$stmt = $db->prepare("SELECT id, logo, logo_text_color, logo_variant, name, price, currency_id, next_payment, inactive FROM subscriptions WHERE user_id = :userId AND next_payment >= date('now') AND inactive = 0 AND cycle != 5 ORDER BY next_payment ASC LIMIT 3");+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();+$upcomingSubscriptions = [];+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $upcomingSubscriptions[] = $row;+}++// Fetch enabled subscriptions with manual renewal that are overdue+$stmt = $db->prepare("SELECT id, logo, logo_text_color, logo_variant, name, price, currency_id, next_payment, inactive, auto_renew FROM subscriptions WHERE user_id = :userId AND next_payment < date('now') AND auto_renew = 0 AND inactive = 0 AND cycle != 5 ORDER BY next_payment ASC");+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();+$overdueSubscriptions = [];+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $overdueSubscriptions[] = $row;+}+$hasOverdueSubscriptions = !empty($overdueSubscriptions);++require_once 'includes/stats_calculations.php';++// Get AI Recommendations for user+$stmt = $db->prepare("SELECT * FROM ai_recommendations WHERE user_id = :userId");+$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();+$aiRecommendations = [];+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $aiRecommendations[] = $row;+}++?>++<section class="contain dashboard">+ <?php+ if ($isAdmin && $settings['update_notification']) {+ if (!is_null($settings['latest_version'])) {+ $latestVersion = $settings['latest_version'];+ if (version_compare($version, $latestVersion) == -1) {+ ?>+ <div class="update-banner">+ <?= translate('new_version_available', $i18n) ?>:+ <span><a href="https://github.com/ellite/Wallos/releases/tag/<?= htmlspecialchars($latestVersion) ?>"+ target="_blank" rel="noreferer">+ <?= htmlspecialchars($latestVersion) ?>+ </a></span>+ </div>+ <?php+ }+ }+ }+ if ($demoMode) {+ ?>+ <div class="demo-banner">+ Running in <b>Demo Mode</b>, certain actions and settings are disabled.<br>+ The database will be reset every 120 minutes.+ </div>+ <?php+ }+ ?>+ <h1><?= translate('hello', $i18n) ?> <?= htmlspecialchars($first_name) ?></h1>++ <?php+ // If there are overdue subscriptions, display them+ if ($hasOverdueSubscriptions) {+ ?>+ <div class="overdue-subscriptions">+ <h2><?= translate('overdue_renewals', $i18n) ?></h2>+ <div class="dashboard-subscriptions-container">+ <div class="dashboard-subscriptions-list">+ <?php++ foreach ($overdueSubscriptions as $subscription) {+ $subscriptionName = htmlspecialchars($subscription['name']);+ $subscriptionPrice = $subscription['price'];+ $subscriptionCurrency = $subscription['currency_id'];+ $subscriptionNextPayment = $subscription['next_payment'];+ $subscriptionDisplayNextPayment = formatDate($subscriptionNextPayment, $lang);+ $subscriptionDisplayPrice = formatPrice($subscriptionPrice, $currencies[$subscriptionCurrency]['code'], $currencies);++ ?>+ <div class="subscription-item" onClick="showSubscriptionDetails(event, <?= $subscription['id'] ?>)" data-id="<?= $subscription['id'] ?>">+ <?php+ if (empty($subscription['logo'])) {+ ?>+ <p class="subscription-item-title"><?= $subscriptionName ?></p>+ <?php+ } else {+ $subscriptionLogoSrc = "images/uploads/logos/" . $subscription['logo'];+ $subscriptionLogoVariantSrc = !empty($subscription['logo_variant']) ? "images/uploads/logos/" . $subscription['logo_variant'] : null;+ echo renderThemedLogoImg($subscriptionLogoSrc, $subscriptionLogoVariantSrc, $subscription['logo_text_color'] ?? null, 'subscription-item-logo', 'alt="' . $subscriptionName . ' logo" title="' . $subscriptionName . '"');+ }+ ?>+ <div class="subscription-item-info">+ <p class="subscription-item-date"> <?= $subscriptionDisplayNextPayment ?>+ </p>+ <p class="subscription-item-price"> <?= $subscriptionDisplayPrice ?></p>+ </div>+ </div>+ <?php+ }+ ?>+ </div>+ </div>+ </div>+ <?php+ }+ ?>++ <div class="upcoming-subscriptions">+ <h2><?= translate('upcoming_payments', $i18n) ?></h2>+ <div class="dashboard-subscriptions-container">+ <div class="dashboard-subscriptions-list">+ <?php+ if (empty($upcomingSubscriptions)) {+ ?>+ <p><?= translate('no_upcoming_payments', $i18n) ?></p>+ <?php+ } else {+ foreach ($upcomingSubscriptions as $subscription) {+ $subscriptionName = htmlspecialchars($subscription['name']);+ $subscriptionPrice = $subscription['price'];+ $subscriptionCurrency = $subscription['currency_id'];+ $subscriptionNextPayment = $subscription['next_payment'];+ $subscriptionDisplayNextPayment = formatDate($subscriptionNextPayment, $lang);+ $subscriptionDisplayPrice = formatPrice($subscriptionPrice, $currencies[$subscriptionCurrency]['code'], $currencies);++ ?>+ <div class="subscription-item" onClick="showSubscriptionDetails(event, <?= $subscription['id'] ?>)" data-id="<?= $subscription['id'] ?>">+ <?php+ if (empty($subscription['logo'])) {+ ?>+ <p class="subscription-item-title"><?= $subscriptionName ?></p>+ <?php+ } else {+ $subscriptionLogoSrc = "images/uploads/logos/" . $subscription['logo'];+ $subscriptionLogoVariantSrc = !empty($subscription['logo_variant']) ? "images/uploads/logos/" . $subscription['logo_variant'] : null;+ echo renderThemedLogoImg($subscriptionLogoSrc, $subscriptionLogoVariantSrc, $subscription['logo_text_color'] ?? null, 'subscription-item-logo', 'alt="' . $subscriptionName . ' logo" title="' . $subscriptionName . '"');+ }+ ?>+ <div class="subscription-item-info">+ <p class="subscription-item-date"> <?= $subscriptionDisplayNextPayment ?></p>+ <p class="subscription-item-price"> <?= $subscriptionDisplayPrice ?></p>+ </div>+ </div>+ <?php+ }+ }+ ?>+ </div>+ </div>++ <?php if (!empty($aiRecommendations)) { ?>+ <div class="ai-recommendations">+ <h2><?= translate('ai_recommendations', $i18n) ?></h2>+ <div class="ai-recommendations-container">+ <ul class="ai-recommendations-list">+ <?php++ foreach ($aiRecommendations as $key => $recommendation) { ?>+ <li class="ai-recommendation-item" data-id="<?= $recommendation['id'] ?>">+ <div class="ai-recommendation-header">+ <h3>+ <span><?= ($key + 1) . ". " ?></span>+ <?= htmlspecialchars($recommendation['title']) ?>+ </h3>+ <span class="item-arrow-down fa fa-caret-down"></span>+ </div>+ <p class="collapsible"><?= htmlspecialchars($recommendation['description']) ?></p>+ <p class="ai-recommendation-savings">+ <?= htmlspecialchars($recommendation['savings']) ?>+ <span>+ <a href="#" class="delete-ai-recommendation" title="<?= translate('delete', $i18n) ?>">+ <i class="fa fa-trash"></i>+ </a>+ </span>+ </p>+ </li>+ <?php } ?>+ </ul>+ </div>+ </div>++ <?php } ?>++ <?php if (isset($amountDueThisMonth) || isset($budget) || isset($budgetUsed) || isset($budgetLeft) || isset($overBudgetAmount)) { ?>+ <div class="budget-subscriptions">+ <h2><?= translate('your_budget', $i18n) ?></h2>+ <div class="dashboard-subscriptions-container">+ <div class="dashboard-subscriptions-list">+ <?php if (isset($amountDueThisMonth)) { ?>+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate("amount_due", $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value">+ <?= CurrencyFormatter::format($amountDueThisMonth, $currencies[$userData['main_currency']]['code']) ?>+ </p>+ </div>+ </div>+ <?php } ?>+ <?php if (isset($budget) && $budget > 0) { ?>+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate("budget", $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value">+ <?= formatPrice($budget, $currencies[$userData['main_currency']]['code'], $currencies) ?>+ </p>+ </div>+ </div>+ <?php } ?>+ <?php if (isset($budgetUsed)) { ?>+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate("budget_used", $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value">+ <?= number_format($budgetUsed, 2) ?>%+ </p>+ </div>+ </div>+ <?php } ?>+ <?php if (isset($budgetLeft)) { ?>+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate("budget_remaining", $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value">+ <?= formatPrice($budgetLeft, $currencies[$userData['main_currency']]['code'], $currencies) ?>+ </p>+ </div>+ </div>+ <?php } ?>+ <?php if (isset($overBudgetAmount) && $overBudgetAmount > 0) { ?>+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate("over_budget", $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value">+ <?= formatPrice($overBudgetAmount, $currencies[$userData['main_currency']]['code'], $currencies) ?>+ </p>+ </div>+ </div>+ <?php } ?>+ </div>+ </div>+ </div>+ <?php } ?>+ </div>++ <?php if (isset($activeSubscriptions) && $activeSubscriptions > 0) { ?>+ <div class="current-subscriptions">+ <h2><?= translate('your_subscriptions', $i18n) ?></h2>+ <div class="dashboard-subscriptions-container">+ <div class="dashboard-subscriptions-list">+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate('active_subscriptions', $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value"><?= $activeSubscriptions ?></p>+ </div>+ </div>++ <?php if (isset($totalCostPerMonth)) { ?>+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate('monthly_cost', $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value">+ <?= CurrencyFormatter::format($totalCostPerMonth, $currencies[$userData['main_currency']]['code']) ?>+ </p>+ </div>+ </div>+ <?php } ?>++ <?php if (isset($totalCostPerYear)) { ?>+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate('yearly_cost', $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value">+ <?= CurrencyFormatter::format($totalCostPerYear, $currencies[$userData['main_currency']]['code']) ?>+ </p>+ </div>+ </div>+ <?php } ?>+ </div>+ </div>+ </div>+ <?php } ?>++ <?php if (isset($inactiveSubscriptions) && $inactiveSubscriptions > 0) { ?>+ <div class="savings-subscriptions">+ <h2><?= translate('your_savings', $i18n) ?></h2>+ <div class="dashboard-subscriptions-container">+ <div class="dashboard-subscriptions-list">+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate('inactive_subscriptions', $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value"><?= $inactiveSubscriptions ?></p>+ </div>+ </div>++ <?php if (isset($totalSavingsPerMonth) && $totalSavingsPerMonth > 0) { ?>+ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate('monthly_savings', $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value">+ <?= CurrencyFormatter::format($totalSavingsPerMonth, $currencies[$userData['main_currency']]['code']) ?>+ </p>+ </div>+ </div>++ <div class="subscription-item thin">+ <p class="subscription-item-title"><?= translate('yearly_savings', $i18n) ?></p>+ <div class="subscription-item-info">+ <p class="subscription-item-value">+ <?= CurrencyFormatter::format($totalSavingsPerMonth * 12, $currencies[$userData['main_currency']]['code']) ?>+ </p>+ </div>+ </div>+ <?php } ?>+ </div>+ </div>+ </div>+ <?php } ?>++</section>++<?php+// Get all subscriptions for user details lookup+$query = 'SELECT * FROM subscriptions WHERE user_id = :userId';+$stmt = $db->prepare($query);+$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);+$result = $stmt->execute();+$subscriptions = [];+while ($row = $result->fetchArray(SQLITE3_ASSOC)) {+ $subscriptions[] = $row;+}+require_once 'includes/subscription_details_popup.php';+?>++<script src="scripts/dashboard.js?<?= $version ?>"></script>++<?php+require_once 'includes/footer.php';?>\ No newline at end of filediff --git a/migrations/000052.php b/migrations/000052.phpnew file mode 100644index 0000000..280343e--- /dev/null+++ b/migrations/000052.php@@ -0,0 +1,17 @@+<?php+// This migration adds columns for a per-subscription themed logo variant.+// logo_text_color records whether the uploaded logo's text/ink is 'dark' or+// 'light' (NULL when neither/ambiguous, e.g. a colorful logo with no plain+// black/white text). logo_variant is the filename of a generated version+// with just that text recolored for the opposite theme, so a black-text+// logo stays legible on the dark theme and vice versa. Existing rows are+// left NULL, which means "always show the original logo" (unchanged+// behavior) until the subscription's logo is re-uploaded.++$columnQuery = $db->query("SELECT * FROM pragma_table_info('subscriptions') where name='logo_text_color'");+$columnRequired = $columnQuery->fetchArray(SQLITE3_ASSOC) === false;++if ($columnRequired) {+ $db->exec("ALTER TABLE subscriptions ADD COLUMN logo_text_color TEXT DEFAULT NULL");+ $db->exec("ALTER TABLE subscriptions ADD COLUMN logo_variant TEXT DEFAULT NULL");+}diff --git a/scripts/subscription-details.js b/scripts/subscription-details.jsindex 822be20..eb7fa36 100644--- a/scripts/subscription-details.js+++ b/scripts/subscription-details.js@@ -93,10 +93,32 @@ function renderSubscriptionDetails(subscription) {const logoContainer = document.querySelector('#details-logo');logoContainer.innerHTML = "";if (subscription.logo) {- const img = document.createElement('img');- img.src = "images/uploads/logos/" + subscription.logo;- img.alt = "";- logoContainer.appendChild(img);+ // When a themed variant exists, render both images; CSS (see+ // .logo-theme-original/.logo-theme-variant in styles.css) shows only the+ // one matching the current theme, so it updates instantly even if the+ // user toggles theme while the popup is open.+ if (subscription.logo_text_color && subscription.logo_variant) {+ const nativeTheme = subscription.logo_text_color === 'dark' ? 'light' : 'dark';++ const original = document.createElement('img');+ original.src = "images/uploads/logos/" + subscription.logo;+ original.alt = "";+ original.className = "logo-theme-original";+ original.dataset.nativeTheme = nativeTheme;+ logoContainer.appendChild(original);++ const variant = document.createElement('img');+ variant.src = "images/uploads/logos/" + subscription.logo_variant;+ variant.alt = "";+ variant.className = "logo-theme-variant";+ variant.dataset.nativeTheme = nativeTheme;+ logoContainer.appendChild(variant);+ } else {+ const img = document.createElement('img');+ img.src = "images/uploads/logos/" + subscription.logo;+ img.alt = "";+ logoContainer.appendChild(img);+ }} else {const fallback = document.createElement('span');fallback.className = 'details-logo-fallback';diff --git a/settings.php b/settings.phpindex b774dda..753493f 100644--- a/settings.php+++ b/settings.php@@ -1563,6 +1563,10 @@ $userData['currency_symbol'] = $currencies[$main_currency]['symbol'];<div class="settings-notes"><p><i class="fa-solid fa-circle-info"></i>+ <?= translate('remove_background_info', $i18n) ?>+ </p>+ <p>+ <i class="fa-solid fa-triangle-exclamation" aria-hidden="true"></i><?= translate('experimental_info', $i18n) ?></p></div>diff --git a/styles/styles.css b/styles/styles.cssindex ef59003..4b4ec85 100644--- a/styles/styles.css+++ b/styles/styles.css@@ -733,6 +733,27 @@ button.mobile-action-renew {height: 42px;}+/* Themed logo swap: some logos have plain black/white text that becomes+ unreadable on the opposite theme. When a subscription has a themed+ variant, both images are rendered (data-native-theme = the theme the+ *original* already reads well on) and this shows only the one matching+ the current theme -- reacting instantly to a live theme toggle, since it+ keys off the body.dark/body.light class set in theme.js/common.js rather+ than requiring a page reload. */+img.logo-theme-variant {+ display: none;+}++body.dark img.logo-theme-original[data-native-theme="light"],+body.light img.logo-theme-original[data-native-theme="dark"] {+ display: none;+}++body.dark img.logo-theme-variant[data-native-theme="light"],+body.light img.logo-theme-variant[data-native-theme="dark"] {+ display: revert;+}+.subscription .name {flex-basis: 25%;font-weight: 600;diff --git a/subscriptions.php b/subscriptions.phpindex 4dea601..18982db 100644--- a/subscriptions.php+++ b/subscriptions.php@@ -2,6 +2,7 @@require_once 'includes/header.php';require_once 'includes/getdbkeys.php';+require_once 'includes/logo_theme_variant.php';include_once 'includes/list_subscriptions.php';@@ -219,6 +220,8 @@ $subscriptionsView = (isset($_COOKIE['subscriptionsView']) && $_COOKIE['subscrip$id = $subscription['id'];$print[$id]['id'] = $id;$print[$id]['logo'] = $subscription['logo'] != "" ? "images/uploads/logos/" . $subscription['logo'] : "";+ $print[$id]['logo_text_color'] = $subscription['logo_text_color'] ?? null;+ $print[$id]['logo_variant'] = !empty($subscription['logo_variant']) ? "images/uploads/logos/" . $subscription['logo_variant'] : null;$print[$id]['name'] = $subscription['name'];$cycle = $subscription['cycle'];$frequency = $subscription['frequency'];