Get the locale code from the lang attribute in URL.

@param Request $request
@return null|string
517300
private function getViewLocale(Request $request)
    {
        $viewLocale = $request->query->get('lang', null);
        if (null === $viewLocale) {
            // fallback for old parameter
            $viewLocale = $request->query->get('locale', null);
        }

        return $viewLocale;
    }
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]
1308694
protected function getUrlLanguage($locale = null)
    {
        // Check if the functionality is activated
        if (!ConfigQuery::isMultiDomainActivated()) {
            return null;
        }

        // If we don't have a locale value, use the locale value in the session
        if (!$locale) {
            $locale = $this->getCurrentEditionLocale();
        }

        return LangQuery::create()->findOneByLocale($locale)->getUrl();
    }
308773
public function detectLocale(HTTPRequest $request)
    {
        // Given multiple canditates, narrow down the final result using the client's preferred languages
        $inputLocales = $request->getHeader('Accept-Language');
        if (empty($inputLocales)) {
            return null;
        }

        // Generate mapping of priority => list of locales at this priority
        // break up string into pieces (languages and q factors)
        preg_match_all(
            '/(?<code>[a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(?<priority>1|0\.[0-9]+))?/i',
            $inputLocales,
            $parsedLocales
        );

        $prioritisedLocales = [];
        if (count($parsedLocales['code'])) {
            // create a list like "en" => 0.8
            $parsedLocales = array_combine($parsedLocales['code'], $parsedLocales['priority']);

            // Generate nested list of priorities => [locales]
            foreach ($parsedLocales as $locale => $priority) {
                $priority = empty($priority) ? "1.0" : (string)floatval($priority);
                if (empty($prioritisedLocales[$priority])) {
                    $prioritisedLocales[$priority] = [];
                }
                $prioritisedLocales[$priority][] = $locale;
            }

            // sort list based on value
            krsort($prioritisedLocales, SORT_NUMERIC);
        }

        // Check each requested locale against loaded locales
        $locales = Locale::getLocales(true);
        foreach ($prioritisedLocales as $priority => $parsedLocales) {
            foreach ($parsedLocales as $browserLocale) {
                foreach ($locales as $localeObj) {
                    /** @var Locale $localeObj */
                    if ($localeObj->isLocale($browserLocale)) {
                        return $localeObj;
                    }
                }
            }
        }
        return null;
    }
1224378
private function setLocale($locale, $request)
    {
        $allowedLangs = array_keys(Localizer::allowedLanguages());
        if (config('localizer.block_unallowed_langs') && !in_array($locale, $allowedLangs)) {
            abort(404, 'Unallowed language');
        }

        if (Auth::check()) {
            $user = Auth::User();
            $user->locale = $locale;
            $user->save();
        } else {
            $request->session()->put('locale', $locale);
        }
    }
558723
public String resolveLocaleCode(HttpServletRequest request) {
		org.springframework.web.servlet.LocaleResolver resolver = RequestContextUtils.getLocaleResolver(request);
		Locale resolved = resolver.resolveLocale(request);
		if(resolved != Locale.getDefault())
			return resolved.toString();
		else return null;
	}
262716
private function getFormat(Request $request): string
    {
        /**
         * @var string|null
         */
        $contentType = $request->headers->get('CONTENT_TYPE');
        if (null === $contentType) {
            throw new NotAcceptableHttpException('The "Content-Type" header must exist.');
        }

        $format = $this->formatMatcher->getFormat($contentType);
        if (null === $format || !isset($this->formats[$format])) {
            $supportedMimeTypes = [];
            foreach ($this->formats as $mimeTypes) {
                foreach ($mimeTypes as $mimeType) {
                    $supportedMimeTypes[] = $mimeType;
                }
            }

            throw new NotAcceptableHttpException(sprintf(
                'The content-type "%s" is not supported. Supported MIME types are "%s".',
                $contentType,
                implode('", "', $supportedMimeTypes)
            ));
        }

        return $format;
    }
83926
public function sitemapAction(Request $request, $locale)
    {
        $params = [];
        $params['domain'] = $this->getDomainName($request);
        $params['languages'] = $this->container->getParameter('networking_init_cms.page.languages');

        if ($locale != '' or count($params['languages']) == 1) {
            //sitemap ausgeben
            if ($locale == '') {  //use locale as default value
                $locale = $params['languages']['locale'];
            }
            $page_filter = ['visibility' => 'public', 'status' => 'status_published', 'locale' => $locale];
            $em = $this->getDoctrine()->getManager();
            $pageClass = $this->getParameter('networking_init_cms.manager.page.class');
            $params['pages'] = $em->getRepository($pageClass)->findBy($page_filter);
            $params['additional_links'] = $this->getAdditionalLinks($locale);
            //render xml
            $response = $this->render(
                'NetworkingInitCmsBundle:Sitemap:sitemap.xml.twig',
                $params
            );
        } else {
            //multilanguage site, return language overview sitemap

            /* TODO , check if / how "last modified" is possible */
            $response = $this->render(
                'NetworkingInitCmsBundle:Sitemap:multilingual_sitemap.xml.twig',
                $params
            );
        }

        $response->headers->set('Content-Type', 'application/xml');

        return $response;
    }
1012060
protected function getRequestOrigin(HTTPRequest $request)
    {
        // Prefer Origin header
        $origin = $request->getHeader('Origin');
        if ($origin) {
            return $origin;
        }

        // Check referer
        $referer = $request->getHeader('Referer');
        if ($referer) {
            // Extract protocol, hostname, and port
            $refererParts = parse_url($referer);
            if (!$refererParts) {
                return null;
            }
            // Rebuild
            $origin = $refererParts['scheme'] . '://' . $refererParts['host'];
            if (isset($refererParts['port'])) {
                $origin .= ':' . $refererParts['port'];
            }
            return $origin;
        }

        return null;
    }
498371
private function getTraceKey(Request $request): string
    {
        $path = $request->getPathInfo();
        if ($qs = $request->getQueryString()) {
            $path .= '?'.$qs;
        }

        return $request->getMethod().' '.$path;
    }
289031
public function indexAction(Request $request)
    {
        /** @var TranslationManager $manager */
        $manager = $this->get('ongr_translations.translation_manager');

        return $this->render(
            'ONGRTranslationsBundle:List:list.html.twig',
            [
                'locales' => $this->getParameter('ongr_translations.locales'),
                'tags' => $manager->getTags(),
                'domains' => $manager->getDomains(),
            ]
        );
    }
606583
protected Locale getLocale(RequestContext context) {
    return this.locale != null ? this.locale : context.getExternalContext().getLocale();
  }
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();
    }
196915
public function negotiate(Request $request)
    {
        if ([] === $this->supportedLocales) {
            return null;
        }

        if (!$request->hasHeader('Accept-Language')) {
            return null;
        }

        $aggregatedValues = $this->aggregatedValues($request->getHeaderLine('Accept-Language'));

        return $this->compareAgainstSupportedLocales($aggregatedValues);
    }
509253
public static function setLangAttribute($request)
    {
        // language may be present in url without {param} defined
        $languageSlug= self::setFromURL($request);
        if(!$languageSlug) {
            $languageSlug = App::getLocale();
        }

        //add lang parameter to every route/action request if user is accessing a language that's different than default
        if(config('project.multilanguage')) {
            // hide slug on default language in frontend
            //backend
            if (!isInAdmin()) {
                if (config('project.hideDefaultLanguageInURL') && $languageSlug ==  Language::getDefault('slug')) {
                    $languageSlug = '';
                }
            }

            URL::defaults(['lang' => $languageSlug]);
        }

        return;
    }
1189174
public function cgetAction(Request $request)
    {
        $webspaceKey = $this->getRequestParameter($request, 'webspace', true);
        $this->get('sulu_security.security_checker')->checkPermission(
            new SecurityCondition(SnippetAdmin::getDefaultSnippetsSecurityContext($webspaceKey)),
            PermissionTypes::VIEW
        );

        $defaultSnippetManager = $this->get('sulu_snippet.default_snippet.manager');
        $documentManager = $this->get('sulu_document_manager.document_manager');
        $areas = $this->getLocalizedAreas();

        $dataList = [];
        foreach ($areas as $key => $area) {
            $areaData = [
                'key' => $key,
                'template' => $area['template'],
                'title' => $area['title'],
                'defaultUuid' => null,
                'defaultTitle' => null,
                'valid' => true,
            ];

            try {
                $snippet = $defaultSnippetManager->load($webspaceKey, $key, $this->getUser()->getLocale());
                $areaData['defaultUuid'] = $snippet ? $snippet->getUuid() : null;
                $areaData['defaultTitle'] = $snippet ? $snippet->getTitle() : null;
            } catch (WrongSnippetTypeException $exception) {
                // ignore wrong snippet-type
                $areaData['valid'] = false;

                $uuid = $defaultSnippetManager->loadIdentifier($webspaceKey, $key);
                $snippet = $documentManager->find($uuid, $this->getUser()->getLocale());
                $areaData['defaultUuid'] = $snippet ? $snippet->getUuid() : null;
                $areaData['defaultTitle'] = $snippet ? $snippet->getTitle() : null;
            }

            $dataList[$key] = $areaData;
        }

        ksort($dataList);

        $data = [
            '_embedded' => [
                'areas' => array_values($dataList),
            ],
            'total' => count($dataList),
        ];

        return new JsonResponse($data);
    }
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;
    }