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