-
Notifications
You must be signed in to change notification settings - Fork 0
/
wdt.php
914 lines (796 loc) · 30.6 KB
/
wdt.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
<?php
// Define constants for easier configuration and paths.
define("MU_PATH", "wp-content/mu-plugins");
define("ER_URL", "https://raw.githubusercontent.com/mbissett/error-revealer/master/error-revealer.php");
define("BACKUP_CONFIG_FILENAME", "wp-config.my-backup");
define("LOGVIEW_FILEZIE_LIMIT_MB", 50);
// Debugging settings to be ensured in wp-config.php
$config_constants = [
'WP_DEBUG' => 'true',
'WP_DEBUG_LOG' => 'true',
'WP_DEBUG_DISPLAY' => 'false',
'SCRIPT_DEBUG' => 'false',
];
// Path to the WordPress debug log file.
$debug_log_file_path = __DIR__ . '/wp-content/debug.log';
// Array of errors that can be highlighted in the log viewer.
$highlightable_errors = ['exception', 'fatal', 'exhausted'];
// Determine the home URL based on whether HTTPS is enabled.
$home_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
// Determine the current URL for redirection and form actions.
$current_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Capture user input from the URL (GET parameters) for various views and actions.
$current_view = isset($_GET['view']) ? $_GET['view'] : "";
$highlight_errors = (isset($_GET["highlight-errors"]) && $_GET["highlight-errors"] == "true") ? true : false;
$filter_errors = (isset($_GET["filter-errors"]) && $_GET["filter-errors"] == "true") ? true : false;
$bypass_fs_limit = (isset($_GET["bypass-file-limit"]) && $_GET["bypass-file-limit"] == "true") ? true : false;
$error = (isset($_GET["error"])) ? $_GET["error"] : "unknown error";
// Flag to track if debugging is enabled based on the wp-config.php settings.
$debug_enabled = true;
// Use the current time as a unique identifier for certain operations.
$random = time();
// Check if the current view is the debug log viewer.
if($current_view == "debug-log-viewer") {
// Initialize the WPConfigTransformer class to manage wp-config.php.
$wp_config = new WPConfigTransformer('wp-config.php');
// Verify if debugging constants are set as expected; disable debugging if not.
foreach ($config_constants as $key => $value) {
if($wp_config->get_value('constant', $key) != "'$value'") $debug_enabled = false;
}
// Enable debugging if requested and currently not enabled.
if (!$debug_enabled && isset($_GET["enable-debugging"]) && $_GET["enable-debugging"] == "true") {
// Conditionally install the error revealer plugin if requested.
if (isset($_GET["enable-er"]) && $_GET["enable-er"] == "true") {
$file_name = basename(ER_URL);
// Prevent reinstallation if the error revealer is already present.
if (file_exists($file_name) || file_exists(MU_PATH . '/' . $file_name)) {
$location = $home_url . '?view=error&error=error revealer is already installed';
header("Location: $location");
die();
}
// Attempt to download the error revealer; fail gracefully on error.
if (!file_put_contents($file_name . $random, file_get_contents(ER_URL))) {
$location = $home_url . '?view=error&error=failed to download error revealer from source';
header("Location: $location");
die();
}
// Ensure the MU plugins directory exists before moving the file there.
if (!file_exists(MU_PATH)) mkdir(MU_PATH, 0755, true);
rename($file_name . $random, MU_PATH . '/' . $file_name);
}
// Backup wp-config.php before enabling debugging.
if (!file_exists(BACKUP_CONFIG_FILENAME)) {
copy('wp-config.php', BACKUP_CONFIG_FILENAME);
foreach ($config_constants as $key => $value) {
$wp_config->update('constant', $key, $value);
}
} else {
// Abort if a backup already exists to prevent data loss.
$location = $home_url . '?view=error&error=wp-config.php backup file already exists';
header("Location: $location");
die();
}
// Confirm debugging is now enabled.
$debug_enabled = true;
}
// Disable debugging if requested and currently enabled.
if ($debug_enabled && isset($_GET["disable-debugging"]) && $_GET["disable-debugging"] == "true") {
// Optionally delete the error revealer as part of cleanup.
if (file_exists(MU_PATH . '/error-revealer.php')) {
unlink(MU_PATH . '/error-revealer.php');
}
// Restore the original wp-config.php from backup.
if (file_exists(BACKUP_CONFIG_FILENAME)) {
copy(BACKUP_CONFIG_FILENAME, BACKUP_CONFIG_FILENAME . $random);
unlink('wp-config.php');
rename(BACKUP_CONFIG_FILENAME, 'wp-config.php');
unlink(BACKUP_CONFIG_FILENAME . $random);
} else {
// Error handling if backup does not exist.
$location = $home_url . '?view=error&error=wp-config.php backup file does not exist';
header("Location: $location");
die();
}
// Mark debugging as disabled.
$debug_enabled = false;
}
// Download the debug log file if requested.
if ($debug_enabled && isset($_GET["download-log-file"]) && $_GET["download-log-file"] == "true") {
if (file_exists($debug_log_file_path)) {
// Serve the debug log file for download.
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($debug_log_file_path) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($debug_log_file_path));
flush();
readfile($debug_log_file_path);
exit;
} else {
echo "Debug log file does not exist.";
}
}
// Rotate the debug log file if requested.
if ($debug_enabled && isset($_GET["rotate-log-file"]) && $_GET["rotate-log-file"] == "true") {
if (file_exists($debug_log_file_path)) {
// Generate a new name for the log file and rename it.
$path_info = pathinfo($debug_log_file_path);
$new_name = $path_info['dirname'] . DIRECTORY_SEPARATOR . $path_info['filename'] . '-' . $random . '.' . $path_info['extension'];
rename($debug_log_file_path, $new_name);
}
}
// Delete the debug log file if requested.
if ($debug_enabled && isset($_GET["delete-log-file"]) && $_GET["delete-log-file"] == "true") {
if (file_exists($debug_log_file_path)) {
// Remove the log file from the server.
unlink($debug_log_file_path);
}
}
} else if ($current_view == "delete-tool") {
// Delete this tool itself when requested, for security reasons.
unlink(__FILE__);
$location = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];
header("Location: $location");
die();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WordPress Debugging Tools</title>
<style>
body {
margin: 0;
font-family: 'Courier New', monospace;
background-color: #1e1e1e;
color: #d4d4d4;
}
/* Common styles for buttons and submit inputs */
button, input[type="submit"] {
padding: 10px 20px;
background-color: #007acc;
color: white;
border: none;
cursor: pointer;
}
button:hover, input[type="submit"]:hover {
background-color: #005a9e;
}
button.btn-red, input[type="submit"].btn-red{
background-color: #cc0046;
}
button.btn-red:hover, input[type="submit"].btn-red:hover {
background-color: #930535;
}
/* Ribbon bar styles */
.ribbon-bar {
background-color: #2c2c2c;
padding: 10px 0;
overflow: hidden;
display: flex;
justify-content:flex-start; /* Distribute buttons evenly */
flex-wrap: wrap;
}
.ribbon-bar form {
margin: 10px;
}
/* Content area styles */
.content-area {
padding: 20px;
overflow-y: auto;
}
/* Landing page container */
.landing-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 50px;
padding: 20px;
background-color: #252526;
border-radius: 10px;
width: 90%;
max-width: 500px;
margin: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.landing-container form,
.landing-container input,
.landing-container label,
.landing-container button {
font-family: 'Arial', sans-serif;
}
.landing-container form,
.landing-container input[type="text"],
.landing-container input[type="submit"],
.landing-container button,
.landing-container a {
width: 100%;
}
.header {
font-size: 24px;
font-family: 'Verdana', sans-serif;
}
/* Styles for text inputs and checkboxes */
input[type="text"], .checkbox-container {
width: 100%;
margin-top: 5px;
margin-bottom: 20px;
}
input[type="text"] {
padding: 10px;
border: 1px solid #333;
background-color: #333336;
color: #d4d4d4;
box-sizing: border-box;
}
.checkbox-container {
display: flex;
align-items: center;
}
input[type="checkbox"] {
accent-color: #007acc;
}
.checkbox-label {
margin-left: 10px;
}
span.tip {
display: block;
font-size: 13px;
color: gray;
margin-bottom: 20px;
margin-top: -10px;
}
/* Log entry styles */
.log-entry {
background-color: #333336;
border-left: 5px solid #007acc;
padding: 10px;
margin-bottom: 10px;
white-space: pre-wrap;
}
.log-entry.highlight{
background-color: #5d0000;
border-left: 5px solid #cc003b;
}
/* Responsive styles */
@media (max-width: 600px) {
.ribbon-bar form {
width: 100%;
margin: 5px 0;
}
}
</style>
</head>
<body>
<?php if($current_view == "debug-log-viewer"):?>
<?php if(!$debug_enabled):?>
<div class="landing-container">
<div class="header">Debug Log Viewer</div>
<form method="get" action="<?php echo $current_url; ?>">
<input type="checkbox" name="enable-er" id="enable-er" value="true" checked>
<label for="enable-er" class="checkbox-label">Install Error Revealer</label>
<br><br>
<input type="checkbox" name="enable-debugging" id="enable-debugging" value="true" checked>
<label for="enable-debugging" class="checkbox-label">Modify wp-config.php file</label>
<br><br>
<input type="hidden" name="view" value="debug-log-viewer">
<input type="submit" value="Enable Debugging" class="btn-red"/>
</form>
<a href="<?php echo $home_url; ?>"><button>Home</button></a>
</div>
<?php else:?>
<div class="ribbon-bar">
<form method="get" action="<?php echo $home_url; ?>">
<div class="form-field">
<input type="hidden" name="view" value="debug-log-viewer">
<?php if($bypass_fs_limit):?><input type="hidden" name="bypass-file-limit" value="true"><?php endif;?>
<input type="hidden" name="highlight-errors" value="<?php echo ($highlight_errors == true) ? "false" : "true";?>">
<input type="submit" value="Highlight errors" class="<?php echo ($highlight_errors == true) ? "btn-red" : "";?>"/>
</div>
</form>
<form method="get" action="<?php echo $home_url; ?>">
<div class="form-field">
<input type="hidden" name="view" value="debug-log-viewer">
<?php if($bypass_fs_limit):?><input type="hidden" name="bypass-file-limit" value="true"><?php endif;?>
<input type="hidden" name="filter-errors" value="<?php echo ($filter_errors == true) ? "false" : "true";?>">
<input type="submit" value="Filter errors" class="<?php echo ($filter_errors == true) ? "btn-red" : "";?>"/>
</div>
</form>
<form method="get" action="<?php echo $home_url; ?>">
<div class="form-field">
<input type="hidden" name="view" value="debug-log-viewer">
<input type="hidden" name="download-log-file" value="true">
<input type="submit" value="Download log file"/>
</div>
</form>
<form method="get" action="<?php echo $home_url; ?>">
<div class="form-field">
<input type="hidden" name="view" value="debug-log-viewer">
<input type="hidden" name="rotate-log-file" value="true">
<input type="submit" value="Rotate log file"/>
</div>
</form>
<form method="get" action="<?php echo $home_url; ?>">
<div class="form-field">
<input type="hidden" name="view" value="debug-log-viewer">
<input type="hidden" name="delete-log-file" value="true">
<input type="submit" value="Delete log file" class="btn-red"/>
</div>
</form>
<form method="get" action="<?php echo $home_url; ?>">
<div class="form-field">
<input type="hidden" name="view" value="debug-log-viewer">
<input type="hidden" name="disable-debugging" value="true">
<input type="submit" value="Disable Debugging" />
</div>
</form>
<form method="get" action="<?php echo $home_url; ?>">
<div class="form-field">
<a href="<?php echo $home_url; ?>"><button>Home</button></a>
</div>
</form>
</div>
<div class="content-area">
<?php
if (file_exists($debug_log_file_path)) {
if (filesize($debug_log_file_path) > LOGVIEW_FILEZIE_LIMIT_MB * 1024 * 1024 && !$bypass_fs_limit) {
echo '<div class="log-entry highlight">Log file is larger than ' . LOGVIEW_FILEZIE_LIMIT_MB . 'MB. Its recommended to download the file and view using a text editor. </div>';
echo '<form method="get" action="' . $home_url. '"><div class="form-field"><input type="hidden" name="view" value="debug-log-viewer"><input type="hidden" name="bypass-file-limit" value="true"><input type="submit" value="Bypass the limitation"/></div></form>';
} else {
$error_logs = file($debug_log_file_path);
if (is_array($error_logs)) {
$error_logs = array_reverse($error_logs);
foreach ($error_logs as $log) {
$is_error = false;
if ($filter_errors || $highlight_errors) $is_error = string_contains_any_of_array($log, $highlightable_errors);
if ($filter_errors) {
if ($is_error) echo '<div class="log-entry highlight">' . $log . '</div>';
} else {
echo '<div class="' . (($is_error) ? 'log-entry highlight' : 'log-entry') . '">' . $log . '</div>';
}
}
}
}
} else {
echo '<div class="log-entry">No error logs found</div>';
}
?>
</div>
<?php endif;?>
<?php elseif($current_view == "list-versions"):?>
<?php $versions = wp_details(); ?>
<div class="ribbon-bar">
<form method="get" action="<?php echo $home_url; ?>">
<div class="form-field">
<a href="<?php echo $home_url; ?>"><button>Home</button></a>
</div>
</form>
</div>
<div class="content-area">
<?php
echo '<div class="log-entry"><b>WordPress</b><br>' . (isset($versions['wp_version']) ? $versions['wp_version'] : "failed to read") . '</div><br>';
echo '<div class="log-entry"><b>' . (isset($versions['theme']['name']) ? $versions['theme']['name'] . '</b> (theme)' : "Theme</b>") . '<br>' . (isset($versions['theme']['version']) ? $versions['theme']['version'] : "failed to read") . '</div><br>';
foreach ($versions['plugins'] as $plugin => $version) {
echo '<div class="log-entry"><b>' . $plugin . '</b><br>' . $version . '</div>';
}
?>
</div>
<?php elseif($current_view == "error"): ?>
<div class="landing-container">
<div class="header">Error!</div>
<div class="log-entry highlight"><?php echo $error; ?></div>
<a href="<?php echo $home_url; ?>"><button>Home</button></a>
</div>
<?php else:?>
<div class="landing-container">
<div class="header">WordPress Debugging Tools</div>
<form method="get" action="<?php echo $current_url; ?>">
<input type="hidden" name="view" value="debug-log-viewer">
<input type="submit" value="Debug Log Viewer" />
</form>
<form method="get" action="<?php echo $current_url; ?>">
<input type="hidden" name="view" value="list-versions">
<input type="submit" value="List Versions" />
</form>
<form method="get" action="<?php echo $current_url; ?>">
<input type="hidden" name="view" value="delete-tool">
<input type="submit" value="Delete This Tool" class="btn-red"/>
</form>
<!--<span class="tip">prabch</span>-->
</div>
<?php endif; ?>
</body>
</html>
<?php
function string_contains_any_of_array($string, $array) {
$pattern = '/' . implode('|', array_map('preg_quote', $array)) . '/i';
return preg_match($pattern, $string) === 1;
}
function wp_details() {
$wp_version = '';
$theme_details = [];
$plugins_details = [];
// Get WordPress version
if (file_exists('wp-includes/version.php')) {
$version_file = file_get_contents('wp-includes/version.php');
if (preg_match('/\$wp_version\s*=\s*\'([^\']+)\'/', $version_file, $matches)) {
$wp_version = $matches[1];
}
}
// Get current theme details
$themes_dir = 'wp-content/themes';
if ($active_theme = get_active_theme($themes_dir)) {
$style_css = $themes_dir . '/' . $active_theme . '/style.css';
if (file_exists($style_css)) {
$theme_data = parse_file_data($style_css, ['Theme Name', 'Version']);
$theme_details = [
'name' => $theme_data['Theme Name'] ?? 'Unknown',
'version' => $theme_data['Version'] ?? 'Unknown'
];
}
}
// Get plugins details
$plugins_dir = 'wp-content/plugins';
if (is_dir($plugins_dir)) {
$dir = new DirectoryIterator($plugins_dir);
foreach ($dir as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
$plugin_files = glob($fileinfo->getPathname() . '/*.php');
foreach ($plugin_files as $file) {
if (is_plugin_file($file)) {
$plugin_data = parse_file_data($file, ['Plugin Name', 'Version']);
if (!empty($plugin_data['Plugin Name'])) {
$plugins_details[$plugin_data['Plugin Name']] = $plugin_data['Version'] ?? 'Unknown';
}
}
}
}
}
}
return [
'wp_version' => $wp_version,
'theme' => $theme_details,
'plugins' => $plugins_details
];
}
function get_active_theme($themes_dir) {
// Assuming the active theme will have been used more recently
$latest_mtime = 0;
$active_theme = '';
foreach (new DirectoryIterator($themes_dir) as $dir) {
if ($dir->isDir() && !$dir->isDot()) {
$theme_dir = $dir->getPathname();
$mtime = filemtime($theme_dir);
if ($mtime > $latest_mtime) {
$latest_mtime = $mtime;
$active_theme = $dir->getFilename();
}
}
}
return $active_theme;
}
function is_plugin_file($file) {
$file_contents = file_get_contents($file);
return strpos($file_contents, 'Plugin Name:') !== false;
}
function parse_file_data($file, $fields) {
$contents = file_get_contents($file);
$data = [];
foreach ($fields as $field) {
if (preg_match('/' . preg_quote($field) . ':\s*(.+)/i', $contents, $matches)) {
$data[$field] = trim($matches[1]);
}
}
return $data;
}
/**
* Transforms a wp-config.php file.
*/
class WPConfigTransformer {
/**
* Append to end of file
*/
const ANCHOR_EOF = 'EOF';
/**
* Path to the wp-config.php file.
*
* @var string
*/
protected $wp_config_path;
/**
* Original source of the wp-config.php file.
*
* @var string
*/
protected $wp_config_src;
/**
* Array of parsed configs.
*
* @var array
*/
protected $wp_configs = array();
/**
* Instantiates the class with a valid wp-config.php.
*
* @throws Exception If the wp-config.php file is missing.
* @throws Exception If the wp-config.php file is not writable.
*
* @param string $wp_config_path Path to a wp-config.php file.
*/
public function __construct( $wp_config_path ) {
$basename = basename( $wp_config_path );
if ( ! file_exists( $wp_config_path ) ) {
throw new Exception( "{$basename} does not exist." );
}
if ( ! is_writable( $wp_config_path ) ) {
throw new Exception( "{$basename} is not writable." );
}
$this->wp_config_path = $wp_config_path;
}
/**
* Checks if a config exists in the wp-config.php file.
*
* @throws Exception If the wp-config.php file is empty.
* @throws Exception If the requested config type is invalid.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
*
* @return bool
*/
public function exists( $type, $name ) {
$wp_config_src = file_get_contents( $this->wp_config_path );
if ( ! trim( $wp_config_src ) ) {
throw new Exception( 'Config file is empty.' );
}
// Normalize the newline to prevent an issue coming from OSX.
$this->wp_config_src = str_replace( array( "\n\r", "\r" ), "\n", $wp_config_src );
$this->wp_configs = $this->parse_wp_config( $this->wp_config_src );
if ( ! isset( $this->wp_configs[ $type ] ) ) {
throw new Exception( "Config type '{$type}' does not exist." );
}
return isset( $this->wp_configs[ $type ][ $name ] );
}
/**
* Get the value of a config in the wp-config.php file.
*
* @throws Exception If the wp-config.php file is empty.
* @throws Exception If the requested config type is invalid.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
*
* @return string|null
*/
public function get_value( $type, $name ) {
$wp_config_src = file_get_contents( $this->wp_config_path );
if ( ! trim( $wp_config_src ) ) {
throw new Exception( 'Config file is empty.' );
}
$this->wp_config_src = $wp_config_src;
$this->wp_configs = $this->parse_wp_config( $this->wp_config_src );
if ( ! isset( $this->wp_configs[ $type ] ) ) {
throw new Exception( "Config type '{$type}' does not exist." );
}
return (isset($this->wp_configs[ $type ][ $name ]['value']) ? $this->wp_configs[ $type ][ $name ]['value'] : "");
}
/**
* Adds a config to the wp-config.php file.
*
* @throws Exception If the config value provided is not a string.
* @throws Exception If the config placement anchor could not be located.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
* @param string $value Config value.
* @param array $options (optional) Array of special behavior options.
*
* @return bool
*/
public function add( $type, $name, $value, array $options = array() ) {
if ( ! is_string( $value ) ) {
throw new Exception( 'Config value must be a string.' );
}
if ( $this->exists( $type, $name ) ) {
return false;
}
$defaults = array(
'raw' => false, // Display value in raw format without quotes.
'anchor' => "/* That's all, stop editing!", // Config placement anchor string.
'separator' => PHP_EOL, // Separator between config definition and anchor string.
'placement' => 'before', // Config placement direction (insert before or after).
);
list( $raw, $anchor, $separator, $placement ) = array_values( array_merge( $defaults, $options ) );
$raw = (bool) $raw;
$anchor = (string) $anchor;
$separator = (string) $separator;
$placement = (string) $placement;
if ( self::ANCHOR_EOF === $anchor ) {
$contents = $this->wp_config_src . $this->normalize( $type, $name, $this->format_value( $value, $raw ) );
} else {
if ( false === strpos( $this->wp_config_src, $anchor ) ) {
throw new Exception( 'Unable to locate placement anchor.' );
}
$new_src = $this->normalize( $type, $name, $this->format_value( $value, $raw ) );
$new_src = ( 'after' === $placement ) ? $anchor . $separator . $new_src : $new_src . $separator . $anchor;
$contents = str_replace( $anchor, $new_src, $this->wp_config_src );
}
return $this->save( $contents );
}
/**
* Updates an existing config in the wp-config.php file.
*
* @throws Exception If the config value provided is not a string.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
* @param string $value Config value.
* @param array $options (optional) Array of special behavior options.
*
* @return bool
*/
public function update( $type, $name, $value, array $options = array() ) {
if ( ! is_string( $value ) ) {
throw new Exception( 'Config value must be a string.' );
}
$defaults = array(
'add' => true, // Add the config if missing.
'raw' => false, // Display value in raw format without quotes.
'normalize' => false, // Normalize config output using WP Coding Standards.
);
list( $add, $raw, $normalize ) = array_values( array_merge( $defaults, $options ) );
$add = (bool) $add;
$raw = (bool) $raw;
$normalize = (bool) $normalize;
if ( ! $this->exists( $type, $name ) ) {
return ( $add ) ? $this->add( $type, $name, $value, $options ) : false;
}
$old_src = $this->wp_configs[ $type ][ $name ]['src'];
$old_value = $this->wp_configs[ $type ][ $name ]['value'];
$new_value = $this->format_value( $value, $raw );
if ( $normalize ) {
$new_src = $this->normalize( $type, $name, $new_value );
} else {
$new_parts = $this->wp_configs[ $type ][ $name ]['parts'];
$new_parts[1] = str_replace( $old_value, $new_value, $new_parts[1] ); // Only edit the value part.
$new_src = implode( '', $new_parts );
}
$contents = preg_replace(
sprintf( '/(?<=^|;|<\?php\s|<\?\s)(\s*?)%s/m', preg_quote( trim( $old_src ), '/' ) ),
'$1' . str_replace( '$', '\$', trim( $new_src ) ),
$this->wp_config_src
);
return $this->save( $contents );
}
/**
* Removes a config from the wp-config.php file.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
*
* @return bool
*/
public function remove( $type, $name ) {
if ( ! $this->exists( $type, $name ) ) {
return false;
}
$pattern = sprintf( '/(?<=^|;|<\?php\s|<\?\s)%s\s*(\S|$)/m', preg_quote( $this->wp_configs[ $type ][ $name ]['src'], '/' ) );
$contents = preg_replace( $pattern, '$1', $this->wp_config_src );
return $this->save( $contents );
}
/**
* Applies formatting to a config value.
*
* @throws Exception When a raw value is requested for an empty string.
*
* @param string $value Config value.
* @param bool $raw Display value in raw format without quotes.
*
* @return mixed
*/
protected function format_value( $value, $raw ) {
if ( $raw && '' === trim( $value ) ) {
throw new Exception( 'Raw value for empty string not supported.' );
}
return ( $raw ) ? $value : var_export( $value, true );
}
/**
* Normalizes the source output for a name/value pair.
*
* @throws Exception If the requested config type does not support normalization.
*
* @param string $type Config type (constant or variable).
* @param string $name Config name.
* @param mixed $value Config value.
*
* @return string
*/
protected function normalize( $type, $name, $value ) {
if ( 'constant' === $type ) {
$placeholder = "define( '%s', %s );";
} elseif ( 'variable' === $type ) {
$placeholder = '$%s = %s;';
} else {
throw new Exception( "Unable to normalize config type '{$type}'." );
}
return sprintf( $placeholder, $name, $value );
}
/**
* Parses the source of a wp-config.php file.
*
* @param string $src Config file source.
*
* @return array
*/
protected function parse_wp_config( $src ) {
$configs = array();
$configs['constant'] = array();
$configs['variable'] = array();
// Strip comments.
foreach ( token_get_all( $src ) as $token ) {
if ( in_array( $token[0], array( T_COMMENT, T_DOC_COMMENT ), true ) ) {
$src = str_replace( $token[1], '', $src );
}
}
preg_match_all( '/(?<=^|;|<\?php\s|<\?\s)(\h*define\s*\(\s*[\'"](\w*?)[\'"]\s*)(,\s*(\'\'|""|\'.*?[^\\\\]\'|".*?[^\\\\]"|.*?)\s*)((?:,\s*(?:true|false)\s*)?\)\s*;)/ims', $src, $constants );
preg_match_all( '/(?<=^|;|<\?php\s|<\?\s)(\h*\$(\w+)\s*=)(\s*(\'\'|""|\'.*?[^\\\\]\'|".*?[^\\\\]"|.*?)\s*;)/ims', $src, $variables );
if ( ! empty( $constants[0] ) && ! empty( $constants[1] ) && ! empty( $constants[2] ) && ! empty( $constants[3] ) && ! empty( $constants[4] ) && ! empty( $constants[5] ) ) {
foreach ( $constants[2] as $index => $name ) {
$configs['constant'][ $name ] = array(
'src' => $constants[0][ $index ],
'value' => $constants[4][ $index ],
'parts' => array(
$constants[1][ $index ],
$constants[3][ $index ],
$constants[5][ $index ],
),
);
}
}
if ( ! empty( $variables[0] ) && ! empty( $variables[1] ) && ! empty( $variables[2] ) && ! empty( $variables[3] ) && ! empty( $variables[4] ) ) {
// Remove duplicate(s), last definition wins.
$variables[2] = array_reverse( array_unique( array_reverse( $variables[2], true ) ), true );
foreach ( $variables[2] as $index => $name ) {
$configs['variable'][ $name ] = array(
'src' => $variables[0][ $index ],
'value' => $variables[4][ $index ],
'parts' => array(
$variables[1][ $index ],
$variables[3][ $index ],
),
);
}
}
return $configs;
}
/**
* Saves new contents to the wp-config.php file.
*
* @throws Exception If the config file content provided is empty.
* @throws Exception If there is a failure when saving the wp-config.php file.
*
* @param string $contents New config contents.
*
* @return bool
*/
protected function save( $contents ) {
if ( ! trim( $contents ) ) {
throw new Exception( 'Cannot save the config file with empty contents.' );
}
if ( $contents === $this->wp_config_src ) {
return false;
}
$result = file_put_contents( $this->wp_config_path, $contents, LOCK_EX );
if ( false === $result ) {
throw new Exception( 'Failed to update the config file.' );
}
return true;
}
}
?>