Passed
Push — master ( 9dbdd9...d5a428 )
by Alexander
04:15
created

framework/base/ErrorHandler.php (4 issues)

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\base;
9
10
use Yii;
11
use yii\helpers\VarDumper;
12
use yii\web\HttpException;
13
14
/**
15
 * ErrorHandler handles uncaught PHP errors and exceptions.
16
 *
17
 * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
18
 * You can access that instance via `Yii::$app->errorHandler`.
19
 *
20
 * For more details and usage information on ErrorHandler, see the [guide article on handling errors](guide:runtime-handling-errors).
21
 *
22
 * @author Qiang Xue <[email protected]>
23
 * @author Alexander Makarov <[email protected]>
24
 * @author Carsten Brandt <[email protected]>
25
 * @since 2.0
26
 */
27
abstract class ErrorHandler extends Component
28
{
29
    /**
30
     * @var bool whether to discard any existing page output before error display. Defaults to true.
31
     */
32
    public $discardExistingOutput = true;
33
    /**
34
     * @var int the size of the reserved memory. A portion of memory is pre-allocated so that
35
     * when an out-of-memory issue occurs, the error handler is able to handle the error with
36
     * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
37
     * Defaults to 256KB.
38
     */
39
    public $memoryReserveSize = 262144;
40
    /**
41
     * @var \Exception|null the exception that is being handled currently.
42
     */
43
    public $exception;
44
    /**
45
     * @var bool if true - `handleException()` will finish script with `ExitCode::OK`.
46
     * false - `ExitCode::UNSPECIFIED_ERROR`.
47
     * @since 2.0.36
48
     */
49
    public $silentExitOnException;
50
51
    /**
52
     * @var string Used to reserve memory for fatal error handler.
53
     */
54
    private $_memoryReserve;
55
    /**
56
     * @var \Exception from HHVM error that stores backtrace
57
     */
58
    private $_hhvmException;
59
    /**
60
     * @var bool whether this instance has been registered using `register()`
61
     */
62
    private $_registered = false;
63
64
65 255
    public function init()
66
    {
67 255
        $this->silentExitOnException = $this->silentExitOnException !== null ? $this->silentExitOnException : YII_ENV_TEST;
68 255
        parent::init();
69 255
    }
70
71
    /**
72
     * Register this error handler.
73
     * @since 2.0.32 this will not do anything if the error handler was already registered
74
     */
75
    public function register()
76
    {
77
        if (!$this->_registered) {
78
            ini_set('display_errors', false);
79
            set_exception_handler([$this, 'handleException']);
80
            if (defined('HHVM_VERSION')) {
81
                set_error_handler([$this, 'handleHhvmError']);
82
            } else {
83
                set_error_handler([$this, 'handleError']);
84
            }
85
            if ($this->memoryReserveSize > 0) {
86
                $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
87
            }
88
            register_shutdown_function([$this, 'handleFatalError']);
89
            $this->_registered = true;
90
        }
91
    }
92
93
    /**
94
     * Unregisters this error handler by restoring the PHP error and exception handlers.
95
     * @since 2.0.32 this will not do anything if the error handler was not registered
96
     */
97
    public function unregister()
98
    {
99
        if ($this->_registered) {
100
            restore_error_handler();
101
            restore_exception_handler();
102
            $this->_registered = false;
103
        }
104
    }
105
106
    /**
107
     * Handles uncaught PHP exceptions.
108
     *
109
     * This method is implemented as a PHP exception handler.
110
     *
111
     * @param \Exception $exception the exception that is not caught
112
     */
113
    public function handleException($exception)
114
    {
115
        if ($exception instanceof ExitException) {
116
            return;
117
        }
118
119
        $this->exception = $exception;
120
121
        // disable error capturing to avoid recursive errors while handling exceptions
122
        $this->unregister();
123
124
        // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
125
        // HTTP exceptions will override this value in renderException()
126
        if (PHP_SAPI !== 'cli') {
127
            http_response_code(500);
128
        }
129
130
        try {
131
            $this->logException($exception);
132
            if ($this->discardExistingOutput) {
133
                $this->clearOutput();
134
            }
135
            $this->renderException($exception);
136
            if (!$this->silentExitOnException) {
137
                \Yii::getLogger()->flush(true);
138
                if (defined('HHVM_VERSION')) {
139
                    flush();
140
                }
141
                exit(1);
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
142
            }
143
        } catch (\Exception $e) {
144
            // an other exception could be thrown while displaying the exception
145
            $this->handleFallbackExceptionMessage($e, $exception);
146
        } catch (\Throwable $e) {
147
            // additional check for \Throwable introduced in PHP 7
148
            $this->handleFallbackExceptionMessage($e, $exception);
149
        }
150
151
        $this->exception = null;
152
    }
153
154
    /**
155
     * Handles exception thrown during exception processing in [[handleException()]].
156
     * @param \Exception|\Throwable $exception Exception that was thrown during main exception processing.
157
     * @param \Exception $previousException Main exception processed in [[handleException()]].
158
     * @since 2.0.11
159
     */
160
    protected function handleFallbackExceptionMessage($exception, $previousException)
161
    {
162
        $msg = "An Error occurred while handling another error:\n";
163
        $msg .= (string) $exception;
164
        $msg .= "\nPrevious exception:\n";
165
        $msg .= (string) $previousException;
166
        if (YII_DEBUG) {
167
            if (PHP_SAPI === 'cli') {
168
                echo $msg . "\n";
169
            } else {
170
                echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
171
            }
172
        } else {
173
            echo 'An internal server error occurred.';
174
        }
175
        $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
176
        error_log($msg);
177
        if (defined('HHVM_VERSION')) {
178
            flush();
179
        }
180
        exit(1);
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
181
    }
182
183
    /**
184
     * Handles HHVM execution errors such as warnings and notices.
185
     *
186
     * This method is used as a HHVM error handler. It will store exception that will
187
     * be used in fatal error handler
188
     *
189
     * @param int $code the level of the error raised.
190
     * @param string $message the error message.
191
     * @param string $file the filename that the error was raised in.
192
     * @param int $line the line number the error was raised at.
193
     * @param mixed $context
194
     * @param mixed $backtrace trace of error
195
     * @return bool whether the normal error handler continues.
196
     *
197
     * @throws ErrorException
198
     * @since 2.0.6
199
     */
200
    public function handleHhvmError($code, $message, $file, $line, $context, $backtrace)
201
    {
202
        if ($this->handleError($code, $message, $file, $line)) {
203
            return true;
204
        }
205
        if (E_ERROR & $code) {
206
            $exception = new ErrorException($message, $code, $code, $file, $line);
207
            $ref = new \ReflectionProperty('\Exception', 'trace');
208
            $ref->setAccessible(true);
209
            $ref->setValue($exception, $backtrace);
210
            $this->_hhvmException = $exception;
211
        }
212
213
        return false;
214
    }
215
216
    /**
217
     * Handles PHP execution errors such as warnings and notices.
218
     *
219
     * This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
220
     *
221
     * @param int $code the level of the error raised.
222
     * @param string $message the error message.
223
     * @param string $file the filename that the error was raised in.
224
     * @param int $line the line number the error was raised at.
225
     * @return bool whether the normal error handler continues.
226
     *
227
     * @throws ErrorException
228
     */
229
    public function handleError($code, $message, $file, $line)
230
    {
231
        if (error_reporting() & $code) {
232
            // load ErrorException manually here because autoloading them will not work
233
            // when error occurs while autoloading a class
234
            if (!class_exists('yii\\base\\ErrorException', false)) {
235
                require_once __DIR__ . '/ErrorException.php';
236
            }
237
            $exception = new ErrorException($message, $code, $code, $file, $line);
238
239
            if (PHP_VERSION_ID < 70400) {
240
                // prior to PHP 7.4 we can't throw exceptions inside of __toString() - it will result a fatal error
241
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
242
                array_shift($trace);
243
                foreach ($trace as $frame) {
244
                    if ($frame['function'] === '__toString') {
245
                        $this->handleException($exception);
246
                        if (defined('HHVM_VERSION')) {
247
                            flush();
248
                        }
249
                        exit(1);
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
250
                    }
251
                }
252
            }
253
254
            throw $exception;
255
        }
256
257
        return false;
258
    }
259
260
    /**
261
     * Handles fatal PHP errors.
262
     */
263
    public function handleFatalError()
264
    {
265
        unset($this->_memoryReserve);
266
267
        // load ErrorException manually here because autoloading them will not work
268
        // when error occurs while autoloading a class
269
        if (!class_exists('yii\\base\\ErrorException', false)) {
270
            require_once __DIR__ . '/ErrorException.php';
271
        }
272
273
        $error = error_get_last();
274
275
        if (ErrorException::isFatalError($error)) {
276
            if (!empty($this->_hhvmException)) {
277
                $exception = $this->_hhvmException;
278
            } else {
279
                $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
280
            }
281
            $this->exception = $exception;
282
283
            $this->logException($exception);
284
285
            if ($this->discardExistingOutput) {
286
                $this->clearOutput();
287
            }
288
            $this->renderException($exception);
289
290
            // need to explicitly flush logs because exit() next will terminate the app immediately
291
            Yii::getLogger()->flush(true);
292
            if (defined('HHVM_VERSION')) {
293
                flush();
294
            }
295
            exit(1);
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
296
        }
297
    }
298
299
    /**
300
     * Renders the exception.
301
     * @param \Exception|\Error|\Throwable $exception the exception to be rendered.
302
     */
303
    abstract protected function renderException($exception);
304
305
    /**
306
     * Logs the given exception.
307
     * @param \Exception $exception the exception to be logged
308
     * @since 2.0.3 this method is now public.
309
     */
310
    public function logException($exception)
311
    {
312
        $category = get_class($exception);
313
        if ($exception instanceof HttpException) {
314
            $category = 'yii\\web\\HttpException:' . $exception->statusCode;
315
        } elseif ($exception instanceof \ErrorException) {
316
            $category .= ':' . $exception->getSeverity();
317
        }
318
        Yii::error($exception, $category);
319
    }
320
321
    /**
322
     * Removes all output echoed before calling this method.
323
     */
324
    public function clearOutput()
325
    {
326
        // the following manual level counting is to deal with zlib.output_compression set to On
327
        for ($level = ob_get_level(); $level > 0; --$level) {
328
            if (!@ob_end_clean()) {
329
                ob_clean();
330
            }
331
        }
332
    }
333
334
    /**
335
     * Converts an exception into a PHP error.
336
     *
337
     * This method can be used to convert exceptions inside of methods like `__toString()`
338
     * to PHP errors because exceptions cannot be thrown inside of them.
339
     * @param \Exception|\Throwable $exception the exception to convert to a PHP error.
340
     */
341
    public static function convertExceptionToError($exception)
342
    {
343
        trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
344
    }
345
346
    /**
347
     * Converts an exception into a simple string.
348
     * @param \Exception|\Error|\Throwable $exception the exception being converted
349
     * @return string the string representation of the exception.
350
     */
351
    public static function convertExceptionToString($exception)
352
    {
353
        if ($exception instanceof UserException) {
354
            return "{$exception->getName()}: {$exception->getMessage()}";
355
        }
356
357
        if (YII_DEBUG) {
358
            return static::convertExceptionToVerboseString($exception);
359
        }
360
361
        return 'An internal server error occurred.';
362
    }
363
364
    /**
365
     * Converts an exception into a string that has verbose information about the exception and its trace.
366
     * @param \Exception|\Error|\Throwable $exception the exception being converted
367
     * @return string the string representation of the exception.
368
     *
369
     * @since 2.0.14
370
     */
371 1
    public static function convertExceptionToVerboseString($exception)
372
    {
373 1
        if ($exception instanceof Exception) {
374
            $message = "Exception ({$exception->getName()})";
375 1
        } elseif ($exception instanceof ErrorException) {
376
            $message = (string)$exception->getName();
377
        } else {
378 1
            $message = 'Exception';
379
        }
380 1
        $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
381 1
            . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
382 1
            . "Stack trace:\n" . $exception->getTraceAsString();
383
384 1
        return $message;
385
    }
386
}
387