<?php
// $Id: xmlsitemap_i18n.module,v 1.4 2009/12/23 22:29:16 davereid Exp $

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Set the regeneration needed flag if multilingual settings are changed.
 */
function xmlsitemap_i18n_form_i18n_admin_settings_alter(&$form, $form_state) {
  array_unshift($form['#submit'], 'xmlsitemap_form_submit_flag_regenerate');
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Allow the user to have multilingual sitemaps.
 */
function xmlsitemap_i18n_form_xmlsitemap_settings_form_alter(&$form, $form_state) {
  $form['xmlsitemap']['xmlsitemap_languages']['#options'] = locale_language_list();
  $form['xmlsitemap']['xmlsitemap_languages']['#description'] = t("Each language's sitemap will respect the <a href=\"@i18n-settings\">multilingual content selection mode</a>.", array('@i18n-settings' => url('admin/settings/language/i18n')));
}

/**
 * Implements hook_query_TAG_alter().
 *
 * @see i18n_db_rewrite_where()
 */
function xmlsitemap_i18n_query_xmlsitemap_alter(QueryAlterableInterface $query) {
  // Get languages to simplify query building.
  $mode = variable_get('i18n_selection_mode', 'simple');
  $current = $query->getMetaData('language')->language;
  $default = i18n_default_language();

  if ($mode == 'mixed' && $current == $default) {
    // If mode is mixed but current = default, is the same as 'simple'.
    $mode = 'simple';
  }

  switch ($mode) {
    case 'simple':
      // Current language and language neutral.
      $query->condition('language', array($current, LANGUAGE_NONE));
      break;
    case 'mixed':
      // Mixed current language (if available) or default language (if not) and language neutral.
      $query->condition('language', array($current, $default, LANGUAGE_NONE));
      break;
    case 'default':
      // Only default language and language neutral.
      $query->condition('language', array($default, LANGUAGE_NONE));
      break;
    case 'strict':
      // Only current language (for nodes), simple for all other types.
      $node_condition = db_and();
      $node_condition->condition('type', 'node');
      $node_condition->condition('language', $current);
      $normal_condition = db_and();
      $normal_condition->condition('type', 'node', '<>');
      $normal_condition->condition('language', array($current, LANGUAGE_NONE));
      $condition = db_or();
      $condition->condition($node_condition);
      $condition->condition($normal_condition);
      $query->condition($condition);
      break;
    case 'off':
      // All content. No language conditions apply.
      break;
  }
}
