You are here

brightcove_media.module in Brightcove Video Connect 7.2

File

brightcove_media/brightcove_media.module
View source
<?php

/**
 * Implements hook_menu().
 */
function brightcove_media_menu() {
  $items = array();
  $items['brightcove/media/list'] = array(
    'title' => '',
    'page callback' => 'brightcove_media_list',
    'access arguments' => array(
      'browse videos',
    ),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implements hook_stream_wrappers().
 */
function brightcove_media_stream_wrappers() {
  return array(
    'brightcove' => array(
      'name' => t('Brightcove videos'),
      'class' => 'MediaBrightcoveStreamWrapper',
      'description' => t('Videos provided by Brightcove.'),
      'type' => STREAM_WRAPPERS_READ_VISIBLE,
    ),
  );
}

/**
 * Implements hook_media_internet_providers().
 */
function brightcove_media_internet_providers() {
  return array(
    'MediaInternetBrightcoveHandler' => array(
      'title' => 'brightcove',
      'image' => 'http://img.brightcove.com/logo-corporate-new.png',
    ),
  );
}

/**
 * Implements hook_media_parse().
 */
function brightcove_media_media_parse($embed_code) {
  $handler = new MediaInternetBrightcoveHandler($embed_code);
  return $handler
    ->parse($embed_code);
}

/**
 * Implements hook_file_formatter_info().
 */
function brightcove_media_file_formatter_info() {
  $formatters = array();
  $formatters['brightcove_media_video'] = array(
    'label' => t('Brightcove Video'),
    'file types' => array(
      'video',
    ),
    'default settings' => array(),
    'view callback' => 'brightcove_media_file_formatter_video_view',
    'settings callback' => 'brightcove_media_file_formatter_video_settings',
  );
  $formatters['brightcove_media_image'] = array(
    'label' => t('Brightcove Preview Image'),
    'file types' => array(
      'video',
    ),
    'default settings' => array(
      'image_style' => '',
    ),
    'view callback' => 'brightcove_media_file_formatter_image_view',
    'settings callback' => 'brightcove_media_file_formatter_image_settings',
  );
  return $formatters;
}
function brightcove_media_file_formatter_video_view($file, $display, $langcode) {
  $scheme = file_uri_scheme($file->uri);
  if ($scheme == 'brightcove' && empty($file->override['wysiwyg'])) {
    $element = array(
      '#theme' => 'brightcove_field_embed',
      '#video_id' => parse_url($file->uri, PHP_URL_HOST),
      '#attached' => array(
        'js' => array(
          'http://admin.brightcove.com/js/BrightcoveExperiences.js' => array(
            'type' => 'external',
          ),
        ),
      ),
    );

    // add player override
    if (isset($display['settings']['player']) && $display['settings']['player']) {
      $element['#player'] = $display['settings']['player'];
      $element['#player_key'] = $display['settings']['player_key'];
    }
    foreach (array(
      'width',
      'height',
    ) as $setting) {
      if (isset($display['settings'][$setting]) && $display['settings'][$setting]) {
        $element['#params'][$setting] = $display['settings'][$setting];
      }
    }
    return $element;
  }
  return NULL;
}
function brightcove_media_file_formatter_image_view($file, $display, $langcode) {
  $scheme = file_uri_scheme($file->uri);
  if ($scheme == 'brightcove') {
    $element = array(
      '#theme' => 'brightcove_field_formatter_entity_image_thumbnailURL',
      '#element' => array(
        'video_id' => parse_url($file->uri, PHP_URL_HOST),
      ),
      '#display' => array(
        'type' => 'entity_image_thumbnailURL',
      ),
    );
    return $element;
  }
  return NULL;
}
function brightcove_media_file_formatter_video_settings($form, $form_state, $settings) {
  $element = array();
  $element['player'] = array(
    '#title' => t('Player Id'),
    '#type' => 'textfield',
    '#default_value' => isset($settings['player']) ? $settings['player'] : '',
  );
  $element['player_key'] = array(
    '#title' => t('Player Key'),
    '#type' => 'textfield',
    '#default_value' => isset($settings['player_key']) ? $settings['player_key'] : '',
  );
  $element['width'] = array(
    '#title' => t('Player Width'),
    '#type' => 'textfield',
    '#default_value' => isset($settings['width']) ? $settings['width'] : '',
  );
  $element['height'] = array(
    '#title' => t('Player Height'),
    '#type' => 'textfield',
    '#default_value' => isset($settings['height']) ? $settings['height'] : '',
  );
  return $element;
}
function brightcove_media_file_formatter_image_settings($form, $form_state, $settings) {
  $element = array();
  $element['image_style'] = array(
    '#title' => t('Image style'),
    '#type' => 'select',
    '#options' => image_style_options(FALSE),
    '#default_value' => isset($settings['image_style']) ? $settings['image_style'] : '',
    '#empty_option' => t('None (original image)'),
  );
  return $element;
}

/**
 * Implements hook_file_formatter_default_displays().
 */
function brightcove_media_file_default_displays() {
  $default_displays = array();
  $video_display_settings = array(
    'media_large' => array(),
    'media_original' => array(),
    'media_gallery_detail' => array(),
    'media_gallery_lightbox' => array(),
  );
  foreach ($video_display_settings as $view_mode => $settings) {
    $display_name = "video__{$view_mode}__brightcove_media_video";
    $default_displays[$display_name] = (object) array(
      'api_version' => 1,
      'name' => $display_name,
      'status' => 1,
      'weight' => 1,
      'settings' => $settings,
    );
  }
  $image_display_styles = array(
    'media_preview' => '',
    'media_large' => '',
    'media_original' => '',
    'media_gallery_thumbnail' => '',
    'media_gallery_block_thumbnail' => '',
    'media_gallery_collection_thumbnail' => '',
  );
  foreach ($image_display_styles as $view_mode => $image_style) {
    $display_name = "video__{$view_mode}__brightcove_media_image";
    $default_displays[$display_name] = (object) array(
      'api_version' => 1,
      'name' => $display_name,
      'status' => 1,
      'weight' => 2,
      'settings' => array(
        'image_style' => $image_style,
      ),
    );
  }
  return $default_displays;
}

/**
 * Implements hook_media_browser_plugin_info().
 */
function brightcove_media_media_browser_plugin_info() {
  return array(
    'brightcove' => array(
      '#weight' => 0,
    ),
  );
}

/**
 * Upload form for brightcove media.
 */
function brightcove_media_upload_form($form, &$form_state) {
  $form['uploadform'] = array(
    '#type' => 'fieldset',
    '#title' => t('Upload video'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#description' => t('It takes several minutes (depending on processing time in Brightcove cloud), until video is available after upload. Clicking \'Upload and attach\' uploads video to Brightcove then closes the dialog and attaches the video.'),
  );
  $form['uploadform']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#description' => t('Video name or title.'),
    '#required' => TRUE,
    '#default_value' => !empty($form_state['values']['title']) ? $form_state['values']['title'] : '',
  );
  $form['uploadform']['file_upload'] = array(
    '#type' => 'file',
    '#title' => t('Video file'),
    '#size' => 40,
    '#required' => FALSE,
    '#description' => t('Allowed file types: ') . '<strong>3g2 3gp asf avi dv flv f4v m4v mov mp4 mpeg mpg mts m2ts qt wmv</strong>',
  );
  $form['uploadform']['short'] = array(
    '#type' => 'textarea',
    '#rows' => 3,
    '#required' => TRUE,
    '#title' => t('Short description'),
    '#description' => t('Video short description.'),
    '#default_value' => !empty($form_state['values']['short']) ? $form_state['values']['short'] : '',
  );
  $form['uploadform']['advanced'] = array(
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#title' => t('Advanced attributes'),
  );
  $form['uploadform']['advanced']['tags'] = array(
    '#type' => 'textfield',
    '#title' => t('Tags'),
    '#description' => t('Associated tags, separated by comma.'),
    '#default_value' => !empty($form_state['values']['tags']) ? $form_state['values']['tags'] : '',
  );
  $form['uploadform']['advanced']['long'] = array(
    '#type' => 'textarea',
    '#rows' => 4,
    '#title' => t('Long description'),
    '#description' => t('Video long description.'),
    '#default_value' => !empty($form_state['values']['long']) ? $form_state['values']['long'] : '',
  );
  $form['uploadform']['advanced']['linktext'] = array(
    '#type' => 'textfield',
    '#title' => t('Related link text'),
    '#description' => t('Related link description or text.'),
    '#default_value' => !empty($form_state['values']['linktext']) ? $form_state['values']['linktext'] : '',
  );
  $form['uploadform']['advanced']['linkurl'] = array(
    '#type' => 'textfield',
    '#title' => t('Related link url'),
    '#description' => t('Related link URL.'),
    '#default_value' => !empty($form_state['values']['linkurl']) ? $form_state['values']['linkurl'] : '',
  );
  $form['uploadform']['upload'] = array(
    '#type' => 'button',
    '#name' => 'upload',
    '#value' => t('Upload and attach'),
    '#ajax' => array(
      'callback' => 'ajax_brightcove_media_upload_callback',
      'wrapper' => 'bc-upload-form',
    ),
  );
  $form['#prefix'] = '<div id="bc-upload-form">';
  $form['#suffix'] = '</div>';
  return $form;
}

/**
 * Filter form for brightcove media video browser.
 */
function brightcove_media_browser_filter_form($form, &$form_state) {
  $form['searchform'] = array(
    '#type' => 'fieldset',
    '#title' => t('Filter videos'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $keywords = '';
  $form['searchform']['keywords'] = array(
    '#type' => 'textfield',
    '#title' => t('Keywords'),
    '#size' => 25,
    '#default_value' => $keywords,
    '#description' => t('Comma separated keywords to search for. (do not add space after comma)'),
  );
  $form['searchform']['search'] = array(
    '#type' => 'radios',
    '#title' => t('Search in'),
    '#options' => array(
      'name' => t('Names and descriptions'),
      'tags' => t('Tags: at least one of these'),
      'and_tags' => t('Tags: all of these'),
    ),
    '#default_value' => 'name',
    '#attributes' => array(
      'class' => array(
        'search-radio',
      ),
    ),
    '#description' => t('"Names and descriptions" searches in Video name, short and long descriptions. Tags searches in Video associated tags.'),
  );
  $form['searchform']['filter'] = array(
    '#type' => 'button',
    '#name' => 'filter',
    '#value' => t('Filter'),
  );
  $form['searchform']['reset'] = array(
    '#type' => 'button',
    '#name' => 'reset',
    '#value' => t('Reset'),
  );
  $form['#prefix'] = '<div id="bc-filter-form">';
  $form['#suffix'] = '</div>';
  return $form;
}

/**
 * Implements hook_media_browser_plugin_view().
 */
function brightcove_media_media_browser_plugin_view($plugin_name, $params) {
  switch ($plugin_name) {
    case 'brightcove':
      $upload_form = drupal_get_form('brightcove_media_upload_form');
      $upload_form = drupal_render($upload_form);
      $filter_form = drupal_get_form('brightcove_media_browser_filter_form');
      $filter_form = drupal_render($filter_form);
      $media_path = drupal_get_path('module', 'media');
      $bcpath = drupal_get_path('module', 'brightcove_media');
      return array(
        '#title' => t('Brightcove videos'),
        '#settings' => array(
          'viewMode' => 'thumbnails',
          'getMediaUrl' => url('brightcove/media/list'),
          'multiselect' => isset($params['multiselect']) && $params['multiselect'] != 'false',
          'types' => isset($params['types']) ? $params['types'] : array(),
        ),
        '#attached' => array(
          'js' => array(
            $media_path . '/js/plugins/media.library.js',
            $bcpath . '/brightcove_media.library.js',
          ),
          'css' => array(
            //@todo: should move this.
            $media_path . '/js/plugins/media.library.css',
            $bcpath . '/brightcove_media.library.css',
          ),
        ),
        '#markup' => '<div id="container"><div id="scrollbox">' . $upload_form . $filter_form . '<ul id="media-browser-library-list" class="media-list-thumbnails"></ul><div id="status"></div></div></div>',
      );
      break;
  }
  return NULL;
}
function brightcove_media_list() {
  global $user;
  module_load_include('browser.inc', 'media', 'includes/media');
  $default_items_per_page = 20;
  $params = drupal_get_query_parameters();
  $limit = isset($params['limit']) ? $params['limit'] : $default_items_per_page;
  $start = isset($params['start']) ? ceil($params['start'] / $limit) : 0;
  $media = array();
  $bc = brightcove_initialize();
  $bc_find_params = array();
  if (isset($params['filter'])) {
    switch ($params['filter']['search']) {
      case 'tags':
        $method = 'find_videos_by_tags';
        $bc_find_params = array(
          'or_tags' => $params['filter']['keywords'],
        );
        break;
      case 'and_tags':
        $method = 'find_videos_by_tags';
        $bc_find_params = array(
          'and_tags' => $params['filter']['keywords'],
        );
        break;
      case 'name':
      default:
        $method = 'find_videos_by_text';
        $bc_find_params = array(
          'text' => join(' ', explode(',', $params['filter']['keywords'])),
        );
        break;
    }
  }
  else {
    $method = 'find_all_videos';
  }
  $result = NULL;
  try {
    $bc_find_params['page_size'] = $limit;
    $bc_find_params['page_number'] = $start;
    $result = $bc
      ->find($method, $bc_find_params);
    if (count($result)) {
      foreach ($result as $video) {
        $file = (object) array(
          'fid' => "v{$video->id}",
          'uid' => $user->uid,
          'filename' => check_plain($video->name),
          'uri' => "brightcove://{$video->id}",
          'filemime' => 'media/brightcove',
          'filesize' => 0,
          'status' => 1,
          'type' => 'video',
        );
        media_browser_build_media_item($file);
        $media[] = $file;
      }
    }
  } catch (Exception $e) {
    watchdog('brightcove', 'Retrieving media list failed.', array(), WATCHDOG_ERROR);
  }
  drupal_json_output(array(
    'media' => $media,
  ));
  exit;
}

/**
 * Implements hook_ctools_plugin_api().
 */
function brightcove_media_ctools_plugin_api($owner, $api) {
  static $api_versions = array(
    'file_entity' => array(
      'file_default_displays' => 1,
    ),
  );
  return isset($api_versions[$owner][$api]) ? array(
    'version' => $api_versions[$owner][$api],
  ) : NULL;
}

/**
 * Implements hook_element_info_alter().
 */
function brightcove_media_element_info_alter(&$type) {
  if (isset($type['media']['#process'])) {
    array_unshift($type['media']['#process'], 'brightcove_media_media_element_process');
  }
}
function brightcove_media_media_element_process(&$element, &$form_state) {
  global $user;
  if (isset($element['#value']['fid']) && strpos($element['#value']['fid'], 'v') === 0) {
    $video_id = substr($element['#value']['fid'], 1);
    $candidates = file_load_multiple(array(), array(
      'uri' => "brightcove://{$video_id}",
    ));
    if (count($candidates)) {
      $element['#value']['fid'] = array_shift($candidates)->fid;
    }
    else {
      $handler = new MediaInternetBrightcoveHandler($video_id);
      if (!isset($_SESSION['brightcove']["video_just_uploaded_{$user->uid}"])) {
        $bc = brightcove_initialize();
        try {
          $result = $bc
            ->find('find_video_by_id', $video_id);
          if (count($result)) {
            $file = (object) $result;
            $_SESSION['brightcove']["selected_video_{$user->uid}"] = $file;
          }
        } catch (Exception $e) {
          watchdog('brightcove', 'Retrieving media list failed.', array(), WATCHDOG_ERROR);
        }
      }
      $element['#value']['fid'] = $handler
        ->save()->fid;
    }
    form_set_value($element, $element['#value'], $form_state);
  }
  return $element;
}

/**
 * Implements hook_node_presave(). (needed for media gallery)
 */
function brightcove_media_node_presave($node) {
  global $user;
  if (isset($node->media_gallery_media['und'])) {
    foreach ($node->media_gallery_media['und'] as &$file) {
      if (isset($file['fid']) && strpos($file['fid'], 'v') === 0) {
        $video_id = substr($file['fid'], 1);
        $candidates = file_load_multiple(array(), array(
          'uri' => "brightcove://{$video_id}",
        ));
        if (count($candidates)) {
          $file['fid'] = array_shift($candidates)->fid;
        }
        else {
          $handler = new MediaInternetBrightcoveHandler($video_id);
          if (!isset($_SESSION['brightcove']["video_just_uploaded_{$user->uid}"])) {
            $bc = brightcove_initialize();
            try {
              $result = $bc
                ->find('find_video_by_id', $video_id);
              if (count($result)) {
                $_SESSION['brightcove']["selected_video_{$user->uid}"] = (object) $result;
              }
            } catch (Exception $e) {
              watchdog('brightcove', 'Retrieving media list failed.', array(), WATCHDOG_ERROR);
            }
          }
          $file['fid'] = $handler
            ->save()->fid;
        }
      }
    }
  }
}

/**
 * Ajax callback for upload form
 *
 * @param $form
 * @param $form_state
 * @return Validated form with messages
 */
function ajax_brightcove_media_upload_callback($form, $form_state) {
  global $user;

  // Make sure it is not set, might be needed if a user changes mind after upload and wants to upload another.
  unset($_SESSION['brightcove']["video_just_uploaded_{$user->uid}"]);
  $limits['extensions'] = '3g2 3gp asf avi dv flv f4v m4v mov mp4 mpeg mpg mts m2ts qt wmv';
  $validators = array(
    'file_validate_extensions' => array(
      $limits['extensions'],
    ),
  );

  // Save new file uploads.
  if ($file = file_save_upload('file_upload', $validators, drupal_realpath(file_default_scheme() . ':/'))) {
    if ($file->filesize <= 0) {

      // Some uploaded files had zero size, that's an error.
      drupal_set_message(t('Uploaded file not found. Are you sure that you uploaded an existing file?'), 'error');
      return $form;
    }
    if (form_get_errors()) {
      return $form;
    }

    // Do something with $file here.
    $meta = array(
      'name' => $form_state['values']['title'],
      'shortDescription' => $form_state['values']['short'],
      'longDescription' => $form_state['values']['long'],
      'linkText' => $form_state['values']['linktext'],
      'linkURL' => $form_state['values']['linkurl'],
      'referenceId' => brightcove_generate_reference(),
    );
    if (!empty($form_state['values']['tags'])) {
      $meta['tags'] = explode(',', $form_state['values']['tags']);
    }
    $id = brightcove_upload_video(drupal_realpath($file->uri), $meta);
    if (!isset($id)) {
      return $form;
    }

    // Construct Video object with ID - we need to cache it and save to session.
    // Brightcove Media API doesn't clear it's cache when a new video is
    // uploaded, therefore the node save would fail.
    $video = new StdClass();
    $video->id = $id;
    $video->name = $form_state['values']['title'];
    brightcove_video_cache_set($id, $video);

    // invalidating brightcove video load cache
    cache_set("bc:video:{$id}", FALSE, 'cache');
    $file_obj = (object) array(
      'fid' => "v{$video->id}",
      'uid' => $user->uid,
      'filename' => check_plain($video->name),
      'uri' => "brightcove://{$video->id}",
      'filemime' => 'media/brightcove',
      'filesize' => 0,
      'status' => 1,
      'type' => 'video',
    );
    media_browser_build_media_item($file_obj);
    $_SESSION['brightcove']["video_just_uploaded_{$user->uid}"] = $file_obj;
    $commands = array();
    $commands[] = ajax_command_brightcove_media_upload($file_obj);
    return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );
  }
  else {
    drupal_set_message(t('Only Video files are allowed here.'), 'error');
    return $form;
  }
}

/**
 * @param $data
 * @param null $settings
 * @return array
 */
function ajax_command_brightcove_media_upload($data, $settings = NULL) {
  return array(
    'command' => 'brightcove_media_upload',
    'data' => $data,
    'settings' => $settings,
  );
}
function brightcove_media_file_uri_to_object($uri, $use_existing = FALSE) {
  if ($use_existing) {
    $query = db_select('file_managed', 'f')
      ->fields('f', array(
      'fid',
    ))
      ->condition('uri', $uri)
      ->execute()
      ->fetchCol();
    if (!empty($query)) {
      $file = file_load(array_shift($query));
    }
  }
  if (!isset($file)) {
    global $user;
    $uri = file_stream_wrapper_uri_normalize($uri);
    $wrapper = file_stream_wrapper_get_instance_by_uri($uri);
    $file = new StdClass();

    // This is gagged because some uris will not support it.
    $file->filesize = @filesize($uri);
    $file->timestamp = REQUEST_TIME;
    $file->status = FILE_STATUS_PERMANENT;
    $file->is_new = TRUE;
    $file->uri = $uri;
    $file->filemime = file_get_mimetype($uri);
    $file->uid = $user->uid;
    if (isset($_SESSION['brightcove']["video_just_uploaded_{$user->uid}"])) {
      $uploaded_video = $_SESSION['brightcove']["video_just_uploaded_{$user->uid}"];
      $file->filename = $uploaded_video->filename;
      unset($_SESSION['brightcove']["video_just_uploaded_{$user->uid}"]);
    }
    else {
      if (isset($_SESSION['brightcove']["selected_video_{$user->uid}"])) {
        $selected_video = $_SESSION['brightcove']["selected_video_{$user->uid}"];
        $file->filename = $selected_video->name;
        unset($_SESSION['brightcove']["selected_video_{$user->uid}"]);
      }
      else {
        $file->filename = basename($uri);
      }
    }
  }
  return $file;
}