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

2,324 lines 74.2 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.8.0
7 * Author: AppMySite
8 * Text Domain: appmysite
9 * Author URI: https://appmysite.com
10 * Tested up to: 6.1.1
11 * WC tested up to: 7.1.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 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_@%f', $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 $output = array();
1059 // Use default arguments.
1060 $args = array(
1061 'post_type' => 'product',
1062 'posts_per_page' => get_option( 'posts_per_page' ),
1063 'post_status' => 'publish',
1064 'paged' => 1,
1065
1066 );
1067 // Posts per page.
1068 if ( ! empty( $param['per_page'] ) ) {
1069 $args['posts_per_page'] = $param['per_page'];
1070 }
1071 // Pagination, starts from 1.
1072 if ( ! empty( $param['page'] ) ) {
1073 $args['paged'] = $param['page'];
1074 }
1075
1076 // Order condition. ASC/DESC.
1077 if ( ! empty( $param['order'] ) ) {
1078 $args['order'] = $param['order'];
1079 }
1080 // Order condition. ASC/DESC.
1081 if ( ! empty( $param['orderby'] ) ) {
1082 $orderby = $param['orderby'];
1083 if ( $orderby == 'price' ) {
1084 $args['orderby'] = 'meta_value_num';
1085 $args['meta_key'] = '_price';
1086
1087 } elseif ( $orderby == 'popularity' ) { // For Popularity case, the sort order will always be desc.
1088 $args['orderby'] = 'meta_value_num';
1089 $args['meta_key'] = 'total_sales';
1090
1091 } else {
1092 $args['orderby'] = $orderby;
1093 }
1094 }
1095
1096 if ( ! empty( $param['featured'] ) ) {
1097 if ( $param['featured'] == true ) {
1098 $args['tax_query'][] = array(
1099 'taxonomy' => 'product_visibility',
1100 'field' => 'name',
1101 'terms' => 'featured',
1102 );
1103 }
1104 }
1105
1106 if ( ! empty( $param['on_sale'] ) ) {
1107 $on_sale = $param['on_sale'];
1108 if($on_sale === 'true' || $on_sale === 'TRUE' || $on_sale === 'True' || $on_sale === 'on' || $on_sale === 'On' || $on_sale === 'ON'|| $on_sale === "1" || $on_sale === 1 ){
1109 $on_sale = true;
1110 }else{
1111 $on_sale = false;
1112 }
1113 if( is_bool( $on_sale ) ) { //|| $on_sale =='true' || $on_sale=='false'
1114
1115 $on_sale_key = $on_sale ? 'post__in' : 'post__not_in';
1116 $on_sale_ids = wc_get_product_ids_on_sale();
1117
1118 // Use 0 when there's no on sale products to avoid return all products.
1119 $on_sale_ids = empty( $on_sale_ids ) ? array( 0 ) : $on_sale_ids;
1120
1121 $args[ $on_sale_key ] = $on_sale_ids;
1122
1123 }
1124 }
1125
1126
1127
1128 if ( ! empty( $param['stock_status'] ) ) {
1129 $args['meta_query'][] = array(
1130 'key' => '_stock_status',
1131 'value' => $param['stock_status'],
1132 );
1133 }
1134
1135 if ( isset( $param['min_price'] ) || isset( $param['max_price'] ) ) {
1136
1137 $price_request = array();
1138 if ( isset( $param['min_price'] ) ) {
1139 $price_request['min_price'] = $param['min_price'];
1140 }
1141
1142 if ( isset( $param['max_price'] ) ) {
1143 $price_request['max_price'] = $param['max_price'];
1144 }
1145 $args['meta_query'][] = wc_get_min_max_price_meta_query( $price_request );
1146 }
1147
1148 if ( ! empty( $param['category'] ) || ! empty( $param['filter'] ) || !empty( $param['tag'] ) ) {
1149
1150 $args['tax_query']['relation'] = 'AND';
1151 if ( ! empty( $param['category'] ) ) {
1152 $args['tax_query'][] = array(
1153 'taxonomy' => 'product_cat',
1154 'field' => 'id',
1155 'terms' => explode( ',', $param['category'] ), // [ $category ],
1156 );
1157 }
1158
1159 if ( ! empty( $param['tag'] ) ) {
1160 $args['tax_query'][] = array(
1161 'taxonomy' => 'product_tag',
1162 'field' => 'id',
1163 'terms' => explode( ',', $param['tag'] ), // [ $tag ],
1164 );
1165 }
1166
1167 if ( ! empty( $param['filter'] ) ) {
1168 foreach ( $param['filter'] as $filter_key => $filter_value ) {
1169 if ( $filter_key === 'min_price' || $filter_key === 'max_price' ) {
1170 continue;
1171 }
1172 $args['tax_query'][] = array(
1173 'taxonomy' => $filter_key,
1174 'field' => 'term_id',
1175 'terms' => explode( ',', $filter_value ),
1176 );
1177 }
1178 }
1179 }
1180
1181 $the_query = new \WP_Query( $args );
1182
1183 if ( ! $the_query->have_posts() ) {
1184 return $output;
1185 }
1186 while ( $the_query->have_posts() ) {
1187 $the_query->the_post();
1188 $product_ids[] = $the_query->post->ID;
1189 $output[] = get_the_title();
1190 }
1191 wp_reset_postdata();
1192
1193 $request = new WP_REST_Request( 'GET', '/wc/v3/products' );
1194 $parameters = array( 'include' => $product_ids );
1195 if ( ! empty( $order ) ) {
1196 $parameters += array( 'order' => $order );
1197 }
1198 if ( ! empty( $orderby ) ) {
1199 $parameters += array( 'orderby' => $orderby );
1200 }
1201 if ( ! empty( $per_page ) ) {
1202 $parameters += array( 'per_page' => $per_page );
1203 }
1204 $request->set_query_params( $parameters );
1205 $response = rest_do_request( $request );
1206 $server = rest_get_server();
1207 $data = $server->response_to_data( $response, false );
1208 return rest_ensure_response( $data );
1209 }
1210
1211
1212 function ams_product_attributes( WP_REST_Request $request ) {
1213
1214 $param = $request->get_params();
1215
1216 $args = array(
1217 'status' => 'publish',
1218 'limit' => -1
1219 );
1220
1221 if(isset( $param['category'] )){
1222 $cat_name = get_term($param['category'], 'product_cat', ARRAY_A );
1223
1224 if(is_wp_error( $cat_name) ){
1225 status_header( 400 );
1226 echo ( json_encode(
1227 array(
1228 'message' => 'There is a problem with your input.',
1229 'error' => $cat_name->get_error_message(),
1230 ),
1231 JSON_UNESCAPED_UNICODE
1232 ) );
1233 die();
1234 }
1235 $args['category'] = array($cat_name['slug'] );
1236 }
1237
1238 if(isset( $param['stock_status'] )){
1239 $args['stock_status'] = $param['stock_status'];
1240 }
1241
1242 if(isset( $param['featured'] )){
1243 $args['featured'] = $param['featured'];
1244 }
1245
1246 if(isset( $param['on_sale'] )){
1247 $args['on_sale'] = $param['on_sale'];
1248 }
1249
1250 if(isset( $param['tag'] )){
1251 $args['tag'] = $param['tag'];
1252 }
1253
1254 $result = [];
1255
1256 $filter_raw = array();
1257 $attrs_raw = wc_get_attribute_taxonomy_names();
1258 foreach( wc_get_products($args) as $product ){
1259 foreach( $product->get_attributes() as $attr_name => $attr ){
1260 $filter_raw[] = $attr_name;
1261 if(is_array($attr->get_terms())){
1262 foreach( $attr->get_terms() as $term ){
1263 $terms_raw[] = $term->name;
1264 }
1265 }
1266 }
1267 }
1268 $filters = array_unique(array_intersect((array)$filter_raw,(array)$attrs_raw));
1269
1270 if(is_array($filters)){
1271 foreach ( $filters as $key=>$filter ){
1272 $terms = get_terms( $filter );
1273 if ( ! empty( $terms ) ) {
1274
1275 $result[$key] = array(
1276 'id' => $filter,
1277 'label' => wc_attribute_label( $filter ) , //$this->decode_html
1278 );
1279 foreach ( $terms as $term ) {
1280 if(in_array($term->name,$terms_raw)){
1281 $result[$key]['values'][] = array(
1282 'label' => $term->name ,
1283 'value' => $term->slug,
1284 'term_id' => $term->term_id,
1285 'count' => $term->count,
1286 );
1287 }
1288 }
1289 }
1290 }
1291 }
1292
1293 return( rest_ensure_response( array_values($result )) );
1294
1295 }
1296
1297 /******
1298
1299 * Authenticate the user.
1300 ******/
1301
1302 function ams_login( WP_REST_Request $request ) {
1303
1304 $req = $request->get_json_params();
1305
1306 $validate = ams_basic_validate( $req, array( 'username', 'password' ) );
1307 if ( $validate != true ) {
1308 return $validate;
1309 }
1310 $wp_version = get_bloginfo( 'version' );
1311 $user = wp_authenticate( sanitize_text_field( $req['username'] ), sanitize_text_field( $req['password'] ) ); // htmlspecialchars
1312
1313 if ( isset( $user->errors ) ) {
1314 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1315 $error = new WP_Error();
1316 $error->add( 'message', __( $error_message . '' ) );
1317 return $error;
1318 } elseif ( isset( $user->data ) ) {
1319 $user->data->user_pass = '';
1320 $user->data->user_activation_key = '';
1321 $user->data->id = $user->ID; //integer
1322 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1323 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1324 $user->data->roles = $user->roles;
1325 $user->data->wp_version = $wp_version;
1326 return rest_ensure_response( $user->data );
1327 } else {
1328 return new WP_Error('ams_error', 'Something went wrong. Please contact support.', array('status' => 500));
1329 }
1330 }
1331
1332
1333 /******
1334
1335 * Verify the user.
1336 ******/
1337 function ams_verify_user( WP_REST_Request $request ) {
1338
1339 $req = $request->get_json_params();
1340
1341 $validate = ams_basic_validate( $req, array( 'username' ) );
1342 if ( $validate != true ) {
1343 return $validate;
1344 }
1345
1346 $is_email = is_email($req['username']);
1347 if(!$is_email){
1348 $user = get_user_by( 'login', $req['username'] ); // | ID | slug | email | login.
1349 }else{
1350 $user = get_user_by( 'email', $req['username'] ); // | ID | slug | email | login.
1351 if( isset( $user->errors ) ) {
1352 $user = get_user_by( 'login', $req['username'] ); // | ID | slug | email | login.
1353 }
1354 }
1355
1356 if ( isset( $user->errors ) ) {
1357 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1358 $error = new WP_Error();
1359 $error->add( 'message', __( $error_message . '' ) );
1360 return $error;
1361 } elseif ( isset( $user->data ) ) {
1362 $user->data->user_pass = '';
1363 $user->data->user_activation_key = '';
1364 $user->data->id = $user->ID; //integer
1365 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1366 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1367 $user->data->roles = $user->roles;
1368 return rest_ensure_response( $user->data );
1369 } else {
1370 return rest_ensure_response( array() ); // User not found.
1371 }
1372
1373 }
1374
1375 function ams_get_profile_meta( WP_REST_Request $request ) {
1376
1377 if ( isset( $request['id'] ) ) {
1378 $user_id = sanitize_text_field( $request['id'] );
1379 }
1380 $validate = ams_basic_validate( $req, array( 'id' ) );
1381 if ( $validate != true ) {
1382 return $validate;
1383 }
1384 $user_meta_data = get_user_meta( $user_id, 'wp_user_avatar', true );
1385 $profile_image_full_path = wp_get_attachment_image_src( $user_meta_data );
1386 return rest_ensure_response( array( 'wp_user_avatar' => $profile_image_full_path ) );
1387 }
1388
1389 /******
1390
1391 * get check out payment url.
1392 * Note: This will be removed in next vesrion.
1393 ******/
1394 function ams_get_order_payment_url( WP_REST_Request $request ) {
1395
1396 $req = $request->get_json_params();
1397 $validate = ams_basic_validate( $req, array( 'order_id' ) );
1398 if ( $validate != true ) {
1399 return $validate;
1400 }
1401 $order_id = sanitize_text_field( $req['order_id'] );
1402 $order = wc_get_order( $order_id ); // Returns WC_Product|null|false
1403 if ( ! isset( $order ) || $order == false ) {
1404 $error = new WP_Error();
1405 $error->add( 'message', __( 'The order ID appears to be invalid. Please try again.' ) );
1406 return $error;
1407 } // Verify Valid Order ID
1408 $pay_now_url = esc_url( $order->get_checkout_payment_url() );
1409 return( rest_ensure_response( html_entity_decode( $pay_now_url ) ) );
1410 }
1411
1412 function ams_wp_get_user_auth_cookies( WP_REST_Request $request ) {
1413
1414 $user_id = sanitize_text_field($request->get_param('user_id'));
1415 $user = get_user_by( 'ID', $user_id ); // | ID | slug | email | login.
1416 if ( isset( $user->errors ) ) {
1417 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1418 $error = new WP_Error();
1419 $error->add( 'message', __( $error_message . '' ) );
1420 return $error;
1421 } elseif ( isset( $user->data ) ) {
1422 $user->data->user_pass = '';
1423 $user->data->user_activation_key = '';
1424 $user->data->id = $user->ID; //integer
1425 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1426 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1427 $user->data->roles = $user->roles;
1428 ####get user wp_generate_auth_cookie####
1429 $expiration = time() + apply_filters('auth_cookie_expiration', 14 * DAY_IN_SECONDS , $user->ID, true);
1430 $site_url = get_site_url();//get_site_option('site_url');
1431 if($site_url){$cookie_hash=md5($site_url);}else{$cookie_hash='';}
1432 $user->data->expiration = $expiration;
1433 //$user->data->expire = $expiration + ( 12 * HOUR_IN_SECONDS );
1434 $user->data->cookie_hash = $cookie_hash;
1435 $user->data->wordpress_logged_in_ = wp_generate_auth_cookie($user->ID, $expiration, 'logged_in');
1436 $user->data->wordpress_ = wp_generate_auth_cookie($user->ID, $expiration, 'secure_auth');
1437 ########################################
1438 return rest_ensure_response( $user->data );
1439 } else {
1440 return new WP_Error('ams_error', 'Something went wrong. Please contact support.', array('status' => 500));
1441 }
1442 }
1443
1444 /******
1445
1446 * Sends rest password link on user's email.
1447 ******/
1448
1449 function ams_send_password_reset_link( WP_REST_Request $request ) {
1450 $req = $request->get_json_params();
1451 $validate = ams_basic_validate( $req, array( 'email' ) );
1452 if ( $validate != true ) {
1453 return $validate;
1454 }
1455 $email = sanitize_email( $req['email'] );
1456 $user = get_user_by( 'email', $email );
1457 if ( ! $user ) {
1458 $error = new WP_Error();
1459 $error->add( 'message', __( 'The email address appears to be incorrect. Please try again.' ) );
1460 return $error;
1461 }
1462 $firstname = $user->first_name;
1463 $email = $user->user_email;
1464 $user_login = $user->user_login;
1465 $retrieve_password = retrieve_password($user_login);
1466
1467 if ( isset( $retrieve_password->errors ) ) {
1468 $error_message = strip_tags( ams_convert_error_to_string( $retrieve_password->errors ) );
1469 $error = new WP_Error();
1470 $error->add( 'message', __( $error_message . '' ) );
1471 return $error;
1472 }
1473
1474 return( rest_ensure_response( array( 'message' => 'Reset Password link sent successfully!' ) ) );
1475
1476 }
1477
1478
1479 /******
1480
1481 * Calculates shipping methods based on cart-items (line_items) , shipping address and coupon.
1482 ******/
1483
1484 function ams_applicable_shipping_method( WP_REST_Request $request ) {
1485
1486 $req = $request->get_json_params();
1487 $validate = ams_basic_validate( $req, array( 'shipping', 'line_items' ) );
1488 if ( $validate != true ) {
1489 return $validate;
1490 }
1491
1492 $shipping = $req['shipping'];
1493 $line_items = $req['line_items'];
1494 $customer_id = 0 ;
1495 if(isset( $req[ 'customer_id' ] )){
1496 $customer_id = sanitize_text_field( $req[ 'customer_id' ] );
1497 }
1498
1499 $content = [];
1500 wc_maybe_define_constant( 'WOOCOMMERCE_CART', true );
1501 wc()->frontend_includes();
1502 WC()->session = new WC_Session_Handler();
1503 WC()->customer = new WC_Customer( $customer_id, true );
1504 WC()->initialize_cart();
1505 WC()->cart->empty_cart();
1506 foreach ( $line_items as $key => $value ) { // prepare cart content which will be used for table rate plugin
1507 if ( array_key_exists( 'variation_id', $value ) ) {
1508 WC()->cart->add_to_cart($value['product_id'], $value['quantity'], $value['variation_id'] );
1509 }else{
1510 WC()->cart->add_to_cart($value['product_id'], $value['quantity'] );
1511 }
1512 }
1513
1514 WC()->customer->set_shipping_first_name(isset($shipping['first_name'])?$shipping['first_name']:'');
1515 WC()->customer->set_shipping_last_name(isset($shipping['last_name'])?$shipping['last_name']:'');
1516 WC()->customer->set_shipping_address_1(isset($shipping['address_1'])?$shipping['address_1']:'');
1517 WC()->customer->set_shipping_address_2(isset($shipping['address_2'])?$shipping['address_2']:'');
1518 WC()->customer->set_shipping_city(isset($shipping['city'])?$shipping['city']:'');
1519 WC()->customer->set_shipping_postcode(isset($shipping['postcode'])?$shipping['postcode']:'');
1520 WC()->customer->set_shipping_country(isset($shipping['country'])? $shipping['country'] :'');
1521 WC()->customer->set_shipping_state(isset($shipping['state'])? $shipping['state']: '');
1522
1523 if(isset( $req[ 'coupon_lines' ] )){
1524 if(!empty( $req[ 'coupon_lines' ] )){
1525 $coupon_code = sanitize_text_field( $req[ 'coupon_lines' ][0]['code'] );
1526 WC()->cart->add_discount( $coupon_code );
1527 }
1528 }
1529
1530 WC()->cart->calculate_shipping();
1531 WC()->cart->calculate_totals();
1532
1533 $packages = apply_filters('woocommerce_cart_shipping_packages', WC()->cart->get_shipping_packages());
1534 $shipping_packages = WC()->shipping->calculate_shipping($packages);
1535
1536 $all_shipping_packages_rates = array();
1537 foreach($shipping_packages as $package){
1538 $pacakage_rates=array();
1539 foreach($package['rates'] as $rate){
1540
1541 $pacakage_rate = array();
1542 $pacakage_rate['id']=(string)$rate->get_instance_id();
1543 $pacakage_rate['title']=$rate->get_label();
1544 $pacakage_rate['method_id']=$rate->get_method_id();
1545 $pacakage_rate['cost']=number_format((float)$rate->get_cost(), 2, '.', '');
1546 $pacakage_rate['tax']= number_format((float)$rate->get_shipping_tax(), 2, '.', '');
1547 array_push($pacakage_rates,$pacakage_rate);
1548 }
1549 if(empty($pacakage_rates)){
1550 return( rest_ensure_response( $pacakage_rates ) );
1551 }
1552 array_push($all_shipping_packages_rates,$pacakage_rates);
1553 }
1554
1555 $result_methods=$all_shipping_packages_rates[0];
1556 for($i=1;$i<count($all_shipping_packages_rates);++$i){
1557 $result_methods = merge_shipping_methods($result_methods,$all_shipping_packages_rates[$i]);
1558 }
1559 WC()->cart->empty_cart();
1560 WC()->session->destroy_session();
1561 return( rest_ensure_response( $result_methods ) );
1562 }
1563
1564 function merge_shipping_methods($methods1,$methods2){
1565 $result=array();
1566 foreach($methods1 as $method1){
1567 foreach($methods2 as $method2){
1568 $current=$method2;
1569 if(($method1["method_id"]=="local_pickup"||$method1["method_id"]=="free_shipping")&&(!in_array($methods2["method_id"],
1570 array("flat_rate","free_shipping","local_pickup")))){
1571 $current["method_id"]="flat_rate";
1572 }
1573 if($method1['method_id']=="local_pickup"&&$methods2["method_id"]=="free_shipping"){
1574 $current["method_id"]=$method1['method_id'];
1575 $current["id"]=$method1['id'];
1576
1577 }
1578 if($method1['method_id']=="flat_rate"){
1579 $current["method_id"]=$method1['method_id'];
1580 $current["id"]=$method1['id'];
1581
1582 }
1583 $current["title"].=" + ".$method1['title'];
1584 $current["cost"]+=$method1['cost'];
1585 array_push($result,$current);
1586 }
1587
1588 }
1589 return $result;
1590 }
1591
1592
1593 function ams_checkout_fields() {
1594 if ( in_array(
1595 'woocommerce-checkout-field-editor/woocommerce-checkout-field-editor.php',
1596 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1597 )
1598 ) {
1599 $result['checkout_shipping_fields'] = ams_object_to_array( get_option( 'wc_fields_shipping', array() ) );
1600 $result['checkout_billing_fields'] = ams_object_to_array( get_option( 'wc_fields_billing', array() ) );
1601 $result['checkout_additional_fields'] = ams_object_to_array( get_option( 'wc_fields_additional', array() ) );
1602 return rest_ensure_response( $result );
1603 } else {
1604 return rest_ensure_response( array() );
1605 }
1606 }
1607
1608 function ams_wc_points_rewards_effective_discount( WP_REST_Request $request ) {
1609 if ( in_array(
1610 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
1611 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1612 )
1613 ) {
1614 $params = $request->get_params();
1615 $line_items = $params['line_items'];
1616 $customer_id = $params['customer_id'];
1617 $wc_points_rewards_discount_amount = $params['wc_points_rewards_discount_amount'];
1618 $granted_user_discount = 0;
1619
1620 // Construct local cart
1621 if ( is_null( WC()->cart ) ) {
1622 wc_load_cart();
1623 }
1624 WC()->cart->empty_cart();
1625 foreach ( $line_items as $key => $value ) {
1626 if(!isset($value['variation'])){$value['variation']= [];}
1627 if ( array_key_exists( 'variation_id', $value ) ) {
1628 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'], $value['variation_id'], $value['variation'] );
1629 } else {
1630 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'] );
1631 }
1632 }
1633
1634 // Verify Global settings of points and reward plugin
1635 $available_user_discount = WC_Points_Rewards_Manager::get_users_points_value( $customer_id );
1636
1637 // no discount
1638 if ( $available_user_discount <= 0 ) {
1639 // return 0;
1640 $error = new WP_Error();
1641 $error->add( 'message', __( 'No reward point available.' ) );
1642 return $error;
1643 }
1644
1645 if ( 'yes' === get_option( 'wc_points_rewards_partial_redemption_enabled' ) && $wc_points_rewards_discount_amount ) {
1646 $requested_user_discount = WC_Points_Rewards_Manager::calculate_points_value( $wc_points_rewards_discount_amount );
1647 if ( $requested_user_discount > 0 && $requested_user_discount < $available_user_discount ) {
1648 $available_user_discount = $requested_user_discount;
1649 }
1650 }
1651
1652 // Limit the discount available by the global minimum discount if set.
1653 $minimum_discount = get_option( 'wc_points_rewards_cart_min_discount', '' );
1654 if ( $minimum_discount > $available_user_discount ) {
1655 // return 0;
1656 $error = new WP_Error();
1657 $error->add( 'message', __( 'Please enter atleast '.$minimum_discount.' points global minimum discount error.' ) );
1658 return $error;
1659 }
1660
1661 // apply product level setting of point and reward plugin.
1662 $discount_applied = 0;
1663
1664 if ( ! did_action( 'woocommerce_before_calculate_totals' ) ) {
1665 WC()->cart->calculate_totals();
1666 }
1667
1668 $max_points_discount_of_all_products = 0;
1669 foreach ( WC()->cart->get_cart() as $item_key => $item ) {
1670
1671 $discount = 0;
1672 $max_discount = WC_Points_Rewards_Product::get_maximum_points_discount_for_product( $item['data'] );
1673
1674 if ( is_numeric( $max_discount ) ) {
1675
1676 // adjust the max discount by the quantity being ordered
1677 $max_discount *= $item['quantity'];
1678
1679
1680 // if the discount available is greater than the max discount, apply the max discount
1681 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
1682
1683 // Max should be product price. As this will be applied before tax, it will respect other coupons.
1684 } else {
1685 /*
1686 * Only exclude taxes when configured to in settings and when generating a discount amount for displaying in
1687 * the checkout message. This makes the actual discount money amount always tax inclusive.
1688 */
1689 if ( 'exclusive' === get_option( 'wc_points_rewards_points_tax_application', wc_prices_include_tax() ? 'inclusive' : 'exclusive' ) && $for_display ) {
1690 if ( function_exists( 'wc_get_price_excluding_tax' ) ) {
1691 $max_discount = wc_get_price_excluding_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
1692 } elseif ( method_exists( $item['data'], 'get_price_excluding_tax' ) ) {
1693 $max_discount = $item['data']->get_price_excluding_tax( $item['quantity'] );
1694 } else {
1695 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
1696 }
1697 } else {
1698 if ( function_exists( 'wc_get_price_including_tax' ) ) {
1699 $max_discount = wc_get_price_including_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
1700 } elseif ( method_exists( $item['data'], 'get_price_including_tax' ) ) {
1701 $max_discount = $item['data']->get_price_including_tax( $item['quantity'] );
1702 } else {
1703 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
1704 }
1705 }
1706
1707 // if the discount available is greater than the max discount, apply the max discount
1708 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
1709 }
1710
1711 $max_points_discount_of_all_products += $max_discount ;
1712
1713 // add the discount to the amount to be applied
1714 $discount_applied += $discount;
1715
1716 // reduce the remaining discount available to be applied
1717 $available_user_discount -= $discount;
1718 }
1719 // limit customer if requested amount to avail discount exceeds the product's maximum discount.
1720 /*
1721 if($wc_points_rewards_discount_amount > $max_points_discount_of_all_products){
1722 $error = new WP_Error();
1723 $error->add( 'message', __( 'You cannot enter more than '.$max_points_discount_of_all_products.' points on these products.' ) );
1724 return $error;
1725 }
1726 */
1727
1728 $existing_discount_amounts = version_compare( WC_VERSION, '3.0.0', '<' )? WC()->cart->discount_total: WC()->cart->get_cart_discount_total();
1729
1730 // if the available discount is greater than the order total, make the discount equal to the order total less any other discounts
1731 if ( version_compare( WC_VERSION, '3.0.0', '<' ) ) {
1732 if ( 'no' === get_option( 'woocommerce_prices_include_tax' ) ) {
1733 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal_ex_tax - $existing_discount_amounts ) );
1734
1735 } else {
1736 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal - $existing_discount_amounts ) );
1737
1738 }
1739 } else {
1740 if ( 'no' === get_option( 'woocommerce_prices_include_tax' ) ) {
1741 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal_ex_tax - $existing_discount_amounts ) );
1742
1743 } else {
1744 $discount_applied = max( 0, min( $discount_applied, WC()->cart->subtotal - $existing_discount_amounts ) );
1745 }
1746 }
1747
1748 // limit the discount available by the global maximum discount if set
1749 $max_discount = get_option( 'wc_points_rewards_cart_max_discount' );
1750
1751 if ( false !== strpos( $max_discount, '%' ) ) {
1752 $max_discount = ams_ams_calculate_discount_modifier( $max_discount );
1753 }
1754 $max_discount = filter_var( $max_discount, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
1755
1756 if ( $max_discount && $max_discount < $discount_applied ) {
1757 $error = new WP_Error();
1758 $error->add( 'message', __( 'You cannot enter more than '.$max_discount.' points.' ) );
1759 return $error;
1760 //$discount_applied = $max_discount;
1761 }
1762 $discount_applied = filter_var( $discount_applied, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
1763 return rest_ensure_response( array( array( 'effective_discount_value' => (float) $discount_applied ) ) );
1764
1765 } else {
1766 return rest_ensure_response( array() );
1767 }
1768 }
1769
1770 function ams_wc_points_rewards_settings() {
1771 if ( in_array(
1772 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
1773 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1774 )
1775 ) {
1776
1777 $result['wc_points_rewards_cart_max_discount'] = get_option( 'wc_points_rewards_cart_max_discount' );
1778 $result['wc_points_rewards_write_review_points'] = get_option( 'wc_points_rewards_write_review_points' );
1779 $result['wc_points_rewards_account_signup_points'] = get_option( 'wc_points_rewards_account_signup_points' );
1780 $result['wc_points_rewards_points_expiry'] = get_option( 'wc_points_rewards_points_expiry' );
1781 $result['wc_points_rewards_points_expire_points_since'] = get_option( 'wc_points_rewards_points_expire_points_since' );
1782 $result['wc_points_rewards_version'] = get_option( 'wc_points_rewards_version' );
1783 $result['wc_points_rewards_earn_points_ratio'] = get_option( 'wc_points_rewards_earn_points_ratio', '' );
1784 $result['wc_points_rewards_earn_points_rounding'] = get_option( 'wc_points_rewards_earn_points_rounding' );
1785 $result['wc_points_rewards_redeem_points_ratio'] = get_option( 'wc_points_rewards_redeem_points_ratio', '' );
1786 $result['wc_points_rewards_partial_redemption_enabled'] = get_option( 'wc_points_rewards_partial_redemption_enabled' );
1787 $result['wc_points_rewards_cart_min_discount'] = get_option( 'wc_points_rewards_cart_min_discount' );
1788 $result['wc_points_rewards_max_discount'] = get_option( 'wc_points_rewards_max_discount' );
1789 $result['wc_points_rewards_points_tax_application'] = get_option( 'wc_points_rewards_points_tax_application' );
1790 $result['wc_points_rewards_points_expiry_number'] = get_option( 'wc_points_rewards_points_expiry_number' );
1791 $result['wc_points_rewards_points_expiry_period'] = get_option( 'wc_points_rewards_points_expiry_period' );
1792 $result['wc_points_rewards_single_product_message'] = get_option( 'wc_points_rewards_single_product_message' );
1793 $result['wc_points_rewards_variable_product_message'] = get_option( 'wc_points_rewards_variable_product_message' );
1794 $result['wc_points_rewards_earn_points_message'] = get_option( 'wc_points_rewards_earn_points_message' );
1795 $result['wc_points_rewards_redeem_points_message'] = get_option( 'wc_points_rewards_redeem_points_message' );
1796 $result['wc_points_rewards_thank_you_message'] = get_option( 'wc_points_rewards_thank_you_message' );
1797
1798 return rest_ensure_response( $result );
1799 } else {
1800 return rest_ensure_response( array() );
1801 }
1802 }
1803
1804 add_filter( 'woocommerce_get_shop_coupon_data', 'ams_create_virtual_coupon', 10, 2 );
1805
1806 function ams_create_virtual_coupon( $false, $data ) {
1807
1808 // Do not interfere with coupon creation and editing.
1809 if ( is_admin() ) {
1810 return $false;
1811 }
1812 $coupon_code_valid = false;
1813 $coupon_settings = null;
1814 $coupon_amount = 0;
1815 if ( ams_is_coupon_code_valid( $data ) ) {
1816 $coupon_code_valid = true;
1817 }
1818 if ( ( $pos = strpos( $data, '@' ) ) !== false ) {
1819 $coupon_amount = (float) substr( $data, $pos + 1 );
1820 }
1821 // Create a coupon with the properties you need
1822 if ( $coupon_code_valid ) {
1823 $coupon_settings = array(
1824 'id' => true,
1825 'discount_type' => 'fixed_cart', // 'fixed_cart', 'percent' or 'fixed_product'
1826 'amount' => $coupon_amount, // value or percentage.
1827 'expiry_date' => date( 'Y-m-d', strtotime( 'tomorrow' ) ), // YYYY-MM-DD
1828 'individual_use' => false,
1829 'product_ids' => array(),
1830 'exclude_product_ids' => array(),
1831 'usage_limit' => '1',
1832 'usage_limit_per_user' => '1',
1833 'limit_usage_to_x_items' => '',
1834 'usage_count' => '',
1835 'free_shipping' => false,
1836 'product_categories' => array(),
1837 'exclude_product_categories' => array(),
1838 'exclude_sale_items' => false,
1839 'minimum_amount' => '',
1840 'maximum_amount' => '',
1841 'customer_email' => array(),
1842 );
1843
1844 return $coupon_settings;
1845 } else {
1846 return false;
1847 }
1848
1849 }
1850
1851 add_action( 'rest_api_init', 'ams_create_api_customer_field' );
1852
1853 function ams_create_api_customer_field() {
1854
1855 // register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
1856 register_rest_field(
1857 'customer',
1858 'ams-rewards-points-balance',
1859 array(
1860 'get_callback' => 'ams_get_rewards_points_balance',
1861 'schema' => null,
1862 )
1863 );
1864 }
1865
1866 function ams_get_rewards_points_balance( $object ) {
1867 if ( in_array(
1868 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
1869 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1870 )
1871 ) {
1872 // get the value of the user's point balance
1873 $available_user_discount = WC_Points_Rewards_Manager::get_users_points( $object['id'] );
1874 // return the post meta
1875 return (float) $available_user_discount;
1876 } else {
1877 return 0;
1878 }
1879 }
1880
1881 add_action( 'woocommerce_order_status_processing', 'ams_order_processing' );
1882 function ams_order_processing( $order_id ) {
1883
1884 if ( in_array(
1885 'woocommerce-points-and-rewards/woocommerce-points-and-rewards.php',
1886 apply_filters( 'active_plugins', get_option( 'active_plugins' ) )
1887 )
1888 ) { // order-redeem
1889 $already_redeemed = get_post_meta( $order_id, '_wc_points_redeemed', true );
1890 $logged_redemption = get_post_meta( $order_id, '_wc_points_logged_redemption', true );
1891
1892 // Points has already been redeemed
1893 if ( ! empty( $already_redeemed ) ) {
1894 return;
1895 }
1896 $order = wc_get_order( $order_id );
1897 $customer_id = version_compare( WC_VERSION, '3.0', '<' ) ? $order->user_id : $order->get_user_id();
1898
1899 // bail for guest user
1900 if ( ! $customer_id ) {
1901 return;
1902 }
1903
1904 $discount_code = $order->get_meta( '_ams_wc_points_rewards_discount_code' );
1905
1906 if ( ! empty( $logged_redemption ) ) {
1907 $points_redeemed = $logged_redemption['points'];
1908 $discount_amount = $logged_redemption['amount'];
1909 $discount_code = $logged_redemption['discount_code'];
1910 } else {
1911 $points_redeemed = $order->get_meta( '_ams_wc_points_redeemed' );
1912 // bail if ams is not involved
1913 if ( ! $points_redeemed ) {
1914 return;
1915 }
1916 // Get amount of discount
1917 $discount_amount = $order->get_meta( '_ams_wc_points_rewards_discount_amount' );
1918
1919 }
1920 WC_Points_Rewards_Manager::decrease_points(
1921 $customer_id,
1922 $points_redeemed,
1923 'order-redeem',
1924 array(
1925 'discount_code' => $discount_code,
1926 'discount_amount' => $discount_amount,
1927 ),
1928 $order_id
1929 );
1930 update_post_meta( $order_id, '_wc_points_redeemed', $points_redeemed );
1931 update_post_meta(
1932 $order_id,
1933 '_wc_points_logged_redemption',
1934 array(
1935 'points' => $points_redeemed,
1936 'amount' => $discount_amount,
1937 'discount_code' => $discount_code,
1938 )
1939 );
1940
1941 // add order note
1942 /* translators: 1: points earned 2: points label 3: discount amount */
1943 $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 ) ) );
1944
1945 }
1946
1947 }
1948 function ams_change_password(WP_REST_Request $request){
1949
1950 $req = $request->get_json_params();
1951
1952 $user = wp_authenticate( sanitize_email( $req['username'] ), sanitize_text_field( $req['password'] ) ); // htmlspecialchars
1953 $customer_id = sanitize_text_field( $req['customer_id'] );
1954 $old_password = sanitize_text_field( $req['old_password'] );
1955 $new_password = sanitize_text_field( $req['new_password'] );
1956 $confirm_password = sanitize_text_field( $req['confirm_password'] );
1957
1958 $user = get_user_by( 'id', $customer_id );
1959 if ( isset( $user->errors ) ) {
1960 $error_message = strip_tags( ams_convert_error_to_string( $user->errors ) );
1961 $error = new WP_Error();
1962 $error->add( 'message', __( $error_message . '' ) );
1963 return $error;
1964 }
1965
1966 $x = wp_check_password( $old_password, $user->data->user_pass, $user->data->ID );
1967
1968 if ( isset( $x->errors ) ) {
1969 $error_message = strip_tags( ams_convert_error_to_string( $x->errors ) );
1970 $error = new WP_Error();
1971 $error->add( 'message', __( $error_message . '' ) );
1972 return $error;
1973 }
1974 if($x)
1975 {
1976 if($new_password == $old_password)
1977 {
1978 return new WP_Error( 'ams_error', 'Sorry, your new password and old password can not be the same.', array( 'status' => 422 ) );
1979 }
1980 if($new_password == $confirm_password)
1981 {
1982 $user_data['ID'] = $user->data->ID;
1983 $user_data['user_pass'] = $new_password;
1984 $uid = wp_update_user( $user_data );
1985 //wp_set_password($new_password , $user_id);
1986 if($uid)
1987 {
1988 unset($passdata);
1989 $user->data->user_pass = '';
1990 $user->data->user_activation_key = '';
1991 $user->data->id = $user->ID; //integer
1992 $user->data->first_name = get_user_meta( $user->ID, 'first_name', true );
1993 $user->data->last_name = get_user_meta( $user->ID, 'last_name', true );
1994 $user->data->roles = $user->roles;
1995 return rest_ensure_response( $user->data );
1996 } else {
1997 return new WP_Error( 'ams_error', 'Sorry, your account was not updated. Please try again later.', array( 'status' => 422 ) );
1998 }
1999 }
2000 else
2001 {
2002 return new WP_Error( 'ams_error', 'Sorry, both your passwords do not match. Please try again. ', array( 'status' => 422 ) );
2003 }
2004 }
2005 else
2006 {
2007 return new WP_Error( 'ams_error', 'Sorry, your old password is not correct. Please try again.', array( 'status' => 422 ) );
2008 }
2009
2010 }
2011
2012 // //
2013 // Other Helping Function ###########################################//
2014 // //
2015 function ams_get_points_rewards_discount_amount( $customer_id, $wc_points_rewards_discount_amount, $line_items ) {
2016
2017 if ( empty( $line_items ) ) {
2018 return 0;
2019 }
2020
2021 $granted_user_discount = 0;
2022 // Construct local cart
2023 if ( is_null( WC()->cart ) ) {
2024 wc_load_cart();
2025 }
2026 WC()->cart->empty_cart();
2027
2028 foreach ( $line_items as $key => $value ) {
2029 if ( array_key_exists( 'variation_id', $value ) ) {
2030 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'], $value['variation_id'] );
2031 } else {
2032 WC()->cart->add_to_cart( $value['product_id'], $value['quantity'] );
2033 }
2034 }
2035
2036 $available_user_discount = WC_Points_Rewards_Manager::get_users_points_value( $customer_id );
2037
2038 // no discount
2039 if ( $available_user_discount <= 0 ) {
2040 return 0;
2041 }
2042 if ( 'yes' === get_option( 'wc_points_rewards_partial_redemption_enabled' ) && $wc_points_rewards_discount_amount ) {
2043 $requested_user_discount = WC_Points_Rewards_Manager::calculate_points_value( $wc_points_rewards_discount_amount );
2044 if ( $requested_user_discount > 0 && $requested_user_discount < $available_user_discount ) {
2045 $available_user_discount = $requested_user_discount;
2046 }
2047 }
2048
2049 // Limit the discount available by the global minimum discount if set.
2050 $minimum_discount = get_option( 'wc_points_rewards_cart_min_discount', '' );
2051 if ( $minimum_discount > $available_user_discount ) {
2052 return 0;
2053 }
2054 $discount_applied = 0;
2055
2056 if ( ! did_action( 'woocommerce_before_calculate_totals' ) ) {
2057 WC()->cart->calculate_totals();
2058 }
2059
2060 foreach ( WC()->cart->get_cart() as $item_key => $item ) {
2061
2062 $discount = 0;
2063 $max_discount = WC_Points_Rewards_Product::get_maximum_points_discount_for_product( $item['data'] );
2064
2065 if ( is_numeric( $max_discount ) ) {
2066
2067 // adjust the max discount by the quantity being ordered
2068 $max_discount *= $item['quantity'];
2069
2070 // if the discount available is greater than the max discount, apply the max discount
2071 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
2072
2073 // Max should be product price. As this will be applied before tax, it will respect other coupons.
2074 } else {
2075 /*
2076 * Only exclude taxes when configured to in settings and when generating a discount amount for displaying in
2077 * the checkout message. This makes the actual discount money amount always tax inclusive.
2078 */
2079 if ( 'exclusive' === get_option( 'wc_points_rewards_points_tax_application', wc_prices_include_tax() ? 'inclusive' : 'exclusive' ) && $for_display ) {
2080 if ( function_exists( 'wc_get_price_excluding_tax' ) ) {
2081 $max_discount = wc_get_price_excluding_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
2082 } elseif ( method_exists( $item['data'], 'get_price_excluding_tax' ) ) {
2083 $max_discount = $item['data']->get_price_excluding_tax( $item['quantity'] );
2084 } else {
2085 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
2086 }
2087 } else {
2088 if ( function_exists( 'wc_get_price_including_tax' ) ) {
2089 $max_discount = wc_get_price_including_tax( $item['data'], array( 'qty' => $item['quantity'] ) );
2090 } elseif ( method_exists( $item['data'], 'get_price_including_tax' ) ) {
2091 $max_discount = $item['data']->get_price_including_tax( $item['quantity'] );
2092 } else {
2093 $max_discount = $item['data']->get_price( 'edit' ) * $item['quantity'];
2094 }
2095 }
2096
2097 // if the discount available is greater than the max discount, apply the max discount
2098 $discount = ( $available_user_discount <= $max_discount ) ? $available_user_discount : $max_discount;
2099 }
2100
2101 // add the discount to the amount to be applied
2102 $discount_applied += $discount;
2103
2104 // reduce the remaining discount available to be applied
2105 $available_user_discount -= $discount;
2106 }
2107 // limit the discount available by the global maximum discount if set
2108 $max_discount = get_option( 'wc_points_rewards_cart_max_discount' );
2109
2110 if ( false !== strpos( $max_discount, '%' ) ) {
2111 $max_discount = ams_calculate_discount_modifier( $max_discount );
2112 WC()->cart->empty_cart();
2113 }
2114 $max_discount = filter_var( $max_discount, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
2115
2116 if ( $max_discount && $max_discount < $discount_applied ) {
2117 $discount_applied = $max_discount;
2118 }
2119 // clear cart before returning
2120 WC()->cart->empty_cart();
2121 $discount_applied = filter_var( $discount_applied, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION );
2122 return $discount_applied;
2123
2124 }
2125
2126 function ams_get_points_label( $count ) {
2127
2128 list( $singular, $plural ) = explode( ':', get_option( 'wc_points_rewards_points_label' ) );
2129
2130 return 1 == $count ? $singular : $plural;
2131 }
2132 function ams_is_coupon_code_valid( $coupon_code ) {
2133 if ( 0 === strpos( $coupon_code, 'wc_points_redemption_' ) ) {
2134 return true;
2135 }
2136 return false;
2137 }
2138
2139 function ams_calculate_discount_modifier( $percentage ) {
2140
2141 $percentage = str_replace( '%', '', $percentage ) / 100;
2142
2143 if ( 'no' === get_option( 'woocommerce_prices_include_tax' ) ) {
2144 $discount = WC()->cart->subtotal_ex_tax;
2145
2146 } else {
2147 $discount = WC()->cart->subtotal;
2148
2149 }
2150
2151 return $percentage * $discount;
2152 }
2153
2154 function ams_object_to_array( $data ) {
2155 if ( is_array( $data ) || is_object( $data ) ) {
2156 $result = array();
2157 foreach ( $data as $key => $value ) {
2158 $value['field_name'] = $key;
2159 $value['options'] = array_values( $value['options'] );
2160 $result[] = $value;
2161
2162 }
2163 return $result;
2164 }
2165 return $data;
2166 }
2167
2168 function ams_build_category_tree( $flat, $pidKey, $idKey = null ) {
2169 $grouped = array();
2170 foreach ( $flat as $sub ) {
2171 $grouped[ $sub[ $pidKey ] ][] = $sub;
2172 }
2173 $level = 0;
2174 $fnBuilder = function( $siblings, $level ) use ( &$fnBuilder, $grouped, $idKey ) {
2175 foreach ( $siblings as $k => $sibling ) {
2176 if ( $sibling['slug'] == 'uncategorized' ) {
2177 unset( $siblings[ $k ] );
2178 continue;
2179 }
2180 $id = $sibling[ $idKey ];
2181 $sibling['description'] = '';
2182 $level++;
2183 if ( isset( $grouped[ $id ] ) ) {
2184 $sibling['depth'] = $level;
2185 $sibling['children'] = array_values( $fnBuilder( $grouped[ $id ], $level ) );
2186 } else {
2187 $sibling['depth'] = $level;
2188 $sibling['children'] = array();
2189 }
2190 $siblings[ $k ] = $sibling;
2191 $level--;
2192 }
2193 return $siblings;
2194 };
2195
2196 if ( isset( $grouped[0] ) ) {
2197 $tree = $fnBuilder( $grouped[0], $level );
2198 }
2199 if ( ! empty( $tree ) ) {
2200 return array_values( $tree );
2201 } else {
2202 foreach ( $flat as $key => $value ) {
2203 if ( $value['slug'] == 'uncategorized' ) {
2204 unset( $flat[ $key ] );
2205 continue;
2206 }
2207 $flat[ $key ]['children'] = array();
2208 }
2209 return array_values( $flat );
2210 }
2211 }
2212
2213 function ams_convert_error_to_string( $er ) {
2214 $string = ' ';
2215 foreach ( $er as $key => $value ) {
2216
2217 $string = $string . '' . $key . ':';
2218 foreach ( $value as $newkey => $newvalue ) {
2219
2220 $string = $string . '' . $newvalue . ' ';
2221 }
2222 }
2223 $string = str_replace( 'Lost your password?', '', $string );
2224 $string = str_replace( 'Error:', '', $string );
2225 $string = str_replace( '[message]', '', $string );
2226 return( $string );
2227 }
2228
2229 function ams_basic_validate( $request, $keys ) {
2230 foreach ( $keys as $key => $value ) {
2231
2232 if ( ! isset( $request[ $value ] ) ) {
2233 status_header( 400 );
2234 echo ( json_encode(
2235 array(
2236 'message' => 'There is a problem with your input!',
2237 'error' => $value . ': Field is required!',
2238 ),
2239 JSON_UNESCAPED_UNICODE
2240 ) );
2241 die();
2242 }
2243 if ( empty( $request[ $value ] ) ) {
2244 status_header( 400 );
2245 echo ( json_encode(
2246 array(
2247 'message' => 'There is a problem with your input!',
2248 'error' => $value . ': Can not be empty!',
2249 ),
2250 JSON_UNESCAPED_UNICODE
2251 ) );
2252 die();
2253 }
2254 }
2255 return true;
2256 }
2257
2258 //Add formatted acf fields to the object so that app can use it.
2259 add_action( 'rest_api_init', 'ams_add_acf_fields' );
2260 function ams_add_acf_fields() {
2261 $postypes_to_exclude = ['acf-field-group','acf-field'];
2262 $extra_postypes_to_include = ["page","post"];
2263 $post_types = array_diff(get_post_types(["_builtin" => false], 'names'),$postypes_to_exclude);
2264
2265 array_push($post_types, $extra_postypes_to_include);
2266
2267 foreach ($post_types as $post_type) {
2268 register_rest_field( $post_type, 'ams_acf', [
2269 'get_callback' => 'ams_expose_acf_fields',
2270 'schema' => null,
2271 ]
2272 );
2273 }
2274 }
2275
2276 function ams_expose_acf_fields( $object ) {
2277 $ID = $object['id'];
2278 $final_fields = [];
2279 if(function_exists('get_fields')){
2280 $fields = get_fields($ID);
2281 $count = 0 ;
2282 if(!empty($fields)){
2283 foreach($fields as $key=>$value){
2284 $final_fields[$count]['key']= $key;
2285 $final_fields[$count]['value'] = $value;
2286 $count++;
2287 }
2288 }
2289 }
2290 return $final_fields;
2291 }
2292
2293 require_once untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/includes/ams-plugin-deactivation-survey.php';
2294
2295 add_action( 'wp_ajax_ams_deactivation_form_submit', 'ams_deactivation_form_submit' );
2296
2297 add_action('admin_enqueue_scripts', 'ams_admin_enqueue_scripts');
2298 function ams_admin_enqueue_scripts(){
2299
2300 $current_page = get_current_screen()->base;
2301
2302 if($current_page == 'plugins' || $current_page == 'plugins-network') {
2303
2304 add_action('admin_footer', 'ams_deactivation_popup');
2305
2306 wp_register_script('ams_jquery', 'https://code.jquery.com/jquery-3.6.0.min.js', array(), '3.6.0', true); // jQuery v3
2307 wp_enqueue_script('ams_jquery');
2308 wp_script_add_data( 'ams_jquery', array( 'integrity', 'crossorigin' ) , array( 'sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=', 'anonymous' ) );
2309
2310 wp_enqueue_script('ams_plugin_deactivation_survey_js', plugins_url('assets/plugin-deactivation-survey.js', __FILE__), array('ams_jquery'));
2311 wp_localize_script('ams_plugin_deactivation_survey_js', 'frontend_ajax_object', array('amsDeactivationSurveyNonce' => wp_create_nonce('ajax-nonce')));
2312 wp_enqueue_style( 'ams_plugin_deactivation_survey_css', plugins_url('assets/plugin-deactivation-survey.css', __FILE__), array());
2313
2314
2315 } else { // # if not on plugins, deregister and dequeue styles & scripts
2316
2317 wp_dequeue_script('ams_jquery');
2318 wp_dequeue_script('ams_plugin_deactivation_survey_js');
2319 wp_dequeue_style('ams_plugin_deactivation_survey_css');
2320
2321 }
2322 }
2323
2324