preparePage

@param Site      $site
@param Page|null $page
@param null      $revisionId

@return mixed|null
@throws RevisionNotFoundException
761677
protected function preparePage(
        Site $site,
        $page,
        $revisionId = null
    ) {
        if (empty($page)) {
            $page = $this->getNotFoundPage($site);
            $page->setCurrentRevision($page->getPublishedRevision());

            return $page;
        }

        $revision = $this->getRevision($site, $page, $revisionId);

        if (empty($revision)) {
            $page = $this->getNotFoundPage($site);
            $page->setCurrentRevision($page->getPublishedRevision());

            return $page;
        }

        $page->setCurrentRevision($revision);

        return $page;
    }
1290722
public function createSite(
        Site $newSite
    ) {
        $newSite = $this->prepareNewSite($newSite);

        $entityManager = $this->getEntityManager();

        /** @var \Rcm\Repository\Page $pageRepo */
        $pageRepo = $entityManager->getRepository(\Rcm\Entity\Page::class);

        $user = $this->getCurrentUserTracking();

        $entityManager->persist($newSite);
        $entityManager->flush($newSite);

        $this->siteVersionRepo->publish(
            new SiteLocator($newSite->getDomainName()),
            $this->siteToImmutableSiteContent($newSite),
            $this->getCurrentUserTracking()->getId(),
            __CLASS__ . '::' . __FUNCTION__,
            $newSite->getSiteId()
        );

        foreach ($this->getDefaultSitePageSettings($user) as $name => $pageData) {
            $createdPage = $this->pageMutationService->createNewPage(
                $user,
                $newSite->getSiteId(),
                $pageData['name'],
                $pageData['pageType'],
                //Axosoft ticket #22776 was created to fix this @TODO. it is a pretty low priority issue
                $pageData //@TODO this is probably not in the correct format for plugins/blocks/pluginWrapper data
            );
            $this->pageMutationService->publishPageRevision(
                $user,
                $newSite->getSiteId(),
                $pageData['name'],
                $pageData['pageType'],
                $createdPage->getStagedRevision()->getRevisionId(),
                function ($pageName, $pageType = PageTypes::NORMAL, $pageRevision = null) {
                    if ($pageType !== PageTypes::NORMAL || $pageRevision !== null) {
                        throw new \Exception('Unsupported Case');

                        return '/' . $pageName;
                    }
                }
            );
        }

        return $newSite;
    }
474280
public function setSite($site = null)
    {
        $this->site = null;

        if (($site = SiteHelper::resolve($site)) === null) {
            $this->site = $this->siteId = null;
        } else {
            $this->siteId = $site->id;
            $this->site = $site;
        }

        return $this;
    }
666828
protected function getNotFoundPage(
        Site $site
    ) {
        $page = $this->findPage->__invoke(
            $site->getSiteId(),
            $site->getNotFoundPage(),
            PageTypes::NORMAL
        );

        if (empty($page)) {
            throw new PageNotFoundException(
                'No default page defined for 404 not found error'
            );
        }

        return $page;
    }
657552
public function svnUser($site, $userId)
    {
        $variables = array(
            'site' => $site,
            'id' => $userId,
        );
        $request = $this->get(array('{+base_path}/sites/{site}/svnusers/{id}.json', $variables));
        return new Response\SvnUser($request);
    }
758311
protected function buildSite($rootPageId)
    {
        $rootPageRecord = (array)BackendUtility::getRecord('pages', $rootPageId);

        $this->validateRootPageRecord($rootPageId, $rootPageRecord);
        $solrConfiguration = Util::getSolrConfigurationFromPageId($rootPageId);
        $domain = $this->getDomainFromConfigurationOrFallbackToDomainRecord($rootPageId);
        $siteHash = $this->getSiteHashForDomain($domain);
        $defaultLanguage = $this->getDefaultLanguage($rootPageId);
        $pageRepository = GeneralUtility::makeInstance(PagesRepository::class);

        return GeneralUtility::makeInstance(
            Site::class,
            /** @scrutinizer ignore-type */ $solrConfiguration,
            /** @scrutinizer ignore-type */ $rootPageRecord,
            /** @scrutinizer ignore-type */ $domain,
            /** @scrutinizer ignore-type */ $siteHash,
            /** @scrutinizer ignore-type */ $pageRepository,
            /** @scrutinizer ignore-type */ $defaultLanguage
        );
    }
503072
public function removeEmptyPages(Site $site)
    {
        $q = $this->createQueryBuilder('p')
            ->select()
            ->andWhere('p._contentset IS NULL')
            ->andWhere('p._site = :site')
            ->orderBy('p._leftnode', 'desc')
            ->setParameter('site', $site);

        foreach ($q->getQuery()->execute() as $page) {
            $this->deletePage($page);
        }
    }
1299539
public function pruneSite(Site $site)
    {
        $siteNodePath = NodePaths::addNodePathSegment(static::SITES_ROOT_PATH, $site->getNodeName());
        $this->nodeDataRepository->removeAllInPath($siteNodePath);
        $siteNodes = $this->nodeDataRepository->findByPath($siteNodePath);
        foreach ($siteNodes as $siteNode) {
            $this->nodeDataRepository->remove($siteNode);
        }

        $site->setPrimaryDomain(null);
        $this->siteRepository->update($site);

        $domainsForSite = $this->domainRepository->findBySite($site);
        foreach ($domainsForSite as $domain) {
            $this->domainRepository->remove($domain);
        }
        $this->persistenceManager->persistAll();

        $this->siteRepository->remove($site);

        $this->emitSitePruned($site);
    }
671668
public function assertCanCreateSitePage(
        SiteEntity $site,
        $pageName,
        $pageType
    ) {
        $allowDuplicates = $this->allowDuplicates($pageType);

        if ($allowDuplicates) {
            return;
        }

        $pageExists = $this->sitePageExists(
            $site,
            $pageName,
            $pageType
        );

        if (!$pageExists) {
            return;
        }

        throw new PageException(
            "Cannot create page: ({$pageName}). " .
            "Duplicate page names not allowed for name: ({$pageName}) type: ({$pageType}) siteId: " .
            '(' . $site->getSiteId() . ')'
        );
    }
34906
public function flushErrorsBySite(Site $site) : int
    {
        $queryBuilder = $this->getQueryBuilder();
        $affectedRows = $this->getPreparedFlushErrorQuery($queryBuilder)
            ->andWhere(
                $queryBuilder->expr()->eq('root', (int)$site->getRootPageId())
            )
            ->execute();
        return $affectedRows;
    }
855111
public function saveTemplateFromRevision($template_name, $revision_id) {
        $revision_id = (int) $revision_id;
        return $this->saveTemplate($template_name, [ 'revision' => $revision_id ]);
    }
895974
private function getEditParams( Revision $revision, EditInfo $editInfo = null ) {
		if ( !$revision->getPageIdentifier()->identifiesPage() ) {
			throw new RuntimeException( '$revision PageIdentifier does not identify a page' );
		}

		$params = [];

		$content = $revision->getContent();
		$data = $content->getData();
		if ( !is_string( $data ) ) {
			throw new RuntimeException( 'Dont know how to save content of this model.' );
		}
		$params['text'] = $content->getData();
		$params['md5'] = md5( $content->getData() );

		$timestamp = $revision->getTimestamp();
		if ( !is_null( $timestamp ) ) {
			$params['basetimestamp'] = $timestamp;
		}

		if ( !is_null( $revision->getPageIdentifier()->getId() ) ) {
			$params['pageid'] = $revision->getPageIdentifier()->getId();
		} else {
			$params['title'] = $revision->getPageIdentifier()->getTitle()->getTitle();
		}

		$params['token'] = $this->api->getToken();

		if ( $this->api->isLoggedin() ) {
			$params['assert'] = 'user';
		}

		$this->addEditInfoParams( $editInfo, $params );

		return $params;
	}
260237
protected function getTranslationOverlaysWithConfiguredSite($pageId, Site $site, $defaultLanguageUid, $siteLanguages)
    {
        $translationOverlays = $this->getTranslationOverlaysForPage($pageId, $site->getSysLanguageMode($defaultLanguageUid));

        foreach ($translationOverlays as $key => $translationOverlay) {
            if (!in_array($translationOverlay['sys_language_uid'], $siteLanguages)) {
                unset($translationOverlays[$key]);
            }
        }

        return $translationOverlays;
    }
1130198
public function update(SiteInterface $site, OutputInterface $output = null, $clean = false)
    {
        $message = sprintf(
            ' > <info>Updating core routes for site</info> : <comment>%s - %s</comment>',
            $site->getName(),
            $site->getUrl()
        );

        $this->writeln($output, [
            str_repeat('=', \strlen($message)),
            '',
            $message,
            '',
            str_repeat('=', \strlen($message)),
        ]);

        $knowRoutes = [];

        $root = $this->pageManager->getPageByUrl($site, '/');

        // no root url for the given website, create one
        if (!$root) {
            $root = $this->createRootPage($site);
            $this->pageManager->save($root);
        }

        // Iterate over declared routes from the routing mechanism
        foreach ($this->router->getRouteCollection()->all() as $name => $route) {
            $name = trim($name);

            $knowRoutes[] = $name;

            $page = $this->pageManager->findOneBy([
                'routeName' => $name,
                'site' => $site->getId(),
            ]);

            $routeHostRegex = $route->compile()->getHostRegex();

            if (
                !$this->decoratorStrategy->isRouteNameDecorable($name)
                || !$this->decoratorStrategy->isRouteUriDecorable($route->getPath())
                || null !== $routeHostRegex
                && !preg_match($routeHostRegex, $site->getHost())
            ) {
                if ($page) {
                    $page->setEnabled(false);

                    $this->writeln($output, sprintf(
                        '  <error>DISABLE</error> <error>% -50s</error> %s',
                        $name,
                        $route->getPath()
                    ));
                } else {
                    continue;
                }
            }

            $update = true;

            if (!$page) {
                $update = false;

                $requirements = $route->getRequirements();

                $page = $this->pageManager->create([
                    'routeName' => $name,
                    'name' => $name,
                    'url' => $route->getPath(),
                    'site' => $site,
                    'requestMethod' => $requirements['_method'] ??
                        'GET|POST|HEAD|DELETE|PUT',
                ]);
            }

            if (!$page->getParent() && $page->getId() !== $root->getId()) {
                $page->setParent($root);
            }

            $page->setSlug($route->getPath());
            $page->setUrl($route->getPath());
            $page->setRequestMethod($requirements['_method'] ??
                'GET|POST|HEAD|DELETE|PUT');

            $this->pageManager->save($page);

            $this->writeln($output, sprintf(
                '  <info>%s</info> % -50s %s',
                $update ? 'UPDATE ' : 'CREATE ',
                $name,
                $route->getPath()
            ));
        }

        // Iterate over error pages
        foreach ($this->exceptionListener->getHttpErrorCodes() as $name) {
            $name = trim((string) $name);

            $knowRoutes[] = $name;

            $page = $this->pageManager->findOneBy([
                'routeName' => $name,
                'site' => $site->getId(),
            ]);

            if (!$page) {
                $params = [
                    'routeName' => $name,
                    'name' => $name,
                    'decorate' => false,
                    'site' => $site,
                ];

                $page = $this->pageManager->create($params);

                $this->writeln($output, sprintf('  <info>%s</info> % -50s %s', 'CREATE ', $name, ''));
            }

            // an internal page or an error page should not have any parent (no direct access)
            $page->setParent(null);
            $this->pageManager->save($page);
        }

        $has = false;

        foreach ($this->pageManager->getHybridPages($site) as $page) {
            if (!$page->isHybrid() || $page->isInternal()) {
                continue;
            }

            if (!\in_array($page->getRouteName(), $knowRoutes, true)) {
                if (!$has) {
                    $has = true;

                    $this->writeln($output, ['', 'Some hybrid pages does not exist anymore', str_repeat('-', 80)]);
                }

                if ($clean) {
                    $this->pageManager->delete($page);

                    $this->writeln($output, sprintf('  <error>REMOVED</error>   %s', $page->getRouteName()));
                } else {
                    $this->writeln($output, sprintf('  <error>ERROR</error>   %s', $page->getRouteName()));
                }
            }
        }

        if ($has && !$clean) {
            $this->writeln($output, <<<'MSG'
<error>
  *WARNING* : Pages has been updated however some pages do not exist anymore.
              You must remove them manually.
</error>
MSG
            );
        }
    }
1336302
protected function prepareLayoutView(
        ModelInterface $layoutView,
        Site $site,
        Page $page
    ) {
        $layoutOverRide = $page->getSiteLayoutOverride();

        if (!empty($layoutOverRide)) {
            $layoutTemplatePath = $this->getLayoutManager()->getSiteLayout(
                $site,
                $layoutOverRide
            );

            $layoutView->setTemplate('layout/' . $layoutTemplatePath);
        }

        return $layoutView;
    }
572768
public function newSiteAction(Site $site = null)
    {
        $sitePackages = $this->packageManager->getFilteredPackages('available', null, 'neos-site');
        $documentNodeTypes = $this->nodeTypeManager->getSubNodeTypes('Neos.Neos:Document', false);
        $this->view->assignMultiple([
            'sitePackages' => $sitePackages,
            'documentNodeTypes' => $documentNodeTypes,
            'site' => $site,
            'generatorServiceIsAvailable' => $this->packageManager->isPackageAvailable('Neos.SiteKickstarter')
        ]);
    }
524731
protected function HasPages(Site $site)
    {
        $this->site = $site;
        $this->tree = new PageTreeProvider($site);
        $this->page = $this->tree->TopMost();
        return (bool) $this->page;
    }