<?php
// $Id: flowplayer.module,v 1.7.2.3 2009/04/22 21:59:44 stuartgreenfield Exp $

/**
 * SWF Tools - FlowPlayer
 *
 * Enables the use of FlowPlayer for media files
 *
 * Author's Site.
 * http://flowplayer.org
 */

define('FLOWPLAYER_MEDIAPLAYER', 'flowplayer_mediaplayer'); // 'player', can display mixed files
define('FLOWPLAYER_IMAGEROTATOR', 'flowplayer_imagerotator'); // 'player', can display images.
define('FLOWPLAYER_DOWNLOAD', 'http://www.tucows.com/download.html?software_id=519713&t=2');

/**
 * Implementation of swftools_methods hook
 * Report methods back to SWF Tools
 */
function flowplayer_swftools_methods() {

  // FlowPlayer has a few different player files, so we need to determine
  // which one is currently active
  $saved_settings = variable_get('swftools_'. FLOWPLAYER_MEDIAPLAYER, array());
  $shared_file = $saved_settings['player'] ? $saved_settings['player'] : 'flowplayer/FlowPlayerClassic.swf';

  $methods = array();
  $media_player = array(
    'name'        => FLOWPLAYER_MEDIAPLAYER,
    'module'      => 'flowplayer',
    'file'        => '',
    'version'     => '7',
    //'shared_file' => 'flowplayer/FlowPlayerClassic.swf',
    'shared_file' => $shared_file,
    'title'       => t('FlowPlayer'),
    'download'    => FLOWPLAYER_DOWNLOAD,
    'width'       => '320',
    'height'      => '263',
  );
  // Wijering support various actions with the same player and info.
  $methods[SWFTOOLS_FLV_DISPLAY][FLOWPLAYER_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_FLV_DISPLAY_LIST][FLOWPLAYER_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_MP3_DISPLAY][FLOWPLAYER_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_MP3_DISPLAY_LIST][FLOWPLAYER_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_MEDIA_DISPLAY][FLOWPLAYER_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_MEDIA_DISPLAY_LIST][FLOWPLAYER_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_IMAGE_DISPLAY_LIST][FLOWPLAYER_MEDIAPLAYER] = $media_player;

  return $methods;
}

/**
 * Implementation of hook_menu().
 */
function flowplayer_menu() {

  $items = array();

    //$items['admin/media/swf/flowplayer'] = array(
    $items['admin/settings/swftools/flowplayer'] = array(
      'title' => 'FlowPlayer',
      'description' => 'Settings for '. l('FlowPlayer', FLOWPLAYER_DOWNLOAD) .'.',
      'access arguments' => array('administer flash'),
      'page callback' => 'drupal_get_form',
      'page arguments' => array('flowplayer_admin_form'),
      'file' => 'flowplayer.admin.inc',
      'file path' => drupal_get_path('module', 'flowplayer'),
    );

  return $items;
}


/**
 * Implementation of swftools_flashvars hook.
 * Return an array of flashvars.
 */
function flowplayer_swftools_flashvars($action, &$methods, &$vars) {

  // Pad out the user parameters (like those passed through swf(), with our
  // configured defaults, allowing the user parameters to dominate.
  $saved_settings = _flowplayer_flashvars($methods->player['name']);

  $saved = array();
  foreach ($saved_settings as $category => $settings) {
    $saved = array_merge($saved, $settings);
  }
  $flashvars = array_merge($saved, $vars->flashvars);

  if (isset($flashvars['image']) && !valid_url($flashvars['image'], TRUE)) {
    $flashvars['image'] = swftools_get_media_url(swftools_get_media_path() . $flashvars['image']);
  }

  if ($vars->params['width']) {$flashvars['width'] = $vars->params['width'];}
  if ($vars->params['height']) {$flashvars['height'] = $vars->params['height'];}

  /* FlowPlayer doesn't like "" when JSON is generated, so we have to construct it ourselves here
   * and assign it to the variable config.
   * Build an array of FlowPlayer configuration settings, then call drupal_to_js to convert
   * to JSON format, and then run through str_replac to make FlowPlayer happy!
   */

  // Initialise array of FlowPlayer configuration settings
  $flowplayer = array();

  // If the passed filename ends in xml then it is a playlist
  // FlowPlayer format requires a bit of adjusting to get things in the right format
  // and we don't want an xml playlist but a flashvars string
  if (pathinfo($vars->othervars['file_url'], PATHINFO_EXTENSION) == 'xml') {

    // Initialise array to hold data
    $playlist = array();

    // Get file paths out of existing array and start to form FlowPlayer format
    foreach ($vars->othervars['playlist_data']['playlist'] as $play) {
      $playlist[] = "{ url: '".$play['fileurl']."' }";
    }

    // Implode the array to create a flashvar ready for later
    $flowplayer['playList'] = '[ '. implode(', ', $playlist) .' ]';
  } else {

    // If not a playlist simply assign file_url to videoFile
    $flowplayer['videoFile'] = $vars->othervars['file_url'];
  }

  // Find out what configuration settings are available
  $available_settings = flowplayer_swftools_variable_mapping();

  // See which ones have been set in othervars and copy to flowplayer array
  foreach ($available_settings[FLOWPLAYER_MEDIAPLAYER] as $setting => $value) {

    if (isset($flashvars[$setting])) {
      $flowplayer[$setting] = $flashvars[$setting];
      unset($vars->flashvars[$setting]);
    }
  }

  /**
   * FlowPlayer uses 'loop' as the parameter to control looping
   * This is already used as flash parameter so using loop in a
   * filter means it isn't passed in the flashvars array. So copy
   * whatever value we have in the parameter to flowplayer array
   */
  if ($vars->othervars['loop'])  {
    $flowplayer['loop'] = $vars->othervars['loop'];
  }

  // Merge $vars->othervars in to flashvars
  //$flowplayer = array_merge($flowplayer, $vars->othervars);

  // Convert to JSON
  $flashvars['config'] = drupal_to_js($flowplayer);

  // Replace " with ', and remove quotes from around true and false, to satisfy FlowPlayer
  $flashvars['config'] = str_replace(array('"', "'false'", "'true'", "'[", "]'"), array("'", "false", "true", "[", "]"), $flashvars['config']);

  // If we had a playlist then the ' has been escaped, so reverse it where it occurs in the playlist
  if ($playlist) {
    $flashvars['config'] = str_replace(array("url: \'", "\' }"), array("url: '", "' }"), $flashvars['config']);
  }

  // Return an array of flash variables
  return $flashvars;
}

/**
 * This function is called from flowplayer_swftools_flashvars() which is called from swf()
 * It will return the default flashvar configuration, just prior to any overrides
 * passed into swf(). We start with the settings defined on admin/swf/wijering
 * which are returned by _flowplayer_settings(). Then we prepare these values for output
 * to html (eg. '1' become 'true') and we unset undefined flashvars to prevent their output.
 *
 */
function _flowplayer_flashvars($this_player) {
  // Cache this.
  static $flashvars = array();
  if (!count($flashvars)) {

    // Media Player
    foreach (array(FLOWPLAYER_MEDIAPLAYER) AS $player) {

      // Get saved settings for this method.
      $defaults = _flowplayer_settings($player);
      foreach ($defaults AS $category => $vars) {
        foreach ($vars AS $key => $setting) {
          if (!$setting || $setting == 'default') {
            unset($defaults[$category][$key]);
          }
          else {
            switch ($category) {
              case 'color':
                $defaults['color'][$key] = str_replace('#', '0x', $defaults['color'][$key]);
                break;
              case 'boolean':
                $defaults['boolean'][$key] = _swftools_tf($defaults['boolean'][$key]);
                break;
            }
          }
        }
      }

      // Not the same as width/height. This determines the extended width OR height
      // past the main view area where the actual playlist file names can be found.
      // Setting both together is not supported.
      if ($defaults['integer']['displaywidth']) {
        unset($defaults['integer']['displayheight']);
      }
      else {
        unset($defaults['integer']['displaywidth']);
      }
      $flashvars[$player] = $defaults;
    }
  }

  return $flashvars[$this_player];
}


function flowplayer_flowplayer_mediaplayer_swftools_playlist($xml_data, &$method, &$vars) {

  $xml = '<playlist version="1" xmlns="http://xspf.org/ns/0/">
            <title>'. $xml_data['header']['title'] .'</title>
            <info></info>
            <annotation></annotation>
            <trackList>
            ';
  foreach ($xml_data['playlist'] AS $track => $details) {

    if (!isset($details['background']) && strtolower(substr($details['fileurl'], -3, 3)) == 'mp3') {
      if (isset($vars->flashvars['image'])) {
        $details['background'] = swftools_get_media_url(swftools_get_media_path() . $vars->flashvars['image']);
      } else {
        $details['background'] = SWFTOOLS_DEFAULT_BG;
      }
    }
    $xml .= "<track>\n";
    $xml .= "<title>". $details['title'] ."</title>\n";
    $xml .= "<creator></creator>\n";
    $xml .= "<location>". $details['fileurl'] ."</location>\n";
    $xml .= "<image>". $details['background'] ."</image>\n";
    $xml .= "<info>". $details['fileurl'] ."</info>\n";
    $xml .= "</track>\n";
  }
  $xml .= '</trackList>
           </playlist>';
  return $xml;
}


/*
 * Implementation of hook_swftools_variable_mapping.
 * We don't map anything to flashvars, but we want to know what
 * settings are available
 *
 */
function flowplayer_swftools_variable_mapping() {
  return array(
    FLOWPLAYER_MEDIAPLAYER => array(
      'videoFile'               => 'flashvars',
      'autoPlay'                => 'flashvars',
      'initialVolumePercentage' => 'flashvars',
      'usePlayOverlay'          => 'flashvars',
      'controlBarGloss'         => 'flashvars',
      'hideControls'            => 'flashvars',
      'loop'                    => 'flashvars',
      'fullscreen'              => 'flashvars',
      'showFullScreenButton'    => 'flashvars',
      'showPlayListButtons'     => 'flashvars',
    ),
  );
}


/**
 * These are the default settings as they are stored in the database and displayed
 * on the settings page.
 */
function _flowplayer_settings($player) {

  switch ($player) {
    case FLOWPLAYER_MEDIAPLAYER:
      // Define the settings list.
      $defaults['boolean'] = array(
        'autoPlay'            => 'default',
        'usePlayOverlay'      => 'default',
        'hideControls'        => 'default',
        'loop'                => 'default',
        'showFullScreenButton'=> 'default',
        'showPlayListButtons' => 'default',
        'fullscreen'          => 'default',
      );
      $defaults['color'] = array(
      );
      $defaults['url'] = array(
      );
      $defaults['integer'] = array(
        'initialVolumePercentage' => '',
      );
      $defaults['other'] = array(
        'player'              => 'default',
        'controlBarGloss'     => 'default',
      );
      $saved_settings = variable_get('swftools_'. FLOWPLAYER_MEDIAPLAYER, array());
      break;

  }

  // Overwrite initialised variables with those that might be already saved.
  foreach ($defaults AS $category => $vars) {
    foreach ($vars AS $key => $setting) {
      if (isset($saved_settings[$key])) {
        $defaults[$category][$key] = $saved_settings[$key];
      }
    }
  }

  return $defaults;
}


/**
 * flashvar and param option arrays. These are used for options settings in the
 * configuration screen.
 *
 */
function _flowplayer_options() {
  $options['type'] = array('default' => 'default', 'sound' => 'sound', 'image' => 'image', 'video' => 'video', 'youtube' => 'youtube', 'camera' => 'camera', 'http' => 'http', 'rtmp' => 'rtmp', );
  $options['overstretch'] = array('default' => 'default', 'uniform' => 'uniform', 'fill' => 'fill', 'exactfit' => 'exactfit', 'none' => 'none', );
  $options['repeat'] = array('default' => 'default', 'none' => 'none', 'list' => 'list', 'always' => 'always', );
  $options['linktarget'] = array('default' => 'default', '_self' => '_self', '_blank' => '_blank', 'none' => 'none', );
  $options['playlist'] = array('default' => 'default', 'bottom' => 'bottom', 'over' => 'over', 'right' => 'right', 'none' => 'none', );
  $options['controlbar'] = array('default' => 'default', 'bottom' => 'bottom', 'over' => 'over', 'none' => 'none', );
  $options['displayclick'] = array('default' => 'default', 'play' => 'play', 'link' => 'link', 'fullscreen' => 'fullscreen', 'none' => 'none', 'mute' => 'mute', 'next' => 'next', );

  $options['player'] = array('flowplayer/FlowPlayerClassic.swf' => 'Classic', 'flowplayer/FlowPlayerDark.swf' => 'Dark', 'flowplayer/FlowPlayerLight.swf' => 'Light', 'flowplayer/FlowPlayerLP.swf' => 'LP', );
  $options['controlBarGloss'] = array('default' => 'default', 'high' => 'high', 'low' => 'low', 'none' => 'none', );
  $options['bool'] = array('default' => 'default', 'true' => 'true', 'false' => 'false');
  return $options;
}


/**
 * Implementation of hook_help
 */
function flowplayer_help($path, $arg) {
  switch ($path) {
    case 'admin/settings/swftools/flowplayer':
      return '<p>'.t('These are the settings for the FlowPlayer media player.
                      For details of what each parameter does refer to the
                      <a href="@flowplayer">FlowPlayer documentation</a>.
                      It is possible that you do not need to change any of
                      these settings and blank values will defer to friendly
                      defaults. Note that the label in (<em>brackets</em>)
                      is the configuration setting name and corresponds to the documentation page.
                      If content is embedded using the SWF Tools filter then each parameter
                      can be over-ridden by specifying a new value in the filter string.', array('@flowplayer' => 'http://flowplayer.org/v2/player/index.html')).'</p>';
  }
}
