<?php

/**
 * Implements hook_filter_info().
 *
 * Adds the Token filter to the textx format options.
 */
function token_filter_filter_info() {
  $filters['filter_tokens'] = array(
    'title' => t('Replace tokens'),
    'description' => t('The usage of this filter should be restricted to trusted users only as tokens with sensitive data could be exposed.'),
    'process callback' => '_token_filter_filter_tokens',
    'tips callback' => '_token_filter_filter_tips',
    'cache' => FALSE,
  );
  return $filters;
}

/**
 * Filter process callback for the token input filter.
 */
function _token_filter_filter_tokens($text, $filter, $format, $langcode, $cache, $cache_id) {
  $data = array();
  $options = array();

  // Attempt to fetch the entity that is being viewed via a backtrace to the
  // field_attach_view($entity_type, $entity) function and parameters §if found.
  $backtrace = debug_backtrace();
  foreach ($backtrace as $caller) {
    if ($caller['function'] == 'field_attach_view') {
      $entity_type = $caller['args'][0];
      $entity = $caller['args'][1];
      $token_type = token_get_entity_mapping('entity', $entity_type);
      $data[$token_type] = $entity;
      // Use the proper language code that field_attach_view was called with.
      if ($langcode = $caller['args'][3]) {
        $language_list = language_list();
        if (!empty($language_list[$langcode])) {
          $options['language'] = $language_list[$langcode];
        }
      }
      break;
    }
    elseif ($caller['function'] == '_drupal_bootstrap_full' || $caller == 'menu_execute_active_handler') {
      // There is no point in going back this far, so just stop.
      break;
    }
  }

  return token_replace($text, $data, $options);
}

/**
 * Filter tip callback for the token input filter.
 */
function _token_filter_filter_tips($filter, $format, $long = FALSE) {
  if ($long) {
    $output = t('Global tokens will be replaced with their respective token values (e.g. [site:name] or [current-page:title]). The following is a list of the tokens that are available:');
    $output .= theme('token_tree', array('click_insert' => FALSE));
    return $output;
  }
  else {
    return t('Global tokens will be replaced with their respective token values (e.g. [site:name] or [current-page:title]).');
  }
}
