4 * @copyright 2001-2019 WoltLab GmbH
5 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
6 * @package WoltLabSuite\Core
11 // set exception handler
12 set_exception_handler([WCF
::class, 'handleException']);
13 // set php error handler
14 set_error_handler([WCF
::class, 'handleError'], E_ALL
);
15 // set shutdown function
16 register_shutdown_function([WCF
::class, 'destruct']);
17 // set autoload function
18 spl_autoload_register([WCF
::class, 'autoload']);
21 * Escapes a string for use in sql query.
23 * @see \wcf\system\database\Database::escapeString()
24 * @param string $string
27 function escapeString($string) {
28 return WCF
::getDB()->escapeString($string);
32 * Helper method to output debug data for all passed variables,
33 * uses `print_r()` for arrays and objects, `var_dump()` otherwise.
38 $args = func_get_args();
39 $length = count($args);
41 echo "ERROR: No arguments provided.<hr>";
44 for ($i = 0; $i < $length; $i++
) {
47 echo "<h2>Argument {$i} (" . gettype($arg) . ")</h2>";
49 if (is_array($arg) ||
is_object($arg)) {
60 $backtrace = debug_backtrace();
62 // output call location to help finding these debug outputs again
63 echo "wcfDebug() called in {$backtrace[0]['file']} on line {$backtrace[0]['line']}";
70 // define DOCUMENT_ROOT on IIS if not set
71 if (PHP_EOL
== "\r\n") {
72 if (!isset($_SERVER['DOCUMENT_ROOT']) && isset($_SERVER['SCRIPT_FILENAME'])) {
73 $_SERVER['DOCUMENT_ROOT'] = str_replace('\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0 - strlen($_SERVER['PHP_SELF'])));
75 if (!isset($_SERVER['DOCUMENT_ROOT']) && isset($_SERVER['PATH_TRANSLATED'])) {
76 $_SERVER['DOCUMENT_ROOT'] = str_replace('\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0 - strlen($_SERVER['PHP_SELF'])));
79 if (!isset($_SERVER['REQUEST_URI'])) {
80 $_SERVER['REQUEST_URI'] = substr($_SERVER['PHP_SELF'], 1);
81 if (isset($_SERVER['QUERY_STRING'])) {
82 $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING'];
87 // setting global gzip compression breaks output buffering
88 if (@ini_get
('zlib.output_compression')) {
89 @ini_set
('zlib.output_compression', '0');
92 if (!function_exists('is_countable')) {
93 function is_countable($var) {
94 return is_array($var) ||
$var instanceof Countable ||
$var instanceof ResourceBundle ||
$var instanceof SimpleXmlElement
;
99 // @codingStandardsIgnoreStart
101 function getRequestId() {
102 if (!defined('WCF_REQUEST_ID_HEADER') ||
!WCF_REQUEST_ID_HEADER
) return '';
104 return $_SERVER[WCF_REQUEST_ID_HEADER
] ??
'';
108 namespace wcf\functions\exception
{
110 use wcf\system\exception\IExtraInformationException
;
111 use wcf\system\exception\SystemException
;
112 use wcf\util\FileUtil
;
113 use wcf\util\StringUtil
;
116 * Logs the given Throwable.
118 * @param \Throwable|\Exception $e
119 * @param string $logFile The log file to use. If set to `null` the default log file will be used and the variable contents will be replaced by the actual path.
120 * @return string The ID of the log entry.
122 function logThrowable($e, &$logFile = null) {
123 if ($logFile === null) $logFile = WCF_DIR
. 'log/' . gmdate('Y-m-d', TIME_NOW
) . '.txt';
126 $stripNewlines = function ($item) {
127 return str_replace("\n", ' ', $item);
130 // don't forget to update ExceptionLogViewPage, when changing the log file format
131 $message = gmdate('r', TIME_NOW
)."\n".
132 'Message: '.$stripNewlines($e->getMessage())."\n".
133 'PHP version: '.phpversion()."\n".
134 'WoltLab Suite version: '.WCF_VERSION
."\n".
135 'Request URI: '.$stripNewlines($_SERVER['REQUEST_URI'] ??
'').(\wcf\
getRequestId() ?
' ('.\wcf\
getRequestId().')' : '')."\n".
136 'Referrer: '.$stripNewlines($_SERVER['HTTP_REFERER'] ??
'')."\n".
137 'User Agent: '.$stripNewlines($_SERVER['HTTP_USER_AGENT'] ??
'')."\n".
138 'Peak Memory Usage: '.memory_get_peak_usage().'/'.FileUtil
::getMemoryLimit()."\n";
141 $message .= "======\n".
142 'Error Class: '.get_class($prev)."\n".
143 'Error Message: '.$stripNewlines($prev->getMessage())."\n".
144 'Error Code: '.intval($prev->getCode())."\n".
145 'File: '.$stripNewlines($prev->getFile()).' ('.$prev->getLine().')'."\n".
146 'Extra Information: '.($prev instanceof IExtraInformationException ?
base64_encode(serialize($prev->getExtraInformation())) : '-')."\n".
147 'Stack Trace: '.json_encode(array_map(function ($item) {
148 $item['args'] = array_map(function ($item) {
149 switch (gettype($item)) {
151 return get_class($item);
153 return array_map(function () {
157 return 'resource('.get_resource_type($item).')';
164 }, sanitizeStacktrace($prev, true)))."\n";
166 while ($prev = $prev->getPrevious());
168 // calculate Exception-ID
169 $exceptionID = sha1($message);
170 $entry = "<<<<<<<<".$exceptionID."<<<<\n".$message."<<<<\n\n";
172 file_put_contents($logFile, $entry, FILE_APPEND
);
174 // let the Exception know it has been logged
175 if (method_exists($e, 'finalizeLog') && is_callable([$e, 'finalizeLog'])) $e->finalizeLog($exceptionID, $logFile);
181 * Pretty prints the given Throwable. It is recommended to `exit;`
182 * the request after calling this function.
184 * @param \Throwable|\Exception $e
187 function printThrowable($e) {
188 $exceptionID = logThrowable($e, $logFile);
189 if (\wcf\
getRequestId()) $exceptionID .= '/'.\wcf\
getRequestId();
191 $exceptionTitle = $exceptionSubtitle = $exceptionExplanation = '';
192 $logFile = sanitizePath($logFile);
194 if (WCF
::getLanguage() !== null) {
195 $exceptionTitle = WCF
::getLanguage()->get('wcf.global.exception.title', true);
196 $exceptionSubtitle = str_replace('{$exceptionID}', $exceptionID, WCF
::getLanguage()->get('wcf.global.exception.subtitle', true));
197 $exceptionExplanation = str_replace('{$logFile}', $logFile, WCF
::getLanguage()->get('wcf.global.exception.explanation', true));
200 catch (\Throwable
$e) {
204 if (!$exceptionTitle ||
!$exceptionSubtitle ||
!$exceptionExplanation) {
205 // one or more failed, fallback to english
206 $exceptionTitle = 'An error has occurred';
207 $exceptionSubtitle = 'Internal error code: <span class="exceptionInlineCodeWrapper"><span class="exceptionInlineCode">'.$exceptionID.'</span></span>';
208 $exceptionExplanation = <<<EXPLANATION
209 <p class="exceptionSubtitle">What happened?</p>
210 <p class="exceptionText">An error has occured while trying to handle your request and execution has been terminated. Please forward the above error code to the site administrator.</p>
211 <p class="exceptionText"> </p> <!-- required to ensure spacing after copy & paste -->
212 <p class="exceptionText">
213 The error code can be used by an administrator to lookup the full error message in the Administration Control Panel via “Logs » Errors”.
214 In addition the error has been written to the log file located at <span class="exceptionInlineCodeWrapper"><span class="exceptionInlineCode">{$logFile}</span></span> and can be accessed with a FTP program or similar.
216 <p class="exceptionText"> </p> <!-- required to ensure spacing after copy & paste -->
217 <p class="exceptionText">Notice: The error code was randomly generated and has no use beyond looking up the full message.</p>
223 * A notice on the HTML used below:
225 * It might appear a bit weird to use <p> all over the place where semantically
226 * other elements would fit in way better. The reason behind this is that we avoid
227 * inheriting unwanted styles (e.g. exception displayed in an overlay) and that
228 * the output needs to be properly readable when copied & pasted somewhere.
230 * Besides the visual appearance, the output was built to provide a maximum of
231 * compatibility and readability when pasted somewhere else, e.g. a WYSIWYG editor
232 * without the potential of messing up the formatting and thus harming the readability.
237 <?php
if (!defined('EXCEPTION_PRIVACY') || EXCEPTION_PRIVACY
!== 'private') { ?
>
238 <title
>Fatal Error
: <?php
echo StringUtil
::encodeHTML($e->getMessage()); ?
></title
>
240 <title
>Fatal Error
</title
>
242 <meta charset
="utf-8">
243 <meta name
="viewport" content
="width=device-width, initial-scale=1">
246 background
-color
: rgb(250, 250, 250);
247 color
: rgb(44, 62, 80);
252 .exceptionContainer
{
253 box
-sizing
: border
-box
;
254 font
-family
: 'Segoe UI', 'Lucida Grande', 'Helvetica Neue', Helvetica
, Arial
, sans
-serif
;
256 padding
-bottom
: 20px
;
259 .exceptionContainer
* {
267 background
-color
: rgb(58, 109, 156);
277 .exceptionErrorCode
{
282 .exceptionErrorCode
.exceptionInlineCode
{
283 background
-color
: rgb(43, 79, 113);
286 font
-family
: monospace
;
292 border
-bottom
: 1px solid
rgb(238, 238, 238);
296 padding
-bottom
: 10px
;
299 .exceptionContainer
> .exceptionBoundary
{
303 .exceptionText
.exceptionInlineCodeWrapper
{
304 border
: 1px solid
rgb(169, 169, 169);
309 .exceptionText
.exceptionInlineCode
{
310 font
-family
: monospace
;
314 .exceptionFieldTitle
{
315 color
: rgb(59, 109, 169);
318 .exceptionFieldTitle
.exceptionColon
{
319 /* hide colon in browser, but will be visible after copy & paste */
323 .exceptionFieldValue
{
328 .exceptionSystemInformation
,
329 .exceptionErrorDetails
,
330 .exceptionStacktrace
{
331 list-style
-type
: none
;
334 .exceptionSystemInformation
> li
:not(:first
-child
),
335 .exceptionErrorDetails
> li
:not(:first
-child
) {
339 .exceptionStacktrace
{
343 padding
-bottom
: 20px
;
346 .exceptionStacktraceFile
,
347 .exceptionStacktraceFile span
,
348 .exceptionStacktraceCall
,
349 .exceptionStacktraceCall span
{
350 font
-family
: monospace
!important
;
351 white
-space
: nowrap
!important
;
354 .exceptionStacktraceCall +
.exceptionStacktraceFile
{
358 .exceptionStacktraceCall
{
362 .exceptionStacktraceCall
,
363 .exceptionStacktraceCall span
{
364 color
: rgb(102, 102, 102) !important
;
365 font
-size
: 13px
!important
;
369 @media
(max
-width
: 767px
) {
375 .exceptionText
.exceptionInlineCodeWrapper
{
376 display
: inline
-block
;
380 .exceptionErrorCode
.exceptionInlineCode
{
387 @media
(min
-width
: 768px
) {
395 .exceptionSystemInformation
{
400 .exceptionSystemInformation1
,
401 .exceptionSystemInformation3
,
402 .exceptionSystemInformation5
{
404 margin
: 0 0 10px
0 !important
;
407 .exceptionSystemInformation2
,
408 .exceptionSystemInformation4
,
409 .exceptionSystemInformation6
{
410 flex
: 0 0 calc(100%
- 210px
);
411 margin
: 0 0 10px
10px
!important
;
412 max
-width
: calc(100%
- 210px
);
415 .exceptionSystemInformation1
{ order
: 1; }
416 .exceptionSystemInformation2
{ order
: 2; }
417 .exceptionSystemInformation3
{ order
: 3; }
418 .exceptionSystemInformation4
{ order
: 4; }
419 .exceptionSystemInformation5
{ order
: 5; }
420 .exceptionSystemInformation6
{ order
: 6; }
422 .exceptionSystemInformation
.exceptionFieldValue
{
424 text
-overflow
: ellipsis
;
430 <body
class="exceptionBody">
431 <div
class="exceptionContainer">
432 <div
class="exceptionHeader">
433 <div
class="exceptionBoundary">
434 <p
class="exceptionTitle"><?php
echo $exceptionTitle; ?
></p
>
435 <p
class="exceptionErrorCode"><?php
echo str_replace('{$exceptionID}', $exceptionID, $exceptionSubtitle); ?
></p
>
439 <div
class="exceptionBoundary">
440 <?php
echo $exceptionExplanation; ?
>
442 <?php
if (!defined('EXCEPTION_PRIVACY') || EXCEPTION_PRIVACY
!== 'private') { ?
>
443 <div
class="exceptionBoundary">
444 <p
class="exceptionSubtitle">System Information
</p
>
445 <ul
class="exceptionSystemInformation">
446 <li
class="exceptionSystemInformation1">
447 <p
class="exceptionFieldTitle">PHP Version
<span
class="exceptionColon">:</span
></p
>
448 <p
class="exceptionFieldValue"><?php
echo StringUtil
::encodeHTML(phpversion()); ?
></p
>
450 <li
class="exceptionSystemInformation3">
451 <p
class="exceptionFieldTitle">WoltLab Suite Core
<span
class="exceptionColon">:</span
></p
>
452 <p
class="exceptionFieldValue"><?php
echo StringUtil
::encodeHTML(WCF_VERSION
); ?
></p
>
454 <li
class="exceptionSystemInformation5">
455 <p
class="exceptionFieldTitle">Peak Memory Usage
<span
class="exceptionColon">:</span
></p
>
456 <p
class="exceptionFieldValue"><?php
echo round(memory_get_peak_usage() / 1024 / 1024, 3); ?
>/<?php
echo round(FileUtil
::getMemoryLimit() / 1024 / 1024, 3); ?
> MiB
</p
>
458 <li
class="exceptionSystemInformation2">
459 <p
class="exceptionFieldTitle">Request URI
<span
class="exceptionColon">:</span
></p
>
460 <p
class="exceptionFieldValue"><?php
if (isset($_SERVER['REQUEST_URI'])) echo StringUtil
::encodeHTML($_SERVER['REQUEST_URI']); ?
></p
>
462 <li
class="exceptionSystemInformation4">
463 <p
class="exceptionFieldTitle">Referrer
<span
class="exceptionColon">:</span
></p
>
464 <p
class="exceptionFieldValue"><?php
if (isset($_SERVER['HTTP_REFERER'])) echo StringUtil
::encodeHTML($_SERVER['HTTP_REFERER']); ?
></p
>
466 <li
class="exceptionSystemInformation6">
467 <p
class="exceptionFieldTitle">User Agent
<span
class="exceptionColon">:</span
></p
>
468 <p
class="exceptionFieldValue"><?php
if (isset($_SERVER['HTTP_USER_AGENT'])) echo StringUtil
::encodeHTML($_SERVER['HTTP_USER_AGENT']); ?
></p
>
478 $exceptions[] = $current;
480 while ($current = $current->getPrevious());
482 $e = array_pop($exceptions);
485 <div
class="exceptionBoundary">
486 <p
class="exceptionSubtitle"><?php
if (!empty($exceptions) && $first) { echo "Original "; } else if (empty($exceptions) && !$first) { echo "Final "; } ?
>Error
</p
>
487 <?php
if ($e instanceof SystemException
&& $e->getDescription()) { ?
>
488 <p
class="exceptionText"><?php
echo $e->getDescription(); ?
></p
>
490 <ul
class="exceptionErrorDetails">
492 <p
class="exceptionFieldTitle">Error Type
<span
class="exceptionColon">:</span
></p
>
493 <p
class="exceptionFieldValue"><?php
echo StringUtil
::encodeHTML(get_class($e)); ?
></p
>
496 <p
class="exceptionFieldTitle">Error Message
<span
class="exceptionColon">:</span
></p
>
497 <p
class="exceptionFieldValue"><?php
echo StringUtil
::encodeHTML($e->getMessage()); ?
></p
>
499 <?php
if ($e->getCode()) { ?
>
501 <p
class="exceptionFieldTitle">Error Code
<span
class="exceptionColon">:</span
></p
>
502 <p
class="exceptionFieldValue"><?php
echo intval($e->getCode()); ?
></p
>
506 <p
class="exceptionFieldTitle">File
<span
class="exceptionColon">:</span
></p
>
507 <p
class="exceptionFieldValue" style
="word-break: break-all"><?php
echo StringUtil
::encodeHTML(sanitizePath($e->getFile())); ?
> (<?php
echo $e->getLine(); ?
>)</p
>
511 if ($e instanceof SystemException
) {
516 $reflection = new \
ReflectionClass($e);
517 $property = $reflection->getProperty('information');
518 $property->setAccessible(true);
519 if ($property->getValue($e)) {
520 throw new \
Exception("Using the 'information' property of SystemException is not supported any more.");
523 if ($e instanceof IExtraInformationException
) {
524 foreach ($e->getExtraInformation() as list($key, $value)) {
527 <p
class="exceptionFieldTitle"><?php
echo StringUtil
::encodeHTML($key); ?
><span
class="exceptionColon">:</span
></p
>
528 <p
class="exceptionFieldValue"><?php
echo StringUtil
::encodeHTML($value); ?
></p
>
535 <p
class="exceptionFieldTitle">Stack Trace
<span
class="exceptionColon">:</span
></p
>
536 <ul
class="exceptionStacktrace">
538 $trace = sanitizeStacktrace($e);
539 for ($i = 0, $max = count($trace); $i < $max; $i++
) {
541 <li
class="exceptionStacktraceFile"><?php
echo '#'.$i.' '.StringUtil
::encodeHTML($trace[$i]['file']).' ('.$trace[$i]['line'].')'.':'; ?
></li
>
542 <li
class="exceptionStacktraceCall">
544 echo $trace[$i]['class'].$trace[$i]['type'].$trace[$i]['function'].'(';
545 echo implode(', ', array_map(function ($item) {
546 switch (gettype($item)) {
553 return "'".addcslashes(StringUtil
::encodeHTML($item), "\\'")."'";
555 return $item ?
'true' : 'false';
557 $keys = array_keys($item);
558 if (count($keys) > 5) return "[ ".count($keys)." items ]";
559 return '[ '.implode(', ', array_map(function ($item) {
563 return get_class($item);
565 return 'resource('.get_resource_type($item).')';
566 case 'resource (closed)':
567 return 'resource (closed)';
570 throw new \
LogicException('Unreachable');
571 }, $trace[$i]['args']));
581 } while ($e = array_pop($exceptions));
591 * Returns the stack trace of the given Throwable with sensitive
592 * information removed.
594 * @param \Throwable|\Exception $e
595 * @param boolean $ignorePaths If set to `true`: Don't call `sanitizePath`.
598 function sanitizeStacktrace($e, $ignorePaths = false) {
599 $trace = $e->getTrace();
601 return array_map(function ($item) use ($ignorePaths) {
602 if (!isset($item['file'])) $item['file'] = '[internal function]';
603 if (!isset($item['line'])) $item['line'] = '?';
604 if (!isset($item['class'])) $item['class'] = '';
605 if (!isset($item['type'])) $item['type'] = '';
606 if (!isset($item['args'])) $item['args'] = [];
608 // strip database credentials
609 if (preg_match('~\\\\?wcf\\\\system\\\\database\\\\[a-zA-Z]*Database~', $item['class']) ||
$item['class'] === 'PDO') {
610 if ($item['function'] === '__construct') {
611 $item['args'] = array_map(function () {
618 $item['args'] = array_map(function ($item) {
619 if (!is_string($item)) return $item;
621 if (preg_match('~^('.preg_quote($_SERVER['DOCUMENT_ROOT'], '~').'|'.preg_quote(WCF_DIR
, '~').')~', $item)) {
622 $item = sanitizePath($item);
628 $item['file'] = sanitizePath($item['file']);
636 * Returns the given path relative to `WCF_DIR`, unless both,
637 * `EXCEPTION_PRIVACY` is `public` and the debug mode is enabled.
639 * @param string $path
642 function sanitizePath($path) {
643 if (WCF
::debugModeIsEnabled() && defined('EXCEPTION_PRIVACY') && EXCEPTION_PRIVACY
=== 'public') {
647 return '*/'.FileUtil
::removeTrailingSlash(FileUtil
::getRelativePath(WCF_DIR
, $path));
650 // @codingStandardsIgnoreEnd