Issue Bug Closed

#106002PathUtility::stripPathSitePrefix generates invalid paths for symlinked document root

Kai Lochbaum 01/28/25, 15:05 updated 12/02/25, 14:27

Description

The static method PathUtility::stripPathSitePrefix removes the public path from the passed $path variable regardless whether the variable starts with the public path or not.

*Prerequisites*
The document root must contain a symbolic link somewhere in the hierarchy.
(!) The real path and the link path must have different lengths.

e.g.
Real path: /kunden/A/B/document_root
Environment Public path / Document Root via Apache: /www/A/B/document_root

*Steps to reproduce the problem*
In PHP call PathUtility::stripPathSitePrefix('/kunden/A/B/document_root/image.png');

Expected result: image.png
Actual result: ot/image.png

Our actual use case uses the GifBuilder to create grayscale images.
The GifBuilder creates an ImageInfo object that uses realpath values.
The public url for the image resource ends up with additional characters at the beginning (ot/typo3temp… instead of typo3temp…).

$imageInfo = GeneralUtility::makeInstance(ImageInfo::class, $fullFileName);
$imageResource = ImageResource::createFromImageInfo($imageInfo);
// calls PathUtility::stripPathSitePrefix($imageInfo->getRealPath())
$imageResource->getPublicUrl();

*Solution*
From my limited core knowledge ;), I would suggest two changes to the function:
1. Use realpath to resolve symbolic links
2. Check if the path actually starts with the public path before using substring.

A possible implementation could be

    /**
     * Strip first part of a path, equal to the length of public web path including trailing slash
     *
     * @internal
     */
    public static function stripPathSitePrefix(string $path): string
    {
        $realPath = realpath($path) ?: $path;
        $realPublicPath = realpath(Environment::getPublicPath()) ?: Environment::getPublicPath();
        if (str_starts_with($realPath, $realPublicPath)) {
            return substr($realPath, strlen($realPublicPath . '/'));
        }
        return $path;
    }

Reviews 6