-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
1542 lines (1271 loc) · 51.2 KB
/
index.php
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: WooCommerce - Mailchimp Product to List Sync
Description: Assign WooCommerce products to Mailchimp Audiences (old Lists) and sync customers to them upon completed purchase/payment.
Author: Shambix
Version: 1.0.2
Author URI: https://www.shambix.com/
License: GPL V3
Text Domain: wmptls
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) die;
class woo_mailchimp_product_class{
private $_plugin_ver = '1.0.2';
private $_db_ver = '1.0';
public $textdomain = 'wmptls';
protected static $_instance = null;
public function __construct(){
global $wpdb;
$this->BASE_PATH = rtrim( dirname(__FILE__), '/' );
$this->BASE_URL = trim( plugin_dir_url( __FILE__ ), '/' );
$this->LOGS_TABLE_NAME = $wpdb->prefix . $this->textdomain . '_logs';
$this->includes();
$this->declare_hooks();
}
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
protected function includes(){
require_once $this->BASE_PATH . '/includes/functions.php';
}
protected function declare_hooks(){
## Activation & deactivation
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
## Plugin related
add_action( 'init', array($this, 'plugins_init') );
add_action( 'plugins_loaded', array( $this, 'plugins_loaded') );
## Endpoint
add_action( 'init', array($this, 'endpoint_create'), 1, 0);
add_action( 'template_redirect', array($this, 'endpoint_handler'), 1 );
## Session
add_action( 'init', array($this, 'init_session'), 1, 0);
}
public function get_version(){
return $this->_plugin_ver . ' / ' . $this->_db_ver;
}
public function activate(){
global $wpdb;
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$charset_collate = $wpdb->get_charset_collate();
## main log
$table_name = $this->LOGS_TABLE_NAME;
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
log_time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
log_type varchar(255) DEFAULT '' NOT NULL,
log_info LONGTEXT,
is_debug tinyint(1) DEFAULT 1,
ipaddress varchar(15) DEFAULT '' NOT NULL,
log_group_id varchar(255) DEFAULT '' NOT NULL,
log_plugin varchar(255) DEFAULT '' NOT NULL,
log_email varchar(255) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
dbDelta( $sql );
$this->save_setting( $this->_db_ver, 'db_ver');
## clear local cache
$this->clear_local_cache();
}
public function deactivate(){
## clear local cache
$this->clear_local_cache();
return true;
}
public function plugins_init(){
do_action( 'wmptls_init' );
}
public function plugins_loaded(){
/* Upgrade mysql table if necessary */
if( $this->get_setting( 'db_ver') != $this->_db_ver ){
$this->activate();
}
if(is_admin()){
## Backend enqueue
add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts_backend'));
add_action('admin_menu', array($this, 'register_admin_menu'),99);
## Methods to handle admin submission
add_action( 'admin_notices', array( $this, 'callback_admin_notice') );
## Methods to handle admin submission
add_action( 'admin_post_' . $this->textdomain . '_configuration', array( $this, 'callback_configuration' ) );
add_action( 'admin_post_' . $this->textdomain . '_admin_log_clear', array( $this, 'callback_log_clear' ) );
add_action( 'admin_post_' . $this->textdomain . '_admin_download_logs', array( $this, 'callback_admin_download_logs_by_group' ) );
## Methods to handle administration ajax
add_action( 'wp_ajax_' . $this->textdomain . '_configuration', array( $this, 'callback_admin_ajax_test_api') );
add_action( 'wp_ajax_' . $this->textdomain . '_admin_delete_logs', array( $this, 'callback_admin_delete_logs') );
add_action( 'wp_ajax_' . $this->textdomain . '_admin_force_sync', array( $this, 'callback_admin_force_sync') );
//if(wp_get_current_user()->user_login == 'prv_admin'){///\\\///\\\todo
add_action( 'add_meta_boxes', array( $this, 'add_meta_box' ) );
add_action( 'save_post', array( $this, 'save_meta_box' ) );
//add_action( 'add_meta_boxes', array( $this, 'add_meta_box_order' ) );
add_action( 'save_post', array( $this, 'save_meta_box_order' ) );
add_action( 'woocommerce_before_order_itemmeta', array( $this, 'before_order_itemmeta' ), 100, 3);
//}
}else{
## Frontend enqueue
//add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts_frontend' ) );
}
## Action links
add_action( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'plugin_action_links') );
//if(wp_get_current_user()->user_login == 'prv_admin'){///\\\///\\\todo
//add_action( 'woocommerce_thankyou', array( $this, 'sync_order' ), 10, 1 );
add_action( 'woocommerce_payment_complete', array( $this, 'sync_order' ), 10, 1 );
//}
}
public function plugin_action_links( $links ) {
$links = array_merge( array(
'<a href="' . esc_url( $this->admin_url() ) . '">' . __( 'Setting', 'wmptls' ) . '</a>',
'<a href="' . esc_url( $this->admin_url( array('tab' => 'logs') ) ) . '">' . __( 'Logs', 'wmptls' ) . '</a>',
), $links );
return $links;
}
/* Get all settings required for this plugin */
public function get_setting($field = false){
return func_get_setting($field, $this->textdomain . '_options');
}
/* Save setting for this plugin, all or specific setting */
public function save_setting($values, $key = false){
return func_save_setting($values, $key, $this->textdomain . '_options');
}
public function admin_url( $query_vars = false ){
// Get target tab
$tab = ( isset($_REQUEST['tab']) ) ? wp_kses($_REQUEST['tab'], '') : '';
if( is_string($query_vars) && strpos($query_vars, 'http') === false ){
parse_str(trim($query_vars, '&'), $query_vars);
}
// Check if the 'tab' var exist in query_vars, and use it if set
if( is_array($query_vars) && isset($query_vars['tab']) ){
$tab = $query_vars['tab'];
unset($query_vars['tab']);
}
// Default admin url for this plugin
if( is_string($query_vars) && strpos($query_vars, 'http') === 0 ){
$url = $query_vars;
}else{
$url = admin_url( 'admin.php?page=' . $this->textdomain . (($tab) ? '&tab=' . $tab : '') );
}
// Include query_vars if any
if( $query_vars ){
if( is_array($query_vars) ){
$url .= '&' . http_build_query($query_vars);
}elseif( is_string($query_vars) ){
if( strpos($query_vars, 'http') === 0 ){
//no action here
}
}
}
return $url;
}
public function logger($type, $info, $is_debug = true, $log_group_id = false, $log_plugin = false, $log_email = false){
global $wpdb;
$info = ( is_array($info) || is_object($info) ) ? print_r( $info, true ) : $info;
if(is_null($is_debug)) $is_debug = true;
$log_group_id = ($log_group_id === false || is_null($log_group_id)) ? $this->_get_log_group_id() : $log_group_id;
$log_plugin = ($log_plugin === false || is_null($log_plugin)) ? $this->_get_log_plugin() : $log_plugin;
$log_email = ($log_email === false || is_null($log_email)) ? $this->_get_log_email() : $log_email;
$arr = array(
'log_time' => current_time( 'mysql' ),
'log_type' => $type,
'log_info' => $info,
'is_debug' => (int)$is_debug,
'ipaddress' => func_get_ip_address(),
'log_group_id' => $log_group_id,
'log_plugin' => $log_plugin,
'log_email' => $log_email,
);
$wpdb->insert( $this->LOGS_TABLE_NAME, $arr );
}
protected function _create_log_group_id(){
$_SESSION['log_group_id'] = substr(md5(uniqid(mt_rand(), true)), 0, 5);
return $_SESSION['log_group_id'];
}
protected function _get_log_group_id(){
if( isset($_SESSION['log_group_id']) && strlen($_SESSION['log_group_id']) > 3 ){
return $_SESSION['log_group_id'];
}
return false;
}
protected function _get_log_plugin(){
if( isset($_SESSION['log_plugin']) ){
return $_SESSION['log_plugin'];
}
return false;
}
protected function _get_log_email(){
if( isset($_SESSION['log_email']) ){
return $_SESSION['log_email'];
}
return false;
}
public function whos_called($index = 2){
$out = '';
if($trace = debug_backtrace()){
if( isset($trace[$index]) ){
if( isset($trace[$index]['class']) ){
$out .= $trace[$index]['class'] . $trace[$index]['type'];
}
if( isset($trace[$index]['function']) ){
$out .= $trace[$index]['function'] . '()';
}
if( isset($trace[$index]['line']) ){
$out .= ':' . $trace[$index]['line'];
}
}
}
return $out;
}
public function callback_admin_notice() {
$screen = get_current_screen();
if( $screen->id != 'woocommerce_page_' . $this->textdomain ) return false;
if( !isset( $_GET['message'] ) ) return false;
switch($_GET['message']){
case 'update':
$class = 'notice notice-success is-dismissible';
$message = __( 'Setting saved.', $this->textdomain );
break;
case 'clearlogs':
$class = 'notice notice-success is-dismissible';
$message = __( 'Logs has been cleared.', $this->textdomain );
break;
}
if( isset($message) && isset($class) ){
printf( '<div class="%1$s"><p>%2$s</p></div>', $class, $message );
}
return true;
}
public function callback_configuration(){
if($_POST){
//func_pr($_POST);die;
$api_key = ( isset($_POST['api_key']) ) ? $_POST['api_key'] : false;
$csv_delimiter = ( isset($_POST['csv_delimiter']) ) ? trim($_POST['csv_delimiter']) : false;
$create_list = ( isset($_POST['create_list']) ) ? $_POST['create_list'] : false;
// Save settings
$this->save_setting($api_key, 'api_key');
$this->save_setting($csv_delimiter, 'csv_delimiter');
$this->save_setting($create_list, 'create_list');
// Clear all local cache
if($clear_cache == 'YES'){
$this->clear_local_cache();
}
wp_redirect( $this->admin_url( array('message' => 'update') ) ); exit;
}
wp_redirect( $this->admin_url() ); exit;
}
public function callback_log_clear(){
global $wpdb;
check_admin_referer('clear_logs');
$table_name = $this->LOGS_TABLE_NAME;
$wpdb->query("TRUNCATE TABLE $table_name");
wp_redirect( $this->admin_url( array('tab' => 'logs', 'message' => 'clearlogs') ) ); exit;
}
public function callback_admin_delete_logs(){
global $wpdb;
if( isset($_POST['delete_ids']) ){
$table_name = $this->LOGS_TABLE_NAME;
$output_ids = false;
$delete_ids = $_POST['delete_ids'];
foreach($delete_ids as $i => $id){
$sql = "DELETE FROM {$table_name} WHERE id = " . $id . " LIMIT 1";
$query = $wpdb->get_results( $sql );
$output_ids[] = $id;
}
echo json_encode( array('status' => 'ok', 'message' => $output_ids ) );
}else{
echo json_encode( array('status' => 'error', 'message' => 'Data error') );
}
exit();
}
public function callback_admin_force_sync(){
if( isset($_POST['order_id']) && isset($_POST['item_id']) ){
$order_id = (int)$_POST['order_id'];
$item_id = (int)$_POST['item_id'];
if($order_id && $item_id){
//___________________________________________________________________________________
$data = $this->get_order_data($order_id);
if($data['order_status'] != 'completed'){
//echo json_encode( array('status' => 'error', 'message' => 'Order status is not completed!') );
}
//set sessions for log
$_SESSION['log_group_id'] = substr(md5(uniqid(mt_rand(), true)), 0, 5);
$_SESSION['log_plugin'] = 'WOO';
$_SESSION['log_email'] = wp_get_current_user()->user_email;
foreach($data['products'] as $z => $prod){
$db_item_id = $prod['item_id'];
$db_product_id = $prod['product_id'];
if($db_item_id == $item_id){
$mailchimp_list_member_sync = wc_get_order_item_meta($item_id, 'mailchimp_list_member_sync', true);
//____________________________________________________________
/////if($mailchimp_list_member_sync != 'YES'){
$mailchimp_list_id = get_post_meta( $db_product_id, 'mailchimp_list_id', true );
if( strlen($mailchimp_list_id) >= 3 ){
$body = array(
'email_address' => $data['order_billing_email'],
'status' => 'subscribed',
'merge_fields' => array(
'FNAME' => $data['order_billing_first_name'],
'LNAME' => $data['order_billing_last_name'],
//'BIRTHDAY' => '',
/*'ADDRESS' => array(
'addr1' => $data['order_billing_address_1'],
'city' => $data['order_billing_city'],
'state' => $data['order_billing_state'],
'zip' => $data['order_billing_postcode'],
),*/
),
);
$arr = $this->call_api('POST', '/lists/' . $mailchimp_list_id . '/members', 'skip_merge_validation=false', $body);
if($arr['status'] == 'ok'){
//return $arr['data']->id;
wc_add_order_item_meta($item_id, 'mailchimp_list_member_sync', 'YES');
}
}
/////}
//____________________________________________________________
break;
}
}
//___________________________________________________________________________________
echo json_encode( array('status' => 'ok', 'message' => '' ) );
}else{
echo json_encode( array('status' => 'error', 'message' => 'Data error') );
}
}else{
echo json_encode( array('status' => 'error', 'message' => 'Data error') );
}
exit();
}
public function callback_admin_download_logs_by_group(){
date_default_timezone_set('Europe/Rome');
global $wpdb;
$filename_to_download = 'wmptls-logs-' . date('YmdHis') . '.csv';
$csv_delimiter = $this->get_setting('csv_delimiter');
if(!$csv_delimiter) $csv_delimiter = ',';
// Redirect output to a client’s web browser (html)
header('Content-Type: application/csv');
header('Content-Disposition: attachment;filename="' . $filename_to_download . '"');
header('Pragma: no-cache');
$outstream = fopen('php://output', 'wb');
$table_name = $this->LOGS_TABLE_NAME;
$sql = "(SELECT * FROM {$table_name} ORDER BY id DESC) ORDER BY id ASC";
$header = ['ID', 'DATE TIME', 'PLUGIN', 'EMAIL'];
for($i = 1; $i <= 5; $i++){
$header[] = sprintf('LOG#%s', $i);
}
$total_cols = sizeof($header);
fputcsv($outstream, $header, $csv_delimiter);
$query = $wpdb->get_results( $sql );
if($query){
$prev_log_group_id = false;
foreach ($query as $line) {
$log_group_id = $line->log_group_id;
if($log_group_id != $prev_log_group_id){
if($prev_log_group_id !== false){
if(sizeof($result) < $total_cols){
for($i = 0; $i < ($total_cols - sizeof($result)); $i++){
$result[] = '';
}
}
fputcsv($outstream, $result, $csv_delimiter);
}
$prev_log_group_id = $log_group_id;
$result = false;
$result[] = $line->log_group_id;
$result[] = date('M d, Y H:i:s', strtotime($line->log_time));
$result[] = $line->log_plugin;
$result[] = $line->log_email;
}
$log_info = str_replace( array('\"', "\'"), array('"', "'"), $line->log_info);
$result[] = $line->log_type . PHP_EOL . PHP_EOL . $log_info;
}
if(sizeof($result) < $total_cols){
for($i = 0; $i < ($total_cols - sizeof($result)); $i++){
$result[] = '';
}
}
fputcsv($outstream, $result, $csv_delimiter);
}
fclose($outstream);
exit;
}
private function clear_local_cache(){
$cache_key = array();
foreach($cache_key as $id => $key){
delete_transient( $key );
}
return true;
}
public function register_admin_menu() {
add_submenu_page( 'woocommerce', 'Mailchimp Product Sync', 'Mailchimp Product Sync', 'manage_options', $this->textdomain, array($this, 'admin_menu_callback') );
}
public function admin_menu_callback(){
include( $this->BASE_PATH . '/view/admin_tabs.php' );
}
public function enqueue_scripts_backend(){
wp_enqueue_style ( $this->textdomain . '-admin-styles', $this->BASE_URL . '/assets/admin.css' );
wp_enqueue_script( $this->textdomain . '-admin-script', $this->BASE_URL . '/assets/admin.js', array(), '1.0' );
//local vars
wp_localize_script( $this->textdomain . '-admin-script', 'localize_var',
array(
'base_url' => $this->BASE_URL,
'base_admin_url' => rtrim(get_admin_url(), '/'),
'ajax_security' => wp_create_nonce( 'special-' . $this->textdomain . '-string' ),
)
);
}
public function enqueue_scripts_frontend(){
// WOOCOMMERCE
/*if (function_exists('is_product') && is_woocommerce()) {
wp_enqueue_style( $this->textdomain . '-style', $this->BASE_URL . '/assets/frontend.css' );
wp_enqueue_script( $this->textdomain . '-script', $this->BASE_URL . '/assets/frontend.js', array('jquery'), '1.0.0', true );
}*/
//local vars
wp_localize_script( $this->textdomain . '-frontend-script', 'localize_var',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajax_security' => wp_create_nonce( 'special-' . $this->textdomain . '-string' ),
)
);
}
public function get_available_endpoints(){
return false;
}
public function endpoint_create(){
if($endpoints = $this->get_available_endpoints()){
foreach($endpoints as $i => $arr){
add_rewrite_endpoint( $arr['endpoint'], EP_ALL );
}
flush_rewrite_rules();
}
}
public function endpoint_handler() {
global $wp_query;
if($endpoints = $this->get_available_endpoints()){
foreach($endpoints as $i => $arr){
if ( isset( $wp_query->query_vars[$arr['endpoint']] ) ){
if(is_callable(array($this, $arr['method']))){
$this->{$arr['method']}();
exit();
}else{
return;
}
}
}
}
return;
}
public function init_session() {
if ( ! session_id() ) {
session_start();
}
}
//___________________________________________________________________________________
// API CALL
//___________________________________________________________________________________
public function get_api_data_center(){
$api_key = $this->get_setting('api_key');
$dc = substr($api_key, strpos($api_key, '-') + 1); //datacenter
return $dc;
}
public function call_api($method, $path = '', $query = false, $body = false, $additional_headers = false){
$api_key = $this->get_setting('api_key');
$dc = substr($api_key, strpos($api_key, '-') + 1); //datacenter
if( !in_array($method, array('GET', 'POST', 'PUT', 'PATCH', 'DELETE')) ){
return false;
}
$args = array(
'method' => $method,
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'user:'. $api_key )
)
);
if( is_array($body) && sizeof($body) ){
$args['body'] = json_encode($body);
}
$url = 'https://' . $dc . '.api.mailchimp.com/3.0' . $path;
$path_complete = $path;
if($query){
$url .= '?' . $query;
$path_complete .= '?' . $query;
}
$logger_type = sprintf('%s %s %s%s', $method, $path_complete, PHP_EOL . PHP_EOL, $this->whos_called());
$this->logger($logger_type, $body, false);
if($method == 'GET'){
$response = wp_remote_get( $url, $args );
}else{
$response = wp_remote_post( $url, $args );
}
$response_body = json_decode( wp_remote_retrieve_body( $response ) );
$logger_type = sprintf('%s %s %s%s', 'RESPONSE', $path_complete, PHP_EOL . PHP_EOL, $this->whos_called());
$this->logger($logger_type, $response_body, false);
if ( wp_remote_retrieve_response_code( $response ) == 200 ) {
return array('status' => 'ok', 'data' => $response_body, 'message' => null );
} else {
return array('status' => wp_remote_retrieve_response_code( $response ), 'data' => null, 'message' => wp_remote_retrieve_response_message( $response ) );
}
}
public function callback_admin_ajax_test_api(){
if( isset($_POST['test']) && $_POST['test'] == 'yes' ){
//set sessions for log
$_SESSION['log_group_id'] = substr(md5(uniqid(mt_rand(), true)), 0, 5);
$_SESSION['log_plugin'] = 'SYSTEM';
$_SESSION['log_email'] = wp_get_current_user()->user_email;
$out = $this->call_api('GET', '/ping');
if($out['status'] == 'ok' && isset($out['data']->health_status)){
echo json_encode( array('status' => 'ok', 'message' => $out['data']->health_status ) );
}else{
echo json_encode( array('status' => 'error', 'message' => $out['message']) );
}
}
exit();
}
//___________________________________________________________________________________
// MAILCHIMP
//___________________________________________________________________________________
public function get_mailchimp_lists($force_update = false, $count = 10){
//get cache
$cache_key = 'wmptls-mailchimp-lists';
$out = get_transient( $cache_key );
// Debug
if($force_update) {
$out = false;
}
if($out === false){
//set sessions for log
$_SESSION['log_group_id'] = substr(md5(uniqid(mt_rand(), true)), 0, 5);
$_SESSION['log_plugin'] = 'SYSTEM';
$_SESSION['log_email'] = wp_get_current_user()->user_email;
if($count < 1) $count = 10;
$arr = $this->call_api('GET', '/lists', 'sort_field=date_created&sort_dir=DESC&count=' . $count);
if($arr['status'] == 'ok' && $arr['data']->lists){
foreach($arr['data']->lists as $x => $obj){
$url = 'https://' . $this->get_api_data_center() . '.admin.mailchimp.com/lists/members/?id=' . $obj->web_id;
$out[] = [
'id' => $obj->id,
'web_id' => $obj->web_id,
'title' => $obj->name,
'created' => $obj->date_created,
'count' => (int)$obj->stats->member_count,
'url' => $url,
];
}
}
set_transient( $cache_key, $out, 1 * DAY_IN_SECONDS );
}
return $out;
}
public function check_api_list_exist($mailchimp_list_id){
if( !strlen($mailchimp_list_id) ) return false;
//set sessions for log
$_SESSION['log_group_id'] = substr(md5(uniqid(mt_rand(), true)), 0, 5);
$_SESSION['log_plugin'] = 'SYSTEM';
$_SESSION['log_email'] = wp_get_current_user()->user_email;
$arr = $this->call_api('GET', '/lists/' . $mailchimp_list_id);
if($arr['status'] == 'ok'){
if( $arr['data']->id == $mailchimp_list_id ){
$web_url = 'https://' . $this->get_api_data_center() . '.admin.mailchimp.com/lists/' . $arr['data']->web_id;
return ['id' => $arr['data']->id, 'web_id' => $arr['data']->web_id, 'web_url' => $web_url, 'name' => $arr['data']->name];
}
}
return false;
}
public function check_api_member_exist($mailchimp_list_id, $email){
if( !strlen($mailchimp_list_id) || !$email ) return false;
//set sessions for log
$_SESSION['log_group_id'] = substr(md5(uniqid(mt_rand(), true)), 0, 5);
$_SESSION['log_plugin'] = 'SYSTEM';
$_SESSION['log_email'] = wp_get_current_user()->user_email;
$search = $this->call_api('GET', '/search-members', 'list_id=' . $mailchimp_list_id . '&query=' . $email);
if($search['status'] == 'ok'){
if( (int)$search['data']->exact_matches->total_items > 0 ){
return true;
}
}
return false;
}
public function get_mailchimp_list_info($list_id){
if($lists = $this->get_mailchimp_lists()){
foreach($lists as $x => $arr){
if($arr['id'] == $list_id){
return $arr;
}
}
}
return false;
}
public function get_mailchimp_list_id_pattern($sku, $slug){
if( strlen($sku) && strlen($slug) ){
return strtolower(sprintf('%s-%s', $sku, $slug));
}
return false;
}
//call_api($method, $path = '', $query = false, $body = false, $additional_headers = false){
public function create_mailchimp_list($list_name){
if( !strlen($list_name) ) return false;
$list_name = trim($list_name, '-_');
$cl = $this->get_setting('create_list');
if( !is_array($cl) ) $cl = [];
$company = $cl['company']; //'ProViaggiArchitettura';
$address1 = $cl['address1']; //'398, Via Emilia Levante';
$address2 = $cl['address2']; //'';
$city = $cl['city']; //'Castel Bolognese';
$state = $cl['state']; //'Italy';
$zip = $cl['zip']; //'48014';
$country = $cl['country']; //'US';
$phone = $cl['phone']; //'';
$permission_reminder = $cl['permission_reminder']; //'0';
$archive_bars = ($cl['archive_bars'] == 'true') ? true : false; //false;
$from_name = $cl['from_name']; //'ProViaggiArchitettura';
$from_email = $cl['from_email']; //'[email protected]';
$subject = $cl['subject']; //'ProViaggiArchitettura';
$language = $cl['language']; //'IT';
$notify_subs = $cl['notify_subs']; //'';
$notify_unsubs = $cl['notify_unsubs']; //'';
$type = ($cl['type'] == 'true') ? true : false; //false;
$visibility = $cl['visibility']; //'pub';
$double_optin = ($cl['double_optin'] == 'true') ? true : false; //false;
$marketing_permissions = ($cl['marketing_permissions'] == 'true') ? true : false; //false;
$body = array(
'name' => $list_name,
'contact' => array (
'company' => $company,
'address1' => $address1,
'address2' => $address2,
'city' => $city,
'state' => $state,
'zip' => $zip,
'country' => $country,
'phone' => $phone
),
'permission_reminder' => $permission_reminder,
'use_archive_bar' => $archive_bars,
'campaign_defaults' => array(
'from_name' => $from_name,
'from_email' => $from_email,
'subject' => $subject,
'language' => $language
),
'notify_on_subscribe' => $notify_subs,
'notify_on_unsubscribe' => $notify_unsubs,
'email_type_option' => $type,
'visibility' => $visibility,
'double_optin' => $double_optin,
'marketing_permissions' => $marketing_permissions,
);
$arr = $this->call_api('POST', '/lists/', false, $body);
if($arr['status'] == 'ok'){
return $arr['data']->id;
}
}
//___________________________________________________________________________________
// WOOCOMMERCE
//___________________________________________________________________________________
private function prepare_slug($post_id){
if(!$post_id) return false;
$obj = wc_get_product( $post_id );
$slug = $obj->get_slug();
if($slug == '') $slug = sanitize_title( $obj->get_name() );
$sku = $obj->get_sku();
return $this->get_mailchimp_list_id_pattern($sku, $slug);
}
public function add_meta_box( $post_type ) {
// Limit meta box to certain post types.
$post_types = array( 'product' );
if ( in_array( $post_type, $post_types ) ) {
add_meta_box(
'woo_mailchimp_product_metabox',
__( 'MailChimp', 'wmptls' ),
array( $this, 'display_meta_box' ),
$post_type,
'side',
'low'
);
}
}
public function display_meta_box( $post ) {
$dont_create_mailchimp_list = get_post_meta( $post->ID, 'dont_create_mailchimp_list', true );
if($dont_create_mailchimp_list == 'YES'){
echo '<p>Don\'t create a Mailchimp list for this product</p>';
return false;
}
$obj = wc_get_product( $post->ID );
$slug = $obj->get_slug();
if($slug == '') $slug = sanitize_title( $obj->get_name() );
$sku = $obj->get_sku();
$status = $obj->get_status();
$pattern = $this->get_mailchimp_list_id_pattern($sku, $slug);
if($status != 'auto-draft'){
// Add an nonce field so we can check for it later.
wp_nonce_field( 'myplugin_inner_custom_box', 'myplugin_inner_custom_box_nonce' );
// Use get_post_meta to retrieve an existing value from the database.
$existing_mailchimp_list_id = get_post_meta( $post->ID, 'mailchimp_list_id', true );
if( strlen($existing_mailchimp_list_id) ){
if($arr = $this->get_mailchimp_list_info($existing_mailchimp_list_id)){
echo sprintf('<p><strong>%s:</strong><br><a href="%s" target="_blank"><strong>%s</strong></a></p>', 'Current List', $arr['url'], $arr['title']);
}
$checked = '';
}else{
$checked = 'checked="checked"';
}
?>
<label for="mailchimp_list_select"><strong><?php _e( 'Select Existing List:', 'wmptls' ); ?></strong></label>
<?php
echo '<select name="mailchimp_list_select" id="mailchimp_list_select">';
echo sprintf('<option value="%s">%s</option>', '', '-- select --');
if($arr = $this->get_mailchimp_lists(true)){
foreach($arr as $i => $info){
$selected = ($existing_mailchimp_list_id == $info['id']) ? ' selected="selected" ' : '';
echo sprintf('<option value="%s" ' . $selected . '>%s</option>', $info['id'], $info['title']);
}
}
echo '</select>';
?>
<p></p>
<label for="mailchimp_list_new"><strong><?php _e( 'Or Create New:', 'wmptls' ); ?></strong></label>
<input type="text" id="mailchimp_list_new" name="mailchimp_list_new" value="" style="width: 100%" />
<?php
}else{
$checked = 'checked="checked"';
// Add an nonce field so we can check for it later.
wp_nonce_field( 'myplugin_inner_custom_box', 'myplugin_inner_custom_box_nonce' );
//echo '<p>This product will be assigned to auto-generated list.</p>';
echo '<p><label><input type="checkbox" name="dont_create_mailchimp_list" value="YES" ' . $checked . ' /> Don\'t create a Mailchimp list for this product</label></p>';
}
}
public function save_meta_box( $post_id ) {
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if ( ! isset( $_POST['myplugin_inner_custom_box_nonce'] ) ) {
return $post_id;
}
$nonce = $_POST['myplugin_inner_custom_box_nonce'];
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce, 'myplugin_inner_custom_box' ) ) {
return $post_id;
}
/*
* If this is an autosave, our form has not been submitted,
* so we don't want to do anything.
*/
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
// Check the user's permissions.
if ( 'product' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return $post_id;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
}
//___________________________________________________________________________________
if( isset($_POST['dont_create_mailchimp_list']) && $_POST['dont_create_mailchimp_list'] == 'YES' ){
update_post_meta( $post_id, 'dont_create_mailchimp_list', 'YES' );
delete_post_meta( $post_id, 'mailchimp_list_id' );
return $post_id;
}else{
delete_post_meta( $post_id, 'dont_create_mailchimp_list' );
}
//___________________________________________________________________________________
$_SESSION['log_group_id'] = substr(md5(uniqid(mt_rand(), true)), 0, 5);
$_SESSION['log_plugin'] = 'SYSTEM';
$_SESSION['log_email'] = wp_get_current_user()->user_email;
/* OK, it's safe for us to save the data now. */
$obj = wc_get_product( $post_id );
$slug = $obj->get_slug();
if($slug == '') $slug = sanitize_title( $obj->get_name() );
$sku = $obj->get_sku();
$pattern = $this->get_mailchimp_list_id_pattern($sku, $slug);
//first save
if( !isset($_POST['mailchimp_list_select']) && !isset($_POST['mailchimp_list_new']) ){
//create new list & update meta
$mailchimp_list_new = $pattern;
if($list_id = $this->create_mailchimp_list($mailchimp_list_new)){
update_post_meta( $post_id, 'mailchimp_list_id', $list_id );
}
//next save
}else{
// Sanitize the user input.
$mailchimp_list_select = sanitize_text_field( $_POST['mailchimp_list_select'] );
$mailchimp_list_new = sanitize_text_field( $_POST['mailchimp_list_new'] );
if( strlen($mailchimp_list_new) ){
//create new list & update meta
$mailchimp_list_new = sanitize_title($mailchimp_list_new);
if($list_id = $this->create_mailchimp_list($mailchimp_list_new)){
update_post_meta( $post_id, 'mailchimp_list_id', $list_id );
}
}elseif( strlen($mailchimp_list_select) ){
//get saved meta
$mailchimp_list_id = get_post_meta( $post_id, 'mailchimp_list_id', true );
if($mailchimp_list_select == $mailchimp_list_id){
//no action here
}else{
//update meta
update_post_meta( $post_id, 'mailchimp_list_id', $mailchimp_list_select );
}
}else{
//reset list
delete_post_meta( $post_id, 'mailchimp_list_id' );
}
}
return $post_id;
}