-
-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathBlueScreen.php
More file actions
601 lines (494 loc) 路 16.5 KB
/
Copy pathBlueScreen.php
File metadata and controls
601 lines (494 loc) 路 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
<?php declare(strict_types=1);
/**
* This file is part of the Tracy (https://tracy.nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Tracy;
use function in_array;
use const ARRAY_FILTER_USE_KEY, ENT_IGNORE, PHP_VERSION_ID;
/**
* Renders a beautiful error/exception page with syntax-highlighted stack trace.
*/
class BlueScreen
{
private const MaxMessageLength = 2000;
/** @var string[] */
public array $info = [];
/**
* @var string[]
* @deprecated use Debugger::$transparentPaths instead
*/
public array $collapsePaths = [];
public int $maxDepth = 5;
public int $maxLength = 150;
public int $maxItems = 100;
/** @var ?(callable(string $key, mixed $value, ?string $class): bool) callable returning true for sensitive data */
public $scrubber;
/** @var string[] */
public array $keysToHide = [
'password', 'passwd', 'pass', 'pwd', 'creditcard', 'credit card', 'cc', 'pin', 'authorization',
self::class . '::$snapshot',
];
public bool $showEnvironment = true;
/** @var array<\Closure(?\Throwable): ?array{tab: string, panel: string}> */
private array $panels = [];
/** @var array<\Closure(\Throwable): ?array{link: string, label: string}> */
private array $actions = [];
/** @var array<\Closure(string, ?string): ?string> */
private array $fileGenerators = [];
/** @var array{0?: Dumper\Value[], 1?: mixed[]} */
private array $snapshot = [];
/** @var \WeakMap<\Fiber|\Generator, true> */
private \WeakMap $fibers;
public function __construct()
{
$this->fileGenerators[] = self::generateNewPhpFileContents(...);
$this->fibers = new \WeakMap;
}
/**
* Add custom panel.
* @param callable(?\Throwable): ?array{tab: string, panel: string} $panel
*/
public function addPanel(callable $panel): static
{
$panel = $panel(...);
if (!in_array($panel, $this->panels, strict: true)) {
$this->panels[] = $panel;
}
return $this;
}
/**
* Add action.
* @param callable(\Throwable): ?array{link: string, label: string} $action
*/
public function addAction(callable $action): static
{
$this->actions[] = $action(...);
return $this;
}
/**
* Add new file generator.
* @param callable(string, ?string): ?string $generator
*/
public function addFileGenerator(callable $generator): static
{
$this->fileGenerators[] = $generator(...);
return $this;
}
public function addFiber(\Fiber|\Generator $fiber): static
{
$this->fibers[$fiber] = true;
return $this;
}
/**
* Renders blue screen.
*/
public function render(\Throwable $exception): void
{
if (!headers_sent()) {
header('Content-Type: text/html; charset=UTF-8');
}
$this->renderTemplate($exception, __DIR__ . '/dist/page.phtml');
}
/**
* Captures blue screen as plain text (markdown).
* @param ?array{file: string, line: int} $logLocation
*/
public function renderAgent(\Throwable $exception, ?array $logLocation = null): string
{
return Helpers::capture(fn() => $this->renderTemplate($exception, __DIR__ . '/dist/agent.phtml', logLocation: $logLocation));
}
/** @internal */
public function renderToAjax(\Throwable $exception, DeferredContent $defer): void
{
$defer->addSetup('Tracy.BlueScreen.loadAjax', Helpers::capture(fn() => $this->renderTemplate($exception, __DIR__ . '/dist/content.phtml')));
if (Helpers::isAgent()) {
$defer->addSetup('console.error', $this->renderAgent($exception));
}
}
/**
* Renders blue screen to file (if file exists, it will not be overwritten).
* @param ?array{file: string, line: int} $logLocation location from which Debugger::log() was called
*/
public function renderToFile(\Throwable $exception, string $file, ?array $logLocation = null): bool
{
if ($handle = @fopen($file, 'x')) {
ob_start(); // double buffer prevents sending HTTP headers in some PHP
ob_start(function ($buffer) use ($handle) {
fwrite($handle, $buffer);
return '';
}, 4096);
$this->renderTemplate($exception, __DIR__ . '/dist/page.phtml', toScreen: false, logLocation: $logLocation);
ob_end_flush();
ob_end_clean();
fclose($handle);
if ($handle = @fopen(substr($file, 0, -5) . '.md', 'x')) {
fwrite($handle, $this->renderAgent($exception, $logLocation));
fclose($handle);
}
return true;
}
return false;
}
/**
* @param ?array{file: string, line: int} $logLocation
*/
private function renderTemplate(
\Throwable $exception,
string $template,
bool $toScreen = true,
?array $logLocation = null,
): void
{
[$generators, $fibers] = $this->findGeneratorsAndFibers($exception);
$headersSent = headers_sent($headersFile, $headersLine);
$obStatus = Debugger::$obStatus;
$showEnvironment = $this->showEnvironment && (!str_contains($exception->getMessage(), 'Allowed memory size'));
$info = array_filter($this->info);
$source = Helpers::getSource();
$lastError = $exception instanceof \ErrorException || $exception instanceof \Error
? null
: error_get_last();
if (function_exists('apache_request_headers')) {
$httpHeaders = apache_request_headers();
} else {
$httpHeaders = array_filter($_SERVER, fn($k) => str_starts_with($k, 'HTTP_'), ARRAY_FILTER_USE_KEY);
$httpHeaders = array_combine(array_map(fn($k) => strtolower(strtr(substr($k, 5), '_', '-')), array_keys($httpHeaders)), $httpHeaders);
}
$this->snapshot = [];
$snapshot = &$this->snapshot[0];
$dump = $this->getDumper();
$agentDump = $this->getAgentDumper();
$css = array_map(file_get_contents(...), array_merge([
__DIR__ . '/../assets/reset.css',
__DIR__ . '/assets/bluescreen.css',
__DIR__ . '/../assets/toggle.css',
__DIR__ . '/../assets/table-sort.css',
__DIR__ . '/../assets/tabs.css',
__DIR__ . '/../Dumper/assets/dumper-light.css',
], Debugger::$customCssFiles));
$css = Helpers::minifyCss(implode('', $css));
$js = array_map(fn($file) => '(function(){' . file_get_contents($file) . '})();', [
__DIR__ . '/../assets/toggle.js',
__DIR__ . '/../assets/table-sort.js',
__DIR__ . '/../assets/tabs.js',
__DIR__ . '/../assets/helpers.js',
__DIR__ . '/../Dumper/assets/dumper.js',
__DIR__ . '/assets/bluescreen.js',
]);
$js = Helpers::minifyJs(implode('', $js));
$nonce = $toScreen ? Helpers::getNonce() : null;
$actions = $toScreen ? $this->renderActions($exception) : [];
$blueScreen = $this;
require $template;
$this->snapshot = [];
}
/**
* @return list<\stdClass>
*/
private function renderPanels(?\Throwable $ex): array
{
$obLevel = ob_get_level();
$res = [];
foreach ($this->panels as $callback) {
try {
$panel = $callback($ex);
if (empty($panel['tab']) || empty($panel['panel'])) {
continue;
}
$res[] = (object) $panel;
continue;
} catch (\Throwable $e) {
}
while (ob_get_level() > $obLevel) { // restore ob-level if broken
ob_end_clean();
}
is_callable($callback, true, $name);
$res[] = (object) [
'tab' => "Error in panel $name",
'panel' => nl2br(Helpers::escapeHtml($e)),
];
}
return $res;
}
/**
* @return list<array{link: string, label: string, external?: bool}>
*/
private function renderActions(\Throwable $ex): array
{
$actions = [];
foreach ($this->actions as $callback) {
$action = $callback($ex);
if (!empty($action['link']) && !empty($action['label'])) {
$actions[] = $action;
}
}
if (
property_exists($ex, 'tracyAction')
&& !empty($ex->tracyAction['link'])
&& !empty($ex->tracyAction['label'])
) {
$actions[] = $ex->tracyAction;
}
if (preg_match('# ([\'"])(\w{3,}(?:\\\\\w{2,})+)\1#i', $ex->getMessage(), $m)) {
$class = $m[2];
if (
!class_exists($class, autoload: false) && !interface_exists($class, autoload: false) && !trait_exists($class, autoload: false)
&& ($file = Helpers::guessClassFile($class)) && !@is_file($file) // @ - may trigger error
) {
[$content, $line] = $this->generateNewFileContents($file, $class);
$actions[] = [
'link' => Helpers::editorUri($file, $line, 'create', '', $content),
'label' => 'create class',
];
}
}
if (preg_match('# ([\'"])((?:/|[a-z]:[/\\\])\w[^\'"]+\.\w{2,5})\1#i', $ex->getMessage(), $m)) {
$file = $m[2];
if (@is_file($file)) { // @ - may trigger error
$label = 'open';
$content = '';
$line = 1;
} else {
$label = 'create';
[$content, $line] = $this->generateNewFileContents($file);
}
$actions[] = [
'link' => Helpers::editorUri($file, $line, $label, '', $content),
'label' => $label . ' file',
];
}
$query = ($ex instanceof \ErrorException ? '' : get_debug_type($ex) . ' ')
. preg_replace('#\'.*\'|".*"#Us', '', $ex->getMessage());
$actions[] = [
'link' => 'https://www.google.com/search?sourceid=tracy&q=' . urlencode($query),
'label' => 'search',
'external' => true,
];
if (
$ex instanceof \ErrorException
&& !empty($ex->skippable)
&& preg_match('#^https?://#', $source = Helpers::getSource())
) {
$actions[] = [
'link' => $source . (strpos($source, '?') ? '&' : '?') . '_tracy_skip_error',
'label' => 'skip error',
];
}
return $actions;
}
/** @internal */
public static function getExceptionTitle(\Throwable $exception): string
{
return $exception instanceof \ErrorException
? Helpers::errorTypeToString($exception->getSeverity())
: get_debug_type($exception);
}
/**
* Returns syntax highlighted snippet from a file, or null if the file cannot be read.
*/
public static function highlightFile(
string $file,
int $line,
int $lines = 15,
bool $php = true,
int $column = 0,
): ?string
{
$source = @file_get_contents($file); // @ file may not exist
if ($source === false) {
return null;
}
$source = $php
? CodeHighlighter::highlightPhp($source, $line, $column)
: '<pre class=tracy-code><div>' . CodeHighlighter::highlightLine(htmlspecialchars($source, ENT_IGNORE, 'UTF-8'), $line, $column) . '</div></pre>';
if ($editor = Helpers::editorUri($file, line: $line, column: $column)) {
$source = substr_replace($source, ' title="Ctrl-Click to open in editor" data-tracy-href="' . Helpers::escapeHtml($editor) . '"', 4, 0);
}
return $source;
}
/**
* Returns syntax highlighted PHP source code with the given line emphasized.
*/
public static function highlightPhp(string $source, int $line, int $lines = 15, int $column = 0): string
{
return CodeHighlighter::highlightPhp($source, $line, $column);
}
/**
* Returns highlighted line in already-tokenized HTML code.
*/
public static function highlightLine(string $html, int $line, int $lines = 15, int $column = 0): string
{
return CodeHighlighter::highlightLine($html, $line, $column);
}
/**
* Should a file be collapsed in stack trace?
* @deprecated use Helpers::countTransparentFrames()
* @internal
*/
public function isCollapsed(string $file): bool
{
return Helpers::countTransparentFrames([['file' => $file]], [...$this->collapsePaths, ...Debugger::$transparentPaths]) > 0;
}
/**
* Returns the exception's stack trace with Tracy-internal handler frames stripped, together with the
* index of the frame that should be expanded by default (or null).
* Strips top frames belonging to DevelopmentStrategy/ProductionStrategy and Debugger error/shutdown handlers.
* @return array{list<array{file?: string, line?: int, class?: string, type?: string, function: string, args?: array<mixed>}>, ?int}
* @internal
*/
public function prepareStack(\Throwable $ex): array
{
$stack = $ex->getTrace();
while ($stack && (
in_array($stack[0]['class'] ?? null, [DevelopmentStrategy::class, ProductionStrategy::class], true)
|| (($stack[0]['class'] ?? null) === Debugger::class && in_array($stack[0]['function'], ['shutdownHandler', 'errorHandler'], true))
)) {
array_shift($stack);
}
$expanded = null;
if (
!$ex instanceof \ErrorException
|| in_array($ex->getSeverity(), [E_USER_NOTICE, E_USER_WARNING, E_USER_DEPRECATED], true)
) {
$n = Helpers::countTransparentFrames([['file' => $ex->getFile(), 'line' => $ex->getLine()], ...$stack], [...$this->collapsePaths, ...Debugger::$transparentPaths]);
$expanded = $n > 0 && $n <= count($stack) ? $n - 1 : null;
}
return [$stack, $expanded];
}
/**
* @return \Closure(mixed, int|string): string
* @internal
*/
public function getDumper(): \Closure
{
return fn($v, $k = null): string => Dumper::toHtml($v, [
Dumper::DEPTH => $this->maxDepth,
Dumper::TRUNCATE => $this->maxLength,
Dumper::ITEMS => $this->maxItems,
Dumper::SNAPSHOT => &$this->snapshot,
Dumper::LOCATION => Dumper::LOCATION_CLASS,
Dumper::SCRUBBER => $this->scrubber,
Dumper::KEYS_TO_HIDE => $this->keysToHide,
], $k);
}
/** @return \Closure(mixed, int|string): string */
public function getAgentDumper(): \Closure
{
return fn($v, $k = null): string => Dumper::toText($v, [
Dumper::DEPTH => 3,
Dumper::TRUNCATE => $this->maxLength,
Dumper::ITEMS => $this->maxItems,
Dumper::SCRUBBER => $this->scrubber,
Dumper::KEYS_TO_HIDE => $this->keysToHide,
], $k);
}
public function formatMessage(\Throwable $exception): string
{
$msg = Helpers::encodeString(trim((string) $exception->getMessage()), self::MaxMessageLength, showWhitespaces: false);
// highlight 'string'
$msg = preg_replace(
'#\'\S(?:[^\']|\\\\\')*\S\'|"\S(?:[^"]|\\\")*\S"#',
'<i>$0</i>',
$msg,
);
// clickable class & methods
$msg = preg_replace_callback(
'#(\w+\\\[\w\\\]+\w)(?:::(\w+))?#',
function ($m) {
if (isset($m[2]) && method_exists($m[1], $m[2])) {
$r = new \ReflectionMethod($m[1], $m[2]);
} elseif (class_exists($m[1], autoload: false) || interface_exists($m[1], autoload: false)) {
$r = new \ReflectionClass($m[1]);
}
if (empty($r) || !$r->getFileName()) {
return $m[0];
}
return '<a href="' . Helpers::escapeHtml(Helpers::editorUri($r->getFileName(), $r->getStartLine() ?: null)) . '" class="tracy-editor">' . $m[0] . '</a>';
},
$msg,
);
// clickable file name
$msg = preg_replace_callback(
'#([\w\\\/.:-]+\.(?:php|phpt|phtml|latte|neon))(?|:(\d+)| on line (\d+))?#',
fn($m) => @is_file($m[1]) // @ - may trigger error
? '<a href="' . Helpers::escapeHtml(Helpers::editorUri($m[1], isset($m[2]) ? (int) $m[2] : null)) . '" class="tracy-editor">' . $m[0] . '</a>'
: $m[0],
$msg,
);
return $msg;
}
private function renderPhpInfo(): void
{
ob_start();
@phpinfo(INFO_LICENSE); // @ phpinfo may be disabled
$license = ob_get_clean();
ob_start();
@phpinfo(INFO_CONFIGURATION | INFO_MODULES); // @ phpinfo may be disabled
$info = ob_get_clean();
if (!str_contains($license, '<body')) {
echo '<pre class="tracy-dump tracy-light">', Helpers::escapeHtml($info), '</pre>';
} else {
$info = str_replace('<table', '<table class="tracy-sortable"', $info);
echo preg_replace('#^.+<body>|</body>.+\z|<hr />|<h1>Configuration</h1>#s', '', $info);
}
}
/** @return array{string, int} */
private function generateNewFileContents(string $file, ?string $class = null): array
{
foreach (array_reverse($this->fileGenerators) as $generator) {
$content = $generator($file, $class);
if ($content !== null) {
$line = 1;
$pos = strpos($content, '$END$');
if ($pos !== false) {
$content = substr_replace($content, '', $pos, 5);
$line = substr_count($content, "\n", 0, $pos) + 1;
}
return [$content, $line];
}
}
return ['', 1];
}
private static function generateNewPhpFileContents(string $file, ?string $class = null): ?string
{
if (!str_ends_with($file, '.php')) {
return null;
}
$res = "<?php\n\ndeclare(strict_types=1);\n\n";
if (!$class) {
return $res . '$END$';
}
if ($pos = strrpos($class, '\\')) {
$res .= 'namespace ' . substr($class, 0, $pos) . ";\n\n";
$class = substr($class, $pos + 1);
}
return $res . "class $class\n{\n\$END\$\n}\n";
}
/** @return array{array<int, \Generator>, array<int, \Fiber>} */
private function findGeneratorsAndFibers(object $object): array
{
$generators = $fibers = [];
$add = function ($obj) use (&$generators, &$fibers) {
if ($obj instanceof \Generator) {
try {
$ref = new \ReflectionGenerator($obj);
// Before PHP 8.4 the ReflectionGenerator cannot be constructed from closed generator.
// Since PHP 8.4 it can, but getTrace throws ReflectionException.
if (PHP_VERSION_ID >= 80400 && $ref->isClosed()) {
return;
}
$generators[spl_object_id($obj)] = $obj;
} catch (\ReflectionException) {
}
} elseif ($obj instanceof \Fiber && $obj->isStarted() && !$obj->isTerminated()) {
$fibers[spl_object_id($obj)] = $obj;
}
};
foreach ($this->fibers as $k => $v) {
$add($k);
}
Helpers::traverseValue($object, $add);
return [$generators, $fibers];
}
}