-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphp-constants-manager.php
More file actions
1336 lines (1129 loc) · 51.2 KB
/
php-constants-manager.php
File metadata and controls
1336 lines (1129 loc) · 51.2 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
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
/**
* Plugin Name: PHP Constants Manager
* Plugin URI: https://github.com/cartpauj/php-constants-manager
* Description: Safely manage PHP constants (defines) through the WordPress admin interface
* Version: 1.2.0
* Author: cartpauj
* Author URI: https://github.com/cartpauj/
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: php-constants-manager
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
// Define plugin constants
define('PHPCM_VERSION', get_file_data(__FILE__, array('Version' => 'Version'))['Version']);
define('PHPCM_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('PHPCM_PLUGIN_URL', plugin_dir_url(__FILE__));
define('PHPCM_PLUGIN_BASENAME', plugin_basename(__FILE__));
// Include required files
require_once PHPCM_PLUGIN_DIR . 'includes/phpcm-helpers.php';
require_once PHPCM_PLUGIN_DIR . 'includes/class-phpcm-list-table.php';
require_once PHPCM_PLUGIN_DIR . 'includes/class-phpcm-all-defines-table.php';
require_once PHPCM_PLUGIN_DIR . 'includes/class-phpcm-db.php';
require_once PHPCM_PLUGIN_DIR . 'includes/class-phpcm-import-export.php';
if (defined('WP_CLI') && WP_CLI) {
require_once PHPCM_PLUGIN_DIR . 'includes/class-phpcm-cli.php';
}
/**
* Main plugin class
*/
class PHP_Constants_Manager {
/**
* Instance of this class
*/
private static $instance = null;
/**
* Database handler
*/
private $db;
/**
* Views directory path
*/
private $views_path;
/**
* Track constants defined by this plugin
*/
private $defined_by_plugin = array();
/**
* Get instance of the class
*/
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
private function __construct() {
$this->db = new PHPCM_DB();
$this->views_path = PHPCM_PLUGIN_DIR . 'views/';
// Hook into WordPress
//add_action('init', array($this, 'init'));
add_action('admin_init', array($this, 'handle_admin_actions'));
add_action('admin_init', array($this, 'migrate_mu_plugin_filename'));
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
add_action('admin_notices', array($this, 'show_admin_notices'));
// Load constants early
add_action('plugins_loaded', array($this, 'load_managed_constants'), 1);
// Add settings link
add_filter('plugin_action_links_' . PHPCM_PLUGIN_BASENAME, array($this, 'add_settings_link'));
// Handle form submissions
add_action('admin_post_phpcm_save_constant', array($this, 'handle_save_constant'));
add_action('admin_post_phpcm_delete_constant', array($this, 'handle_delete_constant'));
add_action('admin_post_phpcm_toggle_constant', array($this, 'handle_toggle_constant'));
add_action('admin_post_phpcm_bulk_action', array($this, 'handle_bulk_action'));
add_action('admin_post_phpcm_export_csv', array($this, 'handle_export_csv'));
add_action('admin_post_phpcm_import_csv', array($this, 'handle_import_csv'));
add_action('admin_post_phpcm_save_settings', array($this, 'handle_save_settings'));
// Handle AJAX requests
add_action('wp_ajax_phpcm_check_constant', array($this, 'ajax_check_constant'));
add_action('wp_ajax_phpcm_toggle_constant', array($this, 'ajax_toggle_constant'));
// Handle screen options
add_filter('set-screen-option', array($this, 'set_screen_options'), 10, 3);
}
/**
* Handle admin actions (including bulk actions)
*/
public function handle_admin_actions() {
// Only process on our plugin pages
// phpcs:disable WordPress.Security.NonceVerification.Recommended
if (!isset($_GET['page']) || strpos(sanitize_text_field(wp_unslash($_GET['page'])), 'php-constants-manager') !== 0) {
return;
}
// Process bulk actions for the main constants page
if (sanitize_text_field(wp_unslash($_GET['page'])) === 'php-constants-manager') {
$this->process_bulk_actions();
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended
}
/**
* Load view template
*/
private function load_view($template, $data = array()) {
$template_path = $this->views_path . $template . '.php';
if (!file_exists($template_path)) {
wp_die(sprintf(
/* translators: %s: template file name */
esc_html__('View template not found: %s', 'php-constants-manager'),
esc_html($template)
));
}
// Make data available to template (avoiding extract for security)
// Variables will be accessed via $data array in templates
include $template_path;
}
/**
* Load managed constants
*/
public function load_managed_constants() {
// Check if table exists first for performance
if (!$this->db->table_exists()) {
// Only run create_table if table doesn't exist
$table_ready = $this->db->create_table();
// If table creation failed, log and bail out gracefully
if (!$table_ready) {
$error_msg = "PHP Constants Manager: Cannot load constants - database table creation failed.";
if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log($error_msg);
}
// Store error for admin notice (only for admin users)
if (function_exists('current_user_can') && current_user_can('manage_options')) {
set_transient('phpcm_load_error', $error_msg, 300);
}
return;
}
}
$constants = $this->db->get_active_constants();
foreach ($constants as $constant) {
if (!defined($constant->name)) {
// Defining user-supplied constant names is this plugin's entire purpose;
// the PrefixAllGlobals rule does not apply to admin-managed data.
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.VariableConstantNameFound
define($constant->name, phpcm_cast_value($constant->value, $constant->type));
$this->defined_by_plugin[] = $constant->name;
}
}
}
/**
* Add admin menu
*/
public function add_admin_menu() {
$main_page = add_menu_page(
__('PHP Constants Manager', 'php-constants-manager'),
__('PHP Constants', 'php-constants-manager'),
'manage_options',
'php-constants-manager',
array($this, 'render_admin_page'),
'dashicons-editor-code',
80
);
$my_constants_page = add_submenu_page(
'php-constants-manager',
__('My Constants', 'php-constants-manager'),
__('My Constants', 'php-constants-manager'),
'manage_options',
'php-constants-manager',
array($this, 'render_admin_page')
);
$all_constants_page = add_submenu_page(
'php-constants-manager',
__('All Constants', 'php-constants-manager'),
__('All Constants', 'php-constants-manager'),
'manage_options',
'php-constants-manager-all-defines',
array($this, 'render_all_defines_page')
);
$import_export_page = add_submenu_page(
'php-constants-manager',
__('Import/Export', 'php-constants-manager'),
__('Import/Export', 'php-constants-manager'),
'manage_options',
'php-constants-manager-import-export',
array($this, 'render_import_export_page')
);
$settings_page = add_submenu_page(
'php-constants-manager',
__('Settings', 'php-constants-manager'),
__('Settings', 'php-constants-manager'),
'manage_options',
'php-constants-manager-settings',
array($this, 'render_settings_page')
);
$help_page = add_submenu_page(
'php-constants-manager',
__('Help', 'php-constants-manager'),
__('Help', 'php-constants-manager'),
'manage_options',
'php-constants-manager-help',
array($this, 'render_help_page')
);
// Add screen options hooks
add_action("load-$main_page", array($this, 'add_my_constants_screen_options'));
add_action("load-$all_constants_page", array($this, 'add_all_constants_screen_options'));
}
/**
* Enqueue admin assets
*/
public function enqueue_admin_assets($hook) {
if (strpos($hook, 'php-constants-manager') === false) {
return;
}
wp_enqueue_style('phpcm-admin-style', PHPCM_PLUGIN_URL . 'assets/admin.css', array(), PHPCM_VERSION);
wp_enqueue_script('phpcm-admin-script', PHPCM_PLUGIN_URL . 'assets/admin.js', array('jquery'), PHPCM_VERSION, true);
wp_localize_script('phpcm-admin-script', 'phpcm_ajax', array(
/* translators: JavaScript confirmation message when deleting a single constant */
'confirm_delete' => __('Are you sure you want to delete this constant?', 'php-constants-manager'),
/* translators: JavaScript confirmation message when deleting multiple constants */
'confirm_bulk_delete' => __('Are you sure you want to delete the selected constants?', 'php-constants-manager'),
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('phpcm_check_constant')
));
}
/**
* Render admin page
*/
public function render_admin_page() {
if (!current_user_can('manage_options')) {
return;
}
// Check if editing or adding
// phpcs:disable WordPress.Security.NonceVerification.Recommended
$action = isset($_GET['action']) ? sanitize_text_field(wp_unslash($_GET['action'])) : '';
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ($action === 'edit' && $id) {
$this->render_edit_page($id);
return;
} elseif ($action === 'add') {
$this->render_add_page();
return;
}
// Create list table instance
$list_table = new PHPCM_List_Table();
$list_table->prepare_items();
// Prepare data for view
$transient_notice = get_transient('phpcm_admin_notice');
if ($transient_notice) {
delete_transient('phpcm_admin_notice');
}
// phpcs:disable WordPress.Security.NonceVerification.Recommended
$message = isset($_GET['message']) ? sanitize_text_field(wp_unslash($_GET['message'])) : '';
// phpcs:enable WordPress.Security.NonceVerification.Recommended
$this->load_view('admin/constants-list', array(
'list_table' => $list_table,
'transient_notice' => $transient_notice,
'message' => $message
));
}
/**
* Render add page
*/
public function render_add_page() {
if (!current_user_can('manage_options')) {
return;
}
$this->render_form();
}
/**
* Render edit page
*/
public function render_edit_page($id) {
if (!current_user_can('manage_options')) {
return;
}
$constant = $this->db->get_constant($id);
if (!$constant) {
wp_die(esc_html__('Constant not found.', 'php-constants-manager'));
}
$this->render_form($constant);
}
/**
* Render constant form
*/
private function render_form($constant = null) {
$is_edit = $constant !== null;
$title = $is_edit ? __('Edit Constant', 'php-constants-manager') : __('Add New Constant', 'php-constants-manager');
$this->load_view('admin/constant-form', array(
'constant' => $constant,
'title' => $title,
'is_edit' => $is_edit
));
}
/**
* Handle save constant
*/
public function handle_save_constant() {
if (!current_user_can('manage_options')) {
wp_die(esc_html__('Insufficient permissions', 'php-constants-manager'));
}
if (!check_admin_referer('phpcm_save_constant', 'phpcm_nonce')) {
wp_die(esc_html__('Security check failed', 'php-constants-manager'));
}
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$name = isset($_POST['constant_name']) ? sanitize_text_field(wp_unslash($_POST['constant_name'])) : '';
// Value is sanitized here; type validation runs below via phpcm_validate_constant_value().
$value = isset($_POST['constant_value']) ? sanitize_textarea_field(wp_unslash($_POST['constant_value'])) : '';
$type = isset($_POST['constant_type']) ? sanitize_text_field(wp_unslash($_POST['constant_type'])) : 'string';
$is_active = !empty($_POST['constant_active']);
// Handle description properly - sanitize but preserve formatting for textarea content
$description = isset($_POST['constant_description']) ? sanitize_textarea_field(wp_unslash($_POST['constant_description'])) : '';
// Validate constant name
if (!phpcm_validate_constant_name($name)) {
wp_die(esc_html__('Invalid constant name', 'php-constants-manager'));
}
// Validate and normalize value based on type
$validation_result = phpcm_validate_constant_value($value, $type);
if ($validation_result['error']) {
// Store error message in transient
set_transient('phpcm_admin_notice', array(
'type' => 'error',
'message' => $validation_result['message']
), 30);
// Redirect back to form
$redirect_url = $id ?
admin_url('admin.php?page=php-constants-manager&action=edit&id=' . $id) :
admin_url('admin.php?page=php-constants-manager&action=add');
wp_safe_redirect($redirect_url);
exit;
}
// Use the normalized value (already normalized to lowercase for booleans)
$value = $validation_result['value'];
// Check if constant is predefined elsewhere and warn
$predefined_check = $this->is_constant_predefined($name, $value, $type, $is_active);
if ($predefined_check['is_predefined']) {
/* translators: action text for when a constant has been updated */
$action_text = $id ? __('updated', 'php-constants-manager') : __('added', 'php-constants-manager');
$message = sprintf(
/* translators: 1: constant name, 2: action (added/updated), 3: existing value */
__('The constant "%1$s" has been %2$s, but it is already defined elsewhere with value: %3$s. Your definition will only take effect when the predefined constant is removed.', 'php-constants-manager'),
$name,
$action_text,
phpcm_format_constant_value($predefined_check['existing_value'])
);
// Store message in transient to show after redirect
set_transient('phpcm_admin_notice', array(
'type' => 'warning',
'message' => $message
), 30);
}
// Save constant
if ($id) {
$result = $this->db->update_constant($id, array(
'value' => $value,
'type' => $type,
'is_active' => $is_active,
'description' => $description
));
if ($result !== false) {
wp_safe_redirect(admin_url('admin.php?page=php-constants-manager&message=saved'));
exit;
} else {
wp_die(esc_html__('Failed to update constant.', 'php-constants-manager'));
}
} else {
// Check if constant already exists in our database
$existing_constant = $this->db->get_constant_by_name($name);
if ($existing_constant) {
// Store error message in transient
set_transient('phpcm_admin_notice', array(
'type' => 'error',
'message' => sprintf(
/* translators: 1: constant name, 2: URL to edit existing constant */
__('A constant with the name "%1$s" already exists. Please <a href="%2$s">edit the existing constant</a> instead of creating a new one.', 'php-constants-manager'),
esc_html($name),
admin_url('admin.php?page=php-constants-manager&action=edit&id=' . $existing_constant->id)
)
), 30);
wp_safe_redirect(admin_url('admin.php?page=php-constants-manager&action=add'));
exit;
}
$result = $this->db->insert_constant(array(
'name' => $name,
'value' => $value,
'type' => $type,
'is_active' => $is_active,
'description' => $description
));
if ($result !== false) {
wp_safe_redirect(admin_url('admin.php?page=php-constants-manager&message=saved'));
exit;
} else {
wp_die(esc_html__('Failed to save constant.', 'php-constants-manager'));
}
}
}
/**
* Handle delete constant
*/
public function handle_delete_constant() {
if (!current_user_can('manage_options')) {
wp_die(esc_html__('Insufficient permissions', 'php-constants-manager'));
}
if (!check_admin_referer('phpcm_delete_constant', 'phpcm_nonce')) {
wp_die(esc_html__('Security check failed', 'php-constants-manager'));
}
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id) {
$this->db->delete_constant($id);
}
wp_safe_redirect(admin_url('admin.php?page=php-constants-manager&message=deleted'));
exit;
}
/**
* Handle toggle constant
*/
public function handle_toggle_constant() {
if (!current_user_can('manage_options')) {
wp_die(esc_html__('Insufficient permissions', 'php-constants-manager'));
}
if (!check_admin_referer('phpcm_toggle_constant', 'phpcm_nonce')) {
wp_die(esc_html__('Security check failed', 'php-constants-manager'));
}
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id) {
$this->db->toggle_constant($id);
}
wp_safe_redirect(admin_url('admin.php?page=php-constants-manager&message=toggled'));
exit;
}
/**
* Process bulk actions (called from admin page)
*/
private function process_bulk_actions() {
// Only process if this is a POST request with bulk action data
if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['action'])) {
return;
}
if (!current_user_can('manage_options')) {
wp_die(esc_html__('Insufficient permissions', 'php-constants-manager'));
}
if (!check_admin_referer('phpcm_bulk_action', 'phpcm_nonce')) {
wp_die(esc_html__('Security check failed', 'php-constants-manager'));
}
$action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
if ($action === '-1') {
$action = isset($_POST['action2']) ? sanitize_text_field(wp_unslash($_POST['action2'])) : '';
}
$ids = isset($_POST['constant']) ? array_map('intval', (array) $_POST['constant']) : array();
if (empty($ids) || empty($action) || $action === '-1') {
return; // No action selected or no items selected
}
$message = '';
switch ($action) {
case 'delete':
foreach ($ids as $id) {
$this->db->delete_constant($id);
}
$message = 'bulk_deleted';
break;
case 'activate':
foreach ($ids as $id) {
$this->db->update_constant($id, array('is_active' => true));
}
$message = 'bulk_activated';
break;
case 'deactivate':
foreach ($ids as $id) {
$this->db->update_constant($id, array('is_active' => false));
}
$message = 'bulk_deactivated';
break;
}
if ($message) {
// Set success message in transient and redirect
$message_text = '';
switch ($message) {
case 'bulk_deleted':
/* translators: %d: number of constants deleted */
$message_text = sprintf(_n('%d constant deleted successfully.', '%d constants deleted successfully.', count($ids), 'php-constants-manager'), count($ids));
break;
case 'bulk_activated':
/* translators: %d: number of constants activated */
$message_text = sprintf(_n('%d constant activated successfully.', '%d constants activated successfully.', count($ids), 'php-constants-manager'), count($ids));
break;
case 'bulk_deactivated':
/* translators: %d: number of constants deactivated */
$message_text = sprintf(_n('%d constant deactivated successfully.', '%d constants deactivated successfully.', count($ids), 'php-constants-manager'), count($ids));
break;
}
if ($message_text) {
set_transient('phpcm_admin_notice', array(
'type' => 'success',
'message' => $message_text
), 30);
}
wp_safe_redirect(admin_url('admin.php?page=php-constants-manager'));
exit;
}
}
/**
* Handle bulk actions (legacy admin-post handler)
*/
public function handle_bulk_action() {
if (!current_user_can('manage_options')) {
wp_die(esc_html__('Insufficient permissions', 'php-constants-manager'));
}
if (!check_admin_referer('phpcm_bulk_action', 'phpcm_nonce')) {
wp_die(esc_html__('Security check failed', 'php-constants-manager'));
}
$action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
if ($action === '-1') {
$action = isset($_POST['action2']) ? sanitize_text_field(wp_unslash($_POST['action2'])) : '';
}
$ids = isset($_POST['constant']) ? array_map('intval', (array) $_POST['constant']) : array();
if (empty($ids) || empty($action)) {
wp_safe_redirect(admin_url('admin.php?page=php-constants-manager'));
exit;
}
$message = '';
switch ($action) {
case 'delete':
foreach ($ids as $id) {
$this->db->delete_constant($id);
}
$message = 'bulk_deleted';
break;
case 'activate':
foreach ($ids as $id) {
$this->db->update_constant($id, array('is_active' => true));
}
$message = 'bulk_activated';
break;
case 'deactivate':
foreach ($ids as $id) {
$this->db->update_constant($id, array('is_active' => false));
}
$message = 'bulk_deactivated';
break;
}
wp_safe_redirect(admin_url('admin.php?page=php-constants-manager&message=' . $message));
exit;
}
/**
* AJAX handler to check if constant is defined
*/
public function ajax_check_constant() {
if (!check_ajax_referer('phpcm_check_constant', 'nonce', false)) {
wp_die(esc_html__('Security check failed', 'php-constants-manager'));
}
if (!current_user_can('manage_options')) {
wp_die(esc_html__('Insufficient permissions', 'php-constants-manager'));
}
$constant_name = isset($_POST['constant_name']) ? sanitize_text_field(wp_unslash($_POST['constant_name'])) : '';
if (empty($constant_name)) {
wp_send_json_error('Invalid constant name');
}
$predefined_check = $this->is_constant_predefined($constant_name);
wp_send_json_success(array(
'is_defined' => defined($constant_name),
'is_predefined' => $predefined_check['is_predefined'],
'value' => $predefined_check['existing_value']
));
}
/**
* AJAX handler to toggle constant status
*/
public function ajax_toggle_constant() {
if (!check_ajax_referer('phpcm_toggle_constant', 'nonce', false)) {
wp_send_json_error(esc_html__('Security check failed', 'php-constants-manager'));
}
if (!current_user_can('manage_options')) {
wp_send_json_error(esc_html__('Insufficient permissions', 'php-constants-manager'));
}
$id = isset($_POST['id']) ? intval($_POST['id']) : 0;
if (!$id) {
wp_send_json_error(esc_html__('Invalid constant ID', 'php-constants-manager'));
}
$constant = $this->db->get_constant($id);
if (!$constant) {
wp_send_json_error(esc_html__('Constant not found', 'php-constants-manager'));
}
$new_status = !$constant->is_active;
$this->db->update_constant($id, array('is_active' => $new_status));
wp_send_json_success(array(
'new_status' => $new_status,
'message' => $new_status ? esc_html__('Constant activated', 'php-constants-manager') : esc_html__('Constant deactivated', 'php-constants-manager')
));
}
/**
* Render all defines page
*/
public function render_all_defines_page() {
if (!current_user_can('manage_options')) {
return;
}
// Create list table instance
$list_table = new PHPCM_All_Defines_Table();
$list_table->prepare_items();
$this->load_view('admin/all-defines', array(
'list_table' => $list_table
));
}
/**
* Render help page
*/
public function render_help_page() {
if (!current_user_can('manage_options')) {
return;
}
$this->load_view('admin/help');
}
/**
* Render import/export page
*/
public function render_import_export_page() {
if (!current_user_can('manage_options')) {
return;
}
// Check for success/error messages
// phpcs:disable WordPress.Security.NonceVerification.Recommended
$message = isset($_GET['message']) ? sanitize_text_field(wp_unslash($_GET['message'])) : '';
$error = isset($_GET['error']) ? sanitize_text_field(wp_unslash($_GET['error'])) : '';
// phpcs:enable WordPress.Security.NonceVerification.Recommended
$this->load_view('admin/import-export', array(
'message' => $message,
'error' => $error
));
}
/**
* Render settings page
*/
public function render_settings_page() {
if (!current_user_can('manage_options')) {
return;
}
// Check for success/error messages
// phpcs:disable WordPress.Security.NonceVerification.Recommended
$message = isset($_GET['message']) ? sanitize_text_field(wp_unslash($_GET['message'])) : '';
$error = isset($_GET['error']) ? sanitize_text_field(wp_unslash($_GET['error'])) : '';
// phpcs:enable WordPress.Security.NonceVerification.Recommended
// Check if must-use plugin exists
$mu_plugin_exists = $this->mu_plugin_exists();
$early_loading_enabled = get_option('phpcm_early_loading_enabled', false);
$this->load_view('admin/settings', array(
'message' => $message,
'error' => $error,
'mu_plugin_exists' => $mu_plugin_exists,
'early_loading_enabled' => $early_loading_enabled
));
}
/**
* Check if must-use plugin exists
*/
private function mu_plugin_exists() {
$mu_plugin_path = WPMU_PLUGIN_DIR . '/0001-php-constants-manager-early.php';
return file_exists($mu_plugin_path);
}
/**
* Create must-use plugin file
*
* The generated MU plugin pulls in the main plugin's helpers file for
* value casting, so the casting contract lives in one place. If the
* main plugin is deleted the MU plugin bails silently.
*/
private function create_mu_plugin() {
if (!wp_mkdir_p(WPMU_PLUGIN_DIR)) {
return false;
}
$mu_plugin_path = WPMU_PLUGIN_DIR . '/0001-php-constants-manager-early.php';
$helpers_path = PHPCM_PLUGIN_DIR . 'includes/phpcm-helpers.php';
$content = "<?php\n";
$content .= "/**\n";
$content .= " * PHP Constants Manager - Early Loading\n";
$content .= " * Loads active constants from the plugin's table before other plugins.\n";
$content .= " * DO NOT EDIT - regenerated by PHP Constants Manager when the\n";
$content .= " * 'Early Loading' setting is toggled.\n";
$content .= " */\n\n";
$content .= "if (!defined('ABSPATH')) { exit; }\n\n";
// Emit the helper path as a safely-escaped single-quoted PHP string literal.
$quoted_path = "'" . str_replace(array('\\', "'"), array('\\\\', "\\'"), $helpers_path) . "'";
$content .= "\$phpcm_helpers = {$quoted_path};\n";
$content .= "if (!file_exists(\$phpcm_helpers)) { return; }\n";
$content .= "require_once \$phpcm_helpers;\n\n";
$content .= "(function () {\n";
$content .= " global \$wpdb;\n";
$content .= " \$GLOBALS['phpcm_early_defined_constants'] = array();\n";
$content .= " \$table = \$wpdb->prefix . 'phpcm_constants';\n";
$content .= " if (\$wpdb->get_var(\$wpdb->prepare('SHOW TABLES LIKE %s', \$table)) !== \$table) { return; }\n";
$content .= " \$constants = \$wpdb->get_results(\"SELECT name, value, type FROM {\$table} WHERE is_active = 1\");\n";
$content .= " if (empty(\$constants)) { return; }\n";
$content .= " \$defined = array();\n";
$content .= " foreach (\$constants as \$c) {\n";
$content .= " if (!defined(\$c->name)) {\n";
$content .= " define(\$c->name, phpcm_cast_value(\$c->value, \$c->type));\n";
$content .= " \$defined[] = \$c->name;\n";
$content .= " }\n";
$content .= " }\n";
$content .= " \$GLOBALS['phpcm_early_defined_constants'] = \$defined;\n";
$content .= "})();\n";
global $wp_filesystem;
if (empty($wp_filesystem)) {
require_once(ABSPATH . '/wp-admin/includes/file.php');
WP_Filesystem();
}
return $wp_filesystem->put_contents($mu_plugin_path, $content, FS_CHMOD_FILE);
}
/**
* Remove must-use plugin file
*/
private function remove_mu_plugin() {
$mu_plugin_path = WPMU_PLUGIN_DIR . '/0001-php-constants-manager-early.php';
if (!file_exists($mu_plugin_path)) {
return true;
}
global $wp_filesystem;
if (empty($wp_filesystem)) {
require_once(ABSPATH . '/wp-admin/includes/file.php');
WP_Filesystem();
}
return $wp_filesystem->delete($mu_plugin_path);
}
/**
* Migrate old must-use plugin filename to new naming convention
*/
public function migrate_mu_plugin_filename() {
// Only run for admin users
if (!current_user_can('manage_options')) {
return;
}
$old_mu_plugin_path = WPMU_PLUGIN_DIR . '/php-constants-manager-early.php';
$new_mu_plugin_path = WPMU_PLUGIN_DIR . '/0001-php-constants-manager-early.php';
// Check if old file exists and new file doesn't exist
if (file_exists($old_mu_plugin_path) && !file_exists($new_mu_plugin_path)) {
global $wp_filesystem;
if (empty($wp_filesystem)) {
require_once(ABSPATH . '/wp-admin/includes/file.php');
WP_Filesystem();
}
// Rename the file quietly
$wp_filesystem->move($old_mu_plugin_path, $new_mu_plugin_path);
}
}
/**
* Get the database handler (used by WP-CLI and other consumers).
*/
public function get_db() {
return $this->db;
}
/**
* Enable or disable the early-loading MU plugin.
*
* @param bool $enabled Desired state.
* @return true|WP_Error True on success, WP_Error on failure.
*/
public function set_early_loading($enabled) {
$enabled = (bool) $enabled;
$previous = (bool) get_option('phpcm_early_loading_enabled', false);
update_option('phpcm_early_loading_enabled', $enabled);
if ($enabled && !$previous) {
if (!$this->create_mu_plugin()) {
update_option('phpcm_early_loading_enabled', false);
return new WP_Error('mu_plugin_create_failed', __('Could not write MU plugin file.', 'php-constants-manager'));
}
} elseif (!$enabled && $previous) {
if (!$this->remove_mu_plugin()) {
update_option('phpcm_early_loading_enabled', true);
return new WP_Error('mu_plugin_remove_failed', __('Could not remove MU plugin file.', 'php-constants-manager'));
}
}
return true;
}
/**
* Identify what defined a constant, if it is currently defined.
*
* @param string $name Constant name.
* @return string|null One of 'early-load', 'plugin', 'elsewhere', or null if not defined.
*/
public function get_constant_source($name) {
if (!defined($name)) {
return null;
}
if (isset($GLOBALS['phpcm_early_defined_constants']) &&
in_array($name, $GLOBALS['phpcm_early_defined_constants'], true)) {
return 'early-load';
}
if (in_array($name, $this->defined_by_plugin, true)) {
return 'plugin';
}
return 'elsewhere';
}
/**
* Check if a constant is truly predefined (not defined by this plugin)
*
* @param string $name Constant name
* @param mixed $our_value Our stored value
* @param string $our_type Our stored type
* @param bool $is_active Whether our constant is active
* @return array Array with 'is_predefined' boolean and 'existing_value' if predefined
*/
public function is_constant_predefined($name, $our_value = null, $our_type = 'string', $is_active = true) {
if (!defined($name)) {
return array('is_predefined' => false, 'existing_value' => null);
}
$existing_value = constant($name);
// If we don't have our value info, it's predefined
if ($our_value === null) {
return array('is_predefined' => true, 'existing_value' => $existing_value);
}
// Check if this constant exists in our database
$our_constant = $this->db->get_constant_by_name($name);
if (!$our_constant) {
// Not in our database but is defined = predefined elsewhere
return array('is_predefined' => true, 'existing_value' => $existing_value);
}
// Check if we defined this constant via early loading (MU plugin)
if (isset($GLOBALS['phpcm_early_defined_constants']) &&
in_array($name, $GLOBALS['phpcm_early_defined_constants'])) {
// We successfully defined it via MU plugin, so it's not predefined
return array('is_predefined' => false, 'existing_value' => $existing_value);
}
// Check if we actually defined this constant during load_managed_constants
if (in_array($name, $this->defined_by_plugin)) {
// We successfully defined it, so it's not predefined
return array('is_predefined' => false, 'existing_value' => $existing_value);
}
// If we didn't define it but it exists and we have it in our database,
// then something else defined it first (e.g., wp-config.php)
return array('is_predefined' => true, 'existing_value' => $existing_value);
}
/**
* Add screen options for My Constants page
*/
public function add_my_constants_screen_options() {
add_screen_option('per_page', array(
'label' => __('Constants per page', 'php-constants-manager'),
'default' => 50,
'option' => 'constants_per_page'