ErrorController.php 13.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
declare(strict_types = 1);
namespace TYPO3\CMS\Frontend\Controller;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

use Psr\Http\Message\ResponseInterface;
19
use Psr\Http\Message\ServerRequestInterface;
20
21
22
use TYPO3\CMS\Core\Controller\ErrorPageController;
use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
23
use TYPO3\CMS\Core\Error\PageErrorHandler\PageErrorHandlerInterface;
24
25
use TYPO3\CMS\Core\Http\HtmlResponse;
use TYPO3\CMS\Core\Http\RedirectResponse;
26
use TYPO3\CMS\Core\Site\Entity\Site;
27
28
29
30
31
32
33
34
35
36
37
38
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Handles "Page Not Found" or "Page Unavailable" requests,
 * returns a response object.
 */
class ErrorController
{
    /**
     * Used for creating a 500 response ("Page unavailable"), usually due some misconfiguration
     * but if configured, a RedirectResponse could be returned as well.
     *
39
     * @param ServerRequestInterface $request
40
41
42
43
44
     * @param string $message
     * @param array $reasons
     * @return ResponseInterface
     * @throws ServiceUnavailableException
     */
45
    public function unavailableAction(ServerRequestInterface $request, string $message, array $reasons = []): ResponseInterface
46
47
48
49
    {
        if (!$this->isPageUnavailableHandlerConfigured()) {
            throw new ServiceUnavailableException($message, 1518472181);
        }
50
51
52
53
54
        $errorHandler = $this->getErrorHandlerFromSite($request, 500);
        if ($errorHandler instanceof PageErrorHandlerInterface) {
            $response = $errorHandler->handlePageError($request, $message, $reasons);
            return $response->withStatus(500, $message);
        }
55
56
57
58
59
60
61
62
63
64
65
66
        return $this->handlePageError(
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'],
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'],
            $message,
            $reasons
        );
    }

    /**
     * Used for creating a 404 response ("Page Not Found"),
     * but if configured, a RedirectResponse could be returned as well.
     *
67
     * @param ServerRequestInterface $request
68
69
70
71
72
     * @param string $message
     * @param array $reasons
     * @return ResponseInterface
     * @throws PageNotFoundException
     */
73
    public function pageNotFoundAction(ServerRequestInterface $request, string $message, array $reasons = []): ResponseInterface
74
    {
75
76
77
78
79
        $errorHandler = $this->getErrorHandlerFromSite($request, 404);
        if ($errorHandler instanceof PageErrorHandlerInterface) {
            $response = $errorHandler->handlePageError($request, $message, $reasons);
            return $response->withStatus(404, $message);
        }
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
        if (!$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
            throw new PageNotFoundException($message, 1518472189);
        }
        return $this->handlePageError(
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'],
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'],
            $message,
            $reasons
        );
    }

    /**
     * Used for creating a 403 response ("Access denied"),
     * but if configured, a RedirectResponse could be returned as well.
     *
95
     * @param ServerRequestInterface $request
96
97
98
99
     * @param string $message
     * @param array $reasons
     * @return ResponseInterface
     */
100
    public function accessDeniedAction(ServerRequestInterface $request, string $message, array $reasons = []): ResponseInterface
101
    {
102
103
104
105
106
        $errorHandler = $this->getErrorHandlerFromSite($request, 403);
        if ($errorHandler instanceof PageErrorHandlerInterface) {
            $response = $errorHandler->handlePageError($request, $message, $reasons);
            return $response->withStatus(403, $message);
        }
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
        return $this->handlePageError(
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'],
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_accessdeniedheader'],
            $message,
            $reasons
        );
    }

    /**
     * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
     * and devIPMask must not match the current visitor's IP address.
     *
     * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
     */
    protected function isPageUnavailableHandlerConfigured(): bool
    {
        return
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
            && !GeneralUtility::cmpIP(
                GeneralUtility::getIndpEnv('REMOTE_ADDR'),
                $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
            )
        ;
    }

    /**
     * Generic error page handler.
     *
     * @param mixed $errorHandler See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
     * @param string $header If set, this is passed directly to the PHP function, header()
     * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
     * @param array $pageAccessFailureReasons
     * @return ResponseInterface
     * @throws \RuntimeException
     */
    protected function handlePageError($errorHandler, string $header = '', string $reason = '', array $pageAccessFailureReasons = []): ResponseInterface
    {
        $response = null;
        $content = '';
        // Simply boolean; Just shows TYPO3 error page with reason:
147
        if (is_bool($errorHandler) || strtolower($errorHandler) === 'true' || (string)$errorHandler === '1') {
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
            $content = GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
                'Page Not Found',
                'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . $reason : '')
            );
        } elseif (GeneralUtility::isFirstPartOfStr($errorHandler, 'USER_FUNCTION:')) {
            $funcRef = trim(substr($errorHandler, 14));
            $params = [
                'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
                'reasonText' => $reason,
                'pageAccessFailureReasons' => $pageAccessFailureReasons
            ];
            try {
                $content = GeneralUtility::callUserFunction($funcRef, $params, $this);
            } catch (\Exception $e) {
                throw new \RuntimeException('Error: 404 page by USER_FUNCTION "' . $funcRef . '" failed.', 1518472235, $e);
            }
        } elseif (GeneralUtility::isFirstPartOfStr($errorHandler, 'READFILE:')) {
            $readFile = GeneralUtility::getFileAbsFileName(trim(substr($errorHandler, 9)));
            if (@is_file($readFile)) {
                $content = str_replace(
                    [
                        '###CURRENT_URL###',
                        '###REASON###'
                    ],
                    [
                        GeneralUtility::getIndpEnv('REQUEST_URI'),
                        htmlspecialchars($reason)
                    ],
                    file_get_contents($readFile)
                );
            } else {
                throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1518472245);
            }
        } elseif (GeneralUtility::isFirstPartOfStr($errorHandler, 'REDIRECT:')) {
            $response = new RedirectResponse(substr($errorHandler, 9));
        } elseif ($errorHandler !== '') {
            // Check if URL is relative
            $urlParts = parse_url($errorHandler);
            // parse_url could return an array without the key "host", the empty check works better than strict check
            if (empty($urlParts['host'])) {
                $urlParts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
                if ($errorHandler[0] === '/') {
                    $errorHandler = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $errorHandler;
                } else {
                    $errorHandler = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $errorHandler;
                }
                $checkBaseTag = false;
            } else {
                $checkBaseTag = true;
            }
            // Check recursion
            if ($errorHandler === GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
                $reason = $reason ?: 'Page cannot be found.';
                $reason .= LF . LF . 'Additionally, ' . $errorHandler . ' was not found while trying to retrieve the error document.';
                throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1518472252);
            }
            // Prepare headers
            $requestHeaders = [
206
207
                'User-agent' => GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
                'Referer' => GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
            ];
            $report = [];
            $res = GeneralUtility::getUrl($errorHandler, 1, $requestHeaders, $report);
            if ((int)$report['error'] !== 0 && (int)$report['error'] !== 200) {
                throw new \RuntimeException('Failed to fetch error page "' . $errorHandler . '", reason: ' . $report['message'], 1518472257);
            }
            if ($res === false) {
                // Last chance -- redirect
                $response = new RedirectResponse($errorHandler);
            } else {
                // Header and content are separated by an empty line
                list($returnedHeaders, $content) = explode(CRLF . CRLF, $res, 2);
                $content .= CRLF;
                // Forward these response headers to the client
                $forwardHeaders = [
                    'Content-Type:'
                ];
                $headerArr = preg_split('/\\r|\\n/', $returnedHeaders, -1, PREG_SPLIT_NO_EMPTY);
                foreach ($headerArr as $headerLine) {
                    foreach ($forwardHeaders as $h) {
                        if (preg_match('/^' . $h . '/', $headerLine)) {
                            $header .= CRLF . $headerLine;
                        }
                    }
                }
                // Put <base> if necessary
                if ($checkBaseTag) {
                    // If content already has <base> tag, we do not need to do anything
                    if (false === stristr($content, '<base ')) {
                        // Generate href for base tag
                        $base = $urlParts['scheme'] . '://';
                        if ($urlParts['user'] != '') {
                            $base .= $urlParts['user'];
                            if ($urlParts['pass'] != '') {
                                $base .= ':' . $urlParts['pass'];
                            }
                            $base .= '@';
                        }
                        $base .= $urlParts['host'];
                        // Add path portion skipping possible file name
                        $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $urlParts['path']);
                        // Put it into content (generate also <head> if necessary)
                        $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
                        if (stristr($content, '<head>')) {
                            $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
                        } else {
                            $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
                        }
                    }
                }
            }
        } else {
            $content = GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
                'Page Not Found',
                $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
            );
        }

        if (!$response) {
            $response = new HtmlResponse($content);
        }
        return $this->applySanitizedHeadersToResponse($response, $header);
    }

    /**
     * Headers which have been requested, will be added to the response object.
274
     * If a header is part of the HTTP Response code, the response object will be annotated as well.
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
     *
     * @param ResponseInterface $response
     * @param string $headers
     * @return ResponseInterface
     */
    protected function applySanitizedHeadersToResponse(ResponseInterface $response, string $headers): ResponseInterface
    {
        if (!empty($headers)) {
            $headerArr = preg_split('/\\r|\\n/', $headers, -1, PREG_SPLIT_NO_EMPTY);
            foreach ($headerArr as $headerLine) {
                if (strpos($headerLine, 'HTTP/') === 0 && strpos($headerLine, ':') === false) {
                    list($protocolVersion, $statusCode, $reasonPhrase) = explode(' ', $headerLine, 3);
                    list(, $protocolVersion) = explode('/', $protocolVersion, 2);
                    $response = $response
                        ->withProtocolVersion((int)$protocolVersion)
                        ->withStatus($statusCode, $reasonPhrase);
                } else {
                    list($headerName, $value) = GeneralUtility::trimExplode(':', $headerLine, 2);
                    $response = $response->withHeader($headerName, $value);
                }
            }
        }
        return $response;
    }
299
300
301
302
303
304
305
306
307
308
309
310
311

    /**
     * Checks if a site is configured, and an error handler is configured for this specific status code.
     *
     * @param ServerRequestInterface $request
     * @param int $statusCode
     * @return PageErrorHandlerInterface|null
     */
    protected function getErrorHandlerFromSite(ServerRequestInterface $request, int $statusCode): ?PageErrorHandlerInterface
    {
        $site = $request->getAttribute('site');
        return $site instanceof Site ? $site->getErrorHandler($statusCode) : $site;
    }
312
}