Skip to content

Beautiful Open-Source Form Builder

2.3 KB
Raw Blame
<?php

namespace App\Service\Storage;

/**
 * Service for URL-safe encoding/decoding of filenames.
 *
 * This is needed because filenames with special characters (like parentheses, apostrophes)
 * cause issues with Laravel signed URLs when the web server decodes the URL path
 * before passing it to PHP. Using base64url encoding ensures the filename only
 * contains URL-safe characters that don't get decoded by the web server.
 *
 * @see https://github.com/OpnForm/OpnForm/issues/1024
 */
class FilenameUrlEncoder
{
    /**
     * Encode a filename using URL-safe base64 encoding.
     *
     * Uses base64url encoding (RFC 4648 §5) which replaces:
     * - '+' with '-'
     * - '/' with '_'
     * - Removes padding '='
     *
     * @param string $filename The original filename
     * @return string The URL-safe encoded filename
     */
    public static function encode(string $filename): string
    {
        return rtrim(strtr(base64_encode($filename), '+/', '-_'), '=');
    }

    /**
     * Decode a URL-safe base64 encoded filename.
     *
     * @param string $encoded The encoded filename
     * @return string The original filename
     */
    public static function decode(string $encoded): string
    {
        // Add padding back if needed
        $padded = str_pad(strtr($encoded, '-_', '+/'), strlen($encoded) + (4 - strlen($encoded) % 4) % 4, '=', STR_PAD_RIGHT);

        $decoded = base64_decode($padded, true);

        if ($decoded === false) {
            // If decoding fails, return the original string (backward compatibility)
            return $encoded;
        }

        return $decoded;
    }

    public static function isEncoded(string $value): bool
    {
        if ($value === '') {
            return false;
        }

        $decoded = self::decode($value);
        if ($decoded === $value) {
            return false;
        }

        if (self::encode($decoded) !== $value) {
            return false;
        }

        return self::isPlausibleFilename($decoded);
    }

    public static function isPlausibleFilename(string $filename): bool
    {
        if ($filename === '' || !mb_check_encoding($filename, 'UTF-8')) {
            return false;
        }

        // Keep in sync with S3KeyCleaner allowed filename characters (excluding "/").
        return preg_match('/^[\p{L}\p{N}\.\s_\-\(\)\'!*]+$/u', $filename) === 1;
    }
}