You are here

emvideo_youtube.module in Asset 7

Emvideo youtube module.

File

modules/emvideo/modules/emvideo_youtube/emvideo_youtube.module
View source
<?php

/**
 * @file
 * Emvideo youtube module.
 */

/**
 * Implements hook_emvideo_parse().
 */
function emvideo_youtube_emvideo_parse($url) {
  $matches = array();
  if (preg_match('@(?:https?\\:\\/\\/)?(?:www\\.)?youtu(?:|\\.be|be\\.com)(\\/watch|\\/embed|\\/v/|\\/)+((.*)?[\\&\\?]v=)?([^"\\& ]+)@i', $url, $matches)) {
    $hosts = array(
      'i.ytimg.com',
      'i1.ytimg.com',
      'i2.ytimg.com',
      'i3.ytimg.com',
      'i4.ytimg.com',
      'img.youtube.com',
    );
    $host = $hosts[array_rand($hosts)];
    return array(
      'source' => 'http://www.youtube.com/v/' . $matches[4],
      'provider' => 'youtube',
      'snapshot' => 'http://' . $host . '/vi/' . $matches[4] . '/mqdefault.jpg',
    );
  }
  return FALSE;
}

/**
 * Implements hook_emvideo_generate().
 */
function emvideo_youtube_emvideo_generate() {
  static $urls = array();
  static $page = 0;

  // If no urls are set, get a new page
  if (count($urls) == 0) {

    // Set pager
    $page++;
    $max_results = 50;

    // Build url and make the request to Youtube API
    $params = array(
      'category' => 'Pets',
      'fields' => 'entry(media:group(media:content(@url)))',
      'max-results' => $max_results,
      'start-index' => 1 + $max_results * ($page - 1),
    );
    $url = "https://gdata.youtube.com/feeds/api/videos?" . http_build_query($params);
    $response = drupal_http_request($url);
    if ($response->code == 200) {
      try {
        $xml = new SimpleXMLElement($response->data);
      } catch (Exception $e) {

        // SimpleXMLElement::__construct produces an E_WARNING error message for
        // each error found in the XML data and throws an exception if errors
        // were detected. Catch any exception and return failure (NULL).
        return;
      }

      // If there is no valid project data, the XML is invalid, so return failure.
      if (!isset($xml->entry)) {
        return;
      }
      else {

        // Parse the content and populate our array
        foreach ($xml->entry as $entry) {

          //All the media namespaced items under a YouTube video entry
          $media = $entry
            ->children('media', TRUE);
          $urls[] = strtok($media->group->content
            ->attributes()->url, '?');
        }
      }
    }
  }

  // Get our value and remove it from the array
  $key = array_rand($urls);
  $url = $urls[$key];
  unset($urls[$key]);
  return $url;
}

Functions

Namesort descending Description
emvideo_youtube_emvideo_generate Implements hook_emvideo_generate().
emvideo_youtube_emvideo_parse Implements hook_emvideo_parse().