<?php

/**
 * @file
 * Add language handling functionality to Drupal.
 */

/**
 * Implements hook_help().
 */
function language_help($path, $arg) {
  switch ($path) {
    case 'admin/help#language':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Language module allows you to maintain a list of languages used on your Drupal site for providing language information for content and for interface translation (using the Locale module). For more information, see the online handbook entry for <a href="@language">Language module</a>.', array('@language' => 'http://drupal.org/documentation/modules/language')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Configuring the list of languages') . '</dt>';
      $output .= '<dd>' . t('<a href="@configure-languages">Configure the list of languages</a> either using the built-in language list or providing any custom languages you wish.', array('@configure-languages' => url('admin/config/regional/language'))) . '</dd>';
      $output .= '<dt>' . t('Configuring a multilingual site') . '</dt>';
      $output .= '<dd>' . t("Language negotiation allows your site to automatically change language based on the domain or path used for each request. Users may (optionally) select their preferred language on their <em>My account</em> page, and your site can be configured to honor a web browser's preferred language settings. Site content can be translated using the <a href='@content-help'>Content Translation module</a>.", array('@content-help' => url('admin/help/translation'))) . '</dd>';
      $output .= '</dl>';
      return $output;

    case 'admin/config/regional/language':
      return '<p>' . t('With multiple languages enabled, registered users may select their preferred language and authors can assign a specific language to content.') . '</p>';

    case 'admin/config/regional/language/add':
      return '<p>' . t('Add a language to be supported by your site. If your desired language is not available, pick <em>Custom language...</em> at the end and provide a language code and other details manually.') . '</p>';

    case 'admin/config/regional/language/detection':
      $output = '<p>' . t("Define how to decide which language is used to display page elements (primarily text provided by Drupal and modules, such as field labels and help text). This decision is made by evaluating a series of detection methods for languages; the first detection method that gets a result will determine which language is used for that type of text. Define the order of evaluation of language detection methods on this page.") . '</p>';
      return $output;

    case 'admin/config/regional/language/detection/session':
      $output = '<p>' . t('Determine the language from a request/session parameter. Example: "http://example.com?language=de" sets language to German based on the use of "de" within the "language" parameter.') . '</p>';
      return $output;

    case 'admin/structure/block/manage/%/%':
      if ($arg[4] == 'language' && $arg[5] == 'language_interface') {
        return '<p>' . t('This block is only shown if <a href="@languages">at least two languages are enabled</a> and <a href="@configuration">language negotiation</a> is set to <em>URL</em> or <em>Session</em>.', array('@languages' => url('admin/config/regional/language'), '@configuration' => url('admin/config/regional/language/detection'))) . '</p>';
      }
      break;
  }
}

/**
 * Implements hook_menu().
 */
function language_menu() {
  // Base language management and configuration.
  $items['admin/config/regional/language'] = array(
    'title' => 'Languages',
    'description' => 'Configure languages for content and the user interface.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('language_admin_overview_form'),
    'access arguments' => array('administer languages'),
    'file' => 'language.admin.inc',
    'weight' => -10,
  );
  $items['admin/config/regional/language/list'] = array(
    'title' => 'List',
    'weight' => 0,
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/config/regional/language/add'] = array(
    'title' => 'Add language',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('language_admin_add_form'),
    'access arguments' => array('administer languages'),
    'weight' => 5,
    'type' => MENU_LOCAL_ACTION,
    'file' => 'language.admin.inc',
  );
  $items['admin/config/regional/language/edit/%language'] = array(
    'title' => 'Edit language',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('language_admin_edit_form', 5),
    'access arguments' => array('administer languages'),
    'file' => 'language.admin.inc',
  );
  $items['admin/config/regional/language/delete/%language'] = array(
    'title' => 'Confirm delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('language_admin_delete_form', 5),
    'access arguments' => array('administer languages'),
    'file' => 'language.admin.inc',
  );

  // Language negotiation.
  $items['admin/config/regional/language/detection'] = array(
    'title' => 'Detection and selection',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('language_negotiation_configure_form'),
    'access arguments' => array('administer languages'),
    'weight' => 10,
    'file' => 'language.admin.inc',
    'type' => MENU_LOCAL_TASK,
  );
  $items['admin/config/regional/language/detection/url'] = array(
    'title' => 'URL language detection configuration',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('language_negotiation_configure_url_form'),
    'access arguments' => array('administer languages'),
    'file' => 'language.admin.inc',
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
  );
  $items['admin/config/regional/language/detection/session'] = array(
    'title' => 'Session language detection configuration',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('language_negotiation_configure_session_form'),
    'access arguments' => array('administer languages'),
    'file' => 'language.admin.inc',
    'type' => MENU_VISIBLE_IN_BREADCRUMB,
  );

  return $items;
}

/**
 * Implements hook_permission().
 */
function language_permission() {
  return array(
    'administer languages' => array(
      'title' => t('Administer languages'),
    ),
  );
}

/**
 * Implements hook_theme().
 */
function language_theme() {
  return array(
    'language_admin_overview_form_table' => array(
      'render element' => 'form',
      'file' => 'language.admin.inc',
    ),
    'language_admin_operations' => array(
      'render element' => 'elements',
      'file' => 'language.admin.inc',
    ),
    'language_negotiation_configure_form' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * API function to add or update a language.
 *
 * @param $language
 *   Language object with properties corresponding to 'language' table columns.
 */
function language_save($language) {
  $language->is_new = !(bool) db_query_range('SELECT 1 FROM {language} WHERE langcode = :langcode', 0, 1, array(':langcode' => $language->langcode))->fetchField();

  // If name was not set, we add a predefined language.
  if (!isset($language->name)) {
    include_once DRUPAL_ROOT . '/core/includes/standard.inc';
    $predefined = standard_language_list();
    $language->name = $predefined[$language->langcode][0];
    $language->direction = isset($predefined[$language->langcode][2]) ? $predefined[$language->langcode][2] : LANGUAGE_LTR;
  }

  // Let other modules modify $language before saved.
  module_invoke_all('language_presave', $language);

  // Save the record and inform others about the change.
  $t_args = array('%language' => $language->name, '%langcode' => $language->langcode);
  if ($language->is_new) {
    drupal_write_record('language', $language);
    module_invoke_all('language_insert', $language);
    watchdog('language', 'The %language (%langcode) language has been created.', $t_args);
  }
  else {
    drupal_write_record('language', $language, array('langcode'));
    module_invoke_all('language_update', $language);
    watchdog('language', 'The %language (%langcode) language has been updated.', $t_args);
  }

  if (!empty($language->default)) {
    // Set the new version of this language as default in a variable.
    $default_language = language_default();
    variable_set('language_default', $language);
  }

  // Update language count based on enabled language count.
  variable_set('language_count', db_query('SELECT COUNT(langcode) FROM {language}')->fetchField());

  // Kill the static cache in language_list().
  drupal_static_reset('language_list');

  return $language;
}

/**
 * Delete a language.
 *
 * @param $langcode
 *   Language code of the language to be deleted.
 * @return
 *   TRUE if language is successfully deleted. Otherwise FALSE.
 */
function language_delete($langcode) {
  $languages = language_list();
  if (isset($languages[$langcode])) {
    $language = $languages[$langcode];

    module_invoke_all('language_delete', $language);

    // Remove the language.
    db_delete('language')
      ->condition('langcode', $language->langcode)
      ->execute();

    variable_set('language_count', variable_get('language_count', 1) - 1);

    drupal_static_reset('language_list');

    $t_args = array('%language' => $language->name, '%langcode' => $language->langcode);
    watchdog('language', 'The %language (%langcode) language has been removed.', $t_args);
    return TRUE;
  }
  return FALSE;
}

/**
 * Implements hook_css_alter().
 *
 * This function checks all CSS files currently added via drupal_add_css() and
 * and checks to see if a related right to left CSS file should be included.
 */
function language_css_alter(&$css) {
  global $language_interface;

  // If the current language is RTL, add the CSS file with the RTL overrides.
  if ($language_interface->direction == LANGUAGE_RTL) {
    foreach ($css as $data => $item) {
      // Only provide RTL overrides for files.
      if ($item['type'] == 'file') {
        $rtl_path = str_replace('.css', '-rtl.css', $item['data']);
        if (file_exists($rtl_path) && !isset($css[$rtl_path])) {
          // Replicate the same item, but with the RTL path and a little larger
          // weight so that it appears directly after the original CSS file.
          $item['data'] = $rtl_path;
          $item['weight'] += 0.01;
          $css[$rtl_path] = $item;
        }
      }
    }
  }
}

/**
 * Implements hook_language_types_info().
 *
 * Defines the three core language types:
 * - Interface language is the only configurable language type in core. It is
 *   used by t() as the default language if none is specified.
 * - Content language is by default non-configurable and inherits the interface
 *   language negotiated value. It is used by the Field API to determine the
 *   display language for fields if no explicit value is specified.
 * - URL language is by default non-configurable and is determined through the
 *   URL language negotiation method or the URL fallback language negotiation
 *   method if no language can be detected. It is used by l() as the default
 *   language if none is specified.
 */
function language_language_types_info() {
  language_negotiation_include();

  return array(
    LANGUAGE_TYPE_INTERFACE => array(
      'name' => t('User interface text'),
      'description' => t('Order of language detection methods for user interface text. If a translation of user interface text is available in the detected language, it will be displayed.'),
    ),
    LANGUAGE_TYPE_CONTENT => array(
      'name' => t('Content'),
      'description' => t('Order of language detection methods for content. If a version of content is available in the detected language, it will be displayed.'),
      'fixed' => array(LANGUAGE_NEGOTIATION_INTERFACE),
    ),
    LANGUAGE_TYPE_URL => array(
      'fixed' => array(LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_URL_FALLBACK),
    ),
  );
}

/**
 * Implements hook_language_negotiation_info().
 */
function language_language_negotiation_info() {
  language_negotiation_include();
  $file = drupal_get_path('module', 'language') . '/language.negotiation.inc';

  $negotiation_info = array();
  $negotiation_info[LANGUAGE_NEGOTIATION_URL] = array(
    'types' => array(LANGUAGE_TYPE_CONTENT, LANGUAGE_TYPE_INTERFACE, LANGUAGE_TYPE_URL),
    'callbacks' => array(
      'negotiation' => 'language_from_url',
      'language_switch' => 'language_switcher_url',
      'url_rewrite' => 'language_url_rewrite_url',
    ),
    'file' => $file,
    'weight' => -8,
    'name' => t('URL'),
    'description' => t('Determine the language from the URL (Path prefix or domain).'),
    'config' => 'admin/config/regional/language/detection/url',
  );

  $negotiation_info[LANGUAGE_NEGOTIATION_SESSION] = array(
    'callbacks' => array(
      'negotiation' => 'language_from_session',
      'language_switch' => 'language_switcher_session',
      'url_rewrite' => 'language_url_rewrite_session',
    ),
    'file' => $file,
    'weight' => -6,
    'name' => t('Session'),
    'description' => t('Determine the language from a request/session parameter.'),
    'config' => 'admin/config/regional/language/detection/session',
  );

  $negotiation_info[LANGUAGE_NEGOTIATION_USER] = array(
    'callbacks' => array('negotiation' => 'language_from_user'),
    'file' => $file,
    'weight' => -4,
    'name' => t('User'),
    'description' => t("Follow the user's language preference."),
  );

  $negotiation_info[LANGUAGE_NEGOTIATION_BROWSER] = array(
    'callbacks' => array('negotiation' => 'language_from_browser'),
    'file' => $file,
    'weight' => -2,
    'cache' => 0,
    'name' => t('Browser'),
    'description' => t("Determine the language from the browser's language settings."),
  );

  $negotiation_info[LANGUAGE_NEGOTIATION_INTERFACE] = array(
    'types' => array(LANGUAGE_TYPE_CONTENT),
    'callbacks' => array('negotiation' => 'language_from_interface'),
    'file' => $file,
    'weight' => 8,
    'name' => t('Interface'),
    'description' => t('Use the detected interface language.'),
  );

  $negotiation_info[LANGUAGE_NEGOTIATION_URL_FALLBACK] = array(
    'types' => array(LANGUAGE_TYPE_URL),
    'callbacks' => array('negotiation' => 'language_url_fallback'),
    'file' => $file,
    'weight' => 8,
    'name' => t('URL fallback'),
    'description' => t('Use an already detected language for URLs if none is found.'),
  );

  return $negotiation_info;
}

/**
 * Include negotiation backend functionality.
 */
function language_negotiation_include() {
  include_once DRUPAL_ROOT . '/core/includes/language.inc';
  include_once DRUPAL_ROOT . '/' . drupal_get_path('module', 'language') . '/language.negotiation.inc';
}

/**
 * Implements hook_modules_enabled().
 */
function language_modules_enabled($modules) {
  language_negotiation_include();
  language_types_set();
  language_negotiation_purge();
}

/**
 * Implements hook_modules_disabled().
 */
function language_modules_disabled($modules) {
  language_modules_enabled($modules);
}

/**
 * Implements hook_language_insert().
 */
function language_language_insert($language) {
  language_negotiation_include();

  // Add new language to the list of language prefixes.
  $prefixes = language_negotiation_url_prefixes();
  $prefixes[$language->langcode] = (empty($language->default) ? $language->langcode : '');
  language_negotiation_url_prefixes_save($prefixes);

  // Add language to the list of language domains.
  $domains = language_negotiation_url_domains();
  $domains[$language->langcode] = '';
  language_negotiation_url_domains_save($domains);
}

/**
 * Implements hook_language_update().
 */
function language_language_update($language) {
  language_negotiation_include();

  // If the language is the default, then ensure that no other languages have
  // blank prefix codes.
  if (!empty($language->default)) {
    $prefixes = language_negotiation_url_prefixes();
    foreach ($prefixes as $langcode => $prefix) {
      if ($prefix == '' && $langcode != $language->langcode) {
        $prefixes[$langcode] = $langcode;
      }
    }
    language_negotiation_url_prefixes_save($prefixes);
  }
}

/**
 * Implements hook_language_delete().
 */
function language_language_delete($language) {
  language_negotiation_include();

  // Remove language from language prefix list.
  $prefixes = language_negotiation_url_prefixes();
  unset($prefixes[$language->langcode]);
  language_negotiation_url_prefixes_save($prefixes);

  // Remove language from language domain list.
  $domains = language_negotiation_url_domains();
  unset($domains[$language->langcode]);
  language_negotiation_url_domains_save($domains);
}

/**
 * Implements hook_block_info().
 */
function language_block_info() {
  include_once DRUPAL_ROOT . '/core/includes/language.inc';
  $block = array();
  $info = language_types_info();
  foreach (language_types_get_configurable(FALSE) as $type) {
    $block[$type] = array(
      // We do not need to escape the language type name since the block 'info'
      // value is supposed not to be sanitized. It is escaped later, if needed.
      'info' => t('Language switcher (!type)', array('!type' => $info[$type]['name'])),
      // Not worth caching.
      'cache' => DRUPAL_NO_CACHE,
    );
  }
  return $block;
}

/**
 * Implements hook_block_view().
 *
 * Displays a language switcher. Only show if we have at least two languages.
 */
function language_block_view($type) {
  if (language_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : current_path();
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      $class = "language-switcher-{$links->method_id}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__language_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

/**
 * Implements hook_preprocess_HOOK() for block.tpl.php.
 */
function language_preprocess_block(&$variables) {
  if ($variables['block']->module == 'language') {
    $variables['attributes_array']['role'] = 'navigation';
  }
}

/**
 * Implements hook_url_outbound_alter().
 *
 * Rewrite outbound URLs with language based prefixes.
 */
function language_url_outbound_alter(&$path, &$options, $original_path) {
  // Only modify internal URLs.
  if (!$options['external'] && language_multilingual()) {
    static $drupal_static_fast;
    if (!isset($drupal_static_fast)) {
      $drupal_static_fast['callbacks'] = &drupal_static(__FUNCTION__);
    }
    $callbacks = &$drupal_static_fast['callbacks'];

    if (!isset($callbacks)) {
      $callbacks = array();
      include_once DRUPAL_ROOT . '/core/includes/language.inc';

      foreach (language_types_get_configurable() as $type) {
        // Get URL rewriter callbacks only from enabled language methods.
        $negotiation = variable_get("language_negotiation_$type", array());

        foreach ($negotiation as $method_id => $method) {
          if (isset($method['callbacks']['url_rewrite'])) {
            if (isset($method['file'])) {
              require_once DRUPAL_ROOT . '/' . $method['file'];
            }
            // Avoid duplicate callback entries.
            $callbacks[$method['callbacks']['url_rewrite']] = TRUE;
          }
        }
      }

      $callbacks = array_keys($callbacks);
    }

    foreach ($callbacks as $callback) {
      if (function_exists($callback)) {
        $callback($path, $options);
      }
    }

    // No language dependent path allowed in this mode.
    if (empty($callbacks)) {
      unset($options['language']);
    }
  }
}
