PluginProbe
AppMySite – WordPress & WooCommerce Mobile App Builder (No-Code Android & iOS App Maker) / 3.5.1
AppMySite – WordPress & WooCommerce Mobile App Builder (No-Code Android & iOS App Maker) v3.5.1
3.15.4 trunk 2.0.0 2.1.0 2.10.0 2.11.0 2.2.0 2.3.0 2.4.0 2.4.1 2.5.0 2.6.0 2.6.1 2.7.0 2.8.0 2.8.1 2.9.0 2.9.1 3.0.0 3.0.1 3.1.0 3.10.0 3.11.0 3.11.1 3.11.2 All 48 releases
appmysite / appmysite.php

appmysite.php in AppMySite – WordPress & WooCommerce Mobile App Builder (No-Code Android & iOS App Maker) 3.5.1, at appmysite.php

2,578 lines 87.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Plugin Name: AppMySite
4 * Plugin URI: https://www.appmysite.com
5 * Description: This plugin enables WordPress & WooCommerce users to sync their websites with native iOS and Android apps, created on <a href="https://www.appmysite.com/"><strong>www.appmysite.com</strong></a>
6 * Version: 3.5.1
7 * Author: AppMySite
8 * Text Domain: appmysite
9 * Author URI: https://appmysite.com
10 * Tested up to: 5.9.3
11 * WC tested up to: 6.3.1
12 * WC requires at least: 3.8.0
13 * License: GPL v2 or later
14 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
15 **/
16
17 // If this file is called directly, abort.
18 if ( ! defined( 'WPINC' ) ) {
19 die( 'No script kiddies please!' );
20 }
21
22 /******************************************************************************
23 * Show warning to all where WordPress version is below minimum requirement.
24 */
25
26 global $wp_version;
27 if ( $wp_version <= 4.9 ) {
28 function wo_incompatibility_with_wp_version() {
29 ?>
30 <div class="notice notice-error">
31 <p><?php esc_html_e( 'AppMySite requires that WordPress 4.9 or greater be used. Update to the latest WordPress version.', 'appmysite' ); ?>
32 <a href="<?php echo esc_url( admin_url( 'update-core.php' ) ); ?>"><?php esc_html_e( 'Update Now', 'appmysite' ); ?></a></p>
33 </div>
34 <?php
35 }
36
37 add_action( 'admin_notices', 'wo_incompatibility_with_wp_version' );
38 }
39
40 add_action(
41 'rest_api_init',
42 function () {
43 register_rest_route(
44 'wc/v3',
45 '/ams-get-plugin-info',
46 array(
47 'methods' => 'GET',
48 'callback' => 'ams_get_version_info',
49 'permission_callback' => '__return_true',
50 )
51 );
52 }
53 );
54
55
56 add_action(
57 'rest_api_init',
58 function () {
59 register_rest_route(
60 'wc/v3',
61 '/ams-menu',
62 array(
63 'methods' => 'GET',
64 'callback' => 'ams_get_menu_items',
65 'permission_callback' => '__return_true',
66 )
67 );
68 }
69 );
70
71 add_action(
72 'rest_api_init',
73 function () {
74 register_rest_route(
75 'wc/v3',
76 '/ams-menu-names',
77 array(
78 'methods' => 'GET',
79 'callback' => 'ams_get_menu_names',
80 'permission_callback' => '__return_true',
81 )
82 );
83 }
84 );
85
86 add_action(
87 'rest_api_init',
88 function () {
89 register_rest_route(
90 'wc/v3',
91 '/ams-login',
92 array(
93 'methods' => 'POST',
94 'callback' => 'ams_login',
95 'permission_callback' => '__return_true',
96 )
97 );
98 }
99 );
100
101 add_action(
102 'rest_api_init',
103 function () {
104 register_rest_route(
105 'wc/v3',
106 '/ams-verify-user',
107 array(
108 'methods' => 'POST',
109 'callback' => 'ams_verify_user',
110 'permission_callback' => '__return_true',
111 )
112 );
113 }
114 );
115
116 add_action(
117 'rest_api_init',
118 function () {
119 register_rest_route(
120 'wc/v3',
121 '/ams-profile-meta',
122 array(
123 'methods' => 'GET',
124 'callback' => 'ams_get_profile_meta',
125 'permission_callback' => '__return_true',
126 )
127 );
128 }
129 );
130
131 add_action(
132 'rest_api_init',
133 function () {
134 register_rest_route(
135 'wc/v3',
136 '/ams-order-payment-url',
137 array(
138 'methods' => 'POST',
139 'callback' => 'ams_get_order_payment_url',
140 'permission_callback' => '__return_true',
141 )
142 );
143 }
144 );
145
146 add_action('rest_api_init', function ()
147 {
148 register_rest_route('wc/v3', '/ams-verify-application-password', array(
149 'methods' => 'GET',
150 'callback' => 'ams_verify_application_password',
151 'permission_callback' => function() {
152 return current_user_can('manage_options');
153 },
154 ));
155 });
156
157 add_action('rest_api_init', function ()
158 {
159 register_rest_route('wc/v3', '/ams-wp-get-user-auth-cookies', array(
160 'methods' => 'POST',
161 'callback' => 'ams_wp_get_user_auth_cookies',
162 'permission_callback' => function() {
163 return current_user_can('manage_options');
164 },
165 'args' => array(
166 'user_id' => array(
167 'required' => true,
168 'type' => 'integer',
169 'description' => 'User ID',
170 )
171 ) ,
172 ));
173 });
174
175 add_action(
176 'rest_api_init',
177 function () {
178 register_rest_route(
179 'wc/v3',
180 '/ams-order-total',
181 array(
182 'methods' => 'POST',
183 'callback' => 'ams_get_order_total',
184 'permission_callback' => '__return_true',
185 )
186 );
187 }
188 );
189
190 add_action(
191 'rest_api_init',
192 function () {
193 register_rest_route(
194 'wc/v3',
195 '/ams-send-password-reset-link',
196 array(
197 'methods' => 'POST',
198 'callback' => 'ams_send_password_reset_link',
199 'permission_callback' => '__return_true',
200 )
201 );
202 }
203 );
204
205 add_action(
206 'rest_api_init',
207 function () {
208 register_rest_route(
209 'wc/v3',
210 '/ams-applicable-shipping-method',
211 array(
212 'methods' => 'POST',
213 'callback' => 'ams_applicable_shipping_method',
214 'permission_callback' => '__return_true',
215 )
216 );
217 }
218 );
219
220 add_action(
221 'rest_api_init',
222 function () {
223 register_rest_route(
224 'wc/v3',
225 '/ams-product-search',
226 array(
227 'methods' => 'GET',
228 'callback' => 'ams_product_search',
229 'permission_callback' => '__return_true',
230 )
231 );
232 }
233 );
234
235 add_action(
236 'rest_api_init',
237 function () {
238 register_rest_route(
239 'wc/v3',
240 '/ams-product-attributes',
241 array(
242 'methods' => 'GET',
243 'callback' => 'ams_product_attributes',
244 'permission_callback' => '__return_true',
245 )
246 );
247 }
248 );
249
250 add_action(
251 'rest_api_init',
252 function () {
253 register_rest_route(
254 'wc/v3',
255 '/ams-verify-cart-items',
256 array(
257 'methods' => 'POST',
258 'callback' => 'ams_verify_cart_items',
259 'permission_callback' => '__return_true',
260 )
261 );
262 }
263 );
264
265 add_action(
266 'rest_api_init',
267 function () {
268 register_rest_route(
269 'wc/v3',
270 '/ams-categories',
271 array(
272 'methods' => 'GET',
273 'callback' => 'ams_categories',
274 'permission_callback' => '__return_true',
275 )
276 );
277 }
278 );
279
280 add_action(
281 'rest_api_init',
282 function () {
283 register_rest_route(
284 'wc/v3',
285 '/ams-post-categories',
286 array(
287 'methods' => 'GET',
288 'callback' => 'ams_post_categories',
289 'permission_callback' => '__return_true',
290 )
291 );
292 }
293 );
294
295 add_action(
296 'rest_api_init',
297 function () {
298 register_rest_route(
299 'wc/v3',
300 '/ams-checkout-fields',
301 array(
302 'methods' => 'GET',
303 'callback' => 'ams_checkout_fields',
304 'permission_callback' => '__return_true',
305 )
306 );
307 }
308 );
309
310 add_action(
311 'rest_api_init',
312 function () {
313 register_rest_route(
314 'wc/v3',
315 '/ams-wc-points-rewards-effective-discount',
316 array(
317 'methods' => 'POST',
318 'callback' => 'ams_wc_points_rewards_effective_discount',
319 'permission_callback' => '__return_true',
320 'args' => array(
321 'line_items' => array(
322 'required' => true,
323 'type' => 'array',
324 'description' => 'Cart items',
325 ),
326 'customer_id' => array(
327 'required' => true,
328 'type' => 'integer',
329 'description' => 'Customer ID',
330 ),
331 'wc_points_rewards_discount_amount' => array(
332 'required' => true,
333 'type' => 'number',
334 'description' => 'Requested user discount',
335 ),
336 ),
337 )
338 );
339 }
340 );
341
342 add_action(
343 'rest_api_init',
344 function () {
345 register_rest_route(
346 'wc/v3',
347 '/ams-wc-points-rewards-settings',
348 array(
349 'methods' => 'GET',
350 'callback' => 'ams_wc_points_rewards_settings',
351 'permission_callback' => '__return_true',
352 )
353 );
354 }
355 );
356
357 add_action(
358 'rest_api_init',
359 function () {
360 register_rest_route(
361 'wc/v3',
362 '/ams-change-password',
363 array(
364 'methods' => 'POST',
365 'callback' => 'ams_change_password',
366 'permission_callback' => '__return_true',
367 'args' => array(
368
369 'customer_id' => array(
370 'required' => true,
371 'type' => 'integer',
372 'description' => 'Customer ID',
373 ),
374 'old_password' => array(
375 'required' => true,
376 'type' => 'text',
377 'description' => 'Old Password',
378 ),
379 'new_password' => array(
380 'required' => true,
381 'type' => 'text',
382 'description' => 'New Password',
383 ),
384 'confirm_password' => array(
385 'required' => true,
386 'type' => 'text',
387 'description' => 'New Password',
388 ),
389 )
390 )
391 );
392 }
393 );
394
395 /******
396 * Load customer payment page without the need of customer login.
397 */
398
399 add_filter( 'user_has_cap', 'ams_allow_payment_without_login', 10, 3 );
400 function ams_allow_payment_without_login( $allcaps, $caps, $args ) {
401
402 if ( ! isset( $caps[0] ) || $caps[0] != 'pay_for_order' ) {
403 return $allcaps;
404 }
405 if ( ! isset( $_GET['key'] ) ) {
406 return $allcaps;
407 }
408 $order = wc_get_order( $args[2] );
409 if ( ! $order ) {
410 return $allcaps;
411 }
412 $order_key = $order->get_order_key();
413 $order_key_check = sanitize_text_field( wp_unslash( $_GET['key'] ) );
414 $allcaps['pay_for_order'] = ( $order_key == $order_key_check );
415 return $allcaps;
416 }
417 /******
418 * Add Default Catalog Orderby Settings in the setting API .
419 */
420 add_filter( 'woocommerce_get_settings_products', 'add_subtab_settings', 10, 2 );
421 function add_subtab_settings( $settings ) {
422 $current_section = get_option( 'woocommerce_default_catalog_orderby' );
423
424 if ( isset( $current_section ) ) {
425 $settings[] = array(
426 'name' => __( 'AMS WC Default Catalog Orderby Settings', 'woocommerce' ),
427 'id' => 'woocommerce_default_catalog_orderby',
428 'label' => 'Woocommerce Default Catalog Orderby',
429 'type' => 'select',
430 'desc' => __( 'This setting determines the sorting order of products in the catalog.', 'woocommerce' ),
431 'desc_tip' => true,
432 'options' => array(
433 'price' => __( 'Sort by price (asc)', 'woocommerce' ),
434 'date' => __( 'Sort by most recent', 'woocommerce' ),
435 'rating' => __( 'Average rating', 'woocommerce' ),
436 'popularity' => __( 'Popularity (sales)', 'woocommerce' ),
437 'menu_order' => __( 'Default sorting (custom ordering + name)', 'woocommerce' ),
438 'price-desc' => __( 'Sort by price (desc)', 'woocommerce' ),
439 ),
440 'default' => '',
441 'value' => get_option( 'woocommerce_default_catalog_orderby' ),
442
443 );
444 return $settings;
445 } else {
446 return $settings; // If not, return the standard settings
447 }
448 }
449
450 /******
451
452 * Adds post's featured media to REST API.
453 */
454
455 register_rest_field(
456 'post',
457 'featured_image_src',
458 array(
459 'get_callback' => 'ams_get_image_src',
460 'update_callback' => null,
461 'schema' => null,
462 )
463 );
464
465 add_action( 'rest_api_init', 'ams_register_rest_field_for_custom_post_type' );
466
467 function ams_register_rest_field_for_custom_post_type(){
468 $ams_custom_post_types = array_values(get_post_types(array('public' => true,'exclude_from_search' => false,'_builtin' => false),'names','and'));
469 if (($key = array_search('product', $ams_custom_post_types)) !== false) { // We don't need this field for products
470 unset($ams_custom_post_types[$key]);
471 }
472 register_rest_field(
473 $ams_custom_post_types, //['product','course','projects']
474 'featured_image_src',
475 array(
476 'get_callback' => 'ams_get_image_src',
477 'update_callback' => null,
478 'schema' => null,
479 )
480 );
481 }
482
483 function ams_get_image_src( $object, $field_name, $request ) {
484 $feat_img_array = wp_get_attachment_image_src(
485 $object['featured_media'], // Image attachment ID
486 'large', // Size. Ex. "thumbnail", "large", "full", etc..
487 false // Whether the image should be treated as an icon.
488 );
489 return $feat_img_array[0];
490 }
491 function ams_get_version_info( WP_REST_Request $request ){
492
493 if ( ! function_exists( 'plugins_api' ) ) {
494 require_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );
495 }
496
497 if( ! function_exists( 'get_plugin_data' ) ) {
498 require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
499 }
500 $version_current = get_plugin_data( __FILE__ )['Version'];
501
502 $args = array(
503 'slug' => 'appmysite',
504 'fields' => array(
505 'version' => true,
506 )
507 );
508
509 $call_api = plugins_api( 'plugin_information', $args );
510
511 if ( is_wp_error( $call_api ) ) {
512
513 $api_error = $call_api->get_error_message();
514
515 return( rest_ensure_response([
516 "AMS_PLUGIN_LATEST_VERSION"=>"0.0.0",
517 "AMS_PLUGIN_CURRENT_VERSION"=>"0.0.0"
518 ]));
519 } else {
520
521 if ( ! empty( $call_api->version ) ) {
522
523 $version_latest = $call_api->version;
524 return( rest_ensure_response( ["AMS_PLUGIN_LATEST_VERSION"=>$version_latest,
525 "AMS_PLUGIN_CURRENT_VERSION"=>$version_current] ) );
526 }
527
528 }
529
530 }
531
532 function ams_verify_application_password( WP_REST_Request $request ) {
533
534 $user = get_user_by( 'ID', apply_filters('determine_current_user', false) ); // | User by ID
535 if ( isset( $user->errors ) ) {
536 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
537 $error = new WP_Error();
538 $error->add( 'message', __( $error_message . '' ) );
539 return $error;
540 } elseif ( isset( $user->data ) ) {
541 $user->data->user_pass = '';
542 $user->data->user_activation_key = '';
543 $user->data->id = $user->ID; //integer
544 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
545 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
546 $user->data->roles = $user->roles;
547 ####get user wp_generate_auth_cookie####
548
549 ########################################
550 return rest_ensure_response( $user->data );
551 } else {
552 return new WP_Error('ams_error', 'Something went wrong. Please contact support.', array('status' => 500));
553 }
554 }
555
556
557
558 /******
559
560 * Adds post's medium & large media to REST API.
561 */
562
563 register_rest_field(
564 'post',
565 'blog_images',
566 array(
567 'get_callback' => 'ams_get_images_urls',
568 'update_callback' => null,
569 'schema' => null,
570 )
571 );
572
573 function ams_get_images_urls( $object, $field_name, $request ) {
574 $medium = wp_get_attachment_image_src( get_post_thumbnail_id( $object['id'] ), 'medium' );
575 $medium_url = $medium['0'];
576
577 $large = wp_get_attachment_image_src( get_post_thumbnail_id( $object['id'] ), 'large' );
578 $large_url = $large['0'];
579
580 return array(
581 'medium' => $medium_url,
582 'large' => $large_url,
583 );
584 }
585
586 /******
587
588 * Get default variant in rest api.
589 */
590 register_rest_field(
591 'product',
592 'ams_default_variation_id',
593 array(
594 'get_callback' => 'ams_get_default_variant',
595 'update_callback' => null,
596 'schema' => null,
597 )
598 );
599 function ams_get_default_variant( $object, $field_name, $request ) {
600
601 $product = wc_get_product( $object['id'] );
602 if ( $product->is_type( 'variable' ) ) {
603 $default_attributes = $product->get_default_attributes();
604 if ( ! empty( $default_attributes ) ) {
605 foreach ( $product->get_available_variations() as $variation_values ) {
606 foreach ( $variation_values['attributes'] as $key => $attribute_value ) {
607 $attribute_name = str_replace( 'attribute_', '', $key );
608 $default_value = $product->get_variation_default_attribute( $attribute_name );
609 if ( $default_value == $attribute_value ) {
610 $is_default_variation = true;
611 } else {
612 $is_default_variation = false;
613 break;
614 }
615 }
616 if ( $is_default_variation ) {
617 $variation_id = $variation_values['variation_id'];
618 break;
619 }
620 }
621 return $variation_id;
622 } else {
623 return 0;
624 }
625 } else {
626 return 0;
627 }
628
629 }
630
631 register_rest_field(
632 ['product','product_variation'],
633 'ams_product_points_reward',
634 array(
635 'get_callback' => 'ams_get_product_points_reward',
636 'update_callback' => null,
637 'schema' => null,
638 )
639 );
640 function ams_get_product_points_reward( $object, $field_name, $request ) {
641
642 $product = wc_get_product( $object['id'] );
643 $product_id = $object['id'];
644
645 if ( ! is_admin() && ! $product->is_type( 'variable' ) ) {
646 $_wc_max_points_earned = get_post_meta( $product_id, '_wc_max_points_earned' );
647 $_wc_min_points_earned = get_post_meta( $product_id, '_wc_min_points_earned' );
648 return get_post_meta( $product_id, '_wc_min_points_earned' );
649
650 } else {
651 return get_post_meta( $product_id, '_wc_points_earned' );
652 }
653
654 }
655
656 /******
657
658 * Get discout percentage in rest api
659 */
660 register_rest_field(
661 'product',
662 'ams_product_discount_percentage',
663 array(
664 'get_callback' => 'ams_get_product_discount_percentage',
665 'update_callback' => null,
666 'schema' => null,
667 )
668 );
669 function ams_get_product_discount_percentage( $object, $field_name, $request ) {
670
671 $product = wc_get_product( $object['id'] );
672 if ( $product->is_on_sale() && ! is_admin() && ! $product->is_type( 'variable' ) ) {
673 $regular_price = (float) $product->get_regular_price(); // Regular price
674 $sale_price = (float) $product->get_price();
675 $saving_price = wc_price( $regular_price - $sale_price );
676 $precision = 2;
677 $discount_percentage = round( 100 - ( $sale_price / $regular_price * 100 ), 2 );
678 return $discount_percentage;
679 } else {
680 return 0.00;
681 }
682
683 }
684
685 /******
686 * Added product display price in rest API to support show price inclusive/exclusive of tax.
687 ******/
688
689 register_rest_field(
690 ['product','product_variation'],
691 'ams_price_to_display',
692 array(
693 'get_callback' => 'ams_get_product_price_to_display',
694 'update_callback' => null,
695 'schema' => null,
696 )
697 );
698 function ams_get_product_price_to_display( $object, $field_name, $request ) {
699
700 $product = wc_get_product( $object['id'] );
701 $ams_price_to_display = wc_get_price_to_display($product,[]);
702 return $ams_price_to_display;
703
704 }
705
706 /******
707 * users_can_register settings for wordpress APIs
708 ******/
709
710 add_action('rest_api_init', function ()
711 {
712 register_setting('general', 'ams_users_can_register', array(
713 'show_in_rest' => true,
714 'type' => 'boolean',
715 'default' => get_option( 'users_can_register' )
716 ));
717 });
718
719 /******
720
721 * This adds product's thumbnail and medium images in the rest api for catalog listing.
722 ******/
723
724 function ams_prepare_product_images( $response, $post, $request ) {
725 global $_wp_additional_image_sizes;
726
727 if ( empty( $response->data ) ) {
728 return $response;
729 }
730 if (is_array($response->data['images']) || is_object($response->data['images'])) {
731 foreach ( $response->data['images'] as $key => $image ) {
732 $image_info = wp_get_attachment_image_src( $image['id'], 'thumbnail' );
733 $response->data['images'][ $key ]['thumbnail'] = $image_info[0];
734 $image_info = wp_get_attachment_image_src( $image['id'], 'medium' );
735 $response->data['images'][ $key ]['medium'] = $image_info[0];
736 }
737 }
738 return $response;
739
740 }
741 add_filter( 'woocommerce_rest_prepare_product_object', 'ams_prepare_product_images', 10, 3 );
742
743
744 /******
745
746 * Provision for coupon in rest api. This modifies order by applying coupon immediately after creating the order.
747 * Adds checkout payment url in rest order api.
748 * Adds thumbnail image of product in get order api
749 */
750
751 add_filter( 'woocommerce_rest_prepare_shop_order_object', 'ams_rest_apply_coupon', 10, 3 );
752
753 function ams_rest_apply_coupon( $response, $object, $request ) {
754 // this section is to apply coupon
755 // If Reward point plugin is enabled #################
756 if ( in_array(
757 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
758 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
759 )
760 ) {
761 $already_redeemed = get_post_meta( $response->data['id'], '_wc_points_redeemed', true );
762 $order = wc_get_order( $response->data['id'] );
763 $wc_points_rewards_discount_amount = $order->get_meta( '_ams_wc_points_redeemed' );
764 if ( !empty( $wc_points_rewards_discount_amount )&& (int)$wc_points_rewards_discount_amount>0){
765 $customer_id = $request->get_param( 'customer_id' );
766 $line_items = $request->get_param( 'line_items' );
767 $reward_amount = ams_get_points_rewards_discount_amount( $customer_id, $wc_points_rewards_discount_amount, $line_items ); // to be calculated
768 $reward_coupon_code = sprintf( 'wc_points_redemption_%s_%s_@%u', $customer_id, date( 'Y_m_d_h_i', current_time( 'timestamp' ) ), $reward_amount );
769 // get actual point to be logged on the basis of allowed reward amount.
770 $actual_points_to_redeemed = WC_Points_Rewards_Manager::calculate_points_for_discount( $reward_amount );
771
772 // update_post_meta for reference
773 if ( empty( $already_redeemed ) && $reward_amount > 0 ) {
774 $results = $order->apply_coupon( $reward_coupon_code );
775 update_post_meta( $response->data['id'], '_ams_wc_points_redeemed', $actual_points_to_redeemed );
776 update_post_meta( $response->data['id'], '_ams_wc_points_rewards_discount_code', $reward_coupon_code );
777 update_post_meta( $response->data['id'], '_ams_wc_points_rewards_discount_amount', $reward_amount );
778
779 }
780 }
781 }
782 // If Reward point plugin is enabled #################
783
784 if ( ! empty( $request->get_param( 'coupon_lines' ) ) ) {
785 foreach ( $request->get_param( 'coupon_lines' ) as $item ) {
786 if ( is_array( $item ) ) {
787 if ( isset( $item['id'] ) ) {
788 if ( ! isset( $item['code'] ) ) {
789 throw new WC_REST_Exception( 'woocommerce_rest_invalid_coupon', __( 'Coupon code is required.', 'woocommerce' ), 400 );
790 }
791 $order = wc_get_order( $response->data['id'] );
792 $results = $order->apply_coupon( wc_clean( $item['code'] ) );
793
794 if ( is_wp_error( $results ) ) {
795 throw new WC_REST_Exception( 'woocommerce_rest_' . $results->get_error_code(), $results->get_error_message(), 400 );
796 }
797 return $response;
798 }
799 }
800 }
801 }
802 // this section is to add extra field into order api
803 $ams_order_checkout_url = ( $value = esc_url( $object->get_checkout_payment_url() ) ) ? $value : '';
804 $response->data['order_checkout_payment_url'] = html_entity_decode( $ams_order_checkout_url );
805 if ( ! empty( $response->data['line_items'] ) ) {
806 foreach ( $response->data['line_items'] as $key => $lineItem ) {
807 $product_id = $lineItem['product_id'];
808 $medium_url = wp_get_attachment_image_src( get_post_thumbnail_id( $product_id ), 'thumbnail' );
809 $response->data['line_items'][ $key ]['ams_order_thumbnail'] = $medium_url[0];
810 }
811 }
812
813 return $response;
814
815 }
816
817
818 /******
819
820 * Get all menu names.
821 ******/
822
823 function ams_get_menu_names() {
824
825 $nav_menu_locations = wp_get_nav_menus();
826 $result = [];
827 foreach((array)$nav_menu_locations as $item){
828 $result[$item->slug]=$item->term_id;
829 }
830 return( rest_ensure_response( $result ) );
831
832 }
833
834 /******
835
836 * Get all items of given menu.
837 ******/
838
839 function ams_get_menu_items( WP_REST_Request $request ) {
840
841 $menu_name = 'primary-menu'; // primary-menu, top
842
843 if ( isset( $request['menu_name'] ) ) {
844 $menu_name = $request['menu_name'];
845 }
846 $nav_menu_items = wp_get_nav_menu_items( $menu_name ); //slug,id
847 return( rest_ensure_response( $nav_menu_items ) );
848
849 }
850
851 /******
852
853 * Get all product and post categories in a binary tree.
854 ******/
855 function ams_categories() {
856
857 $orderby = 'name';
858 $order = 'asc';
859 $hide_empty = true;
860 $cat_args = array(
861 'orderby' => $orderby,
862 'order' => $order,
863 'hide_empty' => $hide_empty,
864 );
865
866 $product_categories = array_values( get_terms( 'product_cat', $cat_args ) );
867 $array_product_categories_items = json_decode( json_encode( $product_categories ), true );
868 if ( empty( $array_product_categories_items ) ) {
869 return rest_ensure_response( $array_product_categories_items );
870 }
871 $category_tree = ams_build_category_tree( $array_product_categories_items, 'parent', 'term_id' );
872 return rest_ensure_response( $category_tree );
873
874 }
875
876 function ams_post_categories() {
877
878 $orderby = 'name';
879 $order = 'asc';
880 $hide_empty = true;
881 $cat_args = array(
882 'orderby' => $orderby,
883 'order' => $order,
884 'hide_empty' => $hide_empty,
885 );
886
887 $product_categories = array_values( get_terms( 'category', $cat_args ) );
888 $array_product_categories_items = json_decode( json_encode( $product_categories ), true );
889 if ( empty( $array_product_categories_items ) ) {
890 return rest_ensure_response( $array_product_categories_items );
891 }
892 $category_tree = ams_build_category_tree( $array_product_categories_items, 'parent', 'term_id' );
893 return rest_ensure_response( $category_tree );
894
895 }
896
897
898 /******
899
900 * Cart items verification
901 ******/
902
903 function ams_verify_cart_items( WP_REST_Request $request ) {
904
905 $params = $request->get_params();
906 $validate = ams_basic_validate( $params, array( 'line_items' ) );
907 if ( $validate != true ) {
908 return $validate;
909 }
910
911 $line_items = $params['line_items'];
912 $result = array();
913 foreach ( $line_items as $key => $value ) {
914 if ( array_key_exists( 'variation_id', $value ) ) {
915
916 $variation = wc_get_product( $value['variation_id'] );
917
918 if ( $variation ) {
919 $result[ $key ]['product_id'] = $variation->get_id();
920 $result[ $key ]['variation_id'] = $value['variation_id'];
921 $result[ $key ]['name'] = $variation->get_name();
922 $result[ $key ]['type'] = $variation->get_type();
923 $result[ $key ]['status'] = $variation->get_status();
924 $result[ $key ]['price'] = $variation->get_price();
925 $result[ $key ]['regular_price'] = $variation->get_regular_price();
926 $result[ $key ]['sale_price'] = $variation->get_sale_price();
927 $result[ $key ]['manage_stock'] = $variation->get_manage_stock();
928 $result[ $key ]['stock_quantity'] = $variation->get_stock_quantity();
929 if ( $result[ $key ]['stock_quantity'] == null ) {
930 $result[ $key ]['stock_quantity'] = '';
931 }
932 $result[ $key ]['stock_status'] = $variation->get_stock_status();
933 $result[ $key ]['on_sale'] = $variation->is_on_sale();
934 if ( 1 == $result[ $key ]['on_sale'] ) {
935
936 $result[ $key ]['on_sale'] = true;
937 } else {
938 $result[ $key ]['on_sale'] = false;
939 }
940 }
941 } else {
942 // get product details
943 $product = wc_get_product( $value['product_id'] );
944 if ( $product ) {
945 $result[ $key ]['product_id'] = $product->get_id();
946 $result[ $key ]['name'] = $product->get_name();
947 $result[ $key ]['type'] = $product->get_type();
948 $result[ $key ]['status'] = $product->get_status();
949 $result[ $key ]['get_price'] = $product->get_price();
950 $result[ $key ]['get_regular_price'] = $product->get_regular_price();
951 $result[ $key ]['get_sale_price'] = $product->get_sale_price();
952 $result[ $key ]['manage_stock'] = $product->get_manage_stock();
953 $result[ $key ]['stock_quantity'] = $product->get_stock_quantity();
954 if ( $result[ $key ]['stock_quantity'] == null ) {
955 $result[ $key ]['stock_quantity'] = '';
956 }
957 $result[ $key ]['stock_status'] = $product->get_stock_status();
958 $result[ $key ]['on_sale'] = $product->is_on_sale();
959 if ( 1 == $result[ $key ]['on_sale'] ) {
960 $result[ $key ]['on_sale'] = true;
961 } else {
962 $result[ $key ]['on_sale'] = false;
963 }
964 }
965 }
966 }
967
968 return rest_ensure_response( array( 'line_items' => $result ) );
969 }
970
971
972 add_action( 'pre_get_posts', 'ams_catalog_hidden_products_search_query_fix' );
973
974 function ams_catalog_hidden_products_search_query_fix( $query = false ) {
975 if ( ! is_admin() && isset( $query->query['post_type'] ) && $query->query['post_type'] === 'product' ) {
976 $tax_query = $query->get( 'tax_query' );
977 if(!is_array($tax_query)){$tax_query=[];}
978 array_push($tax_query,[
979 'taxonomy' => 'product_visibility',
980 'field' => 'name',
981 'terms' => 'exclude-from-catalog',
982 'operator' => 'NOT IN',
983 ]);
984 array_push($tax_query,[
985 'taxonomy' => 'product_visibility',
986 'field' => 'name',
987 'terms' => 'exclude-from-catalog',
988 'operator' => '!=',
989 ]);
990 $tax_query['relation']='AND';
991 $query->set( 'tax_query', $tax_query );
992 }
993 }
994
995 /******
996
997 * Search API with support of multiple sort and order_by parameters .
998 ******/
999 function ams_product_search( WP_REST_Request $request ) {
1000
1001 $param = $request->get_params();
1002 $category = $param['category'];
1003 $filters = $param['filter'];
1004 $per_page = $param['per_page'];
1005 $page = $param['page'];
1006 $order = $param['order'];
1007 $orderby = $param['orderby'];
1008 $featured = $param['featured'];
1009 $on_sale = $param['on_sale'];
1010 $min_price = $param['min_price'];
1011 $max_price = $param['max_price'];
1012 $stock_status = $param['stock_status'];
1013 $output = array();
1014 // Use default arguments.
1015 $args = array(
1016 'post_type' => 'product',
1017 'posts_per_page' => get_option( 'posts_per_page' ),
1018 'post_status' => 'publish',
1019 'paged' => 1,
1020
1021 );
1022 // Posts per page.
1023 if ( ! empty( $per_page ) ) {
1024 $args['posts_per_page'] = $per_page;
1025 }
1026 // Pagination, starts from 1.
1027 if ( ! empty( $page ) ) {
1028 $args['paged'] = $page;
1029 }
1030
1031 // Order condition. ASC/DESC.
1032 if ( ! empty( $order ) ) {
1033 $args['order'] = $order;
1034 }
1035 // Order condition. ASC/DESC.
1036 if ( ! empty( $orderby ) ) {
1037 if ( $orderby == 'price' ) {
1038 $args['orderby'] = 'meta_value_num';
1039 $args['meta_key'] = '_price';
1040
1041 } elseif ( $orderby == 'popularity' ) { // For Popularity case, the sort order will always be desc.
1042 $args['orderby'] = 'meta_value_num';
1043 $args['meta_key'] = 'total_sales';
1044
1045 } else {
1046 $args['orderby'] = $orderby;
1047 }
1048 }
1049
1050 if ( ! empty( $featured ) ) {
1051 if ( $featured == true ) {
1052 $args['tax_query'][] = array(
1053 'taxonomy' => 'product_visibility',
1054 'field' => 'name',
1055 'terms' => 'featured',
1056 );
1057 }
1058 }
1059
1060 if ( ! empty( $on_sale ) ) {
1061 if ( $on_sale == true ) {
1062
1063 $args['meta_query'][] = array(
1064 'key' => '_sale_price',
1065 'value' => 0,
1066 'compare' => '>',
1067 'type' => 'numeric',
1068 );
1069 }
1070 }
1071 if ( ! empty( $stock_status ) ) {
1072 $args['meta_query'][] = array(
1073 'key' => '_stock_status',
1074 'value' => $stock_status,
1075 );
1076 }
1077 if ( isset( $min_price ) || isset( $max_price ) ) {
1078
1079 $price_request = array();
1080 if ( isset( $min_price ) ) {
1081 $price_request['min_price'] = $min_price;
1082 }
1083
1084 if ( isset( $max_price ) ) {
1085 $price_request['max_price'] = $max_price;
1086 }
1087 $args['meta_query'][] = wc_get_min_max_price_meta_query( $price_request );
1088 }
1089
1090 if ( ! empty( $category ) || ! empty( $filters ) ) {
1091
1092 $args['tax_query']['relation'] = 'AND';
1093 if ( ! empty( $category ) ) {
1094 $args['tax_query'][] = array(
1095 'taxonomy' => 'product_cat',
1096 'field' => 'id',
1097 'terms' => explode( ',', $category ), // [ $category ],
1098 'include_children' => true,
1099 );
1100 }
1101
1102 if ( ! empty( $filters ) ) {
1103 foreach ( $filters as $filter_key => $filter_value ) {
1104 if ( $filter_key === 'min_price' || $filter_key === 'max_price' ) {
1105 continue;
1106 }
1107 $args['tax_query'][] = array(
1108 'taxonomy' => $filter_key,
1109 'field' => 'term_id',
1110 'terms' => explode( ',', $filter_value ),
1111 );
1112 }
1113 }
1114 }
1115
1116 $the_query = new \WP_Query( $args );
1117
1118 if ( ! $the_query->have_posts() ) {
1119 return $output;
1120 }
1121 while ( $the_query->have_posts() ) {
1122 $the_query->the_post();
1123 $product_ids[] = $the_query->post->ID;
1124 $output[] = get_the_title();
1125 }
1126 wp_reset_postdata();
1127
1128 $request = new WP_REST_Request( 'GET', '/wc/v3/products' );
1129 $parameters = array( 'include' => $product_ids );
1130 if ( ! empty( $order ) ) {
1131 $parameters += array( 'order' => $order );
1132 }
1133 if ( ! empty( $orderby ) ) {
1134 $parameters += array( 'orderby' => $orderby );
1135 }
1136 if ( ! empty( $per_page ) ) {
1137 $parameters += array( 'per_page' => $per_page );
1138 }
1139 $request->set_query_params( $parameters );
1140 $response = rest_do_request( $request );
1141 $server = rest_get_server();
1142 $data = $server->response_to_data( $response, false );
1143 return rest_ensure_response( $data );
1144 }
1145
1146
1147 function ams_product_attributes( WP_REST_Request $request ) {
1148
1149 $param = $request->get_params();
1150
1151 $args = array(
1152 'status' => 'publish',
1153 'limit' => -1
1154 );
1155
1156 if(isset( $param['category'] )){
1157 $cat_name = get_term($param['category'], 'product_cat', ARRAY_A );
1158
1159 if(is_wp_error( $cat_name) ){
1160 status_header( 400 );
1161 echo ( json_encode(
1162 array(
1163 'message' => 'There is a problem with your input.',
1164 'error' => $cat_name->get_error_message(),
1165 ),
1166 JSON_UNESCAPED_UNICODE
1167 ) );
1168 die();
1169 }
1170 $args['category'] = array($cat_name['slug'] );
1171 }
1172
1173 if(isset( $param['stock_status'] )){
1174 $args['stock_status'] = $param['stock_status'];
1175 }
1176
1177 if(isset( $param['featured'] )){
1178 $args['featured'] = $param['featured'];
1179 }
1180
1181 if(isset( $param['on_sale'] )){
1182 $args['on_sale'] = $param['on_sale'];
1183 }
1184
1185 $result = [];
1186
1187 $filter_raw = array();
1188 $attrs_raw = wc_get_attribute_taxonomy_names();
1189 foreach( wc_get_products($args) as $product ){
1190 foreach( $product->get_attributes() as $attr_name => $attr ){
1191 $filter_raw[] = $attr_name;
1192 if(is_array($attr->get_terms())){
1193 foreach( $attr->get_terms() as $term ){
1194 $terms_raw[] = $term->name;
1195 }
1196 }
1197 }
1198 }
1199 $filters = array_unique(array_intersect((array)$filter_raw,(array)$attrs_raw));
1200
1201 if(is_array($filters)){
1202 foreach ( $filters as $key=>$filter ){
1203 $terms = get_terms( $filter );
1204 if ( ! empty( $terms ) ) {
1205
1206 $result[$key] = array(
1207 'id' => $filter,
1208 'label' => wc_attribute_label( $filter ) , //$this->decode_html
1209 );
1210 foreach ( $terms as $term ) {
1211 if(in_array($term->name,$terms_raw)){
1212 $result[$key]['values'][] = array(
1213 'label' => $term->name ,
1214 'value' => $term->slug,
1215 'term_id' => $term->term_id,
1216 'count' => $term->count,
1217 );
1218 }
1219 }
1220 }
1221 }
1222 }
1223
1224 return( rest_ensure_response( array_values($result )) );
1225
1226 }
1227
1228 /******
1229
1230 * Authenticate the user.
1231 ******/
1232
1233 function ams_login( WP_REST_Request $request ) {
1234
1235 $req = $request->get_json_params();
1236
1237 $validate = ams_basic_validate( $req, array( 'username', 'password' ) );
1238 if ( $validate != true ) {
1239 return $validate;
1240 }
1241 $wp_version = get_bloginfo( 'version' );
1242 $user = wp_authenticate( sanitize_email( $req['username'] ), sanitize_text_field( $req['password'] ) ); // htmlspecialchars
1243
1244 if ( isset( $user->errors ) ) {
1245 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1246 $error = new WP_Error();
1247 $error->add( 'message', __( $error_message . '' ) );
1248 return $error;
1249 } elseif ( isset( $user->data ) ) {
1250 $user->data->user_pass = '';
1251 $user->data->user_activation_key = '';
1252 $user->data->id = $user->ID; //integer
1253 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1254 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1255 $user->data->roles = $user->roles;
1256 $user->data->wp_version = $wp_version;
1257 return rest_ensure_response( $user->data );
1258 } else {
1259 return new WP_Error('ams_error', 'Something went wrong. Please contact support.', array('status' => 500));
1260 }
1261 }
1262
1263
1264 /******
1265
1266 * Verify the user.
1267 ******/
1268 function ams_verify_user( WP_REST_Request $request ) {
1269
1270 $req = $request->get_json_params();
1271
1272 $validate = ams_basic_validate( $req, array( 'username' ) );
1273 if ( $validate != true ) {
1274 return $validate;
1275 }
1276
1277 $is_email = is_email($req['username']);
1278 if(!$is_email){
1279 $user = get_user_by( 'login', $req['username'] ); // | ID | slug | email | login.
1280 }else{
1281 $user = get_user_by( 'email', $req['username'] ); // | ID | slug | email | login.
1282 }
1283
1284 if ( isset( $user->errors ) ) {
1285 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1286 $error = new WP_Error();
1287 $error->add( 'message', __( $error_message . '' ) );
1288 return $error;
1289 } elseif ( isset( $user->data ) ) {
1290 $user->data->user_pass = '';
1291 $user->data->user_activation_key = '';
1292 $user->data->id = $user->ID; //integer
1293 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1294 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1295 $user->data->roles = $user->roles;
1296 return rest_ensure_response( $user->data );
1297 } else {
1298 return rest_ensure_response( array() ); // User not found.
1299 }
1300
1301 }
1302
1303 function ams_get_profile_meta( WP_REST_Request $request ) {
1304
1305 if ( isset( $request['id'] ) ) {
1306 $user_id = sanitize_text_field( $request['id'] );
1307 }
1308 $validate = ams_basic_validate( $req, array( 'id' ) );
1309 if ( $validate != true ) {
1310 return $validate;
1311 }
1312 $user_meta_data = get_user_meta( $user_id, 'wp_user_avatar', true );
1313 $profile_image_full_path = wp_get_attachment_image_src( $user_meta_data );
1314 return rest_ensure_response( array( 'wp_user_avatar' => $profile_image_full_path ) );
1315 }
1316
1317 /******
1318
1319 * get check out payment url.
1320 * Note: This will be removed in next vesrion.
1321 ******/
1322 function ams_get_order_payment_url( WP_REST_Request $request ) {
1323
1324 $req = $request->get_json_params();
1325 $validate = ams_basic_validate( $req, array( 'order_id' ) );
1326 if ( $validate != true ) {
1327 return $validate;
1328 }
1329 $order_id = sanitize_text_field( $req['order_id'] );
1330 $order = wc_get_order( $order_id ); // Returns WC_Product|null|false
1331 if ( ! isset( $order ) || $order == false ) {
1332 $error = new WP_Error();
1333 $error->add( 'message', __( 'The order ID appears to be invalid. Please try again.' ) );
1334 return $error;
1335 } // Verify Valid Order ID
1336 $pay_now_url = esc_url( $order->get_checkout_payment_url() );
1337 return( rest_ensure_response( html_entity_decode( $pay_now_url ) ) );
1338 }
1339
1340 function ams_wp_get_user_auth_cookies( WP_REST_Request $request ) {
1341
1342 $user_id = sanitize_text_field($request->get_param('user_id'));
1343 $user = get_user_by( 'ID', $user_id ); // | ID | slug | email | login.
1344 if ( isset( $user->errors ) ) {
1345 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1346 $error = new WP_Error();
1347 $error->add( 'message', __( $error_message . '' ) );
1348 return $error;
1349 } elseif ( isset( $user->data ) ) {
1350 $user->data->user_pass = '';
1351 $user->data->user_activation_key = '';
1352 $user->data->id = $user->ID; //integer
1353 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1354 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1355 $user->data->roles = $user->roles;
1356 ####get user wp_generate_auth_cookie####
1357 $expiration = time() + apply_filters('auth_cookie_expiration', 14 * DAY_IN_SECONDS , $user->ID, true);
1358 $site_url = get_site_url();//get_site_option('site_url');
1359 if($site_url){$cookie_hash=md5($site_url);}else{$cookie_hash='';}
1360 $user->data->expiration = $expiration;
1361 //$user->data->expire = $expiration + ( 12 * HOUR_IN_SECONDS );
1362 $user->data->cookie_hash = $cookie_hash;
1363 $user->data->wordpress_logged_in_ = wp_generate_auth_cookie($user->ID, $expiration, 'logged_in');
1364 $user->data->wordpress_ = wp_generate_auth_cookie($user->ID, $expiration, 'secure_auth');
1365 ########################################
1366 return rest_ensure_response( $user->data );
1367 } else {
1368 return new WP_Error('ams_error', 'Something went wrong. Please contact support.', array('status' => 500));
1369 }
1370 }
1371
1372 /******
1373
1374 * Sends rest password link on user's email.
1375 ******/
1376
1377 function ams_send_password_reset_link( WP_REST_Request $request ) {
1378 $req = $request->get_json_params();
1379 $validate = ams_basic_validate( $req, array( 'email' ) );
1380 if ( $validate != true ) {
1381 return $validate;
1382 }
1383 $email = sanitize_email( $req['email'] );
1384 $user = get_user_by( 'email', $email );
1385 if ( ! $user ) {
1386 $error = new WP_Error();
1387 $error->add( 'message', __( 'The email address appears to be incorrect. Please try again.' ) );
1388 return $error;
1389 }
1390 $firstname = $user->first_name;
1391 $email = $user->user_email;
1392 $adt_rp_key = get_password_reset_key( $user );
1393 $user_login = $user->user_login;
1394 $rp_link = '<a href="' . wp_lostpassword_url() . "?key=$adt_rp_key&login=" . rawurlencode( $user_login ) . '">' . wp_lostpassword_url() . "?key=$adt_rp_key&login=" . rawurlencode( $user_login ) . '</a>';
1395
1396 if ( $firstname == '' ) {
1397 $firstname = 'Customer';
1398 }
1399 $message = 'Hi ' . $firstname . ',<br>';
1400 $message .= 'Looks like you�ve requested a new password. Click below to reset it. <br>';
1401 $message .= $rp_link . '<br>';
1402 $message .= 'You can safely ignore this email if you do not wish to reset your password.<br><br><br>';
1403 $message .= 'Thanks.<br>';
1404
1405 $subject = __( 'Reset Password on ' . get_bloginfo( 'name' ) );
1406 $headers = array();
1407
1408 add_filter(
1409 'wp_mail_content_type',
1410 function( $content_type ) {
1411 return 'text/html';
1412 }
1413 );
1414 $headers[] = 'From: ' . get_bloginfo( 'name' ) . '<' . get_bloginfo( 'admin_email' ) . '>' . "\r\n";
1415 wp_mail( $email, $subject, $message, $headers );
1416 remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
1417
1418 return( rest_ensure_response( array( 'message' => 'Reset Password link sent successfully!' ) ) );
1419
1420 }
1421
1422
1423 /******
1424
1425 * Calculates shipping methods based on cart-items (line_items) , shipping address and coupon.
1426 ******/
1427
1428 function ams_applicable_shipping_method( WP_REST_Request $request ) {
1429
1430 $req = $request->get_json_params();
1431 $validate = ams_basic_validate( $req, array( 'shipping', 'line_items' ) );
1432 if ( $validate != true ) {
1433 return $validate;
1434 }
1435
1436 $shipping = $req['shipping'];
1437 $line_items = $req['line_items'];
1438 $customer_id = 0 ;
1439 if(isset( $req[ 'customer_id' ] )){
1440 $customer_id = sanitize_text_field( $req[ 'customer_id' ] );
1441 }
1442
1443 $content = [];
1444 wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
1445 wc()->frontend_includes();
1446 WC()->session = new WC_Session_Handler();
1447 WC()->customer = new WC_Customer( $customer_id, true );
1448 WC()->initialize_cart();
1449 WC()->cart->empty_cart();
1450 foreach ( $line_items as $key => $value ) { // prepare cart content which will be used for table rate plugin
1451 if ( array_key_exists( 'variation_id', $value ) ) {
1452 WC()->cart->add_to_cart($value['product_id'], $value['quantity'], $value['variation_id'] );
1453 }else{
1454 WC()->cart->add_to_cart($value['product_id'], $value['quantity'] );
1455 }
1456 }
1457
1458 WC()->customer->set_shipping_first_name(isset($shipping['first_name'])?$shipping['first_name']:'');
1459 WC()->customer->set_shipping_last_name(isset($shipping['last_name'])?$shipping['last_name']:'');
1460 WC()->customer->set_shipping_address_1(isset($shipping['address_1'])?$shipping['address_1']:'');
1461 WC()->customer->set_shipping_address_2(isset($shipping['address_2'])?$shipping['address_2']:'');
1462 WC()->customer->set_shipping_city(isset($shipping['city'])?$shipping['city']:'');
1463 WC()->customer->set_shipping_postcode(isset($shipping['postcode'])?$shipping['postcode']:'');
1464 WC()->customer->set_shipping_country(isset($shipping['country'])? $shipping['country'] :'');
1465 WC()->customer->set_shipping_state(isset($shipping['state'])? $shipping['state']: '');
1466
1467 if(isset( $req[ 'coupon_lines' ] )){
1468 if(!empty( $req[ 'coupon_lines' ] )){
1469 $coupon_code = sanitize_text_field( $req[ 'coupon_lines' ][0]['code'] );
1470 WC()->cart->add_discount( $coupon_code );
1471 }
1472 }
1473
1474 WC()->cart->calculate_shipping();
1475 WC()->cart->calculate_totals();
1476
1477 $packages = apply_filters('woocommerce_cart_shipping_packages', WC()->cart->get_shipping_packages());
1478 $shipping_packages = WC()->shipping->calculate_shipping($packages);
1479
1480 $all_shipping_packages_rates = array();
1481 foreach($shipping_packages as $package){
1482 $pacakage_rates=array();
1483 foreach($package['rates'] as $rate){
1484
1485 $pacakage_rate = array();
1486 $pacakage_rate['id']=(string)$rate->get_instance_id();
1487 $pacakage_rate['title']=$rate->get_label();
1488 $pacakage_rate['method_id']=$rate->get_method_id();
1489 $pacakage_rate['cost']=(float)$rate->get_cost();
1490 array_push($pacakage_rates,$pacakage_rate);
1491 }
1492 if(empty($pacakage_rates)){
1493 return( rest_ensure_response( $pacakage_rates ) );
1494 }
1495 array_push($all_shipping_packages_rates,$pacakage_rates);
1496 }
1497
1498 $result_methods=$all_shipping_packages_rates[0];
1499 for($i=1;$i<count($all_shipping_packages_rates);++$i){
1500 $result_methods = merge_shipping_methods($result_methods,$all_shipping_packages_rates[$i]);
1501 }
1502 WC()->cart->empty_cart();
1503 WC()->session->destroy_session();
1504 return( rest_ensure_response( $result_methods ) );
1505 }
1506
1507 function merge_shipping_methods($methods1,$methods2){
1508 $result=array();
1509 foreach($methods1 as $method1){
1510 foreach($methods2 as $method2){
1511 $current=$method2;
1512 if(($method1["method_id"]=="local_pickup"||$method1["method_id"]=="free_shipping")&&(!in_array($methods2["method_id"],
1513 array("flat_rate","free_shipping","local_pickup")))){
1514 $current["method_id"]="flat_rate";
1515 }
1516 if($method1['method_id']=="local_pickup"&&$methods2["method_id"]=="free_shipping"){
1517 $current["method_id"]=$method1['method_id'];
1518 $current["id"]=$method1['id'];
1519
1520 }
1521 if($method1['method_id']=="flat_rate"){
1522 $current["method_id"]=$method1['method_id'];
1523 $current["id"]=$method1['id'];
1524
1525 }
1526 $current["title"].=" + ".$method1['title'];
1527 $current["cost"]+=$method1['cost'];
1528 array_push($result,$current);
1529 }
1530
1531 }
1532 return $result;
1533 }
1534
1535
1536
1537 function old_applicable_shipping_method( WP_REST_Request $request ) {
1538
1539 $req = $request->get_json_params();
1540 $validate = ams_basic_validate( $req, array( 'shipping', 'line_items' ) );
1541 if ( $validate != true ) {
1542 return $validate;
1543 }
1544
1545 $shipping = $req['shipping'];
1546 $line_items = $req['line_items'];
1547 $free_shipping_by_coupon = rest_sanitize_boolean( $req['free_shipping_by_coupon'] );
1548 $cartTotal = 0;
1549 $content = [];
1550 $do_we_need_to_calculate_table_rates = false;
1551 $table_rate_method_instance_ids = [];
1552 $shipping_class_ids = [];
1553
1554 foreach ( $line_items as $key => $value ) { // prepare cart content which will be used for table rate plugin
1555 if ( array_key_exists( 'variation_id', $value ) ) {
1556
1557 $variation = wc_get_product( $value['variation_id'] );
1558 array_push($shipping_class_ids,$variation->get_shipping_class_id());
1559 $cartTotal += ( wc_get_price_excluding_tax( $variation ) * $line_items[ $key ]['quantity'] ); // price without VAT
1560 //code related to content
1561 $content[$key] = ["key"=>$key,"product_id"=>$value['product_id'],
1562 "variation_id"=>$value['variation_id'],
1563 "quantity"=>$value['quantity'],
1564 "line_total"=>($variation->get_price()*$value['quantity']),
1565 "line_tax"=>(wc_get_price_including_tax($variation)- wc_get_price_excluding_tax( $variation ))*$value['quantity'],
1566 ];
1567
1568 }else{
1569 $product = wc_get_product( $value['product_id'] );
1570 array_push($shipping_class_ids,$product->get_shipping_class_id());
1571 $cartTotal += ( wc_get_price_excluding_tax( $product ) * $line_items[ $key ]['quantity'] ); // price without VAT
1572 //code related to content
1573 $content[$key] = ["key"=>$key,"product_id"=>$value['product_id'],
1574 "quantity"=>$value['quantity'],
1575 "line_total"=>($product->get_price()*$value['quantity']),
1576 "line_tax"=>(wc_get_price_including_tax($product)- wc_get_price_excluding_tax( $product ))*$value['quantity'],
1577 ];
1578 }
1579 }
1580
1581 $stateCode = sanitize_text_field( $shipping['state'] );
1582 $postcode = sanitize_text_field( $shipping['postcode'] );
1583 $countryCode = sanitize_text_field( $shipping['country'] );
1584 $wc_applicable_shipping_methods= array();
1585 $product_qty = array_column( $line_items, 'quantity' );
1586 $only_shipping_zone_zero_exist = false;
1587
1588 // GET REQUEST##########################################
1589 $request_a = new WP_REST_Request( 'GET', '/wc/v3/shipping/zones' );
1590 $response_a = rest_do_request( $request_a );
1591 $server_a = rest_get_server();
1592 $data_a = $server_a->response_to_data( $response_a, false );
1593 $shippingZones = $data_a;
1594 // GET REQUEST##########################################
1595
1596 $shippingZoneId = 0; // Default shipping zone id (Locations not covered by other zones)
1597 unset( $shippingZones[0] ); // Remove default zone from the zone list which is to be matched.
1598 $shippingZones = array_values( $shippingZones );
1599
1600 if ( empty( $shippingZones ) ) {
1601 $only_shipping_zone_zero_exist = true;
1602 }
1603
1604 foreach ( $shippingZones as $key => $shippingZone ) {
1605 // Get location of the each zone
1606 // GET REQUEST##########################################
1607 $request_b = new WP_REST_Request( 'GET', "/wc/v3/shipping/zones/{$shippingZone['id']}/locations" );
1608 $response_b = rest_do_request( $request_b );
1609 $server_b = rest_get_server();
1610 $data_b = $server_b->response_to_data( $response_b, false );
1611 $shippingZones[ $key ]['locations'] = $data_b;
1612 // GET REQUEST##########################################
1613
1614 if ( ! empty( $shippingZones[ $key ]['locations'] ) ) {
1615 foreach ( $shippingZones[ $key ]['locations'] as $locationkey => $locations ) {
1616 if ( $shippingZones[ $key ]['locations'][ $locationkey ]['type'] == 'postcode' ) {
1617 $does_zone_contain_location_of_type_postcode = true;
1618 } else {
1619 $does_zone_contain_location_of_type_postcode = false;
1620 }
1621 }
1622 foreach ( $shippingZones[ $key ]['locations'] as $locationkey => $locations ) {
1623 unset( $shippingZones[ $key ]['locations'][ $locationkey ]['_links'] );
1624
1625 if ( $shippingZones[ $key ]['locations'][ $locationkey ]['type'] == 'postcode' ) {
1626 // if country code and state code does not match but the zone defines post code, we need to match post code
1627
1628 $haystack = $shippingZones[ $key ]['locations'][ $locationkey ]['code'];
1629
1630 if ( strpos( $haystack, '...' ) !== false ) {
1631 $zips = explode( '...', $haystack );
1632 if ( $postcode >= $zips[0] && $postcode <= $zips[1] ) {
1633 $shippingZoneId = $shippingZones[ $key ]['id'];
1634 }
1635 } elseif ( strpos( $haystack, '*' ) !== false ) { // if zone defines preg match of zip Ex. 1100*
1636 $haystack = str_replace( '*', '', $haystack );
1637
1638 if ( preg_match( "/^{$haystack}/", $postcode ) ) {
1639 $shippingZoneId = $shippingZones[ $key ]['id'];
1640 }
1641 } elseif ( strtolower( $haystack ) == strtolower( $postcode ) ) {
1642 $shippingZoneId = $shippingZones[ $key ]['id'];
1643 } else {
1644 // if post code not matched, let's continue the same process for other zones.
1645 }
1646 } elseif ( ( ! $does_zone_contain_location_of_type_postcode ) && ( $shippingZones[ $key ]['locations'][ $locationkey ]['type'] == 'state' ) && ( $shippingZones[ $key ]['locations'][ $locationkey ]['code'] == $countryCode . ':' . $stateCode ) ) {
1647 $shippingZoneId = $shippingZones[ $key ]['id'];
1648 } elseif ( ( ! $does_zone_contain_location_of_type_postcode ) && ( $shippingZones[ $key ]['locations'][ $locationkey ]['type'] == 'country' ) && ( $shippingZones[ $key ]['locations'][ $locationkey ]['code'] == $countryCode ) ) {
1649 $shippingZoneId = $shippingZones[ $key ]['id'];
1650
1651 } elseif ( ( ! $does_zone_contain_location_of_type_postcode ) && ( $shippingZones[ $key ]['locations'][ $locationkey ]['type'] == 'continent' ) && ( $shippingZones[ $key ]['locations'][ $locationkey ]['code'] == ams_get_country_continent( $countryCode ) ) ) {
1652 $shippingZoneId = $shippingZones[ $key ]['id'];
1653
1654 } else {
1655 // continue
1656 }
1657 }
1658 if ( $shippingZoneId != 0 ) {
1659 break;
1660 }
1661 } else // If no location are associated with particular zone, possible with worldwide location
1662 {
1663 $shippingZoneId = $shippingZones[ $key ]['id'];
1664 break;
1665 }
1666 }
1667
1668 // REQUEST##########################################
1669 $request_c = new WP_REST_Request( 'GET', "/wc/v3/shipping/zones/{$shippingZoneId}/methods" );
1670 $response_c = rest_do_request( $request_c );
1671 $server_c = rest_get_server();
1672 $methods = $server_c->response_to_data( $response_c, false );
1673 // REQUEST##########################################
1674
1675 if ( $shippingZoneId == 0 && empty( $methods ) && $only_shipping_zone_zero_exist ) { // If only zone = 0 present and there are no methods in this zone. Additionally, no other zones found, we need to skip the shipping screen, with 0 price.
1676 $wc_applicable_shipping_methods[] = array(
1677 'id' => (string) ( 0 ),
1678 'title' => 'zone_zero_with_no_shipping_methods',
1679 'method_id' => 'zone_zero_with_no_shipping_methods',
1680 'cost' => floatval( '0.00' ),
1681 );
1682 return( rest_ensure_response( $wc_applicable_shipping_methods ) );
1683 }
1684
1685 foreach ( $methods as $methodKey => $method ) {
1686 if ( isset( $method['settings']['min_amount'] ) ) {
1687 if ( $method['settings']['requires']['value'] == 'min_amount' && $cartTotal > $method['settings']['min_amount']['value'] ) {
1688 $methods[ $methodKey ]['methodcost'] = 0;
1689
1690 } elseif ( ( $method['settings']['requires']['value'] == 'coupon' ) && ( $free_shipping_by_coupon == true ) ) {
1691
1692 $methods[ $methodKey ]['methodcost'] = 0;
1693
1694 } elseif ( ( $method['settings']['requires']['value'] == 'both' ) && ( $free_shipping_by_coupon == true ) && ( $cartTotal > $method['settings']['min_amount']['value'] ) ) {
1695
1696 $methods[ $methodKey ]['methodcost'] = 0;
1697
1698 } elseif ( ( $method['settings']['requires']['value'] == 'either' ) && ( $free_shipping_by_coupon == true || $cartTotal > $method['settings']['min_amount']['value'] ) ) {
1699
1700 $methods[ $methodKey ]['methodcost'] = 0;
1701
1702 } elseif ( $method['settings']['requires']['value'] == '' ) {
1703
1704 $methods[ $methodKey ]['methodcost'] = 0;
1705
1706 } else {
1707 unset( $methods[ $methodKey ] ); // remove methods those does not require amount to be applicable (in case of coupon or both coupon and amount)
1708 }
1709 } elseif ( isset( $method['settings']['type'] ) ) {
1710 $methodCost = $method['settings']['cost']['value'];
1711 $methodCost = trim( trim( $methodCost, ']' ), '[' );
1712 if ( strpos( $methodCost, 'fee percent' ) !== false ) {
1713 $methodCost = str_replace( 'fee percent', 'fee_percent', $methodCost );
1714 $methodCostArr = explode( ' ', $methodCost );
1715
1716 foreach ( $methodCostArr as $methodCostkey => $methodCostArrVal ) {
1717 $methodCostArrVal = explode( '="', trim( $methodCostArrVal, '"' ) );
1718 switch ( $methodCostArrVal[0] ) {
1719 case 'fee_percent':
1720 $fee_percent = $methodCostArrVal[1];
1721 break;
1722 case 'min_fee':
1723 $min_fee = $methodCostArrVal[1];
1724 break;
1725 case 'max_fee':
1726 $max_fee = $methodCostArrVal[1];
1727 break;
1728 default:
1729 break;
1730 }
1731 }
1732 $methodNewCost = ( $cartTotal * $fee_percent ) / 100;
1733
1734 if ( isset( $min_fee ) && $min_fee > $methodNewCost ) {
1735 $methodNewCost = $min_fee;
1736 }
1737 if ( isset( $max_fee ) && $methodNewCost > $max_fee ) {
1738 $methodNewCost = $max_fee;
1739 }
1740 } elseif ( strpos( $methodCost, 'qty' ) !== false ) {
1741 $multiplier = (float) $methodCost;
1742 $qty = array_sum( $product_qty ); // $product_qty[$shippinkey];
1743 $methodNewCost = ( $multiplier * $qty );
1744 } else {
1745 $methodNewCost = (float) $methodCost;
1746 }
1747
1748 $methods[ $methodKey ]['settings']['cost']['value'] = $methodNewCost;
1749
1750 foreach ( $shipping_class_ids as $shippinkey => $shipping_class ) {
1751
1752 $shippingClassId = $shipping_class != 0 ? 'class_cost_' . $shipping_class : 'no_class_cost';
1753 $currCost = $method['settings'][ $shippingClassId ]['value'];
1754 $currCost = trim( trim( $currCost, ']' ), '[' );
1755 $methodCost = $method['settings']['cost']['value'];
1756
1757 if ( strpos( $currCost, 'fee percent' ) !== false ) {
1758 $currCost = str_replace( 'fee percent', 'fee_percent', $currCost );
1759 $currCostArr = explode( ' ', $currCost );
1760
1761 foreach ( $currCostArr as $currCostkey => $currCostArrVal ) {
1762 $currCostArrVal = explode( '="', trim( $currCostArrVal, '"' ) );
1763 switch ( $currCostArrVal[0] ) {
1764 case 'fee_percent':
1765 $fee_percent = $currCostArrVal[1];
1766 break;
1767 case 'min_fee':
1768 $min_fee = $currCostArrVal[1];
1769 break;
1770 case 'max_fee':
1771 $max_fee = $currCostArrVal[1];
1772 break;
1773 default:
1774 break;
1775 }
1776 }
1777
1778 $methodNewCost = ( $cartTotal * $fee_percent ) / 100;
1779
1780 if ( isset( $min_fee ) && $min_fee > $methodNewCost ) {
1781 $methodNewCost = $min_fee;
1782 }
1783
1784 if ( isset( $max_fee ) && $methodNewCost > $max_fee ) {
1785 $methodNewCost = $max_fee;
1786 }
1787 $methods[ $methodKey ]['cost'][] = $methodNewCost;
1788
1789 } elseif ( strpos( $currCost, 'qty' ) !== false ) {
1790 $multiplier = (float) $currCost;
1791 $qty = $product_qty[ $shippinkey ];
1792 $methodNewCost = ( $multiplier * $qty );
1793 $methods[ $methodKey ]['cost'][] = $methodNewCost;
1794 } else {
1795 $methodNewCost = (float) $currCost;
1796 $methods[ $methodKey ]['cost'][] = $methodNewCost;
1797 }
1798 }
1799
1800 if ( $method['settings']['type']['value'] == 'class' ) {
1801 $methods[ $methodKey ]['methodcost'] = array_sum( $methods[ $methodKey ]['cost'] ) + $methods[ $methodKey ]['settings']['cost']['value']; // Bugfix +$methodCost
1802 } elseif ( $method['settings']['type']['value'] == 'order' ) {
1803 $methods[ $methodKey ]['methodcost'] = max( $methods[ $methodKey ]['cost'] ) + $methods[ $methodKey ]['settings']['cost']['value']; // Bugfix +$methodCost
1804
1805 } else {
1806 // Continue
1807 }
1808 } else {
1809 $methods[ $methodKey ]['methodcost'] = $methods[ $methodKey ]['settings']['cost']['value'] ? $methods[ $methodKey ]['settings']['cost']['value'] : 0;
1810 }
1811 if ( $methods[ $methodKey ]['enabled'] != 1 || $methods[ $methodKey ]['method_id']=='table_rate') { // remove disabled and table-rate shipping methods
1812 //if this method is table_rate then save its instance_id.
1813 if($methods[ $methodKey ]['method_id']=='table_rate'){
1814 array_push($table_rate_method_instance_ids,$methods[ $methodKey ]['instance_id']) ;
1815 $do_we_need_to_calculate_table_rates = true;
1816 }
1817 unset( $methods[ $methodKey ] );
1818 } else {
1819 $wc_applicable_shipping_methods[] = array(
1820 'id' => (string) $methods[ $methodKey ]['id'],
1821 'title' => $methods[ $methodKey ]['title'],
1822 'method_id' => $methods[ $methodKey ]['method_id'],
1823 'cost' => floatval( $methods[ $methodKey ]['methodcost'] ),
1824 );
1825 }
1826 }
1827
1828 ######Table rate calculation#######
1829 $formatted_table_rate_shipping_methods = [] ;
1830 if ( in_array(
1831 'woocommerce-table-rate-shipping/woocommerce-table-rate-shipping.php',
1832 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1833 )&& $do_we_need_to_calculate_table_rates
1834 ) {
1835 require_once untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/includes/class-ams-wc-shipping-table-rate.php';
1836
1837 //prepare pacakage
1838 $pacakage = [
1839 'contents' => $content,
1840 'contents_cost' => $cartTotal,
1841 'applied_coupons' => [],
1842 'destination' => $shipping,
1843 'cart_subtotal' => $cartTotal,
1844 ];
1845
1846 foreach($table_rate_method_instance_ids as $key =>$table_rate_method_instance_id){
1847 //get table rate shipping method
1848 $object = new AMS_WC_Shipping_Table_Rate($table_rate_method_instance_id);
1849 $table_rate_shipping_methods = $object->get_rates($pacakage);
1850
1851 foreach($table_rate_shipping_methods as $key =>$method){
1852 //unset pacakage which of no use.
1853 unset($table_rate_shipping_methods[$key]['package']);
1854 if(is_array($method['cost'])){$method_cost=(float)$method['cost'][0] + (float)$method['cost']['order'];}else{$method_cost=(float)$method['cost'];}
1855 $formatted_table_rate_shipping_methods = array_merge($formatted_table_rate_shipping_methods,[['id'=>(string)$method['id'],'title'=>$method['label'],'method_id'=>'table_rate','cost'=>round($method_cost,2)]]);
1856
1857 }
1858 }
1859
1860 }
1861
1862 $result = array_merge(array_values($wc_applicable_shipping_methods),array_values($formatted_table_rate_shipping_methods));
1863 return( rest_ensure_response( $result ) );
1864
1865 }
1866
1867 function ams_checkout_fields() {
1868 if ( in_array(
1869 'woocommerce-checkout-field-editor/woocommerce-checkout-field-editor.php',
1870 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1871 )
1872 ) {
1873 $result['checkout_shipping_fields'] = ams_object_to_array( get_option( 'wc_fields_shipping', array() ) );
1874 $result['checkout_billing_fields'] = ams_object_to_array( get_option( 'wc_fields_billing', array() ) );
1875 $result['checkout_additional_fields'] = ams_object_to_array( get_option( 'wc_fields_additional', array() ) );
1876 return rest_ensure_response( $result );
1877 } else {
1878 return rest_ensure_response( array() );
1879 }
1880 }
1881
1882 function ams_wc_points_rewards_effective_discount( WP_REST_Request $request ) {
1883 if ( in_array(
1884 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
1885 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1886 )
1887 ) {
1888 $params = $request->get_params();
1889 $line_items = $params['line_items'];
1890 $customer_id = $params['customer_id'];
1891 $wc_points_rewards_discount_amount = $params['wc_points_rewards_discount_amount'];
1892 $granted_user_discount = 0;
1893
1894 // Construct local cart
1895 if ( is_null( WC()->cart ) ) {
1896 wc_load_cart();
1897 }
1898 WC()->cart->empty_cart();
1899 foreach ( $line_items as $key => $value ) {
1900 if ( array_key_exists( 'variation_id', $value ) ) {
1901 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'], $value['variation_id'] );
1902 } else {
1903 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'] );
1904 }
1905 }
1906
1907 // Verify Global settings of points and reward plugin
1908 $available_user_discount = WC_Points_Rewards_Manager::get_users_points_value( $customer_id );
1909
1910 // no discount
1911 if ( $available_user_discount <= 0 ) {
1912 // return 0;
1913 $error = new WP_Error();
1914 $error->add( 'message', __( 'No reward point available.' ) );
1915 return $error;
1916 }
1917
1918 if ( 'yes' === get_option( 'wc_points_rewards_partial_redemption_enabled' ) && $wc_points_rewards_discount_amount ) {
1919 $requested_user_discount = WC_Points_Rewards_Manager::calculate_points_value( $wc_points_rewards_discount_amount );
1920 if ( $requested_user_discount > 0 && $requested_user_discount < $available_user_discount ) {
1921 $available_user_discount = $requested_user_discount;
1922 }
1923 }
1924
1925 // Limit the discount available by the global minimum discount if set.
1926 $minimum_discount = get_option( 'wc_points_rewards_cart_min_discount', '' );
1927 if ( $minimum_discount > $available_user_discount ) {
1928 // return 0;
1929 $error = new WP_Error();
1930 $error->add( 'message', __( 'Please enter atleast '.$minimum_discount.' points global minimum discount error.' ) );
1931 return $error;
1932 }
1933
1934 // apply product level setting of point and reward plugin.
1935 $discount_applied = 0;
1936
1937 if ( ! did_action( 'woocommerce_before_calculate_totals' ) ) {
1938 WC()->cart->calculate_totals();
1939 }
1940
1941 $max_points_discount_of_all_products = 0;
1942 foreach ( WC()->cart->get_cart() as $item_key => $item ) {
1943
1944 $discount = 0;
1945 $max_discount = WC_Points_Rewards_Product::get_maximum_points_discount_for_product( $item['data'] );
1946
1947 if ( is_numeric( $max_discount ) ) {
1948
1949 // adjust the max discount by the quantity being ordered
1950 $max_discount *= $item['quantity'];
1951
1952
1953 // if the discount available is greater than the max discount, apply the max discount
1954 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
1955
1956 // Max should be product price. As this will be applied before tax, it will respect other coupons.
1957 } else {
1958 /*
1959 * Only exclude taxes when configured to in settings and when generating a discount amount for displaying in
1960 * the checkout message. This makes the actual discount money amount always tax inclusive.
1961 */
1962 if ( 'exclusive' === get_option( 'wc_points_rewards_points_tax_application', wc_prices_include_tax() ? 'inclusive' : 'exclusive' ) && $for_display ) {
1963 if ( function_exists( 'wc_get_price_excluding_tax' ) ) {
1964 $max_discount = wc_get_price_excluding_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
1965 } elseif ( method_exists( $item['data'], 'get_price_excluding_tax' ) ) {
1966 $max_discount = $item['data']->get_price_excluding_tax( $item['quantity'] );
1967 } else {
1968 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
1969 }
1970 } else {
1971 if ( function_exists( 'wc_get_price_including_tax' ) ) {
1972 $max_discount = wc_get_price_including_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
1973 } elseif ( method_exists( $item['data'], 'get_price_including_tax' ) ) {
1974 $max_discount = $item['data']->get_price_including_tax( $item['quantity'] );
1975 } else {
1976 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
1977 }
1978 }
1979
1980 // if the discount available is greater than the max discount, apply the max discount
1981 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
1982 }
1983
1984 $max_points_discount_of_all_products += $max_discount ;
1985
1986 // add the discount to the amount to be applied
1987 $discount_applied += $discount;
1988
1989 // reduce the remaining discount available to be applied
1990 $available_user_discount -= $discount;
1991 }
1992 // limit customer if requested amount to avail discount exceeds the product's maximum discount.
1993 /*
1994 if($wc_points_rewards_discount_amount > $max_points_discount_of_all_products){
1995 $error = new WP_Error();
1996 $error->add( 'message', __( 'You cannot enter more than '.$max_points_discount_of_all_products.' points on these products.' ) );
1997 return $error;
1998 }
1999 */
2000
2001 $existing_discount_amounts = version_compare( WC_VERSION, '3.0.0', '<' )? WC()->cart->discount_total: WC()->cart->get_cart_discount_total();
2002
2003 // if the available discount is greater than the order total, make the discount equal to the order total less any other discounts
2004 if ( version_compare( WC_VERSION, '3.0.0', '<' ) ) {
2005 if ( 'no' === get_option( 'woocommerce_prices_include_tax' ) ) {
2006 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal_ex_tax - $existing_discount_amounts ) );
2007
2008 } else {
2009 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal - $existing_discount_amounts ) );
2010
2011 }
2012 } else {
2013 if ( 'no' === get_option( 'woocommerce_prices_include_tax' ) ) {
2014 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal_ex_tax - $existing_discount_amounts ) );
2015
2016 } else {
2017 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal - $existing_discount_amounts ) );
2018 }
2019 }
2020
2021 // limit the discount available by the global maximum discount if set
2022 $max_discount = get_option( 'wc_points_rewards_cart_max_discount' );
2023
2024 if ( false !== strpos( $max_discount, '%' ) ) {
2025 $max_discount = ams_ams_calculate_discount_modifier( $max_discount );
2026 }
2027 $max_discount = filter_var( $max_discount, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
2028
2029 if ( $max_discount && $max_discount < $discount_applied ) {
2030 $error = new WP_Error();
2031 $error->add( 'message', __( 'You cannot enter more than '.$max_discount.' points.' ) );
2032 return $error;
2033 //$discount_applied = $max_discount;
2034 }
2035 $discount_applied = filter_var( $discount_applied, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
2036 return rest_ensure_response( array( array( 'effective_discount_value' => (float) $discount_applied ) ) );
2037
2038 } else {
2039 return rest_ensure_response( array() );
2040 }
2041 }
2042
2043 function ams_wc_points_rewards_settings() {
2044 if ( in_array(
2045 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
2046 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
2047 )
2048 ) {
2049
2050 $result['wc_points_rewards_cart_max_discount'] = get_option( 'wc_points_rewards_cart_max_discount' );
2051 $result['wc_points_rewards_write_review_points'] = get_option( 'wc_points_rewards_write_review_points' );
2052 $result['wc_points_rewards_account_signup_points'] = get_option( 'wc_points_rewards_account_signup_points' );
2053 $result['wc_points_rewards_points_expiry'] = get_option( 'wc_points_rewards_points_expiry' );
2054 $result['wc_points_rewards_points_expire_points_since'] = get_option( 'wc_points_rewards_points_expire_points_since' );
2055 $result['wc_points_rewards_version'] = get_option( 'wc_points_rewards_version' );
2056 $result['wc_points_rewards_earn_points_ratio'] = get_option( 'wc_points_rewards_earn_points_ratio', '' );
2057 $result['wc_points_rewards_earn_points_rounding'] = get_option( 'wc_points_rewards_earn_points_rounding' );
2058 $result['wc_points_rewards_redeem_points_ratio'] = get_option( 'wc_points_rewards_redeem_points_ratio', '' );
2059 $result['wc_points_rewards_partial_redemption_enabled'] = get_option( 'wc_points_rewards_partial_redemption_enabled' );
2060 $result['wc_points_rewards_cart_min_discount'] = get_option( 'wc_points_rewards_cart_min_discount' );
2061 $result['wc_points_rewards_max_discount'] = get_option( 'wc_points_rewards_max_discount' );
2062 $result['wc_points_rewards_points_tax_application'] = get_option( 'wc_points_rewards_points_tax_application' );
2063 $result['wc_points_rewards_points_expiry_number'] = get_option( 'wc_points_rewards_points_expiry_number' );
2064 $result['wc_points_rewards_points_expiry_period'] = get_option( 'wc_points_rewards_points_expiry_period' );
2065 $result['wc_points_rewards_single_product_message'] = get_option( 'wc_points_rewards_single_product_message' );
2066 $result['wc_points_rewards_variable_product_message'] = get_option( 'wc_points_rewards_variable_product_message' );
2067 $result['wc_points_rewards_earn_points_message'] = get_option( 'wc_points_rewards_earn_points_message' );
2068 $result['wc_points_rewards_redeem_points_message'] = get_option( 'wc_points_rewards_redeem_points_message' );
2069 $result['wc_points_rewards_thank_you_message'] = get_option( 'wc_points_rewards_thank_you_message' );
2070
2071 return rest_ensure_response( $result );
2072 } else {
2073 return rest_ensure_response( array() );
2074 }
2075 }
2076
2077 add_filter( 'woocommerce_get_shop_coupon_data', 'ams_create_virtual_coupon', 10, 2 );
2078
2079 function ams_create_virtual_coupon( $false, $data ) {
2080
2081 // Do not interfere with coupon creation and editing.
2082 if ( is_admin() ) {
2083 return $false;
2084 }
2085 $coupon_code_valid = false;
2086 $coupon_settings = null;
2087 $coupon_amount = 0;
2088 if ( ams_is_coupon_code_valid( $data ) ) {
2089 $coupon_code_valid = true;
2090 }
2091 if ( ( $pos = strpos( $data, '@' ) ) !== false ) {
2092 $coupon_amount = (float) substr( $data, $pos + 1 );
2093 }
2094 // Create a coupon with the properties you need
2095 if ( $coupon_code_valid ) {
2096 $coupon_settings = array(
2097 'id' => true,
2098 'discount_type' => 'fixed_cart', // 'fixed_cart', 'percent' or 'fixed_product'
2099 'amount' => $coupon_amount, // value or percentage.
2100 'expiry_date' => date( 'Y-m-d', strtotime( 'tomorrow' ) ), // YYYY-MM-DD
2101 'individual_use' => false,
2102 'product_ids' => array(),
2103 'exclude_product_ids' => array(),
2104 'usage_limit' => '1',
2105 'usage_limit_per_user' => '1',
2106 'limit_usage_to_x_items' => '',
2107 'usage_count' => '',
2108 'free_shipping' => false,
2109 'product_categories' => array(),
2110 'exclude_product_categories' => array(),
2111 'exclude_sale_items' => false,
2112 'minimum_amount' => '',
2113 'maximum_amount' => '',
2114 'customer_email' => array(),
2115 );
2116
2117 return $coupon_settings;
2118 } else {
2119 return false;
2120 }
2121
2122 }
2123
2124 add_action( 'rest_api_init', 'ams_create_api_customer_field' );
2125
2126 function ams_create_api_customer_field() {
2127
2128 // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
2129 register_rest_field(
2130 'customer',
2131 'ams-rewards-points-balance',
2132 array(
2133 'get_callback' => 'ams_get_rewards_points_balance',
2134 'schema' => null,
2135 )
2136 );
2137 }
2138
2139 function ams_get_rewards_points_balance( $object ) {
2140 if ( in_array(
2141 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
2142 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
2143 )
2144 ) {
2145 // get the value of the user's point balance
2146 $available_user_discount = WC_Points_Rewards_Manager::get_users_points( $object['id'] );
2147 // return the post meta
2148 return (float) $available_user_discount;
2149 } else {
2150 return 0;
2151 }
2152 }
2153
2154 add_action( 'woocommerce_order_status_processing', 'ams_order_processing' );
2155 function ams_order_processing( $order_id ) {
2156
2157 if ( in_array(
2158 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
2159 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
2160 )
2161 ) { // order-redeem
2162 $already_redeemed = get_post_meta( $order_id, '_wc_points_redeemed', true );
2163 $logged_redemption = get_post_meta( $order_id, '_wc_points_logged_redemption', true );
2164
2165 // Points has already been redeemed
2166 if ( ! empty( $already_redeemed ) ) {
2167 return;
2168 }
2169 $order = wc_get_order( $order_id );
2170 $customer_id = version_compare( WC_VERSION, '3.0', '<' ) ? $order->user_id : $order->get_user_id();
2171
2172 // bail for guest user
2173 if ( ! $customer_id ) {
2174 return;
2175 }
2176
2177 $discount_code = $order->get_meta( '_ams_wc_points_rewards_discount_code' );
2178
2179 if ( ! empty( $logged_redemption ) ) {
2180 $points_redeemed = $logged_redemption['points'];
2181 $discount_amount = $logged_redemption['amount'];
2182 $discount_code = $logged_redemption['discount_code'];
2183 } else {
2184 $points_redeemed = $order->get_meta( '_ams_wc_points_redeemed' );
2185 // bail if ams is not involved
2186 if ( ! $points_redeemed ) {
2187 return;
2188 }
2189 // Get amount of discount
2190 $discount_amount = $order->get_meta( '_ams_wc_points_rewards_discount_amount' );
2191
2192 }
2193 WC_Points_Rewards_Manager::decrease_points(
2194 $customer_id,
2195 $points_redeemed,
2196 'order-redeem',
2197 array(
2198 'discount_code' => $discount_code,
2199 'discount_amount' => $discount_amount,
2200 ),
2201 $order_id
2202 );
2203 update_post_meta( $order_id, '_wc_points_redeemed', $points_redeemed );
2204 update_post_meta(
2205 $order_id,
2206 '_wc_points_logged_redemption',
2207 array(
2208 'points' => $points_redeemed,
2209 'amount' => $discount_amount,
2210 'discount_code' => $discount_code,
2211 )
2212 );
2213
2214 // add order note
2215 /* translators: 1: points earned 2: points label 3: discount amount */
2216 $order->add_order_note( sprintf( __( '%1$d %2$s redeemed for a %3$s discount.', 'woocommerce-points-and-rewards' ), $points_redeemed, ams_get_points_label( $points_redeemed ), wc_price( $discount_amount ) ) );
2217
2218 }
2219
2220 }
2221 function ams_change_password(WP_REST_Request $request){
2222
2223 $req = $request->get_json_params();
2224
2225 $user = wp_authenticate( sanitize_email( $req['username'] ), sanitize_text_field( $req['password'] ) ); // htmlspecialchars
2226 $customer_id = sanitize_text_field( $req['customer_id'] );
2227 $old_password = sanitize_text_field( $req['old_password'] );
2228 $new_password = sanitize_text_field( $req['new_password'] );
2229 $confirm_password = sanitize_text_field( $req['confirm_password'] );
2230
2231 $user = get_user_by( 'id', $customer_id );
2232 if ( isset( $user->errors ) ) {
2233 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
2234 $error = new WP_Error();
2235 $error->add( 'message', __( $error_message . '' ) );
2236 return $error;
2237 }
2238
2239 $x = wp_check_password( $old_password, $user->data->user_pass, $user->data->ID );
2240
2241 if ( isset( $x->errors ) ) {
2242 $error_message = strip_tags( ams_convert_error_to_string( $x->errors ) );
2243 $error = new WP_Error();
2244 $error->add( 'message', __( $error_message . '' ) );
2245 return $error;
2246 }
2247 if($x)
2248 {
2249 if($new_password == $old_password)
2250 {
2251 return new WP_Error( 'ams_error', 'Sorry, your new password and old password can not be the same.', array( 'status' => 422 ) );
2252 }
2253 if($new_password == $confirm_password)
2254 {
2255 $user_data['ID'] = $user->data->ID;
2256 $user_data['user_pass'] = $new_password;
2257 $uid = wp_update_user( $user_data );
2258 //wp_set_password($new_password , $user_id);
2259 if($uid)
2260 {
2261 unset($passdata);
2262 $user->data->user_pass = '';
2263 $user->data->user_activation_key = '';
2264 $user->data->id = $user->ID; //integer
2265 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
2266 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
2267 $user->data->roles = $user->roles;
2268 return rest_ensure_response( $user->data );
2269 } else {
2270 return new WP_Error( 'ams_error', 'Sorry, your account was not updated. Please try again later.', array( 'status' => 422 ) );
2271 }
2272 }
2273 else
2274 {
2275 return new WP_Error( 'ams_error', 'Sorry, both your passwords do not match. Please try again. ', array( 'status' => 422 ) );
2276 }
2277 }
2278 else
2279 {
2280 return new WP_Error( 'ams_error', 'Sorry, your old password is not correct. Please try again.', array( 'status' => 422 ) );
2281 }
2282
2283 }
2284
2285 // //
2286 // Other Helping Function ###########################################//
2287 // //
2288 function ams_get_points_rewards_discount_amount( $customer_id, $wc_points_rewards_discount_amount, $line_items ) {
2289
2290 if ( empty( $line_items ) ) {
2291 return 0;
2292 }
2293
2294 $granted_user_discount = 0;
2295 // Construct local cart
2296 if ( is_null( WC()->cart ) ) {
2297 wc_load_cart();
2298 }
2299 WC()->cart->empty_cart();
2300
2301 foreach ( $line_items as $key => $value ) {
2302 if ( array_key_exists( 'variation_id', $value ) ) {
2303 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'], $value['variation_id'] );
2304 } else {
2305 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'] );
2306 }
2307 }
2308
2309 $available_user_discount = WC_Points_Rewards_Manager::get_users_points_value( $customer_id );
2310
2311 // no discount
2312 if ( $available_user_discount <= 0 ) {
2313 return 0;
2314 }
2315 if ( 'yes' === get_option( 'wc_points_rewards_partial_redemption_enabled' ) && $wc_points_rewards_discount_amount ) {
2316 $requested_user_discount = WC_Points_Rewards_Manager::calculate_points_value( $wc_points_rewards_discount_amount );
2317 if ( $requested_user_discount > 0 && $requested_user_discount < $available_user_discount ) {
2318 $available_user_discount = $requested_user_discount;
2319 }
2320 }
2321
2322 // Limit the discount available by the global minimum discount if set.
2323 $minimum_discount = get_option( 'wc_points_rewards_cart_min_discount', '' );
2324 if ( $minimum_discount > $available_user_discount ) {
2325 return 0;
2326 }
2327 $discount_applied = 0;
2328
2329 if ( ! did_action( 'woocommerce_before_calculate_totals' ) ) {
2330 WC()->cart->calculate_totals();
2331 }
2332
2333 foreach ( WC()->cart->get_cart() as $item_key => $item ) {
2334
2335 $discount = 0;
2336 $max_discount = WC_Points_Rewards_Product::get_maximum_points_discount_for_product( $item['data'] );
2337
2338 if ( is_numeric( $max_discount ) ) {
2339
2340 // adjust the max discount by the quantity being ordered
2341 $max_discount *= $item['quantity'];
2342
2343 // if the discount available is greater than the max discount, apply the max discount
2344 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
2345
2346 // Max should be product price. As this will be applied before tax, it will respect other coupons.
2347 } else {
2348 /*
2349 * Only exclude taxes when configured to in settings and when generating a discount amount for displaying in
2350 * the checkout message. This makes the actual discount money amount always tax inclusive.
2351 */
2352 if ( 'exclusive' === get_option( 'wc_points_rewards_points_tax_application', wc_prices_include_tax() ? 'inclusive' : 'exclusive' ) && $for_display ) {
2353 if ( function_exists( 'wc_get_price_excluding_tax' ) ) {
2354 $max_discount = wc_get_price_excluding_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
2355 } elseif ( method_exists( $item['data'], 'get_price_excluding_tax' ) ) {
2356 $max_discount = $item['data']->get_price_excluding_tax( $item['quantity'] );
2357 } else {
2358 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
2359 }
2360 } else {
2361 if ( function_exists( 'wc_get_price_including_tax' ) ) {
2362 $max_discount = wc_get_price_including_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
2363 } elseif ( method_exists( $item['data'], 'get_price_including_tax' ) ) {
2364 $max_discount = $item['data']->get_price_including_tax( $item['quantity'] );
2365 } else {
2366 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
2367 }
2368 }
2369
2370 // if the discount available is greater than the max discount, apply the max discount
2371 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
2372 }
2373
2374 // add the discount to the amount to be applied
2375 $discount_applied += $discount;
2376
2377 // reduce the remaining discount available to be applied
2378 $available_user_discount -= $discount;
2379 }
2380 // limit the discount available by the global maximum discount if set
2381 $max_discount = get_option( 'wc_points_rewards_cart_max_discount' );
2382
2383 if ( false !== strpos( $max_discount, '%' ) ) {
2384 $max_discount = ams_calculate_discount_modifier( $max_discount );
2385 WC()->cart->empty_cart();
2386 }
2387 $max_discount = filter_var( $max_discount, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
2388
2389 if ( $max_discount && $max_discount < $discount_applied ) {
2390 $discount_applied = $max_discount;
2391 }
2392 // clear cart before returning
2393 WC()->cart->empty_cart();
2394 $discount_applied = filter_var( $discount_applied, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
2395 return $discount_applied;
2396
2397 }
2398
2399 function ams_get_points_label( $count ) {
2400
2401 list( $singular, $plural ) = explode( ':', get_option( 'wc_points_rewards_points_label' ) );
2402
2403 return 1 == $count ? $singular : $plural;
2404 }
2405 function ams_is_coupon_code_valid( $coupon_code ) {
2406 if ( 0 === strpos( $coupon_code, 'wc_points_redemption_' ) ) {
2407 return true;
2408 }
2409 return false;
2410 }
2411
2412 function ams_calculate_discount_modifier( $percentage ) {
2413
2414 $percentage = str_replace( '%', '', $percentage ) / 100;
2415
2416 if ( 'no' === get_option( 'woocommerce_prices_include_tax' ) ) {
2417 $discount = WC()->cart->subtotal_ex_tax;
2418
2419 } else {
2420 $discount = WC()->cart->subtotal;
2421
2422 }
2423
2424 return $percentage * $discount;
2425 }
2426
2427 function ams_object_to_array( $data ) {
2428 if ( is_array( $data ) || is_object( $data ) ) {
2429 $result = array();
2430 foreach ( $data as $key => $value ) {
2431 $value['field_name'] = $key;
2432 $value['options'] = array_values( $value['options'] );
2433 $result[] = $value;
2434
2435 }
2436 return $result;
2437 }
2438 return $data;
2439 }
2440
2441 function ams_build_category_tree( $flat, $pidKey, $idKey = null ) {
2442 $grouped = array();
2443 foreach ( $flat as $sub ) {
2444 $grouped[ $sub[ $pidKey ] ][] = $sub;
2445 }
2446 $level = 0;
2447 $fnBuilder = function( $siblings, $level ) use ( &$fnBuilder, $grouped, $idKey ) {
2448 foreach ( $siblings as $k => $sibling ) {
2449 if ( $sibling['slug'] == 'uncategorized' ) {
2450 unset( $siblings[ $k ] );
2451 continue;
2452 }
2453 $id = $sibling[ $idKey ];
2454 $sibling['description'] = '';
2455 $level++;
2456 if ( isset( $grouped[ $id ] ) ) {
2457 $sibling['depth'] = $level;
2458 $sibling['children'] = array_values( $fnBuilder( $grouped[ $id ], $level ) );
2459 } else {
2460 $sibling['depth'] = $level;
2461 $sibling['children'] = array();
2462 }
2463 $siblings[ $k ] = $sibling;
2464 $level--;
2465 }
2466 return $siblings;
2467 };
2468
2469 if ( isset( $grouped[0] ) ) {
2470 $tree = $fnBuilder( $grouped[0], $level );
2471 }
2472 if ( ! empty( $tree ) ) {
2473 return array_values( $tree );
2474 } else {
2475 foreach ( $flat as $key => $value ) {
2476 if ( $value['slug'] == 'uncategorized' ) {
2477 unset( $flat[ $key ] );
2478 continue;
2479 }
2480 $flat[ $key ]['children'] = array();
2481 }
2482 return array_values( $flat );
2483 }
2484 }
2485
2486 function ams_convert_error_to_string( $er ) {
2487 $string = ' ';
2488 foreach ( $er as $key => $value ) {
2489
2490 $string = $string . '' . $key . ':';
2491 foreach ( $value as $newkey => $newvalue ) {
2492
2493 $string = $string . '' . $newvalue . ' ';
2494 }
2495 }
2496 $string = str_replace( 'Lost your password?', '', $string );
2497 $string = str_replace( 'Error:', '', $string );
2498 $string = str_replace( '[message]', '', $string );
2499 return( $string );
2500 }
2501
2502 function ams_basic_validate( $request, $keys ) {
2503 foreach ( $keys as $key => $value ) {
2504
2505 if ( ! isset( $request[ $value ] ) ) {
2506 status_header( 400 );
2507 echo ( json_encode(
2508 array(
2509 'message' => 'There is a problem with your input!',
2510 'error' => $value . ': Field is required!',
2511 ),
2512 JSON_UNESCAPED_UNICODE
2513 ) );
2514 die();
2515 }
2516 if ( empty( $request[ $value ] ) ) {
2517 status_header( 400 );
2518 echo ( json_encode(
2519 array(
2520 'message' => 'There is a problem with your input!',
2521 'error' => $value . ': Can not be empty!',
2522 ),
2523 JSON_UNESCAPED_UNICODE
2524 ) );
2525 die();
2526 }
2527 }
2528 return true;
2529 }
2530 function ams_get_country_continent( $country ) {
2531 $data = array(
2532 'EU' => array( 'AD', 'AL', 'AT', 'AX', 'BA', 'BE', 'BG', 'BY', 'CH', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FO', 'FR', 'FX', 'GB', 'GG', 'GI', 'GR', 'HR', 'HU', 'IE', 'IM', 'IS', 'IT', 'JE', 'LI', 'LT', 'LU', 'LV', 'MC', 'MD', 'ME', 'MK', 'MT', 'NL', 'NO', 'PL', 'PT', 'RO', 'RS', 'RU', 'SE', 'SI', 'SJ', 'SK', 'SM', 'TR', 'UA', 'VA' ),
2533 'AS' => array( 'AE', 'AF', 'AM', 'AP', 'AZ', 'BD', 'BH', 'BN', 'BT', 'CC', 'CY', 'CN', 'CX', 'GE', 'HK', 'ID', 'IL', 'IN', 'IO', 'IQ', 'IR', 'YE', 'JO', 'JP', 'KG', 'KH', 'KP', 'KR', 'KW', 'KZ', 'LA', 'LB', 'LK', 'MY', 'MM', 'MN', 'MO', 'MV', 'NP', 'OM', 'PH', 'PK', 'PS', 'QA', 'SA', 'SG', 'SY', 'TH', 'TJ', 'TL', 'TM', 'TW', 'UZ', 'VN' ),
2534 'OC' => array( 'AS', 'AU', 'CK', 'FJ', 'FM', 'GU', 'KI', 'MH', 'MP', 'NC', 'NF', 'NR', 'NU', 'NZ', 'PF', 'PG', 'PN', 'PW', 'SB', 'TK', 'TO', 'TV', 'UM', 'VU', 'WF', 'WS' ),
2535 'NA' => array( 'CA', 'MX', 'US', 'AG', 'AI', 'AN', 'AW', 'BB', 'BL', 'BM', 'BS', 'BZ', 'CR', 'CU', 'DM', 'DO', 'GD', 'GL', 'GP', 'GT', 'HN', 'HT', 'JM', 'KY', 'KN', 'LC', 'MF', 'MQ', 'MS', 'NI', 'PA', 'PM', 'PR', 'SV', 'TC', 'TT', 'VC', 'VG', 'VI' ),
2536 'SA' => array( 'AR', 'BO', 'BR', 'CL', 'CO', 'EC', 'FK', 'GF', 'GY', 'GY', 'PE', 'PY', 'SR', 'UY', 'VE' ),
2537 'AF' => array( 'AO', 'BF', 'BI', 'BJ', 'BW', 'CD', 'CF', 'CG', 'CI', 'CM', 'CV', 'DJ', 'DZ', 'EG', 'EH', 'ER', 'ET', 'GA', 'GH', 'GM', 'GN', 'GQ', 'GW', 'YT', 'KE', 'KM', 'LY', 'LR', 'LS', 'MA', 'MG', 'ML', 'MR', 'MU', 'MW', 'MZ', 'NA', 'NE', 'NG', 'RE', 'RW', 'SC', 'SD', 'SH', 'SL', 'SN', 'SO', 'ST', 'SZ', 'TD', 'TG', 'TN', 'TZ', 'UG', 'ZA', 'ZM', 'ZW' ),
2538 );
2539 foreach ( $data as $continent => $countries ) {
2540 if ( in_array( $country, $countries ) ) {
2541 return $continent;
2542 }
2543 }
2544 return '';
2545 }
2546
2547 require_once untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/includes/ams-plugin-deactivation-survey.php';
2548
2549 add_action( 'wp_ajax_ams_deactivation_form_submit', 'ams_deactivation_form_submit' );
2550
2551 add_action('admin_enqueue_scripts', 'ams_admin_enqueue_scripts');
2552 function ams_admin_enqueue_scripts(){
2553
2554 $current_page = get_current_screen()->base;
2555
2556 if($current_page == 'plugins' || $current_page == 'plugins-network') {
2557
2558 add_action('admin_footer', 'ams_deactivation_popup');
2559
2560 wp_register_script('ams_jquery', 'https://code.jquery.com/jquery-3.6.0.min.js', array(), '3.6.0', true); // jQuery v3
2561 wp_enqueue_script('ams_jquery');
2562 wp_script_add_data( 'ams_jquery', array( 'integrity', 'crossorigin' ) , array( 'sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=', 'anonymous' ) );
2563
2564 wp_enqueue_script('ams_plugin_deactivation_survey_js', plugins_url('assets/plugin-deactivation-survey.js', __FILE__), array('ams_jquery'));
2565 wp_localize_script('ams_plugin_deactivation_survey_js', 'frontend_ajax_object', array('amsDeactivationSurveyNonce' => wp_create_nonce('ajax-nonce')));
2566 wp_enqueue_style( 'ams_plugin_deactivation_survey_css', plugins_url('assets/plugin-deactivation-survey.css', __FILE__), array());
2567
2568
2569 } else { // # if not on plugins, deregister and dequeue styles & scripts
2570
2571 wp_dequeue_script('ams_jquery');
2572 wp_dequeue_script('ams_plugin_deactivation_survey_js');
2573 wp_dequeue_style('ams_plugin_deactivation_survey_css');
2574
2575 }
2576 }
2577
2578