Get the MIME type of a file using magic.

@param string $file_path Relative or absolute path to an existing file.

@return string|null The associated MIME type or null if no known type was detected.
177569
public static function getMagicType($file_path) {
		$file_info = finfo_open(FILEINFO_MIME_TYPE);
		$mime_type = finfo_file($file_info, $file_path);
		finfo_close($file_info);

		// Only return valid types, in order to maintain circular compatibility between methods.
		if (static::hasType($mime_type)) {
			return $mime_type;
		}
	}
1075821
private function verifyMimeType($mime_type)
    {
        $allowed = $this->config['allowed_mime_types'];
        if (! empty($allowed) && ! in_array(strtolower($mime_type), $allowed)) {
            throw FileNotSupportedException::mimeRestricted(strtolower($mime_type), $allowed);
        }

        return $mime_type;
    }
62190
public function isType($path, $mimeType)
    {
        $mimeTypes = explode('|', $mimeType);

        return (in_array(self::getType($path), $mimeTypes));
    }
77357
def guess_filetype(filepath):
    """"""
    # If we have python-magic, use it to determine file type
    typ = None

    # Some specific checks for known file suffixes
    _fn = filepath.lower()
    _name, _ext = os.path.splitext(_fn)
    if _ext in known_types:
        typ = known_types[_ext]

    if typ is None and have_magic:
        try:
            # it seems there are conflicting versions of a 'magic'
            # module for python floating around...*sigh*
            if hasattr(magic, 'from_file'):
                typ = magic.from_file(filepath, mime=True)

            elif magic_tester is not None:
                descrip = magic_tester.file(filepath)
                if descrip.startswith("FITS image data"):
                    return ('image', 'fits')

        except Exception as e:
            pass

    if typ is None:
        # if no magic, or magic fails, fall back to mimetypes
        try:
            typ, enc = mimetypes.guess_type(filepath)

        except Exception as e:
            # fail
            pass

    if typ:
        typ, subtyp = typ.split('/')
        return (typ, subtyp)

    raise ValueError("Can't determine file type of '%s'" % (filepath))
1140194
public static function _getMIME ($path)
	{
		
		// Check file exists
		
		if (!parent::_Exists ($path))
		{
			return FALSE;
		}
		
		// Get image data
		
		$arrData	= getimagesize ($path);
		
		// Return mime type
		
		return $arrData[2];
		
	}
86500
public static function readFile($file_path)
    {
        try {
            $file = fopen($file_path, 'r');
            $content = fread($file, filesize($file_path));
            fclose($file);
            return $content;
        } catch (\Exception $e) {
            return '';
        }
    }
374540
public static function guessMimeTypeByExtension($extension, $fallback_mime_type = '')
    {
        if ($extension === 'jpeg') {
            return 'image/jpeg';
        }
        $mime_type = array_search($extension, static::$mimetype_default_extensions);

        return $mime_type ?: $fallback_mime_type;
    }
739484
public static function getTypeFromFile(string $path): string
    {
        if (!is_file($path) || !is_readable($path)) {
            throw new \InvalidArgumentException(
                "invalid value provided for 'path'; ".
                "expecting an absolute path to a readable file"
            );
        }

        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $type = @$finfo->file($path);
        return ($type === false) ? "application/octet-stream" : $type;
    }
426943
public function getMimeType($file){

        if(function_exists('finfo_open')) {
            $const = defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME;
            $info = finfo_open($const);
            if($info && ($result = finfo_file($info,$file,$const)) !== false){
                finfo_close($info);
                return $result;
            }//if
        }//if

        if(function_exists('mime_content_type') && ($result = mime_content_type($file)) !== false) {
            return $result;
        }//if

    }
677078
public function get_content_type($path){
        if( file_exists($path) ){
            $info = finfo_open(FILEINFO_MIME);
            $type = finfo_file($info, $path) ;
            finfo_close($info);
            return $type ?: '' ;
        }else{
            return '';
        }
    }
720726
public static function get_mime_extensions($mimetype = null)
    {
        static $mime_types, $mime_extensions;

        // return cached data
        if (is_array($mime_types)) {
            return $mimetype ? $mime_types[$mimetype] : $mime_extensions;
        }

        // load mapping file
        $file_paths = array();

        if ($mime_types = rcube::get_instance()->config->get('mime_types')) {
            $file_paths[] = $mime_types;
        }

        // try common locations
        if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
            $file_paths[] = 'C:/xampp/apache/conf/mime.types.';
        }
        else {
            $file_paths[] = '/etc/mime.types';
            $file_paths[] = '/etc/httpd/mime.types';
            $file_paths[] = '/etc/httpd2/mime.types';
            $file_paths[] = '/etc/apache/mime.types';
            $file_paths[] = '/etc/apache2/mime.types';
            $file_paths[] = '/etc/nginx/mime.types';
            $file_paths[] = '/usr/local/etc/httpd/conf/mime.types';
            $file_paths[] = '/usr/local/etc/apache/conf/mime.types';
            $file_paths[] = '/usr/local/etc/apache24/mime.types';
        }

        foreach ($file_paths as $fp) {
            if (@is_readable($fp)) {
                $lines = file($fp, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                break;
            }
        }

        $mime_types = $mime_extensions = array();
        $regex = "/([\w\+\-\.\/]+)\s+([\w\s]+)/i";
        foreach ((array)$lines as $line) {
             // skip comments or mime types w/o any extensions
            if ($line[0] == '#' || !preg_match($regex, $line, $matches))
                continue;

            $mime = $matches[1];
            foreach (explode(' ', $matches[2]) as $ext) {
                $ext = trim($ext);
                $mime_types[$mime][] = $ext;
                $mime_extensions[$ext] = $mime;
            }
        }

        // fallback to some well-known types most important for daily emails
        if (empty($mime_types)) {
            foreach (rcube::get_instance()->config->resolve_paths('mimetypes.php') as $fpath) {
                $mime_extensions = array_merge($mime_extensions, (array) @include($fpath));
            }

            foreach ($mime_extensions as $ext => $mime) {
                $mime_types[$mime][] = $ext;
            }
        }

        // Add some known aliases that aren't included by some mime.types (#1488891)
        // the order is important here so standard extensions have higher prio
        $aliases = array(
            'image/gif'      => array('gif'),
            'image/png'      => array('png'),
            'image/x-png'    => array('png'),
            'image/jpeg'     => array('jpg', 'jpeg', 'jpe'),
            'image/jpg'      => array('jpg', 'jpeg', 'jpe'),
            'image/pjpeg'    => array('jpg', 'jpeg', 'jpe'),
            'image/tiff'     => array('tif'),
            'message/rfc822' => array('eml'),
            'text/x-mail'    => array('eml'),
        );

        foreach ($aliases as $mime => $exts) {
            $mime_types[$mime] = array_unique(array_merge((array) $mime_types[$mime], $exts));

            foreach ($exts as $ext) {
                if (!isset($mime_extensions[$ext])) {
                    $mime_extensions[$ext] = $mime;
                }
            }
        }

        return $mimetype ? $mime_types[$mimetype] : $mime_extensions;
    }
907332
protected static function getMimetypeFromLocalFilePath($filePath) {
		$mimetype = getMimeType($filePath);
		if( $mimetype !== 'text/plain' ) {
			return $mimetype;
		}
		return static::getMimetypeFromExtension(pathinfo($filePath, PATHINFO_EXTENSION));
	}
1286836
public static function getFileExt($path, $type = self::MIME_FINFO)
    {
        $mime = self::getFileMime($path, $type);
        return $mime ? self::mimeToExt($mime) : null;
    }
178744
public static function pathModeInfo(string $file_path): int
    {
        /* 如果不存在，则不可读、不可写、不可改 */
        if (!file_exists($file_path)) {
            return false;
        }

        $mark = 0;

        if (0 === stripos(PHP_OS, 'WIN')) {
            /* 测试文件 */
            $test_file = $file_path . '/cf_test.txt';

            /* 如果是目录 */
            if (is_dir($file_path)) {
                /* 检查目录是否可读 */
                $dir = @opendir($file_path);

                //如果目录打开失败，直接返回目录不可修改、不可写、不可读
                if ($dir === false) {
                    return $mark;
                }

                //目录可读 001，目录不可读 000
                if (@readdir($dir) !== false) {
                    $mark ^= 1;
                }

                @closedir($dir);

                /* 检查目录是否可写 */
                $fp = @fopen($test_file, 'wb');

                //如果目录中的文件创建失败，返回不可写。
                if ($fp === false) {
                    return $mark;
                }

                //目录可写可读 011，目录可写不可读 010
                if (@fwrite($fp, 'directory access testing.') !== false) {
                    $mark ^= 2;
                }

                @fclose($fp);
                @unlink($test_file);

                /* 检查目录是否可修改 */
                $fp = @fopen($test_file, 'ab+');
                if ($fp === false) {
                    return $mark;
                }

                if (@fwrite($fp, "modify test.\r\n") !== false) {
                    $mark ^= 4;
                }

                @fclose($fp);

                /* 检查目录下是否有执行rename()函数的权限 */
                if (@rename($test_file, $test_file) !== false) {
                    $mark ^= 8;
                }

                @unlink($test_file);

                /* 如果是文件 */
            } elseif (is_file($file_path)) {
                /* 以读方式打开 */
                $fp = @fopen($file_path, 'rb');
                if ($fp) {
                    $mark ^= 1; //可读 001
                }

                @fclose($fp);

                /* 试着修改文件 */
                $fp = @fopen($file_path, 'ab+');
                if ($fp && @fwrite($fp, '') !== false) {
                    $mark ^= 6; //可修改可写可读 111，不可修改可写可读011...
                }

                @fclose($fp);

                /* 检查目录下是否有执行rename()函数的权限 */
                if (@rename($test_file, $test_file) !== false) {
                    $mark ^= 8;
                }
            }
        } else {
            if (@is_readable($file_path)) {
                $mark ^= 1;
            }

            if (@is_writable($file_path)) {
                $mark ^= 14;
            }
        }

        return $mark;
    }
56519
public function mimeType($path)
    {
        if ($this->isDirectory($path)) {
            return static::$directoryMimetype;
        }
        return $this->mimeTypes->typeOfFile($path);
    }
1288295
public function getMimetype($path)
    {
        $metadata = $this->read($path);

        if ($metadata === false) {
            return false;
        }

        $metadata['mimetype'] = Util::guessMimeType($path, $metadata['contents']);

        return $metadata;
    }
168866
public static function get_file_extension( $file_path = '' ){
		$file_path = strtolower( $file_path );
		$file_path = parse_url( $file_path, PHP_URL_PATH );
		return pathinfo( $file_path, PATHINFO_EXTENSION );
	}