<?php

/**
 * Implements hook_entity_info_alter().
 */
function xmlsitemap_taxonomy_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['bundle label'] = t('Vocabulary');
  $entity_info['taxonomy_term']['xmlsitemap'] = array(
    'process callback' => 'xmlsitemap_taxonomy_xmlsitemap_process_taxonomy_term_links',
  );
}

/**
 * Implements hook_xmlsitemap_link_info_alter().
 */
function xmlsitemap_taxonomy_xmlsitemap_link_info_alter(&$link_info) {
  foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
    // Adjust the edit path to the *real* edit path.
    $link_info['taxonomy_term']['bundles'][$machine_name]['admin']['path'] .= '/edit';
    $link_info['taxonomy_term']['bundles'][$machine_name]['admin']['real path'] .= '/edit';
  }
}

/**
 * Implements hook_cron().
 *
 * Process old taxonomy terms not found in the {xmlsitemap} table.
 */
function xmlsitemap_taxonomy_cron() {
  xmlsitemap_taxonomy_xmlsitemap_index_links(xmlsitemap_var('batch_limit'));
}

/**
 * Implements hook_xmlsitemap_index_links().
 */
function xmlsitemap_taxonomy_xmlsitemap_index_links($limit) {
  if ($bundles = xmlsitemap_get_link_type_enabled_bundles('taxonomy_term')) {
    $tids = db_query_range("SELECT t.tid FROM {taxonomy_term_data} t INNER JOIN {taxonomy_vocabulary} tv USING (vid) LEFT JOIN {xmlsitemap} x ON x.type = 'taxonomy_term' AND t.tid = x.id WHERE x.id IS NULL AND tv.machine_name IN (:bundles) ORDER BY t.tid DESC", 0, $limit, array(':bundles' => $bundles))->fetchCol();
    xmlsitemap_taxonomy_xmlsitemap_process_taxonomy_term_links($tids);
  }
}

/**
 * Process taxonomy term sitemap links.
 *
 * @param $tids
 *   An array of taxonomy term IDs.
 */
function xmlsitemap_taxonomy_xmlsitemap_process_taxonomy_term_links(array $tids) {
  $terms = taxonomy_term_load_multiple($tids);
  foreach ($terms as $term) {
    $link = xmlsitemap_taxonomy_create_link($term);
    xmlsitemap_link_save($link, array($link['type'] => $term));
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * @see taxonomy_form_vocabulary()
 * @see xmlsitemap_add_link_bundle_settings()
 */
function xmlsitemap_taxonomy_form_taxonomy_form_vocabulary_alter(&$form, $form_state) {
  if (in_array('taxonomy_vocabulary_confirm_delete_submit', $form['#submit'])) {
    // If this is the delete form, do not add our form elements.
    return;
  }

  module_load_include('inc', 'xmlsitemap', 'xmlsitemap.admin');
  xmlsitemap_add_link_bundle_settings($form, $form_state, 'taxonomy_term', $form['#vocabulary']->machine_name);
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function xmlsitemap_taxonomy_form_taxonomy_form_term_alter(&$form, $form_state) {
  if ($form['name']['#type'] == 'value') {
    // If this is the delete form, do not add our form elements.
    return;
  }

  // Add the link options.
  module_load_include('inc', 'xmlsitemap', 'xmlsitemap.admin');
  xmlsitemap_add_form_link_options($form, 'taxonomy_term', $form['#term']['vocabulary_machine_name'], $form['tid']['#value']);
}

/**
 * Implements hook_taxonomy_vocabulary_insert().
 */
function xmlsitemap_taxonomy_vocabulary_insert(stdClass $vocabulary) {
  if (isset($vocabulary->xmlsitemap)) {
    xmlsitemap_link_bundle_settings_save('taxonomy_term', $vocabulary->machine_name, $vocabulary->xmlsitemap);
  }
}

/**
 * Implements hook_taxonomy_vocabulary_update().
 */
function xmlsitemap_taxonomy_vocabulary_update(stdClass $vocabulary) {
  if (isset($vocabulary->xmlsitemap)) {
    xmlsitemap_link_bundle_settings_save('taxonomy_term', $vocabulary->machine_name, $vocabulary->xmlsitemap);
  }
}

/**
 * Implements hook_taxonomy_term_insert() {
 */
function xmlsitemap_taxonomy_term_insert(stdClass $term) {
  $link = xmlsitemap_taxonomy_create_link($term);
  xmlsitemap_link_save($link, array($link['type'] => $term));
}

/**
 * Implements hook_taxonomy_term_update() {
 */
function xmlsitemap_taxonomy_term_update(stdClass $term) {
  $link = xmlsitemap_taxonomy_create_link($term);
  xmlsitemap_link_save($link, array($link['type'] => $term));
}

/**
 * Implements hook_taxonomy_term_delete() {
 */
function xmlsitemap_taxonomy_term_delete(stdClass $term) {
  xmlsitemap_link_delete('taxonomy_term', $term->tid);
}

/**
 * Implements hook_field_extra_fields().
 */
function xmlsitemap_taxonomy_field_extra_fields() {
  $extras = array();
  foreach (taxonomy_vocabulary_get_names() as $machine_name => $vocabulary) {
    $extras['taxonomy_term'][$machine_name]['form']['xmlsitemap'] = array(
      'label' => t('XML sitemap'),
      'description' => t('XML sitemap module element'),
      'weight' => 30,
    );
  }
  return $extras;
}

/**
 * Create a sitemap link from a taxonomy term.
 *
 * @param $term
 *   A taxonomy term object.
 * @return
 *   An array representing a sitemap link.
 */
function xmlsitemap_taxonomy_create_link(stdClass &$term) {
  if (!isset($term->xmlsitemap)) {
    $term->xmlsitemap = array();
    if ($term->tid && $link = xmlsitemap_link_load('taxonomy_term', $term->tid)) {
      $term->xmlsitemap = $link;
    }
  }

  $settings = xmlsitemap_link_bundle_load('taxonomy_term', $term->vocabulary_machine_name);
  $uri = entity_uri('taxonomy_term', $term);

  $term->xmlsitemap += array(
    'id' => $term->tid,
    'type' => 'taxonomy_term',
    'subtype' => $term->vocabulary_machine_name,
    'status' => $settings['status'],
    'status_default' => $settings['status'],
    'status_override' => 0,
    'priority' => $settings['priority'],
    'priority_default' => $settings['priority'],
    'priority_override' => 0,
  );

  // The following values must always be checked because they are volatile.
  // @todo How can/should we check taxonomy term access?
  $term->xmlsitemap['loc'] = $uri['path'];
  $term->xmlsitemap['access'] = 1;
  $term->xmlsitemap['language'] = isset($term->language) ? $term->language : LANGUAGE_NONE;

  return $term->xmlsitemap;
}

/**
 * Calculate the priority of a taxonomy term based on depth and weight.
 */
//function xmlsitemap_taxonomy_calculate_term_priority(stdClass $term) {
//  // Calculate priority.
//  // Min weight = -128
//  // Max weight = 127
//  // Max depth = ?
//}

/**
 * Find the tree depth of a taxonomy term.
 *
 * @param $term
 *   A taxonomy term object.
 * @return
 *   The tree depth of the term.
 */
function xmlsitemap_taxonomy_get_term_depth(stdClass $term) {
  static $depths = array();

  if (!isset($depths[$term->tid])) {
    if ($parent = db_query("SELECT parent FROM {taxonomy_term_hierarchy} WHERE tid = %d", $term->tid)->fetchField()) {
      // If the term has a parent, the term's depth is the parent's depth + 1.
      if (!isset($depths[$parent])) {
        $depths[$parent] = xmlsitemap_taxonomy_get_term_depth($parent);
      }
      $depths[$term->tid] = $depths[$parent] + 1;
    }
    else {
      // Term has no parents, so depth is 0.
      $depths[$term->tid] = 0;
    }
  }

  return $depths[$term->tid];
}

/**
 * Find the number of nodes that are associated with a taxonomy term.
 *
 * @param $term
 *   A taxonomy term object.
 * @return
 *   The number of nodes associated with the term.
 */
function xmlsitemap_taxonomy_get_node_count(stdClass $term) {
  // @todo Use db_rewrite_sql() w/ switch user.
  return db_query_range("SELECT COUNT(ti.nid) FROM {taxonomy_index} ti LEFT JOIN {node n} USING (nid) WHERE ti.tid = :tid AND n.status = 1", 0, 1, array(':tid' => $term->tid))->fetchField();
}

/**
 * Implements hook_entity_query_alter().
 *
 * @todo Remove when http://drupal.org/node/1054162 is fixed.
 */
function xmlsitemap_taxonomy_entity_query_alter($query) {
  $conditions = &$query->entityConditions;

  // Alter taxonomy term queries only.
  if (isset($conditions['entity_type']) && $conditions['entity_type']['value'] == 'taxonomy_term' && isset($conditions['bundle'])) {

    // We can only support the operators that are explicit in values.
    if (in_array($conditions['bundle']['operator'], array(NULL, '=', '!=', 'IN', 'NOT IN'))) {
      $vids = array();

      // Convert vocabulary machine names to vocabulary IDs.
      if (is_array($conditions['bundle']['value'])) {
        foreach ($conditions['bundle']['value'] as $vocabulary_machine_name) {
          $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_machine_name);
          $vids[] = $vocabulary->vid;
        }
      }
      else {
        $vocabulary = taxonomy_vocabulary_machine_name_load($conditions['bundle']['value']);
        $vids = $vocabulary->vid;
      }

      $query->propertyCondition('vid', $vids, $conditions['bundle']['operator']);
      unset($conditions['bundle']);
    }
  }
}

/**
 * Implements hook_features_pipe_COMPONENT_alter().
 *
 * Add variables to exported taxonomy vocabularies.
 */
function xmlsitemap_taxonomy_features_pipe_taxonomy_alter(&$pipe, $data, $export) {
  if (!empty($data)) {
    foreach ($data as $vocabulary_name) {
      $pipe['variable'][] = "xmlsitemap_settings_taxonomy_term_{$vocabulary_name}";
    }
  }
}
