PluginProbe ʕ •ᴥ•ʔ
WooCommerce / 4.2.4
WooCommerce v4.2.4
10.8.1 10.8.0 10.8.0-rc.1 10.8.0-beta.2 10.8.0-beta.1 7.8.0-beta.1 7.8.0-beta.2 7.8.0-rc.1 7.8.0-rc.2 7.8.1 7.8.2 7.8.3 7.8.4 7.9.0 7.9.0-beta.1 7.9.0-beta.2 7.9.0-rc.2 7.9.0-rc.3 7.9.1 7.9.2 8.0.0 8.0.0-beta.1 8.0.0-beta.2 8.0.0-rc.1 8.0.0-rc.2 8.0.1 8.0.2 8.0.3 8.0.4 8.0.5 8.1.0 8.1.0-beta.1 8.1.0-rc.1 8.1.0-rc.2 8.1.1 8.1.2 8.1.3 8.1.4 8.2.0 8.2.0-beta.1 8.2.0-rc.1 8.2.0-rc.2 8.2.1 8.2.2 8.2.3 8.2.4 8.2.5 8.3.0 8.3.0-beta.1 8.3.0-rc.1 8.3.0-rc.2 8.3.1 8.3.2 8.3.3 8.3.4 8.4.0 8.4.0-beta.1 8.4.0-rc.1 8.4.1 8.4.2 8.4.3 8.5.0 8.5.0-beta.1 8.5.0-rc.1 8.5.1 8.5.2 8.5.3 8.5.4 8.5.5 8.6.0 8.6.0-beta.1 8.6.0-rc.1 8.6.1 8.6.2 8.6.3 8.6.4 8.7.0 8.7.0-beta.1 8.7.0-beta.2 8.7.0-rc.1 8.7.1 8.7.2 8.7.3 8.8.0 8.8.0-beta.1 8.8.0-rc.1 8.8.1 8.8.2 8.8.3 8.8.4 8.8.5 8.8.6 8.8.7 8.9.0 8.9.0-beta.1 8.9.0-rc.1 8.9.1 8.9.2 8.9.3 8.9.4 8.9.5 9.0.0 9.0.0-beta.1 9.0.0-beta.2 9.0.0-rc.1 9.0.1 9.0.2 9.0.3 9.0.4 9.1.0 9.1.0-beta.1 9.1.0-rc.1 9.1.1 9.1.2 9.1.3 9.1.4 9.1.5 9.1.6 9.2.0 9.2.0-beta.1 9.2.0-rc.1 9.2.1 9.2.2 9.2.3 9.2.4 9.2.5 9.3.0 9.3.0-beta.1 9.3.0-rc.1 9.3.1 9.3.2 9.3.3 9.3.4 9.3.5 9.3.6 9.4.0 9.4.0-beta.1 9.4.0-beta.2 9.4.0-rc.1 9.4.0-rc.2 9.4.0-rc.3 9.4.0-rc.4 9.4.1 9.4.2 9.4.3 9.4.4 9.4.5 9.5.0 9.5.0-beta.1 9.5.0-beta.2 9.5.0-rc.1 9.5.1 9.5.2 9.5.3 9.5.4 9.6.0 9.6.0-beta.1 9.6.0-beta.2 9.6.0-rc.1 9.6.1 9.6.2 9.6.3 9.6.4 9.7.0 9.7.0-beta.1 9.7.0-rc.1 9.7.1 9.7.2 9.7.3 9.8.0 9.8.0-beta.1 9.8.0-rc.1 9.8.1 9.8.2 9.8.3 9.8.4 9.8.5 9.8.6 9.8.7 9.9.0 9.9.0-beta.1 9.9.0-rc.1 9.9.1 9.9.2 9.9.3 9.9.4 9.9.5 9.9.6 9.9.7 3.7.3 7.1.2 3.8.0 7.2.0 3.8.0-beta.1 7.2.0-beta.1 3.8.0-rc.1 7.2.0-beta.2 3.8.0-rc.2 7.2.0-rc.1 3.8.1 7.2.0-rc.2 3.8.2 7.2.1 3.8.3 7.2.2 3.9.0 7.2.3 3.9.0-beta.1 7.2.4 3.9.0-beta.2 7.3.0 3.9.0-rc.1 7.3.0-beta.1 3.9.0-rc.2 7.3.0-beta.2 3.9.0-rc.3 7.3.0-rc.1 3.9.0-rc.4 7.3.0-rc.2 3.9.1 7.3.1 3.9.2 7.4.0 3.9.3 7.4.0-beta.1 3.9.4 7.4.0-beta.2 3.9.5 7.4.0-rc.1 4.0.0 7.4.0-rc.2 4.0.0-beta.1 7.4.1 4.0.0-rc.1 7.4.2 4.0.0-rc.2 7.5.0 4.0.1 7.5.0-beta.1 4.0.2 7.5.0-beta.2 4.0.3 7.5.0-rc.1 4.0.4 7.5.1 4.1.0 7.5.2 4.1.0-beta.1 7.6.0 4.1.0-beta.2 7.6.0-beta.1 4.1.0-rc.1 7.6.0-beta.2 4.1.0-rc.2 7.6.0-rc.1 4.1.1 7.6.0-rc.2 4.1.2 7.6.0-rc.3 4.1.3 7.6.1 4.1.4 7.6.2 4.2.0 7.7.0 4.2.0-RC.1 7.7.0-beta.1 4.2.0-RC.2 7.7.0-beta.2 4.2.0-beta.1 7.7.0-rc.1 4.2.1 7.7.1 4.2.2 7.7.2 4.2.3 7.7.3 4.2.4 7.8.0 4.2.5 4.3.0 4.3.0-beta.1 4.3.0-rc.1 4.3.0-rc.2 4.3.0-rc.3 4.3.1 4.3.2 4.3.3 4.3.4 4.3.5 4.3.6 4.4.0 4.4.0-beta.1 4.4.0-rc.1 4.4.1 4.4.2 4.4.3 4.4.4 4.5.0 4.5.0-beta.1 4.5.0-rc.1 4.5.0-rc.3 4.5.1 4.5.2 4.5.3 4.5.4 4.5.5 4.6.0 4.6.0-beta.1 4.6.0-rc.1 4.6.1 4.6.2 4.6.3 4.6.4 4.6.5 4.7.0 4.7.0-beta.1 4.7.0-beta.2 4.7.0-rc.1 4.7.1 4.7.1-beta.1 4.7.2 4.7.3 4.7.4 4.8.0 4.8.0-beta.1 4.8.0-rc.1 4.8.0-rc.2 4.8.1 4.8.2 4.8.3 4.9.0 4.9.0-beta.1 4.9.0-rc.1 4.9.0-rc.2 4.9.1 4.9.2 4.9.3 4.9.4 4.9.5 5.0.0 5.0.0-beta.1 5.0.0-beta.2 5.0.0-rc.1 5.0.0-rc.2 5.0.0-rc.3 5.0.1 5.0.2 5.0.3 5.1.0 5.1.0-beta.1 5.1.0-rc.1 trunk 5.1.1 10.0.0 5.1.2 10.0.0-rc.1 5.1.3 10.0.0-rc.2 5.2.0 10.0.1 5.2.0-beta.1 10.0.2 5.2.0-rc.1 10.0.3 5.2.0-rc.2 10.0.4 5.2.1 10.0.5 5.2.2 10.0.6 5.2.3 10.1.0 5.2.4 10.1.0-rc.1 5.2.5 10.1.0-rc.2 5.3.0 10.1.0-rc.3 5.3.0-beta.1 10.1.0-rc.4 5.3.0-rc.1 10.1.1 5.3.0-rc.2 10.1.2 5.3.1 10.1.3 5.3.2 10.1.4 5.3.3 10.2.0 5.4.0 10.2.0-beta.1 5.4.0-beta.1 10.2.0-beta.2 5.4.0-rc.1 10.2.0-rc.1 5.4.1 10.2.1 5.4.2 10.2.2 5.4.3 10.2.3 5.4.4 10.2.4 5.4.5 10.3.0 5.5.0 10.3.0-beta.1 5.5.0-beta.1 10.3.0-beta.2 5.5.0-rc.1 10.3.0-rc.1 5.5.0-rc.2 10.3.0-rc.2 5.5.1 10.3.1 5.5.2 10.3.2 5.5.3 10.3.3 5.5.4 10.3.4 5.5.5 10.3.5 5.6.0 10.3.6 5.6.0-beta.1 10.3.7 5.6.0-rc.1 10.3.8 5.6.0-rc.2 10.4.0 5.6.1 10.4.0-beta.1 5.6.2 10.4.0-beta.2 5.6.3 10.4.0-rc.1 5.7.0 10.4.1 5.7.0-beta.1 10.4.2 5.7.0-rc.1 10.4.3 5.7.1 10.4.4 5.7.2 10.5.0 5.7.3 10.5.0-beta.1 5.8.0 10.5.0-beta.2 5.8.0-beta.1 10.5.0-rc.1 5.8.0-beta.2 10.5.0-rc.2 5.8.0-rc.1 10.5.0-rc.3 5.8.1 10.5.1 5.8.2 10.5.2 5.9.0 10.5.3 5.9.0-beta.1 10.6.0 5.9.0-rc.1 10.6.0-beta.1 5.9.0-rc.2 10.6.0-beta.2 5.9.1 10.6.0-rc.1 5.9.2 10.6.1 6.0.0 10.6.2 6.0.0-beta.1 10.7.0 6.0.0-rc.1 10.7.0-beta.1 6.0.1 10.7.0-beta.2 6.0.2 10.7.0-rc.1 6.1.0 3.0.0 6.1.0-beta.1 3.0.1 6.1.0-rc.1 3.0.2 6.1.0-rc.2 3.0.3 6.1.1 3.0.4 6.1.2 3.0.5 6.1.3 3.0.6 6.2.0 3.0.7 6.2.0-beta.1 3.0.8 6.2.0-rc.1 3.0.9 6.2.0-rc.2 3.1.0 6.2.1 3.1.1 6.2.2 3.1.2 6.2.3 3.2.0 6.3.0 3.2.1 6.3.0-beta.1 3.2.2 6.3.0-rc.1 3.2.3 6.3.0-rc.2 3.2.4 6.3.1 3.2.5 6.3.2 3.2.6 6.4.0 3.3.0 6.4.0-beta.1 3.3.1 6.4.0-rc.1 3.3.2 6.4.1 3.3.2-rc.1 6.4.2 3.3.3 6.5.0 3.3.4 6.5.0-beta.1 3.3.5 6.5.0-rc.1 3.3.6 6.5.0-rc.2 3.4.0 6.5.1 3.4.0-beta.1 6.5.2 3.4.0-rc.2 6.6.0 3.4.1 6.6.0-beta.1 3.4.2 6.6.0-rc.1 3.4.3 6.6.0-rc.2 3.4.4 6.6.1 3.4.5 6.6.2 3.4.6 6.7.0 3.4.7 6.7.0-beta.1 3.4.8 6.7.0-beta.2 3.5.0 6.7.0-rc.1 3.5.0-beta.1 6.7.1 3.5.0-rc.1 6.8.0 3.5.0-rc.2 6.8.0-beta.1 3.5.1 6.8.0-beta.2 3.5.10 6.8.0-rc.1 3.5.2 6.8.1 3.5.3 6.8.2 3.5.4 6.8.3 3.5.5 6.9.0 3.5.6 6.9.0-beta.1 3.5.7 6.9.0-beta.2 3.5.8 6.9.0-rc.1 3.5.9 6.9.1 3.6.0 6.9.2 3.6.0-beta.1 6.9.3 3.6.0-rc.1 6.9.4 3.6.0-rc.2 6.9.5 3.6.0-rc.3 7.0.0 3.6.1 7.0.0-beta.1 3.6.2 7.0.0-beta.2 3.6.3 7.0.0-beta.3 3.6.4 7.0.0-rc.1 3.6.5 7.0.0-rc.2 3.6.6 7.0.1 3.6.7 7.0.2 3.7.0 7.1.0 3.7.0-beta.1 7.1.0-beta.1 3.7.0-rc.1 7.1.0-beta.2 3.7.0-rc.2 7.1.0-rc.1 3.7.1 7.1.0-rc.2 3.7.2 7.1.1
woocommerce / includes / class-wc-ajax.php
woocommerce / includes Last commit date
abstracts 5 years ago admin 5 years ago cli 5 years ago customizer 5 years ago data-stores 4 years ago emails 5 years ago export 5 years ago gateways 5 years ago import 5 years ago integrations 5 years ago interfaces 5 years ago legacy 5 years ago libraries 5 years ago log-handlers 5 years ago payment-tokens 5 years ago queue 5 years ago shipping 5 years ago shortcodes 5 years ago theme-support 5 years ago tracks 5 years ago traits 5 years ago walkers 5 years ago wccom-site 5 years ago widgets 5 years ago class-wc-ajax.php 5 years ago class-wc-api.php 5 years ago class-wc-auth.php 5 years ago class-wc-autoloader.php 5 years ago class-wc-background-emailer.php 5 years ago class-wc-background-updater.php 5 years ago class-wc-breadcrumb.php 5 years ago class-wc-cache-helper.php 5 years ago class-wc-cart-fees.php 5 years ago class-wc-cart-session.php 5 years ago class-wc-cart-totals.php 5 years ago class-wc-cart.php 5 years ago class-wc-checkout.php 5 years ago class-wc-cli.php 5 years ago class-wc-comments.php 5 years ago class-wc-countries.php 5 years ago class-wc-coupon.php 5 years ago class-wc-customer-download-log.php 5 years ago class-wc-customer-download.php 5 years ago class-wc-customer.php 5 years ago class-wc-data-exception.php 5 years ago class-wc-data-store.php 5 years ago class-wc-datetime.php 5 years ago class-wc-deprecated-action-hooks.php 5 years ago class-wc-deprecated-filter-hooks.php 5 years ago class-wc-discounts.php 5 years ago class-wc-download-handler.php 5 years ago class-wc-emails.php 5 years ago class-wc-embed.php 5 years ago class-wc-form-handler.php 5 years ago class-wc-frontend-scripts.php 5 years ago class-wc-geo-ip.php 5 years ago class-wc-geolite-integration.php 5 years ago class-wc-geolocation.php 5 years ago class-wc-https.php 5 years ago class-wc-install.php 4 years ago class-wc-integrations.php 5 years ago class-wc-log-levels.php 5 years ago class-wc-logger.php 5 years ago class-wc-meta-data.php 5 years ago class-wc-order-factory.php 5 years ago class-wc-order-item-coupon.php 5 years ago class-wc-order-item-fee.php 5 years ago class-wc-order-item-meta.php 5 years ago class-wc-order-item-product.php 5 years ago class-wc-order-item-shipping.php 5 years ago class-wc-order-item-tax.php 5 years ago class-wc-order-item.php 5 years ago class-wc-order-query.php 5 years ago class-wc-order-refund.php 5 years ago class-wc-order.php 5 years ago class-wc-payment-gateways.php 5 years ago class-wc-payment-tokens.php 5 years ago class-wc-post-data.php 5 years ago class-wc-post-types.php 5 years ago class-wc-privacy-background-process.php 5 years ago class-wc-privacy-erasers.php 5 years ago class-wc-privacy-exporters.php 5 years ago class-wc-privacy.php 5 years ago class-wc-product-attribute.php 5 years ago class-wc-product-download.php 5 years ago class-wc-product-external.php 5 years ago class-wc-product-factory.php 5 years ago class-wc-product-grouped.php 5 years ago class-wc-product-query.php 5 years ago class-wc-product-simple.php 5 years ago class-wc-product-variable.php 5 years ago class-wc-product-variation.php 5 years ago class-wc-query.php 5 years ago class-wc-rate-limiter.php 5 years ago class-wc-regenerate-images-request.php 5 years ago class-wc-regenerate-images.php 5 years ago class-wc-register-wp-admin-settings.php 5 years ago class-wc-rest-authentication.php 5 years ago class-wc-rest-exception.php 5 years ago class-wc-session-handler.php 5 years ago class-wc-shipping-rate.php 5 years ago class-wc-shipping-zone.php 5 years ago class-wc-shipping-zones.php 5 years ago class-wc-shipping.php 5 years ago class-wc-shortcodes.php 5 years ago class-wc-structured-data.php 5 years ago class-wc-tax.php 5 years ago class-wc-template-loader.php 5 years ago class-wc-tracker.php 5 years ago class-wc-validation.php 5 years ago class-wc-webhook.php 5 years ago class-woocommerce.php 4 years ago wc-account-functions.php 5 years ago wc-attribute-functions.php 5 years ago wc-cart-functions.php 5 years ago wc-conditional-functions.php 5 years ago wc-core-functions.php 5 years ago wc-coupon-functions.php 5 years ago wc-deprecated-functions.php 5 years ago wc-formatting-functions.php 5 years ago wc-notice-functions.php 5 years ago wc-order-functions.php 5 years ago wc-order-item-functions.php 5 years ago wc-page-functions.php 5 years ago wc-product-functions.php 5 years ago wc-rest-functions.php 5 years ago wc-stock-functions.php 5 years ago wc-template-functions.php 5 years ago wc-template-hooks.php 5 years ago wc-term-functions.php 5 years ago wc-update-functions.php 4 years ago wc-user-functions.php 5 years ago wc-webhook-functions.php 5 years ago wc-widget-functions.php 5 years ago
class-wc-ajax.php
2992 lines
1 <?php
2 /**
3 * WooCommerce WC_AJAX. AJAX Event Handlers.
4 *
5 * @class WC_AJAX
6 * @package WooCommerce/Classes
7 */
8
9 use Automattic\Jetpack\Constants;
10
11 defined( 'ABSPATH' ) || exit;
12
13 /**
14 * WC_Ajax class.
15 */
16 class WC_AJAX {
17
18 /**
19 * Hook in ajax handlers.
20 */
21 public static function init() {
22 add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
23 add_action( 'template_redirect', array( __CLASS__, 'do_wc_ajax' ), 0 );
24 self::add_ajax_events();
25 }
26
27 /**
28 * Get WC Ajax Endpoint.
29 *
30 * @param string $request Optional.
31 *
32 * @return string
33 */
34 public static function get_endpoint( $request = '' ) {
35 return esc_url_raw( apply_filters( 'woocommerce_ajax_get_endpoint', add_query_arg( 'wc-ajax', $request, remove_query_arg( array( 'remove_item', 'add-to-cart', 'added-to-cart', 'order_again', '_wpnonce' ), home_url( '/', 'relative' ) ) ), $request ) );
36 }
37
38 /**
39 * Set WC AJAX constant and headers.
40 */
41 public static function define_ajax() {
42 // phpcs:disable
43 if ( ! empty( $_GET['wc-ajax'] ) ) {
44 wc_maybe_define_constant( 'DOING_AJAX', true );
45 wc_maybe_define_constant( 'WC_DOING_AJAX', true );
46 if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
47 @ini_set( 'display_errors', 0 ); // Turn off display_errors during AJAX events to prevent malformed JSON.
48 }
49 $GLOBALS['wpdb']->hide_errors();
50 }
51 // phpcs:enable
52 }
53
54 /**
55 * Send headers for WC Ajax Requests.
56 *
57 * @since 2.5.0
58 */
59 private static function wc_ajax_headers() {
60 if ( ! headers_sent() ) {
61 send_origin_headers();
62 send_nosniff_header();
63 wc_nocache_headers();
64 header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
65 header( 'X-Robots-Tag: noindex' );
66 status_header( 200 );
67 } elseif ( Constants::is_true( 'WP_DEBUG' ) ) {
68 headers_sent( $file, $line );
69 trigger_error( "wc_ajax_headers cannot set headers - headers already sent by {$file} on line {$line}", E_USER_NOTICE ); // @codingStandardsIgnoreLine
70 }
71 }
72
73 /**
74 * Check for WC Ajax request and fire action.
75 */
76 public static function do_wc_ajax() {
77 global $wp_query;
78
79 // phpcs:disable WordPress.Security.NonceVerification.Recommended
80 if ( ! empty( $_GET['wc-ajax'] ) ) {
81 $wp_query->set( 'wc-ajax', sanitize_text_field( wp_unslash( $_GET['wc-ajax'] ) ) );
82 }
83
84 $action = $wp_query->get( 'wc-ajax' );
85
86 if ( $action ) {
87 self::wc_ajax_headers();
88 $action = sanitize_text_field( $action );
89 do_action( 'wc_ajax_' . $action );
90 wp_die();
91 }
92 // phpcs:enable
93 }
94
95 /**
96 * Hook in methods - uses WordPress ajax handlers (admin-ajax).
97 */
98 public static function add_ajax_events() {
99 $ajax_events_nopriv = array(
100 'get_refreshed_fragments',
101 'apply_coupon',
102 'remove_coupon',
103 'update_shipping_method',
104 'get_cart_totals',
105 'update_order_review',
106 'add_to_cart',
107 'remove_from_cart',
108 'checkout',
109 'get_variation',
110 'get_customer_location',
111 );
112
113 foreach ( $ajax_events_nopriv as $ajax_event ) {
114 add_action( 'wp_ajax_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );
115 add_action( 'wp_ajax_nopriv_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );
116
117 // WC AJAX can be used for frontend ajax requests.
118 add_action( 'wc_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
119 }
120
121 $ajax_events = array(
122 'feature_product',
123 'mark_order_status',
124 'get_order_details',
125 'add_attribute',
126 'add_new_attribute',
127 'remove_variation',
128 'remove_variations',
129 'save_attributes',
130 'add_variation',
131 'link_all_variations',
132 'revoke_access_to_download',
133 'grant_access_to_download',
134 'get_customer_details',
135 'add_order_item',
136 'add_order_fee',
137 'add_order_shipping',
138 'add_order_tax',
139 'add_coupon_discount',
140 'remove_order_coupon',
141 'remove_order_item',
142 'remove_order_tax',
143 'reduce_order_item_stock',
144 'increase_order_item_stock',
145 'add_order_item_meta',
146 'remove_order_item_meta',
147 'calc_line_taxes',
148 'save_order_items',
149 'load_order_items',
150 'add_order_note',
151 'delete_order_note',
152 'json_search_products',
153 'json_search_products_and_variations',
154 'json_search_downloadable_products_and_variations',
155 'json_search_customers',
156 'json_search_categories',
157 'term_ordering',
158 'product_ordering',
159 'refund_line_items',
160 'delete_refund',
161 'rated',
162 'update_api_key',
163 'load_variations',
164 'save_variations',
165 'bulk_edit_variations',
166 'tax_rates_save_changes',
167 'shipping_zones_save_changes',
168 'shipping_zone_add_method',
169 'shipping_zone_methods_save_changes',
170 'shipping_zone_methods_save_settings',
171 'shipping_classes_save_changes',
172 'toggle_gateway_enabled',
173 );
174
175 foreach ( $ajax_events as $ajax_event ) {
176 add_action( 'wp_ajax_woocommerce_' . $ajax_event, array( __CLASS__, $ajax_event ) );
177 }
178 }
179
180 /**
181 * Get a refreshed cart fragment, including the mini cart HTML.
182 */
183 public static function get_refreshed_fragments() {
184 ob_start();
185
186 woocommerce_mini_cart();
187
188 $mini_cart = ob_get_clean();
189
190 $data = array(
191 'fragments' => apply_filters(
192 'woocommerce_add_to_cart_fragments',
193 array(
194 'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>',
195 )
196 ),
197 'cart_hash' => WC()->cart->get_cart_hash(),
198 );
199
200 wp_send_json( $data );
201 }
202
203 /**
204 * AJAX apply coupon on checkout page.
205 */
206 public static function apply_coupon() {
207
208 check_ajax_referer( 'apply-coupon', 'security' );
209
210 if ( ! empty( $_POST['coupon_code'] ) ) {
211 WC()->cart->add_discount( wc_format_coupon_code( wp_unslash( $_POST['coupon_code'] ) ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
212 } else {
213 wc_add_notice( WC_Coupon::get_generic_coupon_error( WC_Coupon::E_WC_COUPON_PLEASE_ENTER ), 'error' );
214 }
215
216 wc_print_notices();
217 wp_die();
218 }
219
220 /**
221 * AJAX remove coupon on cart and checkout page.
222 */
223 public static function remove_coupon() {
224 check_ajax_referer( 'remove-coupon', 'security' );
225
226 $coupon = isset( $_POST['coupon'] ) ? wc_format_coupon_code( wp_unslash( $_POST['coupon'] ) ) : false; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
227
228 if ( empty( $coupon ) ) {
229 wc_add_notice( __( 'Sorry there was a problem removing this coupon.', 'woocommerce' ), 'error' );
230 } else {
231 WC()->cart->remove_coupon( $coupon );
232 wc_add_notice( __( 'Coupon has been removed.', 'woocommerce' ) );
233 }
234
235 wc_print_notices();
236 wp_die();
237 }
238
239 /**
240 * AJAX update shipping method on cart page.
241 */
242 public static function update_shipping_method() {
243 check_ajax_referer( 'update-shipping-method', 'security' );
244
245 wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
246
247 $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
248 $posted_shipping_methods = isset( $_POST['shipping_method'] ) ? wc_clean( wp_unslash( $_POST['shipping_method'] ) ) : array();
249
250 if ( is_array( $posted_shipping_methods ) ) {
251 foreach ( $posted_shipping_methods as $i => $value ) {
252 $chosen_shipping_methods[ $i ] = $value;
253 }
254 }
255
256 WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
257
258 self::get_cart_totals();
259 }
260
261 /**
262 * AJAX receive updated cart_totals div.
263 */
264 public static function get_cart_totals() {
265 wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
266 WC()->cart->calculate_totals();
267 woocommerce_cart_totals();
268 wp_die();
269 }
270
271 /**
272 * Session has expired.
273 */
274 private static function update_order_review_expired() {
275 wp_send_json(
276 array(
277 'fragments' => apply_filters(
278 'woocommerce_update_order_review_fragments',
279 array(
280 'form.woocommerce-checkout' => '<div class="woocommerce-error">' . __( 'Sorry, your session has expired.', 'woocommerce' ) . ' <a href="' . esc_url( wc_get_page_permalink( 'shop' ) ) . '" class="wc-backward">' . __( 'Return to shop', 'woocommerce' ) . '</a></div>',
281 )
282 ),
283 )
284 );
285 }
286
287 /**
288 * AJAX update order review on checkout.
289 */
290 public static function update_order_review() {
291 check_ajax_referer( 'update-order-review', 'security' );
292
293 wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );
294
295 if ( WC()->cart->is_empty() && ! is_customize_preview() && apply_filters( 'woocommerce_checkout_update_order_review_expired', true ) ) {
296 self::update_order_review_expired();
297 }
298
299 do_action( 'woocommerce_checkout_update_order_review', isset( $_POST['post_data'] ) ? wp_unslash( $_POST['post_data'] ) : '' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
300
301 $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
302 $posted_shipping_methods = isset( $_POST['shipping_method'] ) ? wc_clean( wp_unslash( $_POST['shipping_method'] ) ) : array();
303
304 if ( is_array( $posted_shipping_methods ) ) {
305 foreach ( $posted_shipping_methods as $i => $value ) {
306 $chosen_shipping_methods[ $i ] = $value;
307 }
308 }
309
310 WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
311 WC()->session->set( 'chosen_payment_method', empty( $_POST['payment_method'] ) ? '' : wc_clean( wp_unslash( $_POST['payment_method'] ) ) );
312 WC()->customer->set_props(
313 array(
314 'billing_country' => isset( $_POST['country'] ) ? wc_clean( wp_unslash( $_POST['country'] ) ) : null,
315 'billing_state' => isset( $_POST['state'] ) ? wc_clean( wp_unslash( $_POST['state'] ) ) : null,
316 'billing_postcode' => isset( $_POST['postcode'] ) ? wc_clean( wp_unslash( $_POST['postcode'] ) ) : null,
317 'billing_city' => isset( $_POST['city'] ) ? wc_clean( wp_unslash( $_POST['city'] ) ) : null,
318 'billing_address_1' => isset( $_POST['address'] ) ? wc_clean( wp_unslash( $_POST['address'] ) ) : null,
319 'billing_address_2' => isset( $_POST['address_2'] ) ? wc_clean( wp_unslash( $_POST['address_2'] ) ) : null,
320 )
321 );
322
323 if ( wc_ship_to_billing_address_only() ) {
324 WC()->customer->set_props(
325 array(
326 'shipping_country' => isset( $_POST['country'] ) ? wc_clean( wp_unslash( $_POST['country'] ) ) : null,
327 'shipping_state' => isset( $_POST['state'] ) ? wc_clean( wp_unslash( $_POST['state'] ) ) : null,
328 'shipping_postcode' => isset( $_POST['postcode'] ) ? wc_clean( wp_unslash( $_POST['postcode'] ) ) : null,
329 'shipping_city' => isset( $_POST['city'] ) ? wc_clean( wp_unslash( $_POST['city'] ) ) : null,
330 'shipping_address_1' => isset( $_POST['address'] ) ? wc_clean( wp_unslash( $_POST['address'] ) ) : null,
331 'shipping_address_2' => isset( $_POST['address_2'] ) ? wc_clean( wp_unslash( $_POST['address_2'] ) ) : null,
332 )
333 );
334 } else {
335 WC()->customer->set_props(
336 array(
337 'shipping_country' => isset( $_POST['s_country'] ) ? wc_clean( wp_unslash( $_POST['s_country'] ) ) : null,
338 'shipping_state' => isset( $_POST['s_state'] ) ? wc_clean( wp_unslash( $_POST['s_state'] ) ) : null,
339 'shipping_postcode' => isset( $_POST['s_postcode'] ) ? wc_clean( wp_unslash( $_POST['s_postcode'] ) ) : null,
340 'shipping_city' => isset( $_POST['s_city'] ) ? wc_clean( wp_unslash( $_POST['s_city'] ) ) : null,
341 'shipping_address_1' => isset( $_POST['s_address'] ) ? wc_clean( wp_unslash( $_POST['s_address'] ) ) : null,
342 'shipping_address_2' => isset( $_POST['s_address_2'] ) ? wc_clean( wp_unslash( $_POST['s_address_2'] ) ) : null,
343 )
344 );
345 }
346
347 if ( isset( $_POST['has_full_address'] ) && wc_string_to_bool( wc_clean( wp_unslash( $_POST['has_full_address'] ) ) ) ) {
348 WC()->customer->set_calculated_shipping( true );
349 } else {
350 WC()->customer->set_calculated_shipping( false );
351 }
352
353 WC()->customer->save();
354
355 // Calculate shipping before totals. This will ensure any shipping methods that affect things like taxes are chosen prior to final totals being calculated. Ref: #22708.
356 WC()->cart->calculate_shipping();
357 WC()->cart->calculate_totals();
358
359 // Get order review fragment.
360 ob_start();
361 woocommerce_order_review();
362 $woocommerce_order_review = ob_get_clean();
363
364 // Get checkout payment fragment.
365 ob_start();
366 woocommerce_checkout_payment();
367 $woocommerce_checkout_payment = ob_get_clean();
368
369 // Get messages if reload checkout is not true.
370 $reload_checkout = isset( WC()->session->reload_checkout ) ? true : false;
371 if ( ! $reload_checkout ) {
372 $messages = wc_print_notices( true );
373 } else {
374 $messages = '';
375 }
376
377 unset( WC()->session->refresh_totals, WC()->session->reload_checkout );
378
379 wp_send_json(
380 array(
381 'result' => empty( $messages ) ? 'success' : 'failure',
382 'messages' => $messages,
383 'reload' => $reload_checkout,
384 'fragments' => apply_filters(
385 'woocommerce_update_order_review_fragments',
386 array(
387 '.woocommerce-checkout-review-order-table' => $woocommerce_order_review,
388 '.woocommerce-checkout-payment' => $woocommerce_checkout_payment,
389 )
390 ),
391 )
392 );
393 }
394
395 /**
396 * AJAX add to cart.
397 */
398 public static function add_to_cart() {
399 ob_start();
400
401 // phpcs:disable WordPress.Security.NonceVerification.Missing
402 if ( ! isset( $_POST['product_id'] ) ) {
403 return;
404 }
405
406 $product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST['product_id'] ) );
407 $product = wc_get_product( $product_id );
408 $quantity = empty( $_POST['quantity'] ) ? 1 : wc_stock_amount( wp_unslash( $_POST['quantity'] ) );
409 $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
410 $product_status = get_post_status( $product_id );
411 $variation_id = 0;
412 $variation = array();
413
414 if ( $product && 'variation' === $product->get_type() ) {
415 $variation_id = $product_id;
416 $product_id = $product->get_parent_id();
417 $variation = $product->get_variation_attributes();
418 }
419
420 if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation ) && 'publish' === $product_status ) {
421
422 do_action( 'woocommerce_ajax_added_to_cart', $product_id );
423
424 if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
425 wc_add_to_cart_message( array( $product_id => $quantity ), true );
426 }
427
428 self::get_refreshed_fragments();
429
430 } else {
431
432 // If there was an error adding to the cart, redirect to the product page to show any errors.
433 $data = array(
434 'error' => true,
435 'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
436 );
437
438 wp_send_json( $data );
439 }
440 // phpcs:enable
441 }
442
443 /**
444 * AJAX remove from cart.
445 */
446 public static function remove_from_cart() {
447 ob_start();
448
449 // phpcs:ignore WordPress.Security.NonceVerification.Missing
450 $cart_item_key = wc_clean( isset( $_POST['cart_item_key'] ) ? wp_unslash( $_POST['cart_item_key'] ) : '' );
451
452 if ( $cart_item_key && false !== WC()->cart->remove_cart_item( $cart_item_key ) ) {
453 self::get_refreshed_fragments();
454 } else {
455 wp_send_json_error();
456 }
457 }
458
459 /**
460 * Process ajax checkout form.
461 */
462 public static function checkout() {
463 wc_maybe_define_constant( 'WOOCOMMERCE_CHECKOUT', true );
464 WC()->checkout()->process_checkout();
465 wp_die( 0 );
466 }
467
468 /**
469 * Get a matching variation based on posted attributes.
470 */
471 public static function get_variation() {
472 ob_start();
473
474 // phpcs:disable WordPress.Security.NonceVerification.Missing
475 if ( empty( $_POST['product_id'] ) ) {
476 wp_die();
477 }
478
479 $variable_product = wc_get_product( absint( $_POST['product_id'] ) );
480
481 if ( ! $variable_product ) {
482 wp_die();
483 }
484
485 $data_store = WC_Data_Store::load( 'product' );
486 $variation_id = $data_store->find_matching_product_variation( $variable_product, wp_unslash( $_POST ) );
487 $variation = $variation_id ? $variable_product->get_available_variation( $variation_id ) : false;
488 wp_send_json( $variation );
489 // phpcs:enable
490 }
491
492 /**
493 * Locate user via AJAX.
494 */
495 public static function get_customer_location() {
496 $location_hash = WC_Cache_Helper::geolocation_ajax_get_location_hash();
497 wp_send_json_success( array( 'hash' => $location_hash ) );
498 }
499
500 /**
501 * Toggle Featured status of a product from admin.
502 */
503 public static function feature_product() {
504 if ( current_user_can( 'edit_products' ) && check_admin_referer( 'woocommerce-feature-product' ) && isset( $_GET['product_id'] ) ) {
505 $product = wc_get_product( absint( $_GET['product_id'] ) );
506
507 if ( $product ) {
508 $product->set_featured( ! $product->get_featured() );
509 $product->save();
510 }
511 }
512
513 wp_safe_redirect( wp_get_referer() ? remove_query_arg( array( 'trashed', 'untrashed', 'deleted', 'ids' ), wp_get_referer() ) : admin_url( 'edit.php?post_type=product' ) );
514 exit;
515 }
516
517 /**
518 * Mark an order with a status.
519 */
520 public static function mark_order_status() {
521 if ( current_user_can( 'edit_shop_orders' ) && check_admin_referer( 'woocommerce-mark-order-status' ) && isset( $_GET['status'], $_GET['order_id'] ) ) {
522 $status = sanitize_text_field( wp_unslash( $_GET['status'] ) );
523 $order = wc_get_order( absint( wp_unslash( $_GET['order_id'] ) ) );
524
525 if ( wc_is_order_status( 'wc-' . $status ) && $order ) {
526 // Initialize payment gateways in case order has hooked status transition actions.
527 WC()->payment_gateways();
528
529 $order->update_status( $status, '', true );
530 do_action( 'woocommerce_order_edit_status', $order->get_id(), $status );
531 }
532 }
533
534 wp_safe_redirect( wp_get_referer() ? wp_get_referer() : admin_url( 'edit.php?post_type=shop_order' ) );
535 exit;
536 }
537
538 /**
539 * Get order details.
540 */
541 public static function get_order_details() {
542 check_admin_referer( 'woocommerce-preview-order', 'security' );
543
544 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_GET['order_id'] ) ) {
545 wp_die( -1 );
546 }
547
548 $order = wc_get_order( absint( $_GET['order_id'] ) ); // WPCS: sanitization ok.
549
550 if ( $order ) {
551 include_once 'admin/list-tables/class-wc-admin-list-table-orders.php';
552
553 wp_send_json_success( WC_Admin_List_Table_Orders::order_preview_get_order_details( $order ) );
554 }
555 wp_die();
556 }
557
558 /**
559 * Add an attribute row.
560 */
561 public static function add_attribute() {
562 ob_start();
563
564 check_ajax_referer( 'add-attribute', 'security' );
565
566 if ( ! current_user_can( 'edit_products' ) || ! isset( $_POST['taxonomy'], $_POST['i'] ) ) {
567 wp_die( -1 );
568 }
569
570 $i = absint( $_POST['i'] );
571 $metabox_class = array();
572 $attribute = new WC_Product_Attribute();
573
574 $attribute->set_id( wc_attribute_taxonomy_id_by_name( sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) ) ) );
575 $attribute->set_name( sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) ) );
576 $attribute->set_visible( apply_filters( 'woocommerce_attribute_default_visibility', 1 ) );
577 $attribute->set_variation( apply_filters( 'woocommerce_attribute_default_is_variation', 0 ) );
578
579 if ( $attribute->is_taxonomy() ) {
580 $metabox_class[] = 'taxonomy';
581 $metabox_class[] = $attribute->get_name();
582 }
583
584 include 'admin/meta-boxes/views/html-product-attribute.php';
585 wp_die();
586 }
587
588 /**
589 * Add a new attribute via ajax function.
590 */
591 public static function add_new_attribute() {
592 check_ajax_referer( 'add-attribute', 'security' );
593
594 if ( current_user_can( 'manage_product_terms' ) && isset( $_POST['taxonomy'], $_POST['term'] ) ) {
595 $taxonomy = esc_attr( wp_unslash( $_POST['taxonomy'] ) ); // phpcs:ignore
596 $term = wc_clean( wp_unslash( $_POST['term'] ) );
597
598 if ( taxonomy_exists( $taxonomy ) ) {
599
600 $result = wp_insert_term( $term, $taxonomy );
601
602 if ( is_wp_error( $result ) ) {
603 wp_send_json(
604 array(
605 'error' => $result->get_error_message(),
606 )
607 );
608 } else {
609 $term = get_term_by( 'id', $result['term_id'], $taxonomy );
610 wp_send_json(
611 array(
612 'term_id' => $term->term_id,
613 'name' => $term->name,
614 'slug' => $term->slug,
615 )
616 );
617 }
618 }
619 }
620 wp_die( -1 );
621 }
622
623 /**
624 * Delete variations via ajax function.
625 */
626 public static function remove_variations() {
627 check_ajax_referer( 'delete-variations', 'security' );
628
629 if ( current_user_can( 'edit_products' ) && isset( $_POST['variation_ids'] ) ) {
630 $variation_ids = array_map( 'absint', (array) wp_unslash( $_POST['variation_ids'] ) );
631
632 foreach ( $variation_ids as $variation_id ) {
633 if ( 'product_variation' === get_post_type( $variation_id ) ) {
634 $variation = wc_get_product( $variation_id );
635 $variation->delete( true );
636 }
637 }
638 }
639
640 wp_die( -1 );
641 }
642
643 /**
644 * Save attributes via ajax.
645 */
646 public static function save_attributes() {
647 check_ajax_referer( 'save-attributes', 'security' );
648
649 if ( ! current_user_can( 'edit_products' ) || ! isset( $_POST['data'], $_POST['post_id'] ) ) {
650 wp_die( -1 );
651 }
652
653 $response = array();
654
655 try {
656 parse_str( wp_unslash( $_POST['data'] ), $data ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
657
658 $attributes = WC_Meta_Box_Product_Data::prepare_attributes( $data );
659 $product_id = absint( wp_unslash( $_POST['post_id'] ) );
660 $product_type = ! empty( $_POST['product_type'] ) ? wc_clean( wp_unslash( $_POST['product_type'] ) ) : 'simple';
661 $classname = WC_Product_Factory::get_product_classname( $product_id, $product_type );
662 $product = new $classname( $product_id );
663
664 $product->set_attributes( $attributes );
665 $product->save();
666
667 ob_start();
668 $attributes = $product->get_attributes( 'edit' );
669 $i = -1;
670 if ( ! empty( $data['attribute_names'] ) ) {
671 foreach ( $data['attribute_names'] as $attribute_name ) {
672 $attribute = isset( $attributes[ sanitize_title( $attribute_name ) ] ) ? $attributes[ sanitize_title( $attribute_name ) ] : false;
673 if ( ! $attribute ) {
674 continue;
675 }
676 $i++;
677 $metabox_class = array();
678
679 if ( $attribute->is_taxonomy() ) {
680 $metabox_class[] = 'taxonomy';
681 $metabox_class[] = $attribute->get_name();
682 }
683
684 include 'admin/meta-boxes/views/html-product-attribute.php';
685 }
686 }
687
688 $response['html'] = ob_get_clean();
689 } catch ( Exception $e ) {
690 wp_send_json_error( array( 'error' => $e->getMessage() ) );
691 }
692
693 // wp_send_json_success must be outside the try block not to break phpunit tests.
694 wp_send_json_success( $response );
695 }
696
697 /**
698 * Add variation via ajax function.
699 */
700 public static function add_variation() {
701 check_ajax_referer( 'add-variation', 'security' );
702
703 if ( ! current_user_can( 'edit_products' ) || ! isset( $_POST['post_id'], $_POST['loop'] ) ) {
704 wp_die( -1 );
705 }
706
707 global $post; // Set $post global so its available, like within the admin screens.
708
709 $product_id = intval( $_POST['post_id'] );
710 $post = get_post( $product_id ); // phpcs:ignore
711 $loop = intval( $_POST['loop'] );
712 $product_object = wc_get_product_object( 'variable', $product_id ); // Forces type to variable in case product is unsaved.
713 $variation_object = wc_get_product_object( 'variation' );
714 $variation_object->set_parent_id( $product_id );
715 $variation_object->set_attributes( array_fill_keys( array_map( 'sanitize_title', array_keys( $product_object->get_variation_attributes() ) ), '' ) );
716 $variation_id = $variation_object->save();
717 $variation = get_post( $variation_id );
718 $variation_data = array_merge( get_post_custom( $variation_id ), wc_get_product_variation_attributes( $variation_id ) ); // kept for BW compatibility.
719 include 'admin/meta-boxes/views/html-variation-admin.php';
720 wp_die();
721 }
722
723 /**
724 * Link all variations via ajax function.
725 */
726 public static function link_all_variations() {
727 check_ajax_referer( 'link-variations', 'security' );
728
729 if ( ! current_user_can( 'edit_products' ) ) {
730 wp_die( -1 );
731 }
732
733 wc_maybe_define_constant( 'WC_MAX_LINKED_VARIATIONS', 50 );
734 wc_set_time_limit( 0 );
735
736 $post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;
737
738 if ( ! $post_id ) {
739 wp_die();
740 }
741
742 $product = wc_get_product( $post_id );
743 $data_store = $product->get_data_store();
744
745 if ( ! is_callable( array( $data_store, 'create_all_product_variations' ) ) ) {
746 wp_die();
747 }
748
749 echo esc_html( $data_store->create_all_product_variations( $product, Constants::get_constant( 'WC_MAX_LINKED_VARIATIONS' ) ) );
750
751 $data_store->sort_all_product_variations( $product->get_id() );
752 wp_die();
753 }
754
755 /**
756 * Delete download permissions via ajax function.
757 */
758 public static function revoke_access_to_download() {
759 check_ajax_referer( 'revoke-access', 'security' );
760
761 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['download_id'], $_POST['product_id'], $_POST['order_id'], $_POST['permission_id'] ) ) {
762 wp_die( -1 );
763 }
764 $download_id = wc_clean( wp_unslash( $_POST['download_id'] ) );
765 $product_id = intval( $_POST['product_id'] );
766 $order_id = intval( $_POST['order_id'] );
767 $permission_id = absint( $_POST['permission_id'] );
768 $data_store = WC_Data_Store::load( 'customer-download' );
769 $data_store->delete_by_id( $permission_id );
770
771 do_action( 'woocommerce_ajax_revoke_access_to_product_download', $download_id, $product_id, $order_id, $permission_id );
772
773 wp_die();
774 }
775
776 /**
777 * Grant download permissions via ajax function.
778 */
779 public static function grant_access_to_download() {
780
781 check_ajax_referer( 'grant-access', 'security' );
782
783 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['loop'], $_POST['order_id'], $_POST['product_ids'] ) ) {
784 wp_die( -1 );
785 }
786
787 global $wpdb;
788
789 $wpdb->hide_errors();
790
791 $order_id = intval( $_POST['order_id'] );
792 $product_ids = array_filter( array_map( 'absint', (array) wp_unslash( $_POST['product_ids'] ) ) );
793 $loop = intval( $_POST['loop'] );
794 $file_counter = 0;
795 $order = wc_get_order( $order_id );
796
797 foreach ( $product_ids as $product_id ) {
798 $product = wc_get_product( $product_id );
799 $files = $product->get_downloads();
800
801 if ( ! $order->get_billing_email() ) {
802 wp_die();
803 }
804
805 if ( ! empty( $files ) ) {
806 foreach ( $files as $download_id => $file ) {
807 $inserted_id = wc_downloadable_file_permission( $download_id, $product_id, $order );
808 if ( $inserted_id ) {
809 $download = new WC_Customer_Download( $inserted_id );
810 $loop ++;
811 $file_counter ++;
812
813 if ( $file->get_name() ) {
814 $file_count = $file->get_name();
815 } else {
816 /* translators: %d file count */
817 $file_count = sprintf( __( 'File %d', 'woocommerce' ), $file_counter );
818 }
819 include 'admin/meta-boxes/views/html-order-download-permission.php';
820 }
821 }
822 }
823 }
824 wp_die();
825 }
826
827 /**
828 * Get customer details via ajax.
829 */
830 public static function get_customer_details() {
831 check_ajax_referer( 'get-customer-details', 'security' );
832
833 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['user_id'] ) ) {
834 wp_die( -1 );
835 }
836
837 $user_id = absint( $_POST['user_id'] );
838 $customer = new WC_Customer( $user_id );
839
840 if ( has_filter( 'woocommerce_found_customer_details' ) ) {
841 wc_deprecated_function( 'The woocommerce_found_customer_details filter', '3.0', 'woocommerce_ajax_get_customer_details' );
842 }
843
844 $data = $customer->get_data();
845 $data['date_created'] = $data['date_created'] ? $data['date_created']->getTimestamp() : null;
846 $data['date_modified'] = $data['date_modified'] ? $data['date_modified']->getTimestamp() : null;
847
848 $customer_data = apply_filters( 'woocommerce_ajax_get_customer_details', $data, $customer, $user_id );
849 wp_send_json( $customer_data );
850 }
851
852 /**
853 * Add order item via ajax. Used on the edit order screen in WP Admin.
854 *
855 * @throws Exception If order is invalid.
856 */
857 public static function add_order_item() {
858 check_ajax_referer( 'order-item', 'security' );
859
860 if ( ! current_user_can( 'edit_shop_orders' ) ) {
861 wp_die( -1 );
862 }
863
864 $response = array();
865
866 try {
867 if ( ! isset( $_POST['order_id'] ) ) {
868 throw new Exception( __( 'Invalid order', 'woocommerce' ) );
869 }
870
871 $order_id = absint( wp_unslash( $_POST['order_id'] ) ); // WPCS: input var ok.
872 $order = wc_get_order( $order_id );
873
874 if ( ! $order ) {
875 throw new Exception( __( 'Invalid order', 'woocommerce' ) );
876 }
877
878 // If we passed through items it means we need to save first before adding a new one.
879 $items = ( ! empty( $_POST['items'] ) ) ? wp_unslash( $_POST['items'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
880
881 if ( ! empty( $items ) ) {
882 $save_items = array();
883 parse_str( $items, $save_items );
884 wc_save_order_items( $order->get_id(), $save_items );
885 }
886
887 $items_to_add = isset( $_POST['data'] ) ? array_filter( wp_unslash( (array) $_POST['data'] ) ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
888
889 // Add items to order.
890 $order_notes = array();
891
892 foreach ( $items_to_add as $item ) {
893 if ( ! isset( $item['id'], $item['qty'] ) || empty( $item['id'] ) ) {
894 continue;
895 }
896 $product_id = absint( $item['id'] );
897 $qty = wc_stock_amount( $item['qty'] );
898 $product = wc_get_product( $product_id );
899
900 if ( ! $product ) {
901 throw new Exception( __( 'Invalid product ID', 'woocommerce' ) . ' ' . $product_id );
902 }
903 if ( 'variable' === $product->get_type() ) {
904 /* translators: %s product name */
905 throw new Exception( sprintf( __( '%s is a variable product parent and cannot be added.', 'woocommerce' ), $product->get_name() ) );
906 }
907 $validation_error = new WP_Error();
908 $validation_error = apply_filters( 'woocommerce_ajax_add_order_item_validation', $validation_error, $product, $order, $qty );
909
910 if ( $validation_error->get_error_code() ) {
911 throw new Exception( '<strong>' . __( 'Error:', 'woocommerce' ) . '</strong> ' . $validation_error->get_error_message() );
912 }
913 $item_id = $order->add_product( $product, $qty );
914 $item = apply_filters( 'woocommerce_ajax_order_item', $order->get_item( $item_id ), $item_id, $order, $product );
915 $added_items[ $item_id ] = $item;
916 $order_notes[ $item_id ] = $product->get_formatted_name();
917
918 if ( $product->managing_stock() ) {
919 $new_stock = wc_update_product_stock( $product, $qty, 'decrease' );
920 $order_notes[ $item_id ] = $product->get_formatted_name() . ' &ndash; ' . ( $new_stock + $qty ) . '&rarr;' . $new_stock;
921 $item->add_meta_data( '_reduced_stock', $qty, true );
922 $item->save();
923 }
924
925 do_action( 'woocommerce_ajax_add_order_item_meta', $item_id, $item, $order );
926 }
927
928 /* translators: %s item name. */
929 $order->add_order_note( sprintf( __( 'Added line items: %s', 'woocommerce' ), implode( ', ', $order_notes ) ), false, true );
930
931 do_action( 'woocommerce_ajax_order_items_added', $added_items, $order );
932
933 $data = get_post_meta( $order_id );
934
935 // Get HTML to return.
936 ob_start();
937 include 'admin/meta-boxes/views/html-order-items.php';
938 $items_html = ob_get_clean();
939
940 ob_start();
941 $notes = wc_get_order_notes( array( 'order_id' => $order_id ) );
942 include 'admin/meta-boxes/views/html-order-notes.php';
943 $notes_html = ob_get_clean();
944
945 wp_send_json_success(
946 array(
947 'html' => $items_html,
948 'notes_html' => $notes_html,
949 )
950 );
951 } catch ( Exception $e ) {
952 wp_send_json_error( array( 'error' => $e->getMessage() ) );
953 }
954
955 // wp_send_json_success must be outside the try block not to break phpunit tests.
956 wp_send_json_success( $response );
957 }
958
959 /**
960 * Add order fee via ajax.
961 *
962 * @throws Exception If order is invalid.
963 */
964 public static function add_order_fee() {
965 check_ajax_referer( 'order-item', 'security' );
966
967 if ( ! current_user_can( 'edit_shop_orders' ) ) {
968 wp_die( -1 );
969 }
970
971 $response = array();
972
973 try {
974 $order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
975 $order = wc_get_order( $order_id );
976
977 if ( ! $order ) {
978 throw new Exception( __( 'Invalid order', 'woocommerce' ) );
979 }
980
981 $amount = isset( $_POST['amount'] ) ? wc_clean( wp_unslash( $_POST['amount'] ) ) : 0;
982
983 $calculate_tax_args = array(
984 'country' => isset( $_POST['country'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['country'] ) ) ) : '',
985 'state' => isset( $_POST['state'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['state'] ) ) ) : '',
986 'postcode' => isset( $_POST['postcode'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['postcode'] ) ) ) : '',
987 'city' => isset( $_POST['city'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['city'] ) ) ) : '',
988 );
989
990 if ( strstr( $amount, '%' ) ) {
991 $formatted_amount = $amount;
992 $percent = floatval( trim( $amount, '%' ) );
993 $amount = $order->get_total() * ( $percent / 100 );
994 } else {
995 $amount = floatval( $amount );
996 $formatted_amount = wc_price( $amount, array( 'currency' => $order->get_currency() ) );
997 }
998
999 $fee = new WC_Order_Item_Fee();
1000 $fee->set_amount( $amount );
1001 $fee->set_total( $amount );
1002 /* translators: %s fee amount */
1003 $fee->set_name( sprintf( __( '%s fee', 'woocommerce' ), wc_clean( $formatted_amount ) ) );
1004
1005 $order->add_item( $fee );
1006 $order->calculate_taxes( $calculate_tax_args );
1007 $order->calculate_totals( false );
1008 $order->save();
1009
1010 ob_start();
1011 include 'admin/meta-boxes/views/html-order-items.php';
1012 $response['html'] = ob_get_clean();
1013 } catch ( Exception $e ) {
1014 wp_send_json_error( array( 'error' => $e->getMessage() ) );
1015 }
1016
1017 // wp_send_json_success must be outside the try block not to break phpunit tests.
1018 wp_send_json_success( $response );
1019 }
1020
1021 /**
1022 * Add order shipping cost via ajax.
1023 *
1024 * @throws Exception If order is invalid.
1025 */
1026 public static function add_order_shipping() {
1027 check_ajax_referer( 'order-item', 'security' );
1028
1029 if ( ! current_user_can( 'edit_shop_orders' ) ) {
1030 wp_die( -1 );
1031 }
1032
1033 $response = array();
1034
1035 try {
1036 $order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
1037 $order = wc_get_order( $order_id );
1038
1039 if ( ! $order ) {
1040 throw new Exception( __( 'Invalid order', 'woocommerce' ) );
1041 }
1042
1043 $order_taxes = $order->get_taxes();
1044 $shipping_methods = WC()->shipping() ? WC()->shipping()->load_shipping_methods() : array();
1045
1046 // Add new shipping.
1047 $item = new WC_Order_Item_Shipping();
1048 $item->set_shipping_rate( new WC_Shipping_Rate() );
1049 $item->set_order_id( $order_id );
1050 $item_id = $item->save();
1051
1052 ob_start();
1053 include 'admin/meta-boxes/views/html-order-shipping.php';
1054 $response['html'] = ob_get_clean();
1055 } catch ( Exception $e ) {
1056 wp_send_json_error( array( 'error' => $e->getMessage() ) );
1057 }
1058
1059 // wp_send_json_success must be outside the try block not to break phpunit tests.
1060 wp_send_json_success( $response );
1061 }
1062
1063 /**
1064 * Add order tax column via ajax.
1065 *
1066 * @throws Exception If order or tax rate is invalid.
1067 */
1068 public static function add_order_tax() {
1069 check_ajax_referer( 'order-item', 'security' );
1070
1071 if ( ! current_user_can( 'edit_shop_orders' ) ) {
1072 wp_die( -1 );
1073 }
1074
1075 $response = array();
1076
1077 try {
1078 $order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
1079 $order = wc_get_order( $order_id );
1080
1081 if ( ! $order ) {
1082 throw new Exception( __( 'Invalid order', 'woocommerce' ) );
1083 }
1084
1085 $rate_id = isset( $_POST['rate_id'] ) ? absint( $_POST['rate_id'] ) : '';
1086
1087 if ( ! $rate_id ) {
1088 throw new Exception( __( 'Invalid rate', 'woocommerce' ) );
1089 }
1090
1091 $data = get_post_meta( $order_id );
1092
1093 // Add new tax.
1094 $item = new WC_Order_Item_Tax();
1095 $item->set_rate( $rate_id );
1096 $item->set_order_id( $order_id );
1097 $item->save();
1098
1099 ob_start();
1100 include 'admin/meta-boxes/views/html-order-items.php';
1101 $response['html'] = ob_get_clean();
1102 } catch ( Exception $e ) {
1103 wp_send_json_error( array( 'error' => $e->getMessage() ) );
1104 }
1105
1106 // wp_send_json_success must be outside the try block not to break phpunit tests.
1107 wp_send_json_success( $response );
1108 }
1109
1110 /**
1111 * Add order discount via ajax.
1112 *
1113 * @throws Exception If order or coupon is invalid.
1114 */
1115 public static function add_coupon_discount() {
1116 check_ajax_referer( 'order-item', 'security' );
1117
1118 if ( ! current_user_can( 'edit_shop_orders' ) ) {
1119 wp_die( -1 );
1120 }
1121
1122 $response = array();
1123
1124 try {
1125 $order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
1126 $order = wc_get_order( $order_id );
1127 $calculate_tax_args = array(
1128 'country' => isset( $_POST['country'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['country'] ) ) ) : '',
1129 'state' => isset( $_POST['state'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['state'] ) ) ) : '',
1130 'postcode' => isset( $_POST['postcode'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['postcode'] ) ) ) : '',
1131 'city' => isset( $_POST['city'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['city'] ) ) ) : '',
1132 );
1133
1134 if ( ! $order ) {
1135 throw new Exception( __( 'Invalid order', 'woocommerce' ) );
1136 }
1137
1138 if ( empty( $_POST['coupon'] ) ) {
1139 throw new Exception( __( 'Invalid coupon', 'woocommerce' ) );
1140 }
1141
1142 // Add user ID and/or email so validation for coupon limits works.
1143 $user_id_arg = isset( $_POST['user_id'] ) ? absint( $_POST['user_id'] ) : 0;
1144 $user_email_arg = isset( $_POST['user_email'] ) ? sanitize_email( wp_unslash( $_POST['user_email'] ) ) : '';
1145
1146 if ( $user_id_arg ) {
1147 $order->set_customer_id( $user_id_arg );
1148 }
1149 if ( $user_email_arg ) {
1150 $order->set_billing_email( $user_email_arg );
1151 }
1152
1153 $result = $order->apply_coupon( wc_format_coupon_code( wp_unslash( $_POST['coupon'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1154
1155 if ( is_wp_error( $result ) ) {
1156 throw new Exception( html_entity_decode( wp_strip_all_tags( $result->get_error_message() ) ) );
1157 }
1158
1159 $order->calculate_taxes( $calculate_tax_args );
1160 $order->calculate_totals( false );
1161
1162 ob_start();
1163 include 'admin/meta-boxes/views/html-order-items.php';
1164 $response['html'] = ob_get_clean();
1165 } catch ( Exception $e ) {
1166 wp_send_json_error( array( 'error' => $e->getMessage() ) );
1167 }
1168
1169 // wp_send_json_success must be outside the try block not to break phpunit tests.
1170 wp_send_json_success( $response );
1171 }
1172
1173 /**
1174 * Remove coupon from an order via ajax.
1175 *
1176 * @throws Exception If order or coupon is invalid.
1177 */
1178 public static function remove_order_coupon() {
1179 check_ajax_referer( 'order-item', 'security' );
1180
1181 if ( ! current_user_can( 'edit_shop_orders' ) ) {
1182 wp_die( -1 );
1183 }
1184
1185 $response = array();
1186
1187 try {
1188 $order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
1189 $order = wc_get_order( $order_id );
1190 $calculate_tax_args = array(
1191 'country' => isset( $_POST['country'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['country'] ) ) ) : '',
1192 'state' => isset( $_POST['state'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['state'] ) ) ) : '',
1193 'postcode' => isset( $_POST['postcode'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['postcode'] ) ) ) : '',
1194 'city' => isset( $_POST['city'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['city'] ) ) ) : '',
1195 );
1196
1197 if ( ! $order ) {
1198 throw new Exception( __( 'Invalid order', 'woocommerce' ) );
1199 }
1200
1201 if ( empty( $_POST['coupon'] ) ) {
1202 throw new Exception( __( 'Invalid coupon', 'woocommerce' ) );
1203 }
1204
1205 $order->remove_coupon( wc_format_coupon_code( wp_unslash( $_POST['coupon'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1206 $order->calculate_taxes( $calculate_tax_args );
1207 $order->calculate_totals( false );
1208
1209 ob_start();
1210 include 'admin/meta-boxes/views/html-order-items.php';
1211 $response['html'] = ob_get_clean();
1212 } catch ( Exception $e ) {
1213 wp_send_json_error( array( 'error' => $e->getMessage() ) );
1214 }
1215
1216 // wp_send_json_success must be outside the try block not to break phpunit tests.
1217 wp_send_json_success( $response );
1218 }
1219
1220 /**
1221 * Remove an order item.
1222 *
1223 * @throws Exception If order is invalid.
1224 */
1225 public static function remove_order_item() {
1226 check_ajax_referer( 'order-item', 'security' );
1227
1228 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['order_id'], $_POST['order_item_ids'] ) ) {
1229 wp_die( -1 );
1230 }
1231
1232 $response = array();
1233
1234 try {
1235 $order_id = absint( $_POST['order_id'] );
1236 $order = wc_get_order( $order_id );
1237
1238 if ( ! $order ) {
1239 throw new Exception( __( 'Invalid order', 'woocommerce' ) );
1240 }
1241
1242 if ( ! isset( $_POST['order_item_ids'] ) ) {
1243 throw new Exception( __( 'Invalid items', 'woocommerce' ) );
1244 }
1245
1246 $order_item_ids = wp_unslash( $_POST['order_item_ids'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1247 $items = ( ! empty( $_POST['items'] ) ) ? wp_unslash( $_POST['items'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1248 $calculate_tax_args = array(
1249 'country' => isset( $_POST['country'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['country'] ) ) ) : '',
1250 'state' => isset( $_POST['state'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['state'] ) ) ) : '',
1251 'postcode' => isset( $_POST['postcode'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['postcode'] ) ) ) : '',
1252 'city' => isset( $_POST['city'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['city'] ) ) ) : '',
1253 );
1254
1255 if ( ! is_array( $order_item_ids ) && is_numeric( $order_item_ids ) ) {
1256 $order_item_ids = array( $order_item_ids );
1257 }
1258
1259 // If we passed through items it means we need to save first before deleting.
1260 if ( ! empty( $items ) ) {
1261 $save_items = array();
1262 parse_str( $items, $save_items );
1263 wc_save_order_items( $order->get_id(), $save_items );
1264 }
1265
1266 if ( ! empty( $order_item_ids ) ) {
1267 $order_notes = array();
1268
1269 foreach ( $order_item_ids as $item_id ) {
1270 $item_id = absint( $item_id );
1271 $item = $order->get_item( $item_id );
1272
1273 // Before deleting the item, adjust any stock values already reduced.
1274 if ( $item->is_type( 'line_item' ) ) {
1275 $changed_stock = wc_maybe_adjust_line_item_product_stock( $item, 0 );
1276
1277 if ( $changed_stock && ! is_wp_error( $changed_stock ) ) {
1278 /* translators: %1$s: item name %2$s: stock change */
1279 $order->add_order_note( sprintf( __( 'Deleted %1$s and adjusted stock (%2$s)', 'woocommerce' ), $item->get_name(), $changed_stock['from'] . '&rarr;' . $changed_stock['to'] ), false, true );
1280 } else {
1281 /* translators: %s item name. */
1282 $order->add_order_note( sprintf( __( 'Deleted %s', 'woocommerce' ), $item->get_name() ), false, true );
1283 }
1284 }
1285
1286 wc_delete_order_item( $item_id );
1287 }
1288 }
1289
1290 $order = wc_get_order( $order_id );
1291 $order->calculate_taxes( $calculate_tax_args );
1292 $order->calculate_totals( false );
1293
1294 // Get HTML to return.
1295 ob_start();
1296 include 'admin/meta-boxes/views/html-order-items.php';
1297 $items_html = ob_get_clean();
1298
1299 ob_start();
1300 $notes = wc_get_order_notes( array( 'order_id' => $order_id ) );
1301 include 'admin/meta-boxes/views/html-order-notes.php';
1302 $notes_html = ob_get_clean();
1303
1304 wp_send_json_success(
1305 array(
1306 'html' => $items_html,
1307 'notes_html' => $notes_html,
1308 )
1309 );
1310 } catch ( Exception $e ) {
1311 wp_send_json_error( array( 'error' => $e->getMessage() ) );
1312 }
1313
1314 // wp_send_json_success must be outside the try block not to break phpunit tests.
1315 wp_send_json_success( $response );
1316 }
1317
1318 /**
1319 * Remove an order tax.
1320 *
1321 * @throws Exception If there is an error whilst deleting the rate.
1322 */
1323 public static function remove_order_tax() {
1324 check_ajax_referer( 'order-item', 'security' );
1325
1326 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['order_id'], $_POST['rate_id'] ) ) {
1327 wp_die( -1 );
1328 }
1329
1330 $response = array();
1331
1332 try {
1333 $order_id = absint( $_POST['order_id'] );
1334 $rate_id = absint( $_POST['rate_id'] );
1335
1336 $order = wc_get_order( $order_id );
1337 if ( ! $order->is_editable() ) {
1338 throw new Exception( __( 'Order not editable', 'woocommerce' ) );
1339 }
1340
1341 wc_delete_order_item( $rate_id );
1342
1343 // Need to load order again after deleting to have latest items before calculating.
1344 $order = wc_get_order( $order_id );
1345 $order->calculate_totals( false );
1346
1347 ob_start();
1348 include 'admin/meta-boxes/views/html-order-items.php';
1349 $response['html'] = ob_get_clean();
1350 } catch ( Exception $e ) {
1351 wp_send_json_error( array( 'error' => $e->getMessage() ) );
1352 }
1353
1354 // wp_send_json_success must be outside the try block not to break phpunit tests.
1355 wp_send_json_success( $response );
1356 }
1357
1358 /**
1359 * Calc line tax.
1360 */
1361 public static function calc_line_taxes() {
1362 check_ajax_referer( 'calc-totals', 'security' );
1363
1364 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['order_id'], $_POST['items'] ) ) {
1365 wp_die( -1 );
1366 }
1367
1368 $order_id = absint( $_POST['order_id'] );
1369 $calculate_tax_args = array(
1370 'country' => isset( $_POST['country'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['country'] ) ) ) : '',
1371 'state' => isset( $_POST['state'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['state'] ) ) ) : '',
1372 'postcode' => isset( $_POST['postcode'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['postcode'] ) ) ) : '',
1373 'city' => isset( $_POST['city'] ) ? wc_strtoupper( wc_clean( wp_unslash( $_POST['city'] ) ) ) : '',
1374 );
1375
1376 // Parse the jQuery serialized items.
1377 $items = array();
1378 parse_str( wp_unslash( $_POST['items'] ), $items ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1379
1380 // Save order items first.
1381 wc_save_order_items( $order_id, $items );
1382
1383 // Grab the order and recalculate taxes.
1384 $order = wc_get_order( $order_id );
1385 $order->calculate_taxes( $calculate_tax_args );
1386 $order->calculate_totals( false );
1387 include 'admin/meta-boxes/views/html-order-items.php';
1388 wp_die();
1389 }
1390
1391 /**
1392 * Save order items via ajax.
1393 */
1394 public static function save_order_items() {
1395 check_ajax_referer( 'order-item', 'security' );
1396
1397 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['order_id'], $_POST['items'] ) ) {
1398 wp_die( -1 );
1399 }
1400
1401 if ( isset( $_POST['order_id'], $_POST['items'] ) ) {
1402 $order_id = absint( $_POST['order_id'] );
1403
1404 // Parse the jQuery serialized items.
1405 $items = array();
1406 parse_str( wp_unslash( $_POST['items'] ), $items ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1407
1408 // Save order items.
1409 wc_save_order_items( $order_id, $items );
1410
1411 // Return HTML items.
1412 $order = wc_get_order( $order_id );
1413
1414 // Get HTML to return.
1415 ob_start();
1416 include 'admin/meta-boxes/views/html-order-items.php';
1417 $items_html = ob_get_clean();
1418
1419 ob_start();
1420 $notes = wc_get_order_notes( array( 'order_id' => $order_id ) );
1421 include 'admin/meta-boxes/views/html-order-notes.php';
1422 $notes_html = ob_get_clean();
1423
1424 wp_send_json_success(
1425 array(
1426 'html' => $items_html,
1427 'notes_html' => $notes_html,
1428 )
1429 );
1430 }
1431 wp_die();
1432 }
1433
1434 /**
1435 * Load order items via ajax.
1436 */
1437 public static function load_order_items() {
1438 check_ajax_referer( 'order-item', 'security' );
1439
1440 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['order_id'] ) ) {
1441 wp_die( -1 );
1442 }
1443
1444 // Return HTML items.
1445 $order_id = absint( $_POST['order_id'] );
1446 $order = wc_get_order( $order_id );
1447 include 'admin/meta-boxes/views/html-order-items.php';
1448 wp_die();
1449 }
1450
1451 /**
1452 * Add order note via ajax.
1453 */
1454 public static function add_order_note() {
1455 check_ajax_referer( 'add-order-note', 'security' );
1456
1457 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['post_id'], $_POST['note'], $_POST['note_type'] ) ) {
1458 wp_die( -1 );
1459 }
1460
1461 $post_id = absint( $_POST['post_id'] );
1462 $note = wp_kses_post( trim( wp_unslash( $_POST['note'] ) ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1463 $note_type = wc_clean( wp_unslash( $_POST['note_type'] ) );
1464
1465 $is_customer_note = ( 'customer' === $note_type ) ? 1 : 0;
1466
1467 if ( $post_id > 0 ) {
1468 $order = wc_get_order( $post_id );
1469 $comment_id = $order->add_order_note( $note, $is_customer_note, true );
1470 $note = wc_get_order_note( $comment_id );
1471
1472 $note_classes = array( 'note' );
1473 $note_classes[] = $is_customer_note ? 'customer-note' : '';
1474 $note_classes = apply_filters( 'woocommerce_order_note_class', array_filter( $note_classes ), $note );
1475 ?>
1476 <li rel="<?php echo absint( $note->id ); ?>" class="<?php echo esc_attr( implode( ' ', $note_classes ) ); ?>">
1477 <div class="note_content">
1478 <?php echo wp_kses_post( wpautop( wptexturize( make_clickable( $note->content ) ) ) ); ?>
1479 </div>
1480 <p class="meta">
1481 <abbr class="exact-date" title="<?php echo esc_attr( $note->date_created->date( 'y-m-d h:i:s' ) ); ?>">
1482 <?php
1483 /* translators: $1: Date created, $2 Time created */
1484 printf( esc_html__( 'added on %1$s at %2$s', 'woocommerce' ), esc_html( $note->date_created->date_i18n( wc_date_format() ) ), esc_html( $note->date_created->date_i18n( wc_time_format() ) ) );
1485 ?>
1486 </abbr>
1487 <?php
1488 if ( 'system' !== $note->added_by ) :
1489 /* translators: %s: note author */
1490 printf( ' ' . esc_html__( 'by %s', 'woocommerce' ), esc_html( $note->added_by ) );
1491 endif;
1492 ?>
1493 <a href="#" class="delete_note" role="button"><?php esc_html_e( 'Delete note', 'woocommerce' ); ?></a>
1494 </p>
1495 </li>
1496 <?php
1497 }
1498 wp_die();
1499 }
1500
1501 /**
1502 * Delete order note via ajax.
1503 */
1504 public static function delete_order_note() {
1505 check_ajax_referer( 'delete-order-note', 'security' );
1506
1507 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['note_id'] ) ) {
1508 wp_die( -1 );
1509 }
1510
1511 $note_id = (int) $_POST['note_id'];
1512
1513 if ( $note_id > 0 ) {
1514 wc_delete_order_note( $note_id );
1515 }
1516 wp_die();
1517 }
1518
1519 /**
1520 * Search for products and echo json.
1521 *
1522 * @param string $term (default: '') Term to search for.
1523 * @param bool $include_variations in search or not.
1524 */
1525 public static function json_search_products( $term = '', $include_variations = false ) {
1526 check_ajax_referer( 'search-products', 'security' );
1527
1528 if ( empty( $term ) && isset( $_GET['term'] ) ) {
1529 $term = (string) wc_clean( wp_unslash( $_GET['term'] ) );
1530 }
1531
1532 if ( empty( $term ) ) {
1533 wp_die();
1534 }
1535
1536 if ( ! empty( $_GET['limit'] ) ) {
1537 $limit = absint( $_GET['limit'] );
1538 } else {
1539 $limit = absint( apply_filters( 'woocommerce_json_search_limit', 30 ) );
1540 }
1541
1542 $include_ids = ! empty( $_GET['include'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['include'] ) ) : array();
1543 $exclude_ids = ! empty( $_GET['exclude'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['exclude'] ) ) : array();
1544
1545 $exclude_types = array();
1546 if ( ! empty( $_GET['exclude_type'] ) ) {
1547 // Support both comma-delimited and array format inputs.
1548 $exclude_types = wp_unslash( $_GET['exclude_type'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1549 if ( ! is_array( $exclude_types ) ) {
1550 $exclude_types = explode( ',', $exclude_types );
1551 }
1552
1553 // Sanitize the excluded types against valid product types.
1554 foreach ( $exclude_types as &$exclude_type ) {
1555 $exclude_type = strtolower( trim( $exclude_type ) );
1556 }
1557 $exclude_types = array_intersect(
1558 array_merge( array( 'variation' ), array_keys( wc_get_product_types() ) ),
1559 $exclude_types
1560 );
1561 }
1562
1563 $data_store = WC_Data_Store::load( 'product' );
1564 $ids = $data_store->search_products( $term, '', (bool) $include_variations, false, $limit, $include_ids, $exclude_ids );
1565
1566 $product_objects = array_filter( array_map( 'wc_get_product', $ids ), 'wc_products_array_filter_readable' );
1567 $products = array();
1568
1569 foreach ( $product_objects as $product_object ) {
1570 $formatted_name = $product_object->get_formatted_name();
1571 $managing_stock = $product_object->managing_stock();
1572
1573 if ( in_array( $product_object->get_type(), $exclude_types, true ) ) {
1574 continue;
1575 }
1576
1577 if ( $managing_stock && ! empty( $_GET['display_stock'] ) ) {
1578 $stock_amount = $product_object->get_stock_quantity();
1579 /* Translators: %d stock amount */
1580 $formatted_name .= ' &ndash; ' . sprintf( __( 'Stock: %d', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product_object ) );
1581 }
1582
1583 $products[ $product_object->get_id() ] = rawurldecode( $formatted_name );
1584 }
1585
1586 wp_send_json( apply_filters( 'woocommerce_json_search_found_products', $products ) );
1587 }
1588
1589 /**
1590 * Search for product variations and return json.
1591 *
1592 * @see WC_AJAX::json_search_products()
1593 */
1594 public static function json_search_products_and_variations() {
1595 self::json_search_products( '', true );
1596 }
1597
1598 /**
1599 * Search for downloadable product variations and return json.
1600 *
1601 * @see WC_AJAX::json_search_products()
1602 */
1603 public static function json_search_downloadable_products_and_variations() {
1604 check_ajax_referer( 'search-products', 'security' );
1605
1606 if ( ! empty( $_GET['limit'] ) ) {
1607 $limit = absint( $_GET['limit'] );
1608 } else {
1609 $limit = absint( apply_filters( 'woocommerce_json_search_limit', 30 ) );
1610 }
1611
1612 $include_ids = ! empty( $_GET['include'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['include'] ) ) : array();
1613 $exclude_ids = ! empty( $_GET['exclude'] ) ? array_map( 'absint', (array) wp_unslash( $_GET['exclude'] ) ) : array();
1614
1615 $term = isset( $_GET['term'] ) ? (string) wc_clean( wp_unslash( $_GET['term'] ) ) : '';
1616 $data_store = WC_Data_Store::load( 'product' );
1617 $ids = $data_store->search_products( $term, 'downloadable', true, false, $limit );
1618
1619 $product_objects = array_filter( array_map( 'wc_get_product', $ids ), 'wc_products_array_filter_readable' );
1620 $products = array();
1621
1622 foreach ( $product_objects as $product_object ) {
1623 $products[ $product_object->get_id() ] = rawurldecode( $product_object->get_formatted_name() );
1624 }
1625
1626 wp_send_json( $products );
1627 }
1628
1629 /**
1630 * Search for customers and return json.
1631 */
1632 public static function json_search_customers() {
1633 ob_start();
1634
1635 check_ajax_referer( 'search-customers', 'security' );
1636
1637 if ( ! current_user_can( 'edit_shop_orders' ) ) {
1638 wp_die( -1 );
1639 }
1640
1641 $term = isset( $_GET['term'] ) ? (string) wc_clean( wp_unslash( $_GET['term'] ) ) : '';
1642 $limit = 0;
1643
1644 if ( empty( $term ) ) {
1645 wp_die();
1646 }
1647
1648 $ids = array();
1649 // Search by ID.
1650 if ( is_numeric( $term ) ) {
1651 $customer = new WC_Customer( intval( $term ) );
1652
1653 // Customer does not exists.
1654 if ( 0 !== $customer->get_id() ) {
1655 $ids = array( $customer->get_id() );
1656 }
1657 }
1658
1659 // Usernames can be numeric so we first check that no users was found by ID before searching for numeric username, this prevents performance issues with ID lookups.
1660 if ( empty( $ids ) ) {
1661 $data_store = WC_Data_Store::load( 'customer' );
1662
1663 // If search is smaller than 3 characters, limit result set to avoid
1664 // too many rows being returned.
1665 if ( 3 > strlen( $term ) ) {
1666 $limit = 20;
1667 }
1668 $ids = $data_store->search_customers( $term, $limit );
1669 }
1670
1671 $found_customers = array();
1672
1673 if ( ! empty( $_GET['exclude'] ) ) {
1674 $ids = array_diff( $ids, array_map( 'absint', (array) wp_unslash( $_GET['exclude'] ) ) );
1675 }
1676
1677 foreach ( $ids as $id ) {
1678 $customer = new WC_Customer( $id );
1679 /* translators: 1: user display name 2: user ID 3: user email */
1680 $found_customers[ $id ] = sprintf(
1681 /* translators: $1: customer name, $2 customer id, $3: customer email */
1682 esc_html__( '%1$s (#%2$s &ndash; %3$s)', 'woocommerce' ),
1683 $customer->get_first_name() . ' ' . $customer->get_last_name(),
1684 $customer->get_id(),
1685 $customer->get_email()
1686 );
1687 }
1688
1689 wp_send_json( apply_filters( 'woocommerce_json_search_found_customers', $found_customers ) );
1690 }
1691
1692 /**
1693 * Search for categories and return json.
1694 */
1695 public static function json_search_categories() {
1696 ob_start();
1697
1698 check_ajax_referer( 'search-categories', 'security' );
1699
1700 if ( ! current_user_can( 'edit_products' ) ) {
1701 wp_die( -1 );
1702 }
1703
1704 $search_text = isset( $_GET['term'] ) ? wc_clean( wp_unslash( $_GET['term'] ) ) : '';
1705
1706 if ( ! $search_text ) {
1707 wp_die();
1708 }
1709
1710 $found_categories = array();
1711 $args = array(
1712 'taxonomy' => array( 'product_cat' ),
1713 'orderby' => 'id',
1714 'order' => 'ASC',
1715 'hide_empty' => true,
1716 'fields' => 'all',
1717 'name__like' => $search_text,
1718 );
1719
1720 $terms = get_terms( $args );
1721
1722 if ( $terms ) {
1723 foreach ( $terms as $term ) {
1724 $term->formatted_name = '';
1725
1726 if ( $term->parent ) {
1727 $ancestors = array_reverse( get_ancestors( $term->term_id, 'product_cat' ) );
1728 foreach ( $ancestors as $ancestor ) {
1729 $ancestor_term = get_term( $ancestor, 'product_cat' );
1730 if ( $ancestor_term ) {
1731 $term->formatted_name .= $ancestor_term->name . ' > ';
1732 }
1733 }
1734 }
1735
1736 $term->formatted_name .= $term->name . ' (' . $term->count . ')';
1737 $found_categories[ $term->term_id ] = $term;
1738 }
1739 }
1740
1741 wp_send_json( apply_filters( 'woocommerce_json_search_found_categories', $found_categories ) );
1742 }
1743
1744 /**
1745 * Ajax request handling for categories ordering.
1746 */
1747 public static function term_ordering() {
1748 // phpcs:disable WordPress.Security.NonceVerification.Missing
1749 if ( ! current_user_can( 'edit_products' ) || empty( $_POST['id'] ) ) {
1750 wp_die( -1 );
1751 }
1752
1753 $id = (int) $_POST['id'];
1754 $next_id = isset( $_POST['nextid'] ) && (int) $_POST['nextid'] ? (int) $_POST['nextid'] : null;
1755 $taxonomy = isset( $_POST['thetaxonomy'] ) ? esc_attr( wp_unslash( $_POST['thetaxonomy'] ) ) : null; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1756 $term = get_term_by( 'id', $id, $taxonomy );
1757
1758 if ( ! $id || ! $term || ! $taxonomy ) {
1759 wp_die( 0 );
1760 }
1761
1762 wc_reorder_terms( $term, $next_id, $taxonomy );
1763
1764 $children = get_terms( $taxonomy, "child_of=$id&menu_order=ASC&hide_empty=0" );
1765
1766 if ( $term && count( $children ) ) {
1767 echo 'children';
1768 wp_die();
1769 }
1770 // phpcs:enable
1771 }
1772
1773 /**
1774 * Ajax request handling for product ordering.
1775 *
1776 * Based on Simple Page Ordering by 10up (https://wordpress.org/plugins/simple-page-ordering/).
1777 */
1778 public static function product_ordering() {
1779 global $wpdb;
1780
1781 // phpcs:disable WordPress.Security.NonceVerification.Missing
1782 if ( ! current_user_can( 'edit_products' ) || empty( $_POST['id'] ) ) {
1783 wp_die( -1 );
1784 }
1785
1786 $sorting_id = absint( $_POST['id'] );
1787 $previd = absint( isset( $_POST['previd'] ) ? $_POST['previd'] : 0 );
1788 $nextid = absint( isset( $_POST['nextid'] ) ? $_POST['nextid'] : 0 );
1789 $menu_orders = wp_list_pluck( $wpdb->get_results( "SELECT ID, menu_order FROM {$wpdb->posts} WHERE post_type = 'product' ORDER BY menu_order ASC, post_title ASC" ), 'menu_order', 'ID' );
1790 $index = 0;
1791
1792 foreach ( $menu_orders as $id => $menu_order ) {
1793 $id = absint( $id );
1794
1795 if ( $sorting_id === $id ) {
1796 continue;
1797 }
1798 if ( $nextid === $id ) {
1799 $index ++;
1800 }
1801 $index ++;
1802 $menu_orders[ $id ] = $index;
1803 $wpdb->update( $wpdb->posts, array( 'menu_order' => $index ), array( 'ID' => $id ) );
1804
1805 /**
1806 * When a single product has gotten it's ordering updated.
1807 * $id The product ID
1808 * $index The new menu order
1809 */
1810 do_action( 'woocommerce_after_single_product_ordering', $id, $index );
1811 }
1812
1813 if ( isset( $menu_orders[ $previd ] ) ) {
1814 $menu_orders[ $sorting_id ] = $menu_orders[ $previd ] + 1;
1815 } elseif ( isset( $menu_orders[ $nextid ] ) ) {
1816 $menu_orders[ $sorting_id ] = $menu_orders[ $nextid ] - 1;
1817 } else {
1818 $menu_orders[ $sorting_id ] = 0;
1819 }
1820
1821 $wpdb->update( $wpdb->posts, array( 'menu_order' => $menu_orders[ $sorting_id ] ), array( 'ID' => $sorting_id ) );
1822
1823 WC_Post_Data::delete_product_query_transients();
1824
1825 do_action( 'woocommerce_after_product_ordering', $sorting_id, $menu_orders );
1826 wp_send_json( $menu_orders );
1827 // phpcs:enable
1828 }
1829
1830 /**
1831 * Handle a refund via the edit order screen.
1832 *
1833 * @throws Exception To return errors.
1834 */
1835 public static function refund_line_items() {
1836 ob_start();
1837
1838 check_ajax_referer( 'order-item', 'security' );
1839
1840 if ( ! current_user_can( 'edit_shop_orders' ) ) {
1841 wp_die( -1 );
1842 }
1843
1844 $order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0;
1845 $refund_amount = isset( $_POST['refund_amount'] ) ? wc_format_decimal( sanitize_text_field( wp_unslash( $_POST['refund_amount'] ) ), wc_get_price_decimals() ) : 0;
1846 $refunded_amount = isset( $_POST['refunded_amount'] ) ? wc_format_decimal( sanitize_text_field( wp_unslash( $_POST['refunded_amount'] ) ), wc_get_price_decimals() ) : 0;
1847 $refund_reason = isset( $_POST['refund_reason'] ) ? sanitize_text_field( wp_unslash( $_POST['refund_reason'] ) ) : '';
1848 $line_item_qtys = isset( $_POST['line_item_qtys'] ) ? json_decode( sanitize_text_field( wp_unslash( $_POST['line_item_qtys'] ) ), true ) : array();
1849 $line_item_totals = isset( $_POST['line_item_totals'] ) ? json_decode( sanitize_text_field( wp_unslash( $_POST['line_item_totals'] ) ), true ) : array();
1850 $line_item_tax_totals = isset( $_POST['line_item_tax_totals'] ) ? json_decode( sanitize_text_field( wp_unslash( $_POST['line_item_tax_totals'] ) ), true ) : array();
1851 $api_refund = isset( $_POST['api_refund'] ) && 'true' === $_POST['api_refund'];
1852 $restock_refunded_items = isset( $_POST['restock_refunded_items'] ) && 'true' === $_POST['restock_refunded_items'];
1853 $refund = false;
1854 $response = array();
1855
1856 try {
1857 $order = wc_get_order( $order_id );
1858 $max_refund = wc_format_decimal( $order->get_total() - $order->get_total_refunded(), wc_get_price_decimals() );
1859
1860 if ( ! $refund_amount || $max_refund < $refund_amount || 0 > $refund_amount ) {
1861 throw new Exception( __( 'Invalid refund amount', 'woocommerce' ) );
1862 }
1863
1864 if ( wc_format_decimal( $order->get_total_refunded(), wc_get_price_decimals() ) !== $refunded_amount ) {
1865 throw new Exception( __( 'Error processing refund. Please try again.', 'woocommerce' ) );
1866 }
1867
1868 // Prepare line items which we are refunding.
1869 $line_items = array();
1870 $item_ids = array_unique( array_merge( array_keys( $line_item_qtys ), array_keys( $line_item_totals ) ) );
1871
1872 foreach ( $item_ids as $item_id ) {
1873 $line_items[ $item_id ] = array(
1874 'qty' => 0,
1875 'refund_total' => 0,
1876 'refund_tax' => array(),
1877 );
1878 }
1879 foreach ( $line_item_qtys as $item_id => $qty ) {
1880 $line_items[ $item_id ]['qty'] = max( $qty, 0 );
1881 }
1882 foreach ( $line_item_totals as $item_id => $total ) {
1883 $line_items[ $item_id ]['refund_total'] = wc_format_decimal( $total );
1884 }
1885 foreach ( $line_item_tax_totals as $item_id => $tax_totals ) {
1886 $line_items[ $item_id ]['refund_tax'] = array_filter( array_map( 'wc_format_decimal', $tax_totals ) );
1887 }
1888
1889 // Create the refund object.
1890 $refund = wc_create_refund(
1891 array(
1892 'amount' => $refund_amount,
1893 'reason' => $refund_reason,
1894 'order_id' => $order_id,
1895 'line_items' => $line_items,
1896 'refund_payment' => $api_refund,
1897 'restock_items' => $restock_refunded_items,
1898 )
1899 );
1900
1901 if ( is_wp_error( $refund ) ) {
1902 throw new Exception( $refund->get_error_message() );
1903 }
1904
1905 if ( did_action( 'woocommerce_order_fully_refunded' ) ) {
1906 $response['status'] = 'fully_refunded';
1907 }
1908 } catch ( Exception $e ) {
1909 wp_send_json_error( array( 'error' => $e->getMessage() ) );
1910 }
1911
1912 // wp_send_json_success must be outside the try block not to break phpunit tests.
1913 wp_send_json_success( $response );
1914 }
1915
1916 /**
1917 * Delete a refund.
1918 */
1919 public static function delete_refund() {
1920 check_ajax_referer( 'order-item', 'security' );
1921
1922 if ( ! current_user_can( 'edit_shop_orders' ) || ! isset( $_POST['refund_id'] ) ) {
1923 wp_die( -1 );
1924 }
1925
1926 $refund_ids = array_map( 'absint', is_array( $_POST['refund_id'] ) ? wp_unslash( $_POST['refund_id'] ) : array( wp_unslash( $_POST['refund_id'] ) ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1927 foreach ( $refund_ids as $refund_id ) {
1928 if ( $refund_id && 'shop_order_refund' === get_post_type( $refund_id ) ) {
1929 $refund = wc_get_order( $refund_id );
1930 $order_id = $refund->get_parent_id();
1931 $refund->delete( true );
1932 do_action( 'woocommerce_refund_deleted', $refund_id, $order_id );
1933 }
1934 }
1935 wp_die();
1936 }
1937
1938 /**
1939 * Triggered when clicking the rating footer.
1940 */
1941 public static function rated() {
1942 if ( ! current_user_can( 'manage_woocommerce' ) ) {
1943 wp_die( -1 );
1944 }
1945 update_option( 'woocommerce_admin_footer_text_rated', 1 );
1946 wp_die();
1947 }
1948
1949 /**
1950 * Create/Update API key.
1951 *
1952 * @throws Exception On invalid or empty description, user, or permissions.
1953 */
1954 public static function update_api_key() {
1955 ob_start();
1956
1957 global $wpdb;
1958
1959 check_ajax_referer( 'update-api-key', 'security' );
1960
1961 if ( ! current_user_can( 'manage_woocommerce' ) ) {
1962 wp_die( -1 );
1963 }
1964
1965 $response = array();
1966
1967 try {
1968 if ( empty( $_POST['description'] ) ) {
1969 throw new Exception( __( 'Description is missing.', 'woocommerce' ) );
1970 }
1971 if ( empty( $_POST['user'] ) ) {
1972 throw new Exception( __( 'User is missing.', 'woocommerce' ) );
1973 }
1974 if ( empty( $_POST['permissions'] ) ) {
1975 throw new Exception( __( 'Permissions is missing.', 'woocommerce' ) );
1976 }
1977
1978 $key_id = isset( $_POST['key_id'] ) ? absint( $_POST['key_id'] ) : 0;
1979 $description = sanitize_text_field( wp_unslash( $_POST['description'] ) );
1980 $permissions = ( in_array( wp_unslash( $_POST['permissions'] ), array( 'read', 'write', 'read_write' ), true ) ) ? sanitize_text_field( wp_unslash( $_POST['permissions'] ) ) : 'read';
1981 $user_id = absint( $_POST['user'] );
1982
1983 // Check if current user can edit other users.
1984 if ( $user_id && ! current_user_can( 'edit_user', $user_id ) ) {
1985 if ( get_current_user_id() !== $user_id ) {
1986 throw new Exception( __( 'You do not have permission to assign API Keys to the selected user.', 'woocommerce' ) );
1987 }
1988 }
1989
1990 if ( 0 < $key_id ) {
1991 $data = array(
1992 'user_id' => $user_id,
1993 'description' => $description,
1994 'permissions' => $permissions,
1995 );
1996
1997 $wpdb->update(
1998 $wpdb->prefix . 'woocommerce_api_keys',
1999 $data,
2000 array( 'key_id' => $key_id ),
2001 array(
2002 '%d',
2003 '%s',
2004 '%s',
2005 ),
2006 array( '%d' )
2007 );
2008
2009 $response = $data;
2010 $response['consumer_key'] = '';
2011 $response['consumer_secret'] = '';
2012 $response['message'] = __( 'API Key updated successfully.', 'woocommerce' );
2013 } else {
2014 $consumer_key = 'ck_' . wc_rand_hash();
2015 $consumer_secret = 'cs_' . wc_rand_hash();
2016
2017 $data = array(
2018 'user_id' => $user_id,
2019 'description' => $description,
2020 'permissions' => $permissions,
2021 'consumer_key' => wc_api_hash( $consumer_key ),
2022 'consumer_secret' => $consumer_secret,
2023 'truncated_key' => substr( $consumer_key, -7 ),
2024 );
2025
2026 $wpdb->insert(
2027 $wpdb->prefix . 'woocommerce_api_keys',
2028 $data,
2029 array(
2030 '%d',
2031 '%s',
2032 '%s',
2033 '%s',
2034 '%s',
2035 '%s',
2036 )
2037 );
2038
2039 $key_id = $wpdb->insert_id;
2040 $response = $data;
2041 $response['consumer_key'] = $consumer_key;
2042 $response['consumer_secret'] = $consumer_secret;
2043 $response['message'] = __( 'API Key generated successfully. Make sure to copy your new keys now as the secret key will be hidden once you leave this page.', 'woocommerce' );
2044 $response['revoke_url'] = '<a style="color: #a00; text-decoration: none;" href="' . esc_url( wp_nonce_url( add_query_arg( array( 'revoke-key' => $key_id ), admin_url( 'admin.php?page=wc-settings&tab=advanced&section=keys' ) ), 'revoke' ) ) . '">' . __( 'Revoke key', 'woocommerce' ) . '</a>';
2045 }
2046 } catch ( Exception $e ) {
2047 wp_send_json_error( array( 'message' => $e->getMessage() ) );
2048 }
2049
2050 // wp_send_json_success must be outside the try block not to break phpunit tests.
2051 wp_send_json_success( $response );
2052 }
2053
2054 /**
2055 * Load variations via AJAX.
2056 */
2057 public static function load_variations() {
2058 ob_start();
2059
2060 check_ajax_referer( 'load-variations', 'security' );
2061
2062 if ( ! current_user_can( 'edit_products' ) || empty( $_POST['product_id'] ) ) {
2063 wp_die( -1 );
2064 }
2065
2066 // Set $post global so its available, like within the admin screens.
2067 global $post;
2068
2069 $loop = 0;
2070 $product_id = absint( $_POST['product_id'] );
2071 $post = get_post( $product_id ); // phpcs:ignore
2072 $product_object = wc_get_product( $product_id );
2073 $per_page = ! empty( $_POST['per_page'] ) ? absint( $_POST['per_page'] ) : 10;
2074 $page = ! empty( $_POST['page'] ) ? absint( $_POST['page'] ) : 1;
2075 $variations = wc_get_products(
2076 array(
2077 'status' => array( 'private', 'publish' ),
2078 'type' => 'variation',
2079 'parent' => $product_id,
2080 'limit' => $per_page,
2081 'page' => $page,
2082 'orderby' => array(
2083 'menu_order' => 'ASC',
2084 'ID' => 'DESC',
2085 ),
2086 'return' => 'objects',
2087 )
2088 );
2089
2090 if ( $variations ) {
2091 wc_render_invalid_variation_notice( $product_object );
2092
2093 foreach ( $variations as $variation_object ) {
2094 $variation_id = $variation_object->get_id();
2095 $variation = get_post( $variation_id );
2096 $variation_data = array_merge( get_post_custom( $variation_id ), wc_get_product_variation_attributes( $variation_id ) ); // kept for BW compatibility.
2097 include 'admin/meta-boxes/views/html-variation-admin.php';
2098 $loop++;
2099 }
2100 }
2101 wp_die();
2102 }
2103
2104 /**
2105 * Save variations via AJAX.
2106 */
2107 public static function save_variations() {
2108 ob_start();
2109
2110 check_ajax_referer( 'save-variations', 'security' );
2111
2112 // Check permissions again and make sure we have what we need.
2113 if ( ! current_user_can( 'edit_products' ) || empty( $_POST ) || empty( $_POST['product_id'] ) ) {
2114 wp_die( -1 );
2115 }
2116
2117 $product_id = absint( $_POST['product_id'] );
2118 WC_Admin_Meta_Boxes::$meta_box_errors = array();
2119 WC_Meta_Box_Product_Data::save_variations( $product_id, get_post( $product_id ) );
2120
2121 do_action( 'woocommerce_ajax_save_product_variations', $product_id );
2122
2123 $errors = WC_Admin_Meta_Boxes::$meta_box_errors;
2124
2125 if ( $errors ) {
2126 echo '<div class="error notice is-dismissible">';
2127
2128 foreach ( $errors as $error ) {
2129 echo '<p>' . wp_kses_post( $error ) . '</p>';
2130 }
2131
2132 echo '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' . esc_html__( 'Dismiss this notice.', 'woocommerce' ) . '</span></button>';
2133 echo '</div>';
2134
2135 delete_option( 'woocommerce_meta_box_errors' );
2136 }
2137
2138 wp_die();
2139 }
2140
2141 /**
2142 * Bulk action - Toggle Enabled.
2143 *
2144 * @param array $variations List of variations.
2145 * @param array $data Data to set.
2146 *
2147 * @used-by bulk_edit_variations
2148 */
2149 private static function variation_bulk_action_toggle_enabled( $variations, $data ) {
2150 foreach ( $variations as $variation_id ) {
2151 $variation = wc_get_product( $variation_id );
2152 $variation->set_status( 'private' === $variation->get_status( 'edit' ) ? 'publish' : 'private' );
2153 $variation->save();
2154 }
2155 }
2156
2157 /**
2158 * Bulk action - Toggle Downloadable Checkbox.
2159 *
2160 * @param array $variations List of variations.
2161 * @param array $data Data to set.
2162 *
2163 * @used-by bulk_edit_variations
2164 */
2165 private static function variation_bulk_action_toggle_downloadable( $variations, $data ) {
2166 self::variation_bulk_toggle( $variations, 'downloadable' );
2167 }
2168
2169 /**
2170 * Bulk action - Toggle Virtual Checkbox.
2171 *
2172 * @param array $variations List of variations.
2173 * @param array $data Data to set.
2174 *
2175 * @used-by bulk_edit_variations
2176 */
2177 private static function variation_bulk_action_toggle_virtual( $variations, $data ) {
2178 self::variation_bulk_toggle( $variations, 'virtual' );
2179 }
2180
2181 /**
2182 * Bulk action - Toggle Manage Stock Checkbox.
2183 *
2184 * @param array $variations List of variations.
2185 * @param array $data Data to set.
2186 *
2187 * @used-by bulk_edit_variations
2188 */
2189 private static function variation_bulk_action_toggle_manage_stock( $variations, $data ) {
2190 self::variation_bulk_toggle( $variations, 'manage_stock' );
2191 }
2192
2193 /**
2194 * Bulk action - Set Regular Prices.
2195 *
2196 * @param array $variations List of variations.
2197 * @param array $data Data to set.
2198 *
2199 * @used-by bulk_edit_variations
2200 */
2201 private static function variation_bulk_action_variable_regular_price( $variations, $data ) {
2202 self::variation_bulk_set( $variations, 'regular_price', $data['value'] );
2203 }
2204
2205 /**
2206 * Bulk action - Set Sale Prices.
2207 *
2208 * @param array $variations List of variations.
2209 * @param array $data Data to set.
2210 *
2211 * @used-by bulk_edit_variations
2212 */
2213 private static function variation_bulk_action_variable_sale_price( $variations, $data ) {
2214 self::variation_bulk_set( $variations, 'sale_price', $data['value'] );
2215 }
2216
2217 /**
2218 * Bulk action - Set Stock Status as In Stock.
2219 *
2220 * @param array $variations List of variations.
2221 * @param array $data Data to set.
2222 *
2223 * @used-by bulk_edit_variations
2224 */
2225 private static function variation_bulk_action_variable_stock_status_instock( $variations, $data ) {
2226 self::variation_bulk_set( $variations, 'stock_status', 'instock' );
2227 }
2228
2229 /**
2230 * Bulk action - Set Stock Status as Out of Stock.
2231 *
2232 * @param array $variations List of variations.
2233 * @param array $data Data to set.
2234 *
2235 * @used-by bulk_edit_variations
2236 */
2237 private static function variation_bulk_action_variable_stock_status_outofstock( $variations, $data ) {
2238 self::variation_bulk_set( $variations, 'stock_status', 'outofstock' );
2239 }
2240
2241 /**
2242 * Bulk action - Set Stock Status as On Backorder.
2243 *
2244 * @param array $variations List of variations.
2245 * @param array $data Data to set.
2246 *
2247 * @used-by bulk_edit_variations
2248 */
2249 private static function variation_bulk_action_variable_stock_status_onbackorder( $variations, $data ) {
2250 self::variation_bulk_set( $variations, 'stock_status', 'onbackorder' );
2251 }
2252
2253 /**
2254 * Bulk action - Set Stock.
2255 *
2256 * @param array $variations List of variations.
2257 * @param array $data Data to set.
2258 *
2259 * @used-by bulk_edit_variations
2260 */
2261 private static function variation_bulk_action_variable_stock( $variations, $data ) {
2262 if ( ! isset( $data['value'] ) ) {
2263 return;
2264 }
2265
2266 $quantity = wc_stock_amount( wc_clean( $data['value'] ) );
2267
2268 foreach ( $variations as $variation_id ) {
2269 $variation = wc_get_product( $variation_id );
2270 if ( $variation->managing_stock() ) {
2271 $variation->set_stock_quantity( $quantity );
2272 } else {
2273 $variation->set_stock_quantity( null );
2274 }
2275 $variation->save();
2276 }
2277 }
2278
2279 /**
2280 * Bulk action - Set Weight.
2281 *
2282 * @param array $variations List of variations.
2283 * @param array $data Data to set.
2284 *
2285 * @used-by bulk_edit_variations
2286 */
2287 private static function variation_bulk_action_variable_weight( $variations, $data ) {
2288 self::variation_bulk_set( $variations, 'weight', $data['value'] );
2289 }
2290
2291 /**
2292 * Bulk action - Set Length.
2293 *
2294 * @param array $variations List of variations.
2295 * @param array $data Data to set.
2296 *
2297 * @used-by bulk_edit_variations
2298 */
2299 private static function variation_bulk_action_variable_length( $variations, $data ) {
2300 self::variation_bulk_set( $variations, 'length', $data['value'] );
2301 }
2302
2303 /**
2304 * Bulk action - Set Width.
2305 *
2306 * @param array $variations List of variations.
2307 * @param array $data Data to set.
2308 *
2309 * @used-by bulk_edit_variations
2310 */
2311 private static function variation_bulk_action_variable_width( $variations, $data ) {
2312 self::variation_bulk_set( $variations, 'width', $data['value'] );
2313 }
2314
2315 /**
2316 * Bulk action - Set Height.
2317 *
2318 * @param array $variations List of variations.
2319 * @param array $data Data to set.
2320 *
2321 * @used-by bulk_edit_variations
2322 */
2323 private static function variation_bulk_action_variable_height( $variations, $data ) {
2324 self::variation_bulk_set( $variations, 'height', $data['value'] );
2325 }
2326
2327 /**
2328 * Bulk action - Set Download Limit.
2329 *
2330 * @param array $variations List of variations.
2331 * @param array $data Data to set.
2332 *
2333 * @used-by bulk_edit_variations
2334 */
2335 private static function variation_bulk_action_variable_download_limit( $variations, $data ) {
2336 self::variation_bulk_set( $variations, 'download_limit', $data['value'] );
2337 }
2338
2339 /**
2340 * Bulk action - Set Download Expiry.
2341 *
2342 * @param array $variations List of variations.
2343 * @param array $data Data to set.
2344 *
2345 * @used-by bulk_edit_variations
2346 */
2347 private static function variation_bulk_action_variable_download_expiry( $variations, $data ) {
2348 self::variation_bulk_set( $variations, 'download_expiry', $data['value'] );
2349 }
2350
2351 /**
2352 * Bulk action - Delete all.
2353 *
2354 * @param array $variations List of variations.
2355 * @param array $data Data to set.
2356 *
2357 * @used-by bulk_edit_variations
2358 */
2359 private static function variation_bulk_action_delete_all( $variations, $data ) {
2360 if ( isset( $data['allowed'] ) && 'true' === $data['allowed'] ) {
2361 foreach ( $variations as $variation_id ) {
2362 $variation = wc_get_product( $variation_id );
2363 $variation->delete( true );
2364 }
2365 }
2366 }
2367
2368 /**
2369 * Bulk action - Sale Schedule.
2370 *
2371 * @param array $variations List of variations.
2372 * @param array $data Data to set.
2373 *
2374 * @used-by bulk_edit_variations
2375 */
2376 private static function variation_bulk_action_variable_sale_schedule( $variations, $data ) {
2377 if ( ! isset( $data['date_from'] ) && ! isset( $data['date_to'] ) ) {
2378 return;
2379 }
2380
2381 foreach ( $variations as $variation_id ) {
2382 $variation = wc_get_product( $variation_id );
2383
2384 if ( 'false' !== $data['date_from'] ) {
2385 $variation->set_date_on_sale_from( wc_clean( $data['date_from'] ) );
2386 }
2387
2388 if ( 'false' !== $data['date_to'] ) {
2389 $variation->set_date_on_sale_to( wc_clean( $data['date_to'] ) );
2390 }
2391
2392 $variation->save();
2393 }
2394 }
2395
2396 /**
2397 * Bulk action - Increase Regular Prices.
2398 *
2399 * @param array $variations List of variations.
2400 * @param array $data Data to set.
2401 *
2402 * @used-by bulk_edit_variations
2403 */
2404 private static function variation_bulk_action_variable_regular_price_increase( $variations, $data ) {
2405 self::variation_bulk_adjust_price( $variations, 'regular_price', '+', wc_clean( $data['value'] ) );
2406 }
2407
2408 /**
2409 * Bulk action - Decrease Regular Prices.
2410 *
2411 * @param array $variations List of variations.
2412 * @param array $data Data to set.
2413 *
2414 * @used-by bulk_edit_variations
2415 */
2416 private static function variation_bulk_action_variable_regular_price_decrease( $variations, $data ) {
2417 self::variation_bulk_adjust_price( $variations, 'regular_price', '-', wc_clean( $data['value'] ) );
2418 }
2419
2420 /**
2421 * Bulk action - Increase Sale Prices.
2422 *
2423 * @param array $variations List of variations.
2424 * @param array $data Data to set.
2425 *
2426 * @used-by bulk_edit_variations
2427 */
2428 private static function variation_bulk_action_variable_sale_price_increase( $variations, $data ) {
2429 self::variation_bulk_adjust_price( $variations, 'sale_price', '+', wc_clean( $data['value'] ) );
2430 }
2431
2432 /**
2433 * Bulk action - Decrease Sale Prices.
2434 *
2435 * @param array $variations List of variations.
2436 * @param array $data Data to set.
2437 *
2438 * @used-by bulk_edit_variations
2439 */
2440 private static function variation_bulk_action_variable_sale_price_decrease( $variations, $data ) {
2441 self::variation_bulk_adjust_price( $variations, 'sale_price', '-', wc_clean( $data['value'] ) );
2442 }
2443
2444 /**
2445 * Bulk action - Set Price.
2446 *
2447 * @param array $variations List of variations.
2448 * @param string $field price being adjusted _regular_price or _sale_price.
2449 * @param string $operator + or -.
2450 * @param string $value Price or Percent.
2451 *
2452 * @used-by bulk_edit_variations
2453 */
2454 private static function variation_bulk_adjust_price( $variations, $field, $operator, $value ) {
2455 foreach ( $variations as $variation_id ) {
2456 $variation = wc_get_product( $variation_id );
2457 $field_value = $variation->{"get_$field"}( 'edit' );
2458
2459 if ( '%' === substr( $value, -1 ) ) {
2460 $percent = wc_format_decimal( substr( $value, 0, -1 ) );
2461 $field_value += round( ( $field_value / 100 ) * $percent, wc_get_price_decimals() ) * "{$operator}1";
2462 } else {
2463 $field_value += $value * "{$operator}1";
2464 }
2465
2466 $variation->{"set_$field"}( $field_value );
2467 $variation->save();
2468 }
2469 }
2470
2471 /**
2472 * Bulk set convenience function.
2473 *
2474 * @param array $variations List of variations.
2475 * @param string $field Field to set.
2476 * @param string $value to set.
2477 */
2478 private static function variation_bulk_set( $variations, $field, $value ) {
2479 foreach ( $variations as $variation_id ) {
2480 $variation = wc_get_product( $variation_id );
2481 $variation->{ "set_$field" }( wc_clean( $value ) );
2482 $variation->save();
2483 }
2484 }
2485
2486 /**
2487 * Bulk toggle convenience function.
2488 *
2489 * @param array $variations List of variations.
2490 * @param string $field Field to toggle.
2491 */
2492 private static function variation_bulk_toggle( $variations, $field ) {
2493 foreach ( $variations as $variation_id ) {
2494 $variation = wc_get_product( $variation_id );
2495 $prev_value = $variation->{ "get_$field" }( 'edit' );
2496 $variation->{ "set_$field" }( ! $prev_value );
2497 $variation->save();
2498 }
2499 }
2500
2501 /**
2502 * Bulk edit variations via AJAX.
2503 *
2504 * @uses WC_AJAX::variation_bulk_set()
2505 * @uses WC_AJAX::variation_bulk_adjust_price()
2506 * @uses WC_AJAX::variation_bulk_action_variable_sale_price_decrease()
2507 * @uses WC_AJAX::variation_bulk_action_variable_sale_price_increase()
2508 * @uses WC_AJAX::variation_bulk_action_variable_regular_price_decrease()
2509 * @uses WC_AJAX::variation_bulk_action_variable_regular_price_increase()
2510 * @uses WC_AJAX::variation_bulk_action_variable_sale_schedule()
2511 * @uses WC_AJAX::variation_bulk_action_delete_all()
2512 * @uses WC_AJAX::variation_bulk_action_variable_download_expiry()
2513 * @uses WC_AJAX::variation_bulk_action_variable_download_limit()
2514 * @uses WC_AJAX::variation_bulk_action_variable_height()
2515 * @uses WC_AJAX::variation_bulk_action_variable_width()
2516 * @uses WC_AJAX::variation_bulk_action_variable_length()
2517 * @uses WC_AJAX::variation_bulk_action_variable_weight()
2518 * @uses WC_AJAX::variation_bulk_action_variable_stock()
2519 * @uses WC_AJAX::variation_bulk_action_variable_sale_price()
2520 * @uses WC_AJAX::variation_bulk_action_variable_regular_price()
2521 * @uses WC_AJAX::variation_bulk_action_toggle_manage_stock()
2522 * @uses WC_AJAX::variation_bulk_action_toggle_virtual()
2523 * @uses WC_AJAX::variation_bulk_action_toggle_downloadable()
2524 * @uses WC_AJAX::variation_bulk_action_toggle_enabled
2525 */
2526 public static function bulk_edit_variations() {
2527 ob_start();
2528
2529 check_ajax_referer( 'bulk-edit-variations', 'security' );
2530
2531 // Check permissions again and make sure we have what we need.
2532 if ( ! current_user_can( 'edit_products' ) || empty( $_POST['product_id'] ) || empty( $_POST['bulk_action'] ) ) {
2533 wp_die( -1 );
2534 }
2535
2536 $product_id = absint( $_POST['product_id'] );
2537 $bulk_action = wc_clean( wp_unslash( $_POST['bulk_action'] ) );
2538 $data = ! empty( $_POST['data'] ) ? wc_clean( wp_unslash( $_POST['data'] ) ) : array();
2539 $variations = array();
2540
2541 if ( apply_filters( 'woocommerce_bulk_edit_variations_need_children', true ) ) {
2542 $variations = get_posts(
2543 array(
2544 'post_parent' => $product_id,
2545 'posts_per_page' => -1,
2546 'post_type' => 'product_variation',
2547 'fields' => 'ids',
2548 'post_status' => array( 'publish', 'private' ),
2549 )
2550 );
2551 }
2552
2553 if ( method_exists( __CLASS__, "variation_bulk_action_$bulk_action" ) ) {
2554 call_user_func( array( __CLASS__, "variation_bulk_action_$bulk_action" ), $variations, $data );
2555 } else {
2556 do_action( 'woocommerce_bulk_edit_variations_default', $bulk_action, $data, $product_id, $variations );
2557 }
2558
2559 do_action( 'woocommerce_bulk_edit_variations', $bulk_action, $data, $product_id, $variations );
2560 WC_Product_Variable::sync( $product_id );
2561 wc_delete_product_transients( $product_id );
2562 wp_die();
2563 }
2564
2565 /**
2566 * Handle submissions from assets/js/settings-views-html-settings-tax.js Backbone model.
2567 */
2568 public static function tax_rates_save_changes() {
2569 // phpcs:disable WordPress.Security.NonceVerification.Missing
2570 if ( ! isset( $_POST['wc_tax_nonce'], $_POST['changes'] ) ) {
2571 wp_send_json_error( 'missing_fields' );
2572 wp_die();
2573 }
2574
2575 $current_class = ! empty( $_POST['current_class'] ) ? wp_unslash( $_POST['current_class'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2576
2577 if ( ! wp_verify_nonce( wp_unslash( $_POST['wc_tax_nonce'] ), 'wc_tax_nonce-class:' . $current_class ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2578 wp_send_json_error( 'bad_nonce' );
2579 wp_die();
2580 }
2581
2582 $current_class = WC_Tax::format_tax_rate_class( $current_class );
2583
2584 // Check User Caps.
2585 if ( ! current_user_can( 'manage_woocommerce' ) ) {
2586 wp_send_json_error( 'missing_capabilities' );
2587 wp_die();
2588 }
2589
2590 $changes = wp_unslash( $_POST['changes'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2591 foreach ( $changes as $tax_rate_id => $data ) {
2592 if ( isset( $data['deleted'] ) ) {
2593 if ( isset( $data['newRow'] ) ) {
2594 // So the user added and deleted a new row.
2595 // That's fine, it's not in the database anyways. NEXT!
2596 continue;
2597 }
2598 WC_Tax::_delete_tax_rate( $tax_rate_id );
2599 }
2600
2601 $tax_rate = array_intersect_key(
2602 $data,
2603 array(
2604 'tax_rate_country' => 1,
2605 'tax_rate_state' => 1,
2606 'tax_rate' => 1,
2607 'tax_rate_name' => 1,
2608 'tax_rate_priority' => 1,
2609 'tax_rate_compound' => 1,
2610 'tax_rate_shipping' => 1,
2611 'tax_rate_order' => 1,
2612 )
2613 );
2614
2615 if ( isset( $tax_rate['tax_rate'] ) ) {
2616 $tax_rate['tax_rate'] = wc_format_decimal( $tax_rate['tax_rate'] );
2617 }
2618
2619 if ( isset( $data['newRow'] ) ) {
2620 $tax_rate['tax_rate_class'] = $current_class;
2621 $tax_rate_id = WC_Tax::_insert_tax_rate( $tax_rate );
2622 } elseif ( ! empty( $tax_rate ) ) {
2623 WC_Tax::_update_tax_rate( $tax_rate_id, $tax_rate );
2624 }
2625
2626 if ( isset( $data['postcode'] ) ) {
2627 $postcode = array_map( 'wc_clean', $data['postcode'] );
2628 $postcode = array_map( 'wc_normalize_postcode', $postcode );
2629 WC_Tax::_update_tax_rate_postcodes( $tax_rate_id, $postcode );
2630 }
2631 if ( isset( $data['city'] ) ) {
2632 WC_Tax::_update_tax_rate_cities( $tax_rate_id, array_map( 'wc_clean', array_map( 'wp_unslash', $data['city'] ) ) );
2633 }
2634 }
2635
2636 WC_Cache_Helper::invalidate_cache_group( 'taxes' );
2637 WC_Cache_Helper::get_transient_version( 'shipping', true );
2638
2639 wp_send_json_success(
2640 array(
2641 'rates' => WC_Tax::get_rates_for_tax_class( $current_class ),
2642 )
2643 );
2644 // phpcs:enable
2645 }
2646
2647 /**
2648 * Handle submissions from assets/js/wc-shipping-zones.js Backbone model.
2649 */
2650 public static function shipping_zones_save_changes() {
2651 if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['changes'] ) ) {
2652 wp_send_json_error( 'missing_fields' );
2653 wp_die();
2654 }
2655
2656 if ( ! wp_verify_nonce( wp_unslash( $_POST['wc_shipping_zones_nonce'] ), 'wc_shipping_zones_nonce' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2657 wp_send_json_error( 'bad_nonce' );
2658 wp_die();
2659 }
2660
2661 // Check User Caps.
2662 if ( ! current_user_can( 'manage_woocommerce' ) ) {
2663 wp_send_json_error( 'missing_capabilities' );
2664 wp_die();
2665 }
2666
2667 $changes = wp_unslash( $_POST['changes'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2668 foreach ( $changes as $zone_id => $data ) {
2669 if ( isset( $data['deleted'] ) ) {
2670 if ( isset( $data['newRow'] ) ) {
2671 // So the user added and deleted a new row.
2672 // That's fine, it's not in the database anyways. NEXT!
2673 continue;
2674 }
2675 WC_Shipping_Zones::delete_zone( $zone_id );
2676 continue;
2677 }
2678
2679 $zone_data = array_intersect_key(
2680 $data,
2681 array(
2682 'zone_id' => 1,
2683 'zone_order' => 1,
2684 )
2685 );
2686
2687 if ( isset( $zone_data['zone_id'] ) ) {
2688 $zone = new WC_Shipping_Zone( $zone_data['zone_id'] );
2689
2690 if ( isset( $zone_data['zone_order'] ) ) {
2691 $zone->set_zone_order( $zone_data['zone_order'] );
2692 }
2693
2694 $zone->save();
2695 }
2696 }
2697
2698 wp_send_json_success(
2699 array(
2700 'zones' => WC_Shipping_Zones::get_zones( 'json' ),
2701 )
2702 );
2703 }
2704
2705 /**
2706 * Handle submissions from assets/js/wc-shipping-zone-methods.js Backbone model.
2707 */
2708 public static function shipping_zone_add_method() {
2709 if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['zone_id'], $_POST['method_id'] ) ) {
2710 wp_send_json_error( 'missing_fields' );
2711 wp_die();
2712 }
2713
2714 if ( ! wp_verify_nonce( wp_unslash( $_POST['wc_shipping_zones_nonce'] ), 'wc_shipping_zones_nonce' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2715 wp_send_json_error( 'bad_nonce' );
2716 wp_die();
2717 }
2718
2719 // Check User Caps.
2720 if ( ! current_user_can( 'manage_woocommerce' ) ) {
2721 wp_send_json_error( 'missing_capabilities' );
2722 wp_die();
2723 }
2724
2725 $zone_id = wc_clean( wp_unslash( $_POST['zone_id'] ) );
2726 $zone = new WC_Shipping_Zone( $zone_id );
2727 $instance_id = $zone->add_shipping_method( wc_clean( wp_unslash( $_POST['method_id'] ) ) );
2728
2729 wp_send_json_success(
2730 array(
2731 'instance_id' => $instance_id,
2732 'zone_id' => $zone->get_id(),
2733 'zone_name' => $zone->get_zone_name(),
2734 'methods' => $zone->get_shipping_methods( false, 'json' ),
2735 )
2736 );
2737 }
2738
2739 /**
2740 * Handle submissions from assets/js/wc-shipping-zone-methods.js Backbone model.
2741 */
2742 public static function shipping_zone_methods_save_changes() {
2743 if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['zone_id'], $_POST['changes'] ) ) {
2744 wp_send_json_error( 'missing_fields' );
2745 wp_die();
2746 }
2747
2748 if ( ! wp_verify_nonce( wp_unslash( $_POST['wc_shipping_zones_nonce'] ), 'wc_shipping_zones_nonce' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2749 wp_send_json_error( 'bad_nonce' );
2750 wp_die();
2751 }
2752
2753 if ( ! current_user_can( 'manage_woocommerce' ) ) {
2754 wp_send_json_error( 'missing_capabilities' );
2755 wp_die();
2756 }
2757
2758 global $wpdb;
2759
2760 $zone_id = wc_clean( wp_unslash( $_POST['zone_id'] ) );
2761 $zone = new WC_Shipping_Zone( $zone_id );
2762 $changes = wp_unslash( $_POST['changes'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2763
2764 if ( isset( $changes['zone_name'] ) ) {
2765 $zone->set_zone_name( wc_clean( $changes['zone_name'] ) );
2766 }
2767
2768 if ( isset( $changes['zone_locations'] ) ) {
2769 $zone->clear_locations( array( 'state', 'country', 'continent' ) );
2770 $locations = array_filter( array_map( 'wc_clean', (array) $changes['zone_locations'] ) );
2771 foreach ( $locations as $location ) {
2772 // Each posted location will be in the format type:code.
2773 $location_parts = explode( ':', $location );
2774 switch ( $location_parts[0] ) {
2775 case 'state':
2776 $zone->add_location( $location_parts[1] . ':' . $location_parts[2], 'state' );
2777 break;
2778 case 'country':
2779 $zone->add_location( $location_parts[1], 'country' );
2780 break;
2781 case 'continent':
2782 $zone->add_location( $location_parts[1], 'continent' );
2783 break;
2784 }
2785 }
2786 }
2787
2788 if ( isset( $changes['zone_postcodes'] ) ) {
2789 $zone->clear_locations( 'postcode' );
2790 $postcodes = array_filter( array_map( 'strtoupper', array_map( 'wc_clean', explode( "\n", $changes['zone_postcodes'] ) ) ) );
2791 foreach ( $postcodes as $postcode ) {
2792 $zone->add_location( $postcode, 'postcode' );
2793 }
2794 }
2795
2796 if ( isset( $changes['methods'] ) ) {
2797 foreach ( $changes['methods'] as $instance_id => $data ) {
2798 $method_id = $wpdb->get_var( $wpdb->prepare( "SELECT method_id FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE instance_id = %d", $instance_id ) );
2799
2800 if ( isset( $data['deleted'] ) ) {
2801 $shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
2802 $option_key = $shipping_method->get_instance_option_key();
2803 if ( $wpdb->delete( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'instance_id' => $instance_id ) ) ) {
2804 delete_option( $option_key );
2805 do_action( 'woocommerce_shipping_zone_method_deleted', $instance_id, $method_id, $zone_id );
2806 }
2807 continue;
2808 }
2809
2810 $method_data = array_intersect_key(
2811 $data,
2812 array(
2813 'method_order' => 1,
2814 'enabled' => 1,
2815 )
2816 );
2817
2818 if ( isset( $method_data['method_order'] ) ) {
2819 $wpdb->update( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'method_order' => absint( $method_data['method_order'] ) ), array( 'instance_id' => absint( $instance_id ) ) );
2820 }
2821
2822 if ( isset( $method_data['enabled'] ) ) {
2823 $is_enabled = absint( 'yes' === $method_data['enabled'] );
2824 if ( $wpdb->update( "{$wpdb->prefix}woocommerce_shipping_zone_methods", array( 'is_enabled' => $is_enabled ), array( 'instance_id' => absint( $instance_id ) ) ) ) {
2825 do_action( 'woocommerce_shipping_zone_method_status_toggled', $instance_id, $method_id, $zone_id, $is_enabled );
2826 }
2827 }
2828 }
2829 }
2830
2831 $zone->save();
2832
2833 wp_send_json_success(
2834 array(
2835 'zone_id' => $zone->get_id(),
2836 'zone_name' => $zone->get_zone_name(),
2837 'methods' => $zone->get_shipping_methods( false, 'json' ),
2838 )
2839 );
2840 }
2841
2842 /**
2843 * Save method settings
2844 */
2845 public static function shipping_zone_methods_save_settings() {
2846 if ( ! isset( $_POST['wc_shipping_zones_nonce'], $_POST['instance_id'], $_POST['data'] ) ) {
2847 wp_send_json_error( 'missing_fields' );
2848 wp_die();
2849 }
2850
2851 if ( ! wp_verify_nonce( wp_unslash( $_POST['wc_shipping_zones_nonce'] ), 'wc_shipping_zones_nonce' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2852 wp_send_json_error( 'bad_nonce' );
2853 wp_die();
2854 }
2855
2856 if ( ! current_user_can( 'manage_woocommerce' ) ) {
2857 wp_send_json_error( 'missing_capabilities' );
2858 wp_die();
2859 }
2860
2861 $instance_id = absint( $_POST['instance_id'] );
2862 $zone = WC_Shipping_Zones::get_zone_by( 'instance_id', $instance_id );
2863 $shipping_method = WC_Shipping_Zones::get_shipping_method( $instance_id );
2864 $shipping_method->set_post_data( wp_unslash( $_POST['data'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2865 $shipping_method->process_admin_options();
2866
2867 WC_Cache_Helper::get_transient_version( 'shipping', true );
2868
2869 wp_send_json_success(
2870 array(
2871 'zone_id' => $zone->get_id(),
2872 'zone_name' => $zone->get_zone_name(),
2873 'methods' => $zone->get_shipping_methods( false, 'json' ),
2874 'errors' => $shipping_method->get_errors(),
2875 )
2876 );
2877 }
2878
2879 /**
2880 * Handle submissions from assets/js/wc-shipping-classes.js Backbone model.
2881 */
2882 public static function shipping_classes_save_changes() {
2883 if ( ! isset( $_POST['wc_shipping_classes_nonce'], $_POST['changes'] ) ) {
2884 wp_send_json_error( 'missing_fields' );
2885 wp_die();
2886 }
2887
2888 if ( ! wp_verify_nonce( wp_unslash( $_POST['wc_shipping_classes_nonce'] ), 'wc_shipping_classes_nonce' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2889 wp_send_json_error( 'bad_nonce' );
2890 wp_die();
2891 }
2892
2893 if ( ! current_user_can( 'manage_woocommerce' ) ) {
2894 wp_send_json_error( 'missing_capabilities' );
2895 wp_die();
2896 }
2897
2898 $changes = wp_unslash( $_POST['changes'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
2899
2900 foreach ( $changes as $term_id => $data ) {
2901 $term_id = absint( $term_id );
2902
2903 if ( isset( $data['deleted'] ) ) {
2904 if ( isset( $data['newRow'] ) ) {
2905 // So the user added and deleted a new row.
2906 // That's fine, it's not in the database anyways. NEXT!
2907 continue;
2908 }
2909 wp_delete_term( $term_id, 'product_shipping_class' );
2910 continue;
2911 }
2912
2913 $update_args = array();
2914
2915 if ( isset( $data['name'] ) ) {
2916 $update_args['name'] = wc_clean( $data['name'] );
2917 }
2918
2919 if ( isset( $data['slug'] ) ) {
2920 $update_args['slug'] = wc_clean( $data['slug'] );
2921 }
2922
2923 if ( isset( $data['description'] ) ) {
2924 $update_args['description'] = wc_clean( $data['description'] );
2925 }
2926
2927 if ( isset( $data['newRow'] ) ) {
2928 $update_args = array_filter( $update_args );
2929 if ( empty( $update_args['name'] ) ) {
2930 continue;
2931 }
2932 $inserted_term = wp_insert_term( $update_args['name'], 'product_shipping_class', $update_args );
2933 $term_id = is_wp_error( $inserted_term ) ? 0 : $inserted_term['term_id'];
2934 } else {
2935 wp_update_term( $term_id, 'product_shipping_class', $update_args );
2936 }
2937
2938 do_action( 'woocommerce_shipping_classes_save_class', $term_id, $data );
2939 }
2940
2941 $wc_shipping = WC_Shipping::instance();
2942
2943 wp_send_json_success(
2944 array(
2945 'shipping_classes' => $wc_shipping->get_shipping_classes(),
2946 )
2947 );
2948 }
2949
2950 /**
2951 * Toggle payment gateway on or off via AJAX.
2952 *
2953 * @since 3.4.0
2954 */
2955 public static function toggle_gateway_enabled() {
2956 if ( current_user_can( 'manage_woocommerce' ) && check_ajax_referer( 'woocommerce-toggle-payment-gateway-enabled', 'security' ) && isset( $_POST['gateway_id'] ) ) {
2957 // Load gateways.
2958 $payment_gateways = WC()->payment_gateways->payment_gateways();
2959
2960 // Get posted gateway.
2961 $gateway_id = wc_clean( wp_unslash( $_POST['gateway_id'] ) );
2962
2963 foreach ( $payment_gateways as $gateway ) {
2964 if ( ! in_array( $gateway_id, array( $gateway->id, sanitize_title( get_class( $gateway ) ) ), true ) ) {
2965 continue;
2966 }
2967 $enabled = $gateway->get_option( 'enabled', 'no' );
2968
2969 if ( ! wc_string_to_bool( $enabled ) ) {
2970 if ( $gateway->needs_setup() ) {
2971 wp_send_json_error( 'needs_setup' );
2972 wp_die();
2973 } else {
2974 $gateway->update_option( 'enabled', 'yes' );
2975 }
2976 } else {
2977 // Disable the gateway.
2978 $gateway->update_option( 'enabled', 'no' );
2979 }
2980
2981 wp_send_json_success( ! wc_string_to_bool( $enabled ) );
2982 wp_die();
2983 }
2984 }
2985
2986 wp_send_json_error( 'invalid_gateway_id' );
2987 wp_die();
2988 }
2989 }
2990
2991 WC_AJAX::init();
2992