[BUGFIX] Check if a valid logger is available in error handlers
[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 if ($this->logger) {
133 $this->logger->log(LogLevel::NOTICE - $severity, $message);
134 }
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 $errorLevels[$errorLevel],
159 $flashMessageSeverity
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 }