This repository has been archived by the owner on Feb 23, 2019. It is now read-only.
/
Util_Mime.php
80 lines (65 loc) · 1.6 KB
/
Util_Mime.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
namespace W3TC;
class Util_Mime {
/**
* Returns file mime type
*
* @param string $file
* @return string
*/
static public function get_mime_type( $file ) {
static $cache = array();
if ( !isset( $cache[$file] ) ) {
$mime_type = false;
/**
* Try to detect by extension (fast)
*/
$mime_types = include W3TC_INC_DIR . '/mime/all.php';
foreach ( $mime_types as $extension => $type ) {
if ( preg_match( '~\.(' . $extension . ')$~i', $file ) ) {
if ( is_array( $type ) )
$mime_type = array_pop( $type );
else
$mime_type = $type;
break;
}
}
/**
* Try to detect using file info function
*/
if ( !$mime_type && function_exists( 'finfo_open' ) ) {
$finfo = @finfo_open( FILEINFO_MIME );
if ( !$finfo ) {
$finfo = @finfo_open( FILEINFO_MIME );
}
if ( $finfo ) {
$mime_type = @finfo_file( $finfo, $file );
if ( $mime_type ) {
$extra_mime_type_info = strpos( $mime_type, "; " );
if ( $extra_mime_type_info ) {
$mime_type = substr( $mime_type, 0, $extra_mime_type_info );
}
if ( $mime_type == 'application/octet-stream' ) {
$mime_type = false;
}
}
@finfo_close( $finfo );
}
}
/**
* Try to detect using mime type function
*/
if ( !$mime_type && function_exists( 'mime_content_type' ) ) {
$mime_type = @mime_content_type( $file );
}
/**
* If detection failed use default mime type
*/
if ( !$mime_type ) {
$mime_type = 'application/octet-stream';
}
$cache[$file] = $mime_type;
}
return $cache[$file];
}
}