xref: /dokuwiki/inc/ErrorHandler.php (revision dbe0790d4cb5bac92c977818735d040e84836756)
1<?php
2
3namespace dokuwiki;
4
5use dokuwiki\Exception\FatalException;
6
7/**
8 * Manage the global handling of errors and exceptions
9 *
10 * Developer may use this to log and display exceptions themselves
11 */
12class ErrorHandler
13{
14
15    /**
16     * Register the default error handling
17     */
18    public static function register()
19    {
20        set_error_handler([ErrorHandler::class, 'errorConverter']);
21        if (!defined('DOKU_UNITTEST')) {
22            set_exception_handler([ErrorHandler::class, 'fatalException']);
23            register_shutdown_function([ErrorHandler::class, 'fatalShutdown']);
24        }
25    }
26
27    /**
28     * Default Exception handler to show a nice user message before dieing
29     *
30     * The exception is logged to the error log
31     *
32     * @param \Throwable $e
33     */
34    public static function fatalException($e)
35    {
36        $plugin = self::guessPlugin($e);
37        $title = hsc(get_class($e) . ': ' . $e->getMessage());
38        $msg = 'An unforeseen error has occured. This is most likely a bug somewhere.';
39        if ($plugin) $msg .= ' It might be a problem in the ' . $plugin . ' plugin.';
40        $logged = self::logException($e)
41            ? 'More info has been written to the DokuWiki _error.log'
42            : $e->getFile() . ':' . $e->getLine();
43
44        echo <<<EOT
45<!DOCTYPE html>
46<html>
47<head><title>$title</title></head>
48<body style="font-family: Arial, sans-serif">
49    <div style="width:60%; margin: auto; background-color: #fcc;
50                border: 1px solid #faa; padding: 0.5em 1em;">
51        <h1 style="font-size: 120%">$title</h1>
52        <p>$msg</p>
53        <p>$logged</p>
54    </div>
55</body>
56</html>
57EOT;
58    }
59
60    /**
61     * Convenience method to display an error message for the given Exception
62     *
63     * @param \Throwable $e
64     * @param string $intro
65     */
66    public static function showExceptionMsg($e, $intro = 'Error!')
67    {
68        $msg = hsc($intro) . '<br />' . hsc(get_class($e) . ': ' . $e->getMessage());
69        if (self::logException($e)) $msg .= '<br />More info is available in the _error.log';
70        msg($msg, -1);
71    }
72
73    /**
74     * Default error handler to convert old school warnings, notices, etc to exceptions
75     *
76     * You should not need to call this directly!
77     *
78     * @param int $errno
79     * @param string $errstr
80     * @param string $errfile
81     * @param int $errline
82     * @return bool
83     * @throws \ErrorException
84     */
85    public static function errorConverter($errno, $errstr, $errfile, $errline)
86    {
87
88        if (!(error_reporting() & $errno)) {
89            // This error code is not included in error_reporting, so let it fall
90            // through to the standard PHP error handler
91            return false;
92        }
93
94        throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
95    }
96
97    /**
98     * Last resort to handle fatal errors that still can't be caught
99     */
100    public static function fatalShutdown()
101    {
102        $error = error_get_last();
103        // Check if it's a core/fatal error, otherwise it's a normal shutdown
104        if (
105            $error !== null &&
106            in_array(
107                $error['type'],
108                [
109                    E_ERROR,
110                    E_CORE_ERROR,
111                    E_COMPILE_ERROR,
112                ]
113            )
114        ) {
115            self::fatalException(
116                new FatalException($error['message'], 0, $error['type'], $error['file'], $error['line'])
117            );
118        }
119    }
120
121    /**
122     * Log the given exception to the error log
123     *
124     * @param \Throwable $e
125     * @return bool false if the logging failed
126     */
127    public static function logException($e)
128    {
129        global $conf;
130
131        $log = join("\t", [
132                gmdate('c'),
133                get_class($e),
134                $e->getFile() . '(' . $e->getLine() . ')',
135                $e->getMessage(),
136            ]) . "\n";
137        $log .= $e->getTraceAsString() . "\n";
138        return io_saveFile($conf['cachedir'] . '/_error.log', $log, true);
139    }
140
141    /**
142     * Checks the the stacktrace for plugin files
143     *
144     * @param \Throwable $e
145     * @return false|string
146     */
147    protected static function guessPlugin($e)
148    {
149        if (preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $e->getFile()), $match)) {
150            return $match[1];
151        }
152
153        foreach ($e->getTrace() as $line) {
154            if (
155                isset($line['class']) &&
156                preg_match('/\w+?_plugin_(\w+)/', $line['class'], $match)
157            ) {
158                return $match[1];
159            }
160
161            if (
162                isset($line['file']) &&
163                preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $line['file']), $match)
164            ) {
165                return $match[1];
166            }
167        }
168
169        return false;
170    }
171}
172