<?php
/**
 * @file
 * Custom tokens for Metatag.
 */

/**
 * Implements hook_token_info().
 */
function metatag_token_info() {
  $info = array();

  $info['types']['metatag'] = array(
    'name' => t('Meta tags'),
    'description' => t('Generated by the Metatag module, may not be used to fill in other meta tags.'),
  );

  $metatag_info = metatag_get_info();

  foreach($metatag_info['tags'] as $value) {
    $info['tokens']['metatag'][$value['name']] = array(
      'name' => $value['label'],
      'description' => $value['description']
    );
  }

  if (module_exists('taxonomy')) {
    $info['tokens']['term']['metatag'] = array(
      'name' => t('Metatag.'),
      'description' => t('Metatag.'),
      'type' => 'metatag'
    );
  }

  if (module_exists('node')) {
    $info['tokens']['node']['metatag'] = array(
      'name' => t('Metatag.'),
      'description' => t('Metatag.'),
      'type' => 'metatag'
    );
  }

  return $info;
}

/**
 * Implements hook_tokens().
 */
function metatag_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  $sanitize = !empty($options['sanitize']);

  // Metatag tokens.
  if ($type == 'metatag' && !empty($data['metatag'])) {
    $metatag = $data['metatag'];
    foreach ($tokens as $name => $original) {
      if(isset($metatag[$name])){
        $replacements[$original] = $sanitize ? filter_xss($metatag[$name]) : $metatag[$name];
      }
    }
  }

  // Token tokens.
  if ($type == 'term' && !empty($data['term'])) {
    $term = $data['term'];

    if ($metatag_tokens = token_find_with_prefix($tokens, 'metatag')) {
      $result = metatag_token_generate_array($term, 'taxonomy_term', $term->vocabulary_machine_name);
      $replacements += token_generate('metatag', $metatag_tokens, array('metatag' => $result), $options);
    }
  }

  // Node tokens.
  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];

    if ($metatag_tokens = token_find_with_prefix($tokens, 'metatag')) {
      $result = metatag_token_generate_array($node, 'node', $node->type);
      $replacements += token_generate('metatag', $metatag_tokens, array('metatag' => $result), $options);
    }
  }

  return $replacements;
}

/**
 * Implements hook_tokens_alter().
 *
 * Fix [node:summary] until http://drupal.org/node/1295524 is committed, this
 * code is retrofitted from the patches in that issue.
 */
function metatag_tokens_alter(array &$replacements, array $context) {
  // Only proceed if this is working on a node.
  if ($context['type'] == 'node' && !empty($context['data']['node'])) {
    // Loop through each of the tokens.
    foreach ($context['tokens'] as $name => $original) {
      // Only deal with the 'node:summary' token, that's the one being fixed.
      if ($name == 'summary') {
        // A shortcut to the node being processed.
        $node = $context['data']['node'];

        // Work out the langcode being used.
        if (isset($context['options']['language'])) {
          $langcode = $context['options']['language']->language;
        }
        else {
          $langcode = NULL;
        }

        // Decide whether the string needs to be sanitized.
        $sanitize = !empty($context['options']['sanitize']);

        if ($items = field_get_items('node', $node, 'body', $langcode)) {
          $instance = field_info_instance('node', 'body', $node->type);
          $field_langcode = field_language('node', $node, 'body', $langcode);

          // If the summary is not empty, use it.
          if (!empty($items[0]['summary'])) {
            $output = $sanitize ? _text_sanitize($instance, $field_langcode, $items[0], 'summary') : $items[0]['summary'];
          }

          // Attempt to provide a suitable version of the 'body' field.
          else {
            $output = $sanitize ? _text_sanitize($instance, $field_langcode, $items[0], 'value') : $items[0]['value'];
            // A summary was requested.
            if ($name == 'summary') {
              if (isset($instance['display']['teaser']['settings']['trim_length'])) {
                $trim_length = $instance['display']['teaser']['settings']['trim_length'];
              }
              else {
                // Use default value.
                $trim_length = NULL;
              }
              // Generate an optionally trimmed summary of the body field.
              $output = text_summary($output, $instance['settings']['text_processing'] ? $items[0]['format'] : NULL, $trim_length);
            }
          }

          // Override the original value.
          $replacements[$original] = $output;
        }
      }
    }
  }
}

/**
 * Generate an array of meta tags for a given entity.
 */
function metatag_token_generate_array($entity, $entity_type, $bundle) {
  if (metatag_entity_supports_metatags($entity_type, $bundle)) {
    $token_type = token_get_entity_mapping('entity', $entity_type);

    $instance = "{$entity_type}:{$bundle}";
    $options = array();
    $options['token data'][$token_type] = $entity;
    $options['entity'] = $entity;

    $metatags = isset($entity->metatags) ? $entity->metatags : array();
    $metatags += metatag_config_load_with_defaults($instance);

    $result = array();
    foreach ($metatags as $metatag => $data) {
      if ($metatag_instance = metatag_get_instance($metatag, $data)) {
        $result[$metatag] = $metatag_instance->getValue($options);
      }
    }
    return $result;
  }

  return NULL;
}
