You are here

function mimedetect_mime in MimeDetect 7

Same name and namespace in other branches
  1. 5 mimedetect.module \mimedetect_mime()
  2. 6 mimedetect.module \mimedetect_mime()

Detect File Mime Type.

Parameters

object $file: A standard Drupal file object. The uri property is used to locate the file and if the mime detection fails, the mimetype property is returned.

Return value

string Containing the file's MIME type.

1 call to mimedetect_mime()
mimedetect_fileupload_file_validate in mimedetect_fileupload/mimedetect_fileupload.module
Implements hook_file_validate().

File

./mimedetect.module, line 37
Provide server side mime type detection.

Code

function mimedetect_mime($file) {
  $file = (object) $file;
  $mime = FALSE;

  // Try to use the fileinfo extension first.
  if (variable_get('mimedetect_enable_file_info', FALSE) && extension_loaded('fileinfo')) {
    $magic_file = variable_get('mimedetect_magic', '');
    static $finfo = FALSE;
    if ($finfo || ($finfo = @finfo_open(FILEINFO_MIME, $magic_file))) {
      $mime = finfo_file($finfo, drupal_realpath($file->uri));
    }
  }

  // Try the 'file' binary.
  if ((!$mime || $mime == 'application/octet-stream') && variable_get('mimedetect_enable_file_binary', FALSE) && ($filebin = variable_get('mimedetect_file_binary', '/usr/bin/file')) && basename($filebin) == 'file' && is_executable($filebin)) {

    // On OSX the -i switch is -I, so if we use the long flags everyone is
    // happy. I checked back to version 3.41 and it still supports the long
    // names but if you run into problems you can use " -bi ".
    $command = $filebin . ' --brief --mime' . (!empty($magic_file) ? ' --magic-file=' . escapeshellarg($magic_file) : '') . ' ' . escapeshellarg(drupal_realpath($file->uri));
    $mime = trim(exec($command));
  }

  // With text we often get charset like 'text/plain; charset=us-ascii'.
  $mime = explode(';', $mime);
  $mime = trim($mime[0]);

  // If it was unable to determine the file MIME type, fallback to the core
  // MIME mapping based on file name extension.
  if (!$mime || $mime == 'application/octet-stream') {
    $mime = file_get_mimetype($file->filename);
  }
  return $mime;
}