Passed
Pull Request — release-11.5.x (#3050)
by Mario
34:15
created

Tsfe::getAbsRefPrefixFromTSFE()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 13
ccs 7
cts 8
cp 0.875
rs 10
cc 3
nc 3
nop 1
crap 3.0175
1
<?php
2
namespace ApacheSolrForTypo3\Solr\FrontendEnvironment;
3
4
use TYPO3\CMS\Core\Context\Context;
5
use TYPO3\CMS\Core\Context\Exception\AspectNotFoundException;
6
use TYPO3\CMS\Core\Context\LanguageAspectFactory;
7
use TYPO3\CMS\Core\Context\TypoScriptAspect;
8
use TYPO3\CMS\Core\Context\VisibilityAspect;
9
use TYPO3\CMS\Core\Core\SystemEnvironmentBuilder;
10
use TYPO3\CMS\Core\Error\Http\InternalServerErrorException;
11
use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
12
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
13
use TYPO3\CMS\Core\Http\ImmediateResponseException;
14
use TYPO3\CMS\Core\Localization\Locales;
15
use TYPO3\CMS\Core\SingletonInterface;
16
use TYPO3\CMS\Core\Site\SiteFinder;
17
use TYPO3\CMS\Core\TypoScript\TemplateService;
18
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
19
use TYPO3\CMS\Backend\Utility\BackendUtility;
20
use TYPO3\CMS\Core\Utility\GeneralUtility;
21
use TYPO3\CMS\Frontend\Page\PageRepository;
22
use TYPO3\CMS\Core\Context\UserAspect;
23
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
24
use TYPO3\CMS\Core\Http\ServerRequest;
25
26
class Tsfe implements SingletonInterface
27
{
28
29
    private $tsfeCache = [];
30
31
    private $requestCache = [];
32
33
    /**
34
     * @param int $pageId
35
     * @param int $language
36
     * @throws AspectNotFoundException
37
     */
38 141
    public function changeLanguageContext(int $pageId, int $language): void
39
    {
40
        /* @var Context $context */
41 141
        $context = GeneralUtility::makeInstance(Context::class);
42 141
        if ($context->hasAspect('language')) {
43 141
            $hasRightLanguageId = $context->getPropertyFromAspect('language', 'id') === $language;
44 141
            $hasRightContentLanguageId = $context->getPropertyFromAspect('language', 'contentId')  === $language;
45 141
            if ($hasRightLanguageId && $hasRightContentLanguageId) {
46 141
                return;
47
            }
48
        }
49
50
        /* @var $siteFinder SiteFinder */
51 17
        $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
52
        try {
53 17
            $site = $siteFinder->getSiteByPageId($pageId);
54 17
            $languageAspect = LanguageAspectFactory::createFromSiteLanguage($site->getLanguageById($language));
55 17
            $context->setAspect('language', $languageAspect);
56
        } catch (SiteNotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
57
58
        }
59 17
    }
60
61
    /**
62
     * Initializes the TSFE for a given page ID and language.
63
     *
64
     * @param $pageId
65
     * @param int $language
66
     * @throws AspectNotFoundException
67
     * @throws ImmediateResponseException
68
     * @throws InternalServerErrorException
69
     * @throws ServiceUnavailableException
70
     * @throws SiteNotFoundException
71
     */
72 22
    public function initializeTsfe($pageId, $language = 0)
73
    {
74
        // resetting, a TSFE instance with data from a different page Id could be set already
75 22
        unset($GLOBALS['TSFE']);
76
77 22
        $cacheId = $pageId . '|' . $language;
78
79
        /** @var Context $context */
80 22
        $context = GeneralUtility::makeInstance(Context::class);
81 22
        $this->changeLanguageContext((int)$pageId, (int)$language);
82
83
        /* @var SiteFinder $siteFinder */
84 22
        $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
85 22
        $site = $siteFinder->getSiteByPageId($pageId);
86 22
        $siteLanguage = $site->getLanguageById($language);
87
88 22
        if (!isset($this->requestCache[$cacheId])) {
89
            /* @var ServerRequest $request */
90 22
            $request = GeneralUtility::makeInstance(ServerRequest::class);
91 22
            $this->requestCache[$cacheId] = $request
92 22
                ->withAttribute('site', $site)
93 22
                ->withAttribute('language', $siteLanguage)
94 22
                ->withAttribute('applicationType', SystemEnvironmentBuilder::REQUESTTYPE_FE)
95 22
                ->withUri($site->getBase());
96
        }
97 22
        $GLOBALS['TYPO3_REQUEST'] = $this->requestCache[$cacheId];
98
99 22
        if (!isset($this->tsfeCache[$cacheId])) {
100
            // TYPO3 by default enables a preview mode if a backend user is logged in,
101
            // the VisibilityAspect is configured to show hidden elements.
102
            // Due to this setting hidden relations/translations might be indexed
103
            // when running the Solr indexer via the TYPO3 backend.
104
            // To avoid this, the VisibilityAspect is adapted for indexing.
105 22
            $context->setAspect(
106 22
                'visibility',
107 22
                GeneralUtility::makeInstance(
108 22
                    VisibilityAspect::class,
109 22
                    false,
110 22
                    false
111
                )
112
            );
113
114 22
            $feUser = GeneralUtility::makeInstance(FrontendUserAuthentication::class);
115
116
            /* @var TypoScriptFrontendController $globalsTSFE */
117 22
            $globalsTSFE = GeneralUtility::makeInstance(TypoScriptFrontendController::class, $context, $site, $siteLanguage, null, $feUser);
118 22
            $GLOBALS['TSFE'] = $globalsTSFE;
119 22
            $GLOBALS['TSFE']->id = $pageId;
120 22
            $GLOBALS['TSFE']->type = 0;
121
122
            // for certain situations we need to trick TSFE into granting us
123
            // access to the page in any case to make getPageAndRootline() work
124
            // see http://forge.typo3.org/issues/42122
125 22
            $pageRecord = BackendUtility::getRecord('pages', $pageId, 'fe_group');
126
127 22
            $userGroups = [0, -1];
128 22
            if (!empty($pageRecord['fe_group'])) {
129
                $userGroups = array_unique(array_merge($userGroups, explode(',', $pageRecord['fe_group'])));
130
            }
131 22
            $context->setAspect('frontend.user', GeneralUtility::makeInstance(UserAspect::class, $feUser, $userGroups));
132
133
            // @extensionScannerIgnoreLine
134 22
            $GLOBALS['TSFE']->sys_page = GeneralUtility::makeInstance(PageRepository::class);
135 22
            $GLOBALS['TSFE']->getPageAndRootlineWithDomain($pageId, $GLOBALS['TYPO3_REQUEST']);
136
137 22
            $template = GeneralUtility::makeInstance(TemplateService::class, $context);
138 22
            $GLOBALS['TSFE']->tmpl = $template;
139 22
            $context->setAspect('typoscript', GeneralUtility::makeInstance(TypoScriptAspect::class, true));
140 22
            $GLOBALS['TSFE']->no_cache = true;
141 22
            $GLOBALS['TSFE']->tmpl->start($GLOBALS['TSFE']->rootLine);
142 22
            $GLOBALS['TSFE']->no_cache = false;
143 22
            $GLOBALS['TSFE']->getConfigArray();
144 22
            $GLOBALS['TSFE']->settingLanguage();
145
146 21
            $GLOBALS['TSFE']->newCObj();
147 21
            $GLOBALS['TSFE']->absRefPrefix = self::getAbsRefPrefixFromTSFE($GLOBALS['TSFE']);
0 ignored issues
show
Bug Best Practice introduced by
The method ApacheSolrForTypo3\Solr\...tAbsRefPrefixFromTSFE() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

147
            /** @scrutinizer ignore-call */ 
148
            $GLOBALS['TSFE']->absRefPrefix = self::getAbsRefPrefixFromTSFE($GLOBALS['TSFE']);
Loading history...
148 21
            $GLOBALS['TSFE']->calculateLinkVars([]);
149
150 21
            $this->tsfeCache[$cacheId] = $GLOBALS['TSFE'];
151
        }
152
153 21
        $GLOBALS['TSFE'] = $this->tsfeCache[$cacheId];
154 21
        Locales::setSystemLocaleFromSiteLanguage($siteLanguage);
155 21
        $this->changeLanguageContext((int)$pageId, (int)$language);
156 21
    }
157
158
    /**
159
     * Resolves the configured absRefPrefix to a valid value and resolved if absRefPrefix
160
     * is set to "auto".
161
     */
162 21
    private function getAbsRefPrefixFromTSFE(TypoScriptFrontendController $TSFE): string
163
    {
164 21
        $absRefPrefix = '';
165 21
        if (empty($TSFE->config['config']['absRefPrefix'])) {
166
            return $absRefPrefix;
167
        }
168
169 21
        $absRefPrefix = trim($TSFE->config['config']['absRefPrefix']);
170 21
        if ($absRefPrefix === 'auto') {
171 21
            $absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
172
        }
173
174 21
        return $absRefPrefix;
175
    }
176
}
177