TYPO3 v15 dev-main snapshot ()
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is part of the TYPO3 CMS project.
|
||||
*
|
||||
* It is free software; you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License, either version 2
|
||||
* of the License, or any later version.
|
||||
*
|
||||
* For the full copyright and license information, please read the
|
||||
* LICENSE.txt file that was distributed with this source code.
|
||||
*
|
||||
* The TYPO3 project - inspiring people to share!
|
||||
*/
|
||||
|
||||
namespace TYPO3\CMS\Core\Utility\File;
|
||||
|
||||
use TYPO3\CMS\Core\Charset\CharsetConverter;
|
||||
use TYPO3\CMS\Core\Utility\GeneralUtility;
|
||||
use TYPO3\CMS\Core\Utility\PathUtility;
|
||||
use TYPO3\CMS\Core\Utility\StringUtility;
|
||||
|
||||
/**
|
||||
* Contains class with basic file management functions
|
||||
*
|
||||
* Contains functions for management, validation etc of files in TYPO3.
|
||||
*
|
||||
* @internal All methods in this class should not be used anymore since TYPO3 6.0, this class is therefore marked
|
||||
* as internal.
|
||||
* Please use corresponding \TYPO3\CMS\Core\Resource\ResourceStorage
|
||||
* (fetched via BE_USERS->getFileStorages()), as all functions should be
|
||||
* found there (in a cleaner manner).
|
||||
*/
|
||||
class BasicFileUtility
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public const UNSAFE_FILENAME_CHARACTER_EXPRESSION = '\\x00-\\x2C\\/\\x3A-\\x3F\\x5B-\\x60\\x7B-\\xBF';
|
||||
|
||||
/**
|
||||
* This number decides the highest allowed appended number used on a filename before we use naming with unique strings
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $maxNumber = 99;
|
||||
|
||||
/**
|
||||
* This number decides how many characters out of a unique MD5-hash that is appended to a filename if getUniqueName is asked to find an available filename.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $uniquePrecision = 6;
|
||||
|
||||
/**
|
||||
* Cleans $theDir for slashes in the end of the string and returns the new path, if it exists on the server.
|
||||
*
|
||||
* @param string $theDir Directory path to check
|
||||
* @return bool|string Returns the cleaned up directory name if OK, otherwise FALSE.
|
||||
* @todo: should go into the LocalDriver in a protected way (not important to the outside world)
|
||||
*/
|
||||
protected function sanitizeFolderPath($theDir)
|
||||
{
|
||||
if (!GeneralUtility::validPathStr($theDir)) {
|
||||
return false;
|
||||
}
|
||||
$theDir = PathUtility::getCanonicalPath($theDir);
|
||||
if (@is_dir($theDir)) {
|
||||
return $theDir;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the destination path/filename of a unique filename/foldername in that path.
|
||||
* If $theFile exists in $theDest (directory) the file have numbers appended up to $this->maxNumber. Hereafter a unique string will be appended.
|
||||
* This function is used by fx. DataHandler when files are attached to records and needs to be uniquely named in the uploads/* folders
|
||||
*
|
||||
* @param string $theFile The input filename to check
|
||||
* @param string $theDest The directory for which to return a unique filename for $theFile. $theDest MUST be a valid directory. Should be absolute.
|
||||
* @param bool $dontCheckForUnique If set the filename is returned with the path prepended without checking whether it already existed!
|
||||
* @return string|null The destination absolute filepath (not just the name!) of a unique filename/foldername in that path.
|
||||
* @internal May be removed without further notice. Method has been marked as deprecated for various versions but is still used in core.
|
||||
* @todo: should go into the LocalDriver in a protected way (not important to the outside world)
|
||||
*/
|
||||
public function getUniqueName($theFile, $theDest, $dontCheckForUnique = false)
|
||||
{
|
||||
// $theDest is cleaned up
|
||||
$theDest = $this->sanitizeFolderPath($theDest);
|
||||
if ($theDest) {
|
||||
// Fetches info about path, name, extension of $theFile
|
||||
$origFileInfo = GeneralUtility::split_fileref($theFile);
|
||||
// Check if the file exists and if not - return the filename...
|
||||
$fileInfo = $origFileInfo;
|
||||
$theDestFile = $theDest . '/' . $fileInfo['file'];
|
||||
// The destinations file
|
||||
if (!file_exists($theDestFile) || $dontCheckForUnique) {
|
||||
// If the file does NOT exist we return this filename
|
||||
return $theDestFile;
|
||||
}
|
||||
// Well the filename in its pure form existed. Now we try to append numbers / unique-strings and see if we can find an available filename...
|
||||
$theTempFileBody = preg_replace('/_[0-9][0-9]$/', '', $origFileInfo['filebody']);
|
||||
// This removes _xx if appended to the file
|
||||
$theOrigExt = $origFileInfo['realFileext'] ? '.' . $origFileInfo['realFileext'] : '';
|
||||
for ($a = 1; $a <= $this->maxNumber + 1; $a++) {
|
||||
if ($a <= $this->maxNumber) {
|
||||
// First we try to append numbers
|
||||
$insert = '_' . sprintf('%02d', $a);
|
||||
} else {
|
||||
// .. then we try unique-strings...
|
||||
$insert = '_' . substr(md5(StringUtility::getUniqueId()), 0, $this->uniquePrecision);
|
||||
}
|
||||
$theTestFile = $theTempFileBody . $insert . $theOrigExt;
|
||||
$theDestFile = $theDest . '/' . $theTestFile;
|
||||
// The destinations file
|
||||
if (!file_exists($theDestFile)) {
|
||||
// If the file does NOT exist we return this filename
|
||||
return $theDestFile;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a string where any character not matching [.a-zA-Z0-9_-] is substituted by '_'
|
||||
* Trailing dots are removed
|
||||
*
|
||||
* @param string $fileName Input string, typically the body of a filename
|
||||
* @return string Output string with any characters not matching [.a-zA-Z0-9_-] is substituted by '_' and trailing dots removed
|
||||
* @internal May be removed without further notice. Method has been marked as deprecated for various versions but is still used in core.
|
||||
*/
|
||||
public function cleanFileName($fileName)
|
||||
{
|
||||
// Handle UTF-8 characters
|
||||
if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['UTF8filesystem']) {
|
||||
// allow ".", "-", 0-9, a-z, A-Z and everything beyond U+C0 (latin capital letter a with grave)
|
||||
$cleanFileName = preg_replace('/[' . self::UNSAFE_FILENAME_CHARACTER_EXPRESSION . ']/u', '_', trim($fileName)) ?? '';
|
||||
} else {
|
||||
$fileName = GeneralUtility::makeInstance(CharsetConverter::class)->utf8_char_mapping($fileName);
|
||||
// Replace unwanted characters by underscores
|
||||
$cleanFileName = preg_replace('/[' . self::UNSAFE_FILENAME_CHARACTER_EXPRESSION . '\\xC0-\\xFF]/', '_', trim($fileName)) ?? '';
|
||||
}
|
||||
// Strip trailing dots and return
|
||||
return rtrim($cleanFileName, '.');
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is part of the TYPO3 CMS project.
|
||||
*
|
||||
* It is free software; you can redistribute it and/or modify it under
|
||||
* the terms of the GNU General Public License, either version 2
|
||||
* of the License, or any later version.
|
||||
*
|
||||
* For the full copyright and license information, please read the
|
||||
* LICENSE.txt file that was distributed with this source code.
|
||||
*
|
||||
* The TYPO3 project - inspiring people to share!
|
||||
*/
|
||||
|
||||
namespace TYPO3\CMS\Core\Utility\File;
|
||||
|
||||
use Symfony\Component\Filesystem\Exception\IOException;
|
||||
use TYPO3\CMS\Core\Core\Environment;
|
||||
use TYPO3\CMS\Core\Utility\CommandUtility;
|
||||
use TYPO3\CMS\Core\Utility\PathUtility;
|
||||
|
||||
/**
|
||||
* Most of this code is thankfully taken from \Composer\Util\Filesystem
|
||||
*
|
||||
* @internal Only to be used in TYPO3\CMS\Core\SystemResource namespace
|
||||
*/
|
||||
readonly class FileSystem
|
||||
{
|
||||
/**
|
||||
* Returns the shortest path from $from to $to
|
||||
*
|
||||
* @param bool $directories If true, the source/target are considered to be directories
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public function findShortestPath(string $from, string $to, bool $directories = false): string
|
||||
{
|
||||
if (!PathUtility::isAbsolutePath($from) || !PathUtility::isAbsolutePath($to)) {
|
||||
throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to), 1765283155);
|
||||
}
|
||||
|
||||
$from = PathUtility::getCanonicalPath($from);
|
||||
$to = PathUtility::getCanonicalPath($to);
|
||||
|
||||
if ($directories) {
|
||||
$from = rtrim($from, '/') . '/dummy_file';
|
||||
}
|
||||
|
||||
if (dirname($from) === dirname($to)) {
|
||||
return './' . basename($to);
|
||||
}
|
||||
|
||||
$commonPath = $to;
|
||||
while (!str_starts_with($from . '/', $commonPath . '/') && $commonPath !== '/' && preg_match('{^[A-Z]:/?$}i', $commonPath) === 0) {
|
||||
$commonPath = str_replace('\\', '/', dirname($commonPath));
|
||||
}
|
||||
|
||||
// no commonality at all
|
||||
if (!str_starts_with($from, $commonPath)) {
|
||||
return $to;
|
||||
}
|
||||
|
||||
$commonPath = rtrim($commonPath, '/') . '/';
|
||||
$sourcePathDepth = substr_count((string)substr($from, strlen($commonPath)), '/');
|
||||
$commonPathCode = str_repeat('../', $sourcePathDepth);
|
||||
|
||||
$result = $commonPathCode . substr($to, strlen($commonPath));
|
||||
if ($result === '') {
|
||||
return './';
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a relative symlink from $link to $target
|
||||
*
|
||||
* @param string $target The path of the binary file to be symlinked
|
||||
* @param string $link The path where the symlink should be created
|
||||
*/
|
||||
public function relativeSymlink(string $target, string $link): bool
|
||||
{
|
||||
if (!function_exists('symlink')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$cwd = $this->getCwd();
|
||||
|
||||
$relativePath = $this->findShortestPath($link, $target);
|
||||
chdir(dirname($link));
|
||||
$result = @symlink($relativePath, $link);
|
||||
|
||||
chdir($cwd);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if that directory is a symlink.
|
||||
*/
|
||||
public function isSymlinkedDirectory(string $directory): bool
|
||||
{
|
||||
if (!is_dir($directory)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$resolved = $this->resolveSymlinkedDirectorySymlink($directory);
|
||||
|
||||
return is_link($resolved);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if that file is a symlink.
|
||||
*/
|
||||
public function isSymlinkedFile(string $file): bool
|
||||
{
|
||||
if (!is_file($file)) {
|
||||
return false;
|
||||
}
|
||||
return is_link($file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an NTFS junction.
|
||||
*/
|
||||
public function junction(string $target, string $junction): void
|
||||
{
|
||||
if (!Environment::isWindows()) {
|
||||
throw new \LogicException(sprintf('Function %s is not available on non-Windows platform', __CLASS__), 1765283168);
|
||||
}
|
||||
if (!is_dir($target)) {
|
||||
throw new IOException(sprintf('Cannot junction to "%s" as it is not a directory.', $target), 1765283131, null, $target);
|
||||
}
|
||||
|
||||
// Removing any previously junction to ensure clean execution.
|
||||
if (!is_dir($junction) || $this->isJunction($junction)) {
|
||||
@rmdir($junction);
|
||||
}
|
||||
$commandLine = [
|
||||
'mklink',
|
||||
'/J',
|
||||
];
|
||||
$commandLine[] = str_replace('/', DIRECTORY_SEPARATOR, $junction);
|
||||
$commandLine[] = realpath($target);
|
||||
CommandUtility::exec($commandLine);
|
||||
|
||||
if (CommandUtility::exec($commandLine) === false) {
|
||||
throw new IOException(sprintf('Failed to create junction to "%s" at "%s".', $target, $junction), 1763664408, null, $target);
|
||||
}
|
||||
clearstatcache(true, $junction);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the target directory is a Windows NTFS Junction.
|
||||
*
|
||||
* We test if the path is a directory and not an ordinary link, then check
|
||||
* that the mode value returned from lstat (which gives the status of the
|
||||
* link itself) is not a directory, by replicating the POSIX S_ISDIR test.
|
||||
*
|
||||
* @param string $junction Path to check.
|
||||
*/
|
||||
public function isJunction(string $junction): bool
|
||||
{
|
||||
if (!Environment::isWindows()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Important to clear all caches first
|
||||
clearstatcache(true, $junction);
|
||||
|
||||
if (!is_dir($junction) || is_link($junction)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$stat = lstat($junction);
|
||||
|
||||
// S_ISDIR test (S_IFDIR is 0x4000, S_IFMT is 0xF000 bitmask)
|
||||
return is_array($stat) && ($stat['mode'] & 0xF000) !== 0x4000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve pathname to symbolic link of a directory
|
||||
*
|
||||
* @param string $pathname Directory path to resolve
|
||||
*/
|
||||
private function resolveSymlinkedDirectorySymlink(string $pathname): string
|
||||
{
|
||||
if (!is_dir($pathname)) {
|
||||
return $pathname;
|
||||
}
|
||||
|
||||
$resolved = rtrim($pathname, '/');
|
||||
|
||||
if ($resolved === '') {
|
||||
return $pathname;
|
||||
}
|
||||
|
||||
return $resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* getcwd() equivalent which always returns a string
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
private function getCwd(): string
|
||||
{
|
||||
$cwd = getcwd();
|
||||
// fallback to realpath('') just in case this works but odds are it would break as well if we are in a case where getcwd fails
|
||||
if ($cwd === false) {
|
||||
$cwd = realpath('');
|
||||
}
|
||||
// crappy state, assume '' and hopefully relative paths allow things to continue
|
||||
if ($cwd === false) {
|
||||
throw new \RuntimeException('Could not determine the current working directory', 1765283181);
|
||||
}
|
||||
return $cwd;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user