forked from fa/breadcrumb-the-shire
329 lines
9.9 KiB
PHP
329 lines
9.9 KiB
PHP
<?php
|
|
|
|
namespace MintyPHP\Service\Tenant;
|
|
|
|
class TenantAvatarService
|
|
{
|
|
private const MAX_SIZE = 5242880; // 5 MB
|
|
private const SIZES = [64, 128, 256];
|
|
private const DEFAULT_SIZE = 128;
|
|
|
|
public static function isValidUuid(string $uuid): bool
|
|
{
|
|
return (bool) preg_match('/^[a-f0-9-]{36}$/i', $uuid);
|
|
}
|
|
|
|
public static function storageBase(): string
|
|
{
|
|
if (defined('APP_STORAGE_PATH') && APP_STORAGE_PATH) {
|
|
return rtrim(APP_STORAGE_PATH, '/');
|
|
}
|
|
return rtrim(dirname(__DIR__, 3) . '/storage', '/');
|
|
}
|
|
|
|
public static function tenantDir(string $uuid): string
|
|
{
|
|
return self::storageBase() . '/tenants/' . $uuid . '/avatar';
|
|
}
|
|
|
|
public static function findAvatarPath(string $uuid, ?int $size = null): ?string
|
|
{
|
|
if (!self::isValidUuid($uuid)) {
|
|
return null;
|
|
}
|
|
$dirs = self::avatarDirs($uuid);
|
|
foreach ($dirs as $dir) {
|
|
if (!is_dir($dir)) {
|
|
continue;
|
|
}
|
|
if ($size) {
|
|
$size = self::normalizeSize($size);
|
|
$variant = self::findVariantPath($dir, $size);
|
|
if ($variant) {
|
|
return $variant;
|
|
}
|
|
}
|
|
$defaultVariant = self::findVariantPath($dir, self::DEFAULT_SIZE);
|
|
if ($defaultVariant) {
|
|
return $defaultVariant;
|
|
}
|
|
$original = self::findOriginalPath($dir);
|
|
if ($original) {
|
|
return $original;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public static function hasAvatar(string $uuid): bool
|
|
{
|
|
$path = self::findAvatarPath($uuid);
|
|
return $path ? is_file($path) : false;
|
|
}
|
|
|
|
public static function delete(string $uuid): bool
|
|
{
|
|
if (!self::isValidUuid($uuid)) {
|
|
return false;
|
|
}
|
|
foreach (self::avatarDirs($uuid) as $dir) {
|
|
if (!is_dir($dir)) {
|
|
continue;
|
|
}
|
|
$matches = array_merge(
|
|
glob($dir . '/avatar-*.*') ?: [],
|
|
glob($dir . '/avatar.*') ?: [],
|
|
glob($dir . '/original.*') ?: []
|
|
);
|
|
foreach ($matches as $file) {
|
|
if (is_file($file)) {
|
|
@unlink($file);
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public static function saveUpload(string $uuid, array $file): array
|
|
{
|
|
if (!self::isValidUuid($uuid)) {
|
|
return ['ok' => false, 'error' => t('Tenant not found')];
|
|
}
|
|
if (empty($file) || !isset($file['tmp_name'])) {
|
|
return ['ok' => false, 'error' => t('No file uploaded')];
|
|
}
|
|
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
|
|
return ['ok' => false, 'error' => t('Upload failed')];
|
|
}
|
|
if (($file['size'] ?? 0) > self::MAX_SIZE) {
|
|
return ['ok' => false, 'error' => t('File is too large')];
|
|
}
|
|
|
|
$tmpPath = $file['tmp_name'];
|
|
$mime = self::detectMime($tmpPath);
|
|
$isSvg = self::isSvgUpload($mime, $tmpPath);
|
|
$ext = self::extensionForMime($mime, $isSvg);
|
|
if (!$ext) {
|
|
return ['ok' => false, 'error' => t('Invalid image file')];
|
|
}
|
|
if ($isSvg && !self::isSafeSvg($tmpPath)) {
|
|
return ['ok' => false, 'error' => t('Invalid image file')];
|
|
}
|
|
|
|
$dir = self::tenantDir($uuid);
|
|
if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
|
|
return ['ok' => false, 'error' => t('Upload failed')];
|
|
}
|
|
|
|
self::delete($uuid);
|
|
$originalPath = $dir . '/original.' . $ext;
|
|
if (!move_uploaded_file($tmpPath, $originalPath)) {
|
|
return ['ok' => false, 'error' => t('Upload failed')];
|
|
}
|
|
@chmod($originalPath, 0644);
|
|
|
|
$variantExt = function_exists('imagewebp') ? 'webp' : 'jpg';
|
|
if (!$isSvg && self::canResize()) {
|
|
foreach (self::SIZES as $size) {
|
|
$target = $dir . '/avatar-' . $size . '.' . $variantExt;
|
|
self::resizeAndFit($originalPath, $target, $size, $size, $variantExt);
|
|
}
|
|
}
|
|
|
|
return ['ok' => true, 'path' => $originalPath, 'mime' => $mime];
|
|
}
|
|
|
|
public static function detectMime(string $path): string
|
|
{
|
|
if (function_exists('finfo_open')) {
|
|
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
|
if ($finfo) {
|
|
$mime = finfo_file($finfo, $path);
|
|
if (is_string($mime) && $mime !== '') {
|
|
if (self::isSvgUpload($mime, $path)) {
|
|
return 'image/svg+xml';
|
|
}
|
|
return $mime;
|
|
}
|
|
}
|
|
}
|
|
if (self::isSvgUpload('application/octet-stream', $path)) {
|
|
return 'image/svg+xml';
|
|
}
|
|
return 'application/octet-stream';
|
|
}
|
|
|
|
private static function extensionForMime(string $mime, bool $isSvg = false): ?string
|
|
{
|
|
if ($isSvg) {
|
|
return 'svg';
|
|
}
|
|
$map = [
|
|
'image/jpeg' => 'jpg',
|
|
'image/png' => 'png',
|
|
'image/webp' => 'webp',
|
|
];
|
|
return $map[$mime] ?? null;
|
|
}
|
|
|
|
private static function isSvgUpload(string $mime, string $path): bool
|
|
{
|
|
if ($mime === 'image/svg+xml') {
|
|
return true;
|
|
}
|
|
$head = @file_get_contents($path, false, null, 0, 1024);
|
|
if (!is_string($head) || $head === '') {
|
|
return false;
|
|
}
|
|
return stripos($head, '<svg') !== false;
|
|
}
|
|
|
|
private static function isSafeSvg(string $path): bool
|
|
{
|
|
$contents = @file_get_contents($path);
|
|
if (!is_string($contents) || $contents === '') {
|
|
return false;
|
|
}
|
|
$lower = strtolower($contents);
|
|
if (strpos($lower, '<script') !== false) {
|
|
return false;
|
|
}
|
|
if (strpos($lower, 'onload=') !== false) {
|
|
return false;
|
|
}
|
|
if (strpos($lower, 'javascript:') !== false) {
|
|
return false;
|
|
}
|
|
if (strpos($lower, '<foreignobject') !== false) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private static function normalizeSize(int $size): int
|
|
{
|
|
if (in_array($size, self::SIZES, true)) {
|
|
return $size;
|
|
}
|
|
return self::DEFAULT_SIZE;
|
|
}
|
|
|
|
private static function findVariantPath(string $dir, int $size): ?string
|
|
{
|
|
$matches = glob($dir . '/avatar-' . $size . '.*');
|
|
if (!$matches) {
|
|
return null;
|
|
}
|
|
usort($matches, static function ($a, $b) {
|
|
return filemtime($b) <=> filemtime($a);
|
|
});
|
|
return $matches[0] ?? null;
|
|
}
|
|
|
|
private static function findOriginalPath(string $dir): ?string
|
|
{
|
|
$matches = glob($dir . '/original.*');
|
|
if (!$matches) {
|
|
return null;
|
|
}
|
|
usort($matches, static function ($a, $b) {
|
|
return filemtime($b) <=> filemtime($a);
|
|
});
|
|
return $matches[0] ?? null;
|
|
}
|
|
|
|
private static function canResize(): bool
|
|
{
|
|
return function_exists('imagecreatetruecolor') && function_exists('imagecopyresampled');
|
|
}
|
|
|
|
private static function createImageResource(string $path, string $mime)
|
|
{
|
|
if ($mime === 'image/jpeg' && function_exists('imagecreatefromjpeg')) {
|
|
return imagecreatefromjpeg($path);
|
|
}
|
|
if ($mime === 'image/png' && function_exists('imagecreatefrompng')) {
|
|
return imagecreatefrompng($path);
|
|
}
|
|
if ($mime === 'image/webp' && function_exists('imagecreatefromwebp')) {
|
|
return imagecreatefromwebp($path);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private static function resizeAndFit(string $sourcePath, string $targetPath, int $width, int $height, string $ext): bool
|
|
{
|
|
$mime = self::detectMime($sourcePath);
|
|
$src = self::createImageResource($sourcePath, $mime);
|
|
if (!$src) {
|
|
return false;
|
|
}
|
|
|
|
$srcWidth = imagesx($src);
|
|
$srcHeight = imagesy($src);
|
|
if ($srcWidth === 0 || $srcHeight === 0) {
|
|
imagedestroy($src);
|
|
return false;
|
|
}
|
|
|
|
$scale = min($width / $srcWidth, $height / $srcHeight);
|
|
$dstWidth = (int) round($srcWidth * $scale);
|
|
$dstHeight = (int) round($srcHeight * $scale);
|
|
if ($dstWidth < 1) $dstWidth = 1;
|
|
if ($dstHeight < 1) $dstHeight = 1;
|
|
|
|
$dst = imagecreatetruecolor($dstWidth, $dstHeight);
|
|
if ($ext === 'png' || $ext === 'webp') {
|
|
imagealphablending($dst, false);
|
|
imagesavealpha($dst, true);
|
|
$transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127);
|
|
imagefilledrectangle($dst, 0, 0, $dstWidth, $dstHeight, $transparent);
|
|
}
|
|
|
|
imagecopyresampled(
|
|
$dst,
|
|
$src,
|
|
0,
|
|
0,
|
|
0,
|
|
0,
|
|
$dstWidth,
|
|
$dstHeight,
|
|
$srcWidth,
|
|
$srcHeight
|
|
);
|
|
|
|
$saved = false;
|
|
if ($ext === 'webp' && function_exists('imagewebp')) {
|
|
$saved = imagewebp($dst, $targetPath, 82);
|
|
} elseif ($ext === 'png' && function_exists('imagepng')) {
|
|
$saved = imagepng($dst, $targetPath, 6);
|
|
} else {
|
|
$saved = imagejpeg($dst, $targetPath, 85);
|
|
}
|
|
|
|
imagedestroy($src);
|
|
imagedestroy($dst);
|
|
|
|
if ($saved) {
|
|
@chmod($targetPath, 0644);
|
|
}
|
|
return $saved;
|
|
}
|
|
|
|
private static function avatarDirs(string $uuid): array
|
|
{
|
|
$dirs = [self::tenantDir($uuid)];
|
|
$legacy = self::legacyTenantDir($uuid);
|
|
if ($legacy !== $dirs[0]) {
|
|
$dirs[] = $legacy;
|
|
}
|
|
return $dirs;
|
|
}
|
|
|
|
private static function legacyTenantDir(string $uuid): string
|
|
{
|
|
return self::storageBase() . '/tenants/' . $uuid;
|
|
}
|
|
}
|