Resolve language

Taken from Nette\Http\Request::detectLanguage()
@author David Grudl
198451
public function resolve(): ?string {
    if(is_null($this->loader)) {
      throw new LoaderNotSetException("Loader is not available, cannot detect possible languages.");
    }
    $header = $this->request->getHeader("Accept-Language");
    $langs = $this->loader->getAvailableLanguages();
    if(is_null($header)) {
      return null;
    }
    $s = strtolower($header);  // case insensitive
    $s = strtr($s, '_', '-');  // cs_CZ means cs-CZ
    rsort($langs);             // first more specific
    $pattern = ')(?:-[^\s,;=]+)?\s*(?:;\s*q=([0-9.]+))?#';
    preg_match_all('#(' . implode('|', $langs) . $pattern, $s, $matches);
    if(!$matches[0]) {
      return null;
    }
    $max = 0;
    $lang = null;
    foreach($matches[1] as $key => $value) {
      $q = ($matches[2][$key] === '') ? 1.0 : (float) $matches[2][$key];
      if($q > $max) {
        $max = $q;
        $lang = $value;
      }
    }
    return $lang;
  }
174682
public function detect(): \Nails\Common\Factory\Locale
    {
        /**
         * Detect the locale from the request, weakest first
         * - Request headers
         * - Active user preference
         * - The URL (/{locale}/.*)
         * - A locale cookie
         * - Explicitly provided via $_GET['locale']
         */

        $oLocale = $this->getDefautLocale();
        if (static::ENABLE_SNIFF) {

            if (static::ENABLE_SNIFF_HEADER) {
                $this->sniffHeader($oLocale);
            }
            if (static::ENABLE_SNIFF_USER) {
                $this->sniffActiveUser($oLocale);
            }
            if (static::ENABLE_SNIFF_URL) {
                $this->sniffUrl($oLocale);
            }
            if (static::ENABLE_SNIFF_COOKIE) {
                $this->sniffCookie($oLocale);
            }
            if (static::ENABLE_SNIFF_QUERY) {
                $this->sniffQuery($oLocale);
            }

            if (!$this->isSupportedLocale($oLocale)) {
                $oLocale = $this->getDefautLocale();
            }

        }

        return $this
            ->set($oLocale)
            ->get();
    }
416704
public function resolve(Request $request)
    {
        //locale
        switch ($this->localePattern) {
            case self::PATTERN_DOMAIN:
                $locale = $this->resolveFromDomain($request);
                $request->setLocale($locale);
                break;
        }

        return $request->getLocale();
    }
1342548
protected function detect($uri=NULL) {
		$this->current=$this->primary;
		if (preg_match('/^'.preg_quote($this->f3->get('BASE'),'/').'\/([^\/?]+)([\/?]|$)/',$uri?:$_SERVER['REQUEST_URI'],$m) &&
				array_key_exists($m[1],$this->languages))
			$this->current=$m[1];
		else {//auto-detect language
			$this->auto=TRUE;
			$detected=array_intersect(explode(',',$this->f3->get('LANGUAGE')),explode(',',implode(',',$this->languages)));
			if ($detected=reset($detected))
				foreach($this->languages as $lang=>$locales)
					if (in_array($detected,explode(',',$locales))) {
						$this->current=$lang;
						break;
					}
		}
		$this->f3->set('LANGUAGE',$this->languages[$this->current]);
	}
1256588
public static function getLangFromRequest()
    {
        if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            return '';
        }

        $languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
        foreach ($languages as $bl) {
            if (preg_match('/^([a-zA-Z]{2,3})(?:[-_]([a-zA-Z]{2,3}))?(;q=[0-9]\\.[0-9])?$/', $bl, $match)) {
                $lang = strtolower($match[1]);

                return $lang;
            }
        }

        return '';
    }
1234452
private static function resolveScheme(){
        $scheme = filter_input(INPUT_SERVER, "REQUEST_SCHEME");
        $https  = filter_input(INPUT_SERVER, "HTTPS");

        if(is_string($scheme)){
            return strtolower($scheme);
        }

        if(null !== $https){
            if(is_bool($https)){
                return $https ? "https" : "http";
            }

            return "off" === $https ? "http" : "https";
        }

        return "http";
    }
400088
protected function detectLanguage($lang, $request)
    {
        $lang = $this->setLanguagInSession($lang);

        $this->sessionValues = $_SESSION[self::SESSION_PARAMETER_LANGUAGE_COMPONENT];

        $this->checkForceRedirect($lang, $request);
    }
810435
public function resolve()
    {
        $httpHost = $this->request->getHttpHost();
        $domains = explode('.', $httpHost);
        $level = config('localizer.domain.level', 3);

        return ($total = count($domains)) >= $level ? $domains[$total - $level] : null;
    }
592085
protected function detectByRequestHeader()
    {
        // Direct stop of processing if needed header not set
        if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            return false;
        }

        // Process header accept-language (except-language should be like 'de-de,de;q=0.8,en;q=0.3,en-us;q=0.5')
        $acceptedLanguages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);

        // Valid result?
        if (count($acceptedLanguages) < 1) {
            return false;
        }

        // iterate over raw header-entries and extract
        foreach ($acceptedLanguages as $acceptedLanguage) {
            // prepare by splitting
            $parts = explode(';', $acceptedLanguage);

            // locale preset
            $locale = strtolower(trim($parts[0]));
            $weight = 1;

            // check if q is set
            if (count($parts) > 1) {
                $weight = trim(str_replace('q=', '', $parts[1]));
            }

            // if locale is valid add it
            if ($this->isValidLocaleCode($locale) && $weight >= 0) {
                $this->addLocale($locale, $weight);
            }
        }

        // Now sort by it's weight!
        $this->detectedLocales = $this->sortByWeight($this->detectedLocales);

        // iterate over sorted result and retrieve language and country in correct order
        foreach ($this->detectedLocales as $localeSet) {
            $parts    = explode('-', $localeSet['locale']);
            $parts[1] = (isset($parts[1])) ? $parts[1] : $parts[0];

            // get language and country validated
            $language = ($this->isValidLocaleCode($parts[0])) ? $parts[0] : null;
            $country  = ($this->isValidLocaleCode($parts[1])) ? $parts[1] : null;

            // store
            $this->detectedLanguages[] = $language;
            $this->detectedCountries[] = $country;
        }

        // Success - return the preferred locale-set
        return [
            'locale'   => $this->detectedLocales[0]['locale'],
            'weight'   => $this->detectedLocales[0]['weight'],
            'language' => $this->detectedLanguages[0],
            'country'  => $this->detectedCountries[0],
        ];
    }
277120
function languages()
    {
        // trust configuration
        $configured = $this->rc->config->get('spellcheck_languages');
        if (!empty($configured) && is_array($configured) && !$configured[0]) {
            return $configured;
        }
        else if (!empty($configured)) {
            $langs = (array)$configured;
        }
        else if ($this->backend) {
            $langs = $this->backend->languages();
        }

        // load index
        @include(RCUBE_LOCALIZATION_DIR . 'index.inc');

        // add correct labels
        $languages = array();
        foreach ($langs as $lang) {
            $langc = strtolower(substr($lang, 0, 2));
            $alias = $rcube_language_aliases[$langc];
            if (!$alias) {
                $alias = $langc.'_'.strtoupper($langc);
            }
            if ($rcube_languages[$lang]) {
                $languages[$lang] = $rcube_languages[$lang];
            }
            else if ($rcube_languages[$alias]) {
                $languages[$lang] = $rcube_languages[$alias];
            }
            else {
                $languages[$lang] = ucfirst($lang);
            }
        }

        // remove possible duplicates (#1489395)
        $languages = array_unique($languages);

        asort($languages);

        return $languages;
    }
1103696
protected function checkForAlternateVerbs($request)
	{
		$methods = array_diff(Router::$verbs, array($request->getMethod()));

		// Here we will spin through all verbs except for the current request verb and
		// check to see if any routes respond to them. If they do, we will return a
		// proper error response with the correct headers on the response string.
		$others = array();

		foreach ($methods as $method)
		{
			if ( ! is_null($this->check($this->get($method), $request, false)))
			{
				$others[] = $method;
			}
		}

		return $others;
	}
1166299
private function parseAcceptLanguage(Request $request)
    {
        $locales = [];
        $acceptLanguage = trim($request->headers->get('Accept-Language'));

        if (!empty($acceptLanguage)) {
            $locales = array_map(function (AcceptLanguage $acceptLanguage) {
                return $acceptLanguage->getType();
            }, $this->localeNegotiator->parse($acceptLanguage));
        }

        return $locales;
    }
1355847
private function resolveFromLanguage(array $parameters): ?Language
    {
        if (isset($parameters['fromLanguage'])) {
            return $parameters['fromLanguage'];
        }

        if (isset($parameters['fromLanguageCode'])) {
            return $this->loadLanguage($parameters['fromLanguageCode']);
        }

        return null;
    }
137701
public function searchAction(Request $request)
    {
        $this->get('session')->remove('language_search_session');

        if ($request->getMethod() === Request::METHOD_POST) {

            $form = $this->createForm(new LanguageFormType(),new Language(),array(
                'search' => true,
            ));

            $form->handleRequest($request);

            $this->get('session')->set('language_search_session',serialize($form->getData()));
        }

        return $this->redirect($this->generateUrl('admin_language'));
    }
966435
private function askAboutDefaultLanguage()
    {
        $languageList = [];
        foreach(Language::ISOlist() as $language){
            $languageList[] = $language->name;
        }

        $languageName = $this->anticipate('What is your site\'s primary language?', $languageList, 'English');
        $this->PRIMARY_LANGUAGE = Language::getISOByName($languageName);
        if(!$this->PRIMARY_LANGUAGE) {
            throw  new \Exception('Langauge could not be found in ISO 639.1 list!');
        }
    }
66482
public function detect()
	{
		if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
		{
			$browserLangs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
			$systemLangs  = $this->available();
			foreach ($browserLangs as $browserLang)
			{
				// Slice out the part before ; on first step, the part before - on second, place into array
				$browserLang = substr($browserLang, 0, strcspn($browserLang, ';'));
				$primary_browserLang = substr($browserLang, 0, 2);
				foreach ($systemLangs as $systemLang)
				{
					// Take off 3 letters iso code languages as they can't match browsers' languages and default them to en
					$Jinstall_lang = $systemLang->lang_code;

					if (strlen($Jinstall_lang) < 6)
					{
						if (strtolower($browserLang) == strtolower(substr($systemLang->lang_code, 0, strlen($browserLang))))
						{
							return $systemLang->lang_code;
						}
						elseif ($primary_browserLang == substr($systemLang->lang_code, 0, 2))
						{
							$primaryDetectedLang = $systemLang->lang_code;
						}
					}
				}

				if (isset($primaryDetectedLang))
				{
					return $primaryDetectedLang;
				}
			}
		}

		return null;
	}
383556
public function resolve()
    {
        if (static::$environment !== null) {
            return static::$environment;
        }

        $language = setlocale(LC_ALL, 0);
        $languages = explode(';', $language);
        $languageArray = [];

        foreach ($languages as $locale) {
            if (strpos($locale, '=') !== false) {
                $language = substr($locale, strpos($locale, '='));
                $language = substr($language, 1);
            }
            if ($language !== 'C') {
                if (strpos($language, '.') !== false) {
                    $language = substr($language, 0, strpos($language, '.'));
                } else {
                    if (strpos($language, '@') !== false) {
                        $language = substr($language, 0, strpos($language, '@'));
                    }
                }
                $language = str_ireplace(
                    array_keys(Data::$languages),
                    array_values(Data::$languages),
                    (string)$language
                );
                $language = str_ireplace(array_keys(Data::$regions), array_values(Data::$regions), $language);

                $languageArray[$language] = 1;
                if (strpos($language, '_') !== false) {
                    $languageArray[substr($language, 0, strpos($language, '_'))] = 1;
                }
            }
        }
        static::$environment = $languageArray;

        return ! empty($languageArray) ? array_keys($languageArray)[0] : null;
    }