Passed
Push — master ( 428a99...6f7ef8 )
by
unknown
19:55
created

getTypoScriptFrontendController()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
 * It is free software; you can redistribute it and/or modify it under
9
 * the terms of the GNU General Public License, either version 2
10
 * of the License, or any later version.
11
 *
12
 * For the full copyright and license information, please read the
13
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
 * The TYPO3 project - inspiring people to share!
16
 */
17
18
namespace TYPO3\CMS\Workspaces\Middleware;
19
20
use Psr\Http\Message\ResponseInterface;
21
use Psr\Http\Message\ServerRequestInterface;
22
use Psr\Http\Message\UriInterface;
23
use Psr\Http\Server\MiddlewareInterface;
24
use Psr\Http\Server\RequestHandlerInterface;
25
use Symfony\Component\HttpFoundation\Cookie;
26
use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
27
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
28
use TYPO3\CMS\Core\Context\Context;
29
use TYPO3\CMS\Core\Context\UserAspect;
30
use TYPO3\CMS\Core\Context\WorkspaceAspect;
31
use TYPO3\CMS\Core\Database\ConnectionPool;
32
use TYPO3\CMS\Core\Http\CookieHeaderTrait;
33
use TYPO3\CMS\Core\Http\HtmlResponse;
34
use TYPO3\CMS\Core\Http\NormalizedParams;
35
use TYPO3\CMS\Core\Http\Stream;
36
use TYPO3\CMS\Core\Localization\LanguageService;
37
use TYPO3\CMS\Core\Routing\RouteResultInterface;
38
use TYPO3\CMS\Core\Utility\GeneralUtility;
39
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
40
use TYPO3\CMS\Workspaces\Authentication\PreviewUserAuthentication;
41
42
/**
43
 * Middleware to
44
 * - evaluate ADMCMD_prev as GET parameter or from a cookie
45
 * - initializes the PreviewUser as $GLOBALS['BE_USER']
46
 * - renders a message about a possible workspace previewing currently
47
 *
48
 * @internal
49
 */
50
class WorkspacePreview implements MiddlewareInterface
51
{
52
    use CookieHeaderTrait;
53
54
    /**
55
     * The GET parameter to be used (also the cookie name)
56
     *
57
     * @var string
58
     */
59
    protected $previewKey = 'ADMCMD_prev';
60
61
    /**
62
     * Initializes a possible preview user (by checking for GET/cookie of name "ADMCMD_prev")
63
     *
64
     * The GET parameter "ADMCMD_prev=LIVE" can be used to preview a live workspace from the backend even if the
65
     * backend user is in a different workspace.
66
     *
67
     * Additionally, if a workspace is previewed, an additional message text is shown.
68
     *
69
     * @param ServerRequestInterface $request
70
     * @param RequestHandlerInterface $handler
71
     * @return ResponseInterface
72
     * @throws \Exception
73
     */
74
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
75
    {
76
        $addInformationAboutDisabledCache = false;
77
        $keyword = $this->getPreviewInputCode($request);
78
        $setCookieOnCurrentRequest = false;
79
        /** @var NormalizedParams $normalizedParams */
80
        $normalizedParams = $request->getAttribute('normalizedParams');
81
        $context = GeneralUtility::makeInstance(Context::class);
82
83
        // First, if a Log out is happening, a custom HTML output page is shown and the request exits with removing
84
        // the cookie for the backend preview.
85
        if ($keyword === 'LOGOUT') {
86
            // "log out", and unset the cookie
87
            $message = $this->getLogoutTemplateMessage($request->getUri());
88
            $response = new HtmlResponse($message);
89
            return $this->addCookie('', $normalizedParams, $response);
90
        }
91
92
        // If the keyword is ignore, then the preview is not managed as "Preview User" but handled
93
        // via the regular backend user or even no user if the GET parameter ADMCMD_noBeUser is set
94
        if (!empty($keyword) && $keyword !== 'IGNORE' && $keyword !== 'LIVE') {
95
            $routeResult = $request->getAttribute('routing', null);
96
            // A keyword was found in a query parameter or in a cookie
97
            // If the keyword is valid, activate a BE User and override any existing BE Users
98
            // (in case workspace ID was given and a corresponding site to be used was found)
99
            $previewWorkspaceId = (int)$this->getWorkspaceIdFromRequest($request, $keyword);
100
            if ($previewWorkspaceId > 0 && $routeResult instanceof RouteResultInterface) {
101
                $previewUser = $this->initializePreviewUser($previewWorkspaceId);
102
                if ($previewUser instanceof PreviewUserAuthentication) {
103
                    $GLOBALS['BE_USER'] = $previewUser;
104
                    // Register the preview user as aspect
105
                    $this->setBackendUserAspect($context, $previewUser);
106
                    // If the GET parameter is set, and we have a valid Preview User, the cookie needs to be
107
                    // set and the GET parameter should be removed.
108
                    $setCookieOnCurrentRequest = $request->getQueryParams()[$this->previewKey] ?? false;
109
                }
110
            }
111
        }
112
113
        // If keyword is set to "LIVE", then ensure that there is no workspace preview, but keep the BE User logged in.
114
        // This option is solely used to ensure that a be user can preview the live version of a page in the
115
        // workspace preview module.
116
        if ($keyword === 'LIVE' && $GLOBALS['BE_USER'] instanceof FrontendBackendUserAuthentication) {
117
            // We need to set the workspace to live here
118
            $GLOBALS['BE_USER']->setTemporaryWorkspace(0);
119
            // Register the backend user as aspect
120
            $this->setBackendUserAspect($context, $GLOBALS['BE_USER']);
121
            // Caching is disabled, because otherwise generated URLs could include the keyword parameter
122
            $request = $request->withAttribute('noCache', true);
123
            $addInformationAboutDisabledCache = true;
124
            $setCookieOnCurrentRequest = false;
125
        }
126
127
        $response = $handler->handle($request);
128
129
        $tsfe = $this->getTypoScriptFrontendController();
130
        if ($tsfe instanceof TypoScriptFrontendController && $addInformationAboutDisabledCache) {
131
            $tsfe->set_no_cache('GET Parameter ADMCMD_prev=LIVE was given', true);
132
        }
133
134
        // Add an info box to the frontend content
135
        if ($tsfe instanceof TypoScriptFrontendController && $context->getPropertyFromAspect('workspace', 'isOffline', false)) {
136
            $previewInfo = $this->renderPreviewInfo($tsfe, $request->getUri());
137
            $body = $response->getBody();
138
            $body->rewind();
139
            $content = $body->getContents();
140
            $content = str_ireplace('</body>', $previewInfo . '</body>', $content);
141
            $body = new Stream('php://temp', 'rw');
142
            $body->write($content);
0 ignored issues
show
Bug introduced by
It seems like $content can also be of type array; however, parameter $string of TYPO3\CMS\Core\Http\Stream::write() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

142
            $body->write(/** @scrutinizer ignore-type */ $content);
Loading history...
143
            $response = $response->withBody($body);
144
        }
145
146
        // If the GET parameter ADMCMD_prev is set, then a cookie is set for the next request to keep the preview user
147
        if ($setCookieOnCurrentRequest) {
148
            $response = $this->addCookie($keyword, $normalizedParams, $response);
149
        }
150
        return $response;
151
    }
152
153
    /**
154
     * Renders the logout template when the "logout" button was pressed.
155
     * Returns a string which can be put into a HttpResponse.
156
     *
157
     * @param UriInterface $currentUrl
158
     * @return string
159
     */
160
    protected function getLogoutTemplateMessage(UriInterface $currentUrl): string
161
    {
162
        $currentUrl = $this->removePreviewParameterFromUrl($currentUrl);
163
        if ($GLOBALS['TYPO3_CONF_VARS']['FE']['workspacePreviewLogoutTemplate']) {
164
            $templateFile = GeneralUtility::getFileAbsFileName($GLOBALS['TYPO3_CONF_VARS']['FE']['workspacePreviewLogoutTemplate']);
165
            if (@is_file($templateFile)) {
166
                $message = (string)file_get_contents($templateFile);
167
            } else {
168
                $message = $this->getLanguageService()->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang_mod.xlf:previewLogoutError');
169
                $message = htmlspecialchars($message);
170
                $message = sprintf($message, '<strong>', '</strong><br>', $templateFile);
171
            }
172
        } else {
173
            $message = $this->getLanguageService()->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang_mod.xlf:previewLogoutSuccess');
174
            $message = htmlspecialchars($message);
175
            $message = sprintf($message, '<a href="' . htmlspecialchars((string)$currentUrl) . '">', '</a>');
176
        }
177
        return sprintf($message, htmlspecialchars((string)$currentUrl));
178
    }
179
180
    /**
181
     * Looking for an ADMCMD_prev code, looks it up if found and returns configuration data.
182
     * Background: From the backend a request to the frontend to show a page, possibly with
183
     * workspace preview can be "recorded" and associated with a keyword.
184
     * When the frontend is requested with this keyword the associated request parameters are
185
     * restored from the database AND the backend user is loaded - only for that request.
186
     * The main point is that a special URL valid for a limited time,
187
     * eg. http://localhost/typo3site/index.php?ADMCMD_prev=035d9bf938bd23cb657735f68a8cedbf will
188
     * open up for a preview that doesn't require login. Thus it's useful for sending in an email
189
     * to someone without backend account.
190
     *
191
     * @param ServerRequestInterface $request
192
     * @param string $inputCode
193
     * @return int|null Workspace ID stored in the preview configuration array of a sys_preview record.
194
     * @throws \Exception
195
     */
196
    protected function getWorkspaceIdFromRequest(ServerRequestInterface $request, string $inputCode): ?int
197
    {
198
        $previewData = $this->getPreviewData($inputCode);
199
        if (!is_array($previewData)) {
200
            // ADMCMD command could not be executed! (No keyword configuration found)
201
            return null;
202
        }
203
        if ($request->getMethod() === 'POST') {
204
            throw new \Exception('POST requests are incompatible with keyword preview.', 1294585191);
205
        }
206
        // Validate configuration
207
        $previewConfig = json_decode($previewData['config'], true);
208
        if (!$previewConfig['fullWorkspace']) {
209
            throw new \Exception('Preview configuration did not include a workspace preview', 1294585190);
210
        }
211
        return (int)$previewConfig['fullWorkspace'];
212
    }
213
214
    /**
215
     * Creates a preview user and sets the workspace ID
216
     *
217
     * @param int $workspaceUid the workspace ID to set
218
     * @return PreviewUserAuthentication|null if the set up of the workspace was successful, the user is returned.
219
     */
220
    protected function initializePreviewUser(int $workspaceUid): ?PreviewUserAuthentication
221
    {
222
        $previewUser = GeneralUtility::makeInstance(PreviewUserAuthentication::class);
223
        if ($previewUser->setTemporaryWorkspace($workspaceUid)) {
224
            return $previewUser;
225
        }
226
        return null;
227
    }
228
229
    /**
230
     * Adds a cookie for logging in a preview user into the HTTP response
231
     *
232
     * @param string $keyword
233
     * @param NormalizedParams $normalizedParams
234
     * @param ResponseInterface $response
235
     * @return ResponseInterface
236
     */
237
    protected function addCookie(string $keyword, NormalizedParams $normalizedParams, ResponseInterface $response): ResponseInterface
238
    {
239
        $cookieSameSite = $this->sanitizeSameSiteCookieValue(
240
            strtolower($GLOBALS['TYPO3_CONF_VARS']['BE']['cookieSameSite'] ?? Cookie::SAMESITE_STRICT)
241
        );
242
        // SameSite Cookie = None needs the secure option (only allowed on HTTPS)
243
        $isSecure = $cookieSameSite === Cookie::SAMESITE_NONE || $normalizedParams->isHttps();
244
245
        $cookie = new Cookie(
246
            $this->previewKey,
247
            $keyword,
248
            0,
249
            $normalizedParams->getSitePath(),
250
            null,
251
            $isSecure,
252
            true,
253
            false,
254
            $cookieSameSite
255
        );
256
        return $response->withAddedHeader('Set-Cookie', $cookie->__toString());
257
    }
258
259
    /**
260
     * Returns the input code value from the admin command variable
261
     * If no inputcode and a cookie is set, load input code from cookie
262
     *
263
     * @param ServerRequestInterface $request
264
     * @return string keyword
265
     */
266
    protected function getPreviewInputCode(ServerRequestInterface $request): string
267
    {
268
        return $request->getQueryParams()[$this->previewKey] ?? $request->getCookieParams()[$this->previewKey] ?? '';
269
    }
270
271
    /**
272
     * Look for keyword configuration record in the database, but check if the keyword has expired already
273
     *
274
     * @param string $keyword
275
     * @return mixed array of the result set or null
276
     */
277
    protected function getPreviewData(string $keyword)
278
    {
279
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
280
            ->getQueryBuilderForTable('sys_preview');
281
        return $queryBuilder
282
            ->select('*')
283
            ->from('sys_preview')
284
            ->where(
285
                $queryBuilder->expr()->eq(
286
                    'keyword',
287
                    $queryBuilder->createNamedParameter($keyword)
288
                ),
289
                $queryBuilder->expr()->gt(
290
                    'endtime',
291
                    $queryBuilder->createNamedParameter($GLOBALS['EXEC_TIME'], \PDO::PARAM_INT)
292
                )
293
            )
294
            ->setMaxResults(1)
295
            ->execute()
296
            ->fetch();
297
    }
298
299
    /**
300
     * Code regarding adding a custom preview message, when previewing a workspace
301
     */
302
303
    /**
304
     * Renders a message at the bottom of the HTML page, can be modified via
305
     *
306
     *   config.disablePreviewNotification = 1 (to disable the additional info text)
307
     *
308
     * and
309
     *
310
     *   config.message_preview_workspace = This is not the online version but the version of "%s" workspace (ID: %s).
311
     *
312
     * via TypoScript.
313
     *
314
     * @param TypoScriptFrontendController $tsfe
315
     * @param UriInterface $currentUrl
316
     * @return string
317
     */
318
    protected function renderPreviewInfo(TypoScriptFrontendController $tsfe, UriInterface $currentUrl): string
319
    {
320
        $content = '';
321
        if (!isset($tsfe->config['config']['disablePreviewNotification']) || (int)$tsfe->config['config']['disablePreviewNotification'] !== 1) {
322
            // get the title of the current workspace
323
            $currentWorkspaceId = $tsfe->whichWorkspace();
324
            $currentWorkspaceTitle = $this->getWorkspaceTitle($currentWorkspaceId);
325
            $currentWorkspaceTitle = htmlspecialchars($currentWorkspaceTitle);
326
            if ($tsfe->config['config']['message_preview_workspace'] ?? false) {
327
                $content = sprintf(
328
                    $tsfe->config['config']['message_preview_workspace'],
329
                    $currentWorkspaceTitle,
330
                    $currentWorkspaceId ?? -99
331
                );
332
            } else {
333
                $text = $this->getLanguageService()->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang_mod.xlf:previewText');
334
                $text = htmlspecialchars($text);
335
                $text = sprintf($text, $currentWorkspaceTitle, $currentWorkspaceId ?? -99);
336
                $stopPreviewText = $this->getLanguageService()->sL('LLL:EXT:workspaces/Resources/Private/Language/locallang_mod.xlf:stopPreview');
337
                $stopPreviewText = htmlspecialchars($stopPreviewText);
338
                if ($GLOBALS['BE_USER'] instanceof PreviewUserAuthentication) {
339
                    $urlForStoppingPreview = (string)$this->removePreviewParameterFromUrl($currentUrl, 'LOGOUT');
340
                    $text .= '<br><a style="color: #000; pointer-events: visible;" href="' . htmlspecialchars($urlForStoppingPreview) . '">' . $stopPreviewText . '</a>';
341
                }
342
                $styles = [];
343
                $styles[] = 'position: fixed';
344
                $styles[] = 'top: 15px';
345
                $styles[] = 'right: 15px';
346
                $styles[] = 'padding: 8px 18px';
347
                $styles[] = 'background: #fff3cd';
348
                $styles[] = 'border: 1px solid #ffeeba';
349
                $styles[] = 'font-family: sans-serif';
350
                $styles[] = 'font-size: 14px';
351
                $styles[] = 'font-weight: bold';
352
                $styles[] = 'color: #856404';
353
                $styles[] = 'z-index: 20000';
354
                $styles[] = 'user-select: none';
355
                $styles[] = 'pointer-events: none';
356
                $styles[] = 'text-align: center';
357
                $styles[] = 'border-radius: 2px';
358
                $content = '<div id="typo3-preview-info" style="' . implode(';', $styles) . '">' . $text . '</div>';
359
            }
360
        }
361
        return $content;
362
    }
363
364
    /**
365
     * Fetches the title of the workspace
366
     *
367
     * @param int $workspaceId
368
     * @return string the title of the workspace
369
     */
370
    protected function getWorkspaceTitle(int $workspaceId): string
371
    {
372
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
373
            ->getQueryBuilderForTable('sys_workspace');
374
        $title = $queryBuilder
375
            ->select('title')
376
            ->from('sys_workspace')
377
            ->where(
378
                $queryBuilder->expr()->eq(
379
                    'uid',
380
                    $queryBuilder->createNamedParameter($workspaceId, \PDO::PARAM_INT)
381
                )
382
            )
383
            ->execute()
384
            ->fetchColumn();
385
        return (string)($title !== false ? $title : '');
386
    }
387
388
    /**
389
     * Used for generating URLs (e.g. in logout page) without the existing ADMCMD_prev keyword as GET variable
390
     *
391
     * @param UriInterface $url
392
     * @param string $newAdminCommand
393
     * @return UriInterface
394
     */
395
    protected function removePreviewParameterFromUrl(UriInterface $url, string $newAdminCommand = ''): UriInterface
396
    {
397
        $queryString = $url->getQuery();
398
        if (!empty($queryString)) {
399
            $queryStringParts = GeneralUtility::explodeUrl2Array($queryString);
400
            unset($queryStringParts[$this->previewKey]);
401
        } else {
402
            $queryStringParts = [];
403
        }
404
        if ($newAdminCommand !== '') {
405
            $queryStringParts[$this->previewKey] = $newAdminCommand;
406
        }
407
        $queryString = http_build_query($queryStringParts, '', '&', PHP_QUERY_RFC3986);
408
        return $url->withQuery($queryString);
409
    }
410
411
    /**
412
     * @return LanguageService
413
     */
414
    protected function getLanguageService(): LanguageService
415
    {
416
        return $GLOBALS['LANG'] ?: LanguageService::create('default');
417
    }
418
419
    /**
420
     * Register or override the backend user as aspect, as well as the workspace information the user object is holding
421
     *
422
     * @param Context $context
423
     * @param BackendUserAuthentication $user
424
     */
425
    protected function setBackendUserAspect(Context $context, BackendUserAuthentication $user = null)
426
    {
427
        $context->setAspect('backend.user', GeneralUtility::makeInstance(UserAspect::class, $user));
428
        $context->setAspect('workspace', GeneralUtility::makeInstance(WorkspaceAspect::class, $user ? $user->workspace : 0));
429
    }
430
431
    protected function getTypoScriptFrontendController(): ?TypoScriptFrontendController
432
    {
433
        return $GLOBALS['TSFE'] ?? null;
434
    }
435
}
436