Detect which locale to use based on the clients Accept-Language header.

@throws \Titon\G11n\Exception\MissingTranslatorException
484906
public function initialize() {
        if (!$this->isEnabled()) {
            return;
        }

        $current = null;

        // Determine via cookie
        if (!empty($_COOKIE['locale']) && isset($this->_locales[$_COOKIE['locale']])) {
            $current = $_COOKIE['locale'];

        // Determine locale based on HTTP headers
        } else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $header = mb_strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']);

            if (mb_strpos($header, ';') !== false) {
                $header = mb_strstr($header, ';', true);
            }

            $header = explode(',', $header);

            if (count($header) > 0) {
                foreach ($header as $key) {
                    if (isset($this->_locales[$key])) {
                        $current = $key;
                        break;
                    }
                }
            }
        }

        // Set current to the fallback if none found
        if ($current === null) {
            $current = $this->_fallback->getCode();
        }

        // Check for a translator
        if (!$this->_translator) {
            throw new MissingTranslatorException('A translator is required for G11n message parsing');
        }

        $this->emit('g11n.onInit', [$this, &$current]);

        // Apply the locale
        $this->useLocale($current);
    }
769335
protected static function get_target_locales()
    {
        // if locales are explicitly set, use these
        if (is_array(self::config()->locales)) {
            return (array)self::config()->locales;
            // otherwise check the allowed locales. If these have been set, use these
        } else if (is_array(Translatable::get_allowed_locales())) {
            return (array)Translatable::get_allowed_locales();
        }

        // last resort is to take the existing content languages
        return array_keys(Translatable::get_existing_content_languages());
    }
376895
public Locale getAcceptLanguage() {
		// See section 14.4 of RFC 2616 (HTTP/1.1) for more information about how the Accept-Language header
		// must interpreted to determine the preferred language of the client.
		Locale preferredLocale = null;
		float q = 0;
		Iterator<Header> it = (Iterator<Header>) this.message
			.getHeaders(AcceptLanguageHeader.NAME);
		while (it.hasNext()) {
			AcceptLanguageHeader alh = (AcceptLanguageHeader) it.next();
			if(preferredLocale == null) {
				preferredLocale = alh.getAcceptLanguage();
				q = alh.getQValue();
			} else {
				if(alh.getQValue() > q) {
					preferredLocale = alh.getAcceptLanguage();
					q = alh.getQValue();
				}
			}
		}
		return preferredLocale;
	}
64393
private function initLocale()
    {
        $this->locale = $this->detectLocale();

        // datetime format
        if (!setlocale(LC_TIME, $this->locales[$this->locale])) {
            throw new \Exception(sprintf("Unable to set locale to '%s'", $this->locales[$this->locale]));
        }

        // punic default value
        Data::setDefaultLocale($this->getIETF());

        if ('cli' !== PHP_SAPI) {
            if (!self::request()->getCookie(self::COOKIE_LANGUAGE)) {
                self::response()->addCookie(new Cookie(self::COOKIE_LANGUAGE, $this->locale, 60 * 60 * 24 * 365));
            }
        }
    }
617794
private function find_or_initialize_translation_details() {
		$set = get_transient( 'yoast_i18n_' . $this->project_slug . '_' . $this->locale );

		if ( ! $set ) {
			$set = $this->retrieve_translation_details();
			set_transient( 'yoast_i18n_' . $this->project_slug . '_' . $this->locale, $set, DAY_IN_SECONDS );
		}

		return $set;
	}
1344692
public function check_locale_availability(string $langpackcode) : bool {
        global $CFG;

        if (empty($langpackcode)) {
            throw new coding_exception('Invalid language pack code in \\'.__METHOD__.'() call, only non-empty string is allowed');
        }

        // Fetch the correct locale based on ostype.
        if ($CFG->ostype === 'WINDOWS') {
            $stringtofetch = 'localewin';
        } else {
            $stringtofetch = 'locale';
        }

        // Store current locale.
        $currentlocale = $this->set_locale(LC_ALL, 0);

        $locale = get_string_manager()->get_string($stringtofetch, 'langconfig', $a = null, $langpackcode);

        // Try to set new locale.
        $return = $this->set_locale(LC_ALL, $locale);

        // Restore current locale.
        $this->set_locale(LC_ALL, $currentlocale);

        // If $return is not equal to false, it means that setlocale() succeed to change locale.
        return $return !== false;
    }
786
private function _checkLocale()
    {
        if (!is_int($this->_country)
            || !is_int($this->_language)
            || !is_int($this->_currency)
        ) {
            throw new Klarna_InvalidLocaleException;
        }
    }
1038272
private function checkLocaleSet() {
		
		if (!$this->defaultLocale) {
			
			$locale = Locale::getDefault();
			$this->defaultLocale = $locale;
			
			// server variable
			setlocale(LC_ALL, $locale->getRepresentation());
			
		}
		
		if (!$this->currentLocale) {
			
			// temporary sets default locale as current
			$this->currentLocale = $this->defaultLocale;
			
			// gets favorite language from browser settings
			if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
			
				preg_match_all('/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?' .
						'(\s*;\s*q\s*=\s*(1\.0{0,3}|0\.\d{0,3}))?\s*(,|$)/i',
						$_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches, PREG_SET_ORDER);
			
				// if browser’s lang matches and it’s different by current, will set as current
				if (!isset($matches[0][1]) or $this->currentLocale->getLanguage()->code == $matches[0][1]) {
					return;
				}
				
				$locale = Locale::getDefaultByLanguage($matches[0][1]);
				if (!$locale) {
					return;
				}
				
				$this->setLocale($locale);
					
			}

		}
		
	}
147818
def get_headers_lang (headers):
    """"""
    if 'Accept-Language' not in headers:
        return default_language
    languages = headers['Accept-Language'].split(",")
    # sort with preference values
    pref_languages = []
    for lang in languages:
        pref = 1.0
        if ";" in lang:
            lang, _pref = lang.split(';', 1)
            try:
                pref = float(_pref)
            except ValueError:
                pass
        pref_languages.append((pref, lang))
    pref_languages.sort()
    # search for lang
    for lang in (x[1] for x in pref_languages):
        if lang in supported_languages:
            return lang
    return default_language
1300146
public function setLocale()
    {
        // Initialize Locale if set and configured.
        if ($this['language']->enabled() && $this['config']->get('system.languages.override_locale')) {
            $language = $this['language']->getLanguage();
            setlocale(LC_ALL, \strlen($language) < 3 ? ($language . '_' . strtoupper($language)) : $language);
        } elseif ($this['config']->get('system.default_locale')) {
            setlocale(LC_ALL, $this['config']->get('system.default_locale'));
        }
    }
567268
def select_locale_by_request(self, request, locales=()):
        """"""
        default_locale = locales and locales[0] or self.cfg.default_locale

        if len(locales) == 1 or 'ACCEPT-LANGUAGE' not in request.headers:
            return default_locale

        ulocales = [
            (q, locale_delim_re.split(v)[0])
            for v, q in parse_accept_header(request.headers['ACCEPT-LANGUAGE'])
        ]
        ulocales.sort()
        ulocales.reverse()

        for locale in locales:
            for _, ulocale in ulocales:
                ulocale = locale_delim_re.split(ulocale)[0]
                if ulocale.lower() == locale.lower():
                    return ulocale

        return ulocales[0][1]
690270
protected function checkLocale($locale)
    {
        $languageFound = null;
        $language = strstr($locale, '_', true);

        foreach ($this->configuration['locales'] as $availableLocale) {
            // If locale matches, the exact matching was found.
            if ($availableLocale === $locale) {
                return $availableLocale;
            }

            // Check if language (without locale) matches.
            if ($language == $availableLocale) {
                $languageFound = $availableLocale;
            }
        }

        if ($languageFound) {
            return $languageFound;
        }

        return null;
    }
1018084
private function setlocale() {
        foreach ($this->codeSets as $code) {
            if (substr($code, 0, strlen($this->loadedLang)) === $this->loadedLang) {
                setlocale(LC_TIME, $code);
                break;
            }
        }
    }
653387
public function detectLanguage()
    {
        $acceptableLanguages = Yii::$app->getRequest()->getAcceptableLanguages();
        foreach ($acceptableLanguages as $language) {
            if ($this->isValidLanguage($language)) {
                return $language;
            }
        }
        foreach ($acceptableLanguages as $language) {
            $pattern = preg_quote(substr($language, 0, 2), '/');
            foreach ($this->languages as $key => $value) {
                if (preg_match('/^' . $pattern . '/', $value) || preg_match('/^' . $pattern . '/', $key)) {
                    return $this->isValidLanguage($key) ? $key : $value;
                }
            }
        }

        return false;
    }
1103666
protected function restoreLocale() {
		$primaryLocale = $this->getPrimaryLocale();
		if ($primaryLocale && $primaryLocale !== $this->locale) {
			I18n::setLocale($this->locale);
		}
	}
844348
protected function _setLocale() {
		$language = $this->_language->getCurrentUiLang(false);

		return (bool)setlocale(LC_ALL, $language);
	}
867076
public function getLocalization()
	{
		$data = parent::getLocalization();
		
		if (empty($data)) {
			$data = $this->detectRequestPageLocalization();
			
			$this->setLocalization($data);
		}
	
		return $data;
	}