Gets the preferred site based on the given request.

@param array   $sites   An array of enabled sites
@param Request $request A request instance

@return SiteInterface|null
776580
protected function getPreferredSite(array $sites, Request $request)
    {
        if (0 === \count($sites)) {
            return;
        }

        $sitesLocales = array_map(static function (SiteInterface $site) {
            return $site->getLocale();
        }, $sites);

        $language = $request->getPreferredLanguage($sitesLocales);
        $host = $request->getHost();

        foreach ($sites as $site) {
            if (\in_array($site->getHost(), ['localhost', $host], true) && $language === $site->getLocale()) {
                return $site;
            }
        }

        return reset($sites);
    }
1038839
public function cgetNodes(Request $request)
    {
        $tree = $this->getBooleanRequestParameter($request, 'tree', false, false);
        $ids = $this->getRequestParameter($request, 'ids');

        if (true === $tree) {
            return $this->getTreeForUuid($request, $this->getRequestParameter($request, 'id', false, null));
        } elseif (null !== $ids) {
            return $this->getNodesByIds($request, $ids);
        }

        $language = $this->getLanguage($request);
        $webspace = $this->getWebspace($request);
        $excludeGhosts = $this->getBooleanRequestParameter($request, 'exclude-ghosts', false, false);

        $parentUuid = $request->get('parentId');
        $depth = $request->get('depth', 1);
        $depth = intval($depth);
        $flat = $request->get('flat', 'true');
        $flat = ('true' === $flat);

        // TODO pagination
        $result = $this->getRepository()->getNodes(
            $parentUuid,
            $webspace,
            $language,
            $depth,
            $flat,
            false,
            $excludeGhosts
        );

        return $this->handleView($this->view($result));
    }
618549
private function getPaginationRelativeUrl(Request $request, array $parameters = array())
    {
        $relativeUrl = new RequestHelper($request, $this->router);

        return $relativeUrl->getRelativeUrl($parameters);
    }
1103972
protected function fillSite($site, array $params)
    {
        if ($site) {
            $params['site'] = $site;
        } elseif ($this->siteCode) {
            $params['site'] = $this->siteCode;
        }

        return $params;
    }
770695
public static function setSites($sites)
    {
        self::triggerSetSitesEvent($sites);

        foreach ($sites as $idsite => $site) {
            self::setSiteFromArray($idsite, $site);
        }
    }
1288201
public function chooserIndexAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $folderId = false;

        $type = $request->get('type', 'all');
        $cKEditorFuncNum = $request->get('CKEditorFuncNum');
        $linkChooser = $request->get('linkChooser');

        // Go to the last visited folder
        if ($session->get('last-media-folder')) {
            try {
                $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($session->get('last-media-folder'));
                $folderId = $session->get('last-media-folder');
            } catch (EntityNotFoundException $e) {
                $folderId = false;
            }
        }

        if (!$folderId) {
            // Redirect to the first top folder
            /* @var Folder $firstFolder */
            $firstFolder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFirstTopFolder();
            $folderId = $firstFolder->getId();
        }

        $params = array(
            'folderId' => $folderId,
            'type' => $type,
            'CKEditorFuncNum' => $cKEditorFuncNum,
            'linkChooser' => $linkChooser,
        );

        return $this->redirect($this->generateUrl('KunstmaanMediaBundle_chooser_show_folder', $params));
    }
1349644
public function indexAction( Request $request )
	{
		if( $this->hasRole( ['ROLE_ADMIN', 'ROLE_SUPER_ADMIN'] ) )
		{
			$context = $this->get( 'aimeos.context' )->get( false );
			$siteManager = \Aimeos\MShop::create( $context, 'locale/site' );
			$user = $this->get( 'security.token_storage' )->getToken()->getUser();
			$siteCode = ( $user->getSiteId() ? $siteManager->getItem( $user->getSiteId() )->getCode() : 'default' );
			$locale = $user->getLanguageId() ?: $this->getParameter( 'locale' );

			$params = array(
				'resource' => 'dashboard',
				'site' => $request->attributes->get( 'site', $request->query->get( 'site', $siteCode ) ),
				'lang' => $request->attributes->get( 'lang', $request->query->get( 'lang', $locale ) ),
			);
			return $this->redirect( $this->generateUrl( 'aimeos_shop_jqadm_search', $params ) );
		}


		$param = array( 'error' => '', 'username' => '' );

		if( $this->has( 'security.authentication_utils' ) )
		{
			$auth = $this->get( 'security.authentication_utils' );

			$param['error'] = $auth->getLastAuthenticationError();
			$param['username'] = $auth->getLastUsername();
		}

		return $this->render( 'AimeosShopBundle:Admin:index.html.twig', $param );
	}
982275
public function matchMethod(RequestInterface $request, array $maps)
    {
        $matched = [];

        $method = $request->getMethod();

        /** @var RequestMap $map */
        foreach ($maps as $map) {
            if ($map->getRequest()->getMethod() === $method) {
                $matched[] = $map;
            }
        }

        return $matched;
    }
12385
public function matchRequest(Request $request, RouteCollectionInterface $routes)
    {
        $path   = $request->getPath();
        $filtered = $this->filterByMethodAndScheme($routes, $request);

        if ($filtered instanceof CachedCollectionInterface && 0 !== count($r = $route->findByStaticPath($path))) {
            $filtered = $r;
        }

        $nomatch = array_diff_key($routes->all(), $filtered->all());

        foreach ($filtered->all() as $name => $route) {
            $rctx = $route->getContext();

            // does it match host?
            if (!$this->matchHost($rctx, $request, $route->getHost())) {
                $nomatch[$name] = $route;
                continue;
            }

            // does it match static path?
            if (0 !== strpos($path, $rctx->getStaticPath())) {
                continue;
            }

            // does it match pattern described on the route?
            if ((bool)preg_match_all($rctx->getRegex(), $path, $matches)) {
                $vars    = $this->getMatchedVars($route, $matches);
                $handler = $route->getHandler();

                return new MatchContext(self::MATCH, $name, $request, $handler, $vars);
            }

            $nomatch[$name] = $route;
        }

        return new MatchContext($this->getMatchFailureReason($nomatch, $request), null, $request, null);
    }
213393
public function findByRequest(Request $request): ?PageInterface
    {
        if (null !== $route = $request->attributes->get('_route', null)) {
            return $this->findByRoute($route);
        }

        return null;
    }
197670
protected function matchRequest(SiteInterface $site, Request $request)
    {
        $results = [];

        // we read the value from the attribute to handle fragment support
        $requestPathInfo = $request->get('pathInfo', $request->getPathInfo());

        if (!preg_match(sprintf('@^(%s)(/.*|$)@', $site->getRelativePath()), $requestPathInfo, $results)) {
            return false;
        }

        return $results[2];
    }
1222678
public function createAction(Request $request)
    {
        $title = $request->get('title', null);

        $siterootManager = $this->get('phlexible_siteroot.siteroot_manager');

        $siteroot = new Siteroot();
        foreach (explode(',', $this->container->getParameter('phlexible_gui.languages.available')) as $language) {
            $siteroot->setTitle($language, $title);
        }
        $siteroot
            ->setCreateUserId($this->getUser()->getId())
            ->setCreatedAt(new \DateTime())
            ->setModifyUserId($siteroot->getCreateUserId())
            ->setModifiedAt($siteroot->getCreatedAt());

        $siterootManager->updateSiteroot($siteroot);

        return new ResultResponse(true, 'New Siteroot created.');
    }
1158711
private function getWebspaceKey(Request $request, $ignoreWebspaces)
    {
        if ($ignoreWebspaces) {
            return null;
        }

        $sulu = $request->get('_sulu');
        if (!$sulu) {
            return null;
        }

        /** @var Webspace $webspace */
        $webspace = $sulu->getAttribute('webspace');
        if (!$webspace) {
            return null;
        }

        return $webspace->getKey();
    }
251605
private SitePreference getSitePreferenceQueryParameter(HttpServletRequest request) {
		String string = request.getParameter(SITE_PREFERENCE_PARAMETER);
		try {
			return string != null && string.length() > 0 ? SitePreference.valueOf(string.toUpperCase()) : null;
		} catch (IllegalArgumentException e) {
			return null;
		}
	}
547839
public function cgetAction(Request $request)
    {
        try {
            /** @var ListRestHelperInterface $listRestHelper */
            $listRestHelper = $this->get('sulu_core.list_rest_helper');
            $securityChecker = $this->get('sulu_security.security_checker');

            $flat = $this->getBooleanRequestParameter($request, 'flat', false);
            $depth = $request->get('depth', 0);
            $parentId = $request->get('parentId', null);
            $limit = $request->get('limit', null);
            $offset = $this->getOffset($request, $limit);
            $search = $listRestHelper->getSearchPattern();
            $sortBy = $request->get('sortBy');
            $sortOrder = $request->get('sortOrder', 'ASC');
            $includeRoot = $this->getBooleanRequestParameter($request, 'includeRoot', false, false);
            $collectionManager = $this->getCollectionManager();

            if ('root' === $parentId) {
                $includeRoot = false;
                $parentId = null;
            }

            if ($flat) {
                $collections = $collectionManager->get(
                    $this->getRequestParameter($request, 'locale', true),
                    [
                        'depth' => $depth,
                        'parent' => $parentId,
                    ],
                    $limit,
                    $offset,
                    null !== $sortBy ? [$sortBy => $sortOrder] : []
                );
            } else {
                $collections = $collectionManager->getTree(
                    $this->getRequestParameter($request, 'locale', true),
                    $offset,
                    $limit,
                    $search,
                    $depth,
                    null !== $sortBy ? [$sortBy => $sortOrder] : [],
                    $securityChecker->hasPermission('sulu.media.system_collections', 'view')
                );
            }

            if ($includeRoot && !$parentId) {
                $collections = [
                    new RootCollection(
                        $this->get('translator')->trans('sulu_media.all_collections', [], 'admin'),
                        $collections
                    ),
                ];
            }

            $all = $collectionManager->getCount();

            $list = new ListRepresentation(
                $collections,
                self::$entityKey,
                'get_collections',
                $request->query->all(),
                $listRestHelper->getPage(),
                $listRestHelper->getLimit(),
                $all
            );

            $view = $this->view($list, 200);
        } catch (CollectionNotFoundException $cnf) {
            $view = $this->view($cnf->toArray(), 404);
        } catch (MediaException $me) {
            $view = $this->view($me->toArray(), 400);
        }

        return $this->handleView($view);
    }
1166140
public function matchUrl(RequestInterface $request, array $maps)
    {
        $matched = [];

        $uri = (string)$request->getUri();

        /** @var RequestMap $map */
        foreach ($maps as $map) {
            if ((string)$map->getRequest()->getUri() === $uri) {
                $matched[] = $map;
            }
        }

        return $matched;
    }
833655
public function treeAction(Request $request = null)
    {
        $this->admin->checkAccess('tree');

        $sites = $this->get('sonata.page.manager.site')->findBy(array());
        $pageManager = $this->get('sonata.page.manager.page');

        $currentSite = null;
        $siteId = $request->get('site');
        foreach ($sites as $site) {
            if ($siteId && $site->getId() === $siteId) {
                $currentSite = $site;
            } elseif (!$siteId && $site->getIsDefault()) {
                $currentSite = $site;
            }
        }
        if (!$currentSite && count($sites) === 1) {
            $currentSite = $sites[0];
        }

        $showAllPages = $this->get('security.context')->isGranted('ROLE_SUPER_ADMIN');

        if ($currentSite) {
            $pages = $pageManager->loadPages($currentSite, $showAllPages);
        } else {
            $pages = array();
        }

        $datagrid = $this->admin->getDatagrid();
        $formView = $datagrid->getForm()->createView();

        $this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());

        return $this->render($this->admin->getTemplate('tree'), array(
            'action' => 'tree',
            'sites' => $sites,
            'currentSite' => $currentSite,
            'pages' => $pages,
            'form' => $formView,
            'csrf_token' => $this->getCsrfToken('sonata.batch'),
        ));
    }