-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathConnector.php
More file actions
1377 lines (1242 loc) · 44 KB
/
Copy pathConnector.php
File metadata and controls
1377 lines (1242 loc) · 44 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
/**
* MyDot Connector Class
*
* Provides connection and product information for MyDot license management integration.
*
* @package Accessibility_Checker
* @since 1.xx.x
*/
namespace EqualizeDigital\AccessibilityChecker\MyDot;
use EqualizeDigital\AccessibilityChecker\Admin\AdminPage\ConnectedServicesPage;
use EqualizeDigital\AccessibilityChecker\SystemInfo\SystemInfo;
/**
* Class Connector
*
* Handles MyDot product and license integration constants and utilities.
*
* @since 1.xx.x
*/
class Connector {
/**
* The product name used in MyDot licensing system.
*
* @since 1.xx.x
*
* @var string
*/
const PRODUCT_NAME = 'Accessibility Checker Free';
/**
* The default MyDot API endpoint for license validation.
*
* @since 1.xx.x
*
* @var string
*/
const API_ENDPOINT = 'https://my.equalizedigital.com';
/**
* The product ID used in MyDot licensing system.
*
* @since 1.xx.x
*
* @var int
*/
const PRODUCT_ID = 1666;
/**
* TTL for transient-based admin notices (seconds).
*/
private const NOTICE_TRANSIENT_TTL = 60;
/**
* License metadata option: stores inferred license state from EDD responses.
*
* This is not raw response data; it's processed/inferred state that combines:
* - License type inference (free vs pro) based on product_id, item_name, or source context
* - License level inference (single-site, multi-site, unlimited, lifetime) from license_limit
* - Formatted/sanitized response fields (expires, site_count, activations_left, etc.)
*
* Single option (not scattered across multiple wp_options for better atomicity).
*
* @var string
*/
private const LICENSE_METADATA_OPTION = 'edac_license_metadata';
/**
* License status constants.
*/
private const LICENSE_STATUS_VALID = 'valid';
private const LICENSE_STATUS_EXPIRED = 'expired';
private const LICENSE_STATUS_UNKNOWN = 'unknown';
/**
* License type constants.
*/
private const LICENSE_TYPE_FREE = 'free';
private const LICENSE_TYPE_PRO = 'pro';
private const LICENSE_TYPE_UNKNOWN = 'unknown';
/**
* License level constants.
*/
private const LICENSE_LEVEL_SINGLE_SITE = 'single-site';
private const LICENSE_LEVEL_MULTI_SITE = 'multi-site';
private const LICENSE_LEVEL_UNLIMITED = 'unlimited';
private const LICENSE_LEVEL_LIFETIME = 'lifetime';
private const LICENSE_LEVEL_UNKNOWN = 'unknown';
/**
* Determine whether enrollment should use the filtered product ID.
*
* We only use Pro product context when Pro is active and licensed.
*
* @return bool
*/
private static function should_use_filtered_product_id_for_enrollment(): bool {
return defined( 'EDACP_VERSION' ) && 'valid' === get_option( 'edacp_license_status' );
}
/**
* Determine whether Pro should be the sole authority for license checks.
*
* Pro is authoritative whenever the Pro plugin is loaded and a non-empty
* license key is present. Free license checks are fully suppressed in this
* state so that both plugins cannot write conflicting status values to the
* database simultaneously. Pro's own cron handles all revalidation; Free
* never needs to re-run alongside it.
*
* @return bool
*/
private static function is_pro_license_check_active(): bool {
if ( ! defined( 'EDACP_VERSION' ) ) {
return false;
}
return '' !== trim( (string) get_option( 'edacp_license_key', '' ) );
}
/**
* Expose the free product ID via a filter so other plugins (e.g. Pro) can
* read it when inferring license type from API response product IDs.
*
* @return int
*/
public static function get_free_product_id(): int {
return self::PRODUCT_ID;
}
/**
* Sets up the license page and handlers.
*
* @since 1.xx.x
*/
public function init() {
$connected_services = new ConnectedServicesPage( 'manage_options' );
$connected_services->add_page();
// Expose the free product ID so the Pro plugin can infer license type from API response product IDs.
add_filter( 'edac_free_product_id', [ __CLASS__, 'get_free_product_id' ] );
// Ensure the license options group is registered so options.php allows saves.
add_action( 'admin_init', [ $this, 'register_license_settings' ] );
// Admin-post handler for license activate/deactivate.
add_action( 'admin_post_edac_license', [ $this, 'handle_license_post' ] );
// Schedule periodic license checks.
add_action( 'init', [ $this, 'check_license_cron' ] );
add_action( 'edac_check_license_hook', [ $this, 'periodic_check_license' ] );
// The admin-post handlers for register/unregister buttons.
add_action( 'admin_post_edac_jwt_register', [ $this, 'handle_jwt_register_post' ] );
add_action( 'admin_post_edac_jwt_unregister', [ $this, 'handle_jwt_unregister_post' ] );
// When the pro license is deactivated, unregister the site to avoid orphaned registrations.
add_action( 'edacp_license_deactivated', [ $this, 'handle_site_unregistration' ], 10, 3 );
// When a Pro license is activated on an already-connected site, refresh registration
// so enrollment context is updated for Pro.
add_action( 'edacp_license_activated', [ $this, 'handle_pro_license_activation' ], 10, 3 );
add_action(
'in_admin_header',
function () {
// Display transient-backed admin notices after redirects.
add_action( 'admin_notices', [ $this, 'display_admin_notices' ] );
},
1000
);
}
/**
* Register license settings so the edac_license group is allowed by options.php.
*
* @since 1.xx.x
*
* @return void
*/
public function register_license_settings() {
register_setting(
'edac_license',
'edacp_license_key',
[
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
]
);
register_setting(
'edac_license',
'edac_license_status',
[
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
]
);
register_setting(
'edac_license',
'edac_license_error',
[
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
]
);
}
/**
* Handle license activate/deactivate from admin-post.
*
* @since 1.xx.x
*
* @return void
*/
public function handle_license_post() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to manage this license.', 'accessibility-checker' ) );
}
check_admin_referer( 'edac_license_nonce', 'edac_license_nonce' );
// Normalize license key from the form.
if ( isset( $_POST['edacp_license_key'] ) ) {
$license = sanitize_text_field( wp_unslash( $_POST['edacp_license_key'] ) );
update_option( 'edacp_license_key', $license );
}
if ( isset( $_POST['edac_license_activate'] ) ) {
$this->activate_license();
} elseif ( isset( $_POST['edac_license_deactivate'] ) ) {
$this->deactivate_license();
}
$redirect = wp_get_referer();
if ( ! $redirect ) {
$redirect = admin_url();
}
wp_safe_redirect( $redirect );
exit;
}
/**
* Activate the license via API and store status/error.
*
* @since 1.xx.x
*
* @return void
*/
private function activate_license() {
// Pro is authoritative whenever its license check flow is active.
if ( self::is_pro_license_check_active() ) {
update_option( 'edac_license_error', __( 'Pro license management is active. Please manage your license from Accessibility Checker Pro.', 'accessibility-checker' ) );
return;
}
$license = trim( get_option( 'edacp_license_key' ) );
if ( empty( $license ) ) {
update_option( 'edac_license_error', 'missing' );
return;
}
$api_params = [
'edd_action' => 'activate_license',
'license' => $license,
'item_id' => self::PRODUCT_ID,
'url' => home_url(),
];
$api_params = array_merge( $api_params, SystemInfo::get_license_request_context() );
$response = wp_remote_post(
self::get_api_endpoint(),
[
'timeout' => 15, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout -- accommodation for slow hosting environments.
'sslverify' => self::verify_ssl(),
'body' => $api_params,
]
);
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
$message = is_wp_error( $response ) ? $response->get_error_message() : esc_html__( 'An error occurred, please try again.', 'accessibility-checker' );
update_option( 'edac_license_error', $message );
return;
}
$license_data = json_decode( wp_remote_retrieve_body( $response ) );
self::store_license_metadata_from_response( $license_data, 'free' );
if ( isset( $license_data->error ) ) {
update_option( 'edac_license_error', $license_data->error );
update_option( 'edac_license_status', $license_data->license ?? '' );
return;
}
delete_option( 'edac_license_error' );
update_option( 'edac_license_status', $license_data->license ?? '' );
// Automatically register the site after successful license activation.
if ( 'valid' === ( $license_data->license ?? '' ) ) {
$this->handle_site_registration();
// Always clear fallback marker when license recovers to valid state,
// regardless of whether registration succeeded. License validity and
// registration status are independent concerns (license = key validity,
// registration = reports feature). The registration can be retried separately.
delete_option( 'edac_fallback_active' );
}
}
/**
* Clear all license and enrollment state.
*
* Called when deactivating or removing a license to ensure a clean slate.
*
* @return void
*/
private static function clear_all_license_state(): void {
delete_option( 'edacp_license_key' );
delete_option( 'edacp_license_status' );
delete_option( 'edacp_license_error' );
delete_option( 'edac_license_status' );
delete_option( 'edac_license_error' );
self::clear_stored_license_metadata();
self::clear_report_connection_state();
delete_option( 'edac_fallback_active' );
}
/**
* Clear report-connection specific state only.
*
* @return void
*/
private static function clear_report_connection_state(): void {
delete_option( 'edac_jwt_public_key' );
delete_option( 'edac_site_id' );
delete_option( 'edac_collection_interval_days' );
delete_option( 'edac_next_collection' );
}
/**
* Clear free-authority license state while preserving active Pro status.
*
* @return void
*/
private static function clear_free_disconnect_license_state(): void {
delete_option( 'edacp_license_key' );
delete_option( 'edac_license_status' );
delete_option( 'edac_license_error' );
self::clear_stored_license_metadata();
delete_option( 'edac_fallback_active' );
}
/**
* Determine whether an unregister action should preserve current license state.
*
* Active Pro licenses should remain active when only disabling reports.
*
* @return bool
*/
private static function should_preserve_license_on_unregistration(): bool {
return defined( 'EDACP_VERSION' ) && self::LICENSE_STATUS_VALID === get_option( 'edacp_license_status' );
}
/**
* Deactivate the license via API and always clear local stored values.
*
* @since 1.xx.x
*
* @return void
*/
private function deactivate_license() {
$license = trim( get_option( 'edacp_license_key' ) );
if ( empty( $license ) ) {
self::clear_all_license_state();
return;
}
// Best effort unregister: do not block local disconnect on remote failures.
$site_id = (string) get_option( 'edac_site_id' );
if ( '' !== $site_id ) {
self::unregister_site( $site_id, get_site_url(), $license );
}
$api_params = [
'edd_action' => 'deactivate_license',
'license' => $license,
'item_name' => rawurlencode( self::PRODUCT_NAME ),
'url' => home_url(),
];
wp_remote_post(
self::get_api_endpoint(),
[
'timeout' => 15, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout -- accommodation for slow hosting environments.
'sslverify' => self::verify_ssl(),
'body' => $api_params,
]
);
// Remote deactivation is a best effort. Intentionally clear local
// state regardless of API response so users can always disconnect.
self::clear_all_license_state();
}
/**
* License check
*
* Also includes proactive JWT public key verification as part of key rotation strategy.
*
* Bails early if the pro plugin (EDACP) is enabled to let it handle license checking.
*
* @return void
*/
public function periodic_check_license() {
// Pro is authoritative whenever its own license check flow is active.
if ( self::is_pro_license_check_active() ) {
return;
}
$license = trim( get_option( 'edacp_license_key' ) );
if ( ! $license ) {
return;
}
$api_params = [
'edd_action' => 'check_license',
'license' => $license,
'item_id' => self::PRODUCT_ID,
'item_name' => rawurlencode( self::PRODUCT_NAME ),
'url' => home_url(),
'edac_version' => defined( 'EDAC_VERSION' ) ? EDAC_VERSION : '0.0.0',
];
$api_params = array_merge( $api_params, SystemInfo::get_license_request_context() );
// Call the custom API.
$response = wp_remote_post(
self::get_api_endpoint(),
[
'timeout' => 15, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout -- 15 seconds is needed for now.
'sslverify' => self::verify_ssl(),
'body' => $api_params,
]
);
if ( is_wp_error( $response ) ) {
// this is a silent failure, we should log this or flag it somehow.
return;
}
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
// this is a silent failure, we should log this or flag it somehow.
return;
}
$license_data = json_decode( wp_remote_retrieve_body( $response ) );
self::store_license_metadata_from_response( $license_data, 'free' );
if ( isset( $license_data->license ) ) {
update_option( 'edac_license_status', $license_data->license );
if ( 'valid' === $license_data->license ) {
// License has recovered to valid, so clear error notices and fallback marker.
delete_option( 'edac_license_error' );
delete_option( 'edacp_license_error' );
// Free revalidated successfully after fallback; remove the temporary
// fallback marker so UI can reflect connected state again.
delete_option( 'edac_fallback_active' );
} elseif ( 'expired' === $license_data->license ) {
// License expired: set the error option so admin notices fire on the next page load.
update_option( 'edac_license_error', 'expired' );
}
}
// Verify and update JWT public key daily before validation fails.
// This ensures the site always has the latest key from the issuer without any downtime.
self::verify_and_update_public_key();
}
/**
* License check cron schedule
*
* @return void
*/
public function check_license_cron() {
if ( self::is_pro_license_check_active() ) {
wp_clear_scheduled_hook( 'edac_check_license_hook' );
return;
}
if ( ! wp_next_scheduled( 'edac_check_license_hook' ) ) {
wp_schedule_event( time(), 'daily', 'edac_check_license_hook' );
}
}
/**
* Determines whether to verify SSL for licensing requests.
*
* Can be disabled by returning `false` to the `edac_verify_ssl_for_licensing` filter.
*
* @since 1.xx.x
*
* @return bool Whether to verify SSL. Defaults to `true`.
*/
public static function verify_ssl() {
return (bool) apply_filters( 'edac_verify_ssl_for_licensing', true );
}
/**
* Get the MyDot API endpoint.
*
* Can be overridden by filtering the value with the `edac_mydot_api_endpoint` filter.
*
* @since 1.xx.x
*
* @return string The API endpoint URL (with protocol). Defaults to `https://my.equalizedigital.com`.
*/
public static function get_api_endpoint() {
/**
* Filters the MyDot API endpoint URL.
*
* @since 1.xx.x
*
* @param string $default The default or environment-overridden API endpoint URL.
*/
return apply_filters( 'edac_mydot_api_endpoint', self::API_ENDPOINT );
}
/**
* Get the MyDot product ID.
*
* Can be overridden by filtering the value with the `edac_mydot_product_id` filter.
*
* @since 1.xx.x
*
* @return int The product ID. Defaults to 1666.
*/
public static function get_product_id(): int {
/**
* Filters the MyDot product ID.
*
* @since 1.xx.x
*
* @param int $default The default product ID.
*/
return (int) apply_filters( 'edac_mydot_product_id', self::PRODUCT_ID );
}
/**
* Get the active license key.
*
* Both free and pro plugins store their license key in the same option 'edacp_license_key'.
* The actual product type (free vs pro) is determined by the EDD response item_id at activation
* time and stored in the metadata. This function simply retrieves the key itself.
*
* @return string The license key or empty string if none stored.
*
* @since 1.xx.x
*/
public static function get_license_key(): string {
return (string) get_option( 'edacp_license_key', '' );
}
/**
* Handle admin-post for site registration (button on License page).
*
* @since 1.xx.x
*
* @return void
*/
public function handle_jwt_register_post() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to register this site.', 'accessibility-checker' ) );
}
check_admin_referer( 'edac_jwt_register', 'edac_jwt_register_nonce' );
$this->handle_site_registration();
$redirect = wp_get_referer();
if ( ! $redirect ) {
$redirect = admin_url();
}
wp_safe_redirect( $redirect );
exit;
}
/**
* Handle admin-post for site unregistration (button on License page).
*
* @since 1.xx.x
*
* @return void
*/
public function handle_jwt_unregister_post() {
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to unregister this site.', 'accessibility-checker' ) );
}
check_admin_referer( 'edac_jwt_unregister', 'edac_jwt_unregister_nonce' );
$this->handle_site_unregistration();
$redirect = wp_get_referer();
if ( ! $redirect ) {
$redirect = admin_url();
}
wp_safe_redirect( $redirect );
exit;
}
/**
* Handle the site registration process including UI feedback.
*
* @since 1.xx.x
*
* @return bool True when registration succeeded and state was saved.
*/
private function handle_site_registration(): bool {
$license_key = self::get_license_key();
if ( empty( $license_key ) ) {
set_transient(
$this->get_notice_transient_key(),
[
'type' => 'error',
'message' => __( 'No license key found. Please activate a license before registering your site.', 'accessibility-checker' ),
],
self::NOTICE_TRANSIENT_TTL
);
return false;
}
$site_url = site_url();
$site_name = get_bloginfo( 'name' );
$response_data = self::register_site( $license_key, $site_url, $site_name, true, true );
if ( empty( $response_data['success'] ) ) {
$error_msg = ! empty( $response_data['message'] ) ? $response_data['message'] : __( 'Unknown error occurred while registering the site.', 'accessibility-checker' );
set_transient(
$this->get_notice_transient_key(),
[
'type' => 'error',
'message' => $error_msg,
],
self::NOTICE_TRANSIENT_TTL
);
return false;
}
if ( isset( $response_data['data'] ) ) {
$data = $response_data['data'];
if ( ! empty( $data['jwt_public_key'] ) ) {
update_option( 'edac_jwt_public_key', $data['jwt_public_key'] );
}
if ( ! empty( $data['site_id'] ) ) {
update_option( 'edac_site_id', $data['site_id'] );
}
if ( ! empty( $data['collection_interval_days'] ) ) {
update_option( 'edac_collection_interval_days', $data['collection_interval_days'] );
}
if ( ! empty( $data['next_collection'] ) ) {
update_option( 'edac_next_collection', $data['next_collection'] );
}
set_transient(
$this->get_notice_transient_key(),
[
'type' => 'success',
'message' => __( 'Site registered successfully. Your site is now configured to use additional accessibility services.', 'accessibility-checker' ),
],
self::NOTICE_TRANSIENT_TTL
);
return true;
} else {
set_transient(
$this->get_notice_transient_key(),
[
'type' => 'warning',
'message' => __( 'Site registration completed, but the response data was not in the expected format. Some features may not work correctly.', 'accessibility-checker' ),
],
self::NOTICE_TRANSIENT_TTL
);
return false;
}
}
/**
* Refresh enrollment after Pro activation when the site is already connected.
*
* This keeps backend enrollment context aligned on free->pro upgrades without
* requiring users to manually disconnect/reconnect reports.
*
* @param string $license Activated license key.
* @param string $url Site URL from activation hook.
* @param object|null $license_data Activation response payload.
* @return void
*/
public function handle_pro_license_activation( $license = '', $url = '', $license_data = null ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Hook signature intentionally accepts action args for compatibility.
$site_id = (string) get_option( 'edac_site_id', '' );
if ( '' === $site_id ) {
return;
}
$license_key = self::get_license_key();
if ( '' === $license_key ) {
return;
}
$response_data = self::register_site( $license_key, site_url(), get_bloginfo( 'name' ), true, true );
if ( empty( $response_data['success'] ) || empty( $response_data['data'] ) ) {
return;
}
$data = $response_data['data'];
if ( ! empty( $data['jwt_public_key'] ) ) {
update_option( 'edac_jwt_public_key', $data['jwt_public_key'] );
}
if ( ! empty( $data['site_id'] ) ) {
update_option( 'edac_site_id', $data['site_id'] );
}
if ( ! empty( $data['collection_interval_days'] ) ) {
update_option( 'edac_collection_interval_days', $data['collection_interval_days'] );
}
if ( ! empty( $data['next_collection'] ) ) {
update_option( 'edac_next_collection', $data['next_collection'] );
}
}
/**
* Handle the site unregistration process including UI feedback.
*
* @since 1.xx.x
*
* @param string $license Optional license key passed from deactivation hooks.
* @param string $url Optional site URL from deactivation hooks.
* @param object|null $license_data Optional license payload from deactivation hooks.
*
* @return void
*/
public function handle_site_unregistration( $license = '', $url = '', $license_data = null ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed,VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Hook signature intentionally accepts action args for compatibility.
$preserve_license = self::should_preserve_license_on_unregistration();
$site_id = get_option( 'edac_site_id' );
$license_key = '' !== (string) $license ? (string) $license : self::get_license_key();
if ( empty( $site_id ) || empty( $license_key ) ) {
// Clear local report connection state even when required data is missing.
self::clear_report_connection_state();
if ( ! $preserve_license ) {
// Free disconnect keeps the historical behavior of clearing the key.
self::clear_free_disconnect_license_state();
}
set_transient(
$this->get_notice_transient_key(),
[
'type' => 'error',
'message' => __( 'Unable to unregister site. Required registration data is missing.', 'accessibility-checker' ),
],
self::NOTICE_TRANSIENT_TTL
);
return;
}
$response_data = self::unregister_site( $site_id, get_site_url(), $license_key );
// Always clear local report state so reports are disabled immediately.
self::clear_report_connection_state();
if ( ! $preserve_license ) {
// Free disconnect keeps the historical behavior of clearing the key,
// even when the API response is an error.
self::clear_free_disconnect_license_state();
}
if ( empty( $response_data['success'] ) ) {
$error_msg = ! empty( $response_data['message'] ) ? $response_data['message'] : __( 'Unknown error occurred while unregistering the site.', 'accessibility-checker' );
set_transient(
$this->get_notice_transient_key(),
[
'type' => 'error',
'message' => $error_msg,
],
self::NOTICE_TRANSIENT_TTL
);
return;
}
set_transient(
$this->get_notice_transient_key(),
[
'type' => 'success',
'message' => __( 'Site unregistered successfully. Your site will no longer receive email reports.', 'accessibility-checker' ),
],
self::NOTICE_TRANSIENT_TTL
);
}
/**
* Register a site with the MyDot API.
*
* @since 1.xx.x
*
* @param string $license_key The license key to register the site with.
* @param string $site_url The URL of the site to register.
* @param string $site_name The name of the site to register.
* @param bool $weekly_reports Whether to enable weekly reports.
* @param bool $monthly_reports Whether to enable monthly reports.
*
* @return array The response data from the API.
*/
public static function register_site( $license_key, $site_url, $site_name, $weekly_reports = true, $monthly_reports = true ) {
if ( empty( $license_key ) ) {
return [
'success' => false,
'message' => __( 'No license key provided.', 'accessibility-checker' ),
];
}
$request_data = [
'site_url' => $site_url,
'site_name' => $site_name,
'license_key' => $license_key,
'weekly_reports' => $weekly_reports,
'monthly_reports' => $monthly_reports,
];
if ( self::should_use_filtered_product_id_for_enrollment() ) {
$request_data['product_id'] = self::get_product_id();
}
$response = wp_remote_post(
self::get_api_endpoint() . '/wp-json/myed-email-reports/v1/register-site',
[
'headers' => [ 'Content-Type' => 'application/json' ],
'body' => wp_json_encode( $request_data ),
'method' => 'POST',
'data_format' => 'body',
'timeout' => 15, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout -- accommodation for slow hosting environments.
'sslverify' => self::verify_ssl(),
]
);
if ( is_wp_error( $response ) ) {
return [
'success' => false,
'message' => $response->get_error_message(),
];
}
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = wp_remote_retrieve_body( $response );
$response_data = json_decode( $response_body, true );
if ( 200 !== $response_code || empty( $response_body ) ) {
return [
'success' => false,
'message' => ( ! empty( $response_data['message'] ) ? $response_data['message'] : __( 'Unknown error occurred while registering the site.', 'accessibility-checker' ) ),
];
}
return $response_data;
}
/**
* Unregister a site from the MyDot API.
*
* @since 1.xx.x
*
* @param string $site_id The site ID for the registered site.
* @param string $site_url The URL of the site to unregister.
* @param string $license_key The license key associated with the site.
*
* @return array The response data from the API.
*/
public static function unregister_site( $site_id, $site_url, $license_key ) {
if ( empty( $site_id ) || empty( $site_url ) || empty( $license_key ) ) {
return [
'success' => false,
'message' => __( 'Missing required parameters for unregistration.', 'accessibility-checker' ),
];
}
$request_data = [
'site_id' => $site_id,
'site_url' => $site_url,
'license_key' => $license_key,
];
if ( self::should_use_filtered_product_id_for_enrollment() ) {
$request_data['product_id'] = self::get_product_id();
}
$response = wp_remote_post(
self::get_api_endpoint() . '/wp-json/myed-email-reports/v1/unregister-site',
[
'headers' => [
'Content-Type' => 'application/json',
],
'body' => wp_json_encode( $request_data ),
'method' => 'POST',
'data_format' => 'body',
'timeout' => 15, // phpcs:ignore WordPressVIPMinimum.Performance.RemoteRequestTimeout.timeout_timeout -- accommodation for slow hosting environments.
'sslverify' => self::verify_ssl(),
]
);
if ( is_wp_error( $response ) ) {
return [
'success' => false,
'message' => $response->get_error_message(),
];
}
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = wp_remote_retrieve_body( $response );
$response_data = json_decode( $response_body, true );
if ( 200 !== $response_code || empty( $response_body ) ) {
return [
'success' => false,
'message' => ( ! empty( $response_data['message'] ) ? $response_data['message'] : __( 'Unknown error occurred while unregistering the site.', 'accessibility-checker' ) ),
];
}
return $response_data;
}
/**
* Get the expected issuer for JWT validation (RFC 8725).
*
* @since 1.xx.x
*
* @return string The issuer URL/identifier.
*/
public static function get_jwt_issuer() {
// strip the protocol for issuer comparison.
return apply_filters( 'edac_jwt_issuer', preg_replace( '#^https?://#', '', self::get_api_endpoint() ) );
}
/**
* Get the expected audience for JWT validation (RFC 8725).
*
* @since 1.xx.x
*
* @return string The audience identifier (site URL or API endpoint identifier).
*/
public static function get_jwt_audience() {
// strip the protocol for audience comparison.
return apply_filters( 'edac_jwt_audience', preg_replace( '#^https?://#', '', home_url() ) );
}
/**
* Validate a JWT token using the stored public key (RFC 8725 compliant).
*
* Validates:
* - Token structure (3 parts separated by dots)
* - Header algorithm (RS256)
* - Signature using stored public key
* - Token expiration (exp claim)
* - Issuer (iss claim) per RFC 8725 to prevent token substitution attacks
* - Audience (aud claim) per RFC 8725 to ensure token is for this recipient
* - Not Before (nbf claim) if present
*
* @since 1.xx.x
*
* @param string $token The JWT token to validate.
* @return bool True if the token is valid, false otherwise.
*/
public static function validate_jwt_token( $token ) {
if ( empty( $token ) ) {
return false;
}
$public_key = get_option( 'edac_jwt_public_key' );
if ( empty( $public_key ) ) {
return false;
}
$parts = explode( '.', $token );
if ( count( $parts ) !== 3 ) {
return false;
}
list( $header_b64, $payload_b64, $signature_b64 ) = $parts;
$header_json = self::base64url_decode_strict( $header_b64 );
$payload_json = self::base64url_decode_strict( $payload_b64 );
if ( false === $header_json || false === $payload_json ) {
return false;
}
$header = json_decode( $header_json, true );
$payload = json_decode( $payload_json, true );
if ( ! $header || ! $payload ) {
return false;
}
// Require that aud, iss and exp all exist.
if ( ! isset( $payload['aud'], $payload['iss'], $payload['exp'] ) ) {
return false;
}
// The exp should be numeric and an int.
if ( ! is_numeric( $payload['exp'] ) ) {
return false;
}
$exp = (int) $payload['exp'];
$message = $header_b64 . '.' . $payload_b64;
$signature_decoded = self::base64url_decode_strict( $signature_b64 );
if ( false === $signature_decoded ) {
return false;
}
$algo = $header['alg'] ?? 'RS256';
if ( 'RS256' !== $algo ) {
return false;
}
$public_key_resource = openssl_pkey_get_public( $public_key );
if ( ! $public_key_resource ) {
return false;
}
$verify_result = openssl_verify( $message, $signature_decoded, $public_key_resource, OPENSSL_ALGO_SHA256 );
if ( 1 !== $verify_result ) {
return false;
}