-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
debug.php
678 lines (580 loc) · 15.8 KB
/
debug.php
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
<?php
/**
* @package Joomla.Plugin
* @subpackage System.Debug
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
use DebugBar\DataCollector\MemoryCollector;
use DebugBar\DataCollector\MessagesCollector;
use DebugBar\DataCollector\RequestDataCollector;
use DebugBar\DebugBar;
use DebugBar\OpenHandler;
use Joomla\CMS\Application\CMSApplicationInterface;
use Joomla\CMS\Document\HtmlDocument;
use Joomla\CMS\Log\Log;
use Joomla\CMS\Log\LogEntry;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;
use Joomla\Database\DatabaseDriver;
use Joomla\Database\Event\ConnectionEvent;
use Joomla\Event\DispatcherInterface;
use Joomla\Plugin\System\Debug\DataCollector\InfoCollector;
use Joomla\Plugin\System\Debug\DataCollector\LanguageErrorsCollector;
use Joomla\Plugin\System\Debug\DataCollector\LanguageFilesCollector;
use Joomla\Plugin\System\Debug\DataCollector\LanguageStringsCollector;
use Joomla\Plugin\System\Debug\DataCollector\ProfileCollector;
use Joomla\Plugin\System\Debug\DataCollector\QueryCollector;
use Joomla\Plugin\System\Debug\DataCollector\SessionCollector;
use Joomla\Plugin\System\Debug\JavascriptRenderer;
use Joomla\Plugin\System\Debug\Storage\FileStorage;
/**
* Joomla! Debug plugin.
*
* @since 1.5
*/
class PlgSystemDebug extends CMSPlugin
{
/**
* True if debug lang is on.
*
* @var boolean
* @since 3.0
*/
private $debugLang = false;
/**
* Holds log entries handled by the plugin.
*
* @var LogEntry[]
* @since 3.1
*/
private $logEntries = [];
/**
* Holds SHOW PROFILES of queries.
*
* @var array
* @since 3.1.2
*/
private $sqlShowProfiles = [];
/**
* Holds all SHOW PROFILE FOR QUERY n, indexed by n-1.
*
* @var array
* @since 3.1.2
*/
private $sqlShowProfileEach = [];
/**
* Holds all EXPLAIN EXTENDED for all queries.
*
* @var array
* @since 3.1.2
*/
private $explains = [];
/**
* Holds total amount of executed queries.
*
* @var int
* @since 3.2
*/
private $totalQueries = 0;
/**
* Application object.
*
* @var CMSApplicationInterface
* @since 3.3
*/
protected $app;
/**
* Database object.
*
* @var DatabaseDriver
* @since 3.8.0
*/
protected $db;
/**
* @var DebugBar
* @since 4.0.0
*/
private $debugBar;
/**
* The query monitor.
*
* @var \Joomla\Database\Monitor\DebugMonitor
* @since 4.0.0
*/
private $queryMonitor;
/**
* AJAX marker
*
* @var bool
* @since 4.0.0
*/
protected $isAjax = false;
/**
* Constructor.
*
* @param DispatcherInterface &$subject The object to observe.
* @param array $config An optional associative array of configuration settings.
*
* @since 1.5
*/
public function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
$this->debugLang = $this->app->get('debug_lang');
// Skip the plugin if debug is off
if (!$this->debugLang && !$this->app->get('debug'))
{
return;
}
$this->app->getConfig()->set('gzip', false);
ob_start();
ob_implicit_flush(false);
/** @var \Joomla\Database\Monitor\DebugMonitor */
$this->queryMonitor = $this->db->getMonitor();
if (!$this->params->get('queries', 1))
{
// Remove the database driver monitor
$this->db->setMonitor(null);
}
$storagePath = JPATH_CACHE . '/plg_system_debug_' . $this->app->getName();
$this->debugBar = new DebugBar;
$this->debugBar->setStorage(new FileStorage($storagePath));
$this->isAjax = $this->app->input->get('option') === 'com_ajax'
&& $this->app->input->get('plugin') === 'debug' && $this->app->input->get('group') === 'system';
$this->setupLogging();
}
/**
* Add the CSS for debug.
* We can't do this in the constructor because stuff breaks.
*
* @return void
*
* @since 2.5
*/
public function onAfterDispatch()
{
// Only if debugging or language debug is enabled.
if ((JDEBUG || $this->debugLang) && $this->isAuthorisedDisplayDebug() && $this->app->getDocument() instanceof HtmlDocument)
{
// Use our own jQuery and fontawesome instead of the debug bar shipped version
$assetManager = $this->app->getDocument()->getWebAssetManager();
$assetManager->registerAndUseStyle(
'plg.system.debug',
'plg_system_debug/debug.css',
[],
[],
['fontawesome']
);
$assetManager->registerAndUseScript(
'plg.system.debug',
'plg_system_debug/debug.min.js',
[],
['defer' => true],
['jquery']
);
}
// Disable asset media version if needed.
if (JDEBUG && (int) $this->params->get('refresh_assets', 1) === 0)
{
$this->app->getDocument()->setMediaVersion(null);
}
}
/**
* Show the debug info.
*
* @return void
*
* @since 1.6
*/
public function onAfterRespond()
{
// Do not render if debugging or language debug is not enabled.
if (!JDEBUG && !$this->debugLang || $this->isAjax || !($this->app->getDocument() instanceof HtmlDocument))
{
return;
}
// User has to be authorised to see the debug information.
if (!$this->isAuthorisedDisplayDebug())
{
return;
}
// Load language.
$this->loadLanguage();
$this->debugBar->addCollector(new InfoCollector($this->params, $this->debugBar->getCurrentRequestId()));
if (JDEBUG)
{
if ($this->params->get('memory', 1))
{
$this->debugBar->addCollector(new MemoryCollector);
}
if ($this->params->get('request', 1))
{
$this->debugBar->addCollector(new RequestDataCollector);
}
if ($this->params->get('session', 1))
{
$this->debugBar->addCollector(new SessionCollector($this->params));
}
if ($this->params->get('profile', 1))
{
$this->debugBar->addCollector(new ProfileCollector($this->params));
}
if ($this->params->get('queries', 1))
{
// Call $db->disconnect() here to trigger the onAfterDisconnect() method here in this class!
$this->db->disconnect();
$this->debugBar->addCollector(new QueryCollector($this->params, $this->queryMonitor, $this->sqlShowProfileEach, $this->explains));
}
if (!empty($this->logEntries) && $this->params->get('logs', 1))
{
$this->collectLogs();
}
}
if ($this->debugLang)
{
$this->debugBar->addCollector(new LanguageFilesCollector($this->params));
$this->debugBar->addCollector(new LanguageStringsCollector($this->params));
$this->debugBar->addCollector(new LanguageErrorsCollector($this->params));
}
// Only render for HTML output.
if (!($this->app->getDocument() instanceof HtmlDocument))
{
$this->debugBar->stackData();
return;
}
$debugBarRenderer = new JavascriptRenderer($this->debugBar, Uri::root(true) . '/media/vendor/debugbar/');
$openHandlerUrl = Uri::base(true) . '/index.php?option=com_ajax&plugin=debug&group=system&format=raw&action=openhandler';
$openHandlerUrl .= '&' . Session::getFormToken() . '=1';
$debugBarRenderer->setOpenHandlerUrl($openHandlerUrl);
/**
* @todo disable highlightjs from the DebugBar, import it through NPM
* and deliver it through Joomla's API
* Also every DebugBar script and stylesheet needs to use Joomla's API
* $debugBarRenderer->disableVendor('highlightjs');
*/
// Capture output.
$contents = ob_get_contents();
if ($contents)
{
ob_end_clean();
}
// No debug for Safari and Chrome redirection.
if (strpos($contents, '<html><head><meta http-equiv="refresh" content="0;') === 0
&& strpos(strtolower($_SERVER['HTTP_USER_AGENT'] ?? ''), 'webkit') !== false)
{
$this->debugBar->stackData();
echo $contents;
return;
}
echo str_replace('</body>', $debugBarRenderer->renderHead() . $debugBarRenderer->render() . '</body>', $contents);
}
/**
* AJAX handler
*
* @return string
*
* @since 4.0.0
*/
public function onAjaxDebug()
{
// Do not render if debugging or language debug is not enabled.
if (!JDEBUG && !$this->debugLang)
{
return '';
}
// User has to be authorised to see the debug information.
if (!$this->isAuthorisedDisplayDebug() || !Session::checkToken('request'))
{
return '';
}
switch ($this->app->input->get('action'))
{
case 'openhandler':
$handler = new OpenHandler($this->debugBar);
return $handler->handle($this->app->input->request->getArray(), false, false);
default:
return '';
}
}
/**
* Setup logging functionality.
*
* @return $this
*
* @since 4.0.0
*/
private function setupLogging(): self
{
// Log the deprecated API.
if ($this->params->get('log-deprecated'))
{
Log::addLogger(['text_file' => 'deprecated.php'], Log::ALL, ['deprecated']);
}
// Log everything (except deprecated APIs, these are logged separately with the option above).
if ($this->params->get('log-everything', 0))
{
Log::addLogger(['text_file' => 'everything.php'], Log::ALL, ['deprecated', 'databasequery'], true);
}
if ($this->params->get('logs', 1))
{
$priority = 0;
foreach ($this->params->get('log_priorities', []) as $p)
{
$const = '\\Joomla\\CMS\\Log\\Log::' . strtoupper($p);
if (defined($const))
{
$priority |= constant($const);
}
}
// Split into an array at any character other than alphabet, numbers, _, ., or -
$categories = preg_split('/[^\w.-]+/', $this->params->get('log_categories', ''), -1, PREG_SPLIT_NO_EMPTY);
$mode = $this->params->get('log_category_mode', 0);
Log::addLogger(['logger' => 'callback', 'callback' => [$this, 'logger']], $priority, $categories, $mode);
}
// Log deprecated class aliases
foreach (JLoader::getDeprecatedAliases() as $deprecation)
{
Log::add(
sprintf(
'%1$s has been aliased to %2$s and the former class name is deprecated. The alias will be removed in %3$s.',
$deprecation['old'],
$deprecation['new'],
$deprecation['version']
),
Log::WARNING,
'deprecation-notes'
);
}
return $this;
}
/**
* Method to check if the current user is allowed to see the debug information or not.
*
* @return boolean True if access is allowed.
*
* @since 3.0
*/
private function isAuthorisedDisplayDebug(): bool
{
static $result = null;
if ($result !== null)
{
return $result;
}
// If the user is not allowed to view the output then end here.
$filterGroups = (array) $this->params->get('filter_groups', []);
if (!empty($filterGroups))
{
$userGroups = $this->app->getIdentity()->get('groups');
if (!array_intersect($filterGroups, $userGroups))
{
$result = false;
return false;
}
}
$result = true;
return true;
}
/**
* Disconnect handler for database to collect profiling and explain information.
*
* @param ConnectionEvent $event Event object
*
* @return void
*
* @since 4.0.0
*/
public function onAfterDisconnect(ConnectionEvent $event)
{
if (!JDEBUG)
{
return;
}
$db = $event->getDriver();
// Remove the monitor to avoid monitoring the following queries
$db->setMonitor(null);
$this->totalQueries = $db->getCount();
if ($this->params->get('query_profiles') && $db->getServerType() === 'mysql')
{
try
{
// Check if profiling is enabled.
$db->setQuery("SHOW VARIABLES LIKE 'have_profiling'");
$hasProfiling = $db->loadResult();
if ($hasProfiling)
{
// Run a SHOW PROFILE query.
$db->setQuery('SHOW PROFILES');
$this->sqlShowProfiles = $db->loadAssocList();
if ($this->sqlShowProfiles)
{
foreach ($this->sqlShowProfiles as $qn)
{
// Run SHOW PROFILE FOR QUERY for each query where a profile is available (max 100).
$db->setQuery('SHOW PROFILE FOR QUERY ' . (int) $qn['Query_ID']);
$this->sqlShowProfileEach[(int) ($qn['Query_ID'] - 1)] = $db->loadAssocList();
}
}
}
else
{
$this->sqlShowProfileEach[0] = [['Error' => 'MySql have_profiling = off']];
}
}
catch (Exception $e)
{
$this->sqlShowProfileEach[0] = [['Error' => $e->getMessage()]];
}
}
if ($this->params->get('query_explains') && in_array($db->getServerType(), ['mysql', 'postgresql'], true))
{
$logs = $this->queryMonitor->getLogs();
$boundParams = $this->queryMonitor->getBoundParams();
foreach ($logs as $k => $query)
{
$dbVersion56 = $db->getServerType() === 'mysql' && version_compare($db->getVersion(), '5.6', '>=');
$dbVersion80 = $db->getServerType() === 'mysql' && version_compare($db->getVersion(), '8.0', '>=');
if ($dbVersion80)
{
$dbVersion56 = false;
}
if ((stripos($query, 'select') === 0) || ($dbVersion56 && ((stripos($query, 'delete') === 0) || (stripos($query, 'update') === 0))))
{
try
{
$queryInstance = $db->getQuery(true);
$queryInstance->setQuery('EXPLAIN ' . ($dbVersion56 ? 'EXTENDED ' : '') . $query);
if ($boundParams[$k])
{
foreach ($boundParams[$k] as $key => $obj)
{
$queryInstance->bind($key, $obj->value, $obj->dataType, $obj->length, $obj->driverOptions);
}
}
$this->explains[$k] = $db->setQuery($queryInstance)->loadAssocList();
}
catch (Exception $e)
{
$this->explains[$k] = [['error' => $e->getMessage()]];
}
}
}
}
}
/**
* Store log messages so they can be displayed later.
* This function is passed log entries by JLogLoggerCallback.
*
* @param LogEntry $entry A log entry.
*
* @return void
*
* @since 3.1
*/
public function logger(LogEntry $entry)
{
$this->logEntries[] = $entry;
}
/**
* Collect log messages.
*
* @return $this
*
* @since 4.0.0
*/
private function collectLogs(): self
{
if (!$this->logEntries)
{
return $this;
}
$logDeprecated = $this->params->get('log-deprecated', 0);
$logDeprecatedCore = $this->params->get('log-deprecated-core', 0);
$this->debugBar->addCollector(new MessagesCollector('log'));
if ($logDeprecated)
{
$this->debugBar->addCollector(new MessagesCollector('deprecated'));
$this->debugBar->addCollector(new MessagesCollector('deprecation-notes'));
}
if ($logDeprecatedCore)
{
$this->debugBar->addCollector(new MessagesCollector('deprecated-core'));
}
foreach ($this->logEntries as $entry)
{
switch ($entry->category)
{
case 'deprecation-notes':
if ($logDeprecated)
{
$this->debugBar[$entry->category]->addMessage($entry->message);
}
break;
case 'deprecated':
if (!$logDeprecated && !$logDeprecatedCore)
{
break;
}
$file = $entry->callStack[2]['file'] ?? '';
$line = $entry->callStack[2]['line'] ?? '';
if (!$file)
{
// In case trigger_error is used
$file = $entry->callStack[4]['file'] ?? '';
$line = $entry->callStack[4]['line'] ?? '';
}
$category = $entry->category;
$relative = str_replace(JPATH_ROOT, '', $file);
if (0 === strpos($relative, '/libraries/src'))
{
if (!$logDeprecatedCore)
{
break;
}
$category .= '-core';
}
elseif (!$logDeprecated)
{
break;
}
$message = [
'message' => $entry->message,
'caller' => $file . ':' . $line,
// @todo 'stack' => $entry->callStack;
];
$this->debugBar[$category]->addMessage($message, 'warning');
break;
case 'databasequery':
// Should be collected by its own collector
break;
default:
switch ($entry->priority)
{
case Log::EMERGENCY:
case Log::ALERT:
case Log::CRITICAL:
case Log::ERROR:
$level = 'error';
break;
case Log::WARNING:
$level = 'warning';
break;
case Log::NOTICE:
case Log::INFO:
case Log::DEBUG:
$level = 'info';
break;
default:
$level = 'info';
}
$this->debugBar['log']->addMessage($entry->category . ' - ' . $entry->message, $level);
break;
}
}
return $this;
}
}