1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Saito - The Threaded Web Forum |
7
|
|
|
* |
8
|
|
|
* @copyright Copyright (c) the Saito Project Developers |
9
|
|
|
* @link https://github.com/Schlaefer/Saito |
10
|
|
|
* @license http://opensource.org/licenses/MIT |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace ImageUploader\Lib; |
14
|
|
|
|
15
|
|
|
use Cake\Core\Configure; |
16
|
|
|
use Cake\Filesystem\File; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Determine mime-type for a file and try to fix some common mime-type issues. |
20
|
|
|
*/ |
21
|
|
|
class MimeType |
22
|
|
|
{ |
23
|
|
|
/** @var array [<wrong type> => [<file .ext> => <right type>]] */ |
24
|
|
|
private static $conversion = [ |
25
|
|
|
'application/octet-stream' => [ |
26
|
|
|
'mp4' => 'video/mp4', |
27
|
|
|
], |
28
|
|
|
]; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Get mime-type |
32
|
|
|
* |
33
|
|
|
* @param string $filepath File path on server to check the actual file |
34
|
|
|
* @param string|null $name Original file name with original extension |
35
|
|
|
* @return string Determined mime-type |
36
|
|
|
*/ |
37
|
|
|
public static function get(string $filepath, ?string $name): string |
38
|
|
|
{ |
39
|
|
|
$file = new File($filepath); |
40
|
|
|
$type = $file->mime(); |
41
|
|
|
|
42
|
|
|
$name = $name ?: $file->pwd(); |
43
|
|
|
$type = self::fixByFileExtension($type, $name); |
|
|
|
|
44
|
|
|
|
45
|
|
|
return $type; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Fix type based on filename extension |
50
|
|
|
* |
51
|
|
|
* @param string $type original mime-type |
52
|
|
|
* @param string $filename path to file for filename |
53
|
|
|
* @return string fixed mime-type |
54
|
|
|
*/ |
55
|
|
|
private static function fixByFileExtension(string $type, string $filename): string |
56
|
|
|
{ |
57
|
|
|
// Check that mime-type has an .extension based fix. |
58
|
|
|
if (array_key_exists($type, self::$conversion)) { |
59
|
|
|
$UploaderConfig = Configure::read('Saito.Settings.uploader'); |
60
|
|
|
$fileExtension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); |
61
|
|
|
$conversion = self::$conversion[$type]; |
62
|
|
|
foreach ($conversion as $extension => $newType) { |
63
|
|
|
// Check that file has the matching .extension. |
64
|
|
|
if ($fileExtension !== $extension) { |
65
|
|
|
continue; |
66
|
|
|
} |
67
|
|
|
// Check that the mime-type wich is considered a fix is allowed |
68
|
|
|
// at all. |
69
|
|
|
if (!$UploaderConfig->hasType($newType)) { |
70
|
|
|
continue; |
71
|
|
|
} |
72
|
|
|
$type = $newType; |
73
|
|
|
break; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $type; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|