You are here

function mimedetect_mime in MimeDetect 6

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

Detect File Mime Type.

Parameters

$file A standard Drupal file object. The filepath 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.

File

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

Code

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

  // An additional array of mimetypes not included in file_get_mimetype().
  static $additional_mimes = array(
    // Audio types
    'rmi' => 'audio/midi',
    'aidff' => 'audio/x-aiff',
    // Image types
    'cod' => 'image/cis-cod',
    'jfif' => 'image/pipeg',
    'cmx' => 'image/x-cmx',
    // Video types
    'mpa' => 'video/mpeg',
    'mpv2' => 'video/mpeg',
    'asr' => 'video/x-ms-asf',
  );
  $mime = FALSE;
  $magic_file = variable_get('mimedetect_magic', drupal_get_path('module', 'mimedetect') . '/magic');

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

  // Try the 'file' binary.
  if (!$mime && variable_get('mimedetect_enable_file_binary', FALSE) && ($filebin = variable_get('mimedetect_file_binary', '/usr/bin/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 --magic-file=' . escapeshellarg($magic_file) . ' ' . escapeshellarg($file->filepath);
    $mime = trim(exec($command));
  }

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

  // ASF derived media formats are hard to detect with magic. They're typically
  // all reported as video/x-ms-asf or application/octet-stream. These aren't
  // really informative about the media type, so we attempt to figure it out by
  // extension. I expect OGG to present similar difficulties in determining how
  // it should be played.
  if (!$mime || $mime == 'application/octet-stream') {

    // Try core's mime mapping first...
    $mime = file_get_mimetype($file->filename);

    // ...and if that doesn't turn up anything try our additional mappings.
    if ($mime == 'application/octet-stream') {
      $mime = file_get_mimetype($file->filename, $additional_mimes);
    }
  }
  return $mime;
}