You are here

function youtube_get_remote_image in YouTube Field 7

Same name and namespace in other branches
  1. 8 youtube.module \youtube_get_remote_image()

Retrieves the thumbnail image for a given video from YouTube.

Parameters

int|null $video_id: The video ID of the particular YouTube video.

bool $force_small: (optional) When TRUE, this function should return the standard size image regardless of what the youtube_thumb_hires variable is set to. This is used should the high resolution image be found to not exist for a particular video.

Return value

bool|object Either the Drupal $file object of saved image, or FALSE if the save failed.

2 calls to youtube_get_remote_image()
theme_youtube_thumbnail in ./youtube.theme.inc
Theme function for thumbnails.
youtube_tokens in ./youtube.inc
Implements hook_tokens().

File

./youtube.inc, line 136
YouTube field helper functions.

Code

function youtube_get_remote_image($video_id = NULL, $force_small = FALSE) {

  // This variable is TRUE when higher resolution thumbnails should be saved.
  // The only thumbnail resolution higher than the standard 480 is
  // 'maxresdefault'. This resolution image is not guaranteed to exist. If
  // there's an error retrieving the hi-res image, we try again for small.
  $youtube_thumb_hires = variable_get('youtube_thumb_hires', FALSE);

  // This boolean is TRUE if we're obtaining a hi-res thumbnail.
  $get_hires = $youtube_thumb_hires && !$force_small;
  if ($get_hires) {
    $src = youtube_build_remote_image_path($video_id, 'maxresdefault');
  }
  else {
    $src = youtube_build_remote_image_path($video_id);
  }

  // Download file and save it as managed Drupal file.
  $image = drupal_http_request($src);
  if ($image->code != 200) {

    // Silently retry for small image if hi-res did not exist, otherwise log an
    // error and return FALSE.
    if ($get_hires) {
      return youtube_get_remote_image($video_id, TRUE);
    }
    watchdog('youtube', 'HTTP request for video ID %id failed (error code: %err).', array(
      '%id' => $video_id,
      '%err' => $image->code,
    ), WATCHDOG_ERROR);
    return FALSE;
  }

  // Set the path to thumbnails, and make sure it's usable.
  $youtube_thumb_uri = youtube_build_thumbnail_uri();
  if (!file_prepare_directory($youtube_thumb_uri, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
    watchdog('youtube', 'Failed to create YouTube thumbnail directory: %dir', array(
      '%dir' => $youtube_thumb_uri,
    ), WATCHDOG_ERROR);
    return FALSE;
  }
  $destination = youtube_build_thumbnail_uri($video_id);

  // Save the thumbnail and add to Drupal managed files.
  $file = file_save_data($image->data, $destination, FILE_EXISTS_REPLACE);
  if (!$file) {
    watchdog('youtube', 'Unable to save youtube thumbnail to filesystem for video %id', array(
      '%id' => $video_id,
    ), WATCHDOG_ERROR);
  }
  return $file;
}