Skip to content

Commit

Permalink
FileLoader: fixed path normalization for phar and absolute paths [Closes
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Oct 4, 2024
1 parent 6f5a699 commit 2651cd1
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/Latte/Loaders/FileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function isExpired(string $file, int $time): bool
*/
public function getReferredName(string $file, string $referringFile): string
{
if ($this->baseDir || !preg_match('#/|\\\\|[a-z][a-z0-9+.-]*:#iA', $file)) {
if ($this->baseDir || !preg_match('#/|\\\\|[a-z]:|phar:#iA', $file)) {
$file = $this->normalizePath($referringFile . '/../' . $file);
}

Expand All @@ -78,15 +78,16 @@ public function getUniqueId(string $file): string

protected static function normalizePath(string $path): string
{
preg_match('#^([a-z]:|phar://.+?/)?(.*)#i', $path, $m);
$res = [];
foreach (explode('/', strtr($path, '\\', '/')) as $part) {
if ($part === '..' && $res && end($res) !== '..') {
foreach (explode('/', strtr($m[2], '\\', '/')) as $part) {
if ($part === '..' && $res && end($res) !== '..' && end($res) !== '') {
array_pop($res);
} elseif ($part !== '.') {
$res[] = $part;
}
}

return implode(DIRECTORY_SEPARATOR, $res);
return $m[1] . implode(DIRECTORY_SEPARATOR, $res);
}
}
5 changes: 5 additions & 0 deletions tests/common/Loaders.FileLoader.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ Assert::same('/a/b/inner', strtr($loader->getReferredName('inner', '/a\\b/c'), '
Assert::same('/a/b/c', strtr($loader->getReferredName('/a/b/c', '/a/b/c'), '\\', '/'));
Assert::same('/a/c', strtr($loader->getReferredName('../c', '/a/b/c'), '\\', '/'));

Assert::same('/../c', strtr($loader->getReferredName('../c', '/a'), '\\', '/'));
Assert::same('w:/../c', strtr($loader->getReferredName('../c', 'w:\a'), '\\', '/'));
Assert::same('phar://file.phar/../c', strtr($loader->getReferredName('../c', 'phar://file.phar/a'), '\\', '/'));


$loader = new FileLoader;
Assert::exception(
fn() => $loader->getContent('unknown'),
Expand Down

0 comments on commit 2651cd1

Please sign in to comment.