2b7549a90db37957665377af1070cbd4f9028903
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Error / AbstractExceptionHandler.php
1 <?php
2 namespace TYPO3\CMS\Core\Error;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Psr\Log\LoggerAwareInterface;
18 use Psr\Log\LoggerAwareTrait;
19 use TYPO3\CMS\Core\Database\ConnectionPool;
20 use TYPO3\CMS\Core\SingletonInterface;
21 use TYPO3\CMS\Core\Utility\GeneralUtility;
22 use TYPO3\CMS\Core\Utility\HttpUtility;
23
24 /**
25 * An abstract exception handler
26 *
27 * This file is a backport from TYPO3 Flow
28 */
29 abstract class AbstractExceptionHandler implements ExceptionHandlerInterface, SingletonInterface, LoggerAwareInterface
30 {
31 use LoggerAwareTrait;
32
33 const CONTEXT_WEB = 'WEB';
34 const CONTEXT_CLI = 'CLI';
35
36 /**
37 * Displays the given exception
38 *
39 * @param \Throwable $exception The throwable object.
40 *
41 * @throws \Exception
42 */
43 public function handleException(\Throwable $exception)
44 {
45 switch (PHP_SAPI) {
46 case 'cli':
47 $this->echoExceptionCLI($exception);
48 break;
49 default:
50 $this->echoExceptionWeb($exception);
51 }
52 }
53
54 /**
55 * Writes exception to different logs
56 *
57 * @param \Throwable $exception The throwable object.
58 * @param string $context The context where the exception was thrown, WEB or CLI
59 */
60 protected function writeLogEntries(\Throwable $exception, $context)
61 {
62 // Do not write any logs for this message to avoid filling up tables or files with illegal requests
63 if ($exception->getCode() === 1396795884) {
64 return;
65 }
66 $filePathAndName = $exception->getFile();
67 $exceptionCodeNumber = $exception->getCode() > 0 ? '#' . $exception->getCode() . ': ' : '';
68 $logTitle = 'Core: Exception handler (' . $context . ')';
69 $logMessage = 'Uncaught TYPO3 Exception: ' . $exceptionCodeNumber . $exception->getMessage() . ' | '
70 . get_class($exception) . ' thrown in file ' . $filePathAndName . ' in line ' . $exception->getLine();
71 if ($context === 'WEB') {
72 $logMessage .= '. Requested URL: ' . $this->anonymizeToken(GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL'));
73 }
74 // When database credentials are wrong, the exception is probably
75 // caused by this. Therefor we cannot do any database operation,
76 // otherwise this will lead into recurring exceptions.
77 try {
78 $this->logger->critical($logTitle . ': ' . $logMessage, [
79 'TYPO3_MODE' => TYPO3_MODE,
80 'exception' => $exception
81 ]);
82 // Write error message to sys_log table
83 $this->writeLog($logTitle . ': ' . $logMessage);
84 } catch (\Exception $exception) {
85 }
86 }
87
88 /**
89 * Writes an exception in the sys_log table
90 *
91 * @param string $logMessage Default text that follows the message.
92 */
93 protected function writeLog($logMessage)
94 {
95 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
96 ->getConnectionForTable('sys_log');
97
98 if (!$connection->isConnected()) {
99 return;
100 }
101 $userId = 0;
102 $workspace = 0;
103 $data = [];
104 $backendUser = $this->getBackendUser();
105 if (is_object($backendUser)) {
106 if (isset($backendUser->user['uid'])) {
107 $userId = $backendUser->user['uid'];
108 }
109 if (isset($backendUser->workspace)) {
110 $workspace = $backendUser->workspace;
111 }
112 if (!empty($backendUser->user['ses_backuserid'])) {
113 $data['originalUser'] = $backendUser->user['ses_backuserid'];
114 }
115 }
116
117 $connection->insert(
118 'sys_log',
119 [
120 'userid' => $userId,
121 'type' => 5,
122 'action' => 0,
123 'error' => 2,
124 'details_nr' => 0,
125 'details' => str_replace('%', '%%', $logMessage),
126 'log_data' => empty($data) ? '' : serialize($data),
127 'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
128 'tstamp' => $GLOBALS['EXEC_TIME'],
129 'workspace' => $workspace
130 ]
131 );
132 }
133
134 /**
135 * Sends the HTTP Status 500 code, if $exception is *not* a
136 * TYPO3\CMS\Core\Error\Http\StatusException and headers are not sent, yet.
137 *
138 * @param \Throwable $exception The throwable object.
139 */
140 protected function sendStatusHeaders(\Throwable $exception)
141 {
142 if (method_exists($exception, 'getStatusHeaders')) {
143 $headers = $exception->getStatusHeaders();
144 } else {
145 $headers = [HttpUtility::HTTP_STATUS_500];
146 }
147 if (!headers_sent()) {
148 foreach ($headers as $header) {
149 header($header);
150 }
151 }
152 }
153
154 /**
155 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
156 */
157 protected function getBackendUser()
158 {
159 return $GLOBALS['BE_USER'];
160 }
161
162 /**
163 * Replaces the generated token with a generic equivalent
164 *
165 * @param string $requestedUrl
166 * @return string
167 */
168 protected function anonymizeToken(string $requestedUrl): string
169 {
170 $pattern = '/(?<=[tT]oken=)[0-9a-fA-F]{40}/';
171 return preg_replace($pattern, '--AnonymizedToken--', $requestedUrl);
172 }
173 }