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            set_error_handler([ErrorHandler::class, 'logWarning'], E_WARNING);
23        }
24    }
25
26    /**
27     * Default Exception handler to show a nice user message before dieing
28     *
29     * The exception is logged to the error log
30     *
31     * @param \Throwable $e
32     */
33    public static function fatalException($e)
34    {
35        $plugin = self::guessPlugin($e);
36        $title = hsc(get_class($e) . ': ' . $e->getMessage());
37        $msg = 'An unforeseen error has occured. This is most likely a bug somewhere.';
38        if ($plugin) $msg .= ' It might be a problem in the ' . $plugin . ' plugin.';
39        $logged = self::logException($e)
40            ? 'More info has been written to the DokuWiki error log.'
41            : $e->getFile() . ':' . $e->getLine();
42
43        echo <<<EOT
44<!DOCTYPE html>
45<html>
46<head><title>$title</title></head>
47<body style="font-family: Arial, sans-serif">
48    <div style="width:60%; margin: auto; background-color: #fcc;
49                border: 1px solid #faa; padding: 0.5em 1em;">
50        <h1 style="font-size: 120%">$title</h1>
51        <p>$msg</p>
52        <p>$logged</p>
53    </div>
54</body>
55</html>
56EOT;
57    }
58
59    /**
60     * Convenience method to display an error message for the given Exception
61     *
62     * @param \Throwable $e
63     * @param string $intro
64     */
65    public static function showExceptionMsg($e, $intro = 'Error!')
66    {
67        $msg = hsc($intro) . '<br />' . hsc(get_class($e) . ': ' . $e->getMessage());
68        if (self::logException($e)) $msg .= '<br />More info is available in the error log.';
69        msg($msg, -1);
70    }
71
72    /**
73     * Last resort to handle fatal errors that still can't be caught
74     */
75    public static function fatalShutdown()
76    {
77        $error = error_get_last();
78        // Check if it's a core/fatal error, otherwise it's a normal shutdown
79        if (
80            $error !== null &&
81            in_array(
82                $error['type'],
83                [
84                    E_ERROR,
85                    E_CORE_ERROR,
86                    E_COMPILE_ERROR,
87                ]
88            )
89        ) {
90            self::fatalException(
91                new FatalException($error['message'], 0, $error['type'], $error['file'], $error['line'])
92            );
93        }
94    }
95
96    /**
97     * Log the given exception to the error log
98     *
99     * @param \Throwable $e
100     * @return bool false if the logging failed
101     */
102    public static function logException($e)
103    {
104        if (is_a($e, \ErrorException::class) && $e->getSeverity() === E_WARNING) {
105            $prefix = 'Warning';
106        } else {
107            $prefix = get_class($e);
108        }
109
110
111        return Logger::getInstance()->log(
112            $prefix . ': ' . $e->getMessage(),
113            $e->getTraceAsString(),
114            $e->getFile(),
115            $e->getLine()
116        );
117    }
118
119    /**
120     * Log a warning
121     *
122     * @param int $errno
123     * @param string $errstr
124     * @param string $errfile
125     * @param int $errline
126     * @return bool
127     */
128    public static function logWarning($errno, $errstr, $errfile, $errline)
129    {
130        global $conf;
131
132        // ignore supressed warnings
133        if (!(error_reporting() & $errno)) return false;
134
135        $ex = new \ErrorException(
136            $errstr,
137            0,
138            $errno,
139            $errfile,
140            $errline
141        );
142        self::logException($ex);
143
144        return (bool)$conf['hidewarnings'];
145    }
146
147    /**
148     * Checks the the stacktrace for plugin files
149     *
150     * @param \Throwable $e
151     * @return false|string
152     */
153    protected static function guessPlugin($e)
154    {
155        if (preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $e->getFile()), $match)) {
156            return $match[1];
157        }
158
159        foreach ($e->getTrace() as $line) {
160            if (
161                isset($line['class']) &&
162                preg_match('/\w+?_plugin_(\w+)/', $line['class'], $match)
163            ) {
164                return $match[1];
165            }
166
167            if (
168                isset($line['file']) &&
169                preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $line['file']), $match)
170            ) {
171                return $match[1];
172            }
173        }
174
175        return false;
176    }
177}
178