<?php

/**
 * @todo Add revisionable support for metatag data.
 * @todo Add multilingual support for metatag data - is this even needed?
 */

/**
 * Implements hook_theme().
 */
function metatag_theme() {
  $info['metatag'] = array(
    'render element' => 'element',
    'file' => 'metatag.theme.inc',
  );
  $info['metatag_http_equiv'] = array(
    'render element' => 'element',
    'file' => 'metatag.theme.inc',
  );
  $info['metatag_link_rel'] = array(
    'render element' => 'element',
    'file' => 'metatag.theme.inc',
  );
  $info['metatag_link_rev'] = array(
    'render element' => 'element',
    'file' => 'metatag.theme.inc',
  );

  return $info;
}

/**
 * Implements hook_ctools_plugin_api().
 */
function metatag_ctools_plugin_api($owner, $api) {
  if ($owner == 'metatag' && $api == 'metatag') {
    return array('version' => 1);
  }
}

/**
 * Implements hook_hook_info().
 */
function metatag_hook_info() {
  $hooks = array(
    'metatag_info',
    'metatag_info_alter',
    'metatag_config_instance_info',
    'metatag_config_instance_info_alter',
    'metatag_config_load',
    'metatag_config_presave',
    'metatag_config_insert',
    'metatag_config_update',
    'metatag_config_delete',
    'metatag_load',
    'metatag_insert',
    'metatag_update',
    'metatag_delete',
    'metatag_alter',
    'metatag_config_default',
    'metatag_config_default_alter',
    'metatag_api',
  );

  return array_fill_keys($hooks, array('group' => 'metatag'));
}

/**
 * Implements hook_permisson().
 */
function metatag_permission() {
  $permissions['administer meta tags'] = array(
    'title' => t('Administer meta tags.'),
    'restrict access' => TRUE,
  );
  $permissions['edit meta tags'] = array(
    'title' => t('Edit meta tags.'),
  );
  return $permissions;
}

/**
 * Implements hook_menu().
 */
function metatag_menu() {
  $items['admin/config/search/metatags'] = array(
    'title' => 'Meta tags',
    'description' => 'Configure meta tag defaults.',
    'page callback' => 'metatag_config_overview',
    'access arguments' => array('administer meta tags'),
    'file' => 'metatag.admin.inc',
  );
  $items['admin/config/search/metatags/config'] = array(
    'title' => 'Defaults',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/config/search/metatags/config/add'] = array(
    'title' => 'Add a meta tag default',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('metatag_config_add_form'),
    'access arguments' => array('administer meta tags'),
    'file' => 'metatag.admin.inc',
    'type' => MENU_LOCAL_ACTION,
  );
  $items['admin/config/search/metatags/config/%metatag_config'] = array(
    'title callback' => 'metatag_config_title',
    'title arguments' => array(5),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('metatag_config_edit_form', 5),
    'access arguments' => array('administer meta tags'),
    'file' => 'metatag.admin.inc',
  );
  $items['admin/config/search/metatags/config/%metatag_config/edit'] = array(
    'title' => 'Edit',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/config/search/metatags/config/%metatag_config/enable'] = array(
    'title' => 'Enable',
    'page callback' => 'metatag_config_enable',
    'page arguments' => array(5),
    'access callback' => 'metatag_config_access',
    'access arguments' => array('enable', 5),
    'file' => 'metatag.admin.inc',
  );
  $items['admin/config/search/metatags/config/%metatag_config/disable'] = array(
    'title' => 'Disable',
    'page callback' => 'metatag_config_disable',
    'page arguments' => array(5),
    'access callback' => 'metatag_config_access',
    'access arguments' => array('disable', 5),
    'file' => 'metatag.admin.inc',
  );
  $items['admin/config/search/metatags/config/%metatag_config/revert'] = array(
    'title' => 'Revert',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('metatag_config_delete_form', 5),
    'access callback' => 'metatag_config_access',
    'access arguments' => array('revert', 5),
    'file' => 'metatag.admin.inc',
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/config/search/metatags/config/%metatag_config/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('metatag_config_delete_form', 5),
    'access callback' => 'metatag_config_access',
    'access arguments' => array('delete', 5),
    'file' => 'metatag.admin.inc',
  );
  $items['admin/config/search/metatags/config/%metatag_config/export'] = array(
    'title' => 'Export',
    'page callback' => 'metatag_config_export_form',
    'page arguments' => array(5),
    'access arguments' => array('administer meta tags'),
    'file' => 'metatag.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );

  return $items;
}

/**
 * Implements hook_flush_caches().
 */
function metatag_flush_caches() {
  return array('cache_metatag');
}

/**
 * Load a metatag configuration record with all the defaults merged in.
 *
 * For example, given the configuration instance 'node:article', this function
 * will load the configuration records for 'node:article', then 'node', and
 * then finally 'global', with each attempt using an array merge.
 *
 * The levels of defaults is arranged by splitting the $instance variable by
 * the colon character, and always using a 'global' instance at the end.
 */
function metatag_config_load_with_defaults($instance, $include_global = TRUE) {
  $defaults = &drupal_static(__FUNCTION__, array());

  // Statically cache defaults since they can include multiple levels.
  $cid = "config:{$instance}" . ($include_global ? ':withglobal' : ':withoutglobal');
  if (!isset($defaults[$cid])) {
    if ($cache = cache_get($cid, 'cache_metatag')) {
      $defaults[$cid] = $cache->data;
    }
    else {
      $defaults[$cid] = array();
      $instances = metatag_config_get_parent_instances($instance, $include_global);
      $configs = metatag_config_load_multiple($instances);
      foreach ($instances as $key) {
        // Ignore disabled configurations.
        if (!isset($configs[$key]) || !empty($configs[$key]->disabled)) {
          continue;
        }

        // Add config to the defaults array.
        $defaults[$cid] += $configs[$key]->config;
      }

      cache_set($cid, $defaults[$cid], 'cache_metatag');
    }
  }

  return $defaults[$cid];
}

/**
 * Load a metatag configuration record.
 */
function metatag_config_load($instance) {
  $results = metatag_config_load_multiple(array($instance));
  return !empty($results[$instance]) ? $results[$instance] : FALSE;
}

/**
 * Load multiple metatag configuration records.
 */
function metatag_config_load_multiple(array $instances) {
  ctools_include('export');
  return ctools_export_load_object('metatag_config', 'names', $instances);
}

/**
 * Save a metatag configuration record to the database.
 */
function metatag_config_save($config) {
  $config->is_new = empty($config->cid);

  // Allow modules to alter the configuration before it is saved.
  module_invoke_all('metatag_config_presave', $config);

  if ($config->is_new) {
    drupal_write_record('metatag_config', $config);
    module_invoke_all('metatag_config_insert', $config);
  }
  else {
    drupal_write_record('metatag_config', $config, array('cid'));
    module_invoke_all('metatag_config_update', $config);
  }

  unset($config->is_new);

  // Clear any caches.
  metatag_config_cache_clear();
}

/**
 * Delete a metatag configuration record.
 */
function metatag_config_delete($instance) {
  db_delete('metatag_config')
    ->condition('instance', $instance)
    ->execute();

  // Clear any caches.
  metatag_config_cache_clear();
}

/**
 * Clear the metatag configuration cache.
 */
function metatag_config_cache_clear() {
  cache_clear_all('*', 'cache_metatag', TRUE);
  drupal_static_reset('metatag_config_load_with_defaults');
  drupal_static_reset('metatag_entity_has_metatags');
  drpual_static_reset('metatag_entity_supports_metatags');
  ctools_include('export');
  ctools_export_load_object_reset('metatag_config');
}

function metatag_metatags_load($type, $id) {
  $metatags = metatag_metatags_load_multiple($type, array($id));
  return !empty($metatags) ? reset($metatags) : array();
}

function metatag_metatags_load_multiple($type, array $ids) {
  // Double check entity IDs are numeric thanks to Entity API module.
  $ids = array_filter($ids, 'is_numeric');
  if (empty($ids)) {
    return array();
  }

  // Also need to check if the metatag table exists since this condition could
  // fire before the table has been installed yet.
  $table_exists = &drupal_static(__FUNCTION__);
  if (!isset($table_exists)) {
    $table_exists = db_table_exists('metatag');
  }
  if (!$table_exists) {
    return array();
  }

  $metatags = db_query("SELECT entity_id, data FROM {metatag} WHERE entity_type = :type AND entity_id IN (:ids)", array(
    ':type' => $type,
    ':ids' => $ids,
  ))->fetchAllKeyed();
  $metatags = array_map('unserialize', $metatags);
  return $metatags;
}

function metatag_metatags_save($type, $id, $metatags) {
  // Check that $id is numeric because of Entity API and string IDs.
  if (!is_numeric($id)) {
    return;
  }

  // Allow other modules to alter the metatags prior to saving.
  foreach (module_implements('metatag_presave') as $module) {
    $function = "{$module}_metatag_presave";
    $function($metatags, $type, $id);
  }

  if (empty($metatags)) {
    // If the data array is empty, there is no data to actually save, so
    // just delete the record from the database.
    db_delete('metatag')
      ->condition('entity_type', $type)
      ->condition('entity_id', $id)
      ->execute();
  }
  else {
    // Otherwise save the data for this entity.
    db_merge('metatag')
      ->key(array(
        'entity_type' => $type,
        'entity_id' => $id,
      ))
      ->fields(array(
        'data' => serialize($metatags),
      ))
      ->execute();
  }

  // Clear cached data.
  metatag_metatags_cache_clear($type, $id);
}

function metatag_metatags_delete($type, $id) {
  return metatag_metatags_delete_multiple($type, array($id));
}

function metatag_metatags_delete_multiple($type, array $ids) {
  // Double check entity IDs are numeric thanks to Entity API module.
  $ids = array_filter($ids, 'is_numeric');

  if ($metatags = metatag_metatags_load_multiple($type, $ids)) {
    $transaction = db_transaction();
    try {
      // Let other modules know about the metatags being deleted.
      module_invoke_all('metatag_metatags_delete', $type, $ids);

      db_delete('metatag')
        ->condition('entity_type', $type)
        ->condition('entity_id', $ids, 'IN')
        ->execute();

      // Clear cached data.
      metatag_metatags_cache_clear($type, $ids);
    }
    catch (Exception $e) {
      $transaction->rollback();
      watchdog_exception('metatag', $e);
      throw $e;
    }
  }
}

function metatag_metatags_cache_clear($type, $id = NULL) {
  if (empty($id)) {
    cache_clear_all("output:$type", 'cache_metatag', TRUE);
  }
  else {
    $ids = (array) $id;
    foreach ($ids as $id) {
      cache_clear_all("output:$type:$id", 'cache_metatag', TRUE);
    }
  }
}

/**
 * Implements hook_entity_load().
 */
function metatag_entity_load($entities, $type) {
  $metatags = metatag_metatags_load_multiple($type, array_keys($entities));
  foreach ($entities as $id => $entity) {
    $entities[$id]->metatags = isset($metatags[$id]) ? $metatags[$id] : array();
  }
}

/**
 * Implements hook_entity_insert().
 */
function metatag_entity_insert($entity, $entity_type) {
  if (isset($entity->metatags)) {
    list($id) = entity_extract_ids($entity_type, $entity);
    metatag_metatags_save($entity_type, $id, $entity->metatags);
  }
}

/**
 * Implements hook_entity_update().
 */
function metatag_entity_update($entity, $entity_type) {
  list($id) = entity_extract_ids($entity_type, $entity);

  if (isset($entity->metatags)) {
    metatag_metatags_save($entity_type, $id, $entity->metatags);
  }
  else {
    // Still ensure the meta tag output is cached.
    metatag_metatags_cache_clear($entity_type, $id);
  }
}

/**
 * Implements hook_entity_delete().
 */
function metatag_entity_delete($entity, $entity_type) {
  list($id) = entity_extract_ids($entity_type, $entity);
  metatag_metatags_delete($entity_type, $id);
}

/**
 * Implements hook_field_attach_delete_revision().
 */
function metatag_field_attach_delete_revision($entity_type, $entity) {
  //list($entity_id, $revision_id) = entity_extract_ids($entity_type, $entity);
}

/**
 * Implements hook_entity_view().
 */
function metatag_entity_view($entity, $entity_type, $view_mode, $langcode) {
  if (!metatag_entity_has_metatags($entity_type, $entity)) {
    return;
  }

  list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  $instance = "{$entity_type}:{$bundle}";

  if (_metatag_entity_is_page($entity_type, $entity)) {
    $cid_parts = array(
      // @todo Why is this commented out?
      //'view_mode' => $view_mode,
      'langcode' => $langcode,
      'url' => $GLOBALS['base_url'] . '/' . current_path(),
    );
    $cid = "output:{$entity_type}:{$entity_id}:" . hash('sha256', serialize($cid_parts));

    if ($cache = cache_get($cid, 'cache_metatag')) {
      $entity->content['metatags'] = $cache->data;
    }
    else {
      $metatags = isset($entity->metatags) ? $entity->metatags : array();

      // Build options for meta tag rendering.
      $options = array(
        'entity' => $entity,
        'entity_type' => $entity_type,
        'view_mode' => $view_mode,
      );

      // Ensure we actually pass a language object rather than language code.
      $languages = language_list();
      if (isset($langcode) && isset($languages[$langcode])) {
        $options['language'] = $languages[$langcode];
      }

      // Reload the entity object from cache as it may have been altered.
      $token_type = token_get_entity_mapping('entity', $entity_type);
      $entities = entity_load($entity_type, array($entity_id));
      $options['token data'][$token_type] = $entities[$entity_id];
      $options['entity'] = $entities[$entity_id];

      // Render the metatags and save to the cache.
      $entity->content['metatags'] = metatag_metatags_view($instance, $metatags, $options);
      cache_set($cid, $entity->content['metatags'], 'cache_metatag');
    }

    // We need to register the term's metatags, so we can later fetch them.
    // @see metatag_page_build().
    metatag_page_set_metatags($instance, $entity->content['metatags']);
  }
}

/**
 * Build a renderable array of meta tag output.
 *
 * @param string $instance
 *   The configuration instance key of the meta tags to use, e.g.
 *   "node:article".
 * @param array $metatags
 *   An arary of meta tag data.
 * @param array $options
 *   (optional) An array of options including the following keys and values:
 *   - language: A language object.
 *   - token data: An array of data to pass into token_replace() during
 *                 meta tag value generation.
 */
function metatag_metatags_view($instance, array $metatags = array(), array $options = array()) {
  $output = array();
  $metatags += metatag_config_load_with_defaults($instance);

  // Convert language codes to a language object.
  if (isset($options['language']) && is_string($options['language'])) {
    $languages = language_list();
    $options['language'] = isset($languages[$options['language']]) ? $languages[$options['language']] : NULL;
  }

  foreach ($metatags as $metatag => $data) {
    if ($metatag_instance = metatag_get_instance($metatag, $data)) {
      $output[$metatag] = $metatag_instance->getElement($options);
    }
  }

  drupal_alter('metatag_metatags_view', $output);

  return $output;
}

function metatag_metatags_values($instance, array $metatags = array(), array $options = array()) {
  $values = array();
  $metatags += metatag_config_load_with_defaults($instance);

  // Convert language codes to a language object.
  if (isset($options['language']) && is_string($options['language'])) {
    $languages = language_list();
    $options['language'] = isset($languages[$options['language']]) ? $languages[$options['language']] : NULL;
  }

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

  return array_filter($values, 'drupal_strlen');
}

/**
 * Build a FAPI array for editing meta tags.
 *
 * @param array $form
 *   The current FAPI array.
 * @param string $instance
 *   The configuration instance key of the metatags to use, e.g. "node:article".
 * @param array $metatags
 *   An arary of metatag data.
 * @param array $options
 *   (optional) An array of options including the following keys and values:
 *   - token types: An array of token types to be passed to theme_token_tree().
 */
function metatag_metatags_form(array &$form, $instance, array $metatags = array(), array $options = array()) {
  $info = metatag_get_info();
  if (empty($info['tags'])) {
    return;
  }

  // Merge in the default options.
  $options += array(
    'token types' => array(),
    'defaults' => metatag_config_load_with_defaults($instance),
  );

  $form['metatags'] = array(
    '#type' => 'fieldset',
    '#title' => t('Meta tags'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#tree' => TRUE,
    '#access' => user_access('edit meta tags') || user_access('administer meta tags'),
    '#weight' => 40,
    '#attributes' => array(
      'class' => array('metatags-form'),
    ),
    '#metatag_defaults' => $options['defaults'],
  );

  // Only support vertical tabs if there is a vertical tab element.
  foreach (element_children($form) as $key) {
    if (isset($form[$key]['#type']) && $form[$key]['#type'] == 'vertical_tabs') {
      $form['metatags']['#group'] = $key;
      $form['metatags']['#attached']['js']['vertical-tabs'] = drupal_get_path('module', 'metatag') . '/metatag.vertical-tabs.js';
      break;
    }
  }

  // Merge in the default meta tag configurations.
  $metatags += $options['defaults'];

  // Build the form for each metatag.
  foreach ($info['tags'] as $metatag => $metatag_info) {
    // @todo Replace context matching with hook_metatag_access().
    if (isset($options['context']) && isset($metatag_info['context'])) {
      if (!in_array($options['context'], $metatag_info['context'])) {
        continue;
      }
    }

    $metatag_instance = metatag_get_instance($metatag, isset($metatags[$metatag]) ? $metatags[$metatag] : array());
    if (empty($metatag_instance)) {
      continue;
    }

    // Get the form element from the meta tag class.
    $metatag_form = $metatag_instance->getForm($options);

    // Add a default value form element.
    if (isset($options['defaults'][$metatag]['value'])) {
      $metatag_form['default'] = array(
        '#type' => 'hidden',
        '#value' => $options['defaults'][$metatag]['value'],
      );
    }

    if (!empty($metatag_info['group'])) {
      $group_key = $metatag_info['group'];
      if (isset($info['groups'][$group_key]['label']) && !isset($form['metatags'][$group_key])) {
        $group = $info['groups'][$group_key] + array('form' => array(), 'description' => NULL);
        $form['metatags'][$group_key] = $group['form'] + array(
          '#type' => 'fieldset',
          '#title' => check_plain($group['label']),
          '#description' => filter_xss($group['description']),
          '#collapsible' => TRUE,
          '#collapsed' => TRUE,
        );
      }
      $form['metatags'][$group_key][$metatag] = $metatag_form + array('#parents' => array('metatags', $metatag));
    }
    else {
      $form['metatags'][$metatag] = $metatag_form;
    }
  }

  // Show the list of available tokens.
  $form['metatags']['tokens'] = array(
    '#theme' => 'token_tree',
    '#token_types' => $options['token types'],
    '#weight' => 100,
    '#dialog' => TRUE,
  );

  // Add a submit handler to compare the submitted values against the deafult
  // values.
  $form += array('#submit' => array());
  array_unshift($form['#submit'], 'metatag_metatags_form_submit');
}

/**
 * Form submit handler; unset meta tag values that equal their default values.
 */
function metatag_metatags_form_submit($form, &$form_state) {
  $defaults = $form['metatags']['#metatag_defaults'];
  $values = &$form_state['values']['metatags'];
  metatag_filter_values_from_defaults($values, $defaults);
}

/**
 * Implements hook_field_extra_fields().
 */
function metatag_field_extra_fields() {
  $extra = array();
  foreach (entity_get_info() as $entity_type => $entity_info) {
    foreach (array_keys($entity_info['bundles']) as $bundle) {
      if (metatag_entity_supports_metatags($entity_type, $bundle)) {
        $extra[$entity_type][$bundle]['form']['metatags'] = array(
          'label' => t('Meta tags'),
          'description' => t('Meta tag module form elements.'),
          'weight' => 40,
        );
      }
    }
  }
  return $extra;
}

/**
 * Check if an individual entity has meta tags defined, or has defaults.
 *
 * @param string $entity_type
 *   An entity type.
 * @param object $entity
 *   An entity object.
 *
 * @return boolean
 *   TRUE or FALSE if the entity should have a form for or process meta tags.
 */
function metatag_entity_has_metatags($entity_type, $entity) {
  // If an entity has custom meta tags assigned, then we should return TRUE.
  if (!empty($entity->metatags)) {
    return TRUE;
  }

  // Otherwise, check to see if there exists any enabed configuration for
  // either the entity type, or bundle (even if the configuration is empty).
  // If no configuration exists, then we should not be displaying the meta tag
  // forms or processing meta tags on entity view.
  $config_exists = &drupal_static(__FUNCTION__, array());
  list( , , $bundle) = entity_extract_ids($entity_type, $entity);
  $instance = "{$entity_type}:{$bundle}";
  if (!isset($config_exists[$instance])) {
    $config_exists[$instance] = NULL;
    $instances = metatag_config_get_parent_instances($instance, FALSE);
    $configs = metatag_config_load_multiple($instances);
    foreach ($instances as $key) {
      if (!empty($configs[$key]) && empty($configs[$key]->disabled)) {
        $config_exists[$instance] = TRUE;
      }
    }
  }

  return isset($config_exists[$instance]);
}

function metatag_entity_supports_metatags($entity_type = NULL, $bundle = NULL) {
  $types = &drupal_static(__FUNCTION__);

  if (!isset($types)) {
    $types = array();
    foreach (entity_get_info() as $entity_type_key => $entity_info) {
      if (!isset($entity_info['metatags'])) {
        // By default allow entities that have fields or have paths.
        $entity_info['metatags'] = !empty($entity_info['uri callback']) || !empty($entity_info['fieldable']);
      }
      if (empty($entity_info['metatags'])) {
        $types[$entity_type_key] = FALSE;
        continue;
      }
      $types[$entity_type_key] = array();
      foreach ($entity_info['bundles'] as $bundle_key => $bundle_info) {
        $types[$entity_type_key][$bundle_key] = !isset($bundle_info['metatags']) || !empty($bundle_info['metatags']);
      }
    }
  }

  if (isset($entity_type) && isset($bundle)) {
    return isset($types[$entity_type][$bundle]) ? $types[$entity_type][$bundle] : FALSE;
  }
  elseif (isset($entity_type)) {
    return isset($types[$entity_type]) ? ($types[$entity_type] !== FALSE) : FALSE;
  }

  return $types;
}

/**
 * Implements hook_entity_info_alter().
 */
function metatag_entity_info_alter(&$info) {
  $defaults['node'] = array(
    'path' => 'node/%node',
  );
  $defaults['taxonomy_term'] = array(
    'path' => 'taxonomy/term/%taxonomy_term',
  );
  if (module_exists('forum') && ($vid = variable_get('forum_nav_vocabulary', 0)) && $vocabulary = taxonomy_vocabulary_load($vid)) {
    $defaults['taxonomy_term']['bundles'][$vocabulary->machine_name]['path'] = 'forum/%taxonomy_term';
  }
  $defaults['user'] = array(
    'path' => 'user/%user',
  );
  $defaults['comment'] = array(
    'metatags' => FALSE,
  );

  foreach ($defaults as $key => $entity_defaults) {
    if (isset($info[$key])) {
      $info[$key] = drupal_array_merge_deep($entity_defaults, $info[$key]);
    }
  }
}

/**
 * Given a path determine if it is an entity default path.
 *
 * @param $path
 *   The internal path. The id of the entity should be in the string as '[id]'.
 * @return
 *   An array with the entity type and the loaded entity object.
 */
function metatag_load_entity_from_path($path) {
  $entity_paths = &drupal_static(__FUNCTION__);
  $result = FALSE;

  if (!isset($entity_paths)) {
    $entity_paths = array();
    foreach (entity_get_info() as $entity_type => $entity_info) {
      if (isset($entity_info['default path'])) {
        $default_path = $entity_info['default path'];
        $default_path = preg_quote($default_path, '/');
        $default_path = str_replace('\[id\]', '(\d+)', $default_path);
        $entity_paths[$entity_type] = $default_path;
      }
    }
  }

  foreach ($entity_paths as $entity_type => $default_path) {
    if (preg_match("/^{$default_path}$/", $path, $matches)) {
      if ($entity = entity_load($entity_type, array($matches[1]))) {
        $result = array('entity_type' => $entity_type, 'entity' => reset($entity));
      }
      break;
    }
  }

  drupal_alter('metatag_load_entity_from_path', $path, $result);
  return $result;
}

/**
 * Add meta tags to be added later with metatag_page_build().
 *
 * @param string $instance
 *   The configuration instance key of the meta tags, e.g. "node:article".
 * @param array $metatags
 *   An array of meta tags from metatag_metatags_view().
 */
function metatag_page_set_metatags($instance, $metatags) {
  $page_metatags = &drupal_static(__FUNCTION__, array());
  $page_metatags[$instance] = $metatags;
}

/**
 * Retrieve the array of met tags to be added with metatag_page_build().
 */
function metatag_page_get_metatags() {
  // @todo Add alter to this result?
  return drupal_static('metatag_page_set_metatags', array());
}

/**
 * Implements hook_page_build().
 */
function metatag_page_build(&$page) {
  // For some reason with Overlay enabled we get an empty $page, so just fail
  // this case.
  if (!isset($page['content'])) {
    return;
  }

  // Load the metatags render array in before any page content so that more
  // more specific meta tags in the page content can override these meta tags.
  $page['content'] = array('metatags' => metatag_page_get_metatags()) + $page['content'];

  if (drupal_is_front_page()) {
    $page['content']['metatags']['global:frontpage'] = metatag_metatags_view('global:frontpage', array());
  }
  elseif (!path_is_admin(current_path())) {
    // Do not output the global metatags when on an administration path.
    $page['content']['metatags']['global'] = metatag_metatags_view('global', array());
  }
}

/**
 * Returns whether the current page is the page of the passed in entity.
 *
 * @param $type
 *    The entity type; e.g. 'node' or 'user'.
 * @param $entity
 *    The entity object.
 *
 * @return
 *   TRUE if the current page is the page of the specified entity, or FALSE
 *   otherwise.
 */
function _metatag_entity_is_page($type, $entity) {
  $uri = entity_uri($type, $entity);
  return !empty($uri['path']) && current_path() == $uri['path'];
}

/**
 * Implements hook_field_attach_rename_bundle().
 */
function metatag_field_attach_rename_bundle($entity_type, $bundle_old, $bundle_new) {
  $instance_old = $entity_type . ':' . $bundle_old;
  $instance_new = $entity_type . ':' . $bundle_new;
  if ($config = metatag_config_load($instance_old)) {
    $config->instance = $instance_new;
    metatag_config_save($config);
    metatag_config_delete($instance_old);
  }
}

/**
 * Implements hook_field_attach_delete_bundle().
 */
function metatag_field_attach_delete_bundle($entity_type, $bundle) {
  $instance = $entity_type . ':' . $bundle;
  metatag_config_delete($instance);
}

/**
 * Implements hook_field_attach_form().
 */
function metatag_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  if (!metatag_entity_has_metatags($entity_type, $entity)) {
    return;
  }

  list($entity_id, $revision_id, $bundle) = entity_extract_ids($entity_type, $entity);
  $instance = "{$entity_type}:{$bundle}";

  $metatags = isset($entity->metatags) ? $entity->metatags : array();
  $options['token types'] = array(token_get_entity_mapping('entity', $entity_type));
  $options['context'] = $entity_type;

  // @todo Remove metatag_form_alter() when http://drupal.org/node/1284642 is fixed in core.
  //metatag_metatags_form($form, $instance, $metatags, $options);

  $form['#metatags'] = array(
    'instance' => $instance,
    'metatags' => $metatags,
    'options' => $options,
  );
}

/**
 * Implements hook_form_alter().
 *
 * @todo Remove this when http://drupal.org/node/1284642 is fixed in core.
 */
function metatag_form_alter(&$form, $form_state, $form_id) {
  if (!empty($form['#metatags']) && !isset($form['metatags'])) {
    extract($form['#metatags']);
    metatag_metatags_form($form, $instance, $metatags, $options);
    unset($form['#metatags']);
  }
}

/**
 * Get the meta tag information array of a meta tag.
 *
 * @param $metatag
 *   The meta tag name, e.g. description, for which the info shall be returned,
 *   or NULL to return an array with info about all meta tags.
 */
function metatag_get_info($type = NULL, $name = NULL) {
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['metatag_info'] = &drupal_static(__FUNCTION__);
  }
  $info = &$drupal_static_fast['metatag_info'];

  if (!isset($info)) {
    // hook_metatag_info() includes translated strings, so each language is cached
    // separately.
    $cid = 'info:' . $GLOBALS['language']->language;

    if ($cache = cache_get($cid, 'cache_metatag')) {
      $info = $cache->data;
    }
    else {
      $info = module_invoke_all('metatag_info');
      $info += array('tags' => array(), 'groups' => array());

      // Merge in default values.
      foreach ($info['tags'] as $key => $data) {
        $info['tags'][$key] += array(
          // Merge in default values.
          'name' => $key,
          'class' => 'DrupalTextMetaTag',
        );
      }

      // Let other modules alter the entity info and then cache it.
      drupal_alter('metatag_info', $info);
      cache_set($cid, $info, 'cache_metatag');
    }
  }

  if (isset($type) && isset($name)) {
    return isset($info[$type][$name]) ? $info[$type][$name] : FALSE;
  }
  elseif (isset($type)) {
    return isset($info[$type]) ? $info[$type] : array();
  }
  else {
    return $info;
  }
}

function metatag_get_instance($metatag, array $data = array()) {
  $info = metatag_get_info('tags', $metatag);
  if (!empty($info['class']) && class_exists($info['class'])) {
    $class = $info['class'];
    return new $class($info, $data);
  }
  else {
    trigger_error("Failed to load class {$info['class']} for metatag $metatag.", E_USER_ERROR);
  }
}

/**
 * Return the string value of a meta tag.
 *
 * @param $metatag
 *   The meta tag string.
 * @param $data
 *   The array of data for the meta tag class instance.
 * @param $options
 *   An optional array of additional options to pass to the getValue() method
 *   of the meta tag class instance.
 *   - raw: A boolean if TRUE will not perform token replacement.
 *
 * @return
 *   A string value.
 */
function metatag_get_value($metatag, array $data, array $options = array()) {
  $value = '';
  if ($metatag_instance = metatag_get_instance($metatag, $data)) {
    $value = $metatag_instance->getValue($options);
  }
  return $value;
}

/**
 * Set a variable to be altered in metatag_preprocess_html().
 *
 * @see metatag_get_preprocess_variables()
 * @see metatag_preprocess_html()
 * @see metatag_preprocess_maintenance_page()
 */
function metatag_set_preprocess_variable($hook, $variable, $value) {
  $variables = &drupal_static(__FUNCTION__, array());
  $variables[$hook][$variable] = $value;
}

/**
 * Return an array of variables to be altered in preprocess functions.
 *
 * @see metatag_set_preprocess_variable()
 * @see metatag_preprocess_html()
 * @see metatag_preprocess_maintenance_page()
 */
function metatag_get_preprocess_variables($hook) {
  $variables = drupal_static('metatag_set_preprocess_variable', array());
  return isset($variables[$hook]) ? $variables[$hook] : array();
}

/**
 * Implements hook_preprocess_html().
 */
function metatag_preprocess_html(&$variables) {
  foreach (metatag_get_preprocess_variables('html') as $variable => $value) {
    $variables[$variable] = $value;
  }
}

/**
 * Implements hook_preprocess_maintenance_page().
 */
function metatag_preprocess_maintenance_page(&$variables) {
  foreach (metatag_get_preprocess_variables('html') as $variable => $value) {
    $variables[$variable] = $value;
  }
}

/**
 * Implements hook_html_head_alter().
 */
function metatag_html_head_alter(&$elements) {
  // Remove duplicate link tags if found.
  $metatags = metatag_get_info('tags');
  foreach (array_keys($metatags) as $name) {
    if (!isset($elements['metatag_' . $name]) || $elements['metatag_' . $name]['#tag'] != 'link') {
      // Only check for link tags added by the metatags module.
      continue;
    }
    foreach (array_keys($elements) as $key) {
      if (strpos($key, 'drupal_add_html_head_link:' . $name . ':') === 0) {
        unset($elements[$key]);
        break;
      }
    }
  }

  // Remove the default generator meta tag.
  unset($elements['system_meta_generator']);
}

function metatag_metatag_get_form($metatag, array $data = array(), array $options = array()) {
  $instance = metatag_get_instance($metatag, $data);
  return $instance->getForm($options);
}

function metatag_config_instance_info($instance = NULL) {
  global $language;

  $info = &drupal_static(__FUNCTION__);

  // hook_metatag_info() includes translated strings, so each language is cached
  // separately.
  $cid = 'metatag:config:instance:info:' . $language->language;

  if (!isset($info)) {
    if ($cache = cache_get($cid, 'cache_metatag')) {
      $info = $cache->data;
    }
    else {
      $info = module_invoke_all('metatag_config_instance_info');
      drupal_alter('metatag_config_instance_info', $info);
      cache_set($cid, $info, 'cache_metatag');
    }
  }

  if (isset($instance)) {
    return isset($info[$instance]) ? $info[$instance] : FALSE;
  }
  else {
    return $info;
  }
}

/**
 * Filter out meta tag values that equal the default values.
 *
 * @todo Use information in $values[$metatag]['default'] rather than a $defaults parameter.
 */
function metatag_filter_values_from_defaults(array &$values, array $defaults = array()) {
  foreach ($values as $metatag => $data) {
    $default = isset($data['default']) ? $data['default'] : (isset($defaults[$metatag]['value']) ? $defaults[$metatag]['value'] : NULL);
    if (isset($default) && isset($data['value']) && $default === $data['value']) {
      // Meta tag has a default, and it matches user-submitted value.
      unset($values[$metatag]);
    }
    elseif (!isset($default) && (is_string($data['value']) && !drupal_strlen($data['value']) || (is_array($data['value']) && !array_filter($data['value'])))) {
      // Metatag does not have a default, and user did not submit a value.
      unset($values[$metatag]);
    }
    if (isset($values[$metatag]['default'])) {
      // Unset the default hidden value.
      unset($values[$metatag]['default']);
    }
  }
}

/**
 * Return all the parents of a given configuration instance.
 *
 * @param $instance
 *   A meta tag configuration instance.
 *
 * @return
 *   An array of instances starting with the $instance parameter, with the end
 *   of the array being the global instance.
 */
function metatag_config_get_parent_instances($instance, $include_global = TRUE) {
  $parents = array();
  $segments = explode(':', $instance);
  while (count($segments) > 0) {
    $parents[] = implode(':', $segments);
    array_pop($segments);
  }
  if ($include_global && end($parents) !== 'global') {
    $parents[] = 'global';
  }
  reset($parents);
  return $parents;
}

/**
 * Get the proper label of a configuration instance.
 *
 * @param $instance
 *   A meta tag configuration instance.
 */
function metatag_config_instance_label($instance) {
  $labels = &drupal_static(__FUNCTION__, array());

  if (!isset($labels[$instance])) {
    $context = metatag_config_instance_info($instance);
    $labels[$instance] = isset($context['label']) ? $context['label'] : t('Unknown');
    $parents = metatag_config_get_parent_instances($instance, FALSE);
    array_shift($parents);
    if (!empty($parents)) {
      $labels[$instance] = metatag_config_instance_label(implode(':', $parents)) . ': ' . $labels[$instance];
    }
  }

  return $labels[$instance];
}

/**
 * Title callback for meta tag configuration instances.
 */
function metatag_config_title($config) {
  return metatag_config_instance_label($config->instance);
}

/**
 * Access callback for meta tag configuration instances.
 */
function metatag_config_access($op, $config = NULL) {
  if (!user_access('administer meta tags')) {
    return FALSE;
  }

  if ($op == 'enable') {
    return !empty($config->disabled);
  }
  elseif ($op == 'disable') {
    return empty($config->disabled);
  }
  elseif ($op == 'delete') {
    return ($config->export_type & EXPORT_IN_DATABASE) && !($config->export_type & EXPORT_IN_CODE);
  }
  elseif ($op == 'revert') {
    return ($config->export_type & EXPORT_IN_DATABASE) && ($config->export_type & EXPORT_IN_CODE);
  }

  return FALSE;
}
