Generates a response from a page url.
If seo redirect, return target.

@param string      $uri
@param string      $url
@param             $locale
@param string|null $layout

@return Response
9218
public function renderPageByUrl($uri, $url, $locale, $layout = null)
    {
        $page = null;
        if ($viewReference = $this->viewReferenceRepository->getReferenceByUrl($url, $locale)) {
            $page = $this->findPageByReference($viewReference);
            $this->checkPageValidity($page, ['url' => $url, 'locale' => $locale]);
            $page->setReference($viewReference);

            if ($page instanceof BasePage
                && $page->getSeo()
                && $page->getSeo()->getRedirectTo()
                && $page->getSeo()->getRedirectTo()->getLinkType() != Link::TYPE_NONE
                && !$this->session->get('victoire.edit_mode', false)) {
                $link = $page->getSeo()->getRedirectTo();

                return new RedirectResponse($this->container->get('victoire_widget.twig.link_extension')->victoireLinkUrl($link->getParameters()));
            }

            return $this->renderPage($page, $layout);
        } else {
            try {
                /** @var Error404 $error404 */
                $error404 = $this->entityManager->getRepository('VictoireSeoBundle:Error404')->findOneBy(['url' => $uri]);
                /** @var Redirection $redirection */
                $redirection = $this->entityManager->getRepository('VictoireSeoBundle:Redirection')->findOneBy(['url' => $uri]);

                $result = $this->redirectionHandler->handleError($redirection, $error404);

                if ($result instanceof Redirection) {
                    return new RedirectResponse($this->container->get('victoire_widget.twig.link_extension')->victoireLinkUrl(
                        $result->getLink()->getParameters()
                    ), Response::HTTP_MOVED_PERMANENTLY);
                } elseif ($result->getRedirection()) {
                    return new RedirectResponse($this->container->get('victoire_widget.twig.link_extension')->victoireLinkUrl(
                        $result->getRedirection()->getLink()->getParameters()
                    ));
                }
            } catch (NoResultException $e) {
                $error = new Error404();

                $error->setUrl($uri);
                $error->setType($this->redirectionHandler->handleErrorExtension(pathinfo($uri, PATHINFO_EXTENSION)));

                $this->entityManager->persist($error);
                $this->entityManager->flush();
            }

            throw new NotFoundHttpException(sprintf('Page not found (url: "%s", locale: "%s")', $url, $locale));
        }
    }
1153996
public function translateAction(Request $request, $id, $locale)
    {
        /** @var PageInterface $page */
        $page = $this->admin->getObject($id);

        if (!$page) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }
        $language = \Locale::getDisplayLanguage($locale);

        if ($request->getMethod() == 'POST') {
            $pageHelper = $this->container->get('networking_init_cms.helper.page_helper');

            try {
                $pageCopy = $pageHelper->makeTranslationCopy($page, $locale);
                $this->admin->createObjectSecurity($pageCopy);
                $status = 'success';
                $message = $this->translate(
                    'message.translation_saved',
                    ['%language%' => $language]
                );
                $result = 'ok';
                $html = $this->renderView(
                    '@NetworkingInitCms/PageAdmin/page_translation_settings.html.twig',
                    ['object' => $page, 'admin' => $this->admin]
                );
            } catch (\Exception $e) {
                $status = 'error';
                $message = $message = $this->translate(
                    'message.translation_not_saved',
                    ['%language%' => $language, '%url%' => $page->getFullPath()]
                );
                $result = 'error';
                $html = '';
            }

            if ($this->isXmlHttpRequest()) {
                return $this->renderJson(
                    [
                        'result' => $result,
                        'status' => $status,
                        'html' => $html,
                        'message' => $message,
                    ]
                );
            }

            $this->get('session')->getFlashBag()->add(
                'sonata_flash_'.$status,
                $message
            );

            return $this->redirect($this->admin->generateUrl('edit', ['id' => $id]));
        }

        return $this->render(
            '@NetworkingInitCms/PageAdmin/page_translation_copy.html.twig',
            [
                'action' => 'copy',
                'page' => $page,
                'id' => $id,
                'locale' => $locale,
                'language' => $language,
                'admin' => $this->admin,
            ]
        );
    }
1372378
protected function getLocalizedRedirect($locale)
    {
        return is_string($localizedUrl = $this->localization->getLocalizedURL($locale))
            ? $this->makeRedirectResponse($localizedUrl)
            : null;
    }
1030180
public function render(string $layout = null, array $context = [])
    {
        if (null === $layout) {
            $layout = 'default';
        }

        $grav = Grav::instance();

        $block = HtmlBlock::create();
        $block->disableCache();

        $output = $this->getTemplate($layout)->render(
            ['grav' => $grav, 'config' => $grav['config'], 'block' => $block, 'form' => $this, 'layout' => $layout] + $context
        );

        $block->setContent($output);

        return $block;
    }
438941
public function renderPage($view, $layout = null)
    {
        $event = new PageMenuContextualEvent($view);

        //Set currentView and dispatch victoire.on_render_page event with this currentView
        $pageRenderEvent = new PageRenderEvent($view);
        $this->eventDispatcher->dispatch('victoire.on_render_page', $pageRenderEvent);
        $this->currentViewHelper->setCurrentView($view);

        //Build WidgetMap
        $this->widgetMapBuilder->build($view, true);

        //Populate widgets with their data
        $this->widgetDataWarmer->warm($this->entityManager, $view);

        //Dispatch contextual event regarding page type
        if (in_array($view->getType(), ['business_page', 'virtual_business_page'])) {
            //Dispatch also an event with the Business entity name
            $eventName = 'victoire_core.page_menu.contextual';
            if (!$view->getId()) {
                $eventName = 'victoire_core.business_template_menu.contextual';
                $event = new PageMenuContextualEvent($view->getTemplate());
            }
            $this->eventDispatcher->dispatch($eventName, $event);
            $type = $view->getBusinessEntityId();
        } else {
            $type = $view->getType();
        }

        $eventName = 'victoire_core.'.$type.'_menu.contextual';
        $this->eventDispatcher->dispatch($eventName, $event);

        if (null === $layout) {
            //Determine which layout to use
            $layout = $this->guessBestLayoutForView($view);
        }
        $globalConfig = $this->entityManager->getRepository(GlobalConfig::class)->findLast() ?: new GlobalConfig();

        //Create the response
        $response = $this->container->get('templating')->renderResponse('VictoireCoreBundle:Layout:'.$layout.'.html.twig', [
            'globalConfig'                    => $globalConfig,
            'victoire_i18n_available_locales' => $this->availableLocales,
            'victoire_twig_responsive'        => $this->twigResponsive,
            'view'                            => $view,
        ]);

        return $response;
    }
869273
private function resolveContent(
        Row $row,
        $locale,
        $locales,
        MappingInterface $mapping,
        UserInterface $user = null
    ) {
        $webspaceKey = $this->nodeHelper->extractWebspaceFromPath($row->getPath());

        $originalLocale = $locale;
        $availableLocales = $this->resolveAvailableLocales($row);
        $ghostLocale = $this->localizationFinder->findAvailableLocale(
            $webspaceKey,
            $availableLocales,
            $locale
        );
        if (null === $ghostLocale) {
            $ghostLocale = reset($availableLocales);
        }

        $type = null;
        if ($row->getValue('shadowOn')) {
            if (!$mapping->shouldHydrateShadow()) {
                return;
            }
            $type = StructureType::getShadow($row->getValue('shadowBase'));
        } elseif (null !== $ghostLocale && $ghostLocale !== $originalLocale) {
            if (!$mapping->shouldHydrateGhost()) {
                return;
            }
            $locale = $ghostLocale;
            $type = StructureType::getGhost($locale);
        }

        if (
            RedirectType::INTERNAL === $row->getValue('nodeType')
            && $mapping->followInternalLink()
            && '' !== $row->getValue('internalLink')
            && $row->getValue('internalLink') !== $row->getValue('uuid')
        ) {
            // TODO collect all internal link contents and query once
            return $this->resolveInternalLinkContent($row, $locale, $webspaceKey, $mapping, $type, $user);
        }

        $shadowBase = null;
        if ($row->getValue('shadowOn')) {
            $shadowBase = $row->getValue('shadowBase');
        }

        $data = [];
        foreach ($mapping->getProperties() as $item) {
            $data[$item] = $this->resolveProperty($row, $item, $locale, $shadowBase);
        }

        $content = new Content(
            $originalLocale,
            $webspaceKey,
            $row->getValue('uuid'),
            $this->resolvePath($row, $webspaceKey),
            $row->getValue('state'),
            $row->getValue('nodeType'),
            $this->resolveHasChildren($row), $this->resolveProperty($row, 'template', $locale, $shadowBase),
            $data,
            $this->resolvePermissions($row, $user),
            $type
        );
        $content->setRow($row);

        if (!$content->getTemplate() || !$this->structureManager->getStructure($content->getTemplate())) {
            $content->setBrokenTemplate();
        }

        if ($mapping->resolveUrl()) {
            $url = $this->resolveUrl($row, $locale);
            $urls = [];
            array_walk(
                $locales,
                function($item) use (&$urls, $row) {
                    $urls[$item] = $this->resolveUrl($row, $item);
                }
            );

            $content->setUrl($url);
            $content->setUrls($urls);
        }

        if ($mapping->resolveConcreteLocales()) {
            $locales = $this->resolveAvailableLocales($row);
            $content->setContentLocales($locales);
        }

        return $content;
    }
447766
protected function _addPageNrParam($url, $page, $languageId = null)
    {
        if ($page) {
            if ((strpos($url, 'pgNr='))) {
                $url = preg_replace('/pgNr=[0-9]*/', 'pgNr=' . $page, $url);
            } else {
                $url .= ((strpos($url, '?') === false) ? '?' : '&amp;') . 'pgNr=' . $page;
            }
        } else {
            $url = preg_replace('/pgNr=[0-9]*/', '', $url);
            $url = preg_replace('/\&amp\;\&amp\;/', '&amp;', $url);
            $url = preg_replace('/\?\&amp\;/', '?', $url);
            $url = preg_replace('/\&amp\;$/', '', $url);
        }

        return $url;
    }
150497
private function buildQuery(string $url, string $apiKey, string $locale = null, string $region = null) : string
    {
        if (null !== $apiKey) {
            $url = sprintf('%s&key=%s', $url, $apiKey);
        }
        if (null !== $locale) {
            $url = sprintf('%s&language=%s', $url, $locale);
        }
        if (null !== $region) {
            $url = sprintf('%s&region=%s', $url, $region);
        }

        return $url;
    }
452428
public function addItemAction(Request $request, Layout $layout)
    {
        $this->guard($layout, 'update');

        $region = $this->validateInputAndGetRegionName($request);

        $nid = $request->get('nid');
        if (empty($nid)) {
            throw $this->createNotFoundException();
        }
        if (!$node = $this->getNodeStorage()->load($nid)) {
            throw $this->createNotFoundException();
        }
        if (!$node->access('view')) {
            throw $this->createAccessDeniedException();
        }

        $viewmode = $request->get('view_mode', 'teaser');
        $position = $request->get('position');
        $manager  = $this->getContextManager();
        $site     = $this->getSiteContext();
        $item     = new Item($nid, $viewmode);
        $region   = $layout->getRegion($region);

        $region->addAt($item, $position);

        if ($manager->isPageContextRegion($region->getName(), $site->theme)) {
            $manager->getPageContext()->getStorage()->save($layout);
        } else if ($manager->isTransversalContextRegion($region->getName(), $site->theme)) {
            $manager->getSiteContext()->getStorage()->save($layout);
        } else {
            throw $this->createAccessDeniedException();
        }

        return new JsonResponse(['success' => true, 'output' => $this->renderNode($node, $region, $viewmode)]);
    }
1247508
public function handle($request, Closure $next, $theme = null, $layout = null)
    {
        if(isset($theme)) Theme::uses($theme);
        if(isset($layout)) Theme::layout($layout);

        return $next($request);
       
/*
        $response = $next($request);
        
        $originalContent = $response->getOriginalContent();

        if(!is_string($originalContent)) {
            $view_name = $originalContent->getName();
            
            $data = $originalContent->getData();
        } else {
            $view_name = $response->exception->getTrace()[0]['args'][0];
        }
        

        return $theme->scope($view_name, $data)->render();
*/
    }
194811
public function createRedirectResponse(View $view, $location, $format)
    {
        $content = null;
        if ((Response::HTTP_CREATED === $view->getStatusCode() || Response::HTTP_ACCEPTED === $view->getStatusCode()) && null !== $view->getData()) {
            $response = $this->initResponse($view, $format);
        } else {
            $response = $view->getResponse();
            if ('html' === $format && isset($this->forceRedirects[$format])) {
                $redirect = new RedirectResponse($location);
                $content = $redirect->getContent();
                $response->setContent($content);
            }
        }

        $code = isset($this->forceRedirects[$format])
            ? $this->forceRedirects[$format] : $this->getStatusCode($view, $content);

        $response->setStatusCode($code);
        $response->headers->set('Location', $location);

        return $response;
    }
415621
protected function determineLocaleAndQuery($locale, $query)
    {
        if (is_null($query))
        {
            $modelName = $this->getViewModelName();

            $query = with(new $modelName)->newQuery();
        }

        if ($locale)
        {
            $query->where('locale', $locale);
        }

        return $query;
    }
915441
public function set($locale, Request $request)
    {
        $this->setLocale($locale, $request);

        return redirect()->back();
    }
542960
public function editAction(Request $request, $layoutId, $lang = null)
    {
        $layout= $this->get('doctrine.orm.entity_manager')->find('LexikMailerBundle:Layout', $layoutId);

        if (!$layout) {
            throw $this->createNotFoundException(sprintf('No layout found for id "%d".', $layoutId));
        }

        $handler = $this->get('lexik_mailer.form.handler.layout');
        $form = $handler->createForm($layout, $lang);

        if ($handler->processForm($form, $request)) {
            return $this->redirect($this->generateUrl('lexik_mailer.layout_edit', array(
                'layoutId' => $layout->getId(),
                'lang'     => $lang,
            )));
        }

        return $this->render('LexikMailerBundle:Layout:edit.html.twig', array_merge(array(
            'form'          => $form->createView(),
            'base_layout'   => $this->container->getParameter('lexik_mailer.base_layout'),
            'layout'        => $layout,
            'lang'          => $lang,
            'displayLang'   => \Locale::getDisplayLanguage($lang),
            'routePattern'  => urldecode($this->generateUrl('lexik_mailer.layout_edit', array('layoutId' => $layout->getId(), 'lang' => '%lang%'), true)),
        ), $this->getAdditionalParameters()));
    }
309559
protected static function stripLocale($url, $locale)
    {
        if (!self::hasLocaleUrl()) {
            return $url;
        }

        $locale = substr($locale, 0, 2);
        $parts = explode('/', $url);

        if(count($parts) < 2){
        	return $url;
        }

        $urlLocale = $parts[1];

        if ($urlLocale === $locale) {
            return substr($url, 3);
        }

        return $url;
    }
449015
public function getLayoutId(): \Psr\Http\Message\UriInterface
    {
        if (!$this->layoutId) {
            return new Uri();
        }

        return $this->layoutId;
    }
877616
private function executeQuery(string $url, string $locale = null): string
    {
        if (null !== $locale) {
            $url = sprintf('%s&accept-language=%s', $url, $locale);
        }

        return $this->getUrlContents($url);
    }