Repository navigation
Expand file tree
/
Copy pathajcore.php
More file actions
3054 lines (2817 loc) · 128 KB
/
Copy pathajcore.php
File metadata and controls
3054 lines (2817 loc) · 128 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: AJ Core
* Plugin URI: https://github.com/ssnanda/ajcore
* Description: A modular WordPress business toolkit for forms, payments, portals, auth, CRM, and automations.
* Version: 0.11.7
* Author: IT Spector LLC
* Author URI: https://itspector.com
* Update URI: false
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
* Text Domain: ajcore
* Domain Path: /languages
*/
if ( ! defined( 'WPINC' ) ) {
die;
}
if ( ! defined( 'AJCORE_VERSION' ) ) {
define( 'AJCORE_VERSION', '0.11.7' );
}
if ( ! defined( 'AJCORE_PLUGIN_DIR' ) ) {
define( 'AJCORE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'AJCORE_PLUGIN_URL' ) ) {
define( 'AJCORE_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}
if ( ! defined( 'AJCORE_PLUGIN_BASENAME' ) ) {
define( 'AJCORE_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
}
// Registry companion plugins (AJCore-RA, ...) register into; harmless when empty.
require_once AJCORE_PLUGIN_DIR . 'includes/class-ajcore-extensions.php';
require_once AJCORE_PLUGIN_DIR . 'includes/class-ajcore-ops-access.php';
require_once AJCORE_PLUGIN_DIR . 'includes/class-ajcore-zoho-mail.php';
require_once AJCORE_PLUGIN_DIR . 'includes/class-ajcore-pipeline.php';
require_once AJCORE_PLUGIN_DIR . 'includes/class-ajcore-pipeline-tab.php';
require_once AJCORE_PLUGIN_DIR . 'includes/class-ajcore-mail-util.php';
require_once AJCORE_PLUGIN_DIR . 'includes/class-ajcore-mail-pipelines.php';
require_once AJCORE_PLUGIN_DIR . 'includes/class-ajcore-marketing.php';
// Reports this install (site, versions) to freeSIEM Core. Must load at the top level
// of this file so its activation hook registers.
require_once AJCORE_PLUGIN_DIR . 'includes/freesiem-dial-home-ajcore.php';
Freesiem_Dial_Home_ajcore::boot( __FILE__ );
if ( ! defined( 'AJCORE_SYNCED_SETTINGS_FILE' ) ) {
define( 'AJCORE_SYNCED_SETTINGS_FILE', AJCORE_PLUGIN_DIR . 'config/synced-settings.json' );
}
if ( ! defined( 'AJCORE_SYSTEM_FROM_EMAIL' ) ) {
define( 'AJCORE_SYSTEM_FROM_EMAIL', function_exists( 'get_option' ) ? get_option( 'admin_email' ) : '' );
}
if ( ! defined( 'AJFORMS_VERSION' ) ) {
define( 'AJFORMS_VERSION', AJCORE_VERSION );
}
if ( ! defined( 'AJFORMS_PLUGIN_DIR' ) ) {
define( 'AJFORMS_PLUGIN_DIR', AJCORE_PLUGIN_DIR );
}
if ( ! defined( 'AJFORMS_PLUGIN_URL' ) ) {
define( 'AJFORMS_PLUGIN_URL', AJCORE_PLUGIN_URL );
}
if ( ! defined( 'AJFORMS_PLUGIN_BASENAME' ) ) {
define( 'AJFORMS_PLUGIN_BASENAME', AJCORE_PLUGIN_BASENAME );
}
if ( ! defined( 'AJFORMS_SYNCED_SETTINGS_FILE' ) ) {
define( 'AJFORMS_SYNCED_SETTINGS_FILE', AJCORE_SYNCED_SETTINGS_FILE );
}
if ( ! function_exists( 'ajcore_site_domain' ) ) {
/**
* This site's bare domain (no scheme, no www., no port) for building per-site email
* addresses. Falls back to "localhost" when nothing resolvable is available.
*
* @return string e.g. "freesiem.com".
*/
function ajcore_site_domain() {
$host = '';
if ( function_exists( 'home_url' ) ) {
$host = (string) wp_parse_url( home_url(), PHP_URL_HOST );
}
if ( '' === $host && isset( $_SERVER['HTTP_HOST'] ) ) {
$host = (string) sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) );
}
$host = preg_replace( '/^www\./i', '', strtolower( $host ) );
// Drop any :port and anything that isn't a plausible hostname character.
$host = preg_replace( '/[^a-z0-9.\-].*$/', '', (string) $host );
return '' !== $host ? $host : 'localhost';
}
}
if ( ! function_exists( 'ajcore_site_mailbox' ) ) {
/**
* A <mailbox>@<this site's domain> address, for per-site plugin mail defaults.
* Keeps senders/recipients on the sending site's own domain instead of a shared
* hard-coded address, which matters for SPF/DKIM alignment now that this plugin
* ships to many sites.
*
* @param string $mailbox Local part, e.g. "donotreply" or "leads".
* @return string e.g. "leads@freesiem.com".
*/
function ajcore_site_mailbox( $mailbox ) {
$mailbox = preg_replace( '/[^a-z0-9._\-]/', '', strtolower( (string) $mailbox ) );
if ( '' === $mailbox ) {
$mailbox = 'noreply';
}
return $mailbox . '@' . ajcore_site_domain();
}
}
if ( ! function_exists( 'ajcore_default_system_from_email' ) ) {
/**
* Per-site default "From" address for plugin-sent mail: donotreply@<this site's domain>.
*
* Used only when no explicit From email has been configured (the "System From Email"
* setting, or a form's "Notification From" field).
*
* @return string e.g. "donotreply@freesiem.com".
*/
function ajcore_default_system_from_email() {
return ajcore_site_mailbox( 'donotreply' );
}
}
if ( ! function_exists( 'ajcore_default_notification_email' ) ) {
/**
* Per-site default recipient for form notifications: leads@<this site's domain>.
*
* Seeds the "Default Notification Email" setting and any new form that doesn't
* override it. Admins can still point individual forms elsewhere in the builder.
*
* @return string e.g. "leads@freesiem.com".
*/
function ajcore_default_notification_email() {
return ajcore_site_mailbox( 'leads' );
}
}
if ( ! function_exists( 'ajcore_generate_service_request_number' ) ) {
function ajcore_generate_service_request_number( $created_at = null ) {
$pdb = function_exists( 'ajcore_get_portal_db' ) ? ajcore_get_portal_db() : $GLOBALS['wpdb'];
$table = $pdb->prefix . 'aj_portal_service_request_number_counters';
$time = $created_at ? strtotime( (string) $created_at ) : false;
$month = gmdate( 'Y-m', $time ? $time : time() );
$pdb->query( $pdb->prepare( "INSERT INTO {$table} (`year_month`, next_seq) VALUES (%s, 1) ON DUPLICATE KEY UPDATE next_seq = LAST_INSERT_ID(next_seq + 1)", $month ) );
$seq = (int) $pdb->get_var( 'SELECT LAST_INSERT_ID()' );
return sprintf( '%s-%04d', $month, $seq > 0 ? $seq : 1 );
}
}
if ( ! function_exists( 'ajcore_backfill_service_request_numbers' ) ) {
function ajcore_backfill_service_request_numbers() {
$pdb = function_exists( 'ajcore_get_portal_db' ) ? ajcore_get_portal_db() : $GLOBALS['wpdb'];
$table = $pdb->prefix . 'aj_portal_service_requests';
if ( ! $pdb->get_var( "SHOW COLUMNS FROM {$table} LIKE 'service_request_number'" ) ) return;
$lock_name = 'ajcore_service_request_number_backfill';
$got_lock = (bool) $pdb->get_var( $pdb->prepare( 'SELECT GET_LOCK(%s, 10)', $lock_name ) );
if ( ! $got_lock ) return;
try {
// Re-read after acquiring the lock in case another request completed the work while this one waited.
$rows = $pdb->get_results( "SELECT id, created_at FROM {$table} WHERE service_request_number = '' OR service_request_number IS NULL ORDER BY created_at ASC, id ASC" );
foreach ( is_array( $rows ) ? $rows : array() as $row ) {
$pdb->update( $table, array( 'service_request_number' => ajcore_generate_service_request_number( $row->created_at ) ), array( 'id' => (int) $row->id ), array( '%s' ), array( '%d' ) );
}
} finally {
$pdb->query( $pdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock_name ) );
}
}
}
if ( ! function_exists( 'ajcore_resequence_service_request_numbers' ) ) {
/** Compact legacy monthly numbering after the original unlocked backfill created gaps. */
function ajcore_resequence_service_request_numbers() {
$pdb = function_exists( 'ajcore_get_portal_db' ) ? ajcore_get_portal_db() : $GLOBALS['wpdb'];
$table = $pdb->prefix . 'aj_portal_service_requests';
$counter = $pdb->prefix . 'aj_portal_service_request_number_counters';
if ( ! $pdb->get_var( "SHOW COLUMNS FROM {$table} LIKE 'service_request_number'" ) ) return false;
$lock_name = 'ajcore_service_request_number_backfill';
$got_lock = (bool) $pdb->get_var( $pdb->prepare( 'SELECT GET_LOCK(%s, 10)', $lock_name ) );
if ( ! $got_lock ) return false;
try {
$rows = $pdb->get_results( "SELECT id, created_at FROM {$table} ORDER BY created_at ASC, id ASC" );
$counts = array();
foreach ( is_array( $rows ) ? $rows : array() as $row ) {
$timestamp = $row->created_at ? strtotime( (string) $row->created_at ) : false;
$month = gmdate( 'Y-m', $timestamp ? $timestamp : time() );
$counts[ $month ] = isset( $counts[ $month ] ) ? $counts[ $month ] + 1 : 1;
$pdb->update( $table, array( 'service_request_number' => sprintf( '%s-%04d', $month, $counts[ $month ] ) ), array( 'id' => (int) $row->id ), array( '%s' ), array( '%d' ) );
}
$pdb->query( "DELETE FROM {$counter}" );
foreach ( $counts as $month => $count ) {
$pdb->insert( $counter, array( 'year_month' => $month, 'next_seq' => $count ), array( '%s', '%d' ) );
}
return true;
} finally {
$pdb->query( $pdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock_name ) );
}
}
}
/** Permanently suppress Hostinger AI's API-token sales notice on AJ Core sites. */
if ( ! function_exists( 'ajcore_suppress_hostinger_ai_token_notice' ) ) {
function ajcore_suppress_hostinger_ai_token_notice() {
global $wp_filter;
if ( empty( $wp_filter['admin_notices'] ) || empty( $wp_filter['admin_notices']->callbacks ) ) {
return;
}
foreach ( $wp_filter['admin_notices']->callbacks as $priority => $callbacks ) {
foreach ( $callbacks as $callback ) {
$handler = isset( $callback['function'] ) ? $callback['function'] : null;
if ( is_array( $handler ) && is_object( $handler[0] ) && $handler[0] instanceof Hostinger_Ai_Assistant_Notices && 'api_token_plugin_notice' === $handler[1] ) {
remove_action( 'admin_notices', $handler, $priority );
}
}
}
}
add_action( 'admin_init', 'ajcore_suppress_hostinger_ai_token_notice', PHP_INT_MAX );
}
if ( ! function_exists( 'ajforms_get_settings_defaults' ) ) {
function ajforms_get_settings_defaults() {
$defaults = array(
'default_notification_email' => ajcore_default_notification_email(),
'default_notification_subject' => 'New submission for {form_title}',
'default_notifications_enabled' => '1',
'default_from_name' => get_bloginfo( 'name' ),
'default_reply_to_mode' => 'submitter',
'wp_email_templates_enabled' => '1',
'wp_email_from_email' => ajcore_default_system_from_email(),
'wp_email_from_name' => get_bloginfo( 'name' ),
// Outgoing transport. 'smtp' = the settings below, applied in ajcore_configure_smtp_mailer();
// 'php' = whatever mail() does on this host. SMTP is the default because shared hosts
// routinely break mail() (see that function's comment) — authenticated submission is the
// reliable path. Harmless before it's configured: with no smtp_host set, that function
// bows out and WordPress falls back to mail() exactly as before. See Settings → Email.
'mail_mode' => 'smtp',
'smtp_host' => '',
'smtp_port' => '587',
'smtp_encryption' => 'tls',
'smtp_auth' => '1',
'smtp_username' => '',
'smtp_password' => '',
// On by default: see the envelope-sender block in ajcore_configure_smtp_mailer().
'smtp_envelope_from_username' => '1',
'smtp_label' => 'Non-metered',
// Sender identity for mail sent on this profile. Blank falls back to System From.
'smtp_from_email' => '',
'smtp_from_name' => '',
// Profile 2: a metered/transactional provider (ZeptoMail, Postmark, SES…). Unset until a
// host is entered, in which case everything routed here falls back to profile 1.
'smtp2_label' => 'Metered',
'smtp2_host' => '',
'smtp2_port' => '587',
'smtp2_encryption' => 'tls',
'smtp2_auth' => '1',
'smtp2_username' => '',
'smtp2_password' => '',
'smtp2_envelope_from_username' => '1',
'smtp2_from_email' => '',
'smtp2_from_name' => '',
// The profile used by anything that doesn't name one: WordPress system mail, and any form
// or template saved before profiles existed. Set on the AJ Core Mail screen.
'mail_default_profile' => 'smtp',
'wp_password_reset_subject' => 'Password reset for your Portal Login for ' . get_bloginfo( 'name' ),
'wp_welcome_email_subject' => 'Welcome : Your portal access is enabled to ' . get_bloginfo( 'name' ),
'wp_service_status_subject' => 'Update on {service_name}: {status_label}',
'lead_followup_email_subject' => 'Following up from ' . get_bloginfo( 'name' ),
// Registered Agent authorization notice: text is supplied by AJCore-RA (blank here) — see the ncllc_only flag
// on this type in display_email_templates_settings_section(); there is deliberately no
// university_* variant because University Place Office Suites has no registered-agent
// address of its own to authorize).
'ra_authorization_subject' => '',
'wp_password_reset_heading' => 'Set your client portal password',
'wp_password_reset_body' => "Hi {name},\nUse the secure button below to create a new password for your client portal account. This link is private and should only be used by you.",
'wp_welcome_heading' => 'Welcome to your client portal',
'wp_welcome_body' => "Hi {name},\nYour client portal access has been enabled. Use the button below to set your password and sign in securely.",
'wp_service_status_heading' => 'Your service request was updated',
'wp_service_status_body' => "Hi {name},\nThe status of \"{service_name}\" has changed.",
'lead_followup_heading' => "We'd love to hear from you",
'ra_authorization_heading' => '',
// Lines starting with "- " render as the checklist under the address box; every other
// line is an intro paragraph above it (see split_email_copy_bullets()).
'ra_authorization_body' => '',
'ra_authorization_address' => '',
'lead_followup_body' => "Hi {name},\nWe wanted to follow up on your recent inquiry with " . get_bloginfo( 'name' ) . ". If you have any questions or would like to talk through your options, give us a call — we are happy to help.\nReady to get started? You can review our services and pricing anytime on our website.",
'wp_password_reset_from_email' => '',
'wp_password_reset_from_name' => '',
'wp_welcome_from_email' => '',
'wp_welcome_from_name' => '',
'wp_service_status_from_email' => '',
'wp_service_status_from_name' => '',
'lead_followup_from_email' => '',
'lead_followup_from_name' => '',
'ra_authorization_from_email' => '',
'ra_authorization_from_name' => '',
// Sender identity footer on every branded email (see get_branded_email_footer_parts()).
// A real postal address is a standard legitimate-sender signal; its absence is one of
// the few content-level things that measurably hurts transactional deliverability.
'email_footer_address' => '',
// Zoho Mail shared-inbox OAuth app (Inbox settings). client_id/secret/account_email/
// data_center are admin-entered; the rest are written only by the OAuth callback itself.
'zoho_mail_client_id' => '',
'zoho_mail_client_secret' => '',
'zoho_mail_account_email' => '',
// The Zoho Organization ID (zoid) — there's no reliable non-partner API to discover
// this for a regular admin, so it's entered manually. Visible in the Zoho Mail Admin
// Console under Organization -> Profile.
'zoho_mail_org_id' => '',
// Optional manual override: the Zoho Group ID (zgid) of the Shared Mailbox group,
// copied from the Admin Console. Skips the org-wide groups list (which has been
// observed returning an empty list for a Shared Mailbox that demonstrably exists)
// and fetches that one group directly instead.
'zoho_mail_group_id' => '',
'zoho_mail_data_center' => 'com',
'zoho_mail_access_token' => '',
'zoho_mail_refresh_token' => '',
'zoho_mail_token_expires_at' => 0,
'zoho_mail_account_id' => '',
'zoho_mail_connected_email' => '',
'zoho_mail_connected_at' => '',
// Self-hosted Live Chat. Most chat_* / visitor_* keys below are shared across all
// connected sites and master-controlled (see ajcore_get_chat_setting_keys() — that list
// rides the 'ajcore_chat_settings' shared row) — the master's Live Chat settings page is
// the one place they're editable, secondary sites overlay them read-only in
// ajforms_get_settings(). The one exception is chat_widget_enabled: it is deliberately a
// LOCAL per-site option (never in ajcore_get_chat_setting_keys(), never overlaid), so each
// site decides for itself whether the visitor widget shows — even a secondary site on the
// shared network can switch its own widget off without affecting the others.
'chat_server_url' => '',
// Optional override of chat_server_url for AJCore's own outbound /chat/notify call
// only (never sent to the browser). In production these are identical and this stays
// blank — it exists because in local ddev, PHP (inside the ddev container) and the
// browser resolve "the AJOps server" differently (e.g. http://host.docker.internal:3000
// vs http://localhost:3000), and no single URL is reachable from both.
'chat_notify_url' => '',
'chat_notify_secret' => '',
'chat_ws_token_secret' => '',
'chat_internal_secret' => '',
// LOCAL per-site — see the note above the Live Chat block. Not shared, not overlaid.
'chat_widget_enabled' => '0',
// Passive "want to text us?" nudge — on by default (matches the widget's original
// always-on behavior, before this toggle existed) so existing sites see no change.
'chat_engage_popup_enabled' => '1',
'chat_engage_popup_delay_seconds' => '25',
// "Live Visitors" self-identify prompt — a light, dismissible ask (name/email/phone, all
// optional) shown from the chat widget's presence connection, independent of whether the
// visitor ever opens the chat panel. Shared/master-controlled, and only has any effect
// where the (local) chat_widget_enabled switch is also on for that site — the prompt
// rides the widget's existing presence WebSocket (see ajcore-chat-widget.js).
'visitor_identify_enabled' => '0',
// No fixed-collision floor needed against the engage popup's delay/auto-dismiss window —
// the widget retries until the engage popup (if any) is off-screen rather than a one-shot
// check, so any combination of the two delays below is safe.
'visitor_identify_delay_seconds' => '55',
// Visitor-facing "visit timer" — a tiny, unlabeled, barely-there number (cumulative
// seconds on site across every visit, not just this one) shown in a page corner. Shared/
// master-controlled like the settings above; also only has any effect where the (local)
// chat_widget_enabled switch is on for that site (the presence connection carries it down).
'visitor_timer_enabled' => '0',
// Business hours gate for the widget's offline banner — a simple "Mon-Fri 09:00-17:00"
// style string parsed client-side (widget evaluates it against the visitor's local
// clock), not a full per-day schedule builder.
'chat_business_hours_enabled' => '0',
'chat_business_hours' => 'Mon-Fri 09:00-17:00',
// 0 = disabled. Hours of no activity before an open session auto-closes.
'chat_auto_close_hours' => '24',
'chat_transcript_email_subject' => 'Your chat transcript from {site_name}',
'chat_transcript_email_heading' => 'Here\'s a copy of your chat',
'chat_transcript_email_body' => "Hi {name},\nThanks for chatting with us. Here's a copy of your conversation for your records.",
'default_success_message' => 'Form submitted successfully.',
'validation_mode' => 'native',
'require_unique_form_names' => '1',
'honeypot_enabled' => '1',
// Content Filtering (Spam Protection) — checked server-side at submission time,
// applies automatically to every form's free-text fields (and the blocked-domains
// list to every Email field), same "no per-form setup needed" reasoning as honeypot.
'content_filter_block_non_latin' => '0',
'content_filter_block_links' => '0',
'content_filter_blocked_email_domains' => '',
'spam_challenge_provider' => 'turnstile',
'recaptcha_site_key' => '',
'recaptcha_secret_key' => '',
'hcaptcha_site_key' => '',
'hcaptcha_secret_key' => '',
'turnstile_site_key' => '',
'turnstile_secret_key' => '',
// Cloudflare IP blocking (Spam Protection -> "Mark Spam" in AJOps). One account-level
// List ("ajcore_spam_list") plus one zone-level WAF Custom Rule blocking it — see
// ajcore_cloudflare_block_ip() — so blocking any number of spam IPs over time never
// creates more than one rule. Needs a token with Account > Account Filter Lists: Edit
// and Zone > WAF: Edit. account_id/zone_id aren't secrets (both visible in the
// Cloudflare dashboard) but travel with the token since none of the three works alone.
'cloudflare_api_token' => '',
'cloudflare_account_id' => '',
'cloudflare_zone_id' => '',
'webhook_url' => '',
'asana_enabled' => '0',
'asana_personal_access_token' => '',
'asana_workspace_gid' => '',
'asana_project_gid' => '',
'stripe_mode' => 'test',
'stripe_sandbox_publishable_key' => '',
'stripe_sandbox_secret_key' => '',
'stripe_live_publishable_key' => '',
'stripe_live_secret_key' => '',
'stripe_publishable_key' => '',
'stripe_secret_key' => '',
'stripe_products_mode' => 'all',
'stripe_selected_prices' => array(),
'stripe_late_fees_enabled' => '0',
'stripe_late_fee_type' => 'fixed',
'stripe_late_fee_amount' => '25.00',
'stripe_late_fee_grace_days' => 5,
'stripe_late_fee_due_days' => 7,
'portal_event_log_retention_days' => 180,
'portal_event_log_max_rows' => 50000,
'zoho_reservations_enabled' => '0',
'zoho_default_timezone' => 'America/New_York',
'zoho_calendar_uid' => '',
'zoho_calendar_id' => '',
'zoho_calendar_embed_url' => '',
'zoho_resource_uid' => '',
'zoho_schedule_appointment_url' => '',
'zoho_resource_freebusy_url' => 'https://calendar.zoho.com/api/v1/resources/{resourceuid}/freebusy',
'zoho_api_auth_mode' => '',
// Canonical Zoho OAuth setting names.
'zoho_client_id' => '',
'zoho_client_secret' => '',
'zoho_access_token' => '',
'zoho_refresh_token' => '',
'zoho_token_expires_at' => '',
'zoho_api_domain' => '',
// Legacy aliases kept for backward compatibility (populated from canonical on save).
'zoho_oauth_client_id' => '',
'zoho_oauth_client_secret' => '',
'zoho_oauth_api_domain' => '',
'zoho_api_token' => '',
'zoho_api_token_expires_at' => '',
// One-time code: never stored after successful exchange.
'zoho_oauth_authorization_code' => '',
// Availability failure behavior: 'strict' blocks booking if Zoho check fails;
// 'lenient' allows it and logs a warning. Portal API defaults lenient.
'zoho_availability_failure_mode' => 'lenient',
'reservation_resource_name' => 'Conference Room',
'reservation_resource_key' => 'conference_room',
'reservation_menu_label' => 'Conference Room',
'reservation_business_hours_label' => 'Business Hours (Mon–Fri 9am–5pm)',
'reservation_after_hours_label' => 'After-Hours / Weekend',
);
// Extensions (AJCore-RA) layer their business-specific defaults here; saved settings still win.
return apply_filters( 'ajforms_settings_defaults', $defaults );
}
}
if ( ! function_exists( 'ajcore_normalize_stripe_settings' ) ) {
function ajcore_normalize_stripe_settings( $settings ) {
$settings = is_array( $settings ) ? $settings : array();
$mode = ! empty( $settings['stripe_mode'] ) && 'live' === sanitize_key( (string) $settings['stripe_mode'] ) ? 'live' : 'test';
$settings['stripe_mode'] = $mode;
foreach ( array( 'stripe_sandbox_publishable_key', 'stripe_sandbox_secret_key', 'stripe_live_publishable_key', 'stripe_live_secret_key', 'stripe_publishable_key', 'stripe_secret_key' ) as $key ) {
if ( ! isset( $settings[ $key ] ) ) {
$settings[ $key ] = '';
}
}
/* Backward compatibility: if an older single-key setting exists, place it into the matching environment bucket in memory. */
$legacy_publishable = trim( (string) $settings['stripe_publishable_key'] );
if ( '' !== $legacy_publishable && function_exists( 'ajcore_get_stripe_key_environment' ) ) {
$environment = ajcore_get_stripe_key_environment( $legacy_publishable );
if ( 'test' === $environment && '' === trim( (string) $settings['stripe_sandbox_publishable_key'] ) ) {
$settings['stripe_sandbox_publishable_key'] = $legacy_publishable;
} elseif ( 'live' === $environment && '' === trim( (string) $settings['stripe_live_publishable_key'] ) ) {
$settings['stripe_live_publishable_key'] = $legacy_publishable;
}
}
$legacy_secret = trim( (string) $settings['stripe_secret_key'] );
if ( '' !== $legacy_secret && function_exists( 'ajcore_get_stripe_key_environment' ) ) {
$environment = ajcore_get_stripe_key_environment( $legacy_secret );
if ( 'test' === $environment && '' === trim( (string) $settings['stripe_sandbox_secret_key'] ) ) {
$settings['stripe_sandbox_secret_key'] = $legacy_secret;
} elseif ( 'live' === $environment && '' === trim( (string) $settings['stripe_live_secret_key'] ) ) {
$settings['stripe_live_secret_key'] = $legacy_secret;
}
}
$active_prefix = 'live' === $mode ? 'stripe_live' : 'stripe_sandbox';
$settings['stripe_publishable_key'] = trim( (string) $settings[ $active_prefix . '_publishable_key' ] );
$settings['stripe_secret_key'] = trim( (string) $settings[ $active_prefix . '_secret_key' ] );
return $settings;
}
}
if ( ! function_exists( 'ajforms_get_settings' ) ) {
function ajforms_get_settings() {
$raw_saved_settings = get_option( 'ajforms_settings', false );
$saved_settings = is_array( $raw_saved_settings ) ? $raw_saved_settings : array();
$has_saved_settings = false !== $raw_saved_settings && ! empty( $saved_settings );
if ( ! is_array( $saved_settings ) ) {
$saved_settings = array();
}
$file_settings = ajforms_read_synced_settings_file();
if ( ! is_array( $file_settings ) ) {
$file_settings = array();
}
if ( ! $has_saved_settings ) {
$legacy_stripe_settings = ajforms_read_legacy_synced_stripe_settings_file();
if ( ! empty( $legacy_stripe_settings ) ) {
$file_settings = array_merge( $file_settings, $legacy_stripe_settings );
}
}
$settings = wp_parse_args(
array_merge( $file_settings, $saved_settings ),
ajforms_get_settings_defaults()
);
$settings = function_exists( 'ajcore_normalize_stripe_settings' ) ? ajcore_normalize_stripe_settings( $settings ) : $settings;
if ( ! $has_saved_settings && ! empty( $file_settings ) ) {
update_option( 'ajforms_settings', $settings );
}
// Calendar/reservation settings are shared across sites. The master's local
// option is the source of truth (it pushes to the shared DB on every save);
// secondary sites overlay the shared values so they never rely on their own
// stale local copies.
if ( function_exists( 'ajcore_is_shared_db_enabled' ) && ajcore_is_shared_db_enabled()
&& function_exists( 'ajcore_read_shared_calendar_settings' ) ) {
$is_master = ! function_exists( 'ajcore_is_stripe_sync_owner' ) || ajcore_is_stripe_sync_owner();
if ( ! $is_master ) {
$shared_calendar = ajcore_read_shared_calendar_settings();
if ( ! empty( $shared_calendar ) ) {
$settings = array_merge( $settings, $shared_calendar );
}
if ( function_exists( 'ajcore_read_shared_chat_settings' ) ) {
$shared_chat = ajcore_read_shared_chat_settings();
// chat_widget_enabled is a local per-site switch. Older builds (0.7.285–0.7.289)
// published it into the shared row; drop it here so a stale value there can never
// override this site's own local choice.
unset( $shared_chat['chat_widget_enabled'] );
if ( ! empty( $shared_chat ) ) {
$settings = array_merge( $settings, $shared_chat );
}
}
}
}
return $settings;
}
}
if ( ! function_exists( 'ajforms_get_synced_setting_keys' ) ) {
function ajforms_get_synced_setting_keys() {
return array(
'honeypot_enabled',
'spam_challenge_provider',
'recaptcha_site_key',
'hcaptcha_site_key',
'turnstile_site_key',
'asana_enabled',
'asana_workspace_gid',
'asana_project_gid',
'portal_event_log_retention_days',
'portal_event_log_max_rows',
);
}
}
if ( ! function_exists( 'ajforms_get_stripe_setting_keys' ) ) {
function ajforms_get_stripe_setting_keys() {
return array(
'stripe_mode',
'stripe_sandbox_publishable_key',
'stripe_sandbox_secret_key',
'stripe_live_publishable_key',
'stripe_live_secret_key',
'stripe_publishable_key',
'stripe_secret_key',
);
}
}
if ( ! function_exists( 'ajcore_get_secret_setting_keys' ) ) {
/**
* Settings fields that hold credentials and are encrypted at rest in wp_options.
*/
function ajcore_get_secret_setting_keys() {
return array(
'stripe_sandbox_secret_key',
'stripe_live_secret_key',
'stripe_secret_key',
'recaptcha_secret_key',
'hcaptcha_secret_key',
'turnstile_secret_key',
'asana_personal_access_token',
'cloudflare_api_token',
);
}
}
require_once AJCORE_PLUGIN_DIR . 'includes/settings-encryption.php';
if ( ! function_exists( 'ajcore_encrypt_settings_secrets' ) ) {
/**
* pre_update_option_ajforms_settings filter: every save path stores secrets encrypted.
*/
function ajcore_encrypt_settings_secrets( $settings ) {
if ( ! is_array( $settings ) ) {
return $settings;
}
foreach ( ajcore_get_secret_setting_keys() as $key ) {
if ( ! empty( $settings[ $key ] ) && is_string( $settings[ $key ] ) ) {
$settings[ $key ] = ajcore_encrypt_setting_value( $settings[ $key ] );
}
}
return $settings;
}
}
if ( ! function_exists( 'ajcore_decrypt_settings_secrets' ) ) {
/**
* option_ajforms_settings filter: every read path sees decrypted secrets.
*/
function ajcore_decrypt_settings_secrets( $settings ) {
if ( ! is_array( $settings ) ) {
return $settings;
}
foreach ( ajcore_get_secret_setting_keys() as $key ) {
if ( ! empty( $settings[ $key ] ) && is_string( $settings[ $key ] ) ) {
$settings[ $key ] = ajcore_decrypt_setting_value( $settings[ $key ] );
}
}
return $settings;
}
}
add_filter( 'pre_update_option_ajforms_settings', 'ajcore_encrypt_settings_secrets' );
add_filter( 'option_ajforms_settings', 'ajcore_decrypt_settings_secrets' );
if ( ! function_exists( 'ajcore_maybe_encrypt_saved_settings_secrets' ) ) {
/**
* One-time migration: re-save the settings option so existing plaintext secrets
* pass through the encryption filter and land encrypted in the database.
*/
function ajcore_maybe_encrypt_saved_settings_secrets() {
if ( '1' === get_option( 'ajcore_settings_secrets_encrypted' ) ) {
return;
}
$settings = get_option( 'ajforms_settings', false );
if ( is_array( $settings ) && ! empty( $settings ) ) {
update_option( 'ajforms_settings', $settings );
}
update_option( 'ajcore_settings_secrets_encrypted', '1', false );
}
}
add_action( 'admin_init', 'ajcore_maybe_encrypt_saved_settings_secrets' );
if ( ! function_exists( 'ajcore_mask_secret_for_display' ) ) {
/**
* "sk_live_…82Uq" style hint for settings screens — never the full key.
*/
function ajcore_mask_secret_for_display( $value ) {
$value = (string) $value;
if ( '' === $value ) {
return '';
}
if ( strlen( $value ) <= 12 ) {
return '••••';
}
return substr( $value, 0, 8 ) . '••••' . substr( $value, -4 );
}
}
if ( ! function_exists( 'ajcore_cloudflare_api_request' ) ) {
/**
* Thin wrapper around wp_remote_request for Cloudflare's v4 API — every ajcore_cloudflare_*
* helper below goes through this so auth headers/timeout/JSON-decoding stay in one place.
*
* @return array{success:bool,body:array,status:int}|WP_Error
*/
function ajcore_cloudflare_api_request( $method, $url, $api_token, $body = null ) {
$args = array(
'method' => $method,
'timeout' => 15,
'headers' => array(
'Authorization' => 'Bearer ' . $api_token,
'Content-Type' => 'application/json',
),
);
if ( null !== $body ) {
$args['body'] = wp_json_encode( $body );
}
$response = wp_remote_request( $url, $args );
if ( is_wp_error( $response ) ) {
return $response;
}
$status = (int) wp_remote_retrieve_response_code( $response );
$decoded = json_decode( wp_remote_retrieve_body( $response ), true );
return array(
'success' => is_array( $decoded ) && ! empty( $decoded['success'] ),
'body' => is_array( $decoded ) ? $decoded : array(),
'status' => $status,
);
}
}
if ( ! function_exists( 'ajcore_cloudflare_api_error_message' ) ) {
function ajcore_cloudflare_api_error_message( $body, $status ) {
$errors = ( is_array( $body ) && ! empty( $body['errors'] ) && is_array( $body['errors'] ) ) ? $body['errors'] : array();
if ( ! empty( $errors[0]['message'] ) ) {
return (string) $errors[0]['message'];
}
return sprintf( /* translators: %d: HTTP status code */ __( 'Cloudflare request failed with HTTP status %d.', 'ajforms' ), $status );
}
}
if ( ! function_exists( 'AJCORE_CLOUDFLARE_LIST_NAME' ) ) {
// Cloudflare list names: lowercase letters/digits/underscores only, no hyphens or spaces.
define( 'AJCORE_CLOUDFLARE_LIST_NAME', 'ajcore_spam_list' );
define( 'AJCORE_CLOUDFLARE_RULE_DESCRIPTION', 'AJCore-Spam-List' );
}
if ( ! function_exists( 'ajcore_cloudflare_get_settings' ) ) {
/**
* Pulls + validates the three Cloudflare fields every helper below needs. Centralized so the
* "not configured yet" error message is worded identically everywhere it can surface.
*
* @return array{api_token:string,account_id:string,zone_id:string}|WP_Error
*/
function ajcore_cloudflare_get_settings() {
$settings = function_exists( 'ajforms_get_settings' ) ? ajforms_get_settings() : array();
$api_token = ! empty( $settings['cloudflare_api_token'] ) ? trim( (string) $settings['cloudflare_api_token'] ) : '';
$account_id = ! empty( $settings['cloudflare_account_id'] ) ? trim( (string) $settings['cloudflare_account_id'] ) : '';
$zone_id = ! empty( $settings['cloudflare_zone_id'] ) ? trim( (string) $settings['cloudflare_zone_id'] ) : '';
if ( '' === $api_token || '' === $account_id || '' === $zone_id ) {
return new WP_Error( 'ajcore_cloudflare_not_configured', __( 'Cloudflare API Token, Account ID, and Zone ID must all be set on the Spam Protection screen first.', 'ajforms' ) );
}
return array( 'api_token' => $api_token, 'account_id' => $account_id, 'zone_id' => $zone_id );
}
}
if ( ! function_exists( 'ajcore_cloudflare_get_or_create_list' ) ) {
/**
* Finds the account's "ajcore_spam_list" IP list, creating it if this is the first time
* anything has been blocked. Not cached across requests — this only runs when a lead is
* actually marked spam (a human-triggered, infrequent action) or Test Connection is clicked,
* so one fresh lookup per request is cheap and immune to the list having been renamed/deleted
* by hand on Cloudflare's side since the last call. Callers doing multiple operations in one
* request (Test Connection's block-then-unblock round trip) should call this ONCE and reuse
* the id — see the $list_id override on ajcore_cloudflare_block_ip()/unblock_ip() — rather than
* let each operation re-resolve it, which is what previously made Test Connection slow enough
* to occasionally 502 at the origin (each redundant resolution is its own Cloudflare API call).
*
* @return array{id:string,created:bool}|WP_Error
*/
function ajcore_cloudflare_get_or_create_list( $account_id, $api_token ) {
$list = ajcore_cloudflare_api_request(
'GET',
'https://api.cloudflare.com/client/v4/accounts/' . rawurlencode( $account_id ) . '/rules/lists',
$api_token
);
if ( is_wp_error( $list ) ) {
return $list;
}
if ( $list['success'] ) {
foreach ( (array) ( $list['body']['result'] ?? array() ) as $existing ) {
if ( isset( $existing['name'] ) && AJCORE_CLOUDFLARE_LIST_NAME === $existing['name'] ) {
return array( 'id' => (string) $existing['id'], 'created' => false );
}
}
}
$created = ajcore_cloudflare_api_request(
'POST',
'https://api.cloudflare.com/client/v4/accounts/' . rawurlencode( $account_id ) . '/rules/lists',
$api_token,
array(
'name' => AJCORE_CLOUDFLARE_LIST_NAME,
'description' => 'AJCore spam IP blocklist — auto-managed by "Mark Spam" in AJOps, do not edit the name.',
'kind' => 'ip',
)
);
if ( is_wp_error( $created ) ) {
return $created;
}
if ( ! $created['success'] || empty( $created['body']['result']['id'] ) ) {
return new WP_Error( 'ajcore_cloudflare_list_create_failed', ajcore_cloudflare_api_error_message( $created['body'], $created['status'] ) );
}
return array( 'id' => (string) $created['body']['result']['id'], 'created' => true );
}
}
if ( ! function_exists( 'ajcore_cloudflare_find_custom_ruleset' ) ) {
/**
* Finds the zone's http_request_firewall_custom-phase ruleset (the one behind Security rules
* -> Custom rules in the dashboard), full rules array included. Deliberately goes through
* GET /zones/{id}/rulesets (list) + GET /zones/{id}/rulesets/{ruleset_id} (by ID) rather than
* the seemingly-equivalent GET /zones/{id}/rulesets/phases/{phase}/entrypoint shortcut — that
* shortcut 403s ("Authentication error") under a token scoped with Zone > WAF: Edit even
* though the by-ID/list endpoints it's supposedly a convenience wrapper for work fine with the
* exact same token, confirmed by hand against a real zone. Cloudflare-side inconsistency, not
* a documented permission difference — this works around it rather than depending on it.
*
* @return array|null|WP_Error The ruleset (with "id" and "rules"), or null if this zone has
* no custom ruleset yet.
*/
function ajcore_cloudflare_find_custom_ruleset( $zone_id, $api_token ) {
$list = ajcore_cloudflare_api_request(
'GET',
'https://api.cloudflare.com/client/v4/zones/' . rawurlencode( $zone_id ) . '/rulesets',
$api_token
);
if ( is_wp_error( $list ) ) {
return $list;
}
if ( ! $list['success'] ) {
return new WP_Error( 'ajcore_cloudflare_ruleset_list_failed', ajcore_cloudflare_api_error_message( $list['body'], $list['status'] ) );
}
$ruleset_id = '';
foreach ( (array) ( $list['body']['result'] ?? array() ) as $ruleset ) {
if ( isset( $ruleset['phase'] ) && 'http_request_firewall_custom' === $ruleset['phase'] ) {
$ruleset_id = (string) $ruleset['id'];
break;
}
}
if ( '' === $ruleset_id ) {
return null;
}
$detail = ajcore_cloudflare_api_request(
'GET',
'https://api.cloudflare.com/client/v4/zones/' . rawurlencode( $zone_id ) . '/rulesets/' . rawurlencode( $ruleset_id ),
$api_token
);
if ( is_wp_error( $detail ) ) {
return $detail;
}
if ( ! $detail['success'] || empty( $detail['body']['result']['id'] ) ) {
return new WP_Error( 'ajcore_cloudflare_ruleset_get_failed', ajcore_cloudflare_api_error_message( $detail['body'], $detail['status'] ) );
}
return $detail['body']['result'];
}
}
if ( ! function_exists( 'ajcore_cloudflare_ensure_custom_rule' ) ) {
/**
* Makes sure exactly one WAF Custom Rule exists on the zone blocking traffic from the list —
* "ip.src in $ajcore_spam_list" — creating the zone's custom-rules entrypoint ruleset first if
* this zone has never had one. One rule total regardless of how many IPs the list holds later.
* Callers doing multiple operations in one request should call this ONCE and skip re-checking
* — see the $skip_rule_check param on ajcore_cloudflare_block_ip().
*
* @return array{created:bool}|WP_Error
*/
function ajcore_cloudflare_ensure_custom_rule( $zone_id, $api_token ) {
$expression = 'ip.src in $' . AJCORE_CLOUDFLARE_LIST_NAME;
$entrypoint = ajcore_cloudflare_find_custom_ruleset( $zone_id, $api_token );
if ( is_wp_error( $entrypoint ) ) {
return $entrypoint;
}
if ( null !== $entrypoint ) {
foreach ( (array) ( $entrypoint['rules'] ?? array() ) as $rule ) {
if ( isset( $rule['expression'] ) && $expression === $rule['expression'] ) {
return array( 'created' => false ); // Already there.
}
}
// Ruleset exists, our rule doesn't yet — add it without touching any existing rules.
$added = ajcore_cloudflare_api_request(
'POST',
'https://api.cloudflare.com/client/v4/zones/' . rawurlencode( $zone_id ) . '/rulesets/' . rawurlencode( (string) $entrypoint['id'] ) . '/rules',
$api_token,
array(
'action' => 'block',
'expression' => $expression,
'description' => AJCORE_CLOUDFLARE_RULE_DESCRIPTION,
'enabled' => true,
)
);
if ( is_wp_error( $added ) ) {
return $added;
}
if ( ! $added['success'] ) {
return new WP_Error( 'ajcore_cloudflare_rule_add_failed', ajcore_cloudflare_api_error_message( $added['body'], $added['status'] ) );
}
return array( 'created' => true );
}
// 404 (or any non-success) on the entrypoint GET means this zone has no custom ruleset at
// all yet — create it with our rule as its first entry.
$created = ajcore_cloudflare_api_request(
'POST',
'https://api.cloudflare.com/client/v4/zones/' . rawurlencode( $zone_id ) . '/rulesets',
$api_token,
array(
'name' => 'default',
'kind' => 'zone',
'phase' => 'http_request_firewall_custom',
'rules' => array(
array(
'action' => 'block',
'expression' => $expression,
'description' => AJCORE_CLOUDFLARE_RULE_DESCRIPTION,
'enabled' => true,
),
),
)
);
if ( is_wp_error( $created ) ) {
return $created;
}
if ( ! $created['success'] ) {
return new WP_Error( 'ajcore_cloudflare_ruleset_create_failed', ajcore_cloudflare_api_error_message( $created['body'], $created['status'] ) );
}
return array( 'created' => true );
}
}
if ( ! function_exists( 'ajcore_cloudflare_find_list_item' ) ) {
/**
* @return array|null|WP_Error The matching item (with its own "id", distinct from the IP
* string, needed to delete it later), null if not present.
*/
function ajcore_cloudflare_find_list_item( $account_id, $list_id, $api_token, $ip ) {
$search = ajcore_cloudflare_api_request(
'GET',
'https://api.cloudflare.com/client/v4/accounts/' . rawurlencode( $account_id ) . '/rules/lists/' . rawurlencode( $list_id ) . '/items?search=' . rawurlencode( $ip ),
$api_token
);
if ( is_wp_error( $search ) ) {
return $search;
}
if ( ! $search['success'] ) {
return new WP_Error( 'ajcore_cloudflare_list_search_failed', ajcore_cloudflare_api_error_message( $search['body'], $search['status'] ) );
}
foreach ( (array) ( $search['body']['result'] ?? array() ) as $item ) {
if ( isset( $item['ip'] ) && $ip === $item['ip'] ) {
return $item;
}
}
return null;
}
}
if ( ! function_exists( 'ajcore_cloudflare_poll_bulk_operation' ) ) {
/**
* List item add/remove calls are async on Cloudflare's side — they return an operation_id
* immediately rather than confirming completion. Polls briefly (these normally finish in well
* under a second for a single item); if it hasn't confirmed by the last attempt, treats it as
* "submitted" rather than failing the whole action over a slow poll.
*/
function ajcore_cloudflare_poll_bulk_operation( $account_id, $operation_id, $api_token, $attempts = 3 ) {
for ( $i = 0; $i < $attempts; $i++ ) {
$check = ajcore_cloudflare_api_request(
'GET',
'https://api.cloudflare.com/client/v4/accounts/' . rawurlencode( $account_id ) . '/rules/lists/bulk_operations/' . rawurlencode( $operation_id ),
$api_token
);
if ( ! is_wp_error( $check ) && $check['success'] && isset( $check['body']['result']['status'] ) ) {
$op_status = (string) $check['body']['result']['status'];
if ( 'completed' === $op_status ) {
return true;
}
if ( 'failed' === $op_status ) {
return new WP_Error( 'ajcore_cloudflare_bulk_op_failed', ! empty( $check['body']['result']['error'] ) ? (string) $check['body']['result']['error'] : __( 'Cloudflare list update failed.', 'ajforms' ) );
}
}
if ( $i < $attempts - 1 ) {
usleep( 250000 ); // 0.25s between polls.
}
}
return true; // Submitted but not confirmed within the poll window — not treated as failure.