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        return Logger::getInstance()->log(
104            get_class($e) . ': ' . $e->getMessage(),
105            $e->getTraceAsString(),
106            $e->getFile(),
107            $e->getLine()
108        );
109    }
110
111    /**
112     * Checks the the stacktrace for plugin files
113     *
114     * @param \Throwable $e
115     * @return false|string
116     */
117    protected static function guessPlugin($e)
118    {
119        if (preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $e->getFile()), $match)) {
120            return $match[1];
121        }
122
123        foreach ($e->getTrace() as $line) {
124            if (
125                isset($line['class']) &&
126                preg_match('/\w+?_plugin_(\w+)/', $line['class'], $match)
127            ) {
128                return $match[1];
129            }
130
131            if (
132                isset($line['file']) &&
133                preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $line['file']), $match)
134            ) {
135                return $match[1];
136            }
137        }
138
139        return false;
140    }
141}
142