locale_language_from_url

7 locale.inc locale_language_from_url($languages)

Identify language via URL prefix or domain.

Parameters

$languages: An array of valid language objects.

Return value

A valid language code on success, FALSE otherwise.

Related topics

1 string reference to 'locale_language_from_url'

File

includes/locale.inc, line 264
Administration functions for locale.module.

Code

function locale_language_from_url($languages) {
  $language_url = FALSE;

  if (!language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_URL)) {
    return $language_url;
  }

  switch (variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX)) {
    case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
      // $_GET['q'] might not be available at this time, because
      // path initialization runs after the language bootstrap phase.
      list($language, $_GET['q']) = language_url_split_prefix(isset($_GET['q']) ? $_GET['q'] : NULL, $languages);
      if ($language !== FALSE) {
        $language_url = $language->language;
      }
      break;

    case LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN:
      foreach ($languages as $language) {
        // Skip check if the language doesn't have a domain.
        if ($language->domain) {
          // Only compare the domains not the protocols or ports.
          // Remove protocol and add http:// so parse_url works
          $host = 'http://' . str_replace(array('http://', 'https://'), '', $language->domain);
          $host = parse_url($host, PHP_URL_HOST);
          if ($_SERVER['HTTP_HOST'] == $host) {
            $language_url = $language->language;
            break;
          }
        }
      }
      break;
  }

  return $language_url;
}

Comments

locale_language_from_url() doesn't work

I found locale_language_from_url() needs a work-around. This was with Drupal 7.8, but presumably true of other D7 versions. The following code works for me:

    // Due to an apparent bug somewhere in Drupal language processing,
    // locale_language_from_url() doesn't work because it expects $_GET['q'] to
    // include the language prefix, but the prefix has already been removed.
    // As a work-around, temporarily set $_GET['q'] to request_path().
    // This works because request_path() statically caches the original value.
    $languages = language_list();
    $saveq = $_GET['q'];
    $_GET['q'] = request_path();
    $url_language_id  = locale_language_from_url($languages);
    $_GET['q'] = $saveq;

I know that the same language value can normally be accessed via the global $language object, but in my case I needed to detect language from url during bootstrap, when $language is not initialised.

It also seems that this is probably only an issue when serving cached pages:

bootstrap.inc #2218:

      // Restore the metadata cached with the page.
      $_GET['q'] = $cache->data['path'];

I've opened an issue for this - http://drupal.org/node/1286208

Login or register to post comments