<?php
// $Id$

/**
 *  Implementation of hook_mapi_filter()
 */
function mapi_embed_mapi_filter($context, $object) {
	switch ($context) {
		case 'global':
			return array('embed' => '_mapi_embed');
	  case 'teaser':
			return array('embed' => array('_mapi_embed', $object, true));
		case 'page':
			return array('embed' => array('_mapi_embed', $object, false));
	}
}

/**
 *  Implementation of hook_mapi_admin
 */ 
function mapi_embed_mapi_admin($op, $data) {
  switch ($op) {
    case 'settings':
      $form['mapi_allowed_extenal'] = array(
        '#type' => 'textarea',
        '#title' => t('Allowed External Websites'),
        '#description' => t('This determines which foreign websites are allowed during the media file existance checking. These should be on seperate lines, and can contain the wildcard * to specify multiple domains (e.g. youtube.com, *.youtube.com). Note: Simply putting * as a line will allow ANY website. The preceding http:// should not be added.'),
        '#default_value' => variable_get('mapi_allowed_external', '')
      );
      return $form;
  }
}

/**
 *  This allows generic embedding of sites such as youtube.com
 */
function _mapi_embed($details, $object = null, $teaser = false) {
  // need some kind of list to begin with
  if (!count($details)) {
    return '';
  }
    
  // get sources from details
  $sources = (array_key_exists('sources', $details) ? $details['sources'] : $details[0]);
  if (!is_array($sources)) {
    $sources = array($sources);
  }
  $settings = (array_key_exists('settings', $details) ? $details['settings'] : (isset($details[1]) ? $details[1] : array()));

  // check for the correct existance for each of the files.
  foreach ($source as $key => $file) {
    if (is_string($file) && mapi_file_exists($file)) {
      // make sure local ones don't violate the directory locations
      if (realpath($file) !== FALSE && !mapi_file_check_location($file)) {
        unset($source[$key]);
      }
      else {
        $dimensions = mapi_file_dimensions($file);
        $settings['height'] = (isset($settings['height']) ? $settings['height'] : $dimensions['height']);
        $settings['width']  = (isset($settings['width']) ? $settings['width'] : $dimensions['width']);
      }
    }
    // ignore all other contenders
    else {
      unset($source[$key]);
    }
  }
  
  $output = '';
  if (count($source)) {
    $presenter = (isset($details['presenter']) ? array_shift($details['presenter']) : null);
    if (!$presenter && isset($details[2])) {
      $presenter = array_shift($details['presenter']);
    }
    $output = (count($source) > 1 ? mapi_display_playlist($source, $settings, $presenter) : mapi_display($source[0], array('dimensions' => $settings, 'presenter' => $presenter)));
  }
 
  return $output;
}

