1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Utils;
9:
10: use Nette;
11:
12:
13: 14: 15: 16: 17:
18: class MimeTypeDetector
19: {
20:
21: 22: 23:
24: final public function __construct()
25: {
26: throw new Nette\StaticClassException;
27: }
28:
29:
30: 31: 32: 33: 34:
35: public static function fromFile($file)
36: {
37: if (!is_file($file)) {
38: throw new Nette\FileNotFoundException("File '$file' not found.");
39: }
40:
41: $info = @getimagesize($file);
42: if (isset($info['mime'])) {
43: return $info['mime'];
44:
45: } elseif (extension_loaded('fileinfo')) {
46: $type = preg_replace('#[\s;].*\z#', '', finfo_file(finfo_open(FILEINFO_MIME), $file));
47:
48: } elseif (function_exists('mime_content_type')) {
49: $type = mime_content_type($file);
50: }
51:
52: return isset($type) && preg_match('#^\S+/\S+\z#', $type) ? $type : 'application/octet-stream';
53: }
54:
55:
56: 57: 58: 59: 60:
61: public static function fromString($data)
62: {
63: if (extension_loaded('fileinfo') && preg_match('#^(\S+/[^\s;]+)#', finfo_buffer(finfo_open(FILEINFO_MIME), $data), $m)) {
64: return $m[1];
65:
66: } elseif (strncmp($data, "\xff\xd8", 2) === 0) {
67: return 'image/jpeg';
68:
69: } elseif (strncmp($data, "\x89PNG", 4) === 0) {
70: return 'image/png';
71:
72: } elseif (strncmp($data, "GIF", 3) === 0) {
73: return 'image/gif';
74:
75: } else {
76: return 'application/octet-stream';
77: }
78: }
79:
80: }
81: