| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Services; |
| 4 |
|
| 5 |
defined('ABSPATH') || exit; |
| 6 |
|
| 7 |
class MediaMimeType |
| 8 |
{ |
| 9 |
private const ALIASES = [ |
| 10 |
'image/jpg' => 'image/jpeg', |
| 11 |
'image/pjpeg' => 'image/jpeg', |
| 12 |
'image/x-png' => 'image/png', |
| 13 |
'image/x-bmp' => 'image/bmp', |
| 14 |
'image/x-ms-bmp' => 'image/bmp', |
| 15 |
'image/x-windows-bmp' => 'image/bmp', |
| 16 |
]; |
| 17 |
|
| 18 |
/** |
| 19 |
* Detect a media type from the file contents before falling back to its extension. |
| 20 |
* WordPress filters can return non-standard aliases such as image/jpg, which Uploadio rejects. |
| 21 |
*/ |
| 22 |
public static function detect(string $filePath): string |
| 23 |
{ |
| 24 |
if (function_exists('wp_get_image_mime')) { |
| 25 |
$mimeType = wp_get_image_mime($filePath); |
| 26 |
if (is_string($mimeType) && $mimeType !== '') return self::canonicalize($mimeType); |
| 27 |
} |
| 28 |
|
| 29 |
if (function_exists('finfo_open')) { |
| 30 |
$finfo = finfo_open(FILEINFO_MIME_TYPE); |
| 31 |
if ($finfo) { |
| 32 |
$mimeType = finfo_file($finfo, $filePath); |
| 33 |
finfo_close($finfo); |
| 34 |
|
| 35 |
if (is_string($mimeType) && $mimeType !== '' && $mimeType !== 'application/octet-stream') { |
| 36 |
return self::canonicalize($mimeType); |
| 37 |
} |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
$fileType = wp_check_filetype($filePath); |
| 42 |
|
| 43 |
return !empty($fileType['type']) |
| 44 |
? self::canonicalize((string) $fileType['type']) |
| 45 |
: 'application/octet-stream'; |
| 46 |
} |
| 47 |
|
| 48 |
public static function canonicalize(string $mimeType): string |
| 49 |
{ |
| 50 |
$mimeType = strtolower(trim($mimeType)); |
| 51 |
|
| 52 |
return self::ALIASES[$mimeType] ?? $mimeType; |
| 53 |
} |
| 54 |
} |
| 55 |
|