@param Site   $newSite
@param array  $defaultSiteSettings
@param string $createdByUserId
@param string $createdReason

@return Site
@throws \Exception
191954
protected function prepareNewSite(
        Site $newSite,
        array $defaultSiteSettings,
        string $createdByUserId,
        string $createdReason
    ) {
        $siteId = $newSite->getSiteId();
        if (!empty($siteId)) {
            throw new \Exception(
                "Site ID must be empty to create new site, id {$siteId} given."
            );
        }

        if (empty($newSite->getDomain())) {
            throw new \Exception('Domain is required to create new site.');
        }

        return $this->prepareDefaultValues(
            $newSite,
            $defaultSiteSettings,
            $createdByUserId,
            $createdReason
        );
    }
2761
public function copyWebsite(Website $orgWebsite, Website $newWebsite)
    {
        $orgRoot = $orgWebsite->getRoot();
        $orgOptions = $orgWebsite->getOptions();
        $websitePages = $this->websitePageRepository->children($orgRoot);
        array_unshift($websitePages, $orgRoot);
        $newWebsitePagesMap = [];

        foreach ($websitePages as $websitePage) {
            $newWebsitePage = new WebsitePage();
            $newWebsitePage->setWebsite($newWebsite);
            $newWebsitePage->importFromArray($websitePage->exportToArray());
            if ($websitePage->isRoot()) {
                $newWebsite->setRoot($newWebsitePage);
                $this->om->persist($newWebsite);
            } else {
                $newWebsitePageParent = $newWebsitePagesMap[$websitePage->getParent()->getId()];
                $newWebsitePage->setParent($newWebsitePageParent);
                $this->websitePageRepository->persistAsLastChildOf($newWebsitePage, $newWebsitePageParent);
            }
            if ($websitePage->getIsHomepage()) {
                $newWebsite->setHomePage($newWebsitePage);
            }

            $newWebsitePagesMap[$websitePage->getId()] = $newWebsitePage;
        }
        $this->om->flush();
        $newWebsite->getOptions()->importFromArray(
            $this->webDir,
            $orgOptions->exportToArray($this->webDir),
            $this->webDir.DIRECTORY_SEPARATOR.$orgOptions->getUploadDir()
        );

        return $newWebsite;
    }
1223788
protected function createPagePlugins(
        Site $site,
        string $createdByUserId,
        string $createdReason = Tracking::UNKNOWN_REASON,
        $pagesData = [],
        $doFlush = true
    ) {
        $pages = [];
        $pageRevisions = [];

        foreach ($pagesData as $pageName => $pageData) {
            if (empty($pageData['plugins'])) {
                continue;
            }

            $page = $this->pageRepository->getPageByName($site, $pageData['name']);

            if (empty($page)) {
                continue;
            }

            $page->setModifiedByUserId(
                $createdByUserId,
                $createdReason
            );

            $pages[] = $page;

            $pageRevision = $page->getPublishedRevision();

            if (empty($pageRevision)) {
                throw new \Exception(
                    "Could not find published revision for page {$page->getPageId()}"
                );
            }

            foreach ($pageData['plugins'] as $pluginData) {
                $pluginInstance = $this->pluginInstanceRepository->createPluginInstance(
                    $pluginData,
                    $site,
                    $createdByUserId,
                    $createdReason,
                    null,
                    $doFlush
                );

                $pluginData['pluginInstanceId'] = $pluginInstance->getInstanceId();

                $wrapper = $this->pluginWrapperRepository->savePluginWrapper(
                    $pluginData,
                    $site,
                    $createdByUserId,
                    $createdReason,
                    null,
                    $doFlush
                );

                $pageRevision->addPluginWrapper($wrapper);

                $pageRevision->setModifiedByUserId(
                    $createdByUserId,
                    $createdReason
                );

                $this->entityManager->persist($pageRevision);

                $pageRevisions[] = $pageRevision;
            }
        }

        if ($doFlush) {
            $this->entityManager->flush($pages);
            $this->entityManager->flush($pageRevisions);
        }
    }
196174
private static function createSitelinksFeedMapping(
        AdWordsServices $adWordsServices,
        AdWordsSession $session,
        array $sitelinksData
    ) {
        $feedMappingService =
            $adWordsServices->get($session, FeedMappingService::class);

        // Map the feed attribute IDs to the field ID constants.
        $linkTextFieldMapping = new AttributeFieldMapping();
        $linkTextFieldMapping->setFeedAttributeId(
            $sitelinksData['linkTextFeedAttributeId']
        );
        $linkTextFieldMapping->setFieldId(
            self::PLACEHOLDER_FIELD_SITELINK_LINK_TEXT
        );
        $linkFinalUrlFieldMapping = new AttributeFieldMapping();
        $linkFinalUrlFieldMapping->setFeedAttributeId(
            $sitelinksData['linkFinalUrlFeedAttributeId']
        );
        $linkFinalUrlFieldMapping->setFieldId(
            self::PLACEHOLDER_FIELD_SITELINK_FINAL_URL
        );
        $line2FieldMapping = new AttributeFieldMapping();
        $line2FieldMapping->setFeedAttributeId(
            $sitelinksData['line2FeedAttribute']
        );
        $line2FieldMapping->setFieldId(self::PLACEHOLDER_FIELD_LINE_2_TEXT);
        $line3FieldMapping = new AttributeFieldMapping();
        $line3FieldMapping->setFeedAttributeId(
            $sitelinksData['line3FeedAttribute']
        );
        $line3FieldMapping->setFieldId(self::PLACEHOLDER_FIELD_LINE_3_TEXT);

        // Create the feed mapping and feed mapping operation.
        $feedMapping = new FeedMapping();
        $feedMapping->setPlaceholderType(self::PLACEHOLDER_SITELINKS);
        $feedMapping->setFeedId($sitelinksData['sitelinksFeedId']);
        $feedMapping->setAttributeFieldMappings(
            [
                $linkTextFieldMapping,
                $linkFinalUrlFieldMapping,
                $line2FieldMapping,
                $line3FieldMapping
            ]
        );

        $operation = new FeedMappingOperation();
        $operation->setOperand($feedMapping);
        $operation->setOperator(Operator::ADD);

        // Create the feed mapping operation on the server and print out some
        // information.
        $result = $feedMappingService->mutate([$operation]);
        foreach ($result->getValue() as $feedMapping) {
            printf(
                'Feed mapping with ID %d and placeholder type %d was '
                . 'saved for feed with ID %d.%s',
                $feedMapping->getFeedMappingId(),
                $feedMapping->getPlaceholderType(),
                $feedMapping->getFeedId(),
                PHP_EOL
            );
        }
    }
1181336
public function setSite($siteId, $siteName, $siteDefaultLanguage, array $languages)
    {
        $this->siteId = $siteId;
        $this->session->set(
            self::KEY_SITE,
            array(
                'siteId' => $siteId,
                'name' => $siteName,
                'defaultLanguage' => $siteDefaultLanguage,
                'languages' => $languages,
            )
        );
    }
747169
public function selectSite($fieldName, $siteID = false, $includeCurrent = false, $includeAll = false)
    {
        $v = \View::getInstance();
        $v->requireAsset('selectize');
        $currentSelected = $siteID !== 'current' ? 'selected' : '';
        $allSelected = $siteID === 'all' ? 'selected' : '';
        $current = t('Current Site');
        $all  = t('All Sites');
        $defaults = t('Default');
        $specific = t('Sites');

        $sites = '';
        foreach(\Core::make('site')->getList() as $site) {
            $sp = new \Permissions($site);
            if ($sp->canViewSiteInSelector()) {
                $sites .= '<option ' . ($site->getSiteID() == $siteID ? 'selected' : '') . ' value="' . $site->getSiteID() . '">' . $site->getSiteName() . '</option>';
            }
        }

        $currentLine = '';
        $allLine = '';
        if ($includeCurrent) {
            $currentLine = "<option value=\"current\" {$currentSelected}>{$current}</option>";
        }
        if ($includeAll) {
            $allLine = "<option value=\"all\" {$allSelected}>{$all}</option>";
        }

        if (!$includeAll && !$includeCurrent) {
            $html = <<<EOL
        <select name="siteID" data-select="search-sites">
            {$sites}
        </select>
EOL;

        } else {

        $html = <<<EOL
        <select name="siteID" data-select="search-sites">
            <optgroup label="{$defaults}">
            {$currentLine}
            {$allLine}
            </optgroup>
            <optgroup label="{$specific}">
                {$sites}
            </optgroup>
        </select>
EOL;

        }

        $html .= <<<EOL
        <script type="text/javascript">$(function() { $('select[data-select=search-sites]').selectize(); });</script>
EOL;

        return $html;
    }
243186
func newSite(cfg deps.DepsCfg) (*Site, error) {
	c := newPageCollections()

	if cfg.Language == nil {
		cfg.Language = langs.NewDefaultLanguage(cfg.Cfg)
	}

	disabledKinds := make(map[string]bool)
	for _, disabled := range cast.ToStringSlice(cfg.Language.Get("disableKinds")) {
		disabledKinds[disabled] = true
	}

	var (
		mediaTypesConfig    []map[string]interface{}
		outputFormatsConfig []map[string]interface{}

		siteOutputFormatsConfig output.Formats
		siteMediaTypesConfig    media.Types
		err                     error
	)

	// Add language last, if set, so it gets precedence.
	for _, cfg := range []config.Provider{cfg.Cfg, cfg.Language} {
		if cfg.IsSet("mediaTypes") {
			mediaTypesConfig = append(mediaTypesConfig, cfg.GetStringMap("mediaTypes"))
		}
		if cfg.IsSet("outputFormats") {
			outputFormatsConfig = append(outputFormatsConfig, cfg.GetStringMap("outputFormats"))
		}
	}

	siteMediaTypesConfig, err = media.DecodeTypes(mediaTypesConfig...)
	if err != nil {
		return nil, err
	}

	siteOutputFormatsConfig, err = output.DecodeFormats(siteMediaTypesConfig, outputFormatsConfig...)
	if err != nil {
		return nil, err
	}

	outputFormats, err := createSiteOutputFormats(siteOutputFormatsConfig, cfg.Language)
	if err != nil {
		return nil, err
	}

	taxonomies := cfg.Language.GetStringMapString("taxonomies")

	var relatedContentConfig related.Config

	if cfg.Language.IsSet("related") {
		relatedContentConfig, err = related.DecodeConfig(cfg.Language.Get("related"))
		if err != nil {
			return nil, err
		}
	} else {
		relatedContentConfig = related.DefaultConfig
		if _, found := taxonomies["tag"]; found {
			relatedContentConfig.Add(related.IndexConfig{Name: "tags", Weight: 80})
		}
	}

	titleFunc := helpers.GetTitleFunc(cfg.Language.GetString("titleCaseStyle"))

	frontMatterHandler, err := pagemeta.NewFrontmatterHandler(cfg.Logger, cfg.Cfg)
	if err != nil {
		return nil, err
	}

	siteConfig := siteConfigHolder{
		sitemap:          config.DecodeSitemap(config.Sitemap{Priority: -1, Filename: "sitemap.xml"}, cfg.Language.GetStringMap("sitemap")),
		taxonomiesConfig: taxonomies,
		timeout:          time.Duration(cfg.Language.GetInt("timeout")) * time.Millisecond,
		hasCJKLanguage:   cfg.Language.GetBool("hasCJKLanguage"),
		enableEmoji:      cfg.Language.Cfg.GetBool("enableEmoji"),
	}

	s := &Site{
		PageCollections:        c,
		layoutHandler:          output.NewLayoutHandler(),
		language:               cfg.Language,
		disabledKinds:          disabledKinds,
		titleFunc:              titleFunc,
		relatedDocsHandler:     page.NewRelatedDocsHandler(relatedContentConfig),
		outputFormats:          outputFormats,
		rc:                     &siteRenderingContext{output.HTMLFormat},
		outputFormatsConfig:    siteOutputFormatsConfig,
		mediaTypesConfig:       siteMediaTypesConfig,
		frontmatterHandler:     frontMatterHandler,
		buildStats:             &buildStats{},
		enableInlineShortcodes: cfg.Language.GetBool("enableInlineShortcodes"),
		siteCfg:                siteConfig,
	}

	s.prepareInits()

	return s, nil

}
1348944
public function onSitePreCreate(SiteEvent $event)
    {
        $site = $event->getSite();

        if (!empty($site->group_id)) {
            return; // Someone took care of this for us
        }

        $site->group_id = $this->findMostRelevantGroupId();
    }
984809
public function createSite($serverId, array $data, $wait = true)
    {
        $site = $this->post("servers/$serverId/sites", $data)['site'];

        if ($wait) {
            return $this->retry($this->getTimeout(), function () use ($serverId, $site) {
                $site = $this->site($serverId, $site['id']);

                return $site->status == 'installed' ? $site : null;
            });
        }

        return new Site($site + ['server_id' => $serverId], $this);
    }
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;
    }
1331631
protected function prepareSiteData(
        array $siteData,
        string $createdByUserId,
        string $createdReason
    ) {
        $language = $this->buildLanguage($siteData);
        if (!empty($language)) {
            $siteData['language'] = $language;
        }

        $country = $this->buildCountry($siteData);
        if (!empty($country)) {
            $siteData['country'] = $country;
        }

        $domain = $this->buildDomain(
            $siteData,
            $createdByUserId,
            $createdReason
        );
        if (!empty($domain)) {
            $siteData['domain'] = $domain;
        }

        return $siteData;
    }
921128
protected function runSitesYmlProcess()
    {
        $sitesConf = $this->bbapp->getConfig()->getSitesConfig();

        if ($this->siteDomain === null) {
            throw new \InvalidArgumentException('This site domain is not valid (empty value)');
        }

        if (is_array($sitesConf) && array_key_exists($this->siteLabel, $sitesConf)) {
            throw new \InvalidArgumentException('This label `'.$this->siteLabel.'` already present in sites.yml');
        }

        $newSite = [
            \BackBee\Utils\StringUtils::urlize($this->siteLabel) => [
                'label'  => $this->siteLabel,
                'domain' => $this->siteDomain,
            ],
        ];

        $newSitesConf = (is_array($sitesConf)) ? array_merge($sitesConf, $newSite) : $newSite;
        file_put_contents(
                $this->bbapp->getBaseDir().DIRECTORY_SEPARATOR.'repository/Config/sites.yml',
                Yaml::dump($newSitesConf)
        );

        return $this;
    }
1023548
protected function getDefaultSitePageSettings(UserInterface $createdByUser)
    {
        $myConfig = $this->getDefaultSiteSettings();

        $pagesData = $myConfig['pages'];

        // Set the author for each
        foreach ($pagesData as $key => $pageData) {
            $pagesData[$key]['createdByUserId'] = $createdByUser->getId();
            $pagesData[$key]['createdReason'] = 'Default page creation in ' . get_class($this);
            $pagesData[$key]['author'] = $createdByUser->getName();
        }

        return $pagesData;
    }
325931
public function newInstance(
        string $createdByUserId,
        string $createdReason = Tracking::UNKNOWN_REASON
    ) {
        /** @var PluginWrapper $new */
        $new = parent::newInstance(
            $createdByUserId,
            $createdReason
        );

        // if no id, then it has not been save and can be returned
        if (empty($new->pluginWrapperId)) {
            return $new;
        }

        $new->pluginWrapperId = null;

        // @deprecated <deprecated-site-wide-plugin>
        //if (!$new->instance->isSiteWide()) {
            $pluginInstance = $new->instance->newInstance(
                $createdByUserId,
                $createdReason
            );
            $new->instance = $pluginInstance;
        //}

        return $new;
    }
1062799
public function getSiteById($idSite, $env, $includeSite404Table = false)
	{
        // Retrieve cache version if front mode to avoid multiple calls
	    $cacheKey = get_class($this) . '_getSiteById_' . $idSite . '_' . $env . '_' . $includeSite404Table;
        $cacheConfig = 'engine_page_services';
        $melisEngineCacheSystem = $this->getServiceLocator()->get('MelisEngineCacheSystem');
        $results = $melisEngineCacheSystem->getCacheByKey($cacheKey, $cacheConfig);
        if (!empty($results)) return $results;
	    
		$select = $this->tableGateway->getSql()->select();
		
		$select->columns(array('*'));
	
		$siteDomainjoin = new Expression('melis_cms_site_domain.sdom_site_id = melis_cms_site.site_id AND sdom_env =\''.$env.'\'');
		
		if($includeSite404Table) {
		    
		    $site404join = new Expression('melis_cms_site_domain.sdom_site_id = melis_cms_site.site_id');
		    
		    $select->join('melis_cms_site_domain', $siteDomainjoin, array('*'), $select::JOIN_LEFT)
		           ->join('melis_cms_site_404', $site404join, array('*'), $select::JOIN_LEFT);
		}
		else {
		    $select->join('melis_cms_site_domain', $siteDomainjoin, array('*'), $select::JOIN_LEFT);
		}
		
		$select->where('site_id ='.$idSite);
	
		$resultSet = $this->tableGateway->selectWith($select);

		$melisEngineCacheSystem->setCacheByKey($cacheKey, $cacheConfig, $resultSet);
		
		return $resultSet;
	}
825120
public function createDomain(
        $domainName,
        string $createdByUserId,
        string $createdReason = Tracking::UNKNOWN_REASON,
        $primaryDomain = null,
        $doFlush = false
    ) {
        if (empty($domainName)) {
            throw new DomainNotFoundException('Domain name is required.');
        }

        // Check if exists first
        if ($this->domainExists($domainName)) {
            throw new DuplicateDomainException(
                'Duplicate domains may not be created.'
            );
        }

        $domain = new \Rcm\Entity\Domain(
            $createdByUserId,
            $createdReason
        );
        $domain->setDomainName($domainName);

        if ($primaryDomain instanceof \Rcm\Entity\Domain) {
            $domain->setPrimary($primaryDomain);
        }

        $this->getEntityManager()->persist($domain);

        if ($doFlush) {
            $this->getEntityManager()->flush($domain);
        }

        return $domain;
    }
161659
public static function instance($siteId, $name, array $posts)
    {
        $site = new self();

        $site->siteId = $siteId;
        $site->name   = $name;
        $site->posts  = $posts;

        return $site;
    }