xref: /dokuwiki/inc/ErrorHandler.php (revision 51c1fbb36b428d9d354bb1353dae7e97a1219b26)
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     * Register the default error handling
16     */
17    public static function register()
18    {
19        if (!defined('DOKU_UNITTEST')) {
20            set_exception_handler([ErrorHandler::class, 'fatalException']);
21            register_shutdown_function([ErrorHandler::class, 'fatalShutdown']);
22        }
23    }
24
25    /**
26     * Default Exception handler to show a nice user message before dieing
27     *
28     * The exception is logged to the error log
29     *
30     * @param \Throwable $e
31     */
32    public static function fatalException($e)
33    {
34        $plugin = self::guessPlugin($e);
35        $title = hsc(get_class($e) . ': ' . $e->getMessage());
36        $msg = 'An unforeseen error has occured. This is most likely a bug somewhere.';
37        if ($plugin) $msg .= ' It might be a problem in the ' . $plugin . ' plugin.';
38        $logged = self::logException($e)
39            ? 'More info has been written to the DokuWiki _error.log'
40            : $e->getFile() . ':' . $e->getLine();
41
42        echo <<<EOT
43<!DOCTYPE html>
44<html>
45<head><title>$title</title></head>
46<body style="font-family: Arial, sans-serif">
47    <div style="width:60%; margin: auto; background-color: #fcc;
48                border: 1px solid #faa; padding: 0.5em 1em;">
49        <h1 style="font-size: 120%">$title</h1>
50        <p>$msg</p>
51        <p>$logged</p>
52    </div>
53</body>
54</html>
55EOT;
56    }
57
58    /**
59     * Convenience method to display an error message for the given Exception
60     *
61     * @param \Throwable $e
62     * @param string $intro
63     */
64    public static function showExceptionMsg($e, $intro = 'Error!')
65    {
66        $msg = hsc($intro) . '<br />' . hsc(get_class($e) . ': ' . $e->getMessage());
67        if (self::logException($e)) $msg .= '<br />More info is available in the _error.log';
68        msg($msg, -1);
69    }
70
71    /**
72     * Last resort to handle fatal errors that still can't be caught
73     */
74    public static function fatalShutdown()
75    {
76        $error = error_get_last();
77        // Check if it's a core/fatal error, otherwise it's a normal shutdown
78        if (
79            $error !== null &&
80            in_array(
81                $error['type'],
82                [
83                    E_ERROR,
84                    E_CORE_ERROR,
85                    E_COMPILE_ERROR,
86                ]
87            )
88        ) {
89            self::fatalException(
90                new FatalException($error['message'], 0, $error['type'], $error['file'], $error['line'])
91            );
92        }
93    }
94
95    /**
96     * Log the given exception to the error log
97     *
98     * @param \Throwable $e
99     * @return bool false if the logging failed
100     */
101    public static function logException($e)
102    {
103        global $conf;
104
105        $log = join("\t", [
106                gmdate('c'),
107                get_class($e),
108                $e->getFile() . '(' . $e->getLine() . ')',
109                $e->getMessage(),
110            ]) . "\n";
111        $log .= $e->getTraceAsString() . "\n";
112        return io_saveFile($conf['cachedir'] . '/_error.log', $log, true);
113    }
114
115    /**
116     * Checks the the stacktrace for plugin files
117     *
118     * @param \Throwable $e
119     * @return false|string
120     */
121    protected static function guessPlugin($e)
122    {
123        if (preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $e->getFile()), $match)) {
124            return $match[1];
125        }
126
127        foreach ($e->getTrace() as $line) {
128            if (
129                isset($line['class']) &&
130                preg_match('/\w+?_plugin_(\w+)/', $line['class'], $match)
131            ) {
132                return $match[1];
133            }
134
135            if (
136                isset($line['file']) &&
137                preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $line['file']), $match)
138            ) {
139                return $match[1];
140            }
141        }
142
143        return false;
144    }
145}
146