Repository navigation
Expand file tree
/
Copy pathcommentator-bridge.php
More file actions
1006 lines (912 loc) · 34.7 KB
/
Copy pathcommentator-bridge.php
File metadata and controls
1006 lines (912 loc) · 34.7 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: Commentator Bridge
* Plugin URI: https://github.com/linuxundich/commentator
* Description: Lean REST endpoints for the Commentator Android app: cheap checks for new comments, bulk actions the core API lacks, and optional instant notifications via UnifiedPush.
* Version: 1.8.2
* Requires at least: 6.0
* Requires PHP: 7.4
* Author: Christoph Langner
* License: MIT
* License URI: https://opensource.org/licenses/MIT
* Text Domain: commentator-bridge
* Domain Path: /languages
*
* Dieses Plugin ist optional. Ohne es funktioniert die App vollständig, sie
* stellt dann lediglich etwas teurere Anfragen an die Kern-API.
*
* Bewusste Beschränkung: Das Plugin ändert kein Verhalten von WordPress.
* Nach außen sendet es nur, wenn ein Moderator das ausdrücklich eingerichtet
* hat (siehe /push unten), und dann nichts als einen inhaltslosen Weckruf.
*
* Seit 1.2.0 gibt es zwei schreibende Endpunkte. Beide tun ausschließlich
* das, was im Backend ohnehin möglich ist, und prüfen dieselben Rechte:
*
* - /empty leert Spam oder Papierkorb, wie der gleichnamige Knopf in der
* Kommentarverwaltung. Verlangt `moderate_comments`.
* - /blocklist pflegt die Option `disallowed_keys`, also dieselbe Liste wie
* Einstellungen → Diskussion. Verlangt `manage_options`, weil es eine
* seitenweite Option ist; ein Redakteur darf moderieren, aber keine
* Optionen ändern.
*
* Seit 1.5.0 kann die App eine UnifiedPush-Adresse hinterlegen (/push). Bei
* jedem neuen Kommentar, der nicht als Spam erkannt wurde und nicht vom
* Inhaber der Adresse selbst stammt, geht dorthin ein
* Weckruf ohne Inhalt: kein Name, kein Text, keine Kennung. Die App holt die
* Kommentare danach wie gewohnt selbst über die REST-API. Der Push-Server -
* etwa ein eigener ntfy - erfährt damit nur, dass und wann kommentiert wurde.
* Ohne hinterlegte Adresse passiert nichts.
*
* Seit 1.6.0 weckt auch eine Statusänderung - etwa eine Freigabe im
* Backend -, damit die App ihre Benachrichtigung zu dem Kommentar sofort
* zurücknimmt statt erst bei der nächsten regelmäßigen Prüfung.
*
* Seit 1.7.0 zeigt das Benutzerprofil die hinterlegten Adressen, mit
* Entfernen und Testweckruf. Für Admins gibt es zwei Stellschrauben, bewusst
* ohne Einstellungsseite:
*
* - define( 'COMMENTATOR_BRIDGE_DISABLE_PUSH', true ); in wp-config.php
* schaltet die Sofortmeldung ab. Das Plugin sendet dann nichts nach außen
* und nimmt keine Adressen an; alles andere bleibt.
* - Der Filter commentator_bridge_push_allow_local erlaubt Push-Server im
* eigenen Netz, etwa wenn Blog und ntfy auf demselben Rechner laufen.
* Der Filter commentator_bridge_push_endpoint_allowed kann Adressen
* zusätzlich einschränken, etwa auf den eigenen Server.
*/
declare( strict_types = 1 );
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
const COMMENTATOR_BRIDGE_VERSION = '1.8.2';
const COMMENTATOR_BRIDGE_NAMESPACE = 'commentator/v1';
/** Wie viele Kommentare eine Anfrage an /empty höchstens löscht. */
const COMMENTATOR_BRIDGE_EMPTY_BATCH = 200;
/** Hoechstzahl der Teammitglieder, die /team zurueckgibt. */
const COMMENTATOR_BRIDGE_TEAM_LIMIT = 200;
/** Benutzermeta mit den hinterlegten Push-Adressen eines Moderators. */
const COMMENTATOR_BRIDGE_PUSH_META = 'commentator_push_endpoints';
/**
* Höchstzahl der Push-Adressen je Konto. Eine deinstallierte App meldet sich
* nicht ab; die Obergrenze verhindert, dass sich Verwaistes ansammelt - die
* älteste Adresse fällt heraus.
*/
const COMMENTATOR_BRIDGE_PUSH_LIMIT = 5;
/**
* Mindestabstand zwischen zwei Weckrufen wegen Statusänderungen, in
* Sekunden. Sammelmoderation im Backend ändert Dutzende Kommentare auf
* einmal; ein Weckruf genügt, die App gleicht alles in einem Durchgang ab.
* Neue Kommentare wecken immer - einen davon zu verschlucken hieße, ihn erst
* Stunden später zu melden.
*/
const COMMENTATOR_BRIDGE_PUSH_STATUS_GAP = 30;
add_action( 'init', 'commentator_bridge_load_textdomain' );
add_action( 'rest_api_init', 'commentator_bridge_register_routes' );
add_action( 'wp_insert_comment', 'commentator_bridge_push_new_comment', 10, 2 );
add_action( 'transition_comment_status', 'commentator_bridge_push_status_change', 10, 3 );
add_action( 'show_user_profile', 'commentator_bridge_profile_section' );
add_action( 'edit_user_profile', 'commentator_bridge_profile_section' );
add_action( 'admin_post_commentator_push_remove', 'commentator_bridge_profile_remove' );
add_action( 'admin_post_commentator_push_test', 'commentator_bridge_profile_test' );
/**
* Englisch im Code, Übersetzungen unter languages/. WordPress wählt sie nach
* der Sprache des Blogs beziehungsweise des angemeldeten Kontos.
*/
function commentator_bridge_load_textdomain(): void {
load_plugin_textdomain( 'commentator-bridge', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}
function commentator_bridge_register_routes(): void {
register_rest_route(
COMMENTATOR_BRIDGE_NAMESPACE,
'/status',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'commentator_bridge_status',
'permission_callback' => 'commentator_bridge_can_moderate',
)
);
register_rest_route(
COMMENTATOR_BRIDGE_NAMESPACE,
'/summary',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'commentator_bridge_summary',
'permission_callback' => 'commentator_bridge_can_moderate',
)
);
register_rest_route(
COMMENTATOR_BRIDGE_NAMESPACE,
'/team',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'commentator_bridge_team',
'permission_callback' => 'commentator_bridge_can_moderate',
)
);
register_rest_route(
COMMENTATOR_BRIDGE_NAMESPACE,
'/empty',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'commentator_bridge_empty',
'permission_callback' => 'commentator_bridge_can_moderate',
'args' => array(
'status' => array(
'required' => true,
'type' => 'string',
'enum' => array( 'spam', 'trash' ),
'sanitize_callback' => 'sanitize_key',
),
),
)
);
register_rest_route(
COMMENTATOR_BRIDGE_NAMESPACE,
'/push',
array(
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'commentator_bridge_push_add',
'permission_callback' => 'commentator_bridge_can_moderate',
'args' => array(
'endpoint' => array(
'required' => true,
'type' => 'string',
'format' => 'uri',
),
),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => 'commentator_bridge_push_remove',
'permission_callback' => 'commentator_bridge_can_moderate',
'args' => array(
'endpoint' => array(
'required' => true,
'type' => 'string',
),
),
),
)
);
register_rest_route(
COMMENTATOR_BRIDGE_NAMESPACE,
'/push/test',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'commentator_bridge_push_test',
'permission_callback' => 'commentator_bridge_can_moderate',
)
);
register_rest_route(
COMMENTATOR_BRIDGE_NAMESPACE,
'/blocklist',
array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'commentator_bridge_blocklist_get',
'permission_callback' => 'commentator_bridge_can_manage_options',
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'commentator_bridge_blocklist_add',
'permission_callback' => 'commentator_bridge_can_manage_options',
'args' => array(
'value' => array(
'required' => true,
'type' => 'string',
),
),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => 'commentator_bridge_blocklist_remove',
'permission_callback' => 'commentator_bridge_can_manage_options',
'args' => array(
'value' => array(
'required' => true,
'type' => 'string',
),
),
),
)
);
}
/**
* Die Sperrliste ist eine seitenweite Option, kein Kommentarrecht.
*
* Ein Redakteur darf moderieren, aber keine Optionen ändern - das gilt hier
* genauso wie im Backend. Die App fragt die Rechte vorher ab und bietet die
* Sperre gar nicht erst an, wenn sie nicht greifen würde.
*/
function commentator_bridge_can_manage_options(): bool {
return current_user_can( 'manage_options' );
}
/**
* Dieselbe Hürde wie in der Kern-API: Wer keine Kommentare moderieren darf,
* sieht auch hier nichts.
*/
function commentator_bridge_can_moderate(): bool {
return current_user_can( 'moderate_comments' );
}
/**
* Kompakter Zustand für die regelmäßige Prüfung.
*
* Der eigentliche Zweck des Plugins: Statt eine vollständige Kommentarliste
* abzurufen, holt die App drei Werte. Erst wenn sich die neueste Kennung
* geändert hat, lädt sie tatsächlich Kommentare nach.
*/
function commentator_bridge_status(): WP_REST_Response {
// wp_count_comments() ist zwischengespeichert und deshalb günstig.
$counts = wp_count_comments();
list( $latest_id, $latest_date ) = commentator_bridge_latest( 'hold' );
// Zusaetzlich der neueste Kommentar unabhaengig vom Status: Auf Blogs, die
// Kommentare automatisch freischalten, gibt es nie etwas mit Status
// 'hold' - die App wuerde dort sonst nie bemerken, dass ueberhaupt ein
// Kommentar eingegangen ist.
list( $latest_any_id, $latest_any_date ) = commentator_bridge_latest( 'all' );
$response = new WP_REST_Response(
array(
'pending_count' => (int) $counts->moderated,
'latest_comment_id' => $latest_id,
'latest_comment_date_gmt' => $latest_date,
'latest_any_comment_id' => $latest_any_id,
'latest_any_comment_date_gmt' => $latest_any_date,
'plugin_version' => COMMENTATOR_BRIDGE_VERSION,
)
);
// Die Antwort ist naturgemäß flüchtig und darf nicht aus einem Cache kommen.
$response->header( 'Cache-Control', 'no-store, private' );
return $response;
}
/**
* Neuester Kommentar eines Status als Paar aus Kennung und Zeitpunkt.
*
* @param string $status Status im Sinne von WP_Comment_Query.
* @return array{0:int,1:?string}
*/
function commentator_bridge_latest( string $status ): array {
// Sortiert nach Kennung, nicht nach Datum: Die App vergleicht Kennungen,
// um zu entscheiden, ob es etwas Neues gibt. Ein Kommentar mit
// zurueckdatiertem Zeitpunkt - beim Import keine Seltenheit - waere sonst
// der "neueste" und wuerde die Pruefung faelschlich abbrechen lassen.
$latest = get_comments(
array(
'status' => $status,
'number' => 1,
'orderby' => 'comment_ID',
'order' => 'DESC',
'type' => 'comment',
)
);
if ( empty( $latest ) ) {
return array( 0, null );
}
$comment = $latest[0];
return array( (int) $comment->comment_ID, mysql_to_rfc3339( $comment->comment_date_gmt ) );
}
/**
* Kommentaranzahl je Status in einem einzigen Aufruf.
*
* Ohne diesen Endpunkt bräuchte die Filterleiste der App fünf getrennte
* Abfragen, nur um Zahlen anzuzeigen.
*/
function commentator_bridge_summary(): WP_REST_Response {
$counts = wp_count_comments();
$response = new WP_REST_Response(
array(
'counts' => array(
'approve' => (int) $counts->approved,
'hold' => (int) $counts->moderated,
'spam' => (int) $counts->spam,
'trash' => (int) $counts->trash,
// Absichtlich nicht total_comments: Das zaehlt Spam mit.
// WP_Comment_Query versteht unter 'all' genehmigt und offen,
// und genau das listet die REST-API bei status=all auf. Eine
// Zahl, die nicht zur zugehoerigen Liste passt, ist schlimmer
// als keine.
'all' => (int) $counts->approved + (int) $counts->moderated,
),
)
);
$response->header( 'Cache-Control', 'no-store, private' );
return $response;
}
/**
* Wer zum Team gehört, und welche Rollen dafür überhaupt in Frage kommen.
*
* Die App kann das nicht selbst ermitteln: `wp/v2/users` mit `context=edit`
* verlangt `list_users`, und das hat ein Redakteur nicht - also genau das
* Konto, mit dem moderiert wird. Ohne diesen Endpunkt bliebe der App nur, das
* eigene Konto zu erkennen.
*
* Geliefert werden nur Rollen, die Beiträge schreiben dürfen. Abonnenten
* gehören nicht zum Team, und auf großen Blogs wären es Tausende.
*/
function commentator_bridge_team(): WP_REST_Response {
$roles = array();
foreach ( wp_roles()->roles as $slug => $role ) {
$caps = isset( $role['capabilities'] ) ? $role['capabilities'] : array();
$gehoert_dazu = ! empty( $caps['edit_posts'] ) || ! empty( $caps['moderate_comments'] );
if ( $gehoert_dazu ) {
$roles[] = array(
'slug' => (string) $slug,
'name' => translate_user_role( $role['name'] ),
);
}
}
$members = array();
if ( ! empty( $roles ) ) {
$users = get_users(
array(
'role__in' => wp_list_pluck( $roles, 'slug' ),
'number' => COMMENTATOR_BRIDGE_TEAM_LIMIT,
'orderby' => 'ID',
'fields' => array( 'ID' ),
)
);
foreach ( $users as $user ) {
$data = get_userdata( $user->ID );
$members[] = array(
'id' => (int) $user->ID,
'roles' => array_values( (array) $data->roles ),
);
}
}
$response = new WP_REST_Response(
array(
'roles' => $roles,
'members' => $members,
)
);
$response->header( 'Cache-Control', 'no-store, private' );
return $response;
}
/**
* Leert Spam oder Papierkorb endgültig.
*
* Dasselbe, was die Knöpfe „Spam leeren" und „Papierkorb leeren" in der
* Kommentarverwaltung tun. Die Kern-API kennt keine Sammellöschung; ohne
* diesen Endpunkt bräuchte die App eine Anfrage je Kommentar.
*
* Bewusst in Stapeln: Bei einigen tausend Spam-Kommentaren liefe eine einzige
* Anfrage in den Zeitablauf des Webservers. Die Antwort nennt deshalb, wie
* viele noch übrig sind, damit die App weitermachen kann.
*/
function commentator_bridge_empty( WP_REST_Request $request ): WP_REST_Response {
$status = $request->get_param( 'status' );
$ids = get_comments(
array(
'status' => $status,
'number' => COMMENTATOR_BRIDGE_EMPTY_BATCH,
'fields' => 'ids',
)
);
$deleted = 0;
foreach ( $ids as $id ) {
// true = endgültig, nicht erneut in den Papierkorb verschieben.
if ( wp_delete_comment( (int) $id, true ) ) {
++$deleted;
}
}
$counts = wp_count_comments();
$remaining = 'spam' === $status ? (int) $counts->spam : (int) $counts->trash;
$response = new WP_REST_Response(
array(
'deleted' => $deleted,
'remaining' => $remaining,
)
);
$response->header( 'Cache-Control', 'no-store, private' );
return $response;
}
/**
* Liest die Sperrliste aus `disallowed_keys`.
*
* WordPress legt sie als Text mit einem Eintrag je Zeile ab. Ein Kommentar,
* der einen dieser Einträge enthält - in Name, Adresse, Text, URL oder
* IP -, landet direkt im Papierkorb.
*/
function commentator_bridge_blocklist_get(): WP_REST_Response {
$response = new WP_REST_Response( array( 'entries' => commentator_bridge_blocklist_entries() ) );
$response->header( 'Cache-Control', 'no-store, private' );
return $response;
}
function commentator_bridge_blocklist_add( WP_REST_Request $request ) {
$value = trim( (string) $request->get_param( 'value' ) );
// Ein leerer Eintrag würde jeden Kommentar treffen - der Blog wäre für
// Kommentare praktisch geschlossen, ohne dass jemand wüsste warum.
if ( '' === $value ) {
return new WP_Error(
'commentator_blocklist_empty',
__( 'An empty entry is not allowed.', 'commentator-bridge' ),
array( 'status' => 400 )
);
}
$entries = commentator_bridge_blocklist_entries();
if ( ! in_array( $value, $entries, true ) ) {
$entries[] = $value;
commentator_bridge_blocklist_save( $entries );
}
return commentator_bridge_blocklist_get();
}
function commentator_bridge_blocklist_remove( WP_REST_Request $request ): WP_REST_Response {
$value = trim( (string) $request->get_param( 'value' ) );
$entries = commentator_bridge_blocklist_entries();
commentator_bridge_blocklist_save(
array_values(
array_filter(
$entries,
static function ( $entry ) use ( $value ) {
return $entry !== $value;
}
)
)
);
return commentator_bridge_blocklist_get();
}
/**
* @return string[]
*/
function commentator_bridge_blocklist_entries(): array {
$raw = (string) get_option( 'disallowed_keys', '' );
return array_values(
array_filter(
array_map( 'trim', preg_split( '/\r\n|\r|\n/', $raw ) ?: array() ),
static function ( $entry ) {
return '' !== $entry;
}
)
);
}
/**
* @param string[] $entries
*/
function commentator_bridge_blocklist_save( array $entries ): void {
update_option( 'disallowed_keys', implode( "\n", $entries ) );
}
/**
* Hinterlegt eine Push-Adresse für das angemeldete Konto.
*
* Nur HTTPS: Über die Adresse geht zwar kein Inhalt, aber wer mitliest,
* erführe trotzdem, wann der Blog Kommentare bekommt.
*/
function commentator_bridge_push_add( WP_REST_Request $request ) {
if ( ! commentator_bridge_push_enabled() ) {
return new WP_Error(
'commentator_push_disabled',
__( 'Instant notifications are disabled on this site.', 'commentator-bridge' ),
array( 'status' => 403 )
);
}
$endpoint = esc_url_raw( (string) $request->get_param( 'endpoint' ), array( 'https' ) );
if ( '' === $endpoint || ! commentator_bridge_push_endpoint_valid( $endpoint ) ) {
return new WP_Error(
'commentator_invalid_endpoint',
__( 'The push address must be a publicly reachable HTTPS address.', 'commentator-bridge' ),
array( 'status' => 400 )
);
}
$user_id = get_current_user_id();
$endpoints = commentator_bridge_push_endpoints( $user_id );
$endpoints = array_values( array_diff( $endpoints, array( $endpoint ) ) );
$endpoints[] = $endpoint;
$endpoints = array_slice( $endpoints, -COMMENTATOR_BRIDGE_PUSH_LIMIT );
update_user_meta( $user_id, COMMENTATOR_BRIDGE_PUSH_META, $endpoints );
return new WP_REST_Response( array( 'registered' => true ) );
}
function commentator_bridge_push_remove( WP_REST_Request $request ): WP_REST_Response {
$endpoint = (string) $request->get_param( 'endpoint' );
$user_id = get_current_user_id();
$endpoints = commentator_bridge_push_endpoints( $user_id );
$remaining = array_values( array_diff( $endpoints, array( $endpoint ) ) );
if ( empty( $remaining ) ) {
delete_user_meta( $user_id, COMMENTATOR_BRIDGE_PUSH_META );
} else {
update_user_meta( $user_id, COMMENTATOR_BRIDGE_PUSH_META, $remaining );
}
return new WP_REST_Response( array( 'removed' => count( $endpoints ) !== count( $remaining ) ) );
}
/**
* Schickt an alle Adressen des angemeldeten Kontos einen Testweckruf und
* wartet dabei auf die Antwort des Push-Servers - anders als im Betrieb:
* Hier ist gerade die Frage, ob er ankommt.
*/
function commentator_bridge_push_test(): WP_REST_Response {
return new WP_REST_Response( commentator_bridge_push_test_user( get_current_user_id() ) );
}
/** @return array{sent: int, failed: int} */
function commentator_bridge_push_test_user( int $user_id ): array {
$sent = 0;
$failed = 0;
if ( commentator_bridge_push_enabled() ) {
foreach ( commentator_bridge_push_endpoints( $user_id ) as $endpoint ) {
$response = commentator_bridge_push_send( $endpoint, 'test', 'high', true );
$code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
if ( $code >= 200 && $code < 300 ) {
++$sent;
} else {
++$failed;
}
}
}
return array(
'sent' => $sent,
'failed' => $failed,
);
}
/** Ob die Sofortmeldung auf diesem Blog erlaubt ist. */
function commentator_bridge_push_enabled(): bool {
return ! ( defined( 'COMMENTATOR_BRIDGE_DISABLE_PUSH' ) && COMMENTATOR_BRIDGE_DISABLE_PUSH );
}
/** Ob Push-Server im eigenen Netz erlaubt sind. Voreingestellt: nein. */
function commentator_bridge_push_allow_local(): bool {
return (bool) apply_filters( 'commentator_bridge_push_allow_local', false );
}
/**
* Prüft eine Push-Adresse: HTTPS, öffentlich erreichbar - sonst ließe sich
* der Blog als Sprungbrett ins eigene Netz benutzen -, und was der Filter
* commentator_bridge_push_endpoint_allowed dazu sagt.
*/
function commentator_bridge_push_endpoint_valid( string $endpoint ): bool {
if ( 'https' !== wp_parse_url( $endpoint, PHP_URL_SCHEME ) ) {
return false;
}
$port = wp_parse_url( $endpoint, PHP_URL_PORT );
if ( null !== $port && 443 !== (int) $port ) {
return false;
}
$host = (string) wp_parse_url( $endpoint, PHP_URL_HOST );
if ( '' === $host ) {
return false;
}
if ( ! commentator_bridge_push_allow_local() && ! commentator_bridge_push_host_public( $host ) ) {
return false;
}
return (bool) apply_filters( 'commentator_bridge_push_endpoint_allowed', true, $endpoint );
}
/**
* Ob ein Host ausschließlich auf öffentliche Adressen zeigt.
*
* Eigene Prüfung statt wp_http_validate_url(): Die löst nur über IPv4 auf
* (gethostbyname) und hält einen Push-Server, der nur per IPv6 erreichbar ist
* - typisch für einen eigenen ntfy hinter Carrier-Grade-NAT -, für ungültig.
* Hier zählen A- und AAAA-Einträge; jede Adresse muss öffentlich sein, sonst
* ließe sich der Blog als Sprungbrett ins eigene Netz benutzen.
*/
function commentator_bridge_push_host_public( string $host ): bool {
$host = trim( $host, '[]' );
if ( filter_var( $host, FILTER_VALIDATE_IP ) ) {
$ips = array( $host );
} else {
$ips = array();
$records = @dns_get_record( $host, DNS_A | DNS_AAAA ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
foreach ( is_array( $records ) ? $records : array() as $record ) {
if ( isset( $record['ip'] ) ) {
$ips[] = $record['ip'];
} elseif ( isset( $record['ipv6'] ) ) {
$ips[] = $record['ipv6'];
}
}
}
if ( empty( $ips ) ) {
return false;
}
foreach ( $ips as $ip ) {
if ( ! filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) {
return false;
}
}
return true;
}
/**
* Der eine Weg, auf dem das Plugin nach außen sendet.
*
* @return array|WP_Error
*/
function commentator_bridge_push_send( string $endpoint, string $body, string $urgency, bool $blocking ) {
$args = array(
'body' => $body,
'blocking' => $blocking,
'timeout' => 5,
'headers' => array(
'Content-Type' => 'text/plain',
// Web-Push-Kopfzeilen, die auch ntfy versteht: höchstens eine
// Stunde vorhalten - was später käme, holt die regelmäßige
// Prüfung ohnehin ein.
'TTL' => '3600',
'Urgency' => $urgency,
),
);
// Vor jedem Versand erneut geprüft: Zeigt der Name inzwischen ins eigene
// Netz, geht nichts hinaus. wp_safe_remote_post() scheidet aus, es prüft
// wie wp_http_validate_url() nur IPv4.
if ( ! commentator_bridge_push_endpoint_valid( $endpoint ) ) {
return new WP_Error( 'commentator_invalid_endpoint', 'Push endpoint not allowed.' );
}
return wp_remote_post( $endpoint, $args );
}
/** @return string[] */
function commentator_bridge_push_endpoints( int $user_id ): array {
$stored = get_user_meta( $user_id, COMMENTATOR_BRIDGE_PUSH_META, true );
return is_array( $stored ) ? array_values( array_filter( $stored, 'is_string' ) ) : array();
}
/**
* Weckt die Apps der Moderatoren, sobald ein Kommentar eingeht.
*
* An wp_insert_comment und nicht an comment_post: comment_post feuert nur
* für das Kommentarformular der Website. Kommentare über die REST-API, aus
* anderen Plugins oder von wp-cli kämen sonst nie an.
*
* Als Spam Erkanntes weckt niemanden, und niemand wird über den eigenen
* Kommentar geweckt - etwa die Antwort, die er gerade aus der App geschickt
* hat. Gesendet wird nicht blockierend: Wer gerade kommentiert, soll nicht
* auf einen Push-Server warten. Der Rumpf ist absichtlich bedeutungslos - die
* App prüft danach selbst.
*
* @param int $comment_id
* @param WP_Comment $comment
*/
function commentator_bridge_push_new_comment( $comment_id, $comment ): void {
if ( ! $comment instanceof WP_Comment ) {
return;
}
$approved = (string) $comment->comment_approved;
if ( 'spam' === $approved || 'trash' === $approved ) {
return;
}
commentator_bridge_push_wake( (int) $comment->user_id, 'new', 'high', false );
}
/**
* Weckt die Apps, wenn sich der Status eines Kommentars ändert.
*
* Damit verschwindet die Benachrichtigung zu einem im Backend erledigten
* Kommentar sofort. Kommt die Änderung aus der App selbst, hat die sie schon
* zurückgenommen; ein Weckruf löste dann nur eine überflüssige Prüfung aus.
*
* @param string $new_status
* @param string $old_status
* @param WP_Comment $comment
*/
function commentator_bridge_push_status_change( $new_status, $old_status, $comment ): void {
if ( $new_status === $old_status || ! $comment instanceof WP_Comment ) {
return;
}
$agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? (string) $_SERVER['HTTP_USER_AGENT'] : '';
if ( 0 === strpos( $agent, 'Commentator/' ) ) {
return;
}
commentator_bridge_push_wake( 0, 'status', 'normal', true );
}
/**
* Schickt den Weckruf an die hinterlegten Adressen aller Moderatoren.
*
* [$skip_user_id] wird nicht geweckt - niemand braucht eine Meldung über den
* eigenen Kommentar. Mit [$throttle] geht an eine Adresse höchstens alle
* COMMENTATOR_BRIDGE_PUSH_STATUS_GAP Sekunden ein Weckruf. Gesendet wird
* nicht blockierend: Wer gerade kommentiert oder moderiert, soll nicht auf
* einen Push-Server warten.
*/
function commentator_bridge_push_wake( int $skip_user_id, string $body, string $urgency, bool $throttle ): void {
if ( ! commentator_bridge_push_enabled() ) {
return;
}
$users = get_users(
array(
'meta_key' => COMMENTATOR_BRIDGE_PUSH_META, // phpcs:ignore WordPress.DB.SlowDBQuery
'fields' => 'ID',
)
);
foreach ( $users as $user_id ) {
if ( (int) $user_id === $skip_user_id || ! user_can( (int) $user_id, 'moderate_comments' ) ) {
continue;
}
foreach ( commentator_bridge_push_endpoints( (int) $user_id ) as $endpoint ) {
if ( $throttle ) {
$key = 'commentator_push_' . md5( $endpoint );
if ( get_transient( $key ) ) {
continue;
}
set_transient( $key, 1, COMMENTATOR_BRIDGE_PUSH_STATUS_GAP );
}
commentator_bridge_push_queue( $endpoint, $body, $urgency );
}
}
}
/** Option mit dem Ergebnis des letzten Weckrufs - zur Fehlersuche im Profil. */
const COMMENTATOR_BRIDGE_PUSH_LAST = 'commentator_bridge_push_last';
/**
* Merkt einen Weckruf vor; verschickt wird am Ende der Anfrage.
*
* WordPress' "nicht blockierender" Versand wartet trotzdem auf den
* Verbindungsaufbau und gibt nach dem Timeout still auf. Zu einem eigenen
* Server über IPv6 dauerte das auf dem Live-Blog zu lange: Der Weckruf zu
* einem neuen Kommentar kam nie an, und niemand sah es. Deshalb wird hier
* gesammelt, je Adresse höchstens einmal, und erst beim Herunterfahren der
* Anfrage blockierend verschickt - mit Antwort, die festgehalten wird.
*/
function commentator_bridge_push_queue( string $endpoint, string $body, string $urgency ): void {
global $commentator_bridge_push_pending;
if ( ! is_array( $commentator_bridge_push_pending ) ) {
$commentator_bridge_push_pending = array();
add_action( 'shutdown', 'commentator_bridge_push_flush', 1000 );
}
// Ein neuer Kommentar hat Vorrang vor einer Statusänderung.
if ( ! isset( $commentator_bridge_push_pending[ $endpoint ] ) || 'new' === $body ) {
$commentator_bridge_push_pending[ $endpoint ] = array( $body, $urgency );
}
}
/**
* Verschickt die vorgemerkten Weckrufe.
*
* Wo PHP-FPM es erlaubt, geht die Antwort an den Besucher vorher hinaus; sonst
* wartet er die wenigen hundert Millisekunden mit.
*/
function commentator_bridge_push_flush(): void {
global $commentator_bridge_push_pending;
if ( empty( $commentator_bridge_push_pending ) ) {
return;
}
$pending = $commentator_bridge_push_pending;
$commentator_bridge_push_pending = array();
if ( function_exists( 'fastcgi_finish_request' ) ) {
fastcgi_finish_request();
}
$results = array();
foreach ( $pending as $endpoint => list( $body, $urgency ) ) {
$start = microtime( true );
$response = commentator_bridge_push_send( $endpoint, $body, $urgency, true );
$results[] = array(
'server' => (string) wp_parse_url( $endpoint, PHP_URL_HOST ),
'code' => is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response ),
'error' => is_wp_error( $response ) ? $response->get_error_message() : '',
'duration' => round( microtime( true ) - $start, 2 ),
);
}
update_option(
COMMENTATOR_BRIDGE_PUSH_LAST,
array(
'time' => time(),
'trigger' => $body,
'results' => $results,
),
false
);
}
/**
* Abschnitt im Benutzerprofil: wohin dieser Blog Weckrufe schickt.
*
* Nur zur Übersicht und zum Aufräumen - angelegt werden die Adressen von der
* App. Gezeigt wird der Server und das Ende des Themas, nicht die ganze
* Adresse: Wer sie kennt, kann das Telefon wecken.
*/
function commentator_bridge_profile_section( WP_User $user ): void {
if ( ! user_can( $user, 'moderate_comments' ) || ! current_user_can( 'edit_user', $user->ID ) ) {
return;
}
$endpoints = commentator_bridge_push_endpoints( (int) $user->ID );
$notice = isset( $_GET['commentator_push'] ) ? sanitize_key( wp_unslash( $_GET['commentator_push'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
?>
<h2 id="commentator-push"><?php esc_html_e( 'Commentator: instant notifications', 'commentator-bridge' ); ?></h2>
<?php if ( 'removed' === $notice ) : ?>
<p><strong><?php esc_html_e( 'The address has been removed.', 'commentator-bridge' ); ?></strong></p>
<?php elseif ( 0 === strpos( $notice, 'tested' ) ) : ?>
<?php $parts = explode( '_', $notice ); ?>
<p><strong>
<?php
printf(
/* translators: 1: number of accepted test wake-ups, 2: number of rejected ones */
esc_html__( 'Test wake-up: %1$d accepted, %2$d rejected.', 'commentator-bridge' ),
(int) ( $parts[1] ?? 0 ),
(int) ( $parts[2] ?? 0 )
);
?>
</strong>
<?php esc_html_e( 'Accepted means the push server took it. Whether it reaches the phone is shown there by a notification from Commentator.', 'commentator-bridge' ); ?></p>
<?php endif; ?>
<?php if ( ! commentator_bridge_push_enabled() ) : ?>
<p><?php esc_html_e( 'Instant notifications are disabled on this site.', 'commentator-bridge' ); ?> (<code>COMMENTATOR_BRIDGE_DISABLE_PUSH</code>)</p>
<?php elseif ( empty( $endpoints ) ) : ?>
<p><?php esc_html_e( 'No devices registered. Instant notifications are set up in the Commentator app, in the settings of this blog.', 'commentator-bridge' ); ?></p>
<?php else : ?>
<p><?php esc_html_e( 'On every new comment and every status change, these addresses receive a wake-up call without any content.', 'commentator-bridge' ); ?></p>
<table class="widefat striped" style="max-width:40em">
<tbody>
<?php foreach ( $endpoints as $endpoint ) : ?>
<tr>
<td><code><?php echo esc_html( commentator_bridge_push_label( $endpoint ) ); ?></code></td>
<td style="text-align:right">
<a class="button" href="<?php echo esc_url( commentator_bridge_profile_action_url( 'commentator_push_remove', (int) $user->ID, $endpoint ) ); ?>"><?php esc_html_e( 'Remove', 'commentator-bridge' ); ?></a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<p><a class="button" href="<?php echo esc_url( commentator_bridge_profile_action_url( 'commentator_push_test', (int) $user->ID ) ); ?>"><?php esc_html_e( 'Send test wake-up', 'commentator-bridge' ); ?></a></p>
<?php commentator_bridge_profile_last_wake(); ?>
<?php endif; ?>
<?php
}
/** Ergebnis des letzten Weckrufs, damit sich ein Ausbleiben nachvollziehen lässt. */
function commentator_bridge_profile_last_wake(): void {
$last = get_option( COMMENTATOR_BRIDGE_PUSH_LAST );
if ( ! is_array( $last ) || empty( $last['results'] ) ) {
return;
}
$when = wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (int) $last['time'] );
echo '<p class="description">';
printf(
/* translators: %s: date and time */
esc_html__( 'Last wake-up: %s', 'commentator-bridge' ),
esc_html( $when )
);
foreach ( $last['results'] as $result ) {
echo '<br><code>', esc_html( $result['server'] ), '</code> – ';
if ( $result['code'] >= 200 && $result['code'] < 300 ) {
printf(
/* translators: 1: HTTP status code, 2: duration in seconds */
esc_html__( 'delivered (HTTP %1$d, %2$s s)', 'commentator-bridge' ),
(int) $result['code'],
esc_html( number_format_i18n( (float) $result['duration'], 2 ) )
);
} else {
printf(
/* translators: %s: error message or HTTP status */
esc_html__( 'failed: %s', 'commentator-bridge' ),
esc_html( '' !== $result['error'] ? $result['error'] : 'HTTP ' . (int) $result['code'] )
);
}
}
echo '</p>';
}
/** Server und Ende des Themas, etwa "ntfy.sh … x8Kq2a". */
function commentator_bridge_push_label( string $endpoint ): string {
$host = (string) wp_parse_url( $endpoint, PHP_URL_HOST );
$path = (string) wp_parse_url( $endpoint, PHP_URL_PATH );
return $host . ' … ' . substr( $path, -6 );
}
function commentator_bridge_profile_action_url( string $action, int $user_id, string $endpoint = '' ): string {
$args = array(
'action' => $action,
'user_id' => $user_id,
);
if ( '' !== $endpoint ) {
$args['endpoint'] = md5( $endpoint );
}
return wp_nonce_url( add_query_arg( $args, admin_url( 'admin-post.php' ) ), $action . '_' . $user_id );
}
/** Prüft Nonce und Recht und liefert das betroffene Konto. */
function commentator_bridge_profile_target( string $action ): int {
$user_id = isset( $_GET['user_id'] ) ? absint( $_GET['user_id'] ) : 0;
check_admin_referer( $action . '_' . $user_id );
if ( ! $user_id || ! current_user_can( 'edit_user', $user_id ) ) {
wp_die( esc_html__( 'You are not allowed to do this.', 'commentator-bridge' ), 403 );
}
return $user_id;
}
function commentator_bridge_profile_back( int $user_id, string $notice ): void {
wp_safe_redirect( add_query_arg( 'commentator_push', $notice, get_edit_user_link( $user_id ) ) . '#commentator-push' );
exit;
}
function commentator_bridge_profile_remove(): void {
$user_id = commentator_bridge_profile_target( 'commentator_push_remove' );
$hash = isset( $_GET['endpoint'] ) ? sanitize_key( wp_unslash( $_GET['endpoint'] ) ) : '';
$keep = array_values(
array_filter(
commentator_bridge_push_endpoints( $user_id ),
static function ( string $endpoint ) use ( $hash ): bool {
return md5( $endpoint ) !== $hash;
}
)
);
if ( empty( $keep ) ) {
delete_user_meta( $user_id, COMMENTATOR_BRIDGE_PUSH_META );
} else {
update_user_meta( $user_id, COMMENTATOR_BRIDGE_PUSH_META, $keep );
}
commentator_bridge_profile_back( $user_id, 'removed' );
}