<?php

/**
 * @file
 * FileField Meta: Add Video Support to File Field.
 */

/**
 * Implementation of hook_init().
 */
function filefield_meta_init() {
  // Conditional module support.
  if (module_exists('token')) {
    module_load_include('inc', 'filefield_meta', 'filefield_meta.token');
  }
}

/**
 * Implementation of hook_theme().
 */
function filefield_meta_theme() {
  return array(
    'filefield_meta_duration' => array(
      'arguments' => array('duration' => NULL),
    ),
    'filefield_meta_samplerate' => array(
      'arguments' => array('samplerate' => NULL),
    ),
    'filefield_meta_bitrate' => array(
      'arguments' => array('bitrate' => NULL),
    ),
  );
}

/**
 * Implementation of hook_cron(). 
 */
function filefield_meta_cron() {
  $result = db_query('SELECT fm.fid FROM {filefield_meta} fm LEFT JOIN {files} f ON fm.fid=f.fid WHERE f.fid IS NULL');
  while ($file = db_fetch_object($result)) {
    db_query('DELETE FROM {filefield_meta} WHERE fid = %d', $file->fid);
  }
}

/**
 * Implementation of hook_views_api().
 */
function filefield_meta_views_api() {
  return array(
    'api' => 2.0,
    'path' => drupal_get_path('module', 'filefield_meta') . '/includes',
  );
}

/**
 * Implementation of FileField's hook_file_load().
 */
function filefield_meta_file_load(&$file) {
  $result = db_query("SELECT * FROM {filefield_meta} WHERE fid = %d", $file->fid);
  $data = db_fetch_array($result);

  // Essentially this is a lazy-loader. If no record exists, read in the file.
  if ($data) {
    $data['tags'] = isset($data['tags']) ? unserialize($data['tags']) : array();
    $file->data = isset($file->data) ? array_merge($file->data, $data) : $data;
  }
  else {
    filefield_meta_file_insert($file);
  }
}

/**
 * Implementation of FileField's hook_file_insert().
 */
function filefield_meta_file_insert(&$file) {
  if (!empty($file->fid)) {
    filefield_meta($file);
    $record = array_merge($file->data, array('fid' => $file->fid));
    drupal_write_record('filefield_meta', $record);
  }
}

/**
 * Implementation of FileField's hook_file_update().
 */
function filefield_meta_file_update(&$file) {
  if (!empty($file->fid)) {
    filefield_meta_file_delete($file);
    filefield_meta_file_insert($file);
  }
}

/**
 * Implementation of FileField's hook_file_delete().
 */
function filefield_meta_file_delete($file) {
  db_query('DELETE FROM {filefield_meta} WHERE fid = %d', $file->fid);
}

/**
 * Adds the width, height and duration to the file's data property.
 */
function filefield_meta(&$file) {
  $file->data = !empty($file->data) ? $file->data : array();

  // Skip any attempts at adding information if the file is not actually
  // located on this server.
  if (!file_exists($file->filepath)) {
    return;
  }

  $info = getid3_analyze($file->filepath);
  $file->data['width'] = $file->data['height'] = $file->data['duration'] = 0;
  if (isset($info['video']['resolution_x'])) {
    $file->data['width'] = $info['video']['resolution_x'];
    $file->data['height'] = $info['video']['resolution_y'];
  }
  elseif (isset($info['video']['streams'])) {
    foreach ($info['video']['streams'] as $stream) {
      $file->data['width'] = max($file->data['width'], $stream['resolution_x']);
      $file->data['height'] = max($file->data['height'], $stream['resolution_y']);
    }
  }

  if (isset($info['playtime_seconds']))  {
    $file->data['duration'] = $info['playtime_seconds'];
  }

  // Initialize fields. 
  $file->data['audio_format'] = $file->data['audio_channel_mode'] = $file->data['audio_bitrate_mode'] = '';
  $file->data['audio_sample_rate'] = $file->data['audio_bitrate'] = 0;
 
  if (isset($info['audio']))  { 
    $file->data['audio_format'] = $info['audio']['dataformat']; //e.g. mp3
    $file->data['audio_sample_rate'] = $info['audio']['sample_rate']; //e.g. 44100
    $file->data['audio_channel_mode'] = $info['audio']['channelmode']; // e.g. mono
    $file->data['audio_bitrate'] = isset($info['audio']['bitrate']) ? $info['audio']['bitrate'] : NULL; //e.g. 64000
    $file->data['audio_bitrate_mode'] = isset($info['audio']['bitrate_mode']) ? $info['audio']['bitrate_mode'] : NULL; //e.g. cbr
  }

  // Add in arbitrary ID3 tags.
  if (isset($info['tags_html'])) {
    // We use tags_html instead of tags because it is the most reliable data
    // source for pulling in non-UTF-8 characters according to getID3 docs.
    foreach ($info['tags_html'] as $type => $values) {
      // Typically $type may be IDv2 (for MP3s) or quicktime (for AAC).
      foreach ($values as $key => $value) {
        $value = isset($value[0]) ? (string) $value[0] : (string) $value;
        if (!empty($value) && $key != 'coverart' && $key != 'music_cd_identifier') {
          $file->data['tags'][$key] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
        }
      }
    }
  }
}

/**
 * Utility function that simply returns the current list of all known ID3 tags.
 *
 * If new or different ID3 tags are desired, these may be overridden by adding
 * the following to your site's settings.php file.
 *
 * @code
 * $conf['filefield_meta_tags'] = array(
 *   'title' => t('Title'),
 *   'artist' => t('Artist'),
 *   'composer' => t('Composer'),
 *   // etc...
 * );
 * @endcode
 */
function filefield_meta_tags() {
  $defaults = array(
    'title' => t('Title'),
    'artist' => t('Artist'),
    'album' => t('Album'),
    'year' => t('Year'),
    'genre' => t('Genre'),
  );
  return variable_get('filefield_meta_tags', $defaults);
}

/**
 * Convert the float duration into a pretty string.
 *
 * @param $duration
 */
function theme_filefield_meta_duration($duration) {
  $seconds = round((($duration / 60) - floor($duration / 60)) * 60);
  $minutes = floor($duration / 60);
  if ($seconds >= 60) {
    $seconds -= 60;
    $minutes++;
  }
  return intval($minutes) . ':' . str_pad($seconds, 2, 0, STR_PAD_LEFT);
}


/**
 * Formats audio sample rate.
 */
function theme_filefield_meta_samplerate($samplerate) {
  return t('@sampleratekHz', array('@samplerate' => (int) ($samplerate/1000)));
}
 
/**
 * Formats audio bit rate.
 */
function theme_filefield_meta_bitrate($bitrate) {
  return t('@bitrateKbps', array('@bitrate' => (int) ($bitrate/1000)));
}
