PluginProbe
AppMySite – WordPress & WooCommerce Mobile App Builder (No-Code Android & iOS App Maker) / 3.7.0
AppMySite – WordPress & WooCommerce Mobile App Builder (No-Code Android & iOS App Maker) v3.7.0
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.7.0, at appmysite.php

2,276 lines 72.6 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.7.0
7 * Author: AppMySite
8 * Text Domain: appmysite
9 * Author URI: https://appmysite.com
10 * Tested up to: 6.0.2
11 * WC tested up to: 6.9.4
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 add_filter( 'woocommerce_get_settings_products', 'ams_wc_get_cart_url', 10, 2 );
452 function ams_wc_get_cart_url( $settings ) {
453
454 $settings[] = array(
455 'name' => __( 'AMS WC Cart Page URL', 'woocommerce' ),
456 'id' => 'ams_wc_cart_url',
457 'label' => 'Woocommerce cart page URL.',
458 'type' => 'select',
459 'desc' => __( 'This setting determines the cart page url of store.', 'woocommerce' ),
460 'default' => wc_get_cart_url()
461 );
462 return $settings;
463 }
464
465 /******
466
467 * Adds post's featured media to REST API.
468 */
469
470 register_rest_field(
471 'post',
472 'featured_image_src',
473 array(
474 'get_callback' => 'ams_get_image_src',
475 'update_callback' => null,
476 'schema' => null,
477 )
478 );
479
480 add_action( 'rest_api_init', 'ams_register_rest_field_for_custom_post_type' );
481
482 function ams_register_rest_field_for_custom_post_type(){
483 $ams_custom_post_types = array_values(get_post_types(array('_builtin' => false),'names','and')); //'public' => true,'exclude_from_search' => false
484 if (($key = array_search('product', $ams_custom_post_types)) !== false) { // We don't need this field for products
485 unset($ams_custom_post_types[$key]);
486 }
487 register_rest_field(
488 $ams_custom_post_types, //['product','course','projects']
489 'featured_image_src',
490 array(
491 'get_callback' => 'ams_get_image_src',
492 'update_callback' => null,
493 'schema' => null,
494 )
495 );
496 }
497
498 function ams_get_image_src( $object, $field_name, $request ) {
499 $feat_img_array = wp_get_attachment_image_src(
500 $object['featured_media'], // Image attachment ID
501 'large', // Size. Ex. "thumbnail", "large", "full", etc..
502 false // Whether the image should be treated as an icon.
503 );
504 return $feat_img_array[0];
505 }
506 function ams_get_version_info( WP_REST_Request $request ){
507
508 if ( ! function_exists( 'plugins_api' ) ) {
509 require_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );
510 }
511
512 if( ! function_exists( 'get_plugin_data' ) ) {
513 require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
514 }
515 $version_current = get_plugin_data( __FILE__ )['Version'];
516
517 $args = array(
518 'slug' => 'appmysite',
519 'fields' => array(
520 'version' => true,
521 )
522 );
523
524 $call_api = plugins_api( 'plugin_information', $args );
525
526 if ( is_wp_error( $call_api ) ) {
527
528 $api_error = $call_api->get_error_message();
529
530 return( rest_ensure_response([
531 "AMS_PLUGIN_LATEST_VERSION"=>"0.0.0",
532 "AMS_PLUGIN_CURRENT_VERSION"=>"0.0.0"
533 ]));
534 } else {
535
536 if ( ! empty( $call_api->version ) ) {
537
538 $version_latest = $call_api->version;
539 return( rest_ensure_response( ["AMS_PLUGIN_LATEST_VERSION"=>$version_latest,
540 "AMS_PLUGIN_CURRENT_VERSION"=>$version_current] ) );
541 }
542
543 }
544
545 }
546
547 function ams_verify_application_password( WP_REST_Request $request ) {
548
549 $user = get_user_by( 'ID', apply_filters('determine_current_user', false) ); // | User by ID
550 if ( isset( $user->errors ) ) {
551 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
552 $error = new WP_Error();
553 $error->add( 'message', __( $error_message . '' ) );
554 return $error;
555 } elseif ( isset( $user->data ) ) {
556 $user->data->user_pass = '';
557 $user->data->user_activation_key = '';
558 $user->data->id = $user->ID; //integer
559 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
560 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
561 $user->data->roles = $user->roles;
562 ####get user wp_generate_auth_cookie####
563
564 ########################################
565 return rest_ensure_response( $user->data );
566 } else {
567 return new WP_Error('ams_error', 'Something went wrong. Please contact support.', array('status' => 500));
568 }
569 }
570
571
572
573 /******
574
575 * Adds post's medium & large media to REST API.
576 */
577
578 register_rest_field(
579 'post',
580 'blog_images',
581 array(
582 'get_callback' => 'ams_get_images_urls',
583 'update_callback' => null,
584 'schema' => null,
585 )
586 );
587
588 function ams_get_images_urls( $object, $field_name, $request ) {
589 $medium = wp_get_attachment_image_src( get_post_thumbnail_id( $object['id'] ), 'medium' );
590 $medium_url = $medium['0'];
591
592 $large = wp_get_attachment_image_src( get_post_thumbnail_id( $object['id'] ), 'large' );
593 $large_url = $large['0'];
594
595 return array(
596 'medium' => $medium_url,
597 'large' => $large_url,
598 );
599 }
600
601 /******
602
603 * Get default variant in rest api.
604 */
605 register_rest_field(
606 'product',
607 'ams_default_variation_id',
608 array(
609 'get_callback' => 'ams_get_default_variant',
610 'update_callback' => null,
611 'schema' => null,
612 )
613 );
614 function ams_get_default_variant( $object, $field_name, $request ) {
615
616 $product = wc_get_product( $object['id'] );
617 if ( $product->is_type( 'variable' ) ) {
618 $default_attributes = $product->get_default_attributes();
619 if ( ! empty( $default_attributes ) ) {
620 foreach ( $product->get_available_variations() as $variation_values ) {
621 foreach ( $variation_values['attributes'] as $key => $attribute_value ) {
622 $attribute_name = str_replace( 'attribute_', '', $key );
623 $default_value = $product->get_variation_default_attribute( $attribute_name );
624 if ( $default_value == $attribute_value ) {
625 $is_default_variation = true;
626 } else {
627 $is_default_variation = false;
628 break;
629 }
630 }
631 if ( $is_default_variation ) {
632 $variation_id = $variation_values['variation_id'];
633 break;
634 }
635 }
636 return $variation_id;
637 } else {
638 return 0;
639 }
640 } else {
641 return 0;
642 }
643
644 }
645
646 register_rest_field(
647 ['product','product_variation'],
648 'ams_product_points_reward',
649 array(
650 'get_callback' => 'ams_get_product_points_reward',
651 'update_callback' => null,
652 'schema' => null,
653 )
654 );
655 function ams_get_product_points_reward( $object, $field_name, $request ) {
656
657 $product = wc_get_product( $object['id'] );
658 $product_id = $object['id'];
659
660 if ( ! is_admin() && ! $product->is_type( 'variable' ) ) {
661 $_wc_max_points_earned = get_post_meta( $product_id, '_wc_max_points_earned' );
662 $_wc_min_points_earned = get_post_meta( $product_id, '_wc_min_points_earned' );
663 return get_post_meta( $product_id, '_wc_min_points_earned' );
664
665 } else {
666 return get_post_meta( $product_id, '_wc_points_earned' );
667 }
668
669 }
670
671 /******
672
673 * Get discout percentage in rest api
674 */
675 register_rest_field(
676 'product',
677 'ams_product_discount_percentage',
678 array(
679 'get_callback' => 'ams_get_product_discount_percentage',
680 'update_callback' => null,
681 'schema' => null,
682 )
683 );
684 function ams_get_product_discount_percentage( $object, $field_name, $request ) {
685
686 $product = wc_get_product( $object['id'] );
687 if ( $product->is_on_sale() && ! is_admin() && ! $product->is_type( 'variable' ) ) {
688 $regular_price = (float) $product->get_regular_price(); // Regular price
689 $sale_price = (float) $product->get_price();
690 $saving_price = wc_price( $regular_price - $sale_price );
691 $precision = 2;
692 $discount_percentage = round( 100 - ( $sale_price / $regular_price * 100 ), 2 );
693 return $discount_percentage;
694 } else {
695 return 0.00;
696 }
697
698 }
699
700 /******
701 * Added product display price in rest API to support show price inclusive/exclusive of tax.
702 ******/
703
704 register_rest_field(
705 ['product','product_variation'],
706 'ams_price_to_display',
707 array(
708 'get_callback' => 'ams_get_product_price_to_display',
709 'update_callback' => null,
710 'schema' => null,
711 )
712 );
713 function ams_get_product_price_to_display( $object, $field_name, $request ) {
714
715 $product = wc_get_product( $object['id'] );
716 $ams_price_to_display = wc_get_price_to_display($product,[]);
717 return $ams_price_to_display;
718
719 }
720
721 /******
722 * users_can_register settings for wordpress APIs
723 ******/
724
725 add_action('rest_api_init', function ()
726 {
727 register_setting('general', 'ams_users_can_register', array(
728 'show_in_rest' => true,
729 'type' => 'boolean',
730 'default' => get_option( 'users_can_register' )
731 ));
732 });
733
734 /******
735
736 * This adds product's thumbnail and medium images in the rest api for catalog listing.
737 ******/
738
739 function ams_prepare_product_images( $response, $post, $request ) {
740 global $_wp_additional_image_sizes;
741
742 if ( empty( $response->data ) ) {
743 return $response;
744 }
745 if (is_array($response->data['images']) || is_object($response->data['images'])) {
746 foreach ( $response->data['images'] as $key => $image ) {
747 $image_info = wp_get_attachment_image_src( $image['id'], 'thumbnail' );
748 $response->data['images'][ $key ]['thumbnail'] = $image_info[0];
749 $image_info = wp_get_attachment_image_src( $image['id'], 'medium' );
750 $response->data['images'][ $key ]['medium'] = $image_info[0];
751 }
752 }
753 return $response;
754 }
755
756 add_filter( 'woocommerce_rest_prepare_product_object', 'ams_prepare_product_images', 10, 3 );
757
758 function ams_prepare_product_attributes( $response, $post, $request ) {
759
760 if (is_array($response->data['attributes']) || is_object($response->data['attributes'])) {
761
762 if ( empty( $response->data['attributes'] ) ) {
763 return $response;
764 }
765 if ( $post->is_type( 'variable' ) ) {
766 $product_attributes = $post->get_attributes();
767 $ams_wc_product_attributes=[];
768
769 foreach( $post->get_attributes() as $attr_name => $attr ){
770 $attr->id = $attr->get_id();
771 $attr->slug = $attr_name;
772 $attr->terms = $attr->get_terms();
773 $attr->options_slugs = $attr->get_slugs();
774 $ams_wc_product_attributes["attribute_id_".$attr->get_id()] = $attr;
775 }
776
777 foreach ( $response->data['attributes'] as $key => $attributes ) {
778 if(isset($ams_wc_product_attributes['attribute_id_'.$attributes['id']])){
779 $slug = $ams_wc_product_attributes['attribute_id_'.$attributes['id']]->slug;
780 $terms = $ams_wc_product_attributes['attribute_id_'.$attributes['id']]->terms;
781 $options_slugs = $ams_wc_product_attributes['attribute_id_'.$attributes['id']]->options_slugs;
782 }else{
783 $slug = '';
784 $terms = [];
785 $options_slugs = [];
786 }
787
788 $response->data['attributes'][ $key ]['slug'] = $slug;
789 $response->data['attributes'][ $key ]['options_slugs'] = $options_slugs;
790 $response->data['attributes'][ $key ]['terms'] = $terms;
791 }
792 }
793 }
794 return $response;
795 }
796
797 add_filter( 'woocommerce_rest_prepare_product_object', 'ams_prepare_product_attributes', 10, 3 );
798
799
800 /******
801
802 * Provision for coupon in rest api. This modifies order by applying coupon immediately after creating the order.
803 * Adds checkout payment url in rest order api.
804 * Adds thumbnail image of product in get order api
805 */
806
807 add_filter( 'woocommerce_rest_prepare_shop_order_object', 'ams_rest_apply_coupon', 10, 3 );
808
809 function ams_rest_apply_coupon( $response, $object, $request ) {
810 // this section is to apply coupon
811 // If Reward point plugin is enabled #################
812 if ( in_array(
813 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
814 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
815 )
816 ) {
817 $already_redeemed = get_post_meta( $response->data['id'], '_wc_points_redeemed', true );
818 $order = wc_get_order( $response->data['id'] );
819 $wc_points_rewards_discount_amount = $order->get_meta( '_ams_wc_points_redeemed' );
820 if ( !empty( $wc_points_rewards_discount_amount )&& (int)$wc_points_rewards_discount_amount>0){
821 $customer_id = $request->get_param( 'customer_id' );
822 $line_items = $request->get_param( 'line_items' );
823 $reward_amount = ams_get_points_rewards_discount_amount( $customer_id, $wc_points_rewards_discount_amount, $line_items ); // to be calculated
824 $reward_coupon_code = sprintf( 'wc_points_redemption_%s_%s_@%u', $customer_id, date( 'Y_m_d_h_i', current_time( 'timestamp' ) ), $reward_amount );
825 // get actual point to be logged on the basis of allowed reward amount.
826 $actual_points_to_redeemed = WC_Points_Rewards_Manager::calculate_points_for_discount( $reward_amount );
827
828 // update_post_meta for reference
829 if ( empty( $already_redeemed ) && $reward_amount > 0 ) {
830 $results = $order->apply_coupon( $reward_coupon_code );
831 update_post_meta( $response->data['id'], '_ams_wc_points_redeemed', $actual_points_to_redeemed );
832 update_post_meta( $response->data['id'], '_ams_wc_points_rewards_discount_code', $reward_coupon_code );
833 update_post_meta( $response->data['id'], '_ams_wc_points_rewards_discount_amount', $reward_amount );
834
835 }
836 }
837 }
838 // If Reward point plugin is enabled #################
839
840 if ( ! empty( $request->get_param( 'coupon_lines' ) ) ) {
841 foreach ( $request->get_param( 'coupon_lines' ) as $item ) {
842 if ( is_array( $item ) ) {
843 if ( isset( $item['id'] ) ) {
844 if ( ! isset( $item['code'] ) ) {
845 throw new WC_REST_Exception( 'woocommerce_rest_invalid_coupon', __( 'Coupon code is required.', 'woocommerce' ), 400 );
846 }
847 $order = wc_get_order( $response->data['id'] );
848 $results = $order->apply_coupon( wc_clean( $item['code'] ) );
849
850 if ( is_wp_error( $results ) ) {
851 throw new WC_REST_Exception( 'woocommerce_rest_' . $results->get_error_code(), $results->get_error_message(), 400 );
852 }
853 return $response;
854 }
855 }
856 }
857 }
858 // this section is to add extra field into order api
859 $ams_order_checkout_url = ( $value = esc_url( $object->get_checkout_payment_url() ) ) ? $value : '';
860 $response->data['order_checkout_payment_url'] = html_entity_decode( $ams_order_checkout_url );
861 if ( ! empty( $response->data['line_items'] ) ) {
862 foreach ( $response->data['line_items'] as $key => $lineItem ) {
863 $product_id = $lineItem['product_id'];
864 $medium_url = wp_get_attachment_image_src( get_post_thumbnail_id( $product_id ), 'thumbnail' );
865 $response->data['line_items'][ $key ]['ams_order_thumbnail'] = $medium_url[0];
866 }
867 }
868
869 return $response;
870
871 }
872
873
874 /******
875
876 * Get all menu names.
877 ******/
878
879 function ams_get_menu_names() {
880
881 $nav_menu_locations = wp_get_nav_menus();
882 $result = [];
883 foreach((array)$nav_menu_locations as $item){
884 $result[$item->slug]=$item->term_id;
885 }
886 return( rest_ensure_response( $result ) );
887
888 }
889
890 /******
891
892 * Get all items of given menu.
893 ******/
894
895 function ams_get_menu_items( WP_REST_Request $request ) {
896
897 $menu_name = 'primary-menu'; // primary-menu, top
898
899 if ( isset( $request['menu_name'] ) ) {
900 $menu_name = $request['menu_name'];
901 }
902 $nav_menu_items = wp_get_nav_menu_items( $menu_name ); //slug,id
903 return( rest_ensure_response( $nav_menu_items ) );
904
905 }
906
907 /******
908
909 * Get all product and post categories in a binary tree.
910 ******/
911 function ams_categories() {
912
913 $orderby = 'name';
914 $order = 'asc';
915 $hide_empty = true;
916 $cat_args = array(
917 'orderby' => $orderby,
918 'order' => $order,
919 'hide_empty' => $hide_empty,
920 );
921
922 $product_categories = array_values( get_terms( 'product_cat', $cat_args ) );
923 $array_product_categories_items = json_decode( json_encode( $product_categories ), true );
924 if ( empty( $array_product_categories_items ) ) {
925 return rest_ensure_response( $array_product_categories_items );
926 }
927 $category_tree = ams_build_category_tree( $array_product_categories_items, 'parent', 'term_id' );
928 return rest_ensure_response( $category_tree );
929
930 }
931
932 function ams_post_categories() {
933
934 $orderby = 'name';
935 $order = 'asc';
936 $hide_empty = true;
937 $cat_args = array(
938 'orderby' => $orderby,
939 'order' => $order,
940 'hide_empty' => $hide_empty,
941 );
942
943 $product_categories = array_values( get_terms( 'category', $cat_args ) );
944 $array_product_categories_items = json_decode( json_encode( $product_categories ), true );
945 if ( empty( $array_product_categories_items ) ) {
946 return rest_ensure_response( $array_product_categories_items );
947 }
948 $category_tree = ams_build_category_tree( $array_product_categories_items, 'parent', 'term_id' );
949 return rest_ensure_response( $category_tree );
950
951 }
952
953
954 /******
955
956 * Cart items verification
957 ******/
958
959 function ams_verify_cart_items( WP_REST_Request $request ) {
960
961 $params = $request->get_params();
962 $validate = ams_basic_validate( $params, array( 'line_items' ) );
963 if ( $validate != true ) {
964 return $validate;
965 }
966
967 $line_items = $params['line_items'];
968 $result = array();
969 foreach ( $line_items as $key => $value ) {
970 if ( array_key_exists( 'variation_id', $value ) ) {
971
972 $variation = wc_get_product( $value['variation_id'] );
973
974 if ( $variation ) {
975 $result[ $key ]['product_id'] = $variation->get_id();
976 $result[ $key ]['variation_id'] = $value['variation_id'];
977 $result[ $key ]['name'] = $variation->get_name();
978 $result[ $key ]['type'] = $variation->get_type();
979 $result[ $key ]['status'] = $variation->get_status();
980 $result[ $key ]['price'] = $variation->get_price();
981 $result[ $key ]['regular_price'] = $variation->get_regular_price();
982 $result[ $key ]['sale_price'] = $variation->get_sale_price();
983 $result[ $key ]['manage_stock'] = $variation->get_manage_stock();
984 $result[ $key ]['stock_quantity'] = $variation->get_stock_quantity();
985 if ( $result[ $key ]['stock_quantity'] == null ) {
986 $result[ $key ]['stock_quantity'] = '';
987 }
988 $result[ $key ]['stock_status'] = $variation->get_stock_status();
989 $result[ $key ]['on_sale'] = $variation->is_on_sale();
990 if ( 1 == $result[ $key ]['on_sale'] ) {
991
992 $result[ $key ]['on_sale'] = true;
993 } else {
994 $result[ $key ]['on_sale'] = false;
995 }
996 }
997 } else {
998 // get product details
999 $product = wc_get_product( $value['product_id'] );
1000 if ( $product ) {
1001 $result[ $key ]['product_id'] = $product->get_id();
1002 $result[ $key ]['name'] = $product->get_name();
1003 $result[ $key ]['type'] = $product->get_type();
1004 $result[ $key ]['status'] = $product->get_status();
1005 $result[ $key ]['get_price'] = $product->get_price();
1006 $result[ $key ]['get_regular_price'] = $product->get_regular_price();
1007 $result[ $key ]['get_sale_price'] = $product->get_sale_price();
1008 $result[ $key ]['manage_stock'] = $product->get_manage_stock();
1009 $result[ $key ]['stock_quantity'] = $product->get_stock_quantity();
1010 if ( $result[ $key ]['stock_quantity'] == null ) {
1011 $result[ $key ]['stock_quantity'] = '';
1012 }
1013 $result[ $key ]['stock_status'] = $product->get_stock_status();
1014 $result[ $key ]['on_sale'] = $product->is_on_sale();
1015 if ( 1 == $result[ $key ]['on_sale'] ) {
1016 $result[ $key ]['on_sale'] = true;
1017 } else {
1018 $result[ $key ]['on_sale'] = false;
1019 }
1020 }
1021 }
1022 }
1023
1024 return rest_ensure_response( array( 'line_items' => $result ) );
1025 }
1026
1027
1028 add_action( 'pre_get_posts', 'ams_catalog_hidden_products_search_query_fix' );
1029
1030 function ams_catalog_hidden_products_search_query_fix( $query = false ) {
1031 if ( ! is_admin() && isset( $query->query['post_type'] ) && $query->query['post_type'] === 'product' ) {
1032 $tax_query = $query->get( 'tax_query' );
1033 if(!is_array($tax_query)){$tax_query=[];}
1034 array_push($tax_query,[
1035 'taxonomy' => 'product_visibility',
1036 'field' => 'name',
1037 'terms' => 'exclude-from-catalog',
1038 'operator' => 'NOT IN',
1039 ]);
1040 array_push($tax_query,[
1041 'taxonomy' => 'product_visibility',
1042 'field' => 'name',
1043 'terms' => 'exclude-from-catalog',
1044 'operator' => '!=',
1045 ]);
1046 $tax_query['relation']='AND';
1047 $query->set( 'tax_query', $tax_query );
1048 }
1049 }
1050
1051 /******
1052
1053 * Search API with support of multiple sort and order_by parameters .
1054 ******/
1055 function ams_product_search( WP_REST_Request $request ) {
1056
1057 $param = $request->get_params();
1058 $category = $param['category'];
1059 $filters = $param['filter'];
1060 $per_page = $param['per_page'];
1061 $page = $param['page'];
1062 $order = $param['order'];
1063 $orderby = $param['orderby'];
1064 $featured = $param['featured'];
1065 $on_sale = $param['on_sale'];
1066 $min_price = $param['min_price'];
1067 $max_price = $param['max_price'];
1068 $stock_status = $param['stock_status'];
1069 $output = array();
1070 // Use default arguments.
1071 $args = array(
1072 'post_type' => 'product',
1073 'posts_per_page' => get_option( 'posts_per_page' ),
1074 'post_status' => 'publish',
1075 'paged' => 1,
1076
1077 );
1078 // Posts per page.
1079 if ( ! empty( $per_page ) ) {
1080 $args['posts_per_page'] = $per_page;
1081 }
1082 // Pagination, starts from 1.
1083 if ( ! empty( $page ) ) {
1084 $args['paged'] = $page;
1085 }
1086
1087 // Order condition. ASC/DESC.
1088 if ( ! empty( $order ) ) {
1089 $args['order'] = $order;
1090 }
1091 // Order condition. ASC/DESC.
1092 if ( ! empty( $orderby ) ) {
1093 if ( $orderby == 'price' ) {
1094 $args['orderby'] = 'meta_value_num';
1095 $args['meta_key'] = '_price';
1096
1097 } elseif ( $orderby == 'popularity' ) { // For Popularity case, the sort order will always be desc.
1098 $args['orderby'] = 'meta_value_num';
1099 $args['meta_key'] = 'total_sales';
1100
1101 } else {
1102 $args['orderby'] = $orderby;
1103 }
1104 }
1105
1106 if ( ! empty( $featured ) ) {
1107 if ( $featured == true ) {
1108 $args['tax_query'][] = array(
1109 'taxonomy' => 'product_visibility',
1110 'field' => 'name',
1111 'terms' => 'featured',
1112 );
1113 }
1114 }
1115
1116 if ( ! empty( $on_sale ) ) {
1117 if ( $on_sale == true ) {
1118
1119 $args['meta_query'][] = array(
1120 'key' => '_sale_price',
1121 'value' => 0,
1122 'compare' => '>',
1123 'type' => 'numeric',
1124 );
1125 }
1126 }
1127 if ( ! empty( $stock_status ) ) {
1128 $args['meta_query'][] = array(
1129 'key' => '_stock_status',
1130 'value' => $stock_status,
1131 );
1132 }
1133 if ( isset( $min_price ) || isset( $max_price ) ) {
1134
1135 $price_request = array();
1136 if ( isset( $min_price ) ) {
1137 $price_request['min_price'] = $min_price;
1138 }
1139
1140 if ( isset( $max_price ) ) {
1141 $price_request['max_price'] = $max_price;
1142 }
1143 $args['meta_query'][] = wc_get_min_max_price_meta_query( $price_request );
1144 }
1145
1146 if ( ! empty( $category ) || ! empty( $filters ) ) {
1147
1148 $args['tax_query']['relation'] = 'AND';
1149 if ( ! empty( $category ) ) {
1150 $args['tax_query'][] = array(
1151 'taxonomy' => 'product_cat',
1152 'field' => 'id',
1153 'terms' => explode( ',', $category ), // [ $category ],
1154 'include_children' => true,
1155 );
1156 }
1157
1158 if ( ! empty( $filters ) ) {
1159 foreach ( $filters as $filter_key => $filter_value ) {
1160 if ( $filter_key === 'min_price' || $filter_key === 'max_price' ) {
1161 continue;
1162 }
1163 $args['tax_query'][] = array(
1164 'taxonomy' => $filter_key,
1165 'field' => 'term_id',
1166 'terms' => explode( ',', $filter_value ),
1167 );
1168 }
1169 }
1170 }
1171
1172 $the_query = new \WP_Query( $args );
1173
1174 if ( ! $the_query->have_posts() ) {
1175 return $output;
1176 }
1177 while ( $the_query->have_posts() ) {
1178 $the_query->the_post();
1179 $product_ids[] = $the_query->post->ID;
1180 $output[] = get_the_title();
1181 }
1182 wp_reset_postdata();
1183
1184 $request = new WP_REST_Request( 'GET', '/wc/v3/products' );
1185 $parameters = array( 'include' => $product_ids );
1186 if ( ! empty( $order ) ) {
1187 $parameters += array( 'order' => $order );
1188 }
1189 if ( ! empty( $orderby ) ) {
1190 $parameters += array( 'orderby' => $orderby );
1191 }
1192 if ( ! empty( $per_page ) ) {
1193 $parameters += array( 'per_page' => $per_page );
1194 }
1195 $request->set_query_params( $parameters );
1196 $response = rest_do_request( $request );
1197 $server = rest_get_server();
1198 $data = $server->response_to_data( $response, false );
1199 return rest_ensure_response( $data );
1200 }
1201
1202
1203 function ams_product_attributes( WP_REST_Request $request ) {
1204
1205 $param = $request->get_params();
1206
1207 $args = array(
1208 'status' => 'publish',
1209 'limit' => -1
1210 );
1211
1212 if(isset( $param['category'] )){
1213 $cat_name = get_term($param['category'], 'product_cat', ARRAY_A );
1214
1215 if(is_wp_error( $cat_name) ){
1216 status_header( 400 );
1217 echo ( json_encode(
1218 array(
1219 'message' => 'There is a problem with your input.',
1220 'error' => $cat_name->get_error_message(),
1221 ),
1222 JSON_UNESCAPED_UNICODE
1223 ) );
1224 die();
1225 }
1226 $args['category'] = array($cat_name['slug'] );
1227 }
1228
1229 if(isset( $param['stock_status'] )){
1230 $args['stock_status'] = $param['stock_status'];
1231 }
1232
1233 if(isset( $param['featured'] )){
1234 $args['featured'] = $param['featured'];
1235 }
1236
1237 if(isset( $param['on_sale'] )){
1238 $args['on_sale'] = $param['on_sale'];
1239 }
1240
1241 $result = [];
1242
1243 $filter_raw = array();
1244 $attrs_raw = wc_get_attribute_taxonomy_names();
1245 foreach( wc_get_products($args) as $product ){
1246 foreach( $product->get_attributes() as $attr_name => $attr ){
1247 $filter_raw[] = $attr_name;
1248 if(is_array($attr->get_terms())){
1249 foreach( $attr->get_terms() as $term ){
1250 $terms_raw[] = $term->name;
1251 }
1252 }
1253 }
1254 }
1255 $filters = array_unique(array_intersect((array)$filter_raw,(array)$attrs_raw));
1256
1257 if(is_array($filters)){
1258 foreach ( $filters as $key=>$filter ){
1259 $terms = get_terms( $filter );
1260 if ( ! empty( $terms ) ) {
1261
1262 $result[$key] = array(
1263 'id' => $filter,
1264 'label' => wc_attribute_label( $filter ) , //$this->decode_html
1265 );
1266 foreach ( $terms as $term ) {
1267 if(in_array($term->name,$terms_raw)){
1268 $result[$key]['values'][] = array(
1269 'label' => $term->name ,
1270 'value' => $term->slug,
1271 'term_id' => $term->term_id,
1272 'count' => $term->count,
1273 );
1274 }
1275 }
1276 }
1277 }
1278 }
1279
1280 return( rest_ensure_response( array_values($result )) );
1281
1282 }
1283
1284 /******
1285
1286 * Authenticate the user.
1287 ******/
1288
1289 function ams_login( WP_REST_Request $request ) {
1290
1291 $req = $request->get_json_params();
1292
1293 $validate = ams_basic_validate( $req, array( 'username', 'password' ) );
1294 if ( $validate != true ) {
1295 return $validate;
1296 }
1297 $wp_version = get_bloginfo( 'version' );
1298 $user = wp_authenticate( sanitize_text_field( $req['username'] ), sanitize_text_field( $req['password'] ) ); // htmlspecialchars
1299
1300 if ( isset( $user->errors ) ) {
1301 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1302 $error = new WP_Error();
1303 $error->add( 'message', __( $error_message . '' ) );
1304 return $error;
1305 } elseif ( isset( $user->data ) ) {
1306 $user->data->user_pass = '';
1307 $user->data->user_activation_key = '';
1308 $user->data->id = $user->ID; //integer
1309 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1310 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1311 $user->data->roles = $user->roles;
1312 $user->data->wp_version = $wp_version;
1313 return rest_ensure_response( $user->data );
1314 } else {
1315 return new WP_Error('ams_error', 'Something went wrong. Please contact support.', array('status' => 500));
1316 }
1317 }
1318
1319
1320 /******
1321
1322 * Verify the user.
1323 ******/
1324 function ams_verify_user( WP_REST_Request $request ) {
1325
1326 $req = $request->get_json_params();
1327
1328 $validate = ams_basic_validate( $req, array( 'username' ) );
1329 if ( $validate != true ) {
1330 return $validate;
1331 }
1332
1333 $is_email = is_email($req['username']);
1334 if(!$is_email){
1335 $user = get_user_by( 'login', $req['username'] ); // | ID | slug | email | login.
1336 }else{
1337 $user = get_user_by( 'email', $req['username'] ); // | ID | slug | email | login.
1338 if( isset( $user->errors ) ) {
1339 $user = get_user_by( 'login', $req['username'] ); // | ID | slug | email | login.
1340 }
1341 }
1342
1343 if ( isset( $user->errors ) ) {
1344 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1345 $error = new WP_Error();
1346 $error->add( 'message', __( $error_message . '' ) );
1347 return $error;
1348 } elseif ( isset( $user->data ) ) {
1349 $user->data->user_pass = '';
1350 $user->data->user_activation_key = '';
1351 $user->data->id = $user->ID; //integer
1352 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1353 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1354 $user->data->roles = $user->roles;
1355 return rest_ensure_response( $user->data );
1356 } else {
1357 return rest_ensure_response( array() ); // User not found.
1358 }
1359
1360 }
1361
1362 function ams_get_profile_meta( WP_REST_Request $request ) {
1363
1364 if ( isset( $request['id'] ) ) {
1365 $user_id = sanitize_text_field( $request['id'] );
1366 }
1367 $validate = ams_basic_validate( $req, array( 'id' ) );
1368 if ( $validate != true ) {
1369 return $validate;
1370 }
1371 $user_meta_data = get_user_meta( $user_id, 'wp_user_avatar', true );
1372 $profile_image_full_path = wp_get_attachment_image_src( $user_meta_data );
1373 return rest_ensure_response( array( 'wp_user_avatar' => $profile_image_full_path ) );
1374 }
1375
1376 /******
1377
1378 * get check out payment url.
1379 * Note: This will be removed in next vesrion.
1380 ******/
1381 function ams_get_order_payment_url( WP_REST_Request $request ) {
1382
1383 $req = $request->get_json_params();
1384 $validate = ams_basic_validate( $req, array( 'order_id' ) );
1385 if ( $validate != true ) {
1386 return $validate;
1387 }
1388 $order_id = sanitize_text_field( $req['order_id'] );
1389 $order = wc_get_order( $order_id ); // Returns WC_Product|null|false
1390 if ( ! isset( $order ) || $order == false ) {
1391 $error = new WP_Error();
1392 $error->add( 'message', __( 'The order ID appears to be invalid. Please try again.' ) );
1393 return $error;
1394 } // Verify Valid Order ID
1395 $pay_now_url = esc_url( $order->get_checkout_payment_url() );
1396 return( rest_ensure_response( html_entity_decode( $pay_now_url ) ) );
1397 }
1398
1399 function ams_wp_get_user_auth_cookies( WP_REST_Request $request ) {
1400
1401 $user_id = sanitize_text_field($request->get_param('user_id'));
1402 $user = get_user_by( 'ID', $user_id ); // | ID | slug | email | login.
1403 if ( isset( $user->errors ) ) {
1404 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1405 $error = new WP_Error();
1406 $error->add( 'message', __( $error_message . '' ) );
1407 return $error;
1408 } elseif ( isset( $user->data ) ) {
1409 $user->data->user_pass = '';
1410 $user->data->user_activation_key = '';
1411 $user->data->id = $user->ID; //integer
1412 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1413 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1414 $user->data->roles = $user->roles;
1415 ####get user wp_generate_auth_cookie####
1416 $expiration = time() + apply_filters('auth_cookie_expiration', 14 * DAY_IN_SECONDS , $user->ID, true);
1417 $site_url = get_site_url();//get_site_option('site_url');
1418 if($site_url){$cookie_hash=md5($site_url);}else{$cookie_hash='';}
1419 $user->data->expiration = $expiration;
1420 //$user->data->expire = $expiration + ( 12 * HOUR_IN_SECONDS );
1421 $user->data->cookie_hash = $cookie_hash;
1422 $user->data->wordpress_logged_in_ = wp_generate_auth_cookie($user->ID, $expiration, 'logged_in');
1423 $user->data->wordpress_ = wp_generate_auth_cookie($user->ID, $expiration, 'secure_auth');
1424 ########################################
1425 return rest_ensure_response( $user->data );
1426 } else {
1427 return new WP_Error('ams_error', 'Something went wrong. Please contact support.', array('status' => 500));
1428 }
1429 }
1430
1431 /******
1432
1433 * Sends rest password link on user's email.
1434 ******/
1435
1436 function ams_send_password_reset_link( WP_REST_Request $request ) {
1437 $req = $request->get_json_params();
1438 $validate = ams_basic_validate( $req, array( 'email' ) );
1439 if ( $validate != true ) {
1440 return $validate;
1441 }
1442 $email = sanitize_email( $req['email'] );
1443 $user = get_user_by( 'email', $email );
1444 if ( ! $user ) {
1445 $error = new WP_Error();
1446 $error->add( 'message', __( 'The email address appears to be incorrect. Please try again.' ) );
1447 return $error;
1448 }
1449 $firstname = $user->first_name;
1450 $email = $user->user_email;
1451 $user_login = $user->user_login;
1452 $retrieve_password = retrieve_password($user_login);
1453
1454 if ( isset( $retrieve_password->errors ) ) {
1455 $error_message = strip_tags( ams_convert_error_to_string( $retrieve_password->errors ) );
1456 $error = new WP_Error();
1457 $error->add( 'message', __( $error_message . '' ) );
1458 return $error;
1459 }
1460
1461 return( rest_ensure_response( array( 'message' => 'Reset Password link sent successfully!' ) ) );
1462
1463 }
1464
1465
1466 /******
1467
1468 * Calculates shipping methods based on cart-items (line_items) , shipping address and coupon.
1469 ******/
1470
1471 function ams_applicable_shipping_method( WP_REST_Request $request ) {
1472
1473 $req = $request->get_json_params();
1474 $validate = ams_basic_validate( $req, array( 'shipping', 'line_items' ) );
1475 if ( $validate != true ) {
1476 return $validate;
1477 }
1478
1479 $shipping = $req['shipping'];
1480 $line_items = $req['line_items'];
1481 $customer_id = 0 ;
1482 if(isset( $req[ 'customer_id' ] )){
1483 $customer_id = sanitize_text_field( $req[ 'customer_id' ] );
1484 }
1485
1486 $content = [];
1487 wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
1488 wc()->frontend_includes();
1489 WC()->session = new WC_Session_Handler();
1490 WC()->customer = new WC_Customer( $customer_id, true );
1491 WC()->initialize_cart();
1492 WC()->cart->empty_cart();
1493 foreach ( $line_items as $key => $value ) { // prepare cart content which will be used for table rate plugin
1494 if ( array_key_exists( 'variation_id', $value ) ) {
1495 WC()->cart->add_to_cart($value['product_id'], $value['quantity'], $value['variation_id'] );
1496 }else{
1497 WC()->cart->add_to_cart($value['product_id'], $value['quantity'] );
1498 }
1499 }
1500
1501 WC()->customer->set_shipping_first_name(isset($shipping['first_name'])?$shipping['first_name']:'');
1502 WC()->customer->set_shipping_last_name(isset($shipping['last_name'])?$shipping['last_name']:'');
1503 WC()->customer->set_shipping_address_1(isset($shipping['address_1'])?$shipping['address_1']:'');
1504 WC()->customer->set_shipping_address_2(isset($shipping['address_2'])?$shipping['address_2']:'');
1505 WC()->customer->set_shipping_city(isset($shipping['city'])?$shipping['city']:'');
1506 WC()->customer->set_shipping_postcode(isset($shipping['postcode'])?$shipping['postcode']:'');
1507 WC()->customer->set_shipping_country(isset($shipping['country'])? $shipping['country'] :'');
1508 WC()->customer->set_shipping_state(isset($shipping['state'])? $shipping['state']: '');
1509
1510 if(isset( $req[ 'coupon_lines' ] )){
1511 if(!empty( $req[ 'coupon_lines' ] )){
1512 $coupon_code = sanitize_text_field( $req[ 'coupon_lines' ][0]['code'] );
1513 WC()->cart->add_discount( $coupon_code );
1514 }
1515 }
1516
1517 WC()->cart->calculate_shipping();
1518 WC()->cart->calculate_totals();
1519
1520 $packages = apply_filters('woocommerce_cart_shipping_packages', WC()->cart->get_shipping_packages());
1521 $shipping_packages = WC()->shipping->calculate_shipping($packages);
1522
1523 $all_shipping_packages_rates = array();
1524 foreach($shipping_packages as $package){
1525 $pacakage_rates=array();
1526 foreach($package['rates'] as $rate){
1527
1528 $pacakage_rate = array();
1529 $pacakage_rate['id']=(string)$rate->get_instance_id();
1530 $pacakage_rate['title']=$rate->get_label();
1531 $pacakage_rate['method_id']=$rate->get_method_id();
1532 $pacakage_rate['cost']=number_format((float)$rate->get_cost(), 2, '.', '');
1533 $pacakage_rate['tax']= number_format((float)$rate->get_shipping_tax(), 2, '.', '');
1534 array_push($pacakage_rates,$pacakage_rate);
1535 }
1536 if(empty($pacakage_rates)){
1537 return( rest_ensure_response( $pacakage_rates ) );
1538 }
1539 array_push($all_shipping_packages_rates,$pacakage_rates);
1540 }
1541
1542 $result_methods=$all_shipping_packages_rates[0];
1543 for($i=1;$i<count($all_shipping_packages_rates);++$i){
1544 $result_methods = merge_shipping_methods($result_methods,$all_shipping_packages_rates[$i]);
1545 }
1546 WC()->cart->empty_cart();
1547 WC()->session->destroy_session();
1548 return( rest_ensure_response( $result_methods ) );
1549 }
1550
1551 function merge_shipping_methods($methods1,$methods2){
1552 $result=array();
1553 foreach($methods1 as $method1){
1554 foreach($methods2 as $method2){
1555 $current=$method2;
1556 if(($method1["method_id"]=="local_pickup"||$method1["method_id"]=="free_shipping")&&(!in_array($methods2["method_id"],
1557 array("flat_rate","free_shipping","local_pickup")))){
1558 $current["method_id"]="flat_rate";
1559 }
1560 if($method1['method_id']=="local_pickup"&&$methods2["method_id"]=="free_shipping"){
1561 $current["method_id"]=$method1['method_id'];
1562 $current["id"]=$method1['id'];
1563
1564 }
1565 if($method1['method_id']=="flat_rate"){
1566 $current["method_id"]=$method1['method_id'];
1567 $current["id"]=$method1['id'];
1568
1569 }
1570 $current["title"].=" + ".$method1['title'];
1571 $current["cost"]+=$method1['cost'];
1572 array_push($result,$current);
1573 }
1574
1575 }
1576 return $result;
1577 }
1578
1579
1580 function ams_checkout_fields() {
1581 if ( in_array(
1582 'woocommerce-checkout-field-editor/woocommerce-checkout-field-editor.php',
1583 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1584 )
1585 ) {
1586 $result['checkout_shipping_fields'] = ams_object_to_array( get_option( 'wc_fields_shipping', array() ) );
1587 $result['checkout_billing_fields'] = ams_object_to_array( get_option( 'wc_fields_billing', array() ) );
1588 $result['checkout_additional_fields'] = ams_object_to_array( get_option( 'wc_fields_additional', array() ) );
1589 return rest_ensure_response( $result );
1590 } else {
1591 return rest_ensure_response( array() );
1592 }
1593 }
1594
1595 function ams_wc_points_rewards_effective_discount( WP_REST_Request $request ) {
1596 if ( in_array(
1597 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
1598 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1599 )
1600 ) {
1601 $params = $request->get_params();
1602 $line_items = $params['line_items'];
1603 $customer_id = $params['customer_id'];
1604 $wc_points_rewards_discount_amount = $params['wc_points_rewards_discount_amount'];
1605 $granted_user_discount = 0;
1606
1607 // Construct local cart
1608 if ( is_null( WC()->cart ) ) {
1609 wc_load_cart();
1610 }
1611 WC()->cart->empty_cart();
1612 foreach ( $line_items as $key => $value ) {
1613 if(!isset($value['variation'])){$value['variation']= [];}
1614 if ( array_key_exists( 'variation_id', $value ) ) {
1615 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'], $value['variation_id'], $value['variation'] );
1616 } else {
1617 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'] );
1618 }
1619 }
1620
1621 // Verify Global settings of points and reward plugin
1622 $available_user_discount = WC_Points_Rewards_Manager::get_users_points_value( $customer_id );
1623
1624 // no discount
1625 if ( $available_user_discount <= 0 ) {
1626 // return 0;
1627 $error = new WP_Error();
1628 $error->add( 'message', __( 'No reward point available.' ) );
1629 return $error;
1630 }
1631
1632 if ( 'yes' === get_option( 'wc_points_rewards_partial_redemption_enabled' ) && $wc_points_rewards_discount_amount ) {
1633 $requested_user_discount = WC_Points_Rewards_Manager::calculate_points_value( $wc_points_rewards_discount_amount );
1634 if ( $requested_user_discount > 0 && $requested_user_discount < $available_user_discount ) {
1635 $available_user_discount = $requested_user_discount;
1636 }
1637 }
1638
1639 // Limit the discount available by the global minimum discount if set.
1640 $minimum_discount = get_option( 'wc_points_rewards_cart_min_discount', '' );
1641 if ( $minimum_discount > $available_user_discount ) {
1642 // return 0;
1643 $error = new WP_Error();
1644 $error->add( 'message', __( 'Please enter atleast '.$minimum_discount.' points global minimum discount error.' ) );
1645 return $error;
1646 }
1647
1648 // apply product level setting of point and reward plugin.
1649 $discount_applied = 0;
1650
1651 if ( ! did_action( 'woocommerce_before_calculate_totals' ) ) {
1652 WC()->cart->calculate_totals();
1653 }
1654
1655 $max_points_discount_of_all_products = 0;
1656 foreach ( WC()->cart->get_cart() as $item_key => $item ) {
1657
1658 $discount = 0;
1659 $max_discount = WC_Points_Rewards_Product::get_maximum_points_discount_for_product( $item['data'] );
1660
1661 if ( is_numeric( $max_discount ) ) {
1662
1663 // adjust the max discount by the quantity being ordered
1664 $max_discount *= $item['quantity'];
1665
1666
1667 // if the discount available is greater than the max discount, apply the max discount
1668 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
1669
1670 // Max should be product price. As this will be applied before tax, it will respect other coupons.
1671 } else {
1672 /*
1673 * Only exclude taxes when configured to in settings and when generating a discount amount for displaying in
1674 * the checkout message. This makes the actual discount money amount always tax inclusive.
1675 */
1676 if ( 'exclusive' === get_option( 'wc_points_rewards_points_tax_application', wc_prices_include_tax() ? 'inclusive' : 'exclusive' ) && $for_display ) {
1677 if ( function_exists( 'wc_get_price_excluding_tax' ) ) {
1678 $max_discount = wc_get_price_excluding_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
1679 } elseif ( method_exists( $item['data'], 'get_price_excluding_tax' ) ) {
1680 $max_discount = $item['data']->get_price_excluding_tax( $item['quantity'] );
1681 } else {
1682 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
1683 }
1684 } else {
1685 if ( function_exists( 'wc_get_price_including_tax' ) ) {
1686 $max_discount = wc_get_price_including_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
1687 } elseif ( method_exists( $item['data'], 'get_price_including_tax' ) ) {
1688 $max_discount = $item['data']->get_price_including_tax( $item['quantity'] );
1689 } else {
1690 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
1691 }
1692 }
1693
1694 // if the discount available is greater than the max discount, apply the max discount
1695 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
1696 }
1697
1698 $max_points_discount_of_all_products += $max_discount ;
1699
1700 // add the discount to the amount to be applied
1701 $discount_applied += $discount;
1702
1703 // reduce the remaining discount available to be applied
1704 $available_user_discount -= $discount;
1705 }
1706 // limit customer if requested amount to avail discount exceeds the product's maximum discount.
1707 /*
1708 if($wc_points_rewards_discount_amount > $max_points_discount_of_all_products){
1709 $error = new WP_Error();
1710 $error->add( 'message', __( 'You cannot enter more than '.$max_points_discount_of_all_products.' points on these products.' ) );
1711 return $error;
1712 }
1713 */
1714
1715 $existing_discount_amounts = version_compare( WC_VERSION, '3.0.0', '<' )? WC()->cart->discount_total: WC()->cart->get_cart_discount_total();
1716
1717 // if the available discount is greater than the order total, make the discount equal to the order total less any other discounts
1718 if ( version_compare( WC_VERSION, '3.0.0', '<' ) ) {
1719 if ( 'no' === get_option( 'woocommerce_prices_include_tax' ) ) {
1720 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal_ex_tax - $existing_discount_amounts ) );
1721
1722 } else {
1723 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal - $existing_discount_amounts ) );
1724
1725 }
1726 } else {
1727 if ( 'no' === get_option( 'woocommerce_prices_include_tax' ) ) {
1728 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal_ex_tax - $existing_discount_amounts ) );
1729
1730 } else {
1731 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal - $existing_discount_amounts ) );
1732 }
1733 }
1734
1735 // limit the discount available by the global maximum discount if set
1736 $max_discount = get_option( 'wc_points_rewards_cart_max_discount' );
1737
1738 if ( false !== strpos( $max_discount, '%' ) ) {
1739 $max_discount = ams_ams_calculate_discount_modifier( $max_discount );
1740 }
1741 $max_discount = filter_var( $max_discount, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
1742
1743 if ( $max_discount && $max_discount < $discount_applied ) {
1744 $error = new WP_Error();
1745 $error->add( 'message', __( 'You cannot enter more than '.$max_discount.' points.' ) );
1746 return $error;
1747 //$discount_applied = $max_discount;
1748 }
1749 $discount_applied = filter_var( $discount_applied, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
1750 return rest_ensure_response( array( array( 'effective_discount_value' => (float) $discount_applied ) ) );
1751
1752 } else {
1753 return rest_ensure_response( array() );
1754 }
1755 }
1756
1757 function ams_wc_points_rewards_settings() {
1758 if ( in_array(
1759 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
1760 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1761 )
1762 ) {
1763
1764 $result['wc_points_rewards_cart_max_discount'] = get_option( 'wc_points_rewards_cart_max_discount' );
1765 $result['wc_points_rewards_write_review_points'] = get_option( 'wc_points_rewards_write_review_points' );
1766 $result['wc_points_rewards_account_signup_points'] = get_option( 'wc_points_rewards_account_signup_points' );
1767 $result['wc_points_rewards_points_expiry'] = get_option( 'wc_points_rewards_points_expiry' );
1768 $result['wc_points_rewards_points_expire_points_since'] = get_option( 'wc_points_rewards_points_expire_points_since' );
1769 $result['wc_points_rewards_version'] = get_option( 'wc_points_rewards_version' );
1770 $result['wc_points_rewards_earn_points_ratio'] = get_option( 'wc_points_rewards_earn_points_ratio', '' );
1771 $result['wc_points_rewards_earn_points_rounding'] = get_option( 'wc_points_rewards_earn_points_rounding' );
1772 $result['wc_points_rewards_redeem_points_ratio'] = get_option( 'wc_points_rewards_redeem_points_ratio', '' );
1773 $result['wc_points_rewards_partial_redemption_enabled'] = get_option( 'wc_points_rewards_partial_redemption_enabled' );
1774 $result['wc_points_rewards_cart_min_discount'] = get_option( 'wc_points_rewards_cart_min_discount' );
1775 $result['wc_points_rewards_max_discount'] = get_option( 'wc_points_rewards_max_discount' );
1776 $result['wc_points_rewards_points_tax_application'] = get_option( 'wc_points_rewards_points_tax_application' );
1777 $result['wc_points_rewards_points_expiry_number'] = get_option( 'wc_points_rewards_points_expiry_number' );
1778 $result['wc_points_rewards_points_expiry_period'] = get_option( 'wc_points_rewards_points_expiry_period' );
1779 $result['wc_points_rewards_single_product_message'] = get_option( 'wc_points_rewards_single_product_message' );
1780 $result['wc_points_rewards_variable_product_message'] = get_option( 'wc_points_rewards_variable_product_message' );
1781 $result['wc_points_rewards_earn_points_message'] = get_option( 'wc_points_rewards_earn_points_message' );
1782 $result['wc_points_rewards_redeem_points_message'] = get_option( 'wc_points_rewards_redeem_points_message' );
1783 $result['wc_points_rewards_thank_you_message'] = get_option( 'wc_points_rewards_thank_you_message' );
1784
1785 return rest_ensure_response( $result );
1786 } else {
1787 return rest_ensure_response( array() );
1788 }
1789 }
1790
1791 add_filter( 'woocommerce_get_shop_coupon_data', 'ams_create_virtual_coupon', 10, 2 );
1792
1793 function ams_create_virtual_coupon( $false, $data ) {
1794
1795 // Do not interfere with coupon creation and editing.
1796 if ( is_admin() ) {
1797 return $false;
1798 }
1799 $coupon_code_valid = false;
1800 $coupon_settings = null;
1801 $coupon_amount = 0;
1802 if ( ams_is_coupon_code_valid( $data ) ) {
1803 $coupon_code_valid = true;
1804 }
1805 if ( ( $pos = strpos( $data, '@' ) ) !== false ) {
1806 $coupon_amount = (float) substr( $data, $pos + 1 );
1807 }
1808 // Create a coupon with the properties you need
1809 if ( $coupon_code_valid ) {
1810 $coupon_settings = array(
1811 'id' => true,
1812 'discount_type' => 'fixed_cart', // 'fixed_cart', 'percent' or 'fixed_product'
1813 'amount' => $coupon_amount, // value or percentage.
1814 'expiry_date' => date( 'Y-m-d', strtotime( 'tomorrow' ) ), // YYYY-MM-DD
1815 'individual_use' => false,
1816 'product_ids' => array(),
1817 'exclude_product_ids' => array(),
1818 'usage_limit' => '1',
1819 'usage_limit_per_user' => '1',
1820 'limit_usage_to_x_items' => '',
1821 'usage_count' => '',
1822 'free_shipping' => false,
1823 'product_categories' => array(),
1824 'exclude_product_categories' => array(),
1825 'exclude_sale_items' => false,
1826 'minimum_amount' => '',
1827 'maximum_amount' => '',
1828 'customer_email' => array(),
1829 );
1830
1831 return $coupon_settings;
1832 } else {
1833 return false;
1834 }
1835
1836 }
1837
1838 add_action( 'rest_api_init', 'ams_create_api_customer_field' );
1839
1840 function ams_create_api_customer_field() {
1841
1842 // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
1843 register_rest_field(
1844 'customer',
1845 'ams-rewards-points-balance',
1846 array(
1847 'get_callback' => 'ams_get_rewards_points_balance',
1848 'schema' => null,
1849 )
1850 );
1851 }
1852
1853 function ams_get_rewards_points_balance( $object ) {
1854 if ( in_array(
1855 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
1856 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1857 )
1858 ) {
1859 // get the value of the user's point balance
1860 $available_user_discount = WC_Points_Rewards_Manager::get_users_points( $object['id'] );
1861 // return the post meta
1862 return (float) $available_user_discount;
1863 } else {
1864 return 0;
1865 }
1866 }
1867
1868 add_action( 'woocommerce_order_status_processing', 'ams_order_processing' );
1869 function ams_order_processing( $order_id ) {
1870
1871 if ( in_array(
1872 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
1873 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1874 )
1875 ) { // order-redeem
1876 $already_redeemed = get_post_meta( $order_id, '_wc_points_redeemed', true );
1877 $logged_redemption = get_post_meta( $order_id, '_wc_points_logged_redemption', true );
1878
1879 // Points has already been redeemed
1880 if ( ! empty( $already_redeemed ) ) {
1881 return;
1882 }
1883 $order = wc_get_order( $order_id );
1884 $customer_id = version_compare( WC_VERSION, '3.0', '<' ) ? $order->user_id : $order->get_user_id();
1885
1886 // bail for guest user
1887 if ( ! $customer_id ) {
1888 return;
1889 }
1890
1891 $discount_code = $order->get_meta( '_ams_wc_points_rewards_discount_code' );
1892
1893 if ( ! empty( $logged_redemption ) ) {
1894 $points_redeemed = $logged_redemption['points'];
1895 $discount_amount = $logged_redemption['amount'];
1896 $discount_code = $logged_redemption['discount_code'];
1897 } else {
1898 $points_redeemed = $order->get_meta( '_ams_wc_points_redeemed' );
1899 // bail if ams is not involved
1900 if ( ! $points_redeemed ) {
1901 return;
1902 }
1903 // Get amount of discount
1904 $discount_amount = $order->get_meta( '_ams_wc_points_rewards_discount_amount' );
1905
1906 }
1907 WC_Points_Rewards_Manager::decrease_points(
1908 $customer_id,
1909 $points_redeemed,
1910 'order-redeem',
1911 array(
1912 'discount_code' => $discount_code,
1913 'discount_amount' => $discount_amount,
1914 ),
1915 $order_id
1916 );
1917 update_post_meta( $order_id, '_wc_points_redeemed', $points_redeemed );
1918 update_post_meta(
1919 $order_id,
1920 '_wc_points_logged_redemption',
1921 array(
1922 'points' => $points_redeemed,
1923 'amount' => $discount_amount,
1924 'discount_code' => $discount_code,
1925 )
1926 );
1927
1928 // add order note
1929 /* translators: 1: points earned 2: points label 3: discount amount */
1930 $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 ) ) );
1931
1932 }
1933
1934 }
1935 function ams_change_password(WP_REST_Request $request){
1936
1937 $req = $request->get_json_params();
1938
1939 $user = wp_authenticate( sanitize_email( $req['username'] ), sanitize_text_field( $req['password'] ) ); // htmlspecialchars
1940 $customer_id = sanitize_text_field( $req['customer_id'] );
1941 $old_password = sanitize_text_field( $req['old_password'] );
1942 $new_password = sanitize_text_field( $req['new_password'] );
1943 $confirm_password = sanitize_text_field( $req['confirm_password'] );
1944
1945 $user = get_user_by( 'id', $customer_id );
1946 if ( isset( $user->errors ) ) {
1947 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1948 $error = new WP_Error();
1949 $error->add( 'message', __( $error_message . '' ) );
1950 return $error;
1951 }
1952
1953 $x = wp_check_password( $old_password, $user->data->user_pass, $user->data->ID );
1954
1955 if ( isset( $x->errors ) ) {
1956 $error_message = strip_tags( ams_convert_error_to_string( $x->errors ) );
1957 $error = new WP_Error();
1958 $error->add( 'message', __( $error_message . '' ) );
1959 return $error;
1960 }
1961 if($x)
1962 {
1963 if($new_password == $old_password)
1964 {
1965 return new WP_Error( 'ams_error', 'Sorry, your new password and old password can not be the same.', array( 'status' => 422 ) );
1966 }
1967 if($new_password == $confirm_password)
1968 {
1969 $user_data['ID'] = $user->data->ID;
1970 $user_data['user_pass'] = $new_password;
1971 $uid = wp_update_user( $user_data );
1972 //wp_set_password($new_password , $user_id);
1973 if($uid)
1974 {
1975 unset($passdata);
1976 $user->data->user_pass = '';
1977 $user->data->user_activation_key = '';
1978 $user->data->id = $user->ID; //integer
1979 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1980 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1981 $user->data->roles = $user->roles;
1982 return rest_ensure_response( $user->data );
1983 } else {
1984 return new WP_Error( 'ams_error', 'Sorry, your account was not updated. Please try again later.', array( 'status' => 422 ) );
1985 }
1986 }
1987 else
1988 {
1989 return new WP_Error( 'ams_error', 'Sorry, both your passwords do not match. Please try again. ', array( 'status' => 422 ) );
1990 }
1991 }
1992 else
1993 {
1994 return new WP_Error( 'ams_error', 'Sorry, your old password is not correct. Please try again.', array( 'status' => 422 ) );
1995 }
1996
1997 }
1998
1999 // //
2000 // Other Helping Function ###########################################//
2001 // //
2002 function ams_get_points_rewards_discount_amount( $customer_id, $wc_points_rewards_discount_amount, $line_items ) {
2003
2004 if ( empty( $line_items ) ) {
2005 return 0;
2006 }
2007
2008 $granted_user_discount = 0;
2009 // Construct local cart
2010 if ( is_null( WC()->cart ) ) {
2011 wc_load_cart();
2012 }
2013 WC()->cart->empty_cart();
2014
2015 foreach ( $line_items as $key => $value ) {
2016 if ( array_key_exists( 'variation_id', $value ) ) {
2017 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'], $value['variation_id'] );
2018 } else {
2019 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'] );
2020 }
2021 }
2022
2023 $available_user_discount = WC_Points_Rewards_Manager::get_users_points_value( $customer_id );
2024
2025 // no discount
2026 if ( $available_user_discount <= 0 ) {
2027 return 0;
2028 }
2029 if ( 'yes' === get_option( 'wc_points_rewards_partial_redemption_enabled' ) && $wc_points_rewards_discount_amount ) {
2030 $requested_user_discount = WC_Points_Rewards_Manager::calculate_points_value( $wc_points_rewards_discount_amount );
2031 if ( $requested_user_discount > 0 && $requested_user_discount < $available_user_discount ) {
2032 $available_user_discount = $requested_user_discount;
2033 }
2034 }
2035
2036 // Limit the discount available by the global minimum discount if set.
2037 $minimum_discount = get_option( 'wc_points_rewards_cart_min_discount', '' );
2038 if ( $minimum_discount > $available_user_discount ) {
2039 return 0;
2040 }
2041 $discount_applied = 0;
2042
2043 if ( ! did_action( 'woocommerce_before_calculate_totals' ) ) {
2044 WC()->cart->calculate_totals();
2045 }
2046
2047 foreach ( WC()->cart->get_cart() as $item_key => $item ) {
2048
2049 $discount = 0;
2050 $max_discount = WC_Points_Rewards_Product::get_maximum_points_discount_for_product( $item['data'] );
2051
2052 if ( is_numeric( $max_discount ) ) {
2053
2054 // adjust the max discount by the quantity being ordered
2055 $max_discount *= $item['quantity'];
2056
2057 // if the discount available is greater than the max discount, apply the max discount
2058 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
2059
2060 // Max should be product price. As this will be applied before tax, it will respect other coupons.
2061 } else {
2062 /*
2063 * Only exclude taxes when configured to in settings and when generating a discount amount for displaying in
2064 * the checkout message. This makes the actual discount money amount always tax inclusive.
2065 */
2066 if ( 'exclusive' === get_option( 'wc_points_rewards_points_tax_application', wc_prices_include_tax() ? 'inclusive' : 'exclusive' ) && $for_display ) {
2067 if ( function_exists( 'wc_get_price_excluding_tax' ) ) {
2068 $max_discount = wc_get_price_excluding_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
2069 } elseif ( method_exists( $item['data'], 'get_price_excluding_tax' ) ) {
2070 $max_discount = $item['data']->get_price_excluding_tax( $item['quantity'] );
2071 } else {
2072 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
2073 }
2074 } else {
2075 if ( function_exists( 'wc_get_price_including_tax' ) ) {
2076 $max_discount = wc_get_price_including_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
2077 } elseif ( method_exists( $item['data'], 'get_price_including_tax' ) ) {
2078 $max_discount = $item['data']->get_price_including_tax( $item['quantity'] );
2079 } else {
2080 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
2081 }
2082 }
2083
2084 // if the discount available is greater than the max discount, apply the max discount
2085 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
2086 }
2087
2088 // add the discount to the amount to be applied
2089 $discount_applied += $discount;
2090
2091 // reduce the remaining discount available to be applied
2092 $available_user_discount -= $discount;
2093 }
2094 // limit the discount available by the global maximum discount if set
2095 $max_discount = get_option( 'wc_points_rewards_cart_max_discount' );
2096
2097 if ( false !== strpos( $max_discount, '%' ) ) {
2098 $max_discount = ams_calculate_discount_modifier( $max_discount );
2099 WC()->cart->empty_cart();
2100 }
2101 $max_discount = filter_var( $max_discount, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
2102
2103 if ( $max_discount && $max_discount < $discount_applied ) {
2104 $discount_applied = $max_discount;
2105 }
2106 // clear cart before returning
2107 WC()->cart->empty_cart();
2108 $discount_applied = filter_var( $discount_applied, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
2109 return $discount_applied;
2110
2111 }
2112
2113 function ams_get_points_label( $count ) {
2114
2115 list( $singular, $plural ) = explode( ':', get_option( 'wc_points_rewards_points_label' ) );
2116
2117 return 1 == $count ? $singular : $plural;
2118 }
2119 function ams_is_coupon_code_valid( $coupon_code ) {
2120 if ( 0 === strpos( $coupon_code, 'wc_points_redemption_' ) ) {
2121 return true;
2122 }
2123 return false;
2124 }
2125
2126 function ams_calculate_discount_modifier( $percentage ) {
2127
2128 $percentage = str_replace( '%', '', $percentage ) / 100;
2129
2130 if ( 'no' === get_option( 'woocommerce_prices_include_tax' ) ) {
2131 $discount = WC()->cart->subtotal_ex_tax;
2132
2133 } else {
2134 $discount = WC()->cart->subtotal;
2135
2136 }
2137
2138 return $percentage * $discount;
2139 }
2140
2141 function ams_object_to_array( $data ) {
2142 if ( is_array( $data ) || is_object( $data ) ) {
2143 $result = array();
2144 foreach ( $data as $key => $value ) {
2145 $value['field_name'] = $key;
2146 $value['options'] = array_values( $value['options'] );
2147 $result[] = $value;
2148
2149 }
2150 return $result;
2151 }
2152 return $data;
2153 }
2154
2155 function ams_build_category_tree( $flat, $pidKey, $idKey = null ) {
2156 $grouped = array();
2157 foreach ( $flat as $sub ) {
2158 $grouped[ $sub[ $pidKey ] ][] = $sub;
2159 }
2160 $level = 0;
2161 $fnBuilder = function( $siblings, $level ) use ( &$fnBuilder, $grouped, $idKey ) {
2162 foreach ( $siblings as $k => $sibling ) {
2163 if ( $sibling['slug'] == 'uncategorized' ) {
2164 unset( $siblings[ $k ] );
2165 continue;
2166 }
2167 $id = $sibling[ $idKey ];
2168 $sibling['description'] = '';
2169 $level++;
2170 if ( isset( $grouped[ $id ] ) ) {
2171 $sibling['depth'] = $level;
2172 $sibling['children'] = array_values( $fnBuilder( $grouped[ $id ], $level ) );
2173 } else {
2174 $sibling['depth'] = $level;
2175 $sibling['children'] = array();
2176 }
2177 $siblings[ $k ] = $sibling;
2178 $level--;
2179 }
2180 return $siblings;
2181 };
2182
2183 if ( isset( $grouped[0] ) ) {
2184 $tree = $fnBuilder( $grouped[0], $level );
2185 }
2186 if ( ! empty( $tree ) ) {
2187 return array_values( $tree );
2188 } else {
2189 foreach ( $flat as $key => $value ) {
2190 if ( $value['slug'] == 'uncategorized' ) {
2191 unset( $flat[ $key ] );
2192 continue;
2193 }
2194 $flat[ $key ]['children'] = array();
2195 }
2196 return array_values( $flat );
2197 }
2198 }
2199
2200 function ams_convert_error_to_string( $er ) {
2201 $string = ' ';
2202 foreach ( $er as $key => $value ) {
2203
2204 $string = $string . '' . $key . ':';
2205 foreach ( $value as $newkey => $newvalue ) {
2206
2207 $string = $string . '' . $newvalue . ' ';
2208 }
2209 }
2210 $string = str_replace( 'Lost your password?', '', $string );
2211 $string = str_replace( 'Error:', '', $string );
2212 $string = str_replace( '[message]', '', $string );
2213 return( $string );
2214 }
2215
2216 function ams_basic_validate( $request, $keys ) {
2217 foreach ( $keys as $key => $value ) {
2218
2219 if ( ! isset( $request[ $value ] ) ) {
2220 status_header( 400 );
2221 echo ( json_encode(
2222 array(
2223 'message' => 'There is a problem with your input!',
2224 'error' => $value . ': Field is required!',
2225 ),
2226 JSON_UNESCAPED_UNICODE
2227 ) );
2228 die();
2229 }
2230 if ( empty( $request[ $value ] ) ) {
2231 status_header( 400 );
2232 echo ( json_encode(
2233 array(
2234 'message' => 'There is a problem with your input!',
2235 'error' => $value . ': Can not be empty!',
2236 ),
2237 JSON_UNESCAPED_UNICODE
2238 ) );
2239 die();
2240 }
2241 }
2242 return true;
2243 }
2244
2245 require_once untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/includes/ams-plugin-deactivation-survey.php';
2246
2247 add_action( 'wp_ajax_ams_deactivation_form_submit', 'ams_deactivation_form_submit' );
2248
2249 add_action('admin_enqueue_scripts', 'ams_admin_enqueue_scripts');
2250 function ams_admin_enqueue_scripts(){
2251
2252 $current_page = get_current_screen()->base;
2253
2254 if($current_page == 'plugins' || $current_page == 'plugins-network') {
2255
2256 add_action('admin_footer', 'ams_deactivation_popup');
2257
2258 wp_register_script('ams_jquery', 'https://code.jquery.com/jquery-3.6.0.min.js', array(), '3.6.0', true); // jQuery v3
2259 wp_enqueue_script('ams_jquery');
2260 wp_script_add_data( 'ams_jquery', array( 'integrity', 'crossorigin' ) , array( 'sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=', 'anonymous' ) );
2261
2262 wp_enqueue_script('ams_plugin_deactivation_survey_js', plugins_url('assets/plugin-deactivation-survey.js', __FILE__), array('ams_jquery'));
2263 wp_localize_script('ams_plugin_deactivation_survey_js', 'frontend_ajax_object', array('amsDeactivationSurveyNonce' => wp_create_nonce('ajax-nonce')));
2264 wp_enqueue_style( 'ams_plugin_deactivation_survey_css', plugins_url('assets/plugin-deactivation-survey.css', __FILE__), array());
2265
2266
2267 } else { // # if not on plugins, deregister and dequeue styles & scripts
2268
2269 wp_dequeue_script('ams_jquery');
2270 wp_dequeue_script('ams_plugin_deactivation_survey_js');
2271 wp_dequeue_style('ams_plugin_deactivation_survey_css');
2272
2273 }
2274 }
2275
2276