You are here

video_youtube.module in Video 5

Enable Youtube support for video module.

@author Fabio Varesano <fvaresano at yahoo dot it>

File

types/video_youtube/video_youtube.module
View source
<?php

// ex: set tabstop=2 expandtab shiftwidth=2 softtabstop=2:

/**
 * @file
 * Enable Youtube support for video module.
 *
 * @author Fabio Varesano <fvaresano at yahoo dot it>
 */

// let's include apiclient logic
include_once drupal_get_path('module', 'video') . '/includes/apiclient.inc';

/**
 * Implementation of hook_menu
*/
function video_youtube_menu($maycache) {
  $items = array();
  if ($maycache) {
    $items[] = array(
      'path' => 'node/add/video/youtube',
      'title' => t('Youtube'),
      'access' => user_access('create video'),
    );
    $items[] = array(
      'path' => 'admin/settings/video/youtube',
      'title' => t('Youtube'),
      'description' => t('Configure various settings of the video Youtube plugin.'),
      'access' => user_access('administer site configuration'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array(
        'video_youtube_admin_settings',
      ),
      'type' => MENU_NORMAL_ITEM,
    );
  }
  return $items;
}

/**
 * Setting form for video_upload
*/
function video_youtube_admin_settings() {
  $form = array();
  $form['video_youtube_auto_thumbnail'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable auto thumbnailing for youtube videos'),
    '#default_value' => variable_get('video_youtube_auto_thumbnail', false),
  );
  $form['video_youtube_related'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable related videos'),
    '#default_value' => variable_get('video_youtube_related', false),
    '#description' => t('If you enable related videos the Youtube player will display a list of related videos once the video completes playing.'),
  );
  $form['video_youtube_validation'] = array(
    '#type' => 'checkbox',
    '#title' => t('Enable validation'),
    '#default_value' => variable_get('video_youtube_validation', false),
    '#description' => t('If you enable validation, on each youtube video submission, you web server will contact Youtube to check that the inserted video is available and embeddable.'),
  );
  $form['video_youtube_api_key'] = array(
    '#type' => 'textfield',
    '#title' => t('Developer Key'),
    '#description' => t('Insert here the developer Key. You can get one from <a href="http://www.youtube.com/my_profile_dev">Youtube Development pages</a>.'),
    '#default_value' => variable_get('video_youtube_api_key', ''),
  );

  // jlampton added: new youtube optional client id
  $form['video_youtube_client_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Client ID'),
    '#description' => t('Insert here the client ID. You can get one from <a href="http://www.youtube.com/my_profile_dev">Youtube Development pages</a>.'),
    '#default_value' => variable_get('video_youtube_client_id', ''),
  );
  return system_settings_form($form);
}

/**
 * Validate settings
*/
function video_youtube_admin_settings_validate($form_id, &$form_values, &$form) {
  if ($form_values['video_youtube_auto_thumbnail']) {

    // autothumbnailing is active
    // let's check we have a valid dev key
    if ($form_values['video_youtube_api_key'] == '') {
      form_set_error('video_youtube_api_key', t('You have to insert a valid Youtube Developer Key for auto thumbnailing to work'));
    }
  }
}

/**
 * Implementation of hook_v_help
*/
function video_youtube_v_help() {
  $help = array();
  $help['youtube']['data'] = '<b><a href="http://www.youtube.com">' . t('YouTube.com support') . '</a></b>';
  $help['youtube']['children'] = array(
    t('You can host videos on youtube.com and put them on your site. To do this, after you upload the video on youtube.com enter the video URL.'),
  );
  return $help;
}

/**
 * Implementation of hook_v_info()
*/
function video_youtube_v_info() {
  $info['youtube'] = array(
    '#name' => 'Youtube Video',
    '#description' => t('Post a video available on !link to this website.', array(
      '!link' => l(t('Youtube'), 'http://www.youtube.com'),
      NULL,
      NULL,
      NULL,
      TRUE,
    )),
    '#autothumbable' => variable_get('video_youtube_auto_thumbnail', false),
    '#autoresolution' => true,
    '#autoplaytime' => true,
  );
  return $info;
}

/**
 * Implementation of hook_v_form()
*/
function video_youtube_v_form(&$node, &$form) {
  $form['video']['vidfile'] = array(
    '#type' => 'textfield',
    '#title' => t('Youtube Video URL'),
    '#default_value' => $node->vidfile,
    '#maxlength' => 700,
    '#required' => TRUE,
    '#weight' => -20,
    '#description' => t('Insert the URL to the youtube video. ') . l(t('More information.'), 'video/help', NULL, NULL, 'videofile'),
  );
  return $form;
}

/**
 * implementation of hook_v_validate
*/
function video_youtube_v_validate($node) {
  if (!preg_match("/^http:\\/\\/([a-z]{2,3}\\.)?youtube\\.com\\/watch\\?v=/", $node->vidfile)) {
    form_set_error('vidfile', t('The Youtube Video URL field must be similar to <em>http://youtube.com/watch?v=IICWFx7sKmw</em>, <em>http://www.youtube.com/watch?v=IICWFx7sKmw</em> or <em>http://it.youtube.com/watch?v=IICWFx7sKmw</em>'));
  }
  else {
    if (variable_get('video_youtube_validation', false)) {

      // we have a good URL. Let's check that the video is available on Youtube and that it is embeddable.
      // the approach used here is to return errors only if Youtube explicitely says "an error has occurred"
      $id = _video_youtube_get_id($node->vidfile);

      // jlampton changed the youtube validation url
      $response = _video_apiclient_youtube_request('gdata.youtube.com/feeds/api/videos', array(
        'video_id' => $id,
      ));
      if (isset($response['ERROR'])) {
        form_set_error('vidfile', t('The Youtube Video URL validation has failed for some reason. Please check the URL and try again.<br />If the error persists please contact %site_name administrators.', array(
          '%site_name' => variable_get('site_name', 'Drupal'),
        )));
        if (isset($response['ERROR']['DESCRIPTION'][0])) {
          drupal_set_message(t('The Youtube validation service reported the following error: %error', array(
            '%error' => $response['ERROR']['DESCRIPTION'][0],
          )), 'error');
        }
      }
      else {
        if (isset($response['VIDEO_DETAILS']['EMBED_STATUS'][0]) && $response['VIDEO_DETAILS']['EMBED_STATUS'][0] != 'ok') {

          // embedding has been disabled. we let the video pass but we warn the user
          drupal_set_message(t('The video authors have disabled embedding on Youtube. This means that this video will only be playable directly on Youtube.'));
        }
        else {

          // if youtube did not explicetely said "an error has occurred" we accept the video
        }
      }
    }
  }
}

/**
 * Implementation of hook_v_play
*/
function video_youtube_v_play($node) {
  return theme('video_youtube_play', $node);
}

/** AUTOTHUMBNAILING LOGIC */
define('VIDEO_YOUTUBE_API_INFO', 'http://youtube.com/dev');
define('VIDEO_YOUTUBE_API_APPLICATION_URL', 'http://www.youtube.com/my_profile_dev');
define('VIDEO_YOUTUBE_REST_ENDPOINT', 'http://www.youtube.com/api2_rest');

/**
* this is a wrapper for _video_apiclient_request_xml that includes youtube's api key
*/
function _video_apiclient_youtube_request($method, $args = array(), $cacheable = TRUE) {
  $args['dev_id'] = trim(variable_get('video_youtube_api_key', ''));
  $args['method'] = $method;
  return _video_apiclient_request_xml('youtube', VIDEO_YOUTUBE_REST_ENDPOINT, $args, $cacheable);
}

/**
* returns the external url for a thumbnail of a specific video
*  @param $id
*    the youtube id of the specific video
*  @return
*    a URL pointing to the thumbnail
*/
function _video_apiclient_youtube_get_thumbnail_url($id) {
  $response = _video_apiclient_youtube_request('youtube.videos.get_details', array(
    'video_id' => $id,
  ));
  if (isset($response['THUMBNAIL_URL'][0]) && $response['THUMBNAIL_URL'][0] != '') {
    return $response['THUMBNAIL_URL'][0];
  }
  return false;
}

/**
 * Implementation of hook_v_auto_thumbnail
*/
function video_youtube_v_auto_thumbnail($node) {
  if (count($_POST)) {
    if ($_POST['vidfile'] == $node->vidfile) {
      _video_image_thumbnail_debug(t('No new video to thumbnail'));
      return NULL;
    }
    if ($_POST['tempimage']['fids']['_original']) {
      _video_image_thumbnail_debug(t('Video already thumbnailed'));
      return NULL;
    }
    $vidfile = $_POST['vidfile'];
  }
  else {
    $vidfile = $node->vidfile;
  }

  //get the video id
  $id = _video_youtube_get_id($vidfile);

  // get thumbnail url
  $thumbnail_url = _video_apiclient_youtube_get_thumbnail_url($id);
  return _video_image_get_thumb_file_object($thumbnail_url, $id);
}

/**
 * Implementation of hook_v_auto_resolution
*/
function video_youtube_v_auto_resolution(&$node) {

  // we set youtube videos to 425x350 by default
  return array(
    425,
    350,
  );
}

/**
 * Implementation of hook_v_auto_playtime
*/
function video_youtube_v_auto_playtime(&$node) {
  $id = _video_youtube_get_id($node->vidfile);
  $response = _video_apiclient_youtube_request('youtube.videos.get_details', array(
    'video_id' => $id,
  ));

  // NOTE: here we already passed validation so we expect a valid response
  return $response['VIDEO_DETAILS']['LENGTH_SECONDS'][0];

  // return the lenght in seconds
}

/** THEMEABLE FUNCTIONS */

/**
 * Play videos hosted on youtube.com
 * Allows users to host videos on youtube.com and then use the video ID to post it in the module.
 * In the future it could also use the youtube developer API to get info and comments of the video.
 *
 * @param $node
 *   object with node information
 *
 * @return
 *   string of content to display
 */
function theme_video_youtube_play($node) {
  $width = $node->video_scaled_x ? $node->video_scaled_x : '425';
  $height = $node->video_scaled_y ? $node->video_scaled_y : '350';
  $id = _video_youtube_get_id(check_plain($node->vidfile));

  // related video setting
  $rel = variable_get('video_youtube_related', false) ? '1' : '0';

  // this will be executed by not Internet Explorer browsers
  $output = '<!--[if !IE]> <-->
<object type="application/x-shockwave-flash" width="' . $width . '" height="' . $height . '"
data="http://www.youtube.com/v/' . $id . '&rel=' . $rel . '">
<!--> <![endif]-->' . "\n";

  // this will be executed by Internet Explorer
  $output .= '<!--[if IE]>
<object type="application/x-shockwave-flash" width="' . $width . '" height="' . $height . '"
classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">
<![endif]-->' . "\n";

  // params will be passed to both IE or not IE browsers
  $output .= '<param name="movie" value="http://www.youtube.com/v/' . $id . '&rel=' . $rel . '" />' . "\n" . '<param name="wmode" value="transparent" />' . "\n" . _video_get_parameters($node) . '<p>' . t('Your browser is not able to display this multimedia content.') . '</p>
</object>';
  $output = theme('video_format_play', $output, t('http://www.google.com/support/youtube'), t('Link to youtube.com'), t('youtube.com'));
  return $output;
}

/** HELPER FUNCTIONS */

/**
 * Get the id from an URL
*/
function _video_youtube_get_id($url) {
  $parsed_url = parse_url($url);
  parse_str($parsed_url['query'], $parsed_query);
  return $parsed_query['v'];
}

Functions

Namesort descending Description
theme_video_youtube_play Play videos hosted on youtube.com Allows users to host videos on youtube.com and then use the video ID to post it in the module. In the future it could also use the youtube developer API to get info and comments of the video.
video_youtube_admin_settings Setting form for video_upload
video_youtube_admin_settings_validate Validate settings
video_youtube_menu Implementation of hook_menu
video_youtube_v_auto_playtime Implementation of hook_v_auto_playtime
video_youtube_v_auto_resolution Implementation of hook_v_auto_resolution
video_youtube_v_auto_thumbnail Implementation of hook_v_auto_thumbnail
video_youtube_v_form Implementation of hook_v_form()
video_youtube_v_help Implementation of hook_v_help
video_youtube_v_info Implementation of hook_v_info()
video_youtube_v_play Implementation of hook_v_play
video_youtube_v_validate implementation of hook_v_validate
_video_apiclient_youtube_get_thumbnail_url returns the external url for a thumbnail of a specific video
_video_apiclient_youtube_request this is a wrapper for _video_apiclient_request_xml that includes youtube's api key
_video_youtube_get_id Get the id from an URL

Constants