Skip to content

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

10.3 KB
Raw Blame
<?php
error_reporting(E_ERROR | E_PARSE);
require_once '../../includes/connect_endpoint.php';
require_once '../../includes/inputvalidation.php';
require_once '../../includes/getsettings.php';
require_once '../../includes/validate_endpoint.php';
require_once '../../includes/ssrf_helper.php';

if (!file_exists('../../images/uploads/logos')) {
    mkdir('../../images/uploads/logos', 0777, true);
    mkdir('../../images/uploads/logos/avatars', 0777, true);
}

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 getLogoFromUrl($url, $uploadDir, $name, $i18n, $settings)
{
    $currentUrl = $url;
    $maxRedirects = 3;

    for ($i = 0; $i <= $maxRedirects; $i++) {
        if (!filter_var($currentUrl, FILTER_VALIDATE_URL) || !preg_match('/^https?:\/\//i', $currentUrl)) {
            return ["success" => false, "message" => "Invalid URL format."];
        }

        $host = parse_url($currentUrl, PHP_URL_HOST);
        $port = parse_url($currentUrl, PHP_URL_PORT) ?: (parse_url($currentUrl, PHP_URL_SCHEME) === 'https' ? 443 : 80);
        
        $ip = gethostbyname($host);

        $is_private = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false 
                      || is_cgnat_ip($ip);

        if ($is_private) {
            return ["success" => false, "message" => "Invalid IP Address."];
        }

        $ch = curl_init($currentUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Wallos/1.0');
        
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); 

        curl_setopt($ch, CURLOPT_RESOLVE, ["{$host}:{$port}:{$ip}"]);

        $imageData = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($httpCode >= 300 && $httpCode < 400) {
            $redirectUrl = curl_getinfo($ch, CURLINFO_REDIRECT_URL);
            curl_close($ch);
            if (!$redirectUrl) break;
            
            $currentUrl = $redirectUrl;
            continue;
        }

        if ($imageData !== false && $httpCode === 200) {
            $timestamp = time();
            $fileName = $timestamp . '-payments-' . sanitizeFilename($name) . '.png';
            $uploadFile = rtrim($uploadDir, '/') . '/' . $fileName;

            if (saveLogo($imageData, $uploadFile, $name, $settings)) {
                unset($ch);
                return ["success" => true, "filename" => $fileName];
            }
        }

        unset($ch);
        break; 
    }

    return ["success" => false, "message" => "Failed to fetch image."];
}


function saveLogo($imageData, $uploadFile, $name, $settings)
{
    $image = imagecreatefromstring($imageData);
    $removeBackground = isset($settings['removeBackground']) && $settings['removeBackground'] === 'true';
    if ($image !== false) {
        $tempFile = tempnam(sys_get_temp_dir(), 'logo');
        imagepng($image, $tempFile);
        imagedestroy($image);

        $newImage = imagecreatefrompng($tempFile);
        if ($removeBackground) {
            require_once __DIR__ . '/../../includes/gd_background_removal.php';
            // 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;
    } else {
        return false;
    }
}

function resizeAndUploadLogo($uploadedFile, $uploadDir, $name)
{
    $targetWidth = 70;
    $targetHeight = 48;

    $timestamp = time();
    $originalFileName = $uploadedFile['name'];
    $fileExtension = pathinfo($originalFileName, PATHINFO_EXTENSION);
    $fileExtension = validateFileExtension($fileExtension) ? $fileExtension : 'png';
    $fileName = $timestamp . '-payments-' . 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);
            }

            // Crop/trim transparent margins (ensure we update dimensions after cropping)
            require_once __DIR__ . '/../../includes/gd_background_removal.php';
            $image = gdCropTransparent($image, 2);
            $width = imagesx($image);
            $height = imagesy($image);

            $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 $fileName;
        }
    }

    return "";
}

$enabled = 1;
$name = validate($_POST["paymentname"]);
$iconUrl = validate($_POST['icon-url']);

if ($name === "" || ($iconUrl === "" && empty($_FILES['paymenticon']['name']))) {
    $response = [
        "success" => false,
        "message" => translate('fill_all_fields', $i18n)
    ];
    echo json_encode($response);
    exit();
}


$icon = "";

if ($iconUrl !== "") {
    // getLogoFromUrl() reported failure as an array and success as a bare
    // string, and neither the caller nor the bind below looked. The array went
    // into the icon column, the insert failed, and this endpoint answered with
    // a plain-text error the page cannot read, so the user saw "Unknown
    // error, please try again" while the reason the helper had already worked
    // out was thrown away, and error_reporting above kept the warning out of
    // the log (closes #1185).
    //
    // Both subscription copies of this helper already answer
    // ['success' => bool, 'filename'|'message'] and are checked at the call
    // site; this is that shape.
    $result = getLogoFromUrl($iconUrl, '../../images/uploads/logos/', $name, $i18n, $settings);

    if (empty($result['success'])) {
        echo json_encode([
            "success" => false,
            "message" => $result['message'] ?? translate('error', $i18n)
        ]);
        exit();
    }

    $icon = $result['filename'];
} else {
    if (!empty($_FILES['paymenticon']['name'])) {
        $fileType = mime_content_type($_FILES['paymenticon']['tmp_name']);
        if (strpos($fileType, 'image') === false) {
            $response = [
                "success" => false,
                "message" => translate('fill_all_fields', $i18n)
            ];
            echo json_encode($response);
            exit();
        }
        $icon = resizeAndUploadLogo($_FILES['paymenticon'], '../../images/uploads/logos/', $name);
    }
}

// Get the maximum existing ID
$stmt = $db->prepare("SELECT MAX(id) as maxID FROM payment_methods");
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
$maxID = $row['maxID'];

// Ensure the new ID is greater than 31
$newID = max($maxID + 1, 32);

// Insert the new record with the new ID
$sql = "INSERT INTO payment_methods (id, name, icon, enabled, user_id) VALUES (:id, :name, :icon, :enabled, :userId)";
$stmt = $db->prepare($sql);

$stmt->bindParam(':id', $newID, SQLITE3_INTEGER);
$stmt->bindParam(':name', $name, SQLITE3_TEXT);
$stmt->bindParam(':icon', $icon, SQLITE3_TEXT);
$stmt->bindParam(':enabled', $enabled, SQLITE3_INTEGER);
$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);

if ($stmt->execute()) {
    $success['success'] = true;
    $success['message'] = translate('payment_method_added_successfuly', $i18n);
    $json = json_encode($success);
    header('Content-Type: application/json');
    echo $json;
    exit();
} else {
    echo translate('error', $i18n) . ": " . $db->lastErrorMsg();
}

$db->close();

?>