<?php
// $Id: video_filter.module,v 1.12.2.4 2009/03/28 21:53:10 blackdog Exp $

module_load_include('inc', 'video_filter', 'video_filter.codecs');

function video_filter_filter($op, $delta = 0, $format = -1, $text = '') {
  switch ($op) {
    case 'list':
      return array(
        0 => t('Video Filter'),
      );

    case 'no cache':
      switch ($delta) {
        case 0:
          return 1;
        default:
          return 0;
      }

    case 'description':
      switch ($delta) {
        case 0:
          return t('Substitutes [video:URL] with embedded HTML.');
        default:
          return;
      }

    case 'process':
      switch ($delta) {
        case 0:
          return video_filter_process($text, $format);
        default:
          return $text;
      }

    case 'settings':
      switch ($delta) {
        case 0:
          return video_filter_settings($format);
        default:
          return;
      }

    default:
      return $text;
  }
}

function video_filter_filter_tips($delta, $format, $long = FALSE) {
  switch ($delta) {
    case 0:
      if ($long) {
        $codecs = module_invoke_all('codec_info');
        $supported = array();
        foreach ($codecs AS $codec) {
          $supported[] = $codec['name'];
        }
        return t('
          <p><strong>Video Filter</strong></p>
          <p>You may insert videos from popular video sites by using a simple tag <code>[video:URL]</code>.</p>
          <p>Examples:</p>
          <ul>
            <li>Single video:<br /><code>[video:http://www.youtube.com/watch?v=uN1qUeId]</code></li>
            <li>Random video out of multiple:<br /><code>[video:http://www.youtube.com/watch?v=uN1qUeId1,http://www.youtube.com/watch?v=uN1qUeId2]</code></li>
            <li>Override default autoplay setting: <code>[video:http://www.youtube.com/watch?v=uN1qUeId autoplay:1]</code></li>
            <li>Override default width and height:<br /><code>[video:http://www.youtube.com/watch?v=uN1qUeId width:X height:Y]</code></li>
            <li>Align the video:<br /><code>[video:http://www.youtube.com/watch?v=uN1qUeId align:right]</code></li>
          </ul>
          <p>Supported sites: @codecs.', array('@codecs' => implode(', ', $supported)));
      }
      else {
        return t('You may insert videos with [video:URL]');
      } 
      break;
  }
}

function video_filter_process($text, $format = -1) {
  if (preg_match_all('/\[video(\:(.+))?( .+)?\]/isU', $text, $matches_code)) {
    foreach ($matches_code[0] as $ci => $code) {
      $video = array(
        'source' => $matches_code[2][$ci],
        'width' => variable_get('video_filter_width_'.$format, 400),
        'height' => variable_get('video_filter_height_'.$format, 400),
        'autoplay' => variable_get('video_filter_autoplay_'.$format, 0),
      );

      // Pick random out of multiple sources separated by ','
      if (strstr($video['source'], ',')) {
        $sources          = explode(',', $video['source']);
        $random           = array_rand($sources, 1);
        $video['source']  = $sources[$random];
      }

      // Load all codecs
      $codecs = module_invoke_all('codec_info');

      // Find codec
      foreach ($codecs as $codec) {
        if (!is_array($codec['regexp'])) {
          $codec['regexp'] = array($codec['regexp']);
        }

        // Try different regular expressions
        foreach ($codec['regexp'] as $delta => $regexp) {
          if (preg_match($regexp, $video['source'], $matches)) {
            $video['codec'] = $codec;
            $video['codec']['delta'] = $delta;
            $video['codec']['matches'] = $matches;
            break 2;
          }
        }
      }

      // Codec found
      if ($video['codec']) {
        // Override default attributes
        if ($matches_code[3][$ci] && preg_match_all('/\s+([a-z]+)\:([^\s]+)/i', $matches_code[3][$ci], $matches_attributes)) {
          foreach ($matches_attributes[0] as $ai => $attribute) {
            $video[$matches_attributes[1][$ai]] = $matches_attributes[2][$ai];
          }
        }

        // Resize within width and height to given ratio
        if ($video['codec']['ratio']) {
          if ($video['width'] * $video['codec']['ratio'] > $video['height']) {
            $video['width'] = round($video['height'] * $video['codec']['ratio']);
            $video['height'] = round($video['width'] / $video['codec']['ratio']);
          }
          else {
            $video['height'] = round($video['width'] / $video['codec']['ratio']);
            $video['width'] = round($video['height'] * $video['codec']['ratio']);
          }
        }

        $video['autoplay'] = (bool) $video['autoplay'];
        $video['align'] = in_array($video['align'], array('left', 'right')) ? $video['align'] : NULL;

        $replacement = $video['codec']['callback']($video);
      // Invalid format
      }
      else {
        $replacement = '<!-- VIDEO FILTER - INVALID CODEC IN: '.$code.' -->';
      }

      $text = str_replace($code, $replacement, $text);
    }
  }

  return $text;
}

function video_filter_settings($format) {
  $form['video_filter'] = array(
    '#type' => 'fieldset',
    '#title' => t('Video filter'),
    '#collapsible' => TRUE,
  );
  $form['video_filter']['video_filter_width_'.$format] = array(
    '#type' => 'textfield',
    '#title' => t('Default width setting'),
    '#default_value' => variable_get('video_filter_width_'.$format, 400),
    '#maxlength' => 4,
  );
  $form['video_filter']['video_filter_height_'.$format] = array(
    '#type' => 'textfield',
    '#title' => t('Default height setting'),
    '#default_value' => variable_get('video_filter_height_'.$format, 400),
    '#maxlength' => 4,
  );
  $form['video_filter']['video_filter_autoplay_'.$format] = array(
    '#type' => 'radios',
    '#title' => t('Default autoplay setting'),
    '#description' => t('Not all video formats support this setting.'),
    '#default_value' => variable_get('video_filter_autoplay_'.$format, 1),
    '#options' => array(
      0 => t('No'),
      1 => t('Yes'),
    ),
  );

  return $form;
}

/**
 * Wrapper that calls the theme function.
 */
function video_filter_flash($video, $params = array()) {
  return theme('video_filter_flash', $video, $params);
}

/**
 * Function that outputs the <object> element.
 *
 * @ingroup themeable
 */
function theme_video_filter_flash($video, $params) {
  $output = '';

  $output .= '<object type="application/x-shockwave-flash" ';

  if ($video['align']) {
    $output .= 'style="float:'.$video['align'].'" ';
  }

  $output .= 'width="'.$video['width'].'" height="'.$video['height'].'" data="'.$video['source'].'">'."\n";

  $defaults = array(
    'movie' => $video['source'],
    'wmode' => 'transparent',
    'allowFullScreen' => 'true',
  );

  $params = array_merge($defaults, (is_array($params) && count($params)) ? $params : array());

  foreach ($params as $name => $value) {
    $output .= '  <param name="'.$name.'" value="'.$value.'" />'."\n";
  }

  $output .= '</object>'."\n";

  return $output;
}

/**
 * Implementation of hook_theme().
 */
function video_filter_theme($existing, $type, $theme, $path) {
  return array(
    'video_filter_flash' => array(
      'arguments' => array('video' => NULL, 'params' => array()),
    ),
  );
}