-
Notifications
You must be signed in to change notification settings - Fork 9
/
class-pinterest-for-woocommerce.php
1417 lines (1231 loc) · 42.8 KB
/
class-pinterest-for-woocommerce.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
/**
* Installation related functions and actions.
*
* @package Pinterest_For_Woocommerce
* @version 1.0.0
*/
use Automattic\WooCommerce\Grow\Tools\CompatChecker\v0_0_1\Checker;
use Automattic\WooCommerce\Admin\Features\OnboardingTasks\TaskLists;
use Automattic\WooCommerce\Admin\Notes\NotesUnavailableException;
use Automattic\WooCommerce\Pinterest;
use Automattic\WooCommerce\Pinterest\AdCredits;
use Automattic\WooCommerce\Pinterest\AdCreditsCoupons;
use Automattic\WooCommerce\Pinterest\AdsCreditCurrency;
use Automattic\WooCommerce\Pinterest\Admin\Tasks\Onboarding;
use Automattic\WooCommerce\Pinterest\API\UserInteraction;
use Automattic\WooCommerce\Pinterest\Billing;
use Automattic\WooCommerce\Pinterest\FeedRegistration;
use Automattic\WooCommerce\Pinterest\Heartbeat;
use Automattic\WooCommerce\Pinterest\Logger;
use Automattic\WooCommerce\Pinterest\Notes\MarketingNotifications;
use Automattic\WooCommerce\Pinterest\Notes\TokenExchangeFailure;
use Automattic\WooCommerce\Pinterest\Notes\TokenInvalidFailure;
use Automattic\WooCommerce\Pinterest\PinterestApiException;
use Automattic\WooCommerce\Pinterest\ProductFeedStatus;
use Automattic\WooCommerce\Pinterest\Tracking;
use Automattic\WooCommerce\Pinterest\Tracking\Conversions;
use Automattic\WooCommerce\Pinterest\Tracking\Data\User;
use Automattic\WooCommerce\Pinterest\Tracking\Tag;
use Automattic\WooCommerce\Pinterest\Utilities\Tracks;
if ( ! class_exists( 'Pinterest_For_Woocommerce' ) ) :
/**
* Base Plugin class holding generic functionality
*/
final class Pinterest_For_Woocommerce {
use Tracks;
/**
* Tos IDs and URLs per country.
*/
const TOS_PER_COUNTRY = array(
'US' => array(
'tos_id' => 8,
'terms_url' => 'https://business.pinterest.com/en/pinterest-advertising-services-agreement',
),
'CA' => array(
'tos_id' => 8,
'terms_url' => 'https://business.pinterest.com/en/pinterest-advertising-services-agreement',
),
'FR' => array(
'tos_id' => 11,
'terms_url' => 'https://business.pinterest.com/fr/pinterest-advertising-services-agreement',
),
'BR' => array(
'tos_id' => 15,
'terms_url' => 'https://business.pinterest.com/pt-br/pinterest-advertising-services-agreement/',
),
'MX' => array(
'tos_id' => 16,
'terms_url' => 'https://business.pinterest.com/es/pinterest-advertising-services-agreement/mexico/',
),
'*' => array(
'tos_id' => 9,
'terms_url' => 'https://business.pinterest.com/en-gb/pinterest-advertising-services-agreement/',
),
);
/**
* Set the minimum required versions for the plugin.
*/
const PLUGIN_REQUIREMENTS = array(
'php_version' => '7.4',
'wp_version' => '5.6',
'wc_version' => '5.3',
'action_scheduler' => '3.3.0',
);
/**
* Pinterest_For_Woocommerce version.
*
* @var string
*/
public $version = PINTEREST_FOR_WOOCOMMERCE_VERSION;
/**
* The single instance of the class.
*
* @var Pinterest_For_Woocommerce
* @since 1.0.0
*/
protected static $instance = null;
/**
* The initialized state of the class.
*
* @var Pinterest_For_Woocommerce
* @since 1.0.0
*/
protected static $initialized = false;
/**
* Heartbeat instance.
*
* @var Heartbeat
* @since 1.1.0
*/
protected $heartbeat = null;
/**
* When set to true, the settings have been
* changed and the runtime cached must be flushed
*
* @var Pinterest_For_Woocommerce
* @since 1.0.0
*/
protected static $dirty_settings = array();
/**
* The default settings that will be created
* with the given values, if they don't exist.
*
* @var array
* @since 1.0.0
*/
protected static $default_settings = array(
'track_conversions' => true,
'track_conversions_capi' => false,
'enhanced_match_support' => true,
'automatic_enhanced_match_support' => true,
'save_to_pinterest' => true,
'rich_pins_on_posts' => true,
'rich_pins_on_products' => true,
'product_sync_enabled' => true,
'enable_debug_logging' => false,
'erase_plugin_data' => false,
);
/**
* Main Pinterest_For_Woocommerce Instance.
*
* Ensures only one instance of Pinterest_For_Woocommerce is loaded or can be loaded.
*
* @since 1.0.0
* @static
* @see Pinterest_For_Woocommerce()
* @return Pinterest_For_Woocommerce - Main instance.
*/
public static function instance() {
if ( is_null( self::$instance ) ) {
self::$instance = new self();
self::$instance->maybe_init_plugin();
}
return self::$instance;
}
/**
* Cloning is forbidden.
*
* @since 1.0.0
*/
public function __clone() {
_doing_it_wrong( __FUNCTION__, esc_html__( 'Cloning this class is forbidden.', 'pinterest-for-woocommerce' ), '1.0.0' );
}
/**
* Deserializing instances of this class is forbidden.
*
* @since 1.0.0
*/
public function __wakeup() {
_doing_it_wrong( __FUNCTION__, esc_html__( 'Deserializing instances of this class is forbidden.', 'pinterest-for-woocommerce' ), '1.0.0' );
}
/**
* Pinterest_For_Woocommerce Initializer.
*/
public function maybe_init_plugin() {
if ( self::$initialized ) {
_doing_it_wrong( __FUNCTION__, esc_html__( 'Only a single instance of this class is allowed. Use singleton.', 'pinterest-for-woocommerce' ), '1.0.0' );
return;
}
self::$initialized = true;
$this->define_constants();
add_action( 'plugins_loaded', array( $this, 'init_plugin' ) );
/**
* Plugin loaded action.
* phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
*/
do_action( 'pinterest_for_woocommerce_loaded' );
}
/**
* Define Pinterest_For_Woocommerce Constants.
*/
private function define_constants() {
define( 'PINTEREST_FOR_WOOCOMMERCE_PREFIX', 'pinterest-for-woocommerce' );
define( 'PINTEREST_FOR_WOOCOMMERCE_PLUGIN_BASENAME', plugin_basename( PINTEREST_FOR_WOOCOMMERCE_PLUGIN_FILE ) );
define( 'PINTEREST_FOR_WOOCOMMERCE_OPTION_NAME', 'pinterest_for_woocommerce' );
define( 'PINTEREST_FOR_WOOCOMMERCE_DATA_NAME', 'pinterest_for_woocommerce_data' );
define( 'PINTEREST_FOR_WOOCOMMERCE_LOG_PREFIX', 'pinterest-for-woocommerce' );
define( 'PINTEREST_FOR_WOOCOMMERCE_WOO_CONNECT_URL', 'https://api.woocommerce.com/' );
define( 'PINTEREST_FOR_WOOCOMMERCE_WOO_CONNECT_SERVICE', 'pinterest-v5' );
define( 'PINTEREST_FOR_WOOCOMMERCE_API_NAMESPACE', 'pinterest' );
define( 'PINTEREST_FOR_WOOCOMMERCE_CONNECT_NONCE', 'wp_rest' );
define( 'PINTEREST_FOR_WOOCOMMERCE_API_VERSION', '1' );
define( 'PINTEREST_FOR_WOOCOMMERCE_API_AUTH_ENDPOINT', 'oauth/callback' );
define( 'PINTEREST_FOR_WOOCOMMERCE_TRACKER_PREFIX', 'pfw' );
define( 'PINTEREST_FOR_WOOCOMMERCE_PINTEREST_API_VERSION', PINTEREST_FOR_WOOCOMMERCE_OPTION_NAME . '_pinterest_api_version' );
}
/**
* What type of request is this?
*
* @param string $type admin, ajax, cron or frontend.
* @return bool
*/
private function is_request( $type ) {
switch ( $type ) {
case 'admin':
return is_admin();
case 'ajax':
return defined( 'DOING_AJAX' );
case 'cron':
return defined( 'DOING_CRON' );
case 'frontend':
return ( ! is_admin() || defined( 'DOING_AJAX' ) ) && ! defined( 'DOING_CRON' );
default:
return false;
}
}
/**
* Include required core files used in admin and on the frontend.
*/
private function includes() {
include_once 'includes/class-pinterest-for-woocommerce-ads-supported-countries.php';
if ( $this->is_request( 'admin' ) ) {
include_once 'includes/admin/class-pinterest-for-woocommerce-admin.php';
}
if ( $this->is_request( 'frontend' ) ) {
include_once 'includes/class-pinterest-for-woocommerce-frontend-assets.php';
}
}
/**
* Include plugins files and hook into actions and filters.
*
* @since 1.0.0
*/
public function init_plugin() {
if ( ! Checker::instance()->is_compatible( PINTEREST_FOR_WOOCOMMERCE_PLUGIN_FILE, PINTEREST_FOR_WOOCOMMERCE_VERSION ) || ! $this->check_plugin_requirements() ) {
return;
}
$this->includes();
add_action( 'admin_init', array( $this, 'admin_init' ), 0 );
add_action( 'rest_api_init', array( $this, 'init_api_endpoints' ) );
add_action( 'wp_head', array( $this, 'maybe_inject_verification_code' ) );
add_action( 'wp_head', array( Pinterest\RichPins::class, 'maybe_inject_rich_pins_opengraph_tags' ) );
add_action( 'wp', array( Pinterest\SaveToPinterest::class, 'maybe_init' ) );
add_action( 'init', array( $this, 'init' ), 0 );
// ActionScheduler is activated on init 1 so lets make sure we are updating after that.
add_action( 'init', array( $this, 'maybe_update_plugin' ), 5 );
add_action( 'init', array( self::class, 'init_tracking' ) );
add_action( 'init', array( Pinterest\Heartbeat::class, 'schedule_events' ) );
add_action( 'init', array( Pinterest\ProductSync::class, 'maybe_init' ) );
add_action( 'init', array( Pinterest\TrackerSnapshot::class, 'maybe_init' ) );
add_action( 'init', array( Pinterest\Billing::class, 'schedule_event' ) );
add_action( 'init', array( Pinterest\AdCredits::class, 'schedule_event' ) );
add_action( 'init', array( Pinterest\RefreshToken::class, 'schedule_event' ) );
add_action( 'init', array( Pinterest\CommerceIntegration::class, 'init' ) );
// Register the marketing channel if the feature is included.
if ( defined( 'WC_MCM_EXISTS' ) ) {
add_action(
'init',
array( Pinterest\MultichannelMarketing\MarketingChannelRegistrar::class, 'register' )
);
}
// Verify that the ads_campaign is active or not.
add_action( 'admin_init', array( Pinterest\AdCredits::class, 'check_if_ads_campaign_is_active' ) );
// Append credits info to account data.
add_action( 'init', array( $this, 'add_currency_credits_info_to_account_data' ) );
add_action( 'pinterest_for_woocommerce_token_saved', array( self::class, 'set_default_settings' ) );
add_action( 'pinterest_for_woocommerce_token_saved', array( self::class, 'create_commerce_integration' ) );
add_action( 'pinterest_for_woocommerce_token_saved', array( self::class, 'update_account_data' ) );
add_action( 'pinterest_for_woocommerce_token_saved', array( self::class, 'update_linked_businesses' ) );
add_action( 'pinterest_for_woocommerce_token_saved', array( self::class, 'post_update_cleanup' ) );
add_action( 'pinterest_for_woocommerce_token_saved', array( TokenInvalidFailure::class, 'possibly_delete_note' ) );
add_action( 'pinterest_for_woocommerce_disconnect', array( self::class, 'reset_connection' ) );
add_action( 'action_scheduler_failed_execution', array( self::class, 'action_scheduler_reset_connection' ), 10, 2 );
// Handle the Pinterest verification URL.
add_action( 'parse_request', array( $this, 'verification_request' ) );
// Init marketing notifications.
add_action( Heartbeat::DAILY, array( $this, 'init_marketing_notifications' ) );
// Hook the setup task. The hook admin_init is not triggered when the WC fetches the tasks using the endpoint: wp-json/wc-admin/onboarding/tasks and hence hooking into init.
add_action( 'init', array( $this, 'add_onboarding_task' ), 20 );
}
/**
* Initialize Tracker and add trackers to it.
*
* @since 1.4.0
*
* @return Pinterest\Tracking|false
*/
public static function init_tracking() {
/**
* Filters whether to disable tracking.
*
* @since 1.4.0
*
* @param bool $disable_tracking Whether to disable tracking.
*/
$is_tracking_disabled = apply_filters( 'woocommerce_pinterest_disable_tracking', false );
$is_tracking_conversions_disabled = ! Pinterest_For_Woocommerce()::get_setting( 'track_conversions' );
$is_not_a_site = wp_doing_cron() || is_admin();
if ( $is_tracking_disabled || $is_tracking_conversions_disabled || $is_not_a_site ) {
return false;
}
$is_tracking_conversions_capi_enabled = Pinterest_For_Woocommerce()::get_setting( 'track_conversions_capi' );
$tracking = new Tracking( array( new Tag() ) );
if ( $is_tracking_conversions_capi_enabled ) {
$user = new User( WC_Geolocation::get_ip_address(), wc_get_user_agent() );
$conversions_tracker = new Conversions( $user );
$tracking->add_tracker( $conversions_tracker );
}
return $tracking;
}
/**
* Init Pinterest_For_Woocommerce when WordPress initializes.
*/
public function init() {
/**
* Before init action.
* phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
*/
do_action( 'before_pinterest_for_woocommerce_init' );
// Set up localization.
$this->load_plugin_textdomain();
/**
* Init action.
* phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
*/
do_action( 'pinterest_for_woocommerce_init' );
}
/**
* Init classes for admin interface.
*/
public function admin_init() {
$view_factory = new Pinterest\View\PHPViewFactory();
$admin = new Pinterest\Admin\Admin( $view_factory );
$attributes_tab = new Pinterest\Admin\Product\Attributes\AttributesTab( $admin );
$activation_redirect = new Pinterest\Admin\ActivationRedirect();
$variation_attributes = new Pinterest\Admin\Product\Attributes\VariationsAttributes( $admin );
$admin->register();
$attributes_tab->register();
$activation_redirect->register();
$variation_attributes->register();
}
/**
* Init marketing notifications.
*
* @since 1.1.0
*/
public function init_marketing_notifications() {
$notifications = new MarketingNotifications();
$notifications->init_notifications();
}
/**
* Checks all plugin requirements. If run in admin context also adds a notice.
*
* @return boolean
*/
public function check_plugin_requirements() {
$errors = array();
global $wp_version;
if ( ! version_compare( PHP_VERSION, self::PLUGIN_REQUIREMENTS['php_version'], '>=' ) ) {
/* Translators: The minimum PHP version */
$errors[] = sprintf( esc_html__( 'Pinterest for WooCommerce requires a minimum PHP version of %s.', 'pinterest-for-woocommerce' ), self::PLUGIN_REQUIREMENTS['php_version'] );
}
if ( ! version_compare( $wp_version, self::PLUGIN_REQUIREMENTS['wp_version'], '>=' ) ) {
/* Translators: The minimum WP version */
$errors[] = sprintf( esc_html__( 'Pinterest for WooCommerce requires a minimum WordPress version of %s.', 'pinterest-for-woocommerce' ), self::PLUGIN_REQUIREMENTS['wp_version'] );
}
if ( ! defined( 'WC_VERSION' ) || ! version_compare( WC_VERSION, self::PLUGIN_REQUIREMENTS['wc_version'], '>=' ) ) {
/* Translators: The minimum WC version */
$errors[] = sprintf( esc_html__( 'Pinterest for WooCommerce requires a minimum WooCommerce version of %s.', 'pinterest-for-woocommerce' ), self::PLUGIN_REQUIREMENTS['wc_version'] );
}
/**
* Check if WooCommerce Admin is enabled.
* phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
*/
if ( apply_filters( 'woocommerce_admin_disabled', false ) ) {
$errors[] = esc_html__( 'Pinterest for WooCommerce requires WooCommerce Admin to be enabled.', 'pinterest-for-woocommerce' );
}
if ( ! function_exists( 'as_has_scheduled_action' ) ) {
/* Translators: The minimum Action Scheduler version */
$errors[] = sprintf( esc_html__( 'Pinterest for WooCommerce requires a minimum Action Scheduler package of %s. It can be caused by old version of the WooCommerce extensions.', 'pinterest-for-woocommerce' ), self::PLUGIN_REQUIREMENTS['action_scheduler'] );
}
if ( empty( $errors ) ) {
return true;
}
if ( $this->is_request( 'admin' ) ) {
add_action(
'admin_notices',
function () use ( $errors ) {
?>
<div class="notice notice-error">
<?php
foreach ( $errors as $error ) {
echo '<p>' . esc_html( $error ) . '</p>';
}
?>
</div>
<?php
}
);
}
return false;
}
/**
* Plugin update entry point.
*
* @since 1.0.9
* @return void
*/
public function maybe_update_plugin() {
$plugin_update = new Pinterest\PluginUpdate();
$plugin_update->maybe_update();
}
/**
* Load localization files.
*
* Note: the first-loaded translation file overrides any following ones if the same translation is present.
*
* Locales found in:
* - WP_LANG_DIR/pinterest-for-woocommerce/pinterest-for-woocommerce-LOCALE.mo
* - WP_LANG_DIR/plugins/pinterest-for-woocommerce-LOCALE.mo
*/
private function load_plugin_textdomain() {
/**
* Get plugin locale.
* phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
*/
$locale = apply_filters( 'plugin_locale', get_locale(), 'pinterest-for-woocommerce' );
load_textdomain( 'pinterest-for-woocommerce', WP_LANG_DIR . '/pinterest-for-woocommerce/pinterest-for-woocommerce-' . $locale . '.mo' );
load_plugin_textdomain( 'pinterest-for-woocommerce', false, plugin_basename( __DIR__ ) . '/i18n/languages' );
}
/**
* Get the plugin url.
*
* @return string
*/
public function plugin_url() {
return untrailingslashit( plugins_url( '/', __FILE__ ) );
}
/**
* Get the plugin path.
*
* @return string
*/
public function plugin_path() {
return untrailingslashit( plugin_dir_path( __FILE__ ) );
}
/**
* Get the template path.
*
* @return string
*/
public function template_path() {
/**
* Returns template path.
* phpcs:disable WooCommerce.Commenting.CommentHooks.MissingSinceComment
*/
return apply_filters( 'pinterest_for_woocommerce_template_path', 'pinterest-for-woocommerce/' );
}
/**
* Get Ajax URL.
*
* @return string
*/
public function ajax_url() {
return admin_url( 'admin-ajax.php', 'relative' );
}
/**
* Return APP Settings
*
* @since 1.0.0
*
* @param boolean $force Controls whether to force getting a fresh value instead of one from the runtime cache.
* @param string $option Controls which option to read/write to.
*
* @return array
*/
public static function get_settings( $force = false, $option = PINTEREST_FOR_WOOCOMMERCE_OPTION_NAME ) {
static $settings;
if ( $force || is_null( $settings ) || ! isset( $settings[ $option ] ) || ( isset( self::$dirty_settings[ $option ] ) && self::$dirty_settings[ $option ] ) ) {
$settings[ $option ] = get_option( $option );
}
return $settings[ $option ];
}
/**
* Return APP Setting based on its key
*
* @since 1.0.0
*
* @param string $key The key of specific option to retrieve.
* @param boolean $force Controls whether to force getting a fresh value instead of one from the runtime cache.
*
* @return mixed
*/
public static function get_setting( $key, $force = false ) {
$settings = self::get_settings( $force );
return empty( $settings[ $key ] ) ? false : $settings[ $key ];
}
/**
* Save APP Setting
*
* @since 1.0.0
*
* @param string $key The key of specific option to retrieve.
* @param mixed $data The data to save for this option key.
*
* @return boolean
*/
public static function save_setting( $key, $data ) {
$settings = self::get_settings( true );
// Handle possible false value.
if ( ! is_array( $settings ) ) {
$settings = array();
}
$settings[ $key ] = $data;
return self::save_settings( $settings );
}
/**
* Save APP Settings
*
* @since 1.0.0
*
* @param array $settings The array of settings to save.
* @param string $option Controls which option to read/write to.
*
* @return boolean
*/
public static function save_settings( $settings, $option = PINTEREST_FOR_WOOCOMMERCE_OPTION_NAME ) {
self::$dirty_settings[ $option ] = true;
return update_option( $option, $settings );
}
/**
* Set API version used by the plugin.
*
* @since 1.4.0
*
* @param string $version The API version.
*
* @return boolean
*/
public static function set_api_version( $version ) {
return update_option( PINTEREST_FOR_WOOCOMMERCE_PINTEREST_API_VERSION, $version );
}
/**
* Get API version used by the plugin.
*
* @since 1.4.0
*
* @return string The API version.
*/
public static function get_api_version() {
return get_option( PINTEREST_FOR_WOOCOMMERCE_PINTEREST_API_VERSION, '' );
}
/**
* Return APP Data based on its key
*
* @since 1.0.0
*
* @param string $key The key of specific data to retrieve.
* @param boolean $force Controls whether to force getting a fresh value instead of one from the runtime cache.
*
* @return mixed
*/
public static function get_data( $key, $force = false ) {
$settings = self::get_settings( $force, PINTEREST_FOR_WOOCOMMERCE_DATA_NAME );
return $settings[ $key ] ?? null;
}
/**
* Save APP Data
*
* @since 1.0.0
*
* @param string $key The key of specific data to retrieve.
* @param mixed $data The data to save for this option key.
*
* @return boolean
*/
public static function save_data( $key, $data ) {
$settings = self::get_settings( true, PINTEREST_FOR_WOOCOMMERCE_DATA_NAME );
// Handle possible false value.
if ( ! is_array( $settings ) ) {
$settings = array();
}
$settings[ $key ] = $data;
return self::save_settings( $settings, PINTEREST_FOR_WOOCOMMERCE_DATA_NAME );
}
/**
* Remove APP Data key.
*
* @param string $key - The key of specific data to retrieve.
*
* @since 1.3.1
*
* @return bool - True if the data was removed, false otherwise.
*/
public static function remove_data( string $key ) {
$settings = self::get_settings( true, PINTEREST_FOR_WOOCOMMERCE_DATA_NAME );
unset( $settings[ $key ] );
return self::save_settings( $settings, PINTEREST_FOR_WOOCOMMERCE_DATA_NAME );
}
/**
* Add API endpoints
*
* @since 1.0.0
*/
public function init_api_endpoints() {
new Pinterest\API\Advertisers();
new Pinterest\API\AdvertiserConnect();
new Pinterest\API\Auth();
new Pinterest\API\AuthDisconnect();
new Pinterest\API\Businesses();
new Pinterest\API\DomainVerification();
new Pinterest\API\FeedState();
new Pinterest\API\FeedIssues();
new Pinterest\API\Tags();
new Pinterest\API\Health();
new Pinterest\API\Settings();
new Pinterest\API\SyncSettings();
new Pinterest\API\UserInteraction();
}
/**
* Get decrypted token data.
*
* The Access token and Crypto key live in the data option in the following form:
* data: {
* ...
* token: {
* access_token: ${encrypted_token},
* },
* crypto_encoded_key: ${encryption_key},
* ...
* }
*
* @since 1.0.0
*
* @return array {
* Access Token.
*
* @type string $access_token Decrypted Access Token
* }
*/
public static function get_access_token() {
$token_data = self::get_data( 'token_data', true );
$token = array();
try {
$token['access_token'] = empty( $token_data['access_token'] ) ? '' : Pinterest\Crypto::decrypt( $token_data['access_token'] );
} catch ( \Exception $th ) {
/* Translators: The error description */
Logger::log( sprintf( esc_html__( 'Could not decrypt the Pinterest API access token. Try reconnecting to Pinterest. [%s]', 'pinterest-for-woocommerce' ), $th->getMessage() ), 'error' );
}
return $token;
}
/**
* Save encrypted token data. See the documentation of the get_token() method for the expected format of the related data variables.
*
* @since 1.0.0
* @since 1.4.0 Added refresh token and tokens expiration.
*
* @param array $token The array containing the token values to save.
*
* @return boolean
*/
public static function save_token_data( $token ) {
$token['access_token'] = empty( $token['access_token'] ) ? '' : Pinterest\Crypto::encrypt( $token['access_token'] );
$token['expires_in'] = $token['expires_in'] ?? '';
$token['refresh_token'] = empty( $token['refresh_token'] ) ? '' : Pinterest\Crypto::encrypt( $token['refresh_token'] );
$token['refresh_token_expires_in'] = $token['refresh_token_expires_in'] ?? '';
$token['scopes'] = empty( $token['scopes'] ) ? '' : $token['scopes'];
$token['refresh_time'] = time();
return self::save_data( 'token_data', $token );
}
/**
* Save connection info data.
*
* @since 1.4.0
*
* @param array $connection_info_data The array containing the connection info data.
* @return bool True if the data was saved successfully.
*/
public static function save_connection_info_data( array $connection_info_data ): bool {
return self::save_data( 'connection_info_data', $connection_info_data );
}
/**
* Saves the integration data.
*
* @param array $integration_data The array containing the integration data.
* @return bool True if the data was saved successfully.
*/
public static function save_integration_data( array $integration_data ): bool {
return self::save_data( 'integration_data', $integration_data );
}
/**
* Disconnect by clearing the Token and any other data that we should gather from scratch.
*
* @since 1.0.0
*
* @return bool True if disconnection was successful.
*/
public static function disconnect(): bool {
// Reset Feed file generation telemetry.
ProductFeedStatus::deregister();
Pinterest\CommerceIntegration::maybe_unregister_retries();
/*
* If there is no business connected, disconnecting merchant will throw error.
* Just need to clean account data in these cases.
*/
if ( ! self::is_business_connected() ) {
self::flush_options();
// At this point we're disconnected.
return true;
}
try {
// Delete all the feeds for the merchant.
FeedRegistration::maybe_delete_stale_feeds_for_merchant( '' );
// Delete Commerce Integration.
self::delete_commerce_integration();
// Remove stored data.
self::flush_options();
// At this point we're disconnected.
return true;
} catch ( Exception $th ) {
// There was an error disconnecting merchant.
return false;
}
}
/**
* Resets the connection by clearing the local connection data.
*
* @since 1.4.4
*
* @return void
* @throws \Automattic\WooCommerce\Admin\Notes\NotesUnavailableException If the notes API is not available.
*/
public static function reset_connection() {
self::disconnect();
TokenInvalidFailure::possibly_add_note();
}
/**
* Resets the connection from action scheduler.
*
* @since 1.4.4
*
* @param string $action_id The ID of the action.
* @param Exception $e The exception that was thrown.
*
* @return void
* @throws NotesUnavailableException If the notes API is not available.
* @throws Exception If the exception is a 401 error.
*/
public static function action_scheduler_reset_connection( $action_id, $e ) {
if ( in_array( $e->getCode(), array( 401, 403 ) ) ) {
self::reset_connection();
throw $e;
}
}
/**
* Flush data option and remove settings.
*
* @return void
*/
private static function flush_options() {
// Flush the whole data option.
delete_option( PINTEREST_FOR_WOOCOMMERCE_DATA_NAME );
UserInteraction::flush_options();
// Remove settings that may cause issues if stale on disconnect.
self::save_setting( 'account_data', null );
self::save_setting( 'tracking_advertiser', null );
self::save_setting( 'tracking_tag', null );
// Cancel scheduled jobs.
Pinterest\ProductSync::cancel_jobs();
Heartbeat::cancel_jobs();
}
/**
* Return WooConnect Bridge URL
*
* @since 1.0.0
*
* @return string
*/
public static function get_connection_proxy_url() {
return (string) trailingslashit(
/**
* Filters the proxy URL.
*
* @since 1.0.0
*
* @param string $proxy_url the connection proxy URL
*/
apply_filters(
'pinterest_for_woocommerce_connection_proxy_url',
PINTEREST_FOR_WOOCOMMERCE_WOO_CONNECT_URL
)
);
}
/**
* Return The Middleware URL based on the given context
*
* @since 1.0.0
*
* @param string $context The context parameter.
* @param string $args Additional arguments like 'view' or 'business_id'.
*
* @return string
*/
public static function get_middleware_url( $context = 'login', $args = array() ) {
$nonce = wp_create_nonce( PINTEREST_FOR_WOOCOMMERCE_CONNECT_NONCE );
set_transient( PINTEREST_FOR_WOOCOMMERCE_CONNECT_NONCE, $nonce, 10 * MINUTE_IN_SECONDS );
$rest_url = get_rest_url( null, PINTEREST_FOR_WOOCOMMERCE_API_NAMESPACE . '/v' . PINTEREST_FOR_WOOCOMMERCE_API_VERSION . '/' . PINTEREST_FOR_WOOCOMMERCE_API_AUTH_ENDPOINT );
$state_params = array(
'redirect' => $rest_url,
'nonce' => $nonce,
);
switch ( $context ) {
case 'create_business':
$state_params['create-business'] = true;
break;
case 'switch_business':
$state_params['switch-to-business'] = $args['business_id'];
break;
}
$state = http_build_query( $state_params );
// phpcs:ignore Squiz.Commenting.InlineComment.InvalidEndChar
// nosemgrep: audit.php.wp.security.xss.query-arg
return self::get_connection_proxy_url() . 'integrations/connect/' . PINTEREST_FOR_WOOCOMMERCE_WOO_CONNECT_SERVICE . '?' . $state;
}
/**
* Injects needed meta tags to the site's header
*
* @since 1.0.0
*/
public function maybe_inject_verification_code() {
$verification_data = self::get_data( 'verification_data' );
if ( $verification_data ) {
printf( '<meta name="p:domain_verify" content="%s"/>', esc_attr( $verification_data['verification_code'] ) );
}
}
/**
* Connects WC to Pinterest.
*
* @return array the result of APIV5::create_commerce_integration.
* @throws Exception In case of 404, 409 and 500 errors from Pinterest.
* @see Pinterest\API\APIV5::create_commerce_integration
* @since 1.4.0
*/
public static function create_commerce_integration(): array {
$connection_data = self::get_data( 'connection_info_data', true );
// It does not make any sense to create integration without Advertiser ID.
if ( empty( $connection_data['advertiser_id'] ) ) {
throw new Exception(
sprintf(
esc_html__(
'Commerce Integration cannot be created: Advertiser ID is missing.',
'pinterest-for-woocommerce'
)
)
);
}
return Pinterest\CommerceIntegration::handle_create();
}
/**
* Updates WC integration parameters with Pinterest.
*
* @since 1.4.0
*
* @param string $external_business_id External business ID for the integration.
* @param array $data Integration data to update with Pinterest.
*
* @see Pinterest\API\APIV5::update_commerce_integration