forked from pronamic/woocommerce-subscriptions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwoocommerce-subscriptions.php
executable file
·1375 lines (1138 loc) · 55.8 KB
/
woocommerce-subscriptions.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 Subscriptions
* Plugin URI: https://www.woocommerce.com/products/woocommerce-subscriptions/
* Description: Sell products and services with recurring payments in your WooCommerce Store.
* Author: WooCommerce
* Author URI: https://woocommerce.com/
* Version: 3.0.1
*
* WC requires at least: 3.0.9
* WC tested up to: 3.9
* Woo: 27147:6115e6d7e297b623a169fdcf5728b224
*
* Copyright 2019 WooCommerce
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package WooCommerce Subscriptions
* @author WooCommerce.
* @since 1.0
*/
/**
* Required functions
*/
if ( ! function_exists( 'woothemes_queue_update' ) || ! function_exists( 'is_woocommerce_active' ) ) {
require_once( dirname( __FILE__ ) . '/woo-includes/woo-functions.php' );
}
/**
* Plugin updates
*/
woothemes_queue_update( plugin_basename( __FILE__ ), '6115e6d7e297b623a169fdcf5728b224', '27147' );
/**
* Check if WooCommerce is active and at the required minimum version, and if it isn't, disable Subscriptions.
*
* @since 1.0
*/
if ( ! is_woocommerce_active() || version_compare( get_option( 'woocommerce_db_version' ), WC_Subscriptions::$wc_minimum_supported_version, '<' ) ) {
add_action( 'admin_notices', 'WC_Subscriptions::woocommerce_inactive_notice' );
return;
}
define( 'WCS_INIT_TIMESTAMP', gmdate( 'U' ) );
// Manually load functions files.
require_once( dirname( __FILE__ ) . '/wcs-functions.php' );
require_once( dirname( __FILE__ ) . '/includes/gateways/paypal/includes/wcs-paypal-functions.php' );
// Load and set up the Autoloader
require_once( dirname( __FILE__ ) . '/includes/class-wcs-autoloader.php' );
$wcs_autoloader = new WCS_Autoloader( dirname( __FILE__ ) );
$wcs_autoloader->register();
// Load libraries manually.
require_once( dirname( __FILE__ ) . '/includes/libraries/action-scheduler/action-scheduler.php' );
// Initialize our classes.
WC_Subscriptions_Coupon::init();
WC_Subscriptions_Product::init();
WC_Subscriptions_Admin::init();
WC_Subscriptions_Manager::init();
WC_Subscriptions_Cart::init();
WC_Subscriptions_Cart_Validator::init();
WC_Subscriptions_Order::init();
WC_Subscriptions_Renewal_Order::init();
WC_Subscriptions_Checkout::init();
WC_Subscriptions_Email::init();
WC_Subscriptions_Addresses::init();
WC_Subscriptions_Change_Payment_Gateway::init();
WC_Subscriptions_Payment_Gateways::init();
WCS_PayPal_Standard_Change_Payment_Method::init();
WC_Subscriptions_Switcher::init();
WC_Subscriptions_Tracker::init();
WCS_Upgrade_Logger::init();
new WCS_Cart_Renewal();
new WCS_Cart_Resubscribe();
new WCS_Cart_Initial_Payment();
WCS_Download_Handler::init();
WCS_Retry_Manager::init();
new WCS_Cart_Switch();
WCS_Limiter::init();
WCS_Admin_System_Status::init();
WCS_Upgrade_Notice_Manager::init();
WCS_Staging::init();
WCS_Permalink_Manager::init();
WCS_Custom_Order_Item_Manager::init();
WCS_Early_Renewal_Modal_Handler::init();
WCS_Dependent_Hook_Manager::init();
// Some classes run init on a particular hook.
add_action( 'init', array( 'WC_Subscriptions_Synchroniser', 'init' ) );
add_action( 'after_setup_theme', array( 'WC_Subscriptions_Upgrader', 'init' ), 11 );
add_action( 'init', array( 'WC_PayPal_Standard_Subscriptions', 'init' ), 11 );
/**
* The main subscriptions class.
*
* @since 1.0
*/
class WC_Subscriptions {
public static $name = 'subscription';
public static $activation_transient = 'woocommerce_subscriptions_activated';
public static $plugin_file = __FILE__;
public static $version = '3.0.1';
public static $wc_minimum_supported_version = '3.0';
private static $total_subscription_count = null;
private static $scheduler;
/** @var WCS_Cache_Manager */
public static $cache;
/** @var WCS_Autoloader */
protected static $autoloader;
/**
* Set up the class, including it's hooks & filters, when the file is loaded.
*
* @since 1.0
*
* @param WCS_Autoloader $autoloader Autoloader instance.
*/
public static function init( $autoloader = null ) {
self::$autoloader = $autoloader ? $autoloader : new WCS_Autoloader( dirname( __FILE__ ) );
// Register our custom subscription order type after WC_Post_types::register_post_types()
add_action( 'init', __CLASS__ . '::register_order_types', 6 );
add_filter( 'woocommerce_data_stores', __CLASS__ . '::add_data_stores', 10, 1 );
// Register our custom subscription order statuses before WC_Post_types::register_post_status()
add_action( 'init', __CLASS__ . '::register_post_status', 9 );
add_action( 'init', __CLASS__ . '::maybe_activate_woocommerce_subscriptions' );
register_deactivation_hook( __FILE__, __CLASS__ . '::deactivate_woocommerce_subscriptions' );
// Override the WC default "Add to cart" text to "Sign up now" (in various places/templates)
add_filter( 'woocommerce_order_button_text', __CLASS__ . '::order_button_text' );
add_action( 'woocommerce_subscription_add_to_cart', __CLASS__ . '::subscription_add_to_cart', 30 );
add_action( 'woocommerce_variable-subscription_add_to_cart', __CLASS__ . '::variable_subscription_add_to_cart', 30 );
add_action( 'wcopc_subscription_add_to_cart', __CLASS__ . '::wcopc_subscription_add_to_cart' ); // One Page Checkout compatibility
// Enqueue front-end styles, run after Storefront because it sets the styles to be empty
add_filter( 'woocommerce_enqueue_styles', __CLASS__ . '::enqueue_styles', 100, 1 );
// Load translation files
add_action( 'init', __CLASS__ . '::load_plugin_textdomain', 3 );
// Load frontend scripts
add_action( 'wp_enqueue_scripts', __CLASS__ . '::enqueue_frontend_scripts', 3 );
// Load dependent files
add_action( 'plugins_loaded', __CLASS__ . '::load_dependant_classes' );
// Attach hooks which depend on WooCommerce constants
add_action( 'plugins_loaded', array( __CLASS__, 'attach_dependant_hooks' ) );
// Make sure the related order data store instance is loaded and initialised so that cache management will function
add_action( 'plugins_loaded', 'WCS_Related_Order_Store::instance' );
// Make sure the related order data store instance is loaded and initialised so that cache management will function
add_action( 'plugins_loaded', 'WCS_Customer_Store::instance' );
// Staging site or site migration notice
add_action( 'admin_notices', __CLASS__ . '::woocommerce_site_change_notice' );
// Add the "Settings | Documentation" links on the Plugins administration screen
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), __CLASS__ . '::action_links' );
add_filter( 'action_scheduler_queue_runner_batch_size', __CLASS__ . '::action_scheduler_multisite_batch_size' );
add_action( 'in_plugin_update_message-' . plugin_basename( __FILE__ ), __CLASS__ . '::update_notice', 10, 2 );
// get details of orders of a customer
add_action( 'wp_ajax_wcs_get_customer_orders', __CLASS__ . '::get_customer_orders' );
self::$cache = WCS_Cache_Manager::get_instance();
$scheduler_class = apply_filters( 'woocommerce_subscriptions_scheduler', 'WCS_Action_Scheduler' );
self::$scheduler = new $scheduler_class();
}
/**
* Get customer's order details via ajax.
*/
public static function get_customer_orders() {
check_ajax_referer( 'get-customer-orders', 'security' );
if ( ! current_user_can( 'edit_shop_orders' ) ) {
wp_die( -1 );
}
$user_id = absint( $_POST['user_id'] );
$orders = wc_get_orders( array( 'customer' => $user_id, 'post_type' => 'shop_order', 'posts_per_page' => '-1' ) );
$customer_orders = array();
foreach ( $orders as $order ) {
$customer_orders[ wcs_get_objects_property( $order, 'id' ) ] = $order->get_order_number();
}
wp_send_json( $customer_orders );
}
/**
* Register data stores for WooCommerce 3.0+
*
* @since 2.2.0
*/
public static function add_data_stores( $data_stores ) {
// Our custom data stores.
$data_stores['subscription'] = 'WCS_Subscription_Data_Store_CPT';
$data_stores['product-variable-subscription'] = 'WCS_Product_Variable_Data_Store_CPT';
// Use WC core data stores for our products.
$data_stores['product-subscription_variation'] = 'WC_Product_Variation_Data_Store_CPT';
$data_stores['order-item-line_item_pending_switch'] = 'WC_Order_Item_Product_Data_Store';
return $data_stores;
}
/**
* Register core post types
*
* @since 2.0
*/
public static function register_order_types() {
wc_register_order_type(
'shop_subscription',
apply_filters( 'woocommerce_register_post_type_subscription',
array(
// register_post_type() params
'labels' => array(
'name' => __( 'Subscriptions', 'woocommerce-subscriptions' ),
'singular_name' => __( 'Subscription', 'woocommerce-subscriptions' ),
'add_new' => _x( 'Add Subscription', 'custom post type setting', 'woocommerce-subscriptions' ),
'add_new_item' => _x( 'Add New Subscription', 'custom post type setting', 'woocommerce-subscriptions' ),
'edit' => _x( 'Edit', 'custom post type setting', 'woocommerce-subscriptions' ),
'edit_item' => _x( 'Edit Subscription', 'custom post type setting', 'woocommerce-subscriptions' ),
'new_item' => _x( 'New Subscription', 'custom post type setting', 'woocommerce-subscriptions' ),
'view' => _x( 'View Subscription', 'custom post type setting', 'woocommerce-subscriptions' ),
'view_item' => _x( 'View Subscription', 'custom post type setting', 'woocommerce-subscriptions' ),
'search_items' => __( 'Search Subscriptions', 'woocommerce-subscriptions' ),
'not_found' => self::get_not_found_text(),
'not_found_in_trash' => _x( 'No Subscriptions found in trash', 'custom post type setting', 'woocommerce-subscriptions' ),
'parent' => _x( 'Parent Subscriptions', 'custom post type setting', 'woocommerce-subscriptions' ),
'menu_name' => __( 'Subscriptions', 'woocommerce-subscriptions' ),
),
'description' => __( 'This is where subscriptions are stored.', 'woocommerce-subscriptions' ),
'public' => false,
'show_ui' => true,
'capability_type' => 'shop_order',
'map_meta_cap' => true,
'publicly_queryable' => false,
'exclude_from_search' => true,
'show_in_menu' => current_user_can( 'manage_woocommerce' ) ? 'woocommerce' : true,
'hierarchical' => false,
'show_in_nav_menus' => false,
'rewrite' => false,
'query_var' => false,
'supports' => array( 'title', 'comments', 'custom-fields' ),
'has_archive' => false,
// wc_register_order_type() params
'exclude_from_orders_screen' => true,
'add_order_meta_boxes' => true,
'exclude_from_order_count' => true,
'exclude_from_order_views' => true,
'exclude_from_order_webhooks' => true,
'exclude_from_order_reports' => true,
'exclude_from_order_sales_reports' => true,
'class_name' => self::is_woocommerce_pre( '3.0' ) ? 'WC_Subscription_Legacy' : 'WC_Subscription',
)
)
);
}
/**
* Method that returns the not found text. If the user has created at least one subscription, the standard message
* will appear. If that's empty, the long, explanatory one will appear in the table.
*
* Filters:
* - woocommerce_subscriptions_not_empty: gets passed the boolean option value. 'true' means the subscriptions
* list is not empty, the user is familiar with how it works, and standard message appears.
* - woocommerce_subscriptions_not_found_label: gets the original message for other plugins to modify, in case
* they want to add more links, or modify any of the messages.
* @since 2.0
*
* @return string what appears in the list table of the subscriptions
*/
private static function get_not_found_text() {
$subscriptions_exist = self::$cache->cache_and_get( 'wcs_do_subscriptions_exist', 'wcs_do_subscriptions_exist' );
if ( true === apply_filters( 'woocommerce_subscriptions_not_empty', $subscriptions_exist ) ) {
$not_found_text = __( 'No Subscriptions found', 'woocommerce-subscriptions' );
} else {
$not_found_text = '<p>' . __( 'Subscriptions will appear here for you to view and manage once purchased by a customer.', 'woocommerce-subscriptions' ) . '</p>';
// translators: placeholders are opening and closing link tags
$not_found_text .= '<p>' . sprintf( __( '%sLearn more about managing subscriptions »%s', 'woocommerce-subscriptions' ), '<a href="http://docs.woocommerce.com/document/subscriptions/store-manager-guide/#section-3" target="_blank">', '</a>' ) . '</p>';
// translators: placeholders are opening and closing link tags
$not_found_text .= '<p>' . sprintf( __( '%sAdd a subscription product »%s', 'woocommerce-subscriptions' ), '<a href="' . esc_url( WC_Subscriptions_Admin::add_subscription_url() ) . '">', '</a>' ) . '</p>';
}
return apply_filters( 'woocommerce_subscriptions_not_found_label', $not_found_text );
}
/**
* Register our custom post statuses, used for order/subscription status
*/
public static function register_post_status() {
$subscription_statuses = wcs_get_subscription_statuses();
$registered_statuses = apply_filters( 'woocommerce_subscriptions_registered_statuses', array(
'wc-active' => _nx_noop( 'Active <span class="count">(%s)</span>', 'Active <span class="count">(%s)</span>', 'post status label including post count', 'woocommerce-subscriptions' ),
'wc-switched' => _nx_noop( 'Switched <span class="count">(%s)</span>', 'Switched <span class="count">(%s)</span>', 'post status label including post count', 'woocommerce-subscriptions' ),
'wc-expired' => _nx_noop( 'Expired <span class="count">(%s)</span>', 'Expired <span class="count">(%s)</span>', 'post status label including post count', 'woocommerce-subscriptions' ),
'wc-pending-cancel' => _nx_noop( 'Pending Cancellation <span class="count">(%s)</span>', 'Pending Cancellation <span class="count">(%s)</span>', 'post status label including post count', 'woocommerce-subscriptions' ),
) );
if ( is_array( $subscription_statuses ) && is_array( $registered_statuses ) ) {
foreach ( $registered_statuses as $status => $label_count ) {
register_post_status( $status, array(
'label' => $subscription_statuses[ $status ], // use same label/translations as wcs_get_subscription_statuses()
'public' => false,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
'label_count' => $label_count,
) );
}
}
}
/**
* Enqueues scripts for frontend
*
* @since 2.3
*/
public static function enqueue_frontend_scripts() {
$dependencies = array( 'jquery' );
if ( is_cart() || is_checkout() ) {
wp_enqueue_script( 'wcs-cart', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/frontend/wcs-cart.js', $dependencies, WC_Subscriptions::$version, true );
} elseif ( is_product() ) {
wp_enqueue_script( 'wcs-single-product', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/frontend/single-product.js', $dependencies, WC_Subscriptions::$version, true );
} elseif ( wcs_is_view_subscription_page() ) {
global $wp;
$subscription = wcs_get_subscription( $wp->query_vars['view-subscription'] );
if ( $subscription && current_user_can( 'view_order', $subscription->get_id() ) ) {
$dependencies[] = 'jquery-blockui';
$script_params = array(
'ajax_url' => esc_url( WC()->ajax_url() ),
'subscription_id' => $subscription->get_id(),
'add_payment_method_msg' => __( 'To enable automatic renewals for this subscription, you will first need to add a payment method.', 'woocommerce-subscriptions' ) . "\n\n" . __( 'Would you like to add a payment method now?', 'woocommerce-subscriptions' ),
'auto_renew_nonce' => WCS_My_Account_Auto_Renew_Toggle::can_user_toggle_auto_renewal( $subscription ) ? wp_create_nonce( "toggle-auto-renew-{$subscription->get_id()}" ) : false,
'add_payment_method_url' => esc_url( $subscription->get_change_payment_method_url() ),
'has_payment_gateway' => $subscription->has_payment_gateway() && wc_get_payment_gateway_by_order( $subscription )->supports( 'subscriptions' ),
);
wp_enqueue_script( 'wcs-view-subscription', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/frontend/view-subscription.js', $dependencies, WC_Subscriptions::$version, true );
wp_localize_script( 'wcs-view-subscription', 'WCSViewSubscription', apply_filters( 'woocommerce_subscriptions_frontend_view_subscription_script_parameters', $script_params ) );
}
}
}
/**
* Enqueues stylesheet for the My Subscriptions table on the My Account page.
*
* @since 1.5
*/
public static function enqueue_styles( $styles ) {
if ( is_checkout() || is_cart() ) {
$styles['wcs-checkout'] = array(
'src' => str_replace( array( 'http:', 'https:' ), '', plugin_dir_url( __FILE__ ) ) . 'assets/css/checkout.css',
'deps' => 'wc-checkout',
'version' => WC_VERSION,
'media' => 'all',
);
} elseif ( is_account_page() ) {
$styles['wcs-view-subscription'] = array(
'src' => str_replace( array( 'http:', 'https:' ), '', plugin_dir_url( __FILE__ ) ) . 'assets/css/view-subscription.css',
'deps' => 'woocommerce-smallscreen',
'version' => self::$version,
'media' => 'all',
);
}
return $styles;
}
/**
* Loads the my-subscriptions.php template on the My Account page.
*
* @since 1.0
* @param int $current_page
*/
public static function get_my_subscriptions_template( $current_page = 1 ) {
$all_subscriptions = wcs_get_users_subscriptions();
$current_page = empty( $current_page ) ? 1 : absint( $current_page );
$posts_per_page = get_option( 'posts_per_page' );
$max_num_pages = ceil( count( $all_subscriptions ) / $posts_per_page );
$subscriptions = array_slice( $all_subscriptions, ( $current_page - 1 ) * $posts_per_page, $posts_per_page );
wc_get_template( 'myaccount/my-subscriptions.php', array( 'subscriptions' => $subscriptions, 'current_page' => $current_page, 'max_num_pages' => $max_num_pages, 'paginate' => true ), '', plugin_dir_path( __FILE__ ) . 'templates/' );
}
/**
* Output a redirect URL when an item is added to the cart when a subscription was already in the cart.
*
* @since 1.0
*/
public static function redirect_ajax_add_to_cart( $fragments ) {
$fragments['error'] = true;
$fragments['product_url'] = wc_get_cart_url();
# Force error on add_to_cart() to redirect
add_filter( 'woocommerce_add_to_cart_validation', '__return_false', 10 );
add_filter( 'woocommerce_cart_redirect_after_error', __CLASS__ . '::redirect_to_cart', 10, 2 );
do_action( 'wc_ajax_add_to_cart' );
return $fragments;
}
/**
* Return a url for cart redirect.
*
* @since 2.3.0
*/
public static function redirect_to_cart( $permalink, $product_id ) {
return wc_get_cart_url();
}
/**
* When a subscription is added to the cart, remove other products/subscriptions to
* work with PayPal Standard, which only accept one subscription per checkout.
*
* If multiple purchase flag is set, allow them to be added at the same time.
*
* @deprecated 2.6.0
* @since 1.0
*/
public static function maybe_empty_cart( $valid, $product_id, $quantity, $variation_id = '', $variations = array() ) {
wcs_deprecated_function( __METHOD__, '2.6.0', 'WC_Subscriptions_Cart_Validator::maybe_empty_cart()' );
$is_subscription = WC_Subscriptions_Product::is_subscription( $product_id );
$cart_contains_subscription = WC_Subscriptions_Cart::cart_contains_subscription();
$multiple_subscriptions_possible = WC_Subscriptions_Payment_Gateways::one_gateway_supports( 'multiple_subscriptions' );
$manual_renewals_enabled = ( 'yes' == get_option( WC_Subscriptions_Admin::$option_prefix . '_accept_manual_renewals', 'no' ) );
$canonical_product_id = ! empty( $variation_id ) ? $variation_id : $product_id;
if ( $is_subscription && 'yes' != get_option( WC_Subscriptions_Admin::$option_prefix . '_multiple_purchase', 'no' ) ) {
// Generate a cart item key from variation and cart item data - which may be added by other plugins
$cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', array(), $product_id, $variation_id, $quantity );
$cart_item_id = WC()->cart->generate_cart_id( $product_id, $variation_id, $variations, $cart_item_data );
$product = wc_get_product( $product_id );
// If the product is sold individually or if the cart doesn't already contain this product, empty the cart.
if ( ( $product && $product->is_sold_individually() ) || ! WC()->cart->find_product_in_cart( $cart_item_id ) ) {
$coupons = WC()->cart->get_applied_coupons();
WC()->cart->empty_cart();
WC()->cart->set_applied_coupons( $coupons );
}
} elseif ( $is_subscription && wcs_cart_contains_renewal() && ! $multiple_subscriptions_possible && ! $manual_renewals_enabled ) {
WC_Subscriptions_Cart::remove_subscriptions_from_cart();
wc_add_notice( __( 'A subscription renewal has been removed from your cart. Multiple subscriptions can not be purchased at the same time.', 'woocommerce-subscriptions' ), 'notice' );
} elseif ( $is_subscription && $cart_contains_subscription && ! $multiple_subscriptions_possible && ! $manual_renewals_enabled && ! WC_Subscriptions_Cart::cart_contains_product( $canonical_product_id ) ) {
WC_Subscriptions_Cart::remove_subscriptions_from_cart();
wc_add_notice( __( 'A subscription has been removed from your cart. Due to payment gateway restrictions, different subscription products can not be purchased at the same time.', 'woocommerce-subscriptions' ), 'notice' );
} elseif ( $cart_contains_subscription && 'yes' != get_option( WC_Subscriptions_Admin::$option_prefix . '_multiple_purchase', 'no' ) ) {
WC_Subscriptions_Cart::remove_subscriptions_from_cart();
wc_add_notice( __( 'A subscription has been removed from your cart. Products and subscriptions can not be purchased at the same time.', 'woocommerce-subscriptions' ), 'notice' );
// Redirect to cart page to remove subscription & notify shopper
if ( self::is_woocommerce_pre( '3.0.8' ) ) {
add_filter( 'add_to_cart_fragments', __CLASS__ . '::redirect_ajax_add_to_cart' );
} else {
add_filter( 'woocommerce_add_to_cart_fragments', __CLASS__ . '::redirect_ajax_add_to_cart' );
}
}
return WC_Subscriptions_Cart_Validator::maybe_empty_cart( $valid, $product_id, $quantity, $variation_id, $variations );
}
/**
* Removes all subscription products from the shopping cart.
*
* @deprecated 2.6.0
* @since 1.0
*/
public static function remove_subscriptions_from_cart() {
wcs_deprecated_function( __METHOD__, '2.6.0', 'WC_Subscriptions_Cart::remove_subscriptions_from_cart()' );
WC_Subscriptions_Cart::remove_subscriptions_from_cart();
}
/**
* For a smoother sign up process, tell WooCommerce to redirect the shopper immediately to
* the checkout page after she clicks the "Sign up now" button
*
* Only enabled if multiple checkout is not enabled.
*
* @param string $url The cart redirect $url WooCommerce determined.
* @since 1.0
*/
public static function add_to_cart_redirect( $url ) {
// If product is of the subscription type
if ( isset( $_REQUEST['add-to-cart'] ) && is_numeric( $_REQUEST['add-to-cart'] ) && WC_Subscriptions_Product::is_subscription( (int) $_REQUEST['add-to-cart'] ) ) {
// Redirect to checkout if mixed checkout is disabled
if ( 'yes' != get_option( WC_Subscriptions_Admin::$option_prefix . '_multiple_purchase', 'no' ) ) {
$quantity = isset( $_REQUEST['quantity'] ) ? $_REQUEST['quantity'] : 1;
$product_id = $_REQUEST['add-to-cart'];
$add_to_cart_notice = wc_add_to_cart_message( array( $product_id => $quantity ), true, true );
if ( wc_has_notice( $add_to_cart_notice ) ) {
$notices = wc_get_notices();
$add_to_cart_notice_index = array_search( $add_to_cart_notice, $notices['success'] );
unset( $notices['success'][ $add_to_cart_notice_index ] );
wc_set_notices( $notices );
}
$url = wc_get_checkout_url();
}
}
return $url;
}
/**
* Override the WooCommerce "Place order" text with "Sign up now"
*
* @since 1.0
*/
public static function order_button_text( $button_text ) {
global $product;
if ( WC_Subscriptions_Cart::cart_contains_subscription() ) {
$button_text = get_option( WC_Subscriptions_Admin::$option_prefix . '_order_button_text', __( 'Sign up now', 'woocommerce-subscriptions' ) );
}
return $button_text;
}
/**
* Load the subscription add_to_cart template.
*
* Use the same cart template for subscription as that which is used for simple products. Reduce code duplication
* and is made possible by the friendly actions & filters found through WC.
*
* Not using a custom template both prevents code duplication and helps future proof this extension from core changes.
*
* @since 1.0
*/
public static function subscription_add_to_cart() {
wc_get_template( 'single-product/add-to-cart/subscription.php', array(), '', plugin_dir_path( __FILE__ ) . 'templates/' );
}
/**
* Load the variable subscription add_to_cart template
*
* Use a very similar cart template as that of a variable product with added functionality.
*
* @since 2.0.9
*/
public static function variable_subscription_add_to_cart() {
global $product;
// Enqueue variation scripts
wp_enqueue_script( 'wc-add-to-cart-variation' );
// Get Available variations?
$get_variations = sizeof( $product->get_children() ) <= apply_filters( 'woocommerce_ajax_variation_threshold', 30, $product );
// Load the template
wc_get_template( 'single-product/add-to-cart/variable-subscription.php', array(
'available_variations' => $get_variations ? $product->get_available_variations() : false,
'attributes' => $product->get_variation_attributes(),
'selected_attributes' => $product->get_default_attributes(),
), '', plugin_dir_path( __FILE__ ) . 'templates/' );
}
/**
* Compatibility with WooCommerce On One Page Checkout.
*
* Use OPC's simple add to cart template for simple subscription products (to ensure data attributes required by OPC are added).
*
* Variable subscription products will be handled automatically because they identify as "variable" in response to is_type() method calls,
* which OPC uses.
*
* @since 1.5.16
*/
public static function wcopc_subscription_add_to_cart() {
global $product;
wc_get_template( 'checkout/add-to-cart/simple.php', array( 'product' => $product ), '', PP_One_Page_Checkout::$template_path );
}
/**
* Takes a number and returns the number with its relevant suffix appended, eg. for 2, the function returns 2nd
*
* @since 1.0
*/
public static function append_numeral_suffix( $number ) {
// Handle teens: if the tens digit of a number is 1, then write "th" after the number. For example: 11th, 13th, 19th, 112th, 9311th. http://en.wikipedia.org/wiki/English_numerals
if ( strlen( $number ) > 1 && 1 == substr( $number, -2, 1 ) ) {
// translators: placeholder is a number, this is for the teens
$number_string = sprintf( __( '%sth', 'woocommerce-subscriptions' ), $number );
} else { // Append relevant suffix
switch ( substr( $number, -1 ) ) {
case 1:
// translators: placeholder is a number, numbers ending in 1
$number_string = sprintf( __( '%sst', 'woocommerce-subscriptions' ), $number );
break;
case 2:
// translators: placeholder is a number, numbers ending in 2
$number_string = sprintf( __( '%snd', 'woocommerce-subscriptions' ), $number );
break;
case 3:
// translators: placeholder is a number, numbers ending in 3
$number_string = sprintf( __( '%srd', 'woocommerce-subscriptions' ), $number );
break;
default:
// translators: placeholder is a number, numbers ending in 4-9, 0
$number_string = sprintf( __( '%sth', 'woocommerce-subscriptions' ), $number );
break;
}
}
return apply_filters( 'woocommerce_numeral_suffix', $number_string, $number );
}
/*
* Plugin House Keeping
*/
/**
* Called when WooCommerce is inactive or running and out-of-date version to display an inactive notice.
*
* @since 1.2
*/
public static function woocommerce_inactive_notice() {
if ( current_user_can( 'activate_plugins' ) ) {
$admin_notice_content = '';
if ( ! is_woocommerce_active() ) {
$install_url = wp_nonce_url( add_query_arg( array( 'action' => 'install-plugin', 'plugin' => 'woocommerce' ), admin_url( 'update.php' ) ), 'install-plugin_woocommerce' );
// translators: 1$-2$: opening and closing <strong> tags, 3$-4$: link tags, takes to woocommerce plugin on wp.org, 5$-6$: opening and closing link tags, leads to plugins.php in admin
$admin_notice_content = sprintf( esc_html__( '%1$sWooCommerce Subscriptions is inactive.%2$s The %3$sWooCommerce plugin%4$s must be active for WooCommerce Subscriptions to work. Please %5$sinstall & activate WooCommerce »%6$s', 'woocommerce-subscriptions' ), '<strong>', '</strong>', '<a href="http://wordpress.org/extend/plugins/woocommerce/">', '</a>', '<a href="' . esc_url( $install_url ) . '">', '</a>' );
} elseif ( version_compare( get_option( 'woocommerce_db_version' ), self::$wc_minimum_supported_version, '<' ) ) {
// translators: 1$-2$: opening and closing <strong> tags, 3$: minimum supported WooCommerce version, 4$-5$: opening and closing link tags, leads to plugin admin
$admin_notice_content = sprintf( esc_html__( '%1$sWooCommerce Subscriptions is inactive.%2$s This version of Subscriptions requires WooCommerce %3$s or newer. Please %4$supdate WooCommerce to version %3$s or newer »%5$s', 'woocommerce-subscriptions' ), '<strong>', '</strong>', self::$wc_minimum_supported_version,'<a href="' . esc_url( admin_url( 'plugins.php' ) ) . '">', '</a>' );
}
if ( $admin_notice_content ) {
require_once( dirname( __FILE__ ) . '/includes/admin/class-wcs-admin-notice.php' );
$notice = new WCS_Admin_Notice( 'error' );
$notice->set_simple_content( $admin_notice_content );
$notice->display();
}
}
}
/**
* Checks on each admin page load if Subscriptions plugin is activated.
*
* Apparently the official WP API is "lame" and it's far better to use an upgrade routine fired on admin_init: http://core.trac.wordpress.org/ticket/14170
*
* @since 1.1
*/
public static function maybe_activate_woocommerce_subscriptions() {
$is_active = get_option( WC_Subscriptions_Admin::$option_prefix . '_is_active', false );
if ( false == $is_active ) {
// Add the "Subscriptions" product type
if ( ! get_term_by( 'slug', self::$name, 'product_type' ) ) {
wp_insert_term( self::$name, 'product_type' );
}
// Maybe add the "Variable Subscriptions" product type
if ( ! get_term_by( 'slug', 'variable-subscription', 'product_type' ) ) {
wp_insert_term( __( 'Variable Subscription', 'woocommerce-subscriptions' ), 'product_type' );
}
// If no Subscription settings exist, its the first activation, so add defaults
if ( get_option( WC_Subscriptions_Admin::$option_prefix . '_cancelled_role', false ) == false ) {
WC_Subscriptions_Admin::add_default_settings();
}
// if this is the first time activating WooCommerce Subscription we want to enable PayPal debugging by default.
if ( '0' == get_option( WC_Subscriptions_Admin::$option_prefix . '_previous_version', '0' ) && false == get_option( WC_Subscriptions_admin::$option_prefix . '_paypal_debugging_default_set', false ) ) {
$paypal_settings = get_option( 'woocommerce_paypal_settings' );
$paypal_settings['debug'] = 'yes';
update_option( 'woocommerce_paypal_settings', $paypal_settings );
update_option( WC_Subscriptions_admin::$option_prefix . '_paypal_debugging_default_set', 'true' );
}
update_option( WC_Subscriptions_Admin::$option_prefix . '_is_active', true );
set_transient( self::$activation_transient, true, 60 * 60 );
flush_rewrite_rules();
do_action( 'woocommerce_subscriptions_activated' );
}
}
/**
* Called when the plugin is deactivated. Deletes the subscription product type and fires an action.
*
* @since 1.0
*/
public static function deactivate_woocommerce_subscriptions() {
delete_option( WC_Subscriptions_Admin::$option_prefix . '_is_active' );
flush_rewrite_rules();
do_action( 'woocommerce_subscriptions_deactivated' );
}
/**
* Called on plugins_loaded to load any translation files.
*
* @since 1.1
*/
public static function load_plugin_textdomain() {
$plugin_rel_path = apply_filters( 'woocommerce_subscriptions_translation_file_rel_path', dirname( plugin_basename( __FILE__ ) ) . '/languages' );
// Then check for a language file in /wp-content/plugins/woocommerce-subscriptions/languages/ (this will be overriden by any file already loaded)
load_plugin_textdomain( 'woocommerce-subscriptions', false, $plugin_rel_path );
}
/**
* Loads classes that depend on WooCommerce base classes.
*
* @since 1.2.4
*/
public static function load_dependant_classes() {
new WCS_Admin_Post_Types();
new WCS_Admin_Meta_Boxes();
new WCS_Admin_Reports();
new WCS_Report_Cache_Manager();
WCS_Webhooks::init();
new WCS_Auth();
WCS_API::init();
WCS_Template_Loader::init();
new WCS_Query();
WCS_Remove_Item::init();
WCS_User_Change_Status_Handler::init();
WCS_My_Account_Payment_Methods::init();
WCS_My_Account_Auto_Renew_Toggle::init();
if ( self::is_woocommerce_pre( '3.0' ) ) {
WCS_Product_Legacy::init();
// Load WC_DateTime when it doesn't exist yet so we can use it for datetime handling consistently with WC 3.0+
if ( ! class_exists( 'WC_DateTime' ) ) {
require_once( dirname( __FILE__ ) . '/includes/libraries/class-wc-datetime.php' );
}
} else {
new WCS_Deprecated_Filter_Hooks();
}
// Provide a hook to enable running deprecation handling for stores that might want to check for deprecated code
if ( apply_filters( 'woocommerce_subscriptions_load_deprecation_handlers', false ) ) {
new WCS_Action_Deprecator();
new WCS_Filter_Deprecator();
new WCS_Dynamic_Action_Deprecator();
new WCS_Dynamic_Filter_Deprecator();
}
if ( class_exists( 'WCS_Early_Renewal' ) ) {
$notice = new WCS_Admin_Notice( 'error' );
$notice->set_simple_content( sprintf( __( '%1$sWarning!%2$s We can see the %1$sWooCommerce Subscriptions Early Renewal%2$s plugin is active. Version %3$s of %1$sWooCommerce Subscriptions%2$s comes with that plugin\'s functionality packaged into the core plugin. Please deactivate WooCommerce Subscriptions Early Renewal to avoid any conflicts.', 'woocommerce-subscriptions' ), '<b>', '</b>', self::$version ) );
$notice->set_actions( array(
array(
'name' => __( 'Installed Plugins', 'woocommerce-subscriptions' ),
'url' => admin_url( 'plugins.php' ),
),
) );
$notice->display();
} else {
WCS_Early_Renewal_Manager::init();
require_once( dirname( __FILE__ ) . '/includes/early-renewal/wcs-early-renewal-functions.php' );
if ( WCS_Early_Renewal_Manager::is_early_renewal_enabled() ) {
new WCS_Cart_Early_Renewal();
}
}
$failed_scheduled_action_manager = new WCS_Failed_Scheduled_Action_Manager( new WC_Logger() );
$failed_scheduled_action_manager->init();
if ( class_exists( 'WC_Abstract_Privacy' ) ) {
new WCS_Privacy();
}
}
/**
* Some hooks need to check for the version of WooCommerce, which we can only do after WooCommerce is loaded.
*
* @since 1.5.17
*/
public static function attach_dependant_hooks() {
// Redirect the user immediately to the checkout page after clicking "Sign Up Now" buttons to encourage immediate checkout
add_filter( 'woocommerce_add_to_cart_redirect', __CLASS__ . '::add_to_cart_redirect' );
if ( self::is_woocommerce_pre( '2.6' ) ) {
// Display Subscriptions on a User's account page
add_action( 'woocommerce_before_my_account', __CLASS__ . '::get_my_subscriptions_template' );
}
// Ensure the autoloader knows which API to use.
self::$autoloader->use_legacy_api( WC_Subscriptions::is_woocommerce_pre( '3.0' ) );
}
/**
* Displays a notice when Subscriptions is being run on a different site, like a staging or testing site.
*
* @since 1.3.8
*/
public static function woocommerce_site_change_notice() {
if ( self::is_duplicate_site() && current_user_can( 'manage_options' ) ) {
if ( ! empty( $_REQUEST['_wcsnonce'] ) && wp_verify_nonce( $_REQUEST['_wcsnonce'], 'wcs_duplicate_site' ) && isset( $_GET['wc_subscription_duplicate_site'] ) ) {
if ( 'update' === $_GET['wc_subscription_duplicate_site'] ) {
WC_Subscriptions::set_duplicate_site_url_lock();
} elseif ( 'ignore' === $_GET['wc_subscription_duplicate_site'] ) {
update_option( 'wcs_ignore_duplicate_siteurl_notice', self::get_current_sites_duplicate_lock() );
}
wp_safe_redirect( remove_query_arg( array( 'wc_subscription_duplicate_site', '_wcsnonce' ) ) );
} elseif ( self::get_current_sites_duplicate_lock() !== get_option( 'wcs_ignore_duplicate_siteurl_notice' ) ) {
$notice = new WCS_Admin_Notice( 'error' );
$notice->set_simple_content(
sprintf(
// translators: 1$-2$: opening and closing <strong> tags. 3$-4$: opening and closing link tags for learn more. Leads to duplicate site article on docs. 5$-6$: Opening and closing link to production URL. 7$: Production URL .
esc_html__( 'It looks like this site has moved or is a duplicate site. %1$sWooCommerce Subscriptions%2$s has disabled automatic payments and subscription related emails on this site to prevent duplicate payments from a staging or test environment. %1$sWooCommerce Subscriptions%2$s considers %5$s%7$s%6$s to be the site\'s URL. %3$sLearn more »%4$s.', 'woocommerce-subscriptions' ),
'<strong>', '</strong>',
'<a href="https://docs.woocommerce.com/document/subscriptions-handles-staging-sites/" target="_blank">', '</a>',
'<a href="' . esc_url( self::get_site_url_from_source( 'subscriptions_install' ) ) . '" target="_blank">', '</a>',
esc_url( self::get_site_url_from_source( 'subscriptions_install' ) )
)
);
$notice->set_actions( array(
array(
'name' => __( 'Quit nagging me (but don\'t enable automatic payments)', 'woocommerce-subscriptions' ),
'url' => wp_nonce_url( add_query_arg( 'wc_subscription_duplicate_site', 'ignore' ), 'wcs_duplicate_site', '_wcsnonce' ),
'class' => 'button button-primary',
),
array(
'name' => __( 'Enable automatic payments', 'woocommerce-subscriptions' ),
'url' => wp_nonce_url( add_query_arg( 'wc_subscription_duplicate_site', 'update' ), 'wcs_duplicate_site', '_wcsnonce' ),
'class' => 'button',
),
) );
$notice->display();
}
}
}
/**
* A general purpose function for grabbing an array of subscriptions in form of 'subscription_key' => 'subscription_details'.
*
* The $args param is based on the parameter of the same name used by the core WordPress @see get_posts() function.
* It can be used to choose which subscriptions should be returned by the function, how many subscriptions should be returned
* and in what order those subscriptions should be returned.
*
* @param array $args A set of name value pairs to determine the return value.
* 'subscriptions_per_page' The number of subscriptions to return. Set to -1 for unlimited. Default 10.
* 'offset' An optional number of subscription to displace or pass over. Default 0.
* 'orderby' The field which the subscriptions should be ordered by. Can be 'start_date', 'expiry_date', 'end_date', 'status', 'name' or 'order_id'. Defaults to 'start_date'.
* 'order' The order of the values returned. Can be 'ASC' or 'DESC'. Defaults to 'DESC'
* 'customer_id' The user ID of a customer on the site.
* 'product_id' The post ID of a WC_Product_Subscription, WC_Product_Variable_Subscription or WC_Product_Subscription_Variation object
* 'subscription_status' Any valid subscription status. Can be 'any', 'active', 'cancelled', 'suspended', 'expired', 'pending' or 'trash'. Defaults to 'any'.
* @return array Subscription details in 'subscription_key' => 'subscription_details' form.
* @since 1.4
*/
public static function get_subscriptions( $args = array() ) {
if ( isset( $args['orderby'] ) ) {
// Although most of these weren't public orderby values, they were used internally so may have been used by developers
switch ( $args['orderby'] ) {
case '_subscription_status' :
_deprecated_argument( __METHOD__, '2.0', 'The "_subscription_status" orderby value is deprecated. Use "status" instead.' );
$args['orderby'] = 'status';
break;
case '_subscription_start_date' :
_deprecated_argument( __METHOD__, '2.0', 'The "_subscription_start_date" orderby value is deprecated. Use "start_date" instead.' );
$args['orderby'] = 'start_date';
break;
case 'expiry_date' :
case '_subscription_expiry_date' :
case '_subscription_end_date' :
_deprecated_argument( __METHOD__, '2.0', 'The expiry date orderby value is deprecated. Use "end_date" instead.' );
$args['orderby'] = 'end_date';
break;
case 'trial_expiry_date' :
case '_subscription_trial_expiry_date' :
_deprecated_argument( __METHOD__, '2.0', 'The trial expiry date orderby value is deprecated. Use "trial_end_date" instead.' );
$args['orderby'] = 'trial_end_date';
break;
case 'name' :
_deprecated_argument( __METHOD__, '2.0', 'The "name" orderby value is deprecated - subscriptions no longer have just one name as they may contain multiple items.' );
break;
}
}
_deprecated_function( __METHOD__, '2.0', 'wcs_get_subscriptions( $args )' );
$subscriptions = wcs_get_subscriptions( $args );
$subscriptions_in_deprecated_structure = array();
// Get the subscriptions in the backward compatible structure
foreach ( $subscriptions as $subscription ) {
$subscriptions_in_deprecated_structure[ wcs_get_old_subscription_key( $subscription ) ] = wcs_get_subscription_in_deprecated_structure( $subscription );
}
return apply_filters( 'woocommerce_get_subscriptions', $subscriptions_in_deprecated_structure, $args );
}
/**
* Returns the longest possible time period
*
* @since 1.3
*/
public static function get_longest_period( $current_period, $new_period ) {
if ( empty( $current_period ) || 'year' == $new_period ) {
$longest_period = $new_period;
} elseif ( 'month' === $new_period && in_array( $current_period, array( 'week', 'day' ) ) ) {
$longest_period = $new_period;
} elseif ( 'week' === $new_period && 'day' === $current_period ) {
$longest_period = $new_period;
} else {
$longest_period = $current_period;
}
return $longest_period;