-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathdisable-comments.php
More file actions
1986 lines (1774 loc) · 77.3 KB
/
disable-comments.php
File metadata and controls
1986 lines (1774 loc) · 77.3 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: Disable Comments
* Plugin URI: https://wordpress.org/plugins/disable-comments/
* Description: Allows administrators to globally disable comments on their site. Comments can be disabled according to post type. You could bulk delete comments using Tools.
* Version: 2.7.0
* Author: WPDeveloper
* Author URI: https://wpdeveloper.com
* License: GPL-3.0+
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
* Text Domain: disable-comments
* Domain Path: /languages/
*
* @package Disable_Comments
*/
if (!defined('ABSPATH')) {
exit;
}
class Disable_Comments {
const DB_VERSION = 8;
private static $instance = null;
private $options;
public $networkactive;
public $tracker;
public $is_CLI;
public $sitewide_settings;
public $setup_notice_flag;
private $modified_types = array();
public static function get_instance() {
if (is_null(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
function __construct() {
define('DC_VERSION', '2.7.0');
define('DC_PLUGIN_SLUG', 'disable_comments_settings');
define('DC_PLUGIN_ROOT_PATH', dirname(__FILE__));
define('DC_PLUGIN_VIEWS_PATH', DC_PLUGIN_ROOT_PATH . '/views/');
define('DC_PLUGIN_ROOT_URI', plugins_url("/", __FILE__));
define('DC_ASSETS_URI', DC_PLUGIN_ROOT_URI . 'assets/');
// save settings
add_action('wp_ajax_disable_comments_save_settings', array($this, 'disable_comments_settings'));
add_action('wp_ajax_disable_comments_delete_comments', array($this, 'delete_comments_settings'));
add_action('wp_ajax_get_sub_sites', array($this, 'get_sub_sites'));
// Including cli.php
if (defined('WP_CLI') && WP_CLI) {
add_action('init', array($this, 'enable_cli'), 9999);
}
// are we network activated?
$this->networkactive = (is_multisite() && array_key_exists(plugin_basename(__FILE__), (array) get_site_option('active_sitewide_plugins')));
$this->is_CLI = defined('WP_CLI') && WP_CLI;
$this->sitewide_settings = get_site_option('disable_comments_sitewide_settings', false);
// Load options.
// Uses is_network_admin_ajax_context() (routing hint, not capability
// check) because current_user_can() is unavailable during plugin
// construction — pluggable.php hasn't loaded yet. This only controls
// which options table is READ (site vs blog) — writes are always
// gated by capability checks in the AJAX handlers and settings_page().
if ($this->networkactive && ($this->is_network_admin_ajax_context() || $this->sitewide_settings !== '1')) {
$this->options = get_site_option('disable_comments_options', array());
$this->options['disabled_sites'] = $this->get_disabled_sites();
$blog_id = get_current_blog_id();
if (
!$this->is_network_admin_ajax_context() && (
empty($this->options['disabled_sites']) ||
// if site disabled
empty($this->options['disabled_sites']["site_$blog_id"])
)
) {
$this->options = [
'remove_everywhere' => false,
'disabled_post_types' => array(),
'extra_post_types' => array(),
'disabled_sites' => array(),
'remove_xmlrpc_comments' => 0,
'remove_rest_API_comments' => 0,
'show_existing_comments' => false,
'allowed_comment_types' => array(),
'settings_saved' => true,
'db_version' => $this->options['db_version']
];
}
} else {
$this->options = get_option('disable_comments_options', array());
$not_configured = empty($this->options) || empty($this->options['settings_saved']);
if (is_multisite() && $not_configured && $this->sitewide_settings == '1') {
$this->options = get_site_option('disable_comments_options', array());
$this->options['is_network_options'] = true;
}
}
// If it looks like first run, check compat.
if (empty($this->options)) {
$this->check_compatibility();
}
$this->options['sitewide_settings'] = ($this->sitewide_settings == '1');
// Upgrade DB if necessary.
$this->check_db_upgrades();
$this->check_upgrades();
add_action('plugins_loaded', [$this, 'init_filters']);
add_action('wp_loaded', [$this, 'start_plugin_usage_tracking']);
// Add Site Health integration
add_filter('debug_information', array($this, 'add_site_health_info'));
}
/**
* Routing hint: is this request from the network-admin screen?
*
* During AJAX, WP's is_network_admin() is always false, so the JS
* appends ?is_network_admin=1 to ajaxurl (value set server-side in
* admin_enqueue_scripts via is_network_admin()). The GET param is
* client-supplied and therefore forgeable — never use this method
* alone for authorization. Always pair with can_network_admin_ajax_context()
* or an explicit current_user_can() check.
*/
private function is_network_admin_ajax_context() {
if (!$this->networkactive) {
return false;
}
if (is_network_admin()) {
return true;
}
if (defined('DOING_AJAX') && DOING_AJAX && is_multisite() && isset($_GET['is_network_admin'])) {
$param = sanitize_text_field(wp_unslash($_GET['is_network_admin']));
return $param === '1';
}
return false;
}
/**
* Capability-gated network-admin context check.
*
* Returns true only when the request appears to come from the
* network-admin screen AND the current user holds
* manage_network_plugins. Safe for authorization decisions.
*/
private function can_network_admin_ajax_context() {
if ($this->is_network_admin_ajax_context() && current_user_can('manage_network_plugins')) {
return true;
}
return false;
}
/**
* Enable CLI
* @since 2.0.0
*/
public function enable_cli() {
require_once DC_PLUGIN_ROOT_PATH . "/includes/cli.php";
new Disable_Comment_Command($this);
}
public function admin_notice() {
if ($this->tracker instanceof DisableComments_Plugin_Tracker) {
if (isset($this->setup_notice_flag) && $this->setup_notice_flag === true) {
return;
}
$current_screen = get_current_screen()->id;
$has_caps = $this->networkactive && is_network_admin() ? current_user_can('manage_network_plugins') : current_user_can('manage_options');
// if( ! in_array( $current_screen, ['settings_page_disable_comments_settings', 'settings_page_disable_comments_settings-network']) && $has_caps ) {
if ($has_caps && in_array($current_screen, ['dashboard-network', 'dashboard'])) {
$this->tracker->notice();
}
}
}
public function start_plugin_usage_tracking() {
if ($this->networkactive && !$this->options['sitewide_settings']) {
$this->tracker = null;
return;
}
if (!class_exists('DisableComments_Plugin_Tracker')) {
include_once(DC_PLUGIN_ROOT_PATH . '/includes/class-plugin-usage-tracker.php');
}
$tracker = $this->tracker = DisableComments_Plugin_Tracker::get_instance(__FILE__, [
'opt_in' => true,
'goodbye_form' => true,
'item_id' => 'b0112c9030af6ba53de4'
]);
$tracker->set_notice_options(array(
'notice' => __('Want to help make Disable Comments even better?', 'disable-comments'),
'extra_notice' => __('We collect non-sensitive diagnostic data and plugin usage information. Your site URL, WordPress & PHP version, plugins & themes and email address to send you the discount coupon. This data lets us make sure this plugin always stays compatible with the most popular plugins and themes. No spam, I promise.', 'disable-comments'),
));
$tracker->init();
}
private function check_compatibility() {
if (version_compare($GLOBALS['wp_version'], '4.7', '<')) {
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
deactivate_plugins(__FILE__);
// @phpcs:ignore WordPress.Security.NonceVerification.Recommended
if (isset($_GET['action']) && ($_GET['action'] == 'activate' || $_GET['action'] == 'error_scrape')) {
// translators: %s: WordPress version no.
exit(sprintf(esc_html__('Disable Comments requires WordPress version %s or greater.', 'disable-comments'), '4.7'));
}
}
}
private function check_db_upgrades() {
$old_ver = isset($this->options['db_version']) ? $this->options['db_version'] : 0;
if ($old_ver < self::DB_VERSION) {
if ($old_ver < 2) {
// upgrade options from version 0.2.1 or earlier to 0.3.
$this->options['disabled_post_types'] = get_option('disable_comments_post_types', array());
delete_option('disable_comments_post_types');
}
if ($old_ver < 5) {
// simple is beautiful - remove multiple settings in favour of one.
$this->options['remove_everywhere'] = isset($this->options['remove_admin_menu_comments']) ? $this->options['remove_admin_menu_comments'] : false;
foreach (array('remove_admin_menu_comments', 'remove_admin_bar_comments', 'remove_recent_comments', 'remove_discussion', 'remove_rc_widget') as $v) {
unset($this->options[$v]);
}
}
if ($old_ver < 7 && function_exists('get_sites')) {
$this->options['disabled_sites'] = [];
$dc_options = get_site_option('disable_comments_options', array());
foreach (get_sites(['number' => 0, 'fields' => 'ids']) as $blog_id) {
if (isset($dc_options['disabled_sites'])) {
$this->options['disabled_sites']["site_$blog_id"] = in_array($blog_id, $dc_options['disabled_sites']);
} else {
$this->options['disabled_sites']["site_$blog_id"] = true;
}
}
$this->options['disabled_sites'] = $this->get_disabled_sites();
}
if ($old_ver < 8) {
// Add new show_existing_comments option with default value false
// This maintains backward compatibility - existing behavior is preserved
$this->options['show_existing_comments'] = false;
}
foreach (array('remove_everywhere', 'extra_post_types', 'show_existing_comments') as $v) {
if (!isset($this->options[$v])) {
$this->options[$v] = false;
}
}
$this->options['db_version'] = self::DB_VERSION;
$this->update_options($this->networkactive);
}
}
public function check_upgrades() {
$dc_version = get_option('disable_comment_version');
if (version_compare($dc_version, '2.3.1', '<')) {
if ($this->is_remove_everywhere()) {
update_option('show_avatars', true);
}
}
if (!$dc_version || $dc_version != DC_VERSION) {
update_option('disable_comment_version', DC_VERSION);
}
}
private function update_options($is_network_ctx = false) {
if ($this->networkactive && $is_network_ctx) {
update_site_option('disable_comments_options', $this->options);
} else {
update_option('disable_comments_options', $this->options);
}
}
public function get_disabled_sites($default = false) {
$disabled_sites = ['all' => true];
foreach (get_sites(['number' => 0, 'fields' => 'ids']) as $blog_id) {
$disabled_sites["site_{$blog_id}"] = true;
}
if ($default) {
return $disabled_sites;
}
$this->options['disabled_sites'] = isset($this->options['disabled_sites']) ? $this->options['disabled_sites'] : [];
$this->options['disabled_sites'] = wp_parse_args($this->options['disabled_sites'], $disabled_sites);
$disabled_sites = $this->options['disabled_sites'];
unset($disabled_sites['all']);
if (in_array(false, $disabled_sites)) {
$this->options['disabled_sites']['all'] = false;
} else {
$this->options['disabled_sites']['all'] = true;
}
return $this->options['disabled_sites'];
}
// public function get_disabled_count(){
// $disabled_sites = isset($this->options['disabled_sites']) ? $this->options['disabled_sites'] : [];
// unset($disabled_sites['all']);
// return array_sum($disabled_sites);
// }
/**
* Get an array of disabled post type.
*/
public function get_disabled_post_types() {
$types = $this->options['disabled_post_types'];
// Not all extra_post_types might be registered on this particular site.
if ($this->networkactive && !empty($this->options['extra_post_types'])) {
foreach ((array) $this->options['extra_post_types'] as $extra) {
if (post_type_exists($extra)) {
$types[] = $extra;
}
}
}
return $types;
}
/**
* Check whether comments have been disabled on a given post type.
*/
private function is_exclude_by_role() {
if (!empty($this->options['enable_exclude_by_role']) && !empty($this->options['exclude_by_role'])) {
if (is_user_logged_in()) {
$user = wp_get_current_user();
$roles = (array) $user->roles;
$diff = array_intersect($this->options['exclude_by_role'], $roles);
if (count($diff) || (in_array("administrator", $this->options['exclude_by_role']) && is_super_admin())) {
return true;
}
} else if (in_array('logged-out-users', $this->options['exclude_by_role'])) {
return true;
}
}
return false;
}
private function is_remove_everywhere() {
if ($this->is_exclude_by_role()) {
return false;
}
if (isset($this->options['remove_everywhere'])) {
return $this->options['remove_everywhere'];
}
return false;
}
/**
* Check whether comments have been disabled on a given post type.
*/
private function is_post_type_disabled($type) {
if ($this->is_exclude_by_role()) {
return false;
}
return $type && in_array($type, $this->get_disabled_post_types());
}
public function init_filters() {
// These need to happen now.
if ($this->is_remove_everywhere()) {
add_action('widgets_init', array($this, 'disable_rc_widget'));
add_filter('wp_headers', array($this, 'filter_wp_headers'));
add_action('template_redirect', array($this, 'filter_query'), 9); // before redirect_canonical.
// Admin bar filtering has to happen here since WP 3.6.
add_action('template_redirect', array($this, 'filter_admin_bar'));
add_action('admin_init', array($this, 'filter_admin_bar'));
// Disable Comments REST API Endpoint (but allow notes)
add_filter('rest_endpoints', array($this, 'filter_rest_endpoints'));
add_filter('rest_pre_dispatch', array($this, 'filter_rest_comment_dispatch'), 10, 3);
add_filter('rest_comment_query', array($this, 'filter_rest_comment_query'), 10, 2);
}
// remove create comment via xmlrpc
if (isset($this->options['remove_xmlrpc_comments']) && intval($this->options['remove_xmlrpc_comments']) === 1) {
add_filter('xmlrpc_methods', array($this, 'disable_xmlrc_comments'));
}
// rest API Comment Block (but allow notes)
if (isset($this->options['remove_rest_API_comments']) && intval($this->options['remove_rest_API_comments']) === 1) {
add_filter('rest_endpoints', array($this, 'filter_rest_endpoints'));
add_filter('rest_pre_insert_comment', array($this, 'disable_rest_API_comments'), 10, 2);
add_filter('rest_pre_dispatch', array($this, 'filter_rest_comment_dispatch'), 10, 3);
add_filter('rest_comment_query', array($this, 'filter_rest_comment_query'), 10, 2);
}
// These can happen later.
add_action('wp_loaded', array($this, 'init_wploaded_filters'));
// Disable "Latest comments" block in Gutenberg.
add_action('enqueue_block_editor_assets', array($this, 'filter_gutenberg_blocks'));
// settings page assets
add_action('admin_enqueue_scripts', array($this, 'settings_page_assets'));
if (!$this->networkactive || $this->options['sitewide_settings']) {
add_filter('comment_status_links', function ($status_links) {
$status_links['disable_comments'] = sprintf("<a href='" . $this->settings_page_url() . "'>%s</a>", __("Disable Comments", 'disable-comments'));
return $status_links;
});
}
}
public function init_wploaded_filters() {
$disabled_post_types = $this->get_disabled_post_types();
if (!empty($disabled_post_types) && !$this->is_exclude_by_role()) {
foreach ($disabled_post_types as $type) {
// we need to know what native support was for later.
if (post_type_supports($type, 'comments')) {
$this->modified_types[] = $type;
// Keep comments support if show_existing_comments is enabled
// or if there are allowed comment types that need to be displayed
if (empty($this->options['show_existing_comments']) && !$this->has_allowed_comment_types()) {
remove_post_type_support($type, 'comments');
}
remove_post_type_support($type, 'trackbacks');
}
}
} elseif (is_admin() && !$this->is_configured()) {
/**
* It is possible that $disabled_post_types is empty if other
* plugins have disabled comments. Hence we also check for
* remove_everywhere. If you still get a warning you probably
* shouldn't be using this plugin.
*/
add_action('all_admin_notices', array($this, 'setup_notice'));
}
if ($this->is_remove_everywhere() || (!empty($disabled_post_types) && !$this->is_exclude_by_role())) {
add_filter('comments_array', array($this, 'filter_existing_comments'), 20, 2);
add_filter('comments_open', array($this, 'filter_comment_status'), 20, 2);
add_filter('pings_open', array($this, 'filter_comment_status'), 20, 2);
add_filter('get_comments_number', array($this, 'filter_comments_number'), 20, 2);
}
// Filters for the admin only.
if (is_admin()) {
add_action('all_admin_notices', array($this, 'admin_notice'));
if ($this->networkactive && is_network_admin()) {
add_action('network_admin_menu', array($this, 'settings_menu'));
add_action('network_admin_menu', array($this, 'tools_menu'));
add_filter('network_admin_plugin_action_links', array($this, 'plugin_actions_links'), 10, 2);
} elseif (!$this->networkactive || $this->options['sitewide_settings']) {
add_action('admin_menu', array($this, 'settings_menu'));
add_action('admin_menu', array($this, 'tools_menu'));
add_filter('plugin_action_links', array($this, 'plugin_actions_links'), 10, 2);
if (is_multisite()) { // We're on a multisite setup, but the plugin isn't network activated.
register_deactivation_hook(__FILE__, array($this, 'single_site_deactivate'));
}
}
add_action('admin_notices', array($this, 'discussion_notice'));
add_filter('plugin_row_meta', array($this, 'set_plugin_meta'), 10, 2);
if ($this->is_remove_everywhere()) {
add_action('admin_menu', array($this, 'filter_admin_menu'), 9999); // do this as late as possible.
add_action('admin_print_styles-index.php', array($this, 'admin_css'));
add_action('admin_print_styles-profile.php', array($this, 'admin_css'));
add_action('wp_dashboard_setup', array($this, 'filter_dashboard'));
add_filter('pre_option_default_pingback_flag', '__return_zero');
}
}
// Filters for front end only.
else {
add_action('template_redirect', array($this, 'check_comment_template'));
if ($this->is_remove_everywhere()) {
add_filter('feed_links_show_comments_feed', '__return_false');
}
}
}
// public function get_option( $key, $default = false ){
// return $this->networkactive ? get_site_option( $key, $default ) : get_option( $key, $default );
// }
// public function update_option( $option, $value ){
// return $this->networkactive ? update_site_option( $option, $value ) : update_option( $option, $value );
// }
// public function delete_option( $option ){
// return $this->networkactive ? delete_site_option( $option ) : delete_option( $option );
// }
/**
* Replace the theme's comment template with a blank one.
* To prevent this, define DISABLE_COMMENTS_REMOVE_COMMENTS_TEMPLATE
* and set it to True
*/
public function check_comment_template() {
if (is_singular() && ($this->is_remove_everywhere() || $this->is_post_type_disabled(get_post_type()))) {
if (!defined('DISABLE_COMMENTS_REMOVE_COMMENTS_TEMPLATE') || DISABLE_COMMENTS_REMOVE_COMMENTS_TEMPLATE == true) {
// Kill the comments template unless:
// - show_existing_comments is enabled, OR
// - there are allowed comment types that need to be displayed
if (empty($this->options['show_existing_comments']) && !$this->has_allowed_comment_types()) {
add_filter('comments_template', array($this, 'dummy_comments_template'), 20);
}
}
// Remove comment-reply script for themes that include it indiscriminately.
wp_deregister_script('comment-reply');
// feed_links_extra inserts a comments RSS link.
remove_action('wp_head', 'feed_links_extra', 3);
}
}
public function dummy_comments_template() {
return dirname(__FILE__) . '/views/comments.php';
}
public function is_xmlrpc_rest() {
// remove create comment via xmlrpc
if (isset($this->options['remove_xmlrpc_comments']) && intval($this->options['remove_xmlrpc_comments']) === 1) {
return true;
}
// rest API Comment Block
if (isset($this->options['remove_rest_API_comments']) && intval($this->options['remove_rest_API_comments']) === 1) {
return true;
}
return false;
}
/**
* Remove the X-Pingback HTTP header
*/
public function filter_wp_headers($headers) {
unset($headers['X-Pingback']);
return $headers;
}
/**
* remove method wp.newComment
*/
public function disable_xmlrc_comments($methods) {
unset($methods['wp.newComment']);
return $methods;
}
public function disable_rest_API_comments($prepared_comment, $request) {
// Allow comment types in the allowlist (e.g., WordPress 6.9+ block notes)
if ($this->is_allowed_comment_type_request($request)) {
return $prepared_comment;
}
return;
}
/**
* Get the list of allowed comment types from settings
*
* @return array Array of allowed comment types
*/
private function get_allowed_comment_types() {
if (!isset($this->options['allowed_comment_types']) || !is_array($this->options['allowed_comment_types'])) {
return array(); // Default: all special comment types disabled
}
return $this->options['allowed_comment_types'];
}
/**
* Check if any comment types are enabled in the allowlist
*
* @return bool True if there are allowed comment types, false otherwise
*/
private function has_allowed_comment_types() {
$allowed_types = $this->get_allowed_comment_types();
return !empty($allowed_types);
}
/**
* Check if a specific comment type is allowed (enabled in the allowlist)
*
* @param string $comment_type The comment type to check
* @return bool True if the comment type is allowed, false otherwise
*/
private function is_comment_type_allowed($comment_type) {
$allowed_types = $this->get_allowed_comment_types();
return in_array($comment_type, $allowed_types, true);
}
/**
* Get available comment type options for the "Enable Certain Comment Types" UI
*
* This function returns a list of known special comment types that users can enable,
* regardless of whether any comments of those types currently exist in the database.
*
* IMPORTANT: WordPress does not provide a formal API for registering or retrieving
* comment types (unlike post types with get_post_types()). Comment types are simply
* arbitrary string values stored in the wp_comments table. Therefore, we maintain
* a curated list of known special comment types that plugins commonly use.
*
* This function returns only predefined known types plus any types added via the
* 'disable_comments_known_comment_types' filter hook.
*
* @return array Associative array of comment_type => label
*/
public function get_available_comment_type_options() {
// Predefined known special comment types with descriptive labels
// These are shown even if no comments of these types exist yet in the database
//
// Note: WordPress does not have a formal comment type registration API,
// so this list is maintained manually based on common plugin usage.
$known_types = array(
'note' => __('Notes - WordPress 6.9+ (note)', 'disable-comments'),
);
/**
* Filter the list of known comment types shown in the "Enable Certain Comment Types" UI
*
* Plugins can add their own comment types to this list so users can enable them
* even before any comments of those types exist in the database.
*
* Example:
* add_filter( 'disable_comments_known_comment_types', function( $types ) {
* $types['my_custom_type'] = __( 'My Custom Comment Type', 'my-plugin' );
* return $types;
* } );
*
* @param array $known_types Associative array of comment_type => label
*/
return apply_filters('disable_comments_known_comment_types', $known_types);
}
/**
* Check if a REST API request is for an allowed comment type
*
* @param WP_REST_Request $request The REST API request object
* @return bool True if the request is for an allowed comment type, false otherwise
*/
private function is_allowed_comment_type_request($request = null) {
$comment_type = null;
// Check if we have a request object
if (!$request) {
// Check global $_REQUEST for type parameter
if (isset($_REQUEST['type'])) {
$comment_type = sanitize_text_field(wp_unslash($_REQUEST['type']));
}
// Check if we're in a REST API context
elseif (defined('REST_REQUEST') && REST_REQUEST) {
global $wp;
if (isset($wp->query_vars['type'])) {
$comment_type = sanitize_text_field($wp->query_vars['type']);
}
}
} else {
// Check the request object for type parameter
$type = $request->get_param('type');
if ($type) {
$comment_type = $type;
}
// Check the request body for type parameter (for POST requests)
if (!$comment_type) {
$body = $request->get_body_params();
if (isset($body['type'])) {
$comment_type = $body['type'];
}
}
// Check JSON body for type parameter
if (!$comment_type) {
$json = $request->get_json_params();
if (isset($json['type'])) {
$comment_type = $json['type'];
}
}
// For UPDATE requests (PUT/PATCH), check if the existing comment is an allowed type
// WordPress doesn't send the type parameter when updating, only the ID and content
if (!$comment_type) {
$comment_id = $request->get_param('id');
if ($comment_id) {
$comment = get_comment($comment_id);
if ($comment && isset($comment->comment_type)) {
$comment_type = $comment->comment_type;
}
}
}
// For DELETE requests, extract comment ID from the route path
// The comment ID is only in the URL (e.g., /wp/v2/comments/123), not in request params
if (!$comment_type && $request->is_method('DELETE')) {
$route_parts = explode('/', $request->get_route());
$comment_id = end($route_parts);
// Ensure we have a numeric comment ID
if (is_numeric($comment_id)) {
$comment = get_comment((int) $comment_id);
if ($comment && isset($comment->comment_type)) {
$comment_type = $comment->comment_type;
}
}
}
}
// Check if the comment type is in the allowlist
if ($comment_type && $this->is_comment_type_allowed($comment_type)) {
return true;
}
return false;
}
/**
* Issue a 403 for all comment feed requests.
*/
public function filter_query() {
if (is_comment_feed()) {
wp_die(esc_html__('Comments are closed.', 'disable-comments'), '', array('response' => 403));
}
}
/**
* Remove comment links from the admin bar.
*/
public function filter_admin_bar() {
if (is_admin_bar_showing()) {
// Remove comments links from admin bar.
remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
if (is_multisite()) {
add_action('admin_bar_menu', array($this, 'remove_network_comment_links'), 500);
}
}
}
/**
* Remove the comments endpoint for the REST API
* But allow WordPress 6.9+ block notes (type=note) to work
*/
public function filter_rest_endpoints($endpoints) {
// Don't remove endpoints entirely - instead we'll use permission callbacks
// and other filters to block regular comments while allowing notes
// We still need to add a filter to block non-note requests
// This is handled by rest_pre_dispatch filter added in init_filters
return $endpoints;
}
/**
* Filter REST API comment requests to block comments except allowed types
*
* @param mixed $result Response to replace the requested version with
* @param WP_REST_Server $server Server instance
* @param WP_REST_Request $request Request used to generate the response
* @return mixed
*/
public function filter_rest_comment_dispatch($result, $server, $request) {
// Only filter comment-related routes
$route = $request->get_route();
if (strpos($route, '/wp/v2/comments') === false) {
return $result;
}
// Allow requests for comment types in the allowlist to pass through
if ($this->is_allowed_comment_type_request($request)) {
return $result;
}
// Block all other comment requests
return new WP_Error(
'rest_comment_disabled',
__('Comments are disabled.', 'disable-comments'),
array('status' => 403)
);
}
/**
* Filter comment queries in REST API to allow only allowed comment types
*
* @param array $prepared_args Array of arguments for WP_Comment_Query
* @param WP_REST_Request $request The REST API request
* @return array
*/
public function filter_rest_comment_query($prepared_args, $request) {
// If this is a request for an allowed comment type, allow it
if ($this->is_allowed_comment_type_request($request)) {
return $prepared_args;
}
// For non-allowed requests, return empty results
// by setting an impossible condition
$prepared_args['comment__in'] = array(0);
return $prepared_args;
}
/**
* Determines if scripts should be enqueued
*/
public function filter_gutenberg_blocks($hook) {
global $post;
if ($this->is_remove_everywhere() || (isset($post->post_type) && $this->is_post_type_disabled($post->post_type))) {
return $this->disable_comments_script();
}
}
/**
* Enqueues scripts
*/
public function disable_comments_script() {
wp_enqueue_script('disable-comments-gutenberg', plugin_dir_url(__FILE__) . 'assets/js/disable-comments.js', array(), DC_VERSION, true);
}
/**
* Enqueues Scripts for Settings Page
*/
public function settings_page_assets($hook_suffix) {
if (
$hook_suffix === 'settings_page_' . DC_PLUGIN_SLUG ||
$hook_suffix === 'options-general_' . DC_PLUGIN_SLUG
) {
// css
wp_enqueue_style('sweetalert2', DC_ASSETS_URI . 'css/sweetalert2.min.css', [], DC_VERSION);
// wp_enqueue_style('pagination', DC_ASSETS_URI . 'css/pagination.css', [], false);
wp_enqueue_style('disable-comments-style', DC_ASSETS_URI . 'css/style.css', [], DC_VERSION);
wp_enqueue_style('select2', DC_ASSETS_URI . 'css/select2.min.css', [], DC_VERSION);
// js
wp_enqueue_script('sweetalert2', DC_ASSETS_URI . 'js/sweetalert2.all.min.js', array('jquery'), DC_VERSION, true);
wp_enqueue_script('pagination', DC_ASSETS_URI . 'js/pagination.min.js', array('jquery'), DC_VERSION, true);
wp_enqueue_script('select2', DC_ASSETS_URI . 'js/select2.min.js', array('jquery'), DC_VERSION, true);
wp_enqueue_script('disable-comments-scripts', DC_ASSETS_URI . 'js/disable-comments-settings-scripts.js', array('jquery', 'select2', 'pagination', 'sweetalert2', 'wp-i18n'), DC_VERSION, true);
wp_localize_script(
'disable-comments-scripts',
'disableCommentsObj',
array(
'save_action' => 'disable_comments_save_settings',
'delete_action' => 'disable_comments_delete_comments',
'settings_URI' => $this->settings_page_url(),
'_nonce' => wp_create_nonce('disable_comments_save_settings'),
'is_network_admin' => is_network_admin() ? '1' : '0',
)
);
wp_set_script_translations('disable-comments-scripts', 'disable-comments');
} else {
// notice css
wp_enqueue_style('disable-comments-notice', DC_ASSETS_URI . 'css/notice.css', [], DC_VERSION);
}
}
/**
* Remove comment links from the admin bar in a multisite network.
*/
public function remove_network_comment_links($wp_admin_bar) {
if ($this->networkactive && is_user_logged_in()) {
foreach ((array) $wp_admin_bar->user->blogs as $blog) {
$wp_admin_bar->remove_menu('blog-' . $blog->userblog_id . '-c');
}
} else {
// We have no way to know whether the plugin is active on other sites, so only remove this one.
$wp_admin_bar->remove_menu('blog-' . get_current_blog_id() . '-c');
}
}
public function discussion_notice() {
$disabled_post_types = $this->get_disabled_post_types();
if (get_current_screen()->id == 'options-discussion' && !empty($disabled_post_types)) {
$names_escaped = array();
foreach ($disabled_post_types as $type) {
$names_escaped[$type] = esc_html(get_post_type_object($type)->labels->name);
}
// translators: %s: disabled post types.
echo '<div class="notice notice-warning"><p>' . sprintf(esc_html__('Note: The <em>Disable Comments</em> plugin is currently active, and comments are completely disabled on: %s. Many of the settings below will not be applicable for those post types.', 'disable-comments'), implode(esc_html__(', ', 'disable-comments'), $names_escaped)) . '</p></div>';
}
}
/**
* Return context-aware settings page URL
*/
private function settings_page_url() {
$base = $this->networkactive && is_network_admin() ? network_admin_url('settings.php') : admin_url('options-general.php');
return add_query_arg('page', DC_PLUGIN_SLUG, $base);
}
/**
* Return context-aware tools page URL
*/
private function tools_page_url() {
$base = $this->networkactive && is_network_admin() ? network_admin_url('settings.php') : admin_url('tools.php');
return add_query_arg('page', 'disable_comments_tools', $base);
}
public function setup_notice() {
$current_screen = get_current_screen()->id;
if (!in_array($current_screen, ['dashboard-network', 'dashboard'])) {
return;
}
$hascaps = $this->networkactive && is_network_admin() ? current_user_can('manage_network_plugins') : current_user_can('manage_options');
if ($this->networkactive && !is_network_admin() && !$this->options['sitewide_settings']) {
$hascaps = false;
}
if ($hascaps) {
$this->setup_notice_flag = true;
// translators: %s: URL to Disabled Comment settings page.
$html = sprintf(__('The <strong>Disable Comments</strong> plugin is active, but isn\'t configured to do anything yet. Visit the <a href="%s">configuration page</a> to choose which post types to disable comments on.', 'disable-comments'), esc_attr($this->settings_page_url()));
// phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
echo wp_kses_post('<div class="notice dc-text__block disable__comment__alert mb30"><img height="30" src="' . esc_url(DC_ASSETS_URI . 'img/icon-logo.png') . '" alt=""><p>' . $html . '</p></div>');
}
}
public function filter_admin_menu() {
global $pagenow;
if (empty($this->options['show_existing_comments'])) {
if ($pagenow == 'comment.php' || $pagenow == 'edit-comments.php') {
wp_die(esc_html__('Comments are closed.', 'disable-comments'), '', array('response' => 403));
}
remove_menu_page('edit-comments.php');
}
if (!$this->discussion_settings_allowed()) {
if ($pagenow == 'options-discussion.php') {
wp_die(esc_html__('Comments are closed.', 'disable-comments'), '', array('response' => 403));
}
remove_submenu_page('options-general.php', 'options-discussion.php');
}
}
public function filter_dashboard() {
remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
}
public function admin_css() {
echo '<style>
#dashboard_right_now .comment-count,
#dashboard_right_now .comment-mod-count,
#latest-comments,
#welcome-panel .welcome-comments,
.user-comment-shortcuts-wrap {
display: none !important;
}
</style>';
}
public function filter_existing_comments($comments, $post_id) {
$post_type = get_post_type($post_id);
$comments_disabled = $this->is_remove_everywhere() || $this->is_post_type_disabled($post_type);
// If comments are disabled but show_existing_comments is enabled, return existing comments
if ($comments_disabled && !empty($this->options['show_existing_comments'])) {
$comments_disabled = false;
}
// If comments are disabled, filter out regular comments but keep allowed comment types
if ($comments_disabled && !empty($comments)) {
$filtered_comments = array();
foreach ($comments as $comment) {
// Keep comment types that are in the allowlist even when comments are disabled
if (isset($comment->comment_type) && $this->is_comment_type_allowed($comment->comment_type)) {
$filtered_comments[] = $comment;
}
}
return $filtered_comments;
}
// Default behavior: return all comments if not disabled
return $comments;
}
public function filter_comment_status($open, $post_id) {
$post_type = get_post_type($post_id);
return ($this->is_remove_everywhere() || $this->is_post_type_disabled($post_type) ? false : $open);
}
public function filter_comments_number($count, $post_id) {
$post_type = get_post_type($post_id);
$comments_disabled = $this->is_remove_everywhere() || $this->is_post_type_disabled($post_type);
// If comments are disabled but show_existing_comments is enabled, return actual count
if ($comments_disabled && !empty($this->options['show_existing_comments'])) {
return $count;
}
// If comments are disabled but there are allowed comment types, count only those types
if ($comments_disabled && $this->has_allowed_comment_types()) {
return $this->count_allowed_comment_types($post_id);
}
return $comments_disabled ? 0 : $count;
}
/**
* Count comments of allowed types for a specific post
*
* @param int $post_id The post ID
* @return int The count of comments matching allowed types
*/
private function count_allowed_comment_types($post_id) {
$allowed_types = $this->get_allowed_comment_types();
if (empty($allowed_types)) {
return 0;
}
$comments = get_comments(array(