<?php
// $Id: wijering4.module,v 1.7.2.4 2009/04/23 22:25:55 stuartgreenfield Exp $

/**
 * SWF Tools - Jeroen Wijering's Media Player version 4
 *
 * Enables the use of Jeroen Wijering's FLV Media Player version 4
 *
 * Author's Site.
 * http://jeroenwijering.com
 */

define('WIJERING4_MEDIAPLAYER', 'wijering4_mediaplayer'); // 'player', can display mixed files
define('WIJERING4_IMAGEROTATOR', 'wijering4_imagerotator'); // 'player', can display images.
define('WIJERING4_DOWNLOAD', 'http://www.jeroenwijering.com/?item=JW_FLV_Media_Player');

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

  // Wijering4 now comes in two versions - viral and non-viral - since we now cache the results of this function we can
  // check which is present, testing for the viral one first
  
  // Start with the viral player
  $player = 'flash_media_player/player-viral.swf';
  
  // Discover if the viral player is present
  if (!file_exists(swftools_get_player_path() . '/' . $player)) {
   
    // If not, try the non-viral version
    $player = 'flash_media_player/player.swf';
    
    if (!file_exists(swftools_get_player_path() . '/' . $player)) {
      
      // If non-viral isn't present either revert to viral for purposes of the download message (since viral is the default)
      $player = 'flash_media_player/player-viral.swf';
      
    }
    
  }
  
  // Define the media player
  $media_player = array(
    'name'        => WIJERING4_MEDIAPLAYER,
    'module'      => 'wijering4',
    'file'        => 'file', // Define which flashvar to assign a 'file to play' variable.
    'version'     => '7',
    'shared_file' => $player,
    'title'       => t('JW Media Player 4'),
    'download'    => WIJERING4_DOWNLOAD,
    'width'       => '400',
    'height'      => '300',
  );

  // Wijering support various actions with the same player and info.
  $methods[SWFTOOLS_FLV_DISPLAY][WIJERING4_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_FLV_DISPLAY_LIST][WIJERING4_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_MP3_DISPLAY][WIJERING4_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_MP3_DISPLAY_LIST][WIJERING4_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_MEDIA_DISPLAY][WIJERING4_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_MEDIA_DISPLAY_LIST][WIJERING4_MEDIAPLAYER] = $media_player;
  $methods[SWFTOOLS_IMAGE_DISPLAY_LIST][WIJERING4_MEDIAPLAYER] = $media_player;

  // Return methods
  return $methods;
}

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

  $items = array();

    //$items['admin/media/swf/wijering4'] = array(
    $items['admin/settings/swftools/wijering4'] = array(
      'title' => 'JW Media Player 4',
      'description' => 'Settings for '. l('Jeroen Wijering\'s FLV Media Player 4', WIJERING4_DOWNLOAD) .'.',
      'access arguments' => array('administer flash'),
      'page callback' => 'drupal_get_form',
      'page arguments' => array('wijering4_admin_form'),
      'file' => 'wijering4.admin.inc',
      'file path' => drupal_get_path('module', 'wijering4'),
    );

  return $items;
}


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

  switch ($player) {
    case WIJERING4_MEDIAPLAYER:
      // Define the settings list.
      $defaults['boolean'] = array(
        'shuffle'             => 'default',
        'fullscreen'          => 'default',
        'autostart'           => 'default',
        'quality'             => 'default',
      );
      $defaults['color'] = array(
        'backcolor'           => '',
        'frontcolor'          => '',
        'lightcolor'          => '',
        'screencolor'         => '',
      );
      $defaults['url'] = array(
        'logo'                => '',
        'captions'            => '',
        'link'                => '',
        'streamscript'        => '',
        'skin'                => '',
      );
      $defaults['integer'] = array(
        'width'               => '400',
        'height'              => '320',
        'playlistsize'        => '',
        'bufferlength'        => '',
        'volume'              => '',
      );
      $defaults['other'] = array(
        'type'                => 'default',
        'repeat'              => 'default',
        'linktarget'          => 'default',
        'stretching'          => 'default',
        'playlist'            => 'default',
        'controlbar'          => 'default',
        'displayclick'        => 'default',
      );
      $defaults['accessibility'] = array(
        'accessible'          => FALSE,
        'accessible_visible'  => TRUE,
      );
      
      $saved_settings = variable_get('swftools_'. WIJERING4_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;
}

/**
 * Implementation of swftools_flashvars hook.
 * Return an array of flashvars.
 */
function wijering4_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 = _wijering4_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'];}

  // Is this file to be streamed? Check for the stream variable being set
  if (isset($vars->othervars['stream'])) {

    // Extract path info from the $file_url variable describing the file
    $info = pathinfo($vars->othervars['file_url']);
    
    // Set the streamer flashvar
    $vars->flashvars['streamer'] = $vars->othervars['stream'];
    
    // Replace the current (non streamed) file url with the stream filename
    $vars->othervars['file_url'] = $info['basename'];
    
  }
  
  // Return an array of flash variables
  return $flashvars;
}

/**
 * This function is called from wijering4_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 _wijering4_settings(). Then we prepare these values for output
 * to html (eg. '1' become 'true') and we unset undefined flashvars to prevent their output.
 *
 */
function _wijering4_flashvars($this_player) {
  // Cache this.
  static $flashvars = array();
  if (!count($flashvars)) {

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

      // Get saved settings for this method.
      $defaults = _wijering4_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];
}

/**
 * flashvar and param option arrays. These are used for options settings in the
 * configuration screen.
 *
 */
function _wijering4_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['bool'] = array('default' => 'default', 'true' => 'true', 'false' => 'false');
  return $options;
}

function wijering4_wijering4_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.
 *
 */
function wijering4_swftools_variable_mapping() {
  return array(
    WIJERING4_MEDIAPLAYER => array(
      'shuffle'             => 'flashvars',
      'fullscreen'          => 'flashvars',
      'autostart'           => 'flashvars',
      'quality'             => 'flashvars',
      'backcolor'           => 'flashvars',
      'frontcolor'          => 'flashvars',
      'lightcolor'          => 'flashvars',
      'screencolor'         => 'flashvars',
      'logo'                => 'flashvars',
      'captions'            => 'flashvars',
      'link'                => 'flashvars',
      'streamscript'        => 'flashvars',
      'skin'                => 'flashvars',
      'playlistsize'        => 'flashvars',
      'bufferlength'        => 'flashvars',
      'volume'              => 'flashvars',
      'type'                => 'flashvars',
      'repeat'              => 'flashvars',
      'linktarget'          => 'flashvars',
      'stretching'          => 'flashvars',
      'playlist'            => 'flashvars',
      'controlbar'          => 'flashvars',
      'displayclick'        => 'flashvars',
    ),
  );
}


/**
 * Implementation of hook_help
 */
function wijering4_help($path, $arg) {
  switch ($path) {
    case 'admin/settings/swftools/wijering4':
      return '<p>'.t('These are the settings for Jeroen Wijering\'s FLV Media Player 4.
                      For details of what each parameter does refer to the
                      <a href="@wijering">JW Player for Flash wiki page</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 actual flashvar name and corresponds to the wiki 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('@wijering' => 'http://code.jeroenwijering.com/trac/wiki/FlashVars')).'</p>';
  }
}


/**
 * Determine if accessible links should be added below the Wijering player.
 * 
 * @param $vars
 *   The array of variables being processed.
 * @param $id
 *   The id for the object being added.
 * @return
 *   An empty string, or markup containing the accessible links.
 */
function wijering4_accessible(&$vars, $id) {
  
  // If the accessible option is set then add links to the page, respecting visibility setting
  if ($vars->flashvars['accessible']) {

    // Add css to enabled hiding of accessible controls
    drupal_add_css(drupal_get_path('module', 'wijering4') . '/wijering4.css');
    
    // Build content
    $return[] = $vars->flashvars['accessible_visible'] ? '<ul>' : '<ul class="wijering4-accessible-hidden">';
    $return[] = "<li><a href=\"javascript:document.getElementById('$id').sendEvent('PLAY');\">" . t('Play/pause') . '</a></li>';
    $return[] = "<li><a href=\"javascript:document.getElementById('$id').sendEvent('MUTE');\">" . t('Mute/unmute') . '</a></li>';
    $return[] = "<li><a href=\"javascript:document.getElementById('$id').sendEvent('STOP');\">" . t('Rewind and stop') . '</a></li>';
    $return[] = '</ul>';
    
    //Implode array to a string
    $return = implode($return, "\n");

    // Unset the accessible parameters from flashvars so they are not output
    unset($vars->flashvars['accessible'], $vars->flashvars['accessible_visible']);
  }
  else {
    $return = '';
  }
  
  // Return the result
  return $return;

}
