39 lines
1.1 KiB
PHP
39 lines
1.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\FileManager\Model;
|
|
|
|
use Magento\Framework\Exception\LocalizedException;
|
|
|
|
class Filename
|
|
{
|
|
/**
|
|
* @throws LocalizedException
|
|
*/
|
|
public function sanitize(string $originalName, string $extension): string
|
|
{
|
|
if ($originalName === '' || str_contains($originalName, "\0")
|
|
|| str_contains($originalName, '../') || str_contains($originalName, '..\\')
|
|
) {
|
|
throw new LocalizedException(__('The file name is invalid.'));
|
|
}
|
|
|
|
$leafName = basename(str_replace('\\', '/', $originalName));
|
|
$stem = (string) pathinfo($leafName, PATHINFO_FILENAME);
|
|
$stem = preg_replace('/[^\p{L}\p{N}._-]+/u', '_', $stem) ?? '';
|
|
$stem = preg_replace('/\.{2,}/', '.', $stem) ?? '';
|
|
$stem = trim($stem, ".-_ \t\n\r\0\x0B");
|
|
if ($stem === '') {
|
|
$stem = 'file';
|
|
}
|
|
|
|
if (function_exists('mb_strcut')) {
|
|
$stem = mb_strcut($stem, 0, 180, 'UTF-8');
|
|
} else {
|
|
$stem = substr($stem, 0, 180);
|
|
}
|
|
|
|
return $stem . '.' . $extension;
|
|
}
|
|
}
|