[TASK] Update php-cs-fixer to 2.5.0
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Error / ErrorHandler.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 TYPO3\CMS\Core\Database\ConnectionPool;
18 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * Global error handler for TYPO3
23 *
24 * This file is a backport from TYPO3 Flow
25 */
26 class ErrorHandler implements ErrorHandlerInterface
27 {
28 /**
29 * Error levels which should result in an exception thrown.
30 *
31 * @var array
32 */
33 protected $exceptionalErrors = [];
34
35 /**
36 * Whether to write a flash message in case of an error
37 *
38 * @var bool
39 */
40 protected $debugMode = false;
41
42 /**
43 * Registers this class as default error handler
44 *
45 * @param int $errorHandlerErrors The integer representing the E_* error level which should be
46 */
47 public function __construct($errorHandlerErrors)
48 {
49 $excludedErrors = E_COMPILE_WARNING | E_COMPILE_ERROR | E_CORE_WARNING | E_CORE_ERROR | E_PARSE | E_ERROR;
50 // reduces error types to those a custom error handler can process
51 $errorHandlerErrors = $errorHandlerErrors & ~$excludedErrors;
52 set_error_handler([$this, 'handleError'], $errorHandlerErrors);
53 }
54
55 /**
56 * Defines which error levels should result in an exception thrown.
57 *
58 * @param int $exceptionalErrors The integer representing the E_* error level to handle as exceptions
59 */
60 public function setExceptionalErrors($exceptionalErrors)
61 {
62 $this->exceptionalErrors = (int)$exceptionalErrors;
63 }
64
65 /**
66 * @param bool $debugMode
67 */
68 public function setDebugMode($debugMode)
69 {
70 $this->debugMode = (bool)$debugMode;
71 }
72
73 /**
74 * Handles an error.
75 * If the error is registered as exceptionalError it will by converted into an exception, to be handled
76 * by the configured exceptionhandler. Additionally the error message is written to the configured logs.
77 * If TYPO3_MODE is 'BE' the error message is also added to the flashMessageQueue, in FE the error message
78 * is displayed in the admin panel (as TsLog message)
79 *
80 * @param int $errorLevel The error level - one of the E_* constants
81 * @param string $errorMessage The error message
82 * @param string $errorFile Name of the file the error occurred in
83 * @param int $errorLine Line number where the error occurred
84 * @return bool
85 * @throws Exception with the data passed to this method if the error is registered as exceptionalError
86 */
87 public function handleError($errorLevel, $errorMessage, $errorFile, $errorLine)
88 {
89 // Don't do anything if error_reporting is disabled by an @ sign
90 if (error_reporting() === 0) {
91 return true;
92 }
93 $errorLevels = [
94 E_WARNING => 'Warning',
95 E_NOTICE => 'Notice',
96 E_USER_ERROR => 'User Error',
97 E_USER_WARNING => 'User Warning',
98 E_USER_NOTICE => 'User Notice',
99 E_STRICT => 'Runtime Notice',
100 E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
101 E_DEPRECATED => 'Runtime Deprecation Notice'
102 ];
103 $message = 'PHP ' . $errorLevels[$errorLevel] . ': ' . $errorMessage . ' in ' . $errorFile . ' line ' . $errorLine;
104 if ($errorLevel & $this->exceptionalErrors) {
105 // handle error raised at early parse time
106 // autoloader not available & built-in classes not resolvable
107 if (!class_exists('stdClass', false)) {
108 $message = 'PHP ' . $errorLevels[$errorLevel] . ': ' . $errorMessage . ' in ' . basename($errorFile) .
109 'line ' . $errorLine;
110 die($message);
111 }
112 throw new Exception($message, 1476107295);
113 }
114 switch ($errorLevel) {
115 case E_USER_ERROR:
116 case E_RECOVERABLE_ERROR:
117 $severity = 2;
118 break;
119 case E_USER_WARNING:
120 case E_WARNING:
121 $severity = 1;
122 break;
123 default:
124 $severity = 0;
125 }
126 $logTitle = 'Core: Error handler (' . TYPO3_MODE . ')';
127 $message = $logTitle . ': ' . $message;
128 // Write error message to the configured syslogs,
129 // see: $TYPO3_CONF_VARS['SYS']['systemLog']
130 if ($errorLevel & $GLOBALS['TYPO3_CONF_VARS']['SYS']['syslogErrorReporting']) {
131 GeneralUtility::sysLog($message, 'core', $severity + 1);
132 }
133 // Write error message to devlog extension(s),
134 GeneralUtility::devLog($message, 'core', $severity + 1);
135
136 // Write error message to TSlog (admin panel)
137 $timeTracker = $this->getTimeTracker();
138 if (is_object($timeTracker)) {
139 $timeTracker->setTSlogMessage($message, $severity + 1);
140 }
141 // Write error message to sys_log table (ext: belog, Tools->Log)
142 if ($errorLevel & $GLOBALS['TYPO3_CONF_VARS']['SYS']['belogErrorReporting']) {
143 // Silently catch in case an error occurs before a database connection exists.
144 try {
145 $this->writeLog($message, $severity);
146 } catch (\Exception $e) {
147 }
148 }
149 if ($severity === 2) {
150 // Let the internal handler continue. This will stop the script
151 return false;
152 }
153 if ($this->debugMode) {
154 /** @var $flashMessage \TYPO3\CMS\Core\Messaging\FlashMessage */
155 $flashMessage = GeneralUtility::makeInstance(
156 \TYPO3\CMS\Core\Messaging\FlashMessage::class,
157 $message,
158 'PHP ' . $errorLevels[$errorLevel],
159 $severity
160 );
161 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
162 $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
163 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
164 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
165 $defaultFlashMessageQueue->enqueue($flashMessage);
166 }
167 // Don't execute PHP internal error handler
168 return true;
169 }
170
171 /**
172 * Writes an error in the sys_log table
173 *
174 * @param string $logMessage Default text that follows the message (in english!).
175 * @param int $severity The error level of the message (0 = OK, 1 = warning, 2 = error)
176 */
177 protected function writeLog($logMessage, $severity)
178 {
179 $connection = GeneralUtility::makeInstance(ConnectionPool::class)
180 ->getConnectionForTable('sys_log');
181 if ($connection->isConnected()) {
182 $userId = 0;
183 $workspace = 0;
184 $data = [];
185 $backendUser = $this->getBackendUser();
186 if (is_object($backendUser)) {
187 if (isset($backendUser->user['uid'])) {
188 $userId = $backendUser->user['uid'];
189 }
190 if (isset($backendUser->workspace)) {
191 $workspace = $backendUser->workspace;
192 }
193 if (!empty($backendUser->user['ses_backuserid'])) {
194 $data['originalUser'] = $backendUser->user['ses_backuserid'];
195 }
196 }
197
198 $connection->insert(
199 'sys_log',
200 [
201 'userid' => $userId,
202 'type' => 5,
203 'action' => 0,
204 'error' => $severity,
205 'details_nr' => 0,
206 'details' => str_replace('%', '%%', $logMessage),
207 'log_data' => (empty($data) ? '' : serialize($data)),
208 'IP' => (string)GeneralUtility::getIndpEnv('REMOTE_ADDR'),
209 'tstamp' => $GLOBALS['EXEC_TIME'],
210 'workspace' => $workspace
211 ]
212 );
213 }
214 }
215
216 /**
217 * @return TimeTracker
218 */
219 protected function getTimeTracker()
220 {
221 return GeneralUtility::makeInstance(TimeTracker::class);
222 }
223
224 /**
225 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
226 */
227 protected function getBackendUser()
228 {
229 return $GLOBALS['BE_USER'];
230 }
231 }