<?php
/**
 * @file
 * Provides an HTML5-compatible with Flash-fallback video player.
 *
 * This module provides functionality for loading the Video.js library and
 * formatters for CCK FileFields.
 */

/**
 * Implements hook_menu().
 */
function videojs_menu() {
  $items = array();

  $items['admin/config/media/videojs'] = array(
    'title' => 'Video.js',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('videojs_settings_form'),
    'access arguments' => array('administer site configuration'),
    'description' => 'Configure the settings for the Video.js module.',
    'file' => 'includes/videojs.admin.inc',
  );

  return $items;
}

/**
 * Implements hook_theme().
 */
function videojs_theme() {
  return array(
    'videojs' => array(
      'variables' => array('items' => NULL, 'player_id' => NULL, 'attributes' => NULL, 'entity' => NULL, 'entity_type' => NULL, 'posterimage_style' => NULL),
      'template' => 'theme/videojs',
      'file' => 'includes/videojs.theme.inc',
    ),
  );
}

/**
 * Implements hook_field_formatter_info().
 */
function videojs_field_formatter_info() {
  module_load_include('inc', 'videojs', 'includes/videojs.utility');
  $options = videojs_utility::getDefaultDisplaySettings();
  foreach (array_keys($options) as $key) {
    $options[$key] = NULL;
  }
  $options['posterimage_field'] = NULL;
  $options['posterimage_style'] = NULL;

  return array(
    'videojs' => array(
      'label' => t('Video.js'),
      'field types' => array('file', 'media', 'link_field'),
      'description' => t('Display a video file as an HTML5-compatible player with Flash-fallback.'),
      'settings'  => $options,
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function videojs_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  if ($display['type'] !== 'videojs') {
    return array();
  }
  if (empty($items)) {
    return array();
  }

  if ($field['type'] == 'link_field') {
    $links = $items;
    $items = array();
    foreach ($links as $link) {
      $title = $link['title'];

      // Allow the user to override the mime type using the title field
      if (!empty($title) && (strncmp('video/', $title, 6) === 0 || strncmp('audio/', $title, 6) === 0 || strncmp('text/', $title, 5) === 0)) {
        $mime = $title;
        $title = '';
      }
      else {
        $mime = DrupalLocalStreamWrapper::getMimeType($link['url']);

        // If the mime type is application/octet-stream, default to MP4.
        // This happens for instance for links without extensions.
        if ($mime == 'application/octet-stream') {
          $mime = 'video/mp4';
        }
      }

      $items[] = array(
        'uri' => url($link['url'], $link),
        'filemime' => $mime,
        'description' => $title,
      );
    }
  }

  $settings = $display['settings'];
  $attributes = array();
  if (!empty($settings['width']) && !empty($settings['height'])) {
    $attributes['width'] = intval($settings['width']);
    $attributes['height'] = intval($settings['height']);
  }

  if ($settings['autoplay'] !== NULL) {
    $attributes['autoplay'] = $settings['autoplay'];
  }
  if ($settings['loop'] !== NULL) {
    $attributes['loop'] = $settings['loop'];
  }
  if ($settings['hidecontrols'] !== NULL) {
    $attributes['hidecontrols'] = $settings['hidecontrols'];
  }
  if ($settings['preload'] !== NULL) {
    $attributes['preload'] = $settings['preload'];
  }

  // Add the poster image
  if (!empty($settings['posterimage_field']) && !empty($entity->{$settings['posterimage_field']})) {
    $images = field_get_items($entity_type, $entity, $settings['posterimage_field']);
    if (!empty($images)) {
      array_unshift($items, array_shift($images));
    }
  }

  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  return array(
    array(
      '#theme' => 'videojs',
      '#items' => $items,
      '#player_id' => 'videojs-' . $id . '-' . str_replace('_', '-', $instance['field_name']),
      '#attached' => videojs_add(FALSE),
      '#entity' => $entity,
      '#entity_type' => $entity_type,
      '#attributes' => $attributes,
      '#posterimage_style' => !empty($settings['posterimage_style']) ? $settings['posterimage_style'] : NULL,
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function videojs_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $image_styles = image_style_options(FALSE);
  if (isset($instance['entity_type']) && isset($instance['bundle'])) {
    $imagefields = _videojs_find_image_fields($field, $instance['entity_type'], $instance['bundle']);
  }

  $form = array(
    '#element_validate' => array('videojs_field_formatter_settings_form_validate'),
  );

  videojs_utility::getDisplaySettingsForm($form, $settings);

  if (!empty($imagefields)) {
    $form['posterimage_field'] = array(
      '#type' => 'select',
      '#title' => t('Poster image field'),
      '#default_value' => $settings['posterimage_field'],
      '#options' => $imagefields,
      '#description' => t('If an image is uploaded to the field above it will be used as the poster image.'),
      '#empty_value' => NULL,
      '#empty_option' => t('- None -'),
    );
    $form['posterimage_style'] = array(
      '#title' => t('Poster image style'),
      '#type' => 'select',
      '#default_value' => $settings['posterimage_style'],
      '#empty_option' => t('None (original image)'),
      '#description' => t('The original video thumbnail will be displayed. Otherwise, you can add a custom image style at !settings.', array('!settings' => l(t('media image styles'), 'admin/config/media/image-styles'))),
      '#options' => $image_styles,
    );
  }

  return $form;
}

/**
 * Finds image fields in the given entity and bundle.
 *
 * @param $field
 *   Field definition of the video field, used to match image fields when
 *   this field is rendered using Views.
 * @param $entity_type
 *   Entity type in which the image field must occur.
 * @param $bundle
 *   Bundle in which the image field must occur.
 * @return
 *   Array of image field names.
 */
function _videojs_find_image_fields($field, $entity_type, $bundle) {
  $imagefields = array();

  // Determine the image fields that will be selectable.
  if ($entity_type == 'ctools' && $bundle == 'ctools') {
    // This is a fake instance (see ctools_fields_fake_field_instance()).
    // This occurs for instance when this formatter is used in Views.
    // Display all image fields in bundles that contain this field.
    $otherfields = field_info_fields();
    foreach ($otherfields as $otherfield) {
      if ($otherfield['type'] == 'image' && !empty($otherfield['bundles'])) {
        // Find a label by finding an instance label
        $instancelabels = array();
        $bundles_names = array();

        foreach ($otherfield['bundles'] as $otherentitytype => $otherbundles) {
          foreach ($otherbundles as $otherbundle) {
            // Check if this image field appears in one of the video field bundles.
            if (isset($field['bundles'][$otherentitytype]) && in_array($otherbundle, $field['bundles'][$otherentitytype])) {
              $otherinstance = field_info_instance($otherentitytype, $otherfield['field_name'], $otherbundle);
              $instancelabels[$otherinstance['label']] = isset($instancelabels[$otherinstance['label']]) ? $instancelabels[$otherinstance['label']] + 1 : 1;
              $bundles_names[] = t('@entity:@bundle', array('@entity' => $otherentitytype, '@bundle' => $otherbundle));
            }
          }
        }

        if (!empty($instancelabels)) {
          arsort($instancelabels);
          $instancelabel = key($instancelabels);
          $imagefields[$otherfield['field_name']] = $instancelabel . ' — ' . t('Appears in: @bundles.', array('@bundles' => implode(', ', $bundles_names)));
        }
      }
    }
  }
  else {
    $otherinstances = field_info_instances($entity_type, $bundle);
    foreach ($otherinstances as $otherinstance) {
      $otherfield = field_info_field_by_id($otherinstance['field_id']);
      if ($otherfield['type'] == 'image') {
        $imagefields[$otherinstance['field_name']] = $otherinstance['label'];
      }
    }
  }

  return $imagefields;
}

function videojs_field_formatter_settings_form_validate($form, &$form_state) {
  $value = drupal_array_get_nested_value($form_state['values'], $form['#parents']);
  $options = videojs_utility::getDisplaySettingsFormResults($value);
  $value = array_merge($value, $options);

  // The fields need to be both entered or both empty
  if (empty($value['width']) != empty($value['height'])) {
    form_error($form[empty($value['width']) ? 'height' : 'width'], t('The width and height field need to be both set or both empty.'));
  }

  if (empty($value['width'])) {
    $value['width'] = NULL;
    $value['height'] = NULL;
  }

  drupal_array_set_nested_value($form_state['values'], $form['#parents'], $value);
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function videojs_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $image_styles = image_style_options(FALSE);

  $output = t('Player dimensions: @widthxheight', array(
    '@widthxheight' => !empty($settings['width']) && !empty($settings['height']) ? $settings['width'] . 'x' . $settings['height'] : t('default'),
  ));

  if ($settings['loop']) {
    $output .= '<br/>' . t('Loop playback');
  }
  if ($settings['autoplay']) {
    $output .= '<br/>' . t('Auto-play files on page load');
  }
  if ($settings['hidecontrols']) {
    $output .= '<br/>' . t('Hide controls');
  }
  if (!empty($settings['preload'])) {
    $output .= '<br/>' . t('Preload behavior') . ': ' . check_plain($settings['preload']);
  }

  if (!empty($settings['posterimage_field'])) {
    $imageinstance = field_info_instance($instance['entity_type'], $settings['posterimage_field'], $instance['bundle']);
    if ($imageinstance != NULL) {
      $output .= '<br/>';
      $output .= t('Poster image field') . ': ' . check_plain($imageinstance['label']);
    }
  }

  $output .= '<br/>';
  if (isset($image_styles[$settings['posterimage_style']])) {
    $output .= t('Poster image style') . ': ' . check_plain($image_styles[$settings['posterimage_style']]);
  }
  else {
    $output .= t('Poster image style') . ': ' . t('None');
  }

  return $output;
}

/**
 * Add the Video.js library to the page.
 */
function videojs_add($add = TRUE) {
  $added = &drupal_static(__FUNCTION__);

  switch (variable_get('videojs_location', 'cdn')) {
    case 'path':
      $path = variable_get('videojs_directory', 'sites/all/libraries/video-js');
      $remote = strpos($path, '://') !== FALSE || strncmp('//', $path, 2) === 0;
      break;

    case 'libraries':
      if (!module_exists('libraries')) {
        return FALSE;
      }
      $path = libraries_get_path('video-js');
      if ($path === FALSE) {
        return FALSE;
      }
      $remote = FALSE;
      break;

    case 'cdn':
    default:
      $path = '//vjs.zencdn.net/4.0';
      $remote = TRUE;
  }

  $jsdata = $path . '/video.js';
  $jsopts = array('group' => JS_LIBRARY, 'preprocess' => !$remote, 'type' => $remote ? 'external' : 'file', 'weight' => 1);
  $cssdata = $path . '/video-js.css';
  $cssopts = array('preprocess' => !$remote, 'type' => $remote ? 'external' : 'file');
  $swfdata = 'videojs.options.flash.swf = "' . file_create_url($path . '/video-js.swf') . '"';
  $swfopts = array('group' => JS_LIBRARY, 'type' => 'inline', 'weight' => 5);

  if ($add && !$added) {
    drupal_add_js($jsdata, $jsopts);
    drupal_add_css($cssdata, $cssopts);
    drupal_add_js($swfdata, $swfopts);

    $added = TRUE;
  }

  return array(
    'js' => array(
      $jsdata => $jsopts,
      $swfdata => $swfopts,
    ),
    'css' => array(
      $cssdata => $cssopts,
    ),
  );
}

/**
 * Return the version of Video.js installed.
 *
 * @param $path
 *   The path to check for a Video.js installation. This can be a local path
 *   like sites/all/libraries/video-js or a remote path like
 *   http://mycdn.com/videojs. Do not add a trailing slash.
 *   Defaults to videojs_directory when using the local file path location
 *   or whatever location the Libraries API determines.
 *
 * @return
 *   The version found or NULL if no version found.
 */
function videojs_get_version($path = NULL) {
  $version = NULL;

  if (!isset($directory)) {
    $directory = variable_get('videojs_directory', 'sites/all/libraries/video-js');
  }

  // When admins specify a protocol-relative URL, add http because file_get_contents doesn't understand it.
  if (strncmp('//', $directory, 2) === 0) {
    $directory = 'http:' . $directory;
  }

  // Don't use file_exists() because it doesn't work with URLs.
  // Now admins can also refer to directories like http://mycdn.com/videojs.
  $contents = @file_get_contents($directory . '/video.js', FALSE, NULL, 0, 400);

  if (empty($contents)) {
    return NULL;
  }

  $matches = array();
  if (preg_match('/(?:v[ ]*|Version )([\d.]{2,})/i', $contents, $matches)) {
    $version = $matches[1];
  }

  // The archive containing version 4.0.0 contains no identifyable version number.
  // @see https://github.com/videojs/video.js/issues/517
  $devversion = @file_get_contents($directory . '/video.dev.js', FALSE, NULL, 0, 10);
  if (!empty($devversion)) {
    $version = '4';
  }

  return $version;
}

/**
 * Implements hook_libraries_info().
 */
function videojs_libraries_info() {
  $libraries = array();

  $libraries['video-js'] = array(
    'name' => 'Video.js',
    'vendor url' => 'http://videojs.com',
    'download url' => 'http://videojs.com',
    'version arguments' => array(
      'file' => 'video.js',
      // @todo: The following pattern doesn't work for 4.0.0.
      'pattern' => '/(?:v[ ]*|Version )([\d.]{2,})/i',
      'lines' => 10,
      'cols' => 50,
    ),
    'versions' => array(
      '2' => array(
        'files' => array(
          'js' => array('video.js' => array('group' => JS_LIBRARY)),
          'css' => array('video-js.css'),
        ),
      ),
      '3' => array(
        'files' => array(
          'js' => array('video.min.js' => array('group' => JS_LIBRARY)),
          'css' => array('video-js.min.css'),
        ),
        'variants' => array(
          'source' => array(
            'files' => array(
              'js' => array('video.js' => array('group' => JS_LIBRARY)),
              'css' => array('video-js.css'),
            ),
            'minified' => array(
              'files' => array(
                'js' => array('video.min.js' => array('group' => JS_LIBRARY)),
                'css' => array('video-js.min.css'),
              ),
            ),
          ),
        ),
      ),
      '4' => array(
        'files' => array(
          'js' => array('video.js' => array('group' => JS_LIBRARY)),
          'css' => array('video-js.css'),
        ),
        'variants' => array(
          'source' => array(
            'files' => array(
              'js' => array('video.dev.js' => array('group' => JS_LIBRARY)),
              'css' => array('video-js.css'),
            ),
            'minified' => array(
              'files' => array(
                'js' => array('video.js' => array('group' => JS_LIBRARY)),
                'css' => array('video-js.css'),
              ),
            ),
          ),
        ),
      ),
    ),
  );

  return $libraries;
}

/**
 * Implements hook_file_mimetype_mapping_alter().
 *
 * Adds the vtt, webm and weba extensions.
 */
function videojs_file_mimetype_mapping_alter(&$mapping) {
  if (!isset($mapping['extensions']['vtt'])) {
    $mapping['mimetypes']['vtt'] = 'text/vtt';
    $mapping['extensions']['vtt'] = 'vtt';
  }
  if (!isset($mapping['extensions']['webm'])) {
    $mapping['mimetypes']['webm'] = 'video/webm';
    $mapping['extensions']['webm'] = 'webm';
  }
  if (!isset($mapping['extensions']['weba'])) {
    $mapping['mimetypes']['weba'] = 'audio/weba';
    $mapping['extensions']['weba'] = 'weba';
  }
}
