Total Complexity | 43 |
Total Lines | 384 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like WorkspacePreview often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use WorkspacePreview, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
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); |
||
|
|||
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 |
||
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) |
||
429 | } |
||
430 | |||
431 | protected function getTypoScriptFrontendController(): ?TypoScriptFrontendController |
||
432 | { |
||
434 | } |
||
435 | } |
||
436 |