xref: /dokuwiki/inc/ErrorHandler.php (revision 743a69085ea848604e66e72287d87479b11949d6)
1642e976cSAndreas Gohr<?php
2642e976cSAndreas Gohr
3642e976cSAndreas Gohrnamespace dokuwiki;
4642e976cSAndreas Gohr
5dbe0790dSAndreas Gohruse dokuwiki\Exception\FatalException;
6dbe0790dSAndreas Gohr
7dbe0790dSAndreas Gohr/**
8dbe0790dSAndreas Gohr * Manage the global handling of errors and exceptions
9dbe0790dSAndreas Gohr *
10dbe0790dSAndreas Gohr * Developer may use this to log and display exceptions themselves
11dbe0790dSAndreas Gohr */
12642e976cSAndreas Gohrclass ErrorHandler
13642e976cSAndreas Gohr{
14642e976cSAndreas Gohr    /**
1532f53e97SAndreas Gohr     * Standard error codes used in PHP errors
1632f53e97SAndreas Gohr     * @see https://www.php.net/manual/en/errorfunc.constants.php
1732f53e97SAndreas Gohr     */
1874981a4eSAndreas Gohr    protected const ERRORCODES = [
1932f53e97SAndreas Gohr        1 => 'E_ERROR',
2032f53e97SAndreas Gohr        2 => 'E_WARNING',
2132f53e97SAndreas Gohr        4 => 'E_PARSE',
2232f53e97SAndreas Gohr        8 => 'E_NOTICE',
2332f53e97SAndreas Gohr        16 => 'E_CORE_ERROR',
2432f53e97SAndreas Gohr        32 => 'E_CORE_WARNING',
2532f53e97SAndreas Gohr        64 => 'E_COMPILE_ERROR',
2632f53e97SAndreas Gohr        128 => 'E_COMPILE_WARNING',
2732f53e97SAndreas Gohr        256 => 'E_USER_ERROR',
2832f53e97SAndreas Gohr        512 => 'E_USER_WARNING',
2932f53e97SAndreas Gohr        1024 => 'E_USER_NOTICE',
3032f53e97SAndreas Gohr        2048 => 'E_STRICT',
3132f53e97SAndreas Gohr        4096 => 'E_RECOVERABLE_ERROR',
3232f53e97SAndreas Gohr        8192 => 'E_DEPRECATED',
3332f53e97SAndreas Gohr        16384 => 'E_USER_DEPRECATED',
3432f53e97SAndreas Gohr    ];
3532f53e97SAndreas Gohr
3632f53e97SAndreas Gohr    /**
37642e976cSAndreas Gohr     * Register the default error handling
38642e976cSAndreas Gohr     */
39642e976cSAndreas Gohr    public static function register()
40642e976cSAndreas Gohr    {
41642e976cSAndreas Gohr        if (!defined('DOKU_UNITTEST')) {
42093fe67eSAndreas Gohr            set_exception_handler(ErrorHandler::fatalException(...));
43cb4cefebSAndreas Gohr            register_shutdown_function([ErrorHandler::class, 'fatalShutdown']);
4432f53e97SAndreas Gohr            set_error_handler(
45093fe67eSAndreas Gohr                ErrorHandler::errorHandler(...),
4632f53e97SAndreas Gohr                E_WARNING | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR
4732f53e97SAndreas Gohr            );
48642e976cSAndreas Gohr        }
49642e976cSAndreas Gohr    }
50642e976cSAndreas Gohr
51642e976cSAndreas Gohr    /**
52642e976cSAndreas Gohr     * Default Exception handler to show a nice user message before dieing
53642e976cSAndreas Gohr     *
54642e976cSAndreas Gohr     * The exception is logged to the error log
55642e976cSAndreas Gohr     *
56642e976cSAndreas Gohr     * @param \Throwable $e
57642e976cSAndreas Gohr     */
58642e976cSAndreas Gohr    public static function fatalException($e)
59642e976cSAndreas Gohr    {
607e0b27f2SAndreas Gohr        $plugin = self::guessPlugin($e);
61093fe67eSAndreas Gohr        $title = hsc($e::class . ': ' . $e->getMessage());
62642e976cSAndreas Gohr        $msg = 'An unforeseen error has occured. This is most likely a bug somewhere.';
637e0b27f2SAndreas Gohr        if ($plugin) $msg .= ' It might be a problem in the ' . $plugin . ' plugin.';
64642e976cSAndreas Gohr        $logged = self::logException($e)
650ecde6ceSAndreas Gohr            ? 'More info has been written to the DokuWiki error log.'
66642e976cSAndreas Gohr            : $e->getFile() . ':' . $e->getLine();
67642e976cSAndreas Gohr
68642e976cSAndreas Gohr        echo <<<EOT
69642e976cSAndreas Gohr<!DOCTYPE html>
70642e976cSAndreas Gohr<html>
71642e976cSAndreas Gohr<head><title>$title</title></head>
72642e976cSAndreas Gohr<body style="font-family: Arial, sans-serif">
73642e976cSAndreas Gohr    <div style="width:60%; margin: auto; background-color: #fcc;
74642e976cSAndreas Gohr                border: 1px solid #faa; padding: 0.5em 1em;">
75642e976cSAndreas Gohr        <h1 style="font-size: 120%">$title</h1>
76642e976cSAndreas Gohr        <p>$msg</p>
77642e976cSAndreas Gohr        <p>$logged</p>
78642e976cSAndreas Gohr    </div>
79642e976cSAndreas Gohr</body>
80642e976cSAndreas Gohr</html>
81642e976cSAndreas GohrEOT;
82642e976cSAndreas Gohr    }
83642e976cSAndreas Gohr
84642e976cSAndreas Gohr    /**
85642e976cSAndreas Gohr     * Convenience method to display an error message for the given Exception
86642e976cSAndreas Gohr     *
87642e976cSAndreas Gohr     * @param \Throwable $e
88642e976cSAndreas Gohr     * @param string $intro
89642e976cSAndreas Gohr     */
90642e976cSAndreas Gohr    public static function showExceptionMsg($e, $intro = 'Error!')
91642e976cSAndreas Gohr    {
92093fe67eSAndreas Gohr        $msg = hsc($intro) . '<br />' . hsc($e::class . ': ' . $e->getMessage());
930ecde6ceSAndreas Gohr        if (self::logException($e)) $msg .= '<br />More info is available in the error log.';
94ffa84f81SAndreas Gohr        msg($msg, -1);
95642e976cSAndreas Gohr    }
96642e976cSAndreas Gohr
97642e976cSAndreas Gohr    /**
98dbe0790dSAndreas Gohr     * Last resort to handle fatal errors that still can't be caught
99cb4cefebSAndreas Gohr     */
100cb4cefebSAndreas Gohr    public static function fatalShutdown()
101cb4cefebSAndreas Gohr    {
102cb4cefebSAndreas Gohr        $error = error_get_last();
103cb4cefebSAndreas Gohr        // Check if it's a core/fatal error, otherwise it's a normal shutdown
104cb4cefebSAndreas Gohr        if (
105cb4cefebSAndreas Gohr            $error !== null &&
106cb4cefebSAndreas Gohr            in_array(
107cb4cefebSAndreas Gohr                $error['type'],
108cb4cefebSAndreas Gohr                [
109cb4cefebSAndreas Gohr                    E_ERROR,
110cb4cefebSAndreas Gohr                    E_CORE_ERROR,
111cb4cefebSAndreas Gohr                    E_COMPILE_ERROR,
112*743a6908Ssplitbrain                ],
113*743a6908Ssplitbrain                true
114cb4cefebSAndreas Gohr            )
115cb4cefebSAndreas Gohr        ) {
116cb4cefebSAndreas Gohr            self::fatalException(
117dbe0790dSAndreas Gohr                new FatalException($error['message'], 0, $error['type'], $error['file'], $error['line'])
118cb4cefebSAndreas Gohr            );
119cb4cefebSAndreas Gohr        }
120cb4cefebSAndreas Gohr    }
121cb4cefebSAndreas Gohr
122cb4cefebSAndreas Gohr    /**
123642e976cSAndreas Gohr     * Log the given exception to the error log
124642e976cSAndreas Gohr     *
125642e976cSAndreas Gohr     * @param \Throwable $e
126642e976cSAndreas Gohr     * @return bool false if the logging failed
127642e976cSAndreas Gohr     */
128642e976cSAndreas Gohr    public static function logException($e)
129642e976cSAndreas Gohr    {
13024870174SAndreas Gohr        if ($e instanceof \ErrorException) {
13132f53e97SAndreas Gohr            $prefix = self::ERRORCODES[$e->getSeverity()];
132be6462f4SAndreas Gohr        } else {
133093fe67eSAndreas Gohr            $prefix = $e::class;
134be6462f4SAndreas Gohr        }
135be6462f4SAndreas Gohr
1360ecde6ceSAndreas Gohr        return Logger::getInstance()->log(
137be6462f4SAndreas Gohr            $prefix . ': ' . $e->getMessage(),
1380ecde6ceSAndreas Gohr            $e->getTraceAsString(),
1390ecde6ceSAndreas Gohr            $e->getFile(),
1400ecde6ceSAndreas Gohr            $e->getLine()
1410ecde6ceSAndreas Gohr        );
142642e976cSAndreas Gohr    }
1437e0b27f2SAndreas Gohr
1447e0b27f2SAndreas Gohr    /**
14532f53e97SAndreas Gohr     * Error handler to log non-exception errors
146be6462f4SAndreas Gohr     *
147be6462f4SAndreas Gohr     * @param int $errno
148be6462f4SAndreas Gohr     * @param string $errstr
149be6462f4SAndreas Gohr     * @param string $errfile
150be6462f4SAndreas Gohr     * @param int $errline
151be6462f4SAndreas Gohr     * @return bool
152be6462f4SAndreas Gohr     */
15332f53e97SAndreas Gohr    public static function errorHandler($errno, $errstr, $errfile, $errline)
154be6462f4SAndreas Gohr    {
155be6462f4SAndreas Gohr        global $conf;
156be6462f4SAndreas Gohr
157be6462f4SAndreas Gohr        // ignore supressed warnings
158be6462f4SAndreas Gohr        if (!(error_reporting() & $errno)) return false;
159be6462f4SAndreas Gohr
160be6462f4SAndreas Gohr        $ex = new \ErrorException(
161be6462f4SAndreas Gohr            $errstr,
162be6462f4SAndreas Gohr            0,
163be6462f4SAndreas Gohr            $errno,
164be6462f4SAndreas Gohr            $errfile,
165be6462f4SAndreas Gohr            $errline
166be6462f4SAndreas Gohr        );
167be6462f4SAndreas Gohr        self::logException($ex);
168be6462f4SAndreas Gohr
16932f53e97SAndreas Gohr        if ($ex->getSeverity() === E_WARNING && $conf['hidewarnings']) {
17032f53e97SAndreas Gohr            return true;
17132f53e97SAndreas Gohr        }
17232f53e97SAndreas Gohr
17332f53e97SAndreas Gohr        return false;
174be6462f4SAndreas Gohr    }
175be6462f4SAndreas Gohr
176be6462f4SAndreas Gohr    /**
1777e0b27f2SAndreas Gohr     * Checks the the stacktrace for plugin files
1787e0b27f2SAndreas Gohr     *
1797e0b27f2SAndreas Gohr     * @param \Throwable $e
1807e0b27f2SAndreas Gohr     * @return false|string
1817e0b27f2SAndreas Gohr     */
1827e0b27f2SAndreas Gohr    protected static function guessPlugin($e)
1837e0b27f2SAndreas Gohr    {
184dbe0790dSAndreas Gohr        if (preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $e->getFile()), $match)) {
185dbe0790dSAndreas Gohr            return $match[1];
186dbe0790dSAndreas Gohr        }
187dbe0790dSAndreas Gohr
1887e0b27f2SAndreas Gohr        foreach ($e->getTrace() as $line) {
1897e0b27f2SAndreas Gohr            if (
1907e0b27f2SAndreas Gohr                isset($line['class']) &&
1917e0b27f2SAndreas Gohr                preg_match('/\w+?_plugin_(\w+)/', $line['class'], $match)
1927e0b27f2SAndreas Gohr            ) {
1937e0b27f2SAndreas Gohr                return $match[1];
1947e0b27f2SAndreas Gohr            }
1957e0b27f2SAndreas Gohr
1967e0b27f2SAndreas Gohr            if (
1977e0b27f2SAndreas Gohr                isset($line['file']) &&
1987e0b27f2SAndreas Gohr                preg_match('/lib\/plugins\/(\w+)\//', str_replace('\\', '/', $line['file']), $match)
1997e0b27f2SAndreas Gohr            ) {
2007e0b27f2SAndreas Gohr                return $match[1];
2017e0b27f2SAndreas Gohr            }
2027e0b27f2SAndreas Gohr        }
2037e0b27f2SAndreas Gohr
2047e0b27f2SAndreas Gohr        return false;
2057e0b27f2SAndreas Gohr    }
206642e976cSAndreas Gohr}
207