-
Notifications
You must be signed in to change notification settings - Fork 13
/
TracyDebugger.module.php
4832 lines (4246 loc) · 240 KB
/
TracyDebugger.module.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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Processwire module for running the Tracy debugger from Nette.
* by Adrian Jones
*
* Copyright (C) 2024 by Adrian Jones
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* A big thanks to Roland Toth (https://github.com/rolandtoth/) for the idea for this module
* and for significant feedback, testing, and feature suggestions.
*
*/
use Tracy\Debugger;
use Tracy\Helpers;
use Tracy\Dumper;
class TracyDebugger extends WireData implements Module, ConfigurableModule {
/**
* Basic information about module
*/
public static function getModuleInfo() {
return array(
'title' => __('Tracy Debugger', __FILE__),
'summary' => __('Tracy debugger from Nette with many PW specific custom tools.', __FILE__),
'author' => 'Adrian Jones',
'href' => 'https://processwire.com/talk/forum/58-tracy-debugger/',
'version' => '4.26.46',
'autoload' => 100000, // in PW 3.0.114+ higher numbers are loaded first - we want Tracy first
'singular' => true,
'requires' => 'ProcessWire>=2.7.2, PHP>=5.4.4',
'installs' => array('ProcessTracyAdminer'),
'icon' => 'bug',
);
}
const COOKIE_SECRET = 'tracy-debug';
const COLOR_LIGHTGREY = '#999999';
const COLOR_GREEN = '#009900';
const COLOR_NORMAL = '#354B60';
const COLOR_WARN = '#ff8309';
const COLOR_ALERT = '#cd1818';
protected $data = array();
protected $time;
protected $httpReferer;
protected $tracyEnabled = false;
protected $earlyExit = false;
protected $tracyCacheDir;
protected $modulesDbBackupFilename;
protected $serverStyleInfo;
protected static $useOnlineEditor;
protected static $onlineEditor;
protected static $onlineFileEditorDirPath;
public static $inAdmin;
public static $isLocal = false;
public static $allowedSuperuser = false;
public static $allowedTracyUser = false;
public static $validSwitchedUser = false;
public static $validLocalUser = false;
public static $dumpItems = array();
public static $autocompleteArr = array();
public static $allApiData = array();
public static $allApiClassesArr = array();
public static $apiChanges = array();
public static $pageFinderQueries = array();
public static $templateVars = array();
public static $templateConsts = array();
public static $initialFuncs = array();
public static $initialConsts = array();
public static $templateFuncs = array();
public static $includedFiles = array();
public static $fromConsole = false;
public static $oncePanels;
public static $stickyPanels;
public static $showPanels;
public static $disabableModules = array();
public static $restrictedUserDisabledPanels = array();
public static $disabledModules = array();
public static $templatePath;
public static $pageVersion;
public static $templatePathOnce;
public static $templatePathSticky;
public static $templatePathPermission;
public static $tempTemplateFilename;
public static $tracyVersion;
public static $panelGenerationTime = array();
public static $hideInAdmin = array('validator', 'templateResources', 'templatePath');
public static $superUserOnlyPanels = array('console', 'fileEditor', 'adminer', 'terminal', 'adminTools');
public static $pageHtml;
public static $redirectInfo;
public static $processWireInfoSections = array(
'configData' => 'Config Data',
'versionsList' => 'Versions List',
'adminLinks' => 'Admin Links',
'documentationLinks' => 'Documentation Links',
'gotoId' => 'Goto Page By ID',
'processWireWebsiteSearch' => 'ProcessWire Website Search'
);
public static $requestInfoSections = array(
'moduleSettings' => 'Module Settings',
'templateSettings' => 'Template Settings',
'fieldSettings' => 'Field Settings',
'inputFieldSettings' => 'Inputfield Settings',
'fieldCode' => 'Field Code',
'fieldExportCode' => 'Field Export Code',
'pageInfo' => 'Page Info',
'redirectInfo' => 'Redirect Info',
'pagePermissions' => 'Page Permissions',
'languageInfo' => 'Language Info',
'templateInfo' => 'Template Info',
'templateCode' => 'Template Code',
'templateExportCode' => 'Template Export Code',
'pageMeta' => 'Page Meta',
'fieldsListValues' => 'Field List & Values',
'serverRequest' => 'Server Request',
'inputGet' => 'Input GET',
'inputPost' => 'Input POST',
'inputCookie' => 'Input COOKIE',
'session' => 'SESSION',
'pageObject' => 'Page Object',
'templateObject' => 'Template Object',
'fieldsObject' => 'Fields Object',
'editLinks' => 'Page/Template Edit Links'
);
public static $debugModeSections = array(
'pagesLoaded' => 'Pages Loaded',
'modulesLoaded' => 'Modules Loaded',
'hooks' => 'Hooks Triggered',
'databaseQueries' => 'Database Queries',
'selectorQueries' => 'Selector Queries',
'timers' => 'Timers',
'user' => 'User',
'cache' => 'Cache',
'autoload' => 'Autoload'
);
public static $diagnosticsSections = array(
'filesystemFolders' => 'Filesystem Folders',
'filesystemFiles' => 'Filesystem Files',
'mysqlInfo' => 'MySQL Info'
);
public static $dumpPanelTabs = array(
'debugInfo' => 'Debug Info',
'iterator' => 'Iterator',
'fullObject' => 'Full Object'
);
public static $externalPanels = array();
public static $allPanels = array(
'adminTools' => 'Admin Tools',
'adminer' => 'Adminer',
'apiExplorer' => 'API Explorer',
'captainHook' => 'Captain Hook',
'console' => 'Console',
'customPhp' => 'Custom PHP',
'debugMode' => 'Debug Mode',
'diagnostics' => 'Diagnostics',
'dumpsRecorder' => 'Dumps Recorder',
'eventInterceptor' => 'Event Interceptor',
'fileEditor' => 'File Editor',
'gitInfo' => 'Git Info',
'helloWorld' => 'Hello World',
'languageSwitcher' => 'Language Switcher',
'links' => 'Links',
'mailInterceptor' => 'Mail Interceptor',
'methodsInfo' => 'Methods Info',
'moduleDisabler' => 'Module Disabler',
'outputMode' => 'Output Mode',
'pageFiles' => 'Page Files',
'pageRecorder' => 'Page Recorder',
'panelSelector' => 'Panel Selector',
'performance' => 'Performance',
'phpInfo' => 'PHP Info',
'processwireInfo' => 'ProcessWire Info',
'processwireLogs' => 'ProcessWire Logs',
'processwireVersion' => 'ProcessWire Version',
'requestInfo' => 'Request Info',
'requestLogger' => 'Request Logger',
'terminal' => 'Terminal',
'templatePath' => 'Template Path',
'templateResources' => 'Template Resources',
'todo' => 'ToDo',
'tracyExceptions' => 'Tracy Exceptions',
'tracyToggler' => 'Tracy Toggler',
'tracyLogs' => 'Tracy Logs',
'userSwitcher' => 'User Switcher',
'users' => 'Users',
'validator' => 'Validator',
'viewports' => 'Viewports'
);
public static $userBarFeatures = array(
'admin' => 'Admin',
'editPage' => 'Edit Page',
'pageVersions' => 'Page Versions'
);
/**
* Default configuration for module
*
*/
static public function getDefaultData() {
return array(
"enabled" => 1,
"use_php_session" => 0,
"superuserForceDevelopment" => null,
"guestForceDevelopmentLocal" => null,
"forceIsLocal" => false,
"recordGuestDumps" => false,
"ipAddress" => null,
"restrictSuperusers" => null,
"strictMode" => null,
"strictModeAjax" => null,
"forceScream" => null,
"outputMode" => 'detect',
"showLocation" => array('Tracy\Dumper::LOCATION_SOURCE', 'Tracy\Dumper::LOCATION_LINK', 'Tracy\Dumper::LOCATION_CLASS'),
"logSeverity" => array(),
"excludedPwLogFiles" => array('session', 'modules', 'file-compiler'),
"excludedTracyLogFiles" => array(),
"numLogEntries" => 10,
"collapse" => 14,
"collapse_count" => 7,
"maxDepth" => 3,
"maxLength" => 150,
"maxItems" => 100,
"maxAjaxRows" => 3,
"showDebugBar" => array('frontend', 'backend'),
"hideDebugBar" => null,
"hideDebugBarFrontendTemplates" => array(),
"hideDebugBarBackendTemplates" => array(),
"hideDebugBarModals" => array(),
"frontendPanels" => array('processwireInfo', 'requestInfo', 'processwireLogs', 'tracyLogs', 'tracyExceptions', 'methodsInfo', 'debugMode', 'console', 'panelSelector', 'tracyToggler'),
"backendPanels" => array('processwireInfo', 'requestInfo', 'processwireLogs', 'tracyLogs', 'tracyExceptions', 'methodsInfo', 'debugMode', 'console', 'panelSelector', 'tracyToggler'),
"restrictedUserDisabledPanels" => array(),
"nonToggleablePanels" => array(),
"panelSelectorTracyTogglerButton" => 1,
"showUserBar" => null,
"showUserBarTracyUsers" => null,
"userBarFeatures" => array('admin', 'editPage'),
"userBarCustomFeatures" => '',
"userBarBackgroundColor" => '',
"userBarBackgroundOpacity" => 1,
"userBarIconColor" => '#666666',
"userBarTopBottom" => 'bottom',
"userBarLeftRight" => 'left',
"showPanelLabels" => null,
"barPosition" => 'bottom-right',
"panelZindex" => 100,
"styleWhere" => array('backend', 'frontend'),
"styleAdminElements" => "body::before {\n\tcontent: \"[type]\";\n\tbackground: [color];\n\tposition: fixed;\n\tleft: 0;\n\tbottom: 100%;\n\tcolor: #ffffff;\n\twidth: 100vh;\n\tpadding: 0;\n\ttext-align: center;\n\tfont-weight: 600;\n\ttext-transform: uppercase;\n\ttransform: rotate(90deg);\n\ttransform-origin: bottom left;\n\tz-index: 999999;\n\tfont-family: sans-serif;\n\tfont-size: 11px;\n\theight: 13px;\n\tline-height: 13px;\npointer-events: none;\n}\n",
"styleAdminColors" => "\nlocal|#FF9933\n*.local|#FF9933\ndev.*|#FF9933\n*.test|#FF9933\nstaging.*|#8b0066\n*.com|#009900",
"styleAdminType" => array('favicon'),
"showPWInfoPanelIconLabels" => 1,
"linksNewTab" => null,
"pWInfoPanelLinksNewTab" => null,
"customPWInfoPanelLinks" => array(11, 16, 22, 21, 29, 30, 31, 304),
"adminerEditFieldLink" => 1,
"adminerStandAlone" => null,
"adminerThemeColor" => 'blue',
"adminerJsonMaxLevel" => 3,
"adminerJsonInTable" => 1,
"adminerJsonInEdit" => 1,
"adminerJsonMaxTextLength" => 200,
"captainHookShowDescription" => 1,
"captainHookToggleDocComment" => null,
"apiExplorerShowDescription" => 1,
"apiExplorerToggleDocComment" => null,
"apiExplorerModuleClasses" => array(),
"requestInfoPanelSections" => array('moduleSettings', 'templateSettings', 'fieldSettings', 'pageInfo', 'redirectInfo', 'pagePermissions', 'languageInfo', 'templateInfo', 'pageMeta', 'fieldsListValues', 'serverRequest', 'inputGet', 'inputPost', 'inputCookie', 'session', 'editLinks'),
"processwireInfoPanelSections" => array('versionsList', 'adminLinks', 'documentationLinks', 'gotoId', 'processWireWebsiteSearch'),
"debugModePanelSections" => array('pagesLoaded', 'modulesLoaded', 'hooks', 'databaseQueries', 'selectorQueries', 'timers', 'user', 'cache', 'autoload'),
"diagnosticsPanelSections" => array('filesystemFolders'),
"dumpPanelTabs" => array('debugInfo', 'fullObject'),
"requestMethods" => array('GET', 'POST', 'PUT', 'DELETE', 'PATCH'),
"requestLoggerMaxLogs" => 10,
"requestLoggerReturnType" => 'array',
"imagesInFieldListValues" => 0,
"snippetsPath" => 'templates',
"consoleBackupLimit" => 25,
"consoleCodePrefix" => '',
"userSwitcherSelector" => '',
"userSwitcherRestricted" => null,
"userSwitcherIncluded" => null,
"todoIgnoreDirs" => 'git, svn, images, img, errors, sass-cache, node_modules',
"todoScanAssets" => null,
"todoScanModules" => null,
"todoSpecifiedDirectories" => '',
"todoAllowedExtensions" => 'php, module, inc, txt, latte, html, htm, md, css, scss, less, js',
"variablesShowPwObjects" => null,
"alwaysShowDebugTools" => 1,
"respectConfigDebugTools" => null,
"userDevTemplate" => null,
"userDevTemplateSuffix" => 'dev',
"customPhpCode" => '',
"linksCode" => '',
"fromEmail" => '',
"email" => '',
"clearEmailSent" => null,
"slackChannel" => '',
"slackAppOauthToken" => '',
"showFireLogger" => 1,
"reservedMemorySize" => 500000,
"referencePageEdited" => 1,
"debugInfo" => 1,
"editor" => 'vscode://file/%file:%line',
"useOnlineEditor" => array(),
"onlineEditor" => 'tracy',
"forceEditorLinksToTracy" => 1,
"localRootPath" => '',
"aceTheme" => 'tomorrow_night_bright',
"codeFontSize" => 14,
"codeLineHeight" => 24,
"codeShowInvisibles" => true,
"codeTabSize" => 4,
"codeUseSoftTabs" => true,
"codeShowDescription" => 1,
"customSnippetsUrl" => '',
"pwAutocompletions" => 1,
"fileEditorAllowedExtensions" => 'php, module, js, css, txt, log, htaccess',
"fileEditorExcludedDirs" => 'site/assets',
"fileEditorBaseDirectory" => 'templates',
"enableShortcutMethods" => 1,
"enabledShortcutMethods" => array('addBreakpoint', 'bp', 'barDump', 'bd', 'barDumpBig', 'bdb', 'barEcho', 'be', 'debugAll', 'da', 'dump', 'd', 'dumpBig', 'db', 'l', 'templateVars', 'tv', 'timer', 't')
);
}
/**
* Populate the default config data
*
*/
public static $_data;
public function __construct() {
foreach(self::getDefaultData() as $key => $value) {
$this->$key = $value;
}
}
/**
* Initialize the module
*/
public function init() {
$this->time = $_SERVER['REQUEST_TIME_FLOAT'] ?? microtime(true);
if(class_exists('\Tracy\Debugger', false) && Debugger::isEnabled()) return;
// load Tracy files and our helper files
if(version_compare(PHP_VERSION, '8.0.0', '>=')) {
self::$tracyVersion = '2.10.x';
}
elseif(version_compare(PHP_VERSION, '7.2.0', '>=')) {
self::$tracyVersion = '2.9.x';
}
elseif(version_compare(PHP_VERSION, '7.1.0', '>=')) {
self::$tracyVersion = '2.7.x';
}
else {
self::$tracyVersion = '2.5.x';
}
require_once __DIR__ . '/tracy-'.self::$tracyVersion.'/src/tracy.php';
require_once __DIR__ . '/includes/TD.php';
// load any custom function files if includes dir exists
$functionsPath = 'templates/TracyDebugger/includes/';
if(file_exists($this->wire('config')->paths->site.$functionsPath)) {
$functionsFiles = new RecursiveDirectoryIterator($this->wire('config')->paths->site.$functionsPath, RecursiveDirectoryIterator::SKIP_DOTS);
foreach($functionsFiles as $functionFile) {
include_once $functionFile;
}
}
if($this->data['enableShortcutMethods']) {
require_once __DIR__ . '/includes/ShortcutMethods.php';
}
// load base panel class
require_once __DIR__ . '/includes/BasePanel.php';
$externalPanelPaths = glob($this->wire('config')->paths->root.'/site/modules/*/TracyPanels/*.php');
foreach($externalPanelPaths as $panelPath) {
$path_parts = pathinfo($panelPath);
$panelName = lcfirst($path_parts['filename']);
static::$externalPanels[$panelName] = $panelPath;
static::$allPanels[$panelName] = implode(' ', preg_split('/(?=[A-Z])/', $path_parts['filename']));
ksort(static::$allPanels);
}
// merge in settings from config.php file
if(isset($this->wire('config')->tracy) && is_array($this->wire('config')->tracy)) {
$this->data = array_merge($this->data, $this->wire('config')->tracy);
}
//populate for later static access to data
self::$_data = $this;
// determine if server is local dev or live
static::$isLocal = static::isLocal();
// url for $session->redirects
$this->httpReferer = isset($_SERVER['HTTP_REFERER']) ? $this->wire('sanitizer')->text($_SERVER['HTTP_REFERER']) : self::inputHttpUrl(true);
// determine if we are in the admin / backend
static::$inAdmin = $this->inAdmin();
// check if user is superuser and has tracy-debugger permission if required
if($this->data['restrictSuperusers'] && $this->wire('user')->isSuperuser()) {
static::$allowedSuperuser = self::userHasPermission('tracy-debugger');
}
else {
static::$allowedSuperuser = $this->wire('user')->isSuperuser();
}
// determine whether user is allowed to use Tracy and whether DEV or PRODUCTION
static::$allowedTracyUser = static::allowedTracyUser();
$this->tracyCacheDir = $this->wire('config')->paths->cache . 'TracyDebugger/';
if(!is_dir($this->tracyCacheDir)) {
if(!wireMkdir($this->tracyCacheDir)) {
throw new WireException("Unable to create cache path: " . $this->tracyCacheDir);
}
}
// REQUEST LOGGER
// add getRequestData() method to the $page object
// before Tracy enabled check in case this method is used in a template file
$this->wire()->addHook('Page::getRequestData', $this, 'getRequestData');
// EARLY EXITS
// modals
if(in_array('regularModal', $this->data['hideDebugBarModals']) && $this->wire('input')->get->modal == '1') $this->earlyExit = true;
if(in_array('inlineModal', $this->data['hideDebugBarModals']) && $this->wire('input')->get->modal == 'inline') $this->earlyExit = true;
if(in_array('overlayPanels', $this->data['hideDebugBarModals']) && $this->wire('input')->get->modal == 'panel') $this->earlyExit = true;
// formbuilder iframe
if(in_array('formBuilderIframe', $this->data['hideDebugBarModals']) &&
!static::$inAdmin &&
strpos(self::inputUrl(true), DIRECTORY_SEPARATOR.'form-builder'.DIRECTORY_SEPARATOR) !== false) {
$this->earlyExit = true;
}
// adminer iframe
if(strpos(self::inputUrl(true), 'adminer-renderer') !== false) $this->earlyExit = true;
// terminal iframe
if(strpos(self::inputUrl(true), 'terminal') !== false) $this->earlyExit = true;
// don't init Tracy for @soma's PageEditSoftLock polling on Page Edit
if(strpos(self::inputUrl(), 'checkpagelock') !== false) $this->earlyExit = true;
// don't init Tracy for PW ProDevTools ajax request - ATM I know this works for UserActivity module
if($this->wire('config')->input->pwpdt) $this->earlyExit = true;
// don't init Tracy for Pro Profiler ajax request
if(strpos(self::inputUrl(true), '?field=ProfilerEventsTable') !== false) $this->earlyExit = true;
if(isset($_SERVER['REQUEST_URI'])) {
$info = parse_url($_SERVER['REQUEST_URI']);
$queryString = isset($info['query']) ? $info['query'] : '';
// don't init Tracy for the PW Notifications module polling
if(strpos($queryString, 'Notifications=update') !== false) $this->earlyExit = true;
// don't init Tracy for sidenav iframes in admin themes that support this
if(strpos($queryString, 'layout=sidenav-side') !== false ||
strpos($queryString, 'layout=sidenav-tree') !== false ||
strpos($queryString, 'layout=sidenav-init') !== false) $this->earlyExit = true;
// don't init Tracy for Setup > Logs view polling
if(strpos($_SERVER['REQUEST_URI'], DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR) !== false &&
strpos($queryString, 'q=') !== false) $this->earlyExit = true;
}
// if "enabled" not checked or tracyDisabled via config or other early exit
if(!$this->data['enabled'] || $this->wire('config')->tracyDisabled || $this->earlyExit) {
return;
}
// include the Console panel's codeProcessor after ready so it has access to any properties/methods added by other modules
$this->wire()->addHookAfter('ProcessWire::ready', function($event) {
// if it's an ajax request from the Tracy Console panel for code execution, then process and return
if($this->wire('config')->ajax && $this->wire('input')->post->tracyConsole == 1) {
require_once(__DIR__ . '/includes/CodeProcessor.php');
return;
}
}, array('priority' => 9999));
// log requests for Request Logger
$this->wire()->addHookAfter('ProcessWire::ready', function($event) {
if(!method_exists($event->page, 'render')) {
$event->page->addHookAfter('render', $this, 'logRequests');
}
});
$this->wire()->addHookAfter('Page::logRequests', $this, 'logRequests');
// clear session & cookies option in Processwire Info panel
// not inside static::$allowedTracyUser === 'development' check because it won't validate during forceLogin()
if($this->wire('input')->get->tracyClearSession) {
$userName = $this->wire('user')->name;
$this->wire('session')->logout();
if(isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
$this->wire('session')->forceLogin($userName);
$this->wire('session')->tracyLastUrl = substr(str_replace('tracyClearSession=1', '', self::inputUrl(true)), 0, -1);
$this->wire('session')->redirect($this->wire('config')->urls->admin.'module/?reset=1');
}
// USER BAR
if(
$this->wire('user')->isLoggedin() &&
!static::$inAdmin &&
$this->data['showUserBar'] &&
count($this->data['userBarFeatures'])>0 &&
!$this->wire('config')->ajax &&
(static::$allowedTracyUser !== 'development' || $this->data['showUserBarTracyUsers']) &&
(strpos(self::inputUrl(true), DIRECTORY_SEPARATOR.'form-builder'.DIRECTORY_SEPARATOR) === false)
) {
$this->wire()->addHookAfter('ProcessWire::ready', function($event) {
if(!method_exists($event->page, 'render')) {
$event->page->addHookAfter('render', $this, 'addUserBar', array('priority'=>1000));
}
});
}
// Various features that can be run before loading Tracy core files
if(static::$allowedTracyUser === 'development') {
// PANELS TO DISPLAY
$configEnabledPanels = static::$inAdmin ? $this->data['backendPanels'] : $this->data['frontendPanels'];
// need to set $stickyPanels here so it is alway set if available, rather than in the elseif below
// because a "once" cookie would prevent if from being set
if($this->wire('input')->cookie->tracyPanelsSticky) {
static::$stickyPanels = array_filter(explode(',', $this->wire('input')->cookie->tracyPanelsSticky));
}
if($this->wire('input')->cookie->tracyPanelsOnce) {
static::$oncePanels = array_filter(explode(',', $this->wire('input')->cookie->tracyPanelsOnce));
static::$showPanels = static::$oncePanels;
unset($this->wire('input')->cookie->tracyPanelsOnce);
setcookie("tracyPanelsOnce", "", time()-3600, '/');
}
elseif($this->wire('input')->cookie->tracyPanelsSticky) {
static::$showPanels = static::$stickyPanels;
}
else {
static::$showPanels = $configEnabledPanels;
}
if(in_array('debugMode', static::$showPanels)) {
// selectors for Debug Mode panel
$this->wire()->addHookBefore('PageFinder::getQuery', null, function($event) {
$this->timerkey = Debug::timer();
});
$this->wire()->addHookAfter('PageFinder::getQuery', null, function($event) {
$event->setArgument(2, Debug::timer($this->timerkey));
if(method_exists('\ProcessWire\Debug', 'backtrace')) {
// add backtrace to allow tracking of caller
$trace_depth = 3;
$trace = Debug::backtrace();
// filter out expected admin sources...
$filtered_trace = array_filter($trace, function($v) {
return
(strpos($v['file'], '/wire/') !== 0) &&
(strpos($v['file'], '/site/assets/cache/') !== 0)
;
});
// if there are any paths left in the trace, prepare a shorthand listing...
if (!empty($filtered_trace)) {
$first_idx = array_keys($filtered_trace)[0];
$trace = array_slice($trace, $first_idx, $trace_depth);
$filtered_trace = array_reduce($filtered_trace, function($carry, $v) use (&$first_idx) {
$carry .= "\n[$first_idx] " . $v['file'] . ' ' . $v['call'];
$first_idx++;
return $carry;
}, '');
$event->backtrace = $filtered_trace;
}
else {
$event->backtrace = '';
}
}
static::$pageFinderQueries[] = $event;
});
}
// sort panels based on order defined in config settings
$showPanelsOrdered = array();
$i=0;
// add default panels in the defined order
foreach($configEnabledPanels as $panelName) {
if(in_array($panelName, static::$showPanels)) $showPanelsOrdered[$i] = $panelName;
$i++;
}
// add once/sticky panels to the end because there is no specified order for these in config settings
foreach(static::$allPanels as $panelName => $panelTitle) {
if(in_array($panelName, static::$showPanels) && !in_array($panelName, $showPanelsOrdered)) $showPanelsOrdered[$i] = $panelName;
// define disabled panels for restricted users
if((self::$validSwitchedUser || self::userHasPermission("tracy-restricted-panels") || $this->wire('user')->hasRole("tracy-restricted-panels")) && in_array($panelName, $this->data['restrictedUserDisabledPanels'])) {
static::$restrictedUserDisabledPanels[] = $panelName;
}
$i++;
}
// move Panel Selector to the end so it has access to the generation time values for all other panels
static::$showPanels = $showPanelsOrdered;
if(($key = array_search('panelSelector', static::$showPanels)) !== false) {
unset(static::$showPanels[$key]);
static::$showPanels[] = 'panelSelector';
}
// unhide and unlock all fields
if($this->wire('input')->cookie->tracyUnhideUnlockFields == 1) {
$this->wire()->addHookAfter('Field::getInputfield', function(HookEvent $event) {
if($this->page->process !== 'ProcessPageEdit' && $this->page->process !== 'ProcessUser') return;
$inputfield = $event->return;
if($inputfield->collapsed > 0) $inputfield->label .= ' (Unhidden / Uncollapsed / Unlocked by Tracy Debugger)';
$inputfield->collapsed = Inputfield::collapsedNo;
});
}
// ProcessWire Info panel early redirects
// logout
if($this->wire('input')->get->tracyLogout) {
$this->wire('session')->logout();
$this->wire('session')->redirect(rtrim(substr(str_replace(array('tracyLogout=1', 'login=1'), '', self::inputUrl(true)), 0, -1), '?'));
}
// login
if($this->wire('input')->get->tracyLogin) {
$this->wire('session')->tracyLoginUrl = $this->httpReferer;
}
if($this->wire('session')->tracyLoginUrl) {
$this->wire()->addHookAfter('Session::loginSuccess', function(HookEvent $event) {
$this->wire('session')->redirect($this->wire('session')->tracyLoginUrl);
});
}
// refresh modules
if($this->wire('input')->get->tracyModulesRefresh) {
$this->wire('session')->tracyLastUrl = substr(str_replace('tracyModulesRefresh=1', '', self::inputUrl(true)), 0, -1);
$this->wire('session')->redirect($this->wire('config')->urls->admin.'module/?reset=1');
}
if($this->wire('input')->get->reset == 2 && $this->wire('session')->tracyLastUrl) {
$tracyLastUrl = $this->wire('session')->tracyLastUrl;
$this->wire('session')->remove('tracyLastUrl');
$this->wire('session')->redirect($tracyLastUrl);
}
// PW VERSION SWITCHER
// if PW version changed, reload to initialize new version
// don't add in_array(static::$showPanels) check because that won't be true if enabled ONCE due to multiple redirects waiting for $this->wire('config')->version to update
if(($this->wire('input')->post->tracyPwVersion && $this->wire('input')->post->tracyPwVersion != $this->wire('config')->version) || $this->wire('session')->tracyPwVersion) {
$this->wire('session')->tracyPwVersion = $this->wire('session')->tracyPwVersion ?: $this->wire('input')->post->tracyPwVersion;
while($this->wire('session')->tracyPwVersion != $this->wire('config')->version) {
sleep(1);
$this->wire('session')->redirect($this->httpReferer);
}
$this->wire('session')->remove('tracyPwVersion');
}
// REQUEST LOGGER
// enable/disable page logging
if($this->wire('input')->post->tracyRequestLoggerEnableLogging || $this->wire('input')->post->tracyRequestLoggerDisableLogging) {
$configData = $this->wire('modules')->getModuleConfigData("TracyDebugger");
if($this->wire('input')->post->tracyRequestLoggerEnableLogging) {
if(!isset($configData['requestLoggerPages'])) $configData['requestLoggerPages'] = array();
array_push($configData['requestLoggerPages'], $this->wire('input')->post->requestLoggerLogPageId);
}
else {
if(($key = array_search($this->wire('input')->post->requestLoggerLogPageId, $configData['requestLoggerPages'])) !== false) {
unset($configData['requestLoggerPages'][$key]);
}
$data = $this->wire('cache')->get("tracyRequestLogger_id_*_page_".$this->wire('input')->post->requestLoggerLogPageId);
if(count($data) > 0) {
foreach($data as $id => $datum) {
$this->wire('cache')->delete($id);
}
}
}
$this->wire('modules')->saveModuleConfigData($this, $configData);
$this->wire('session')->redirect($this->httpReferer);
}
if($this->data['recordGuestDumps'] || $this->wire('input')->cookie->tracyGuestDumps) {
$configData = $this->wire('modules')->getModuleConfigData("TracyDebugger");
if($this->wire('input')->cookie->tracyGuestDumps) {
$configData['recordGuestDumps'] = $this->data['recordGuestDumps'] = 1;
}
else {
unset($configData['recordGuestDumps']);
}
$this->wire('modules')->saveModuleConfigData($this, $configData);
}
// MODULES DISABLER
//set up backup directory/file - outside conditional so they are available for cleanup when panel is disabled
$this->modulesDbBackupFilename = 'modulesBackup.sql';
if(in_array('moduleDisabler', static::$showPanels) && $this->wire('config')->debug && $this->wire('config')->advanced) {
// if modules DB was just restored, clear the cookie
if($this->wire('input')->cookie->modulesRestored == 1) {
unset($this->wire('input')->cookie->modulesRestored);
setcookie("modulesRestored", "", time()-3600, "/");
unset($this->wire('input')->cookie->tracyModulesDisabled);
setcookie("tracyModulesDisabled", "", time()-3600, "/");
$this->wire('session')->message("Modules successfully restored");
}
// get array of disabable modules
foreach($this->wire('modules') as $name => $label) {
$flags = $this->wire('modules')->getFlags($name);
$info = $this->wire('modules')->getModuleInfoVerbose($name);
if($info['core']) continue;
if($name == 'TracyDebugger') continue;
if(($flags & Modules::flagsAutoload) || ($flags & Modules::flagsDisabled)) {
static::$disabableModules[] = $name;
}
}
// if modules have been checked to disable
if($this->wire('input')->cookie->tracyModulesDisabled) {
// if it doesn't already exist, backup existing modules database
if(!file_exists($this->tracyCacheDir . $this->modulesDbBackupFilename)) {
$backup = new WireDatabaseBackup($this->tracyCacheDir);
$backup->setDatabase($this->wire('database'));
$backup->setDatabaseConfig($this->wire('config'));
$file = $backup->backup(array('tables' => array('modules'), 'filename' => $this->modulesDbBackupFilename));
$restoreModulesCode =
"<?php\n" .
"if(file_exists('".$this->tracyCacheDir.$this->modulesDbBackupFilename."')) {\n" .
"\t\$db = new PDO('mysql:host={$this->wire('config')->dbHost};dbname={$this->wire('config')->dbName}', '{$this->wire('config')->dbUser}', '{$this->wire('config')->dbPass}');\n" .
"\t\$sql = file_get_contents('" . $this->tracyCacheDir . $this->modulesDbBackupFilename . "');\n" .
"\t\$qr = \$db->query(\$sql);\n" .
"}\n" .
"if(isset(\$qr) && \$qr) {\n" .
"\tsetcookie('modulesRestored', 1, time() + (24 * 60 * 60));\n" .
"\theader('Location: ".self::inputHttpUrl(true)."');\n" .
"}\n" .
"else {\n" .
"\techo 'Sorry, there was a problem and the database could not be restored.';\n" .
"}";
if(!$this->wire('files')->filePutContents($this->tracyCacheDir . 'restoremodules.php', $restoreModulesCode, LOCK_EX)) {
throw new WireException("Unable to write file: " . $this->tracyCacheDir . 'restoremodules.php');
}
}
// get array of modules that have been checked to disable
static::$disabledModules = array_filter(explode(',', $this->wire('input')->cookie->tracyModulesDisabled));
}
else {
$this->deleteFile($this->tracyCacheDir . $this->modulesDbBackupFilename);
$this->deleteFile($this->tracyCacheDir . 'restoremodules.php');
}
// add disabled flag to requested modules
$i=0;
foreach(static::$disabableModules as $name) {
$flags = $this->wire('modules')->getFlags($name);
if(in_array($name, static::$disabledModules)) {
if(!($flags & Modules::flagsDisabled)) {
$this->wire('modules')->setFlag($name, Modules::flagsDisabled, true);
$i++;
}
}
elseif($flags & Modules::flagsDisabled) {
$this->wire('modules')->setFlag($name, Modules::flagsDisabled, false);
$i++;
}
}
if($i > 0) $this->wire('session')->redirect($this->httpReferer);
}
else {
$this->deleteFile($this->tracyCacheDir . $this->modulesDbBackupFilename);
$this->deleteFile($this->tracyCacheDir . 'restoremodules.php');
}
// try to delete modules restore file from root
$rootRestoreFile = $this->wire('config')->paths->root . 'restoremodules.php';
if(file_exists($rootRestoreFile)) {
@unlink($rootRestoreFile);
if(is_file($rootRestoreFile)) {
$this->wire('session')->error('Please delete ' . $rootRestoreFile . ' from your system.');
}
}
// PAGE FILES
// delete orphaned files if requested
if($this->wire('input')->post->deleteOrphanFiles && $this->wire('input')->post->orphanPaths) {
foreach(explode('|', $this->wire('input')->post->orphanPaths) as $filePath) {
if(file_exists($filePath)) unlink($filePath);
}
$this->wire('session')->redirect($this->httpReferer);
}
// delete missing pagefiles if requested
if($this->wire('input')->post->deleteMissingFiles && $this->wire('input')->post->missingPaths) {
foreach(json_decode(urldecode($this->wire('input')->post->missingPaths), true) as $pid => $files) {
$p = $this->wire('pages')->get($pid);
foreach($files as $file) {
$pagefile = $p->{$file['field']}->get(pathinfo($file['filename'], PATHINFO_BASENAME));
$p->{$file['field']}->delete($pagefile);
$p->save($file['field']);
}
}
$this->wire('session')->redirect($this->httpReferer);
}
// PAGE RECORDER
// trash / clear recorded pages if requested
if($this->wire('input')->post->trashRecordedPages || $this->wire('input')->post->clearRecordedPages) {
if($this->wire('input')->post->trashRecordedPages) {
foreach($this->data['recordedPages'] as $pid) {
$this->wire('pages')->trash($this->wire('pages')->get($pid));
}
}
$configData = $this->wire('modules')->getModuleConfigData("TracyDebugger");
unset($configData['recordedPages']);
$this->wire('modules')->saveModuleConfigData($this, $configData);
$this->wire('session')->redirect($this->httpReferer);
}
// ADMIN TOOLS
if(static::$allowedSuperuser) {
// delete children
if($this->wire('input')->post->deleteChildren) {
foreach($this->wire('pages')->get((int)$this->wire('input')->post->adminToolsId)->children("include=all") as $child) {
$child->delete(true);
}
}
// delete template
if($this->wire('input')->post->deleteTemplate) {
foreach($this->wire('pages')->find("template=".(int)$this->wire('input')->post->adminToolsId.", include=all") as $p) {
$p->delete();
}
$template = $this->wire('templates')->get((int)$this->wire('input')->post->adminToolsId);
$this->wire('templates')->delete($template);
$templateName = $template->name;
$fieldgroup = $this->wire('fieldgroups')->get($templateName);
if($fieldgroup) $this->wire('fieldgroups')->delete($fieldgroup);
$this->wire('session')->redirect($this->wire('config')->urls->admin);
}
// delete field
if($this->wire('input')->post->deleteField) {
$field = $this->wire('fields')->get((int)$this->wire('input')->post->adminToolsId);
foreach($this->wire('templates') as $template) {
if(!$template->hasField($field)) continue;
$template->fields->remove($field);
$template->fields->save();
}
$this->wire('fields')->delete($field);
$this->wire('session')->redirect($this->wire('config')->urls->admin.'setup/field');
}
// change field type
if($this->wire('input')->post->changeFieldType) {
$field = $this->wire('fields')->get((int)$this->wire('input')->post->adminToolsId);
$field->type = $this->wire('input')->post->changeFieldType;
$field->save();
}
// uninstall module
if($this->wire('input')->post->uninstallModule) {
$moduleName = $this->wire('input')->post->adminToolsName;
$reason = $this->wire('modules')->isUninstallable($moduleName, true);
$class = $this->wire('modules')->getModuleClass($moduleName);
if($reason !== true) {
if(strpos($reason, 'Fieldtype') !== false) {
foreach($this->wire('fields') as $field) {
$fieldtype = wireClassName($field->type, false);
if($fieldtype == $class) {
foreach($this->wire('templates') as $template) {
if(!$template->hasField($field)) continue;
$template->fields->remove($field);
$template->fields->save();
}
$this->wire('fields')->delete($field);
}
}
}
elseif(strpos($reason, 'required') !== false) {
$dependents = $this->wire('modules')->getRequiresForUninstall($class);
foreach($dependents as $dependent) {
$this->wire('modules')->uninstall($dependent);
}
}
}
$this->wire('modules')->uninstall($moduleName);
$this->wire('session')->redirect($this->wire('config')->urls->admin.'module');
}
}
// notify user about email sent flag and provide option to clear it
$emailSentPath = $this->wire('config')->paths->logs.'tracy/email-sent';
if($this->wire('input')->post->clearEmailSent || $this->wire('input')->get->clearEmailSent) {
if(file_exists($emailSentPath)) {
$removed = unlink($emailSentPath);
}
if (!isset($removed) || !$removed) {
$this->wire()->error( __('No file to remove'));
}
else {
$this->wire()->message(__("email-sent file deleted successfully"));
$this->wire('session')->redirect(str_replace(array('?clearEmailSent=1', '&clearEmailSent=1'), '', $this->wire('input')->url(true)));
}
}
if(file_exists($emailSentPath)) {
$this->wire()->warning('Tracy Debugger "Email Sent" flag has been set. <a href="'.$this->wire('input')->url(true).($this->wire('input')->queryString() ? '&' : '?').'clearEmailSent=1">Clear it</a> to continue receiving further emails', Notice::allowMarkup);
}
// CONSOLE PANEL CODE INJECTION
$this->insertCode('init');
$this->wire()->addHookBefore('ProcessWire::finished', function($event) {
$this->insertCode('finished');
});
}
//convert checked location strings to constants and array_reduce to bitwise OR (|) line
$locations = array_map('constant', $this->data['showLocation']);
Debugger::$showLocation = array_reduce($locations, function($a, $b) { return $a | $b; }, 0);
// START ENABLING TRACY
// now that required classes above have been loaded, we can now exit if user is not allowed
if(!static::$allowedTracyUser) return;
// override default PW core behavior that converts exceptions to string for passing to trigger_error()
$this->wire()->addHookBefore('Wire::trackException', function($event) {
$event->wire()->config->allowExceptions = true;
});
// SET TRACY AS ENBALED
// if we get this far, Tracy is fully enabled, so set this for checking in ready()
$this->tracyEnabled = true;
// PROCESSWIRE LOGS
// delete ProcessWire logs if requested
if($this->wire('input')->post->deleteProcessWireLogs) {
$files = glob($this->wire('config')->paths->logs.'*');
foreach($files as $file) {
if(is_file($file)) {
unlink($file);
}
}
}
// TRACY LOGS
// Tracy log folder path
$logFolder = $this->wire('config')->paths->logs.'tracy';
// delete Tracy logs if requested
if($this->wire('input')->post->deleteTracyLogs) {
wireRmdir($logFolder, true);
}
// if Tracy log folder doesn't exist, create it now
if(!is_dir($logFolder)) wireMkdir($logFolder);
// TRACY MODE
if($this->data['outputMode'] == 'development' || static::$allowedTracyUser === 'development') {
$outputMode = Debugger::DEVELOPMENT;
}
elseif($this->data['outputMode'] == 'production' || static::$allowedTracyUser === 'production') {
$outputMode = Debugger::PRODUCTION;
}
else {
$outputMode = Debugger::DETECT;