<?php
// $Id$

$path = drupal_get_path('module', 'mapi_filter');
require_once($path .'/filter.inc');

/**
 * Implementation of hook_filter()
 */
function mapi_filter_filter($op, $delta = 0, $format = -1, $text = '') {
  switch ($op) {
    case 'list':
      return (array(0 => t('Media Filter')));

    case 'description':
      $output = t('Allows media to be displayed within nodes.') ."\n";
      $output .= t("This filters all HTML related to &lt;img&gt;, &lt;embed&gt; or &lt;object&gt; tags.") ."\n";
      $output .= t('These tags will be converted to the appropriate values, and checked for various XSS problems.') ."\n";
      $output .= t('Filter must be placed after HTML filter to display media correctly.');
      return $output;

    // clean up node details into standard [embed] tag from <img>, <embed> or <object> tags.
		// this tag is completely ignored if mapi_embed is not enabled
    case 'prepare':
      // make sure the media is registered.
      return mapi_filter_prepare($text);

    // processes global filter versions
    case 'process':
      return mapi_filter_process($text, mapi_filter_invoke('global', null));
  }
}

/**
 * Implementation of hook_nodeapi()
 */
function mapi_filter_nodeapi(&$node, $op, $teaser, $page) {
  switch ($op) {
    case 'view':
      $location = ($teaser ? 'teaser' : 'page');

      // handle the general cases of node content
      if (isset($node->content['body'])) {
        $node->content['body']['#value'] = mapi_filter_process($node->content['body']['#value'], mapi_filter_invoke($location, $node));
      }
      break;
  }
}

/**
 * Implementation of hook_filter_tips()
 */
function mapi_filter_filter_tips($delta, $format, $long = false) {
  switch ($delta) {
    case 0:
      if (!$long) {
        return t('Provides a general filter for display of media.');
      }
      else {
        return t('This is a specialized filter, that provides a way for global media to be displayed within any text fed through the filtering mechanism.');
      }
      break;
  }
}

/**
 *  Invokes the hook of the mapi_filter, to load all the filters for a given situation
 *  Returns a list of the functions, indicated by key, for dealing with this contextual information.
 */
function mapi_filter_invoke($context, $object) {
	$selections = array();

	$results = module_invoke_all('mapi_filter', $context, $object);
	if (is_array($results)) {
		// check that the corresponding
		foreach ($results as $key => $value) {
			if (is_array($value)) {
				// check that first function exists
				$func = array_shift($value);
				if (function_exists($func)) {
					$selections[$key] = array_merge(array($func), $value);
				}
			}
			elseif (function_exists($value)) {
				$selections[$key] = array($value);
			}
		}
	}

	return $selections;
}
