Repository navigation
Expand file tree
/
Copy pathbootstrap.php
More file actions
3193 lines (2865 loc) · 117 KB
/
Copy pathbootstrap.php
File metadata and controls
3193 lines (2865 loc) · 117 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
// If this file is called directly, abort.
if (!defined( 'WPINC')) {
die;
}
$mailchimp_woocommerce_spl_autoloader = true;
spl_autoload_register(function($class) {
$classes = array(
// helper classes
'Mailchimp_Woocommerce_DB_Helpers' => 'includes/class-mailchimp-woocommerce-db-helpers.php',
// includes root
'MailChimp_Service' => 'includes/class-mailchimp-woocommerce-service.php',
'MailChimp_WooCommerce_Options' => 'includes/class-mailchimp-woocommerce-options.php',
'MailChimp_Newsletter' => 'includes/class-mailchimp-woocommerce-newsletter.php',
'MailChimp_Sms_Consent' => 'includes/class-mailchimp-woocommerce-sms-consent.php',
'MailChimp_WooCommerce_Loader' => 'includes/class-mailchimp-woocommerce-loader.php',
'MailChimp_WooCommerce_i18n' => 'includes/class-mailchimp-woocommerce-i18n.php',
'MailChimp_WooCommerce_Deactivator' => 'includes/class-mailchimp-woocommerce-deactivator.php',
'MailChimp_WooCommerce_Activator' => 'includes/class-mailchimp-woocommerce-activator.php',
'MailChimp_WooCommerce' => 'includes/class-mailchimp-woocommerce.php',
'MailChimp_WooCommerce_Privacy' => 'includes/class-mailchimp-woocommerce-privacy.php',
'Mailchimp_Woocommerce_Deactivation_Survey' => 'includes/class-mailchimp-woocommerce-deactivation-survey.php',
'MailChimp_WooCommerce_Rest_Api' => 'includes/class-mailchimp-woocommerce-rest-api.php',
'Mailchimp_Wocoomerce_CLI' => 'includes/class-mailchimp-woocommerce-cli.php',
'MailChimp_WooCommerce_HPOS' => 'includes/class-mailchimp-woocommerce-hpos.php',
'Mailchimp_Woocommerce_Block_Editor' => 'includes/class-mailchimp-woocommerce-block-editor.php',
// includes/api/assets
'MailChimp_WooCommerce_Address' => 'includes/api/assets/class-mailchimp-address.php',
'MailChimp_WooCommerce_Cart' => 'includes/api/assets/class-mailchimp-cart.php',
'MailChimp_WooCommerce_Customer' => 'includes/api/assets/class-mailchimp-customer.php',
'MailChimp_WooCommerce_LineItem' => 'includes/api/assets/class-mailchimp-line-item.php',
'MailChimp_WooCommerce_Order' => 'includes/api/assets/class-mailchimp-order.php',
'Mailchimp_WooCommerce_Product_Category' => 'includes/api/assets/class-mailchimp-product-category.php',
'MailChimp_WooCommerce_Product' => 'includes/api/assets/class-mailchimp-product.php',
'MailChimp_WooCommerce_ProductVariation' => 'includes/api/assets/class-mailchimp-product-variation.php',
'MailChimp_WooCommerce_PromoCode' => 'includes/api/assets/class-mailchimp-promo-code.php',
'MailChimp_WooCommerce_PromoRule' => 'includes/api/assets/class-mailchimp-promo-rule.php',
'MailChimp_WooCommerce_Store' => 'includes/api/assets/class-mailchimp-store.php',
'MailChimp_WooCommerce_SmsProgram' => 'includes/api/assets/class-mailchimp-sms-program.php',
// includes/api/errors
'MailChimp_WooCommerce_Error' => 'includes/api/errors/class-mailchimp-error.php',
'MailChimp_WooCommerce_RateLimitError' => 'includes/api/errors/class-mailchimp-rate-limit-error.php',
'MailChimp_WooCommerce_ServerError' => 'includes/api/errors/class-mailchimp-server-error.php',
// includes/api/helpers
'MailChimp_WooCommerce_CurrencyCodes' => 'includes/api/helpers/class-mailchimp-woocommerce-api-currency-codes.php',
'MailChimp_Api_Locales' => 'includes/api/helpers/class-mailchimp-woocommerce-api-locales.php',
// includes/api
'MailChimp_WooCommerce_MailChimpApi' => 'includes/api/class-mailchimp-api.php',
'MailChimp_WooCommerce_Api' => 'includes/api/class-mailchimp-woocommerce-api.php',
'MailChimp_WooCommerce_CreateListSubmission' => 'includes/api/class-mailchimp-woocommerce-create-list-submission.php',
'MailChimp_WooCommerce_Transform_Customers' => 'includes/api/class-mailchimp-woocommerce-transform-customers.php',
'MailChimp_WooCommerce_Transform_Coupons' => 'includes/api/class-mailchimp-woocommerce-transform-coupons.php',
'MailChimp_WooCommerce_Transform_Orders' => 'includes/api/class-mailchimp-woocommerce-transform-orders-wc3.php',
'MailChimp_WooCommerce_Transform_Products' => 'includes/api/class-mailchimp-woocommerce-transform-products.php',
'MailChimp_WooCommerce_Transform_Product_Categories' => 'includes/api/class-mailchimp-woocommerce-transform-product-categories.php',
// includes/processes
'Mailchimp_Woocommerce_Job' => 'includes/processes/class-mailchimp-woocommerce-job.php',
'MailChimp_WooCommerce_Abstract_Sync' => 'includes/processes/class-mailchimp-woocommerce-abstract-sync.php',
'MailChimp_WooCommerce_Cart_Update' => 'includes/processes/class-mailchimp-woocommerce-cart-update.php',
'MailChimp_WooCommerce_Process_Customers' => 'includes/processes/class-mailchimp-woocommerce-process-customers.php',
'MailChimp_WooCommerce_Process_Coupons' => 'includes/processes/class-mailchimp-woocommerce-process-coupons.php',
'MailChimp_WooCommerce_Process_Orders' => 'includes/processes/class-mailchimp-woocommerce-process-orders.php',
'MailChimp_WooCommerce_Process_Products' => 'includes/processes/class-mailchimp-woocommerce-process-products.php',
'MailChimp_WooCommerce_Process_Product_Categories' => 'includes/processes/class-mailchimp-woocommerce-process-product-categories.php',
'MailChimp_WooCommerce_SingleCoupon' => 'includes/processes/class-mailchimp-woocommerce-single-coupon.php',
'MailChimp_Woocommerce_Single_Customer' => 'includes/processes/class-mailchimp-woocommerce-single-customer.php',
'MailChimp_WooCommerce_Single_Order' => 'includes/processes/class-mailchimp-woocommerce-single-order.php',
'MailChimp_WooCommerce_Single_Product' => 'includes/processes/class-mailchimp-woocommerce-single-product.php',
'MailChimp_WooCommerce_Single_Product_Variation' => 'includes/processes/class-mailchimp-woocommerce-single-product-variation.php',
'Mailchimp_WooCommerce_Single_Product_Category' => 'includes/processes/class-mailchimp-woocommerce-single-product-category.php',
'MailChimp_WooCommerce_User_Submit' => 'includes/processes/class-mailchimp-woocommerce-user-submit.php',
'MailChimp_WooCommerce_Process_Full_Sync_Manager' => 'includes/processes/class-mailchimp-woocommerce-full-sync-manager.php',
'MailChimp_WooCommerce_Subscriber_Sync' => 'includes/processes/class-mailchimp-woocommerce-subscriber-sync.php',
'MailChimp_WooCommerce_WebHooks_Sync' => 'includes/processes/class-mailchimp-woocommerce-webhooks-sync.php',
'Mailchimp_Woocommerce_Complete_Resource_Sync' => 'includes/processes/class-mailchimp-woocommerce-complete-resource-sync.php',
'MailChimp_WooCommerce_Public' => 'public/class-mailchimp-woocommerce-public.php',
'MailChimp_WooCommerce_Admin' => 'admin/class-mailchimp-woocommerce-admin.php',
'Mailchimp_Woocommerce_Event' => 'admin/v2/processes/class-mailchimp-woocommerce-event.php',
'MailChimp_WooCommerce_Fix_Duplicate_Store' => 'includes/api/class-mailchimp-woocommerce-fix-duplicate-store.php',
'MailChimp_WooCommerce_Logs' => 'includes/api/class-mailchimp-woocommerce-logs.php',
'MailChimp_WooCommerce_Tower' => 'includes/api/class-mailchimp-woocommerce-tower.php',
'MailChimp_WooCommerce_Log_Viewer' => 'includes/api/class-mailchimp-woocommerce-log-viewer.php',
'MailChimp_WooCommerce_Enhanced_Logger' => 'includes/class-mailchimp-woocommerce-enhanced-logger.php',
// pixel tracking
'MailChimp_WooCommerce_Pixel_Tracking' => 'includes/tracking/class-mailchimp-woocommerce-pixel-tracking.php',
);
// if the file exists, require it
$path = plugin_dir_path( __FILE__ );
if (array_key_exists($class, $classes) && file_exists($path.$classes[$class])) {
require $path.$classes[$class];
}
});
/**
* Build (and cache per request) the environment-variables snapshot. This
* function gets called from dozens of logging / version / config sites per
* request — caching eliminates repeated option lookups (especially for
* 'mailchimp-woocommerce-sync.initial_sync' whose row may not exist, which
* would otherwise cost a SELECT per call).
*
* Pass $refresh = true to force a rebuild (e.g. after saving settings in an
* admin handler that needs to see the new value within the same request).
*
* @param bool $refresh
* @return object
*/
function mailchimp_environment_variables($refresh = false) {
static $cached = null;
if ($refresh) {
$cached = null;
}
if ($cached !== null) {
return $cached;
}
global $wp_version;
$o = mailchimp_get_admin_options();
$cached = (object) array(
'repo' => 'master',
'environment' => 'production', // staging or production
'version' => '6.3',
'php_version' => phpversion(),
'wp_version' => (empty($wp_version) ? 'Unknown' : $wp_version),
'wc_version' => function_exists('WC') ? WC()->version : null,
'logging' => ($o && is_array($o) && isset($o['mailchimp_logging'])) ? $o['mailchimp_logging'] : 'standard',
'initial_sync' => \Mailchimp_Woocommerce_DB_Helpers::get_option("mailchimp-woocommerce-sync.initial_sync", false)
);
return $cached;
}
/**
* Option keys that are read on virtually every WP request that loads this
* plugin — not just admin. These are the options touched by update_db_check,
* update_plugin_check, mailchimp_environment_variables, and other early
* code paths that fire between plugins_loaded @ 12 and admin_init.
*
* This set is preloaded on plugins_loaded @ priority 1 so every subsequent
* read in the same request hits the in-memory cache.
*/
function mailchimp_preload_early_keys() {
return array(
'mailchimp-woocommerce', // main options blob
'mailchimp_woocommerce_version', // version compare
'mailchimp-woocommerce-sync.initial_sync', // mailchimp_environment_variables
'mailchimp-woocommerce_cart_table_add_index_update', // update_db_check flag
'mailchimp-woocommerce_cart_table_token_update', // update_db_check flag
'mailchimp-woocommerce_woo_currency_update', // update_db_check flag
'mailchimp_woocommerce_db_mailchimp_carts', // MailChimp_Service::wooIsRunning (fires on woocommerce_init)
);
}
/**
* Runs on plugins_loaded @ 1 — earlier than the plugin's own @ 12 bootstrap.
* By the time update_db_check / update_plugin_check /
* mailchimp_environment_variables execute, their lookups are warm in the
* helper's per-request cache.
*
* Fires on every request (admin + public) because the early code path runs
* either way. Cost is one SELECT ... IN (...) per request.
*/
function mailchimp_preload_early() {
if (!class_exists('\\Mailchimp_Woocommerce_DB_Helpers')) return;
/**
* Filter the early preload list for very-early hooks (before admin_init).
*
* @param array $keys
*/
$keys = apply_filters('mailchimp_preload_early_options', mailchimp_preload_early_keys());
if (!empty($keys)) {
\Mailchimp_Woocommerce_DB_Helpers::preload((array) $keys);
}
}
add_action('plugins_loaded', 'mailchimp_preload_early', 1);
/**
* Baseline option keys that admin-only code paths read. The early set is
* preloaded separately on plugins_loaded @ 1; the helper dedupes, so listing
* them again here is harmless but unnecessary.
*/
function mailchimp_admin_preload_base_keys() {
return array(
'mailchimp-woocommerce-store_id',
'mailchimp-woocommerce-mailchimp_login_id',
'mailchimp-woocommerce-mailchimp_user_id',
'mailchimp-woocommerce-saved_user_id',
'mailchimp-woocommerce-account_name',
'mailchimp-woocommerce-mailchimp_plan',
'mailchimp-woocommerce-comm.opt',
'mailchimp-woocommerce-sync.started_at',
'mailchimp-woocommerce-sync.completed_at',
'mailchimp_woocommerce_db_mailchimp_carts',
'mailchimp-woocommerce-SERVER_ADDR',
'mailchimp_woocommerce_plugin_do_activation_redirect',
'mailchimp-woocommerce-waiting-for-login',
'mailchimp-woocommerce-resource-last-updated',
);
}
/**
* Per-tab option keys on the Mailchimp settings page. The main page uses
* ?tab=<id> to switch between Overview/Store/Audience/Logs/Advanced, so
* different tabs read different option sets. Keys here are additive to the
* base and screen lists.
*/
function mailchimp_admin_preload_keys_for_tab($tab) {
$map = array(
'store_info' => array(
// Read by the SMS consent block on the Store tab.
'mailchimp-woocommerce-tower.opt',
),
'audience' => array(
'mailchimp-woocommerce-cached-api-lists',
),
'advanced' => array(
'mailchimp-woocommerce-tower.opt',
'mailchimp-woocommerce-SERVER_ADDR',
),
);
return isset( $map[ $tab ] ) ? $map[ $tab ] : array();
}
/**
* Per-screen option keys. Add entries here (or via the filter) when a
* specific admin page is known to read a batch of options that aren't in the
* base list. Keys are additive — the base set is always included.
*/
function mailchimp_admin_preload_keys_for_screen($screen_id) {
$map = array(
// Main Mailchimp settings page
'woocommerce_page_mailchimp-woocommerce' => array(
'mailchimp-woocommerce-cached-api-lists',
'mailchimp-woocommerce-cached-api-ping-check',
'mailchimp-woocommerce-waiting-for-login',
'mailchimp-woocommerce-tower.opt',
'mailchimp-woocommerce-errors.store_info',
'mailchimp-woocommerce-validation.api.ping',
),
// WooCommerce dashboard — reads just enough to render the plugin's widgets
'dashboard' => array(
'mailchimp-woocommerce-sync.orders.started_at',
'mailchimp-woocommerce-sync.orders-queueing.completed_at',
'mailchimp-woocommerce-sync.products.started_at',
'mailchimp-woocommerce-sync.products-queueing.completed_at',
),
);
return isset($map[$screen_id]) ? $map[$screen_id] : array();
}
/**
* Transient keys (WITHOUT the _transient_ prefix) that the admin side reads
* on a typical request. Preloading these collapses N × 2 wp_options SELECTs
* down to one batched SELECT per request, and primes WP core's options
* cache so subsequent native get_transient() calls hit memory with no DB
* activity — even on sites without Redis.
*
* Keys that include a list_id are appended in mailchimp_preload_for_admin()
* once the list_id is resolvable (options cache is warm by that point).
*/
function mailchimp_admin_preload_transient_keys() {
return array(
'mailchimp-woocommerce-cached-api-ping-check', // 10min TTL
'mailchimp-woocommerce-cached-api-account-name', // 24h TTL
'mailchimp-woocommerce-cached-api-lists', // 1h TTL
'mailchimp_woocommerce_store_id_verified', // 10min TTL
);
}
/**
* Is this request headed for a Mailchimp plugin admin page or one of our
* AJAX actions? Returns false for every other admin page (post editor,
* users, other plugins' settings, etc.) so we don't burn a DB query
* preloading options nobody on that page will read.
*/
function mailchimp_is_plugin_admin_context() {
if ( ! is_admin() ) {
return false;
}
// AJAX: only preload if the action is one of ours. Browsing other
// plugins' AJAX actions shouldn't pull in our options.
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
$action = '';
if ( isset( $_REQUEST['action'] ) && is_string( $_REQUEST['action'] ) ) {
$action = $_REQUEST['action'];
}
return $action !== ''
&& ( strpos( $action, 'mailchimp' ) === 0
|| strpos( $action, 'mc_woocommerce' ) === 0
|| strpos( $action, 'mailchimp_woocommerce' ) === 0 );
}
// Regular admin requests — ?page= is set before admin_init fires.
if ( isset( $_GET['page'] ) && is_string( $_GET['page'] )
&& strpos( $_GET['page'], 'mailchimp-woocommerce' ) !== false ) {
return true;
}
// Fallback via screen id (populated once admin_init has run for real
// menu pages, catches WooCommerce-subscreen variants).
if ( function_exists( 'get_current_screen' ) ) {
$screen = get_current_screen();
if ( $screen && isset( $screen->id )
&& strpos( $screen->id, 'mailchimp-woocommerce' ) !== false ) {
return true;
}
}
return false;
}
/**
* Single entry point for warming the option cache on admin requests. Hooked
* on admin_init (so get_current_screen() is reliable) and safe to no-op when
* the helper isn't available or this isn't a Mailchimp-related admin view.
*/
function mailchimp_preload_for_admin() {
if ( ! mailchimp_is_plugin_admin_context() ) return;
if ( ! class_exists( '\\Mailchimp_Woocommerce_DB_Helpers' ) ) return;
$screen_id = function_exists('get_current_screen') && get_current_screen()
? get_current_screen()->id
: null;
// ?tab= is the plugin's own sub-page routing, so we can preload keys
// specific to whichever tab is being rendered.
$tab = isset( $_GET['tab'] ) && is_string( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : '';
$keys = array_merge(
mailchimp_admin_preload_base_keys(),
mailchimp_admin_preload_keys_for_screen($screen_id),
$tab !== '' ? mailchimp_admin_preload_keys_for_tab($tab) : array()
);
/**
* Third-party / internal extension point. Filter callbacks receive the
* merged key list and the current screen id, can add/remove/inspect.
*
* @param array $keys option names to preload
* @param string|null $screen_id current admin screen id (may be null early in admin_init)
*/
$keys = apply_filters('mailchimp_preload_options', $keys, $screen_id);
if (!empty($keys)) {
\Mailchimp_Woocommerce_DB_Helpers::preload((array) $keys);
}
// Warm transient caches in a second batched query. Adding list_id-scoped
// transient keys once options are warm (so mailchimp_get_list_id()
// doesn't trigger its own DB read).
$transient_keys = mailchimp_admin_preload_transient_keys();
if ( function_exists( 'mailchimp_get_list_id' ) && ( $list_id = mailchimp_get_list_id() ) ) {
$transient_keys[] = "mailchimp-woocommerce-gdpr-fields.{$list_id}";
$transient_keys[] = "mailchimp_sms_program_{$list_id}";
$transient_keys[] = "mailchimp_sms_status_{$list_id}";
}
/**
* Filter the admin transient preload list.
*
* @param array $transient_keys
* @param string|null $screen_id
*/
$transient_keys = apply_filters('mailchimp_preload_transients', $transient_keys, $screen_id);
if (!empty($transient_keys)) {
\Mailchimp_Woocommerce_DB_Helpers::preload_transients((array) $transient_keys);
}
}
add_action('admin_init', 'mailchimp_preload_for_admin', 1);
/**
* Public/frontend preload. Fires on wp hook (after query parsing, before
* template rendering — well before wp_footer). Only the options the public
* side of the plugin actually reads during a page render.
*/
function mailchimp_preload_for_public() {
if (is_admin()) return;
if (!class_exists('\\Mailchimp_Woocommerce_DB_Helpers')) return;
$keys = array(
'mailchimp-woocommerce-code-snippet',
'mailchimp-woocommerce-script_fragment',
);
/**
* Filter the public preload list.
*
* @param array $keys
*/
$keys = apply_filters('mailchimp_preload_public_options', $keys);
if (!empty($keys)) {
\Mailchimp_Woocommerce_DB_Helpers::preload((array) $keys);
}
}
add_action('wp', 'mailchimp_preload_for_public', 1);
/**
* Is this REST request headed for one of our routes? Matches URI against
* our namespace so preloads don't fire for WooCommerce, WP core, or other
* plugins' REST endpoints.
*/
function mailchimp_is_plugin_rest_context() {
$uri = isset( $_SERVER['REQUEST_URI'] ) ? (string) $_SERVER['REQUEST_URI'] : '';
if ( $uri === '' ) {
return false;
}
// Matches /wp-json/mailchimp-for-woocommerce/v1/... as well as
// ?rest_route=/mailchimp-for-woocommerce/v1/... (permalink-off sites).
return strpos( $uri, '/mailchimp-for-woocommerce/' ) !== false;
}
/**
* REST API requests (wp-json/...) don't fire admin_init, so the admin
* preload never runs. Scoped to our REST namespace only — other plugins'
* REST endpoints shouldn't trigger our preload work.
*/
function mailchimp_preload_for_rest() {
if ( ! mailchimp_is_plugin_rest_context() ) return;
if ( ! class_exists( '\\Mailchimp_Woocommerce_DB_Helpers' ) ) return;
$keys = array(
'mailchimp-woocommerce-store_id',
'mailchimp-woocommerce-store-id-last-verified',
'mailchimp-woocommerce-sync.internal_counter',
'mailchimp-woocommerce-sync.orders.count',
'mailchimp-woocommerce-sync.products.count',
'mailchimp-woocommerce-sync.customers.count',
'mailchimp-woocommerce-sync.coupons.count',
'mailchimp-woocommerce-sync.started_at',
'mailchimp-woocommerce-sync.completed_at',
'mailchimp-woocommerce-sync.last_loop_at',
'mailchimp_woocommerce_db_mailchimp_carts',
);
/**
* Filter the REST preload list.
*
* @param array $keys
*/
$keys = apply_filters('mailchimp_preload_rest_options', $keys);
if (!empty($keys)) {
\Mailchimp_Woocommerce_DB_Helpers::preload((array) $keys);
}
// Transients that REST endpoints commonly read (store-id freshness,
// ping-check). Same rationale as the admin preload — cheap batched
// fetch that eliminates per-read wp_options I/O on sites without
// Redis.
$rest_transient_keys = apply_filters('mailchimp_preload_rest_transients', array(
'mailchimp_woocommerce_store_id_verified',
'mailchimp-woocommerce-cached-api-ping-check',
));
if (!empty($rest_transient_keys)) {
\Mailchimp_Woocommerce_DB_Helpers::preload_transients((array) $rest_transient_keys);
}
}
add_action('rest_api_init', 'mailchimp_preload_for_rest', 1);
/**
* @param Mailchimp_Woocommerce_Job $job
* @param int $delay
*
* @return false|int|string
*/
function mailchimp_as_push( Mailchimp_Woocommerce_Job $job, $delay = 0 ) {
global $wpdb;
$current_page = isset($job->current_page) && $job->current_page >= 0 ? $job->current_page : false;
$job_id = isset($job->id) ? $job->id : ($current_page ? $job->current_page : get_class($job));
$message = ($job_id != get_class($job)) ? ' :: '. (isset($job->current_page) ? 'page ' : 'obj_id ') . $job_id : '';
$attempts = $job->get_attempts() > 0 ? ' attempt:' . $job->get_attempts() : '';
// here is how we can set this on every job.
if (!$job->get_notified_at()) {
$job->set_notified_at(time()+$delay);
}
if ($job->get_attempts() <= 5) {
$job_class = get_class($job);
$args = array(
'job' => maybe_serialize($job),
'obj_id' => $job_id,
'created_at' => gmdate( 'Y-m-d H:i:s', time() )
);
$existing_actions = function_exists('as_get_scheduled_actions') ? as_get_scheduled_actions(array(
'hook' => $job_class,
'status' => ActionScheduler_Store::STATUS_PENDING,
'group' => 'mc-woocommerce',
'args' => array(
'obj_id' => isset($job->id) ? $job->id : null),
)
) : null;
if (!empty($existing_actions)) {
try {
as_unschedule_action($job_class, array('obj_id' => $job->id), 'mc-woocommerce');
$table = $wpdb->prefix . "mailchimp_jobs";
$serialized_job = maybe_serialize($job);
$created_at = gmdate('Y-m-d H:i:s');
$wpdb->query(
$wpdb->prepare(
"UPDATE $table
SET job = %s, created_at = %s
WHERE obj_id = %s AND job LIKE %s",
$serialized_job,
$created_at,
$job->id,
'%' . $job_class . '%'
)
);
} catch (Exception $e) {
}
} else {
$inserted = $wpdb->insert($wpdb->prefix."mailchimp_jobs", $args);
if (!$inserted) {
if ($wpdb->last_error) {
mailchimp_debug('database error on mailchimp_jobs insert', $wpdb->last_error);
}
try {
if (mailchimp_string_contains($wpdb->last_error, 'Table')) {
mailchimp_debug('DB Issue: `mailchimp_job` table was not found!', 'Creating Tables');
install_mailchimp_queue();
$inserted = $wpdb->insert($wpdb->prefix."mailchimp_jobs", $args);
if (!$inserted) {
mailchimp_debug('Queue Job '.get_class($job), $wpdb->last_error);
}
}
} catch (Exception $e) {
mailchimp_error_trace($e, 'trying to create queue tables');
}
}
}
$action_args = array(
'obj_id' => $job_id,
);
// create the action to be handled in X seconds ( default time )
$fire_at = strtotime( '+'.$delay.' seconds' );
// if we have a prepend command, that means it's live traffic, put it to the front of the sync process.
if (isset($job->prepend_to_queue) && $job->prepend_to_queue) {
$sync_started_at = (int) \Mailchimp_Woocommerce_DB_Helpers::get_option('mailchimp-woocommerce-sync.started_at');
if ($sync_started_at > 0) {
$fire_at = $sync_started_at;
mailchimp_debug('action_scheduler. '.get_class($job), "Pushed job {$job_id} to the front of the queue for live traffic");
}
}
$action = as_schedule_single_action( $fire_at, get_class($job), $action_args, "mc-woocommerce");
if (!empty($existing_actions)) {
mailchimp_debug('action_scheduler.reschedule_job', get_class($job) . ($delay > 0 ? ' restarts in '.$delay. ' seconds' : ' re-queued' ) . $message . $attempts);
} else if (!empty($action)) {
mailchimp_log('action_scheduler.queue_job', get_class($job) . ($delay > 0 ? ' starts in '.$delay. ' seconds' : ' queued' ) . $message . $attempts." with id {$action}");
} else {
mailchimp_debug("action_scheduler.queue_job.fail", get_class($job). " :: no action id was saved while trying to schedule action!");
}
return $action;
} else {
$job->set_attempts(0);
mailchimp_log('action_scheduler.fail_job', get_class($job) . ' cancelled. Too many attempts' . $message . $attempts);
return false;
}
}
/**
* We will allow people to filter delay value to specific jobs.
* add_filter( 'mailchimp_handle_or_queue_{$resource}_delay', 'custom_handle_or_queue_resource_function', 10, 1 );
* where $resource is one of the following - product, order, customer, coupon
*
* @param Mailchimp_Woocommerce_Job $job
* @param int $delay
*/
function mailchimp_handle_or_queue(Mailchimp_Woocommerce_Job $job, $delay = 0)
{
if ($job instanceof MailChimp_WooCommerce_Single_Order && isset($job->id) && empty($job->gdpr_fields)) {
// if this is a order process already queued - just skip this
if (get_transient("mailchimp_order_being_processed_{$job->id}") == true) {
mailchimp_debug('queue', "Not queuing up order {$job->id} because it's already queued");
return;
}
// tell the system the order is already queued for processing in this saving process - and we don't need to process it again.
set_transient( "mailchimp_order_being_processed_{$job->id}", true, 30);
}
// Allow sites to alter whether the order or product is synced.
// $job should contain at least the ID of the order/product as $job->id.
$filter_delay = null;
if ( $job instanceof \MailChimp_WooCommerce_Single_Order ) {
$filter_delay = apply_filters('mailchimp_handle_or_queue_order_delay', $delay);
if ( apply_filters( 'mailchimp_should_push_order', $job->id ) === false ) {
mailchimp_debug( 'action_scheduler.queue_job.order', "Order {$job->id} not pushed do to filter." );
return null;
}
} else if ( $job instanceof \MailChimp_WooCommerce_Single_Product ) {
$filter_delay = apply_filters('mailchimp_handle_or_queue_product_delay', $delay);
if ( apply_filters( 'mailchimp_should_push_product', $job->id ) === false ) {
mailchimp_debug( 'action_scheduler.queue_job.product', "Product {$job->id} not pushed do to filter." );
return null;
}
} else if ( $job instanceof \MailChimp_WooCommerce_Single_Product_Variation ) {
$filter_delay = apply_filters('mailchimp_handle_or_queue_product_variation_delay', $delay);
if ( apply_filters( 'mailchimp_should_push_product_variations', $job->id ) === false ) {
mailchimp_debug( 'action_scheduler.queue_job.product_variation', "Product {$job->id} not pushed do to filter." );
return null;
}
} else if ( $job instanceof \MailChimp_WooCommerce_User_Submit ) {
$filter_delay = apply_filters('mailchimp_handle_or_queue_customer_delay', $delay);
} else if ( $job instanceof \MailChimp_WooCommerce_SingleCoupon ) {
$filter_delay = apply_filters('mailchimp_handle_or_queue_coupon_delay', $delay);
if ( apply_filters( 'mailchimp_should_push_coupon', $job->id ) === false ) {
mailchimp_debug( 'action_scheduler.queue_job.order', "Coupon {$job->id} not pushed do to filter." );
return null;
}
}
$filter_delay = !is_null($filter_delay) && is_int($filter_delay) ? $filter_delay : $delay;
$as_job_id = mailchimp_as_push($job, $filter_delay);
if (!is_int($as_job_id)) {
mailchimp_log('action_scheduler.queue_fail', get_class($job) .' FAILED :: as_job_id: '.$as_job_id);
}
}
/**
* Queue a job triggered by a live WooCommerce/WP hook, so its requests carry
* X-Object-Notified-At. Never use for initial sync jobs.
*
* @param Mailchimp_Woocommerce_Job $job
* @param int $delay
*/
function mailchimp_handle_or_queue_live(Mailchimp_Woocommerce_Job $job, $delay = 0)
{
mailchimp_handle_or_queue($job->mark_live_event(), $delay);
}
/**
* Remove pending actions and their persisted payloads for one job class/object.
* Already-running actions cannot be unscheduled.
*
* @return bool
*/
function mailchimp_delete_job_by_id($id, $job_class = null)
{
if (empty($id) || empty($job_class)) {
return false;
}
global $wpdb;
$success = true;
try {
if (function_exists('as_unschedule_all_actions')) {
as_unschedule_all_actions($job_class, array('obj_id' => $id), 'mc-woocommerce');
}
} catch (\Exception $e) {
$success = false;
mailchimp_log('action_scheduler.delete_job_by_id', 'Failed to cancel pending actions', array(
'job_class' => $job_class,
'exception' => $e->getMessage(),
));
}
// Action Scheduler stores only obj_id; the payload lives in mailchimp_jobs.
// Match the serialized object's class prefix, not a class name in its data.
$class_prefix = 'O:' . strlen($job_class) . ':"' . $job_class . '":';
$deleted = $wpdb->query($wpdb->prepare(
"DELETE FROM {$wpdb->prefix}mailchimp_jobs WHERE obj_id = %s AND job LIKE %s",
$id,
$wpdb->esc_like($class_prefix) . '%'
));
if ($deleted === false) {
mailchimp_log('action_scheduler.delete_job_by_id', 'Failed to delete persisted jobs', array(
'job_class' => $job_class,
));
return false;
}
return $success;
}
/**
* @param $job_hook
*
* @return int
*/
function mailchimp_get_remaining_jobs_count($job_hook) {
$existing_actions = function_exists('as_get_scheduled_actions') ? as_get_scheduled_actions(
array(
'hook' => $job_hook,
'status' => ActionScheduler_Store::STATUS_PENDING,
'group' => 'mc-woocommerce',
'per_page' => -1,
), 'ids'
) : null;
// mailchimp_log('sync.full_sync_manager.queue', "counting {$job_hook} actions:", array($existing_actions));
return count($existing_actions);
}
function mailchimp_submit_subscribed_only() {
return ! (bool) mailchimp_get_option('mailchimp_ongoing_sync_status', '1');
}
function get_woo_session($key, $default = null)
{
if (!function_exists('WC')) return $default;
if (!($woo = WC()) || empty(WC()->session)) {
return $default;
}
// not really sure why this would be the case, but if there is no session we can't get it anyway.
if (!is_object($woo->session) || !method_exists($woo->session, 'get')) {
return $default;
}
return $woo->session->get($key, $default);
}
/**
* @return bool
*/
function mailchimp_sync_existing_contacts_only() {
return mailchimp_get_option('mailchimp_auto_subscribe', '1') === '2';
}
/**
* @return bool
*/
function mailchimp_carts_disabled() {
return mailchimp_get_option('mailchimp_cart_tracking', 'all') === 'disabled';
}
/**
* @return bool
*/
function mailchimp_carts_subscribers_only() {
return mailchimp_get_option('mailchimp_cart_tracking', 'all') === 'subscribed';
}
/**
* @return bool
*/
function mailchimp_landing_tracking_enabled() {
return (bool) mailchimp_get_option('mailchimp-woocommerce-enable-landing-tracking', false);
}
/**
* @param $email
* @return string|null
*/
function mailchimp_get_subscriber_status($email) {
try {
return mailchimp_get_api()->member(mailchimp_get_list_id(), $email)['status'];
} catch (Exception $e) {
return null;
}
}
/**
* @param false $force
*
* @return bool
* @throws MailChimp_WooCommerce_Error
* @throws MailChimp_WooCommerce_RateLimitError
* @throws MailChimp_WooCommerce_ServerError
*/
function mailchimp_list_has_double_optin($force = false) {
if (!mailchimp_is_configured()) {
return false;
}
$key = 'double_optin';
$double_optin = mailchimp_get_transient($key);
if (!$force && (isset($double_optin['value']) && ($double_optin['value'] === 'yes' || $double_optin['value'] === 'no'))) {
return $double_optin['value'] === 'yes';
}
try {
$data = mailchimp_get_api()->getList(mailchimp_get_list_id());
$double_optin = array_key_exists('double_optin', $data) ? ($data['double_optin'] ? 'yes' : 'no') : 'no';
mailchimp_set_transient($key, $double_optin, 600);
mailchimp_debug('mailchimp.doi', 'pulled the list again');
return $double_optin === 'yes';
} catch (Exception $e) {
mailchimp_error('api.list', __('Error retrieving list for double_optin check', 'mailchimp-for-woocommerce'));
throw $e;
}
}
/**
* @return bool
*/
function mailchimp_is_configured() {
return (bool) (mailchimp_get_api_key() && mailchimp_get_list_id());
}
/**
* @return bool
*/
function mailchimp_action_scheduler_exists() {
return ( did_action( 'plugins_loaded' ) && ! doing_action( 'plugins_loaded' ) && class_exists( 'ActionScheduler', false ) );
}
/**
* @return bool|int
*/
function mailchimp_get_api_key() {
return mailchimp_get_option('mailchimp_api_key', false);
}
/**
* @return bool|int
*/
function mailchimp_get_list_id() {
return mailchimp_get_option('mailchimp_list', false);
}
/**
* @param $key
*
* @return string
*/
function mailchimp_build_webhook_url( $key ) {
$rest_url = MailChimp_WooCommerce_Rest_Api::url('member-sync');
$qs = mailchimp_string_contains($rest_url, '/wp-json/') ? '?' : '&';
return $rest_url.$qs."auth={$key}";
}
/**
* Generate random string
* @return string
*/
function mailchimp_create_webhook_token(){
return md5( trim( strtolower(get_bloginfo('url') . '|' . time() . '|' . mailchimp_get_list_id() . '|' . wp_salt() ) ) );
}
/**
* @param $url
*/
function mailchimp_set_webhook_url( $url ) {
\Mailchimp_Woocommerce_DB_Helpers::update_option('mc-mailchimp_webhook_url', $url);
}
/**
* Returns webhookurl option
* @return string
*/
function mailchimp_get_webhook_url() {
return \Mailchimp_Woocommerce_DB_Helpers::get_option('mc-mailchimp_webhook_url', false);
}
/**
* Returns webhook url
* @return array Common localhost ips
*/
function mailchimp_common_loopback_ips(){
return array(
'127.0.0.1',
'0:0:0:0:0:0:0:1',
'::1'
);
}
/**
* @return mixed|string
*/
function mailchimp_get_store_id() {
$store_id = mailchimp_get_data('store_id', false);
// "Was this store_id verified against Mailchimp recently?" — tracked as a
// transient with a 10-minute TTL instead of a timestamp option that we
// manually subtract against time(). With an object cache (Redis), the
// read and the write are zero wp_options queries; without one, they're
// still lighter than the old get_option + compare + update_option dance
// and self-expire so there's no timestamp row accumulating stale values.
$verified_transient = 'mailchimp_woocommerce_store_id_verified';
if (!empty($store_id) && get_transient($verified_transient)) {
return $store_id;
}
$api = mailchimp_get_api();
if (mailchimp_is_configured()) {
// let's retrieve the store for this domain, through the API
$store = $api->getStoreIfAvailable($store_id);
// if there's no store, try to fetch from mc a store related to the current domain
if (!$store) {
$stores = $api->stores();
if (!empty($stores)) {
//iterate thru stores, find correct store ID and save it to db
foreach ($stores as $mc_store) {
if ($mc_store->getDomain() === get_option('siteurl')) {
// Route through the helper so our in-process caches
// and object-cache invalidations stay consistent.
\Mailchimp_Woocommerce_DB_Helpers::update_option('mailchimp-woocommerce-store_id', $mc_store->getId(), 'yes');
$store_id = $mc_store->getId();
}
}
}
}
}
if (empty($store_id)) {
mailchimp_set_data('store_id', $store_id = uniqid());
}
// Mark this store_id as verified for the next 10 minutes.
set_transient($verified_transient, 1, 600);
return $store_id;
}
/**
* @param null $email
* @param null $order
*
* @return false|mixed|void
*/
function mailchimp_get_user_tags_to_update($email = null, $order = null) {
$tags = mailchimp_get_option('mailchimp_user_tags');
$formatted_tags = array();
if (!empty($tags)) {
$tags = explode(',', $tags);
foreach ($tags as $tag) {
$formatted_tags[] = array("name" => $tag, "status" => 'active');
}
}
// apply filter to user custom tags addition/removal
$formatted_tags = apply_filters('mailchimp_user_tags', $formatted_tags, $email, $order);
return empty($formatted_tags) ? false : $formatted_tags;
}
/**
* @return bool|MailChimp_WooCommerce_MailChimpApi
*/
function mailchimp_get_api() {
if (($api = MailChimp_WooCommerce_MailChimpApi::getInstance())) {
return $api;
}
if (($key = mailchimp_get_api_key())) {
return MailChimp_WooCommerce_MailChimpApi::constructInstance($key);
}
return false;
}
/**
* @param $key
* @param null $default
* @return null
*/
function mailchimp_get_option($key, $default = null) {
$options = mailchimp_get_admin_options();
if (!is_array($options)) {
return $default;
}