-
Notifications
You must be signed in to change notification settings - Fork 138
/
facebook-commerce.php
2098 lines (1795 loc) · 65.1 KB
/
facebook-commerce.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
/**
* @package FacebookCommerce
*/
if (!defined('ABSPATH')) exit; // Exit if accessed directly
include_once('facebook-config-warmer.php');
include_once('includes/fbproduct.php');
class WC_Facebookcommerce_Integration extends WC_Integration {
const FB_PRODUCT_GROUP_ID = 'fb_product_group_id';
const FB_PRODUCT_ITEM_ID = 'fb_product_item_id';
const FB_PRODUCT_DESCRIPTION = 'fb_product_description';
const FB_VISIBILITY = 'fb_visibility';
const FB_CART_URL = 'fb_cart_url';
const FB_MESSAGE_DISPLAY_TIME = 180;
const FB_VARIANT_SIZE = 'size';
const FB_VARIANT_COLOR = 'color';
const FB_VARIANT_COLOUR = 'colour';
const FB_VARIANT_PATTERN = 'pattern';
const FB_VARIANT_GENDER = 'gender';
public static $validGenderArray =
array("male" => 1, "female" => 1, "unisex" => 1);
const FB_ADMIN_MESSAGE_PREPEND = '<b>Facebook for WooCommerce</b><br/>';
const FB_SYNC_IN_PROGRESS = 'fb_sync_in_progress';
const FB_SYNC_REMAINING = 'fb_sync_remaining';
const FB_SYNC_TIMEOUT = 30;
const FB_PRIORITY_MID = 9;
public function init_settings() {
parent::init_settings();
// side-load pixel config if not present in WordPress config
if (!isset($this->settings['fb_pixel_id']) && class_exists('WC_Facebookcommerce_WarmConfig')) {
$fb_warm_pixel_id = WC_Facebookcommerce_WarmConfig::$fb_warm_pixel_id;
if (isset($fb_warm_pixel_id) && is_numeric($fb_warm_pixel_id) && (int)$fb_warm_pixel_id == $fb_warm_pixel_id) {
$this->settings['fb_pixel_id'] = (string)$fb_warm_pixel_id;
update_option($this->get_option_key(), apply_filters('woocommerce_settings_api_sanitized_fields_' . $this->id, $this->settings));
}
}
}
/**
* Init and hook in the integration.
*
* @access public
* @return void
*/
public function __construct() {
global $woocommerce;
if (!class_exists('WC_Facebookcommerce_REST_Controller')) {
include_once( 'includes/fbcustomapi.php' );
$this->customapi = new WC_Facebookcommerce_REST_Controller();
}
$this->id = 'facebookcommerce';
$this->method_title = __(
'Facebook for WooCommerce',
'facebook-for-commerce');
$this->method_description = __(
'Facebook Commerce and Dynamic Ads (Pixel) Extension',
'facebook-for-commerce');
// Load the settings.
$this->init_settings();
$this->page_id = isset($this->settings['fb_page_id'])
? $this->settings['fb_page_id']
: '';
$this->api_key = isset($this->settings['fb_api_key'])
? $this->settings['fb_api_key']
: '';
$this->pixel_id = isset($this->settings['fb_pixel_id'])
? $this->settings['fb_pixel_id']
: '';
$this->use_pii = isset($this->settings['fb_pixel_use_pii'])
&& $this->settings['fb_pixel_use_pii'] === 'yes'
? true
: false;
$this->product_catalog_id = isset($this->settings['fb_product_catalog_id'])
? $this->settings['fb_product_catalog_id']
: '';
$this->external_merchant_settings_id =
isset($this->settings['fb_external_merchant_settings_id'])
? $this->settings['fb_external_merchant_settings_id']
: '';
$this->init_form_fields();
if (!class_exists('WC_Facebookcommerce_Utils')) {
include_once 'includes/fbutils.php';
}
if (!class_exists('WC_Facebookcommerce_Graph_API')) {
include_once 'includes/fbgraph.php';
$this->fbgraph = new WC_Facebookcommerce_Graph_API($this->api_key);
}
// Hooks
if (is_admin()) {
add_action('admin_notices', array( $this, 'checks' ));
add_action('woocommerce_update_options_integration', array(
$this, 'process_admin_options'
));
add_action('admin_enqueue_scripts', array( $this, 'load_assets'));
add_action('wp_ajax_ajax_save_fb_settings',
array($this, 'ajax_save_fb_settings'), self::FB_PRIORITY_MID);
add_action('wp_ajax_ajax_delete_fb_settings',
array($this, 'ajax_delete_fb_settings'), self::FB_PRIORITY_MID);
add_action('wp_ajax_ajax_sync_all_fb_products',
array($this, 'ajax_sync_all_fb_products'), self::FB_PRIORITY_MID);
add_action('wp_ajax_ajax_reset_all_fb_products',
array($this, 'ajax_reset_all_fb_products'), self::FB_PRIORITY_MID);
// Only load product processing hooks if we have completed setup.
if ($this->api_key && $this->product_catalog_id) {
add_action(
'woocommerce_process_product_meta_simple',
array($this, 'on_simple_product_publish'),
10, // Action priority
1 // Args passed to on_product_publish (should be 'id')
);
add_action(
'woocommerce_process_product_meta_variable',
array($this, 'on_variable_product_publish'),
10, // Action priority
1 // Args passed to on_product_publish (should be 'id')
);
add_action(
'before_delete_post',
array($this, 'on_product_delete'),
10,
1);
add_action('add_meta_boxes', array($this, 'fb_product_metabox'), 10, 1);
add_filter('manage_product_posts_columns',
array($this, 'fb_product_columns'));
add_action('manage_product_posts_custom_column',
array( $this, 'fb_render_product_columns' ), 2);
// Product data tab
add_filter('woocommerce_product_data_tabs',
array($this, 'fb_new_product_tab'));
add_action('woocommerce_product_data_panels',
array($this, 'fb_new_product_tab_content' ));
add_action('wp_ajax_ajax_fb_toggle_visibility',
array($this, 'ajax_toggle_visibility'));
add_action('wp_ajax_ajax_reset_single_fb_product',
array($this, 'ajax_reset_single_fb_product'));
add_action('wp_ajax_ajax_delete_fb_product',
array($this, 'ajax_delete_fb_product'));
}
}
if (!class_exists('WC_Facebookcommerce_EventsTracker')) {
include_once 'facebook-commerce-events-tracker.php';
}
if ($this->pixel_id) {
$user_info = $this->get_user_info();
$this->events_tracker = new WC_Facebookcommerce_EventsTracker(
$this->pixel_id, $user_info);
// Pixel Tracking Hooks
add_action('wp_head',
array($this->events_tracker, 'inject_base_pixel'));
add_action('woocommerce_after_single_product',
array($this->events_tracker, 'inject_view_content_event'));
add_action('woocommerce_after_shop_loop',
array($this->events_tracker, 'inject_view_category_event'));
add_action('pre_get_posts',
array($this->events_tracker, 'inject_search_event'));
add_action('woocommerce_after_cart',
array($this->events_tracker, 'inject_add_to_cart_event'));
add_action('woocommerce_after_checkout_form',
array($this->events_tracker, 'inject_initiate_checkout_event'));
add_action('woocommerce_thankyou',
array($this->events_tracker, 'inject_purchase_event'));
}
// Attempt to load background processing (Woo 3.x.x only)
include_once('includes/fbbackground.php');
if (class_exists('WC_Facebookcommerce_Background_Process')) {
if (!isset($this->background_processor)) {
$this->background_processor =
new WC_Facebookcommerce_Background_Process($this);
}
}
add_action('wp_ajax_ajax_fb_background_check_queue',
array($this, 'ajax_fb_background_check_queue'));
}
public function ajax_fb_background_check_queue() {
$request_time = null;
if (isset($_POST['request_time'])) {
$request_time = esc_js($_POST['request_time']);
}
if ($this->settings['fb_api_key']) {
if (isset($this->background_processor)) {
$is_processing = $this->background_processor->handle_cron_healthcheck();
$remaining = $this->background_processor->get_item_count();
$response = array(
'connected' => true,
'background' => true,
'processing' => $is_processing,
'remaining' => $remaining,
'request_time' => $request_time,
);
} else {
$response = array(
'connected' => true,
'background' => false,
);
}
} else {
$response = array(
'connected' => false,
'background' => false,
);
}
printf(json_encode($response));
wp_die();
}
public function fb_new_product_tab($tabs) {
$tabs['fb_commerce_tab'] = array(
'label' => __('Facebook', 'facebook-for-woocommerce'),
'target' => 'facebook_options',
'class' => array( 'show_if_simple', 'show_if_variable' ),
);
return $tabs;
}
public function fb_new_product_tab_content() {
global $post;
$woo_product = new WC_Facebook_Product($post->ID);
$description = get_post_meta(
$post->ID,
self::FB_PRODUCT_DESCRIPTION,
true);
// 'id' attribute needs to match the 'target' parameter set above
?><div id='facebook_options' class='panel woocommerce_options_panel'><?php
?><div class='options_group'><?php
woocommerce_wp_textarea_input(
array(
'id' => self::FB_PRODUCT_DESCRIPTION,
'label' => __('Facebook Description', 'facebook-for-woocommerce'),
'desc_tip' => 'true',
'description' => __(
'Custom (plain-text only) description for product on Facebook. '.
'If blank, product description will be used. ' .
'If product description is blank, shortname will be used.',
'facebook-for-woocommerce'),
'cols' => 40,
'rows' => 20,
'value' => $description,
));
?></div>
</div><?php
}
public function fb_product_columns($existing_columns) {
if (empty($existing_columns) && ! is_array($existing_columns)) {
$existing_columns = array();
}
$columns = array();
$columns['fb'] = __('Facebook Shop', 'facebook-for-woocommerce');
// Verify that cart URL hasn't changed. We do it here because this page
// is most likely to be visited (so it's a handy place to make the check)
$cart_url = get_option(self::FB_CART_URL);
if (!empty($cart_url) && (wc_get_cart_url() !== $cart_url)) {
$this->display_warning_message('One or more of your products is using a
checkout URL that may be different than your shop checkout URL.
<a href="' . WOOCOMMERCE_FACEBOOK_PLUGIN_SETTINGS_URL . '">
Re-sync your products to update checkout URLs on Facebook.</a>');
}
return array_merge($columns, $existing_columns);
}
public function fb_render_product_columns($column) {
global $post, $the_product;
wp_enqueue_script('wc_facebook_jsx', plugins_url(
'/assets/js/facebook-products.js?ts=' . time(), __FILE__));
if (empty($the_product) || $the_product->get_id() != $post->ID) {
$the_product = new WC_Facebook_Product($post);
}
if ($column === 'fb') {
$fb_product_group_id = get_post_meta(
$post->ID,
self::FB_PRODUCT_GROUP_ID,
true);
if (!$fb_product_group_id) {
printf('<span>Not Synced</span>');
} else {
$viz_value = get_post_meta($post->ID, self::FB_VISIBILITY, true);
$data_tip = $viz_value === '' ?
'Product is synced but not marked as published (visible)
on Facebook.' :
'Product is synced and published (visible) on Facebook.';
printf('<span class="tips" id="tip_%1$s" data-tip="%2$s">',
$post->ID,
$data_tip);
if ($viz_value === '') {
printf(
'<a id="viz_%1$s" class="button button-primary button-large"
href="#" onclick="fb_toggle_visibility(%1$s, true)">Show</a>',
$post->ID);
} else {
printf(
'<a id="viz_%1$s" class="button" href="#"
onclick="fb_toggle_visibility(%1$s, false)">Hide</a>',
$post->ID);
}
}
}
}
public function fb_product_metabox() {
wp_enqueue_script('wc_facebook_jsx', plugins_url(
'/assets/js/facebook-metabox.js?ts=' . time(), __FILE__));
add_meta_box(
'facebook_metabox', // Meta box ID
'Facebook', // Meta box Title
array($this, 'fb_product_meta_box_html'), // Callback
'product', // Screen to which to add the meta box
'side' // Context
);
}
public function fb_product_meta_box_html() {
global $post;
$fb_product_group_id = get_post_meta(
$post->ID,
self::FB_PRODUCT_GROUP_ID,
true);
printf('<span id="fb_metadata">');
if ($fb_product_group_id) {
printf('Facebook ID: <a href="https://facebook.com/'.
$fb_product_group_id . '" target="_blank">' .
$fb_product_group_id . '</a><p/>');
$woo_product = new WC_Facebook_Product($post->ID);
if ($woo_product->get_type() === 'variable') {
printf('<p>Variant IDs:<br/>');
$children = $woo_product->get_children();
foreach ($children as $child_id) {
$fb_product_item_id = get_post_meta(
$child_id,
self::FB_PRODUCT_ITEM_ID,
true);
printf($child_id .' : <a href="https://facebook.com/'.
$fb_product_item_id . '" target="_blank">' .
$fb_product_item_id . '</a><br/>');
}
printf('</p>');
}
$checkbox_value = get_post_meta($post->ID, self::FB_VISIBILITY, true);
printf('Visible: <input name="%1$s" type="checkbox" value="1" %2$s/>',
self::FB_VISIBILITY,
$checkbox_value === '' ? '' : 'checked');
printf(
'<p/><a href="#" onclick="fb_reset_product(%1$s)">
Reset Facebook metadata</a>',
$post->ID);
printf(
'<p/><a href="#" onclick="fb_delete_product(%1$s)">
Delete product(s) on Facebook</a>',
$post->ID);
} else {
printf("<b>This product is not yet synced to Facebook.</b>");
}
printf('</span>');
}
private function get_product_count() {
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids'
);
$products = new WP_Query($args);
wp_reset_postdata();
echo $products->found_posts;
}
// Return store name with sanitized apostrophe
private function get_store_name() {
$name = trim(str_replace(
"'",
"\u{2019}",
html_entity_decode(
get_bloginfo('name'),
ENT_QUOTES,
'UTF-8')));
if ($name) {
return $name;
}
// Fallback to site url
$url = get_site_url();
if ($url) {
return parse_url($url, PHP_URL_HOST);
}
// If site url doesn't exist, fall back to http host.
if ($_SERVER['HTTP_HOST']) {
return $_SERVER['HTTP_HOST'];
}
// If http host doesn't exist, fall back to local host name.
$url = gethostname();
return ($url) ? $url : 'A Store Has No Name';
}
/**
* Load DIA specific JS Data
*/
public function load_assets() {
$screen = get_current_screen();
if (strpos($screen->id , "page_wc-settings") == 0) {
return;
}
if (empty($_GET['tab'])) {
return;
}
if ('integration' !== $_GET['tab']) {
return;
}
?>
<script>
window.facebookAdsToolboxConfig = {
hasGzipSupport:
'<?php echo extension_loaded('zlib') ? 'true' : 'false' ?>'
,popupOrigin: '<?php echo isset($_GET['url']) ? esc_js($_GET['url']) :
'https://www.facebook.com/' ?>'
,feedWasDisabled: 'true'
,platform: 'WooCommerce'
,pixel: {
pixelId: '<?php echo $this->pixel_id ?: '' ?>'
,advanced_matching_supported: true
}
,diaSettingId: '<?php echo $this->external_merchant_settings_id ?: '' ?>'
,store: {
baseUrl: window.location.protocol + '//' + window.location.host
,baseCurrency:
'<?php echo esc_js(
WC_Admin_Settings::get_option('woocommerce_currency'))?>'
,timezoneId: '<?php echo date('Z') ?>'
,storeName: '<?php echo esc_js($this->get_store_name()); ?>'
,version: '<?php echo WC()->version ?>'
,php_version: '<?php echo PHP_VERSION ?>'
,plugin_version:
'<?php echo WC_Facebookcommerce::PLUGIN_VERSION ?>'
}
,feed: {
totalVisibleProducts: '<?php echo $this->get_product_count() ?>'
}
,feedPrepared: {
feedUrl: ''
,feedPingUrl: ''
,samples: <?php echo $this->get_sample_product_feed()?>
}
};
</script>
<?php
wp_enqueue_script('wc_facebook_jsx', plugins_url(
'/assets/js/facebook-settings.js?ts=' . time(), __FILE__));
wp_enqueue_style('wc_facebook_css', plugins_url(
'/assets/css/facebook.css', __FILE__));
}
private function get_user_info() {
$current_user = wp_get_current_user();
if (0 === $current_user->ID || $this->use_pii === false) {
// User not logged in or admin chose not to send PII.
return array();
} else {
return array_filter(
array(
// Keys documented in
// https://developers.facebook.com/docs/facebook-pixel/pixel-with-ads/
// /conversion-tracking#advanced_match
'em' => $current_user->user_email,
'fn' => $current_user->user_firstname,
'ln' => $current_user->user_lastname
),
function ($value) { return $value !== null && $value !== ''; });
}
}
function on_product_delete($wp_id) {
$woo_product = new WC_Facebook_Product($wp_id);
$fb_product_group_id = get_post_meta(
$wp_id,
self::FB_PRODUCT_GROUP_ID,
true);
$fb_product_item_id = get_post_meta(
$wp_id,
self::FB_PRODUCT_ITEM_ID,
true);
if (! ($fb_product_group_id || $fb_product_item_id ) ) {
return; // No synced product, no-op.
}
$products = array($wp_id);
if ($woo_product->get_type() == 'variable') {
$children = $woo_product->get_children();
$products = array_merge($products, $children);
}
foreach ($products as $item_id) {
$fb_product_item_id = get_post_meta(
$item_id,
self::FB_PRODUCT_ITEM_ID,
true);
if ($fb_product_item_id) {
$pi_result = $this->fbgraph->delete_product_item($fb_product_item_id);
self::log($pi_result);
}
}
if ($fb_product_group_id) {
$pg_result = $this->fbgraph->delete_product_group($fb_product_group_id);
self::log($pg_result);
}
}
/**
* Generic function for use with any product publishing.
* Will determine product type (simple or variable) and delegate to
* appropriate handler.
*/
function on_product_publish($wp_id) {
if (get_post_status($wp_id) != 'publish') {
return;
}
$woo_product = new WC_Facebook_Product($wp_id);
$product_type = $woo_product->get_type();
if ($product_type === 'variable') {
$this->on_variable_product_publish($wp_id, $woo_product);
} else {
$this->on_simple_product_publish($wp_id, $woo_product);
}
}
function on_variable_product_publish($wp_id, $woo_product = null) {
if (get_post_status($wp_id) != 'publish') {
return;
}
// Check if product group has been published to FB. If not, it's new.
// If yes, loop through variants and see if product items are published.
if (!$woo_product) {
$woo_product = new WC_Facebook_Product($wp_id);
}
if (isset($_POST[self::FB_PRODUCT_DESCRIPTION])) {
$woo_product->set_description($_POST[self::FB_PRODUCT_DESCRIPTION]);
}
$fb_product_group_id = get_post_meta(
$wp_id,
self::FB_PRODUCT_GROUP_ID,
true);
if ($fb_product_group_id) {
// Set explicit boolean for fb_visibility (published vs staging)
$visibility = get_post_meta($wp_id, self::FB_VISIBILITY, true);
if ($visibility) {
$woo_product->fb_visibility = $visibility;
} else {
$woo_product->fb_visibility = isset($_POST[self::FB_VISIBILITY])
? true : false;
update_post_meta($wp_id, self::FB_VISIBILITY,
$woo_product->fb_visibility);
}
$this->update_product_group($woo_product);
$child_products = $woo_product->get_children();
foreach ($child_products as $item_id) {
$this->on_simple_product_publish($item_id, null);
}
} else {
$this->create_product_variable($woo_product);
}
}
function on_simple_product_publish($wp_id, $woo_product = null) {
if (get_post_status($wp_id) != 'publish') {
return;
}
if (!$woo_product) {
$woo_product = new WC_Facebook_Product($wp_id);
}
if (isset($_POST[self::FB_PRODUCT_DESCRIPTION])) {
$woo_product->set_description($_POST[self::FB_PRODUCT_DESCRIPTION]);
}
// Check if this product has already been published to FB.
// If not, it's new!
$fb_product_item_id = get_post_meta($wp_id, self::FB_PRODUCT_ITEM_ID, true);
if ($fb_product_item_id) {
$visibility = get_post_meta($wp_id, self::FB_VISIBILITY, true);
if ($visibility) {
$woo_product->fb_visibility = $visibility;
} else {
$woo_product->fb_visibility = isset($_POST[self::FB_VISIBILITY])
? true : false;
update_post_meta($wp_id, self::FB_VISIBILITY,
$woo_product->fb_visibility);
}
$this->update_product_item($woo_product, $fb_product_item_id);
} else {
// Check if this is a new product item for an existing product group
if ($woo_product->get_parent_id()) {
$fb_product_group_id = get_post_meta(
$woo_product->get_parent_id(),
self::FB_PRODUCT_GROUP_ID,
true);
// New variant added
if ($fb_product_group_id) {
$this->create_product_simple($woo_product, $fb_product_group_id);
} else {
$this->fblog(
"Wrong! simple_product_publish called without group ID for
a variable product!");
}
} else {
$this->create_product_simple($woo_product); // new product
}
}
}
function create_product_variable($woo_product) {
$retailer_id = WC_Facebookcommerce_Utils::get_fb_retailer_id($woo_product);
$fb_product_group_id = $this->create_product_group(
$woo_product,
$retailer_id,
true);
if ($fb_product_group_id) {
$child_products = $woo_product->get_children();
foreach ($child_products as $item_id) {
$woo_product = new WC_Facebook_Product($item_id);
$retailer_id =
WC_Facebookcommerce_Utils::get_fb_retailer_id($woo_product);
$this->create_product_item(
$woo_product,
$retailer_id,
$fb_product_group_id);
}
}
}
/**
* Create product group and product, store fb-specific info
**/
function create_product_simple($woo_product, $fb_product_group_id = null) {
$retailer_id = WC_Facebookcommerce_Utils::get_fb_retailer_id($woo_product);
if (!$fb_product_group_id) {
$fb_product_group_id = $this->create_product_group(
$woo_product,
$retailer_id);
}
if ($fb_product_group_id) {
$this->create_product_item(
$woo_product,
$retailer_id,
$fb_product_group_id);
}
}
function create_product_group($woo_product, $retailer_id, $variants = false) {
$product_group_data = array(
'retailer_id' => $retailer_id,
);
// Default visibility on create = published
$woo_product->fb_visibility = true;
update_post_meta($woo_product->get_id(), self::FB_VISIBILITY, true);
if ($variants) {
$product_group_data['variants'] =
$this->prepare_variants_for_group($woo_product);
}
$create_product_group_result = $this->check_api_result(
$this->fbgraph->create_product_group(
$this->product_catalog_id,
$product_group_data),
$product_group_data,
$woo_product->get_id());
// New variant added
if ($create_product_group_result) {
$fb_product_group_id = json_decode(
$create_product_group_result['body'])->id;
// update_post_meta is actually more of a create_or_update
update_post_meta(
$woo_product->get_id(),
self::FB_PRODUCT_GROUP_ID,
$fb_product_group_id);
$this->display_success_message(
'Created product group <a href="https://facebook.com/'.
$fb_product_group_id . '" target="_blank">' .
$fb_product_group_id . '</a> on Facebook.');
return $fb_product_group_id;
}
}
function create_product_item($woo_product, $retailer_id, $product_group_id) {
// Default visibility on create = published
$woo_product->fb_visibility = true;
update_post_meta($woo_product->get_id(), self::FB_VISIBILITY, true);
$product_data = $this->prepare_product($woo_product, $retailer_id);
$product_result = $this->check_api_result(
$this->fbgraph->create_product_item(
$product_group_id,
$product_data),
$product_data,
$woo_product->get_id());
if ($product_result) {
$fb_product_item_id = json_decode($product_result['body'])->id;
update_post_meta($woo_product->get_id(),
self::FB_PRODUCT_ITEM_ID, $fb_product_item_id);
$this->display_success_message(
'Created product item <a href="https://facebook.com/'.
$fb_product_item_id . '" target="_blank">' .
$fb_product_item_id . '</a> on Facebook.');
return $fb_product_item_id;
}
}
/**
* Update existing product group (variant data only)
**/
function update_product_group($woo_product) {
$fb_product_group_id = get_post_meta(
$woo_product->get_id(),
self::FB_PRODUCT_GROUP_ID,
true);
if (!$fb_product_group_id) {
return;
}
$variants = $this->prepare_variants_for_group($woo_product);
if (!$variants) {
self::log(
sprintf(__('Nothing to update for product group for %1$s',
'facebook-for-woocommerce'),
$fb_product_group_id));
return;
}
$product_group_data = array(
'variants' => $variants
);
$result = $this->check_api_result(
$this->fbgraph->update_product_group(
$fb_product_group_id,
$product_group_data));
if ($result) {
$this->display_success_message(
'Updated product group <a href="https://facebook.com/'.
$fb_product_group_id .'" target="_blank">' . $fb_product_group_id .
'</a> on Facebook.');
}
}
/**
* Update existing product
**/
function update_product_item($woo_product, $fb_product_item_id) {
$product_data = $this->prepare_product($woo_product);
$result = $this->check_api_result(
$this->fbgraph->update_product_item(
$fb_product_item_id,
$product_data));
if ($result) {
$this->display_success_message(
'Updated product <a href="https://facebook.com/'. $fb_product_item_id .
'" target="_blank">' . $fb_product_item_id . '</a> on Facebook.');
}
}
/**
* Assemble product payload for POST
**/
function prepare_product($woo_product, $retailer_id = null) {
if (!$retailer_id) {
$retailer_id =
WC_Facebookcommerce_Utils::get_fb_retailer_id($woo_product);
}
$image_url = wp_get_attachment_url($woo_product->get_image_id());
// Image URL is required, but product may have been published w/out an image
if (!$image_url) {
$name = urlencode(strip_tags($woo_product->get_title()));
$image_url = 'https://placeholdit.imgix.net/~text?txtsize=33&txt='
. $name . '&w=530&h=530'; // TODO: BETTER PLACEHOLDER
}
$image_url = WC_Facebookcommerce_Utils::make_url($image_url);
$additional_image_urls = array($image_url);
$attachment_ids = $woo_product->get_image_urls();
foreach ($attachment_ids as $attachment_id) {
$attachment_url = wp_get_attachment_url($attachment_id);
if (!empty($attachment_url)) {
array_push($additional_image_urls,
WC_Facebookcommerce_Utils::make_url($attachment_url));
}
}
// Replace Wordpress sanitization's ampersand with a real ampersand.
$product_url = str_replace(
'&%3B',
'&',
html_entity_decode($woo_product->get_permalink()));
if (wc_get_cart_url()) {
$char = '?';
// Some merchant cart pages are actually a querystring
if (strpos(wc_get_cart_url(), '?') !== false) {
$char = '&';
}
$checkout_url = WC_Facebookcommerce_Utils::make_url(
wc_get_cart_url() . $char);
if ($woo_product->get_type() === 'variation') {
$query_data = array(
'add-to-cart' => $woo_product->get_parent_id(),
'variation_id' => $woo_product->get_id()
);
$query_data = array_merge(
$query_data,
$woo_product->get_variation_attributes());
} else {
$query_data = array(
'add-to-cart' => $woo_product->get_id()
);
}
$checkout_url = $checkout_url . http_build_query($query_data);
} else {
$checkout_url = null;
}
// Use new Woo 3.x function if exists
if (function_exists('wc_get_price_to_display')) {
$display_price = floatval(wc_get_price_to_display($woo_product));
} else {
$display_price = floatval($woo_product->get_display_price());
}
$id = $woo_product->get_id();
if ($woo_product->get_type() === 'variation') {
$id = $woo_product->get_parent_id();
}
$categories =
WC_Facebookcommerce_Utils::get_product_categories($id);
// Use display price to include tax (if it's included)
$price = intval($display_price * 100);
$sale_price = $woo_product->get_sale_price();
$sale_price = is_numeric($sale_price) ?
intval($woo_product->get_sale_price() * 100) :
0;
$product_data = array(
'name' => $woo_product->get_title(),
'description' => $woo_product->get_fb_description(),
'image_url' => $image_url,
'additional_image_urls' => $additional_image_urls,
'url'=> $product_url,
'category' => $categories['categories'],
'brand' => $this->get_store_name(),
'retailer_id' => $retailer_id,
'price' => $price,
'currency' => get_woocommerce_currency(),
'availability' => $woo_product->is_in_stock() ? 'in stock' :
'out of stock',
'visibility' => $woo_product->fb_visibility ? 'published' : 'staging'
);
// Only use checkout URLs if they exist.
if ($checkout_url) {
$product_data['checkout_url'] = $checkout_url;
}
if ($sale_price > 0) {
$product_data['sale_price'] = $sale_price;
}
// Loop through variants (size, color, etc) if they exist
// For each product field type, pull the single variant
$variants = $this->prepare_variants_for_item($woo_product);
if ($variants) {
foreach ($variants as $variant) {
// Replace "custom_data:foo" with just "foo" so we can use the key
// Product item API expects "custom_data" instead of "custom_data:foo"
$product_field = str_replace(
'custom_data:',
'',
$variant['product_field']);
if ($product_field === self::FB_VARIANT_GENDER) {
// If we can't validate the gender, this will be null.
$product_data[$product_field] =
$this->validateGender($variant['options'][0]);
}
switch ($product_field) {
case self::FB_VARIANT_SIZE:
case self::FB_VARIANT_COLOR:
case self::FB_VARIANT_PATTERN:
$product_data[$product_field] = $variant['options'][0];
break;
case self::FB_VARIANT_GENDER:
// If we can't validate the GENDER field, we'll fall through to the
// default case and set the gender into custom data.
if ($product_data[$product_field]) {
break;