<?php

/**
 * @file
 * Provides a simple field for easily embedding videos from youtube or vimeo
 *
 * This module is not intended to replace media or video - it does not allow for
 * any local storage of videos, custom players or anything else.
 * It simply allows users to embed videos from youtube and vimeo - and provides
 * hooks to allow other modules to provide more providers.
 *
 * Uses CTools Export UI to manage settings.
 *
 * @see ./plugins/export_ui/video_embed_field_export_ui.inc
 *
 * @author jec006, jdelaune
 */

// Load all Field module hooks.
module_load_include('inc', 'video_embed_field', 'video_embed_field.field');
// Load the admin forms.
module_load_include('inc', 'video_embed_field', 'video_embed_field.admin');
// Load our default handlers.
module_load_include('inc', 'video_embed_field', 'video_embed_field.handlers');
// Load feeds mapping hooks.
module_load_include('inc', 'video_embed_field', 'video_embed_field.feeds');

/**
 * Implements hook_ctools_plugin_directory().
 */
function video_embed_field_ctools_plugin_directory($module, $type) {
  // Load the export_ui plugin.
  if ($type == 'export_ui') {
    return 'plugins/export_ui';
  }
}

/**
 * Implements hook_ctools_plugin_api().
 *
 * Tell CTools that we support the default_mymodule_presets API.
 */
function video_embed_field_ctools_plugin_api($owner, $api) {
  if ($owner == 'video_embed_field' && $api == 'default_video_embed_styles') {
    return array('version' => 1);
  }
}

/**
 * Implements hook_default_video_styles().
 */
function video_embed_field_default_video_embed_styles() {
  $styles = array();

  $handlers = video_embed_get_handlers();
  // Create the normal handler.
  $normal = new stdClass();
  $normal->disabled = FALSE; /* Edit this to true to make a default video_embed_style disabled initially */
  $normal->api_version = 1;
  $normal->name = 'normal';
  $normal->title = 'Normal';
  $normal->data = array();

  $teaser = new stdClass();
  $teaser->disabled = FALSE; /* Edit this to true to make a default video_embed_style disabled initially */
  $teaser->api_version = 1;
  $teaser->name = 'teaser';
  $teaser->title = 'Teaser';
  $teaser->data = array();

  // Add in our settings for each of the handlers.
  foreach ($handlers as $name => $handler) {
    $normal->data[$name] = $handler['defaults'];
    $teaser->data[$name] = $handler['defaults'];
    $teaser->data[$name]['width'] = 480;
    $teaser->data[$name]['height'] = 270;
  }

  return array($normal, $teaser);
}

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

  $items['vef/load/%'] = array(
    'title' => 'Video Embed Field - Load Video',
    'page callback' => '_video_embed_field_show_video',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  $items['admin/config/media/vef'] = array(
    'title' => 'Video Embed Field',
    'description' => 'Video Embed Field configuration',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('administer video styles'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['admin/config/media/vef/settings'] = array(
    'title' => 'Settings',
    'description' => 'Video Embed Field module settings',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('video_embed_field_settings_form'),
    'file' => 'video_embed_field.admin.inc',
    'access arguments' => array('administer video styles'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Implements hook_permission().
 */
function video_embed_field_permission() {
  return array(
    'administer video styles' => array(
      'title' => t('Administer video styles'),
      'description' => t('Create and modify styles for embedded videos.'),
    ),
  );
}

/**
 * Implements hook_theme().
 */
function video_embed_field_theme() {
  return array(
    // Theme functions in video_embed_field.admin.inc.
    'video_embed_field_video_style_list' => array(
      'variables' => array('styles' => NULL),
    ),
    'video_embed_field_embed_code' => array(
      'template' => 'video-embed-field-embed-code',
      'variables' => array(
        'url' => NULL,
        'style' => 'normal',
        'video_data' => array(),
      ),
    ),
    'video_embed_field_colorbox_code' => array(
      'variables' => array(
        'image_url' => NULL,
        'image_style' => 'normal',
        'image_alt' => NULL,
        'video_url' => NULL,
        'video_style' => NULL,
        'video_data' => array(),
      ),
    ),
  );
}

/**
 * Implements hook_views_api().
 */
function video_embed_field_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'video_embed_field') . '/views',
  );
}

/**
 * Get an array of all styles and their settings.
 *
 * @return array
 *   An array of styles keyed by the video style name (name).
 *
 * @see video_embed_field_video_style_load()
 */
function video_embed_field_video_styles() {
  $styles = &drupal_static(__FUNCTION__);

  // Grab from cache or build the array.
  if (!isset($styles)) {
    // Load the style via ctools - which will handle all the caching for us -
    // Because it does a bit more logic, lets still statically cache this.
    ctools_include('export');
    $styles = ctools_export_load_object('vef_video_styles');
  }

  return $styles;
}

/**
 * Load a style by style name. May be used as a loader for menu items.
 *
 * Note that you may also use ctools_export_load_object with the key being
 * vef_video_styles
 *
 * @param string $name
 *   The name of the style.
 *
 * @return array
 *   An video style array containing the following keys:
 *   - "name": The unique video style ID.
 *   - "title": The human readable video style name.
 *   - "data": An array of video settings within this video style.
 *   If the video style name or ID is not valid, an empty array is returned.
 */
function video_embed_field_video_style_load($name) {
  $styles = video_embed_field_video_styles();

  return isset($styles[$name]) ? $styles[$name] : FALSE;
}

/**
 * Creates a hook that other modules can implement to get handlers.
 *
 * Can be used to add more handlers if needed - from other modules and such.
 *
 * @see hook_video_embed_handler_info
 * @see video_embed_field.api.php
 */
function video_embed_get_handlers() {
  $handlers = &drupal_static(__FUNCTION__);

  if (!isset($handlers)) {
    if ($handlers = cache_get('video_embed_field_handlers')) {
      $handlers = $handlers->data;
    }
    else {
      $handlers = module_invoke_all('video_embed_handler_info');
      drupal_alter('video_embed_handler_info', $handlers);
      cache_set('video_embed_field_handlers', $handlers);
    }
  }

  return $handlers;
}

/**
 * Retrieves the video handler for a video URL.
 *
 * @param string $url
 *   The video URL.
 *
 * @return string|bool
 *   The handler name for the URL, FALSE in case there is no handler.
 */
function video_embed_get_handler($url) {
  // Process video URL.
  if (!stristr($url, 'http://') && !stristr($url, 'https://')) {
    $url = 'http://' . $url;
  }
  $parts = parse_url($url);
  if (!isset($parts['host'])) {
    return FALSE;
  }

  $host = $parts['host'];
  if (stripos($host, 'www.') > -1) {
    $host = substr($host, 4);
  }

  $domains = _video_embed_field_get_provider_domains();
  $handlers = video_embed_get_handlers();
  if (isset($domains[$host])) {
    $handler_name = $domains[$host];
    $handler = $handlers[$handler_name];
    $handler['name'] = $handler_name;
    return $handler;
  }
  else {
    return FALSE;
  }
}

/**
 * Creates a form from the player configuration options.
 *
 * @param array $defaults
 *   The default settings for the various fields.
 *
 * @return array
 *   The configuration form array.
 */
function video_embed_field_get_form($defaults) {
  $form = array();

  $handlers = video_embed_get_handlers();

  foreach ($handlers as $name => $handler) {
    if (isset($handler['form']) && function_exists($handler['form'])) {
      $handler_defaults = isset($defaults[$name]) ? $defaults[$name] : array();
      $handler_defaults = array_merge($handler['defaults'], $handler_defaults);

      $form[$name] = call_user_func($handler['form'], $handler_defaults);

      $form[$name] += array(
        '#type' => 'fieldset',
        '#title' => t('@provider settings', array('@provider' => $handler['title'])),
        '#tree' => TRUE,
        '#element_validate' => isset($handler['form_validate']) ? array($handler['form_validate']) : array(),
      );
    }
  }

  return $form;
}

/**
 * Validates the iframe CSS dimensions.
 *
 * @param array $element
 *   The element to validate.
 */
function video_embed_field_validate_dimensions($element) {
  if (!preg_match('/^(\d*)(px|%)?$/', $element['width']['#value'], $results)) {
    form_error($element['width'], t('You should use a valid CSS value for width in @plugin plugin', array('@plugin' => $element['#title'])));
  }
  if (!preg_match('/^(\d*)(px|%)?$/', $element['height']['#value'], $results)) {
    form_error($element['height'], t('You should use a valid CSS value for height in @plugin plugin', array('@plugin' => $element['#title'])));
  }
}

/**
 * Get an array of image styles suitable for using as select list options.
 *
 * @param bool $include_empty
 *   If TRUE a <none> option will be inserted in the options array.
 *
 * @return array
 *   Array of image styles both key and value are set to style name.
 */
function video_embed_field_video_style_options($include_empty = TRUE) {
  $styles = video_embed_field_video_styles();
  $options = array();
  if ($include_empty && !empty($styles)) {
    $options[''] = t('<none>');
  }
  foreach ($styles as $style) {
    $options[$style->name] = $style->title;
  }
  if (empty($options)) {
    $options[''] = t('No defined styles');
  }
  return $options;
}

/**
 * Implements hook_filter_info().
 */
function video_embed_field_filter_info() {
  $filters['video_embed_field'] = array(
    'title' => t('Video Embedding'),
    'description' => t('Replaces [VIDEO::http://www.youtube.com/watch?v=someVideoID::aVideoStyle] tags with embedded videos.'),
    'process callback' => 'video_embed_field_filter_process',
    'tips callback' => '_filter_video_embed_tips',
  );

  return $filters;
}

/**
 * Implements callback_filter_tips().
 *
 * Provides help for the URL filter.
 *
 * @see filter_filter_info()
 */
function _filter_video_embed_tips($filter, $format, $long = FALSE) {
  return t('Replaces [VIDEO::http://www.youtube.com/watch?v=someVideoID::aVideoStyle] tags with embedded videos.');
}

/**
 * Video Embed Field filter process callback.
 */
function video_embed_field_filter_process($text, $filter, $format) {
  preg_match_all('/ \[VIDEO:: ( [^\[\]]+ )* \] /x', $text, $matches);

  $tag_match = (array) array_unique($matches[1]);

  foreach ($tag_match as $tag) {
    $parts = explode('::', $tag);

    // Get video style.
    if (isset($parts[1])) {
      $style = $parts[1];
    }
    else {
      $style = 'normal';
    }

    $embed_code = theme('video_embed_field_embed_code', array('url' => $parts[0], 'style' => $style));

    $text = str_replace('[VIDEO::' . $tag . ']', $embed_code, $text);
  }

  return $text;
}

/**
 * Processes variables to format a video player.
 *
 * @param array $variables
 *   Contains the following information:
 *    - $url
 *    - $style
 *    - $video_data
 *
 * @see video-embed.tpl.php
 */
function template_preprocess_video_embed_field_embed_code(&$variables) {
  // Get the handler.
  $handler = video_embed_get_handler($variables['url']);
  $variables['handler'] = $handler['name'];

  // Load the style.
  $style = video_embed_field_video_style_load($variables['style']);
  // If there was an issue load in the default style.
  if ($style == FALSE) {
    $style = video_embed_field_video_style_load('normal');
  }
  if (isset($style->data[$variables['handler']])) {
    $variables['style_settings'] = $style->data[$variables['handler']];
  }
  // Safety value for when we add new handlers and there are styles stored.
  else {
    $variables['style_settings'] = $handler['defaults'];
  }

  // Prepare the URL.
  if (!stristr($variables['url'], 'http://') && !stristr($variables['url'], 'https://')) {
    $variables['url'] = 'http://' . $variables['url'];
  }

  // Prepare embed code.
  if ($handler && isset($handler['function']) && function_exists($handler['function'])) {
    $embed_code = call_user_func($handler['function'], $variables['url'], $variables['style_settings']);
    $variables['embed_code'] = drupal_render($embed_code);
  }
  else {
    $variables['embed_code'] = l($variables['url'], $variables['url']);
  }

  // Prepare video data.
  $variables['data'] = $variables['video_data'];
  unset($variables['video_data']);
}

/**
 * Returns image style image with a link to an embedded video in colorbox.
 *
 * @param array $variables
 *   An associative array containing:
 *   - image_url: The image URL.
 *   - image_style: The image style to use.
 *   - image_alt: The image ALT attribute.
 *   - video_url: The video URL.
 *   - video_style: The video style to use.
 *   - video_data: An array of data about the video.
 *
 * @return string
 *   The themed output.
 *
 * @ingroup themeable
 */
function theme_video_embed_field_colorbox_code($variables) {
  $path = video_embed_field_get_ajax_url($variables['video_url'], $variables['video_style']);

  $image = array(
    '#theme' => 'image_formatter',
    '#item' => array('uri' => $variables['image_url'], 'alt' => $variables['image_alt']),
    '#image_style' => $variables['image_style'],
    '#path' => $path,
  );

  return drupal_render($image);
}

/**
 * Gets the thumbnail url for a given video url.
 *
 * @param string $url
 *   The url of the video.
 *
 * @return string
 *   String representing the url of the thumbnail, or FALSE on error.
 */
function video_embed_field_thumbnail_url($url) {
  $info = FALSE;
  if ($handler = video_embed_get_handler($url)) {
    if (isset($handler['thumbnail_function']) && function_exists($handler['thumbnail_function'])) {
      $info = call_user_func($handler['thumbnail_function'], $url);
      $info['handler'] = $handler['name'];
    }
    if (empty($info['url']) && isset($handler['thumbnail_default']) && file_exists($handler['thumbnail_default'])) {
      $info = array(
        'handler' => $handler['name'],
        'id' => 'default_thumbnail',
        'url' => $handler['thumbnail_default'],
      );
    }
  }
  return $info;
}

/**
 * Gets a video data array for a given video url.
 *
 * @param string $url
 *   A video URL of the data array you want returned.
 *
 * @return array|false
 *   An array of video data, or FALSE on error.
 */
function video_embed_field_get_video_data($url) {
  $handler = video_embed_get_handler($url);
  if ($handler && isset($handler['data_function']) && function_exists($handler['data_function'])) {
    $data = call_user_func($handler['data_function'], $url);
    $data['handler'] = $handler['name'];
    return $data;
  }
  return FALSE;
}

/**
 * Generates the AJAX path array from the video URL and the video_style.
 *
 * @param string $video_url
 *   The URL to the video.
 * @param string $video_style
 *   The video style to render the video.
 *
 * @return array
 *   The AJAX path array.
 */
function video_embed_field_get_ajax_url($video_url, $video_style) {
  $style = video_embed_field_video_style_load($video_style);

  // If there was an issue load in the default style.
  if ($style == FALSE) {
    $style = video_embed_field_video_style_load('normal');
  }

  $handler = video_embed_get_handler($video_url);

  $data = $style->data[$handler['name']];

  // Write values for later AJAX load.
  $hash = _video_embed_field_store_video($video_url, $video_style);

  return array(
    'path' => 'vef/load/' . $hash,
    'options' => array(
      'attributes' => array(
        'class' => array(
          'colorbox-load',
          'colorbox'
        ),
      ),
      'query' => array(
        'width' => $data['width'],
        'height' => $data['height'] + 5,
      ),
    ),
  );
}

/**
 * Fetches all available provider domains.
 *
 * @return array
 *   An array containing the allowed video domains.
 */
function _video_embed_field_get_provider_domains() {
  $domains = array();

  $handlers = video_embed_get_handlers();
  foreach ($handlers as $name => $handler) {
    if (isset($handler['function']) && function_exists($handler['function'])) {
      foreach ($handler['domains'] as $domain) {
        $domains[$domain] = $name;
      }
    }
  }

  return $domains;
}

/**
 * Fetches all available provider domains for certain field instance.
 *
 * @param array $instance
 *   The instance definition.
 *
 * @return array
 *   An array containing the allowed video domains.
 */
function _video_embed_field_get_instance_provider_domains($instance) {
  return array_intersect(_video_embed_field_get_provider_domains(), $instance['settings']['allowed_providers']);
}

/**
 * Fetches settings string.
 *
 * @param array $settings
 *   The settings array.
 *
 * @return string
 *   The settings string generated from the settings array.
 */
function _video_embed_code_get_settings_str($settings = array()) {
  $values = array();

  foreach ($settings as $name => $value) {
    if (!isset($value)) {
      $values[] = $name;
    }
    else {
      $values[] = $name . '=' . $value;
    }
  }

  return implode('&amp;', $values);
}

/**
 * Stores a video to be loaded later from an _video_embed_field_load_video.
 *
 * @param string $video_url
 *   The video URL.
 * @param string $video_style
 *   The video style.
 *
 * @return string
 *   The hash generated for the video URL and the given style.
 */
function _video_embed_field_store_video($video_url, $video_style) {
  // Create a hash key.
  $hash = _video_embed_field_hash($video_url, $video_style);

  // Check that this record doesn't already exist before saving it.
  if (!_video_embed_field_load_video($hash)) {
    $record = array(
      'vhash' => $hash,
      'video_url' => $video_url,
      'video_style' => $video_style,
    );

    cache_set('vef-store-' . $hash, $record);

    // Add it to our static cache so we won't have to go to the database.
    $static_cache = &drupal_static('vef_video_store', array());
    $static_cache[$hash] = $record;
  }
  return $hash;
}

/**
 * Renders a video for an AJAX call.
 *
 * @param string $hash
 *   The video hash.
 *
 * @return Null
 *   Null because prints an AJAX output.
 */
function _video_embed_field_show_video($hash) {
  $data = _video_embed_field_load_video($hash);
  $video = array(
    '#theme' => 'video_embed_field_embed_code',
    '#style' => $data['video_style'],
    '#url' => $data['video_url'],
  );

  print drupal_render($video);
  return NULL;
}

/**
 * Loads a video from the video store given its hash.
 *
 * @param string $hash
 *   The video hash.
 *
 * @return array|bool
 *   An array with video definition, FALSE if the hash does not exist.
 */
function _video_embed_field_load_video($hash) {
  $static_cache = &drupal_static('vef_video_store', array());
  // Check if we've already loaded it.
  if (isset($static_cache[$hash])) {
    return $static_cache[$hash];
  }
  else {
    $result = cache_get('vef-store-' . $hash);
    if ($result) {
      // Cache it before returning.
      $data = $result->data;
      $static_cache[$hash] = $data;
      return $data;
    }
    else {
      return FALSE;
    }
  }
}

/**
 * Creates a hash for storing or looking up a video in the store table.
 *
 * @param string $video_url
 *   The video URL.
 * @param string $video_style
 *   The video style.
 *
 * @return string
 *   The hash generated for the video URL and the given style.
 */
function _video_embed_field_hash($video_url, $video_style) {
  return md5('vef' . $video_url . $video_style);
}
