PluginProbe
MStore API – Create Native Android & iOS Apps On The Cloud / 4.18.2
MStore API – Create Native Android & iOS Apps On The Cloud v4.18.2
4.21.3 4.21.2 4.21.1 trunk 1.1.5 2.9.4 2.9.5 2.9.6 2.9.7 2.9.8 2.9.9 3.0.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.8 3.0.9 3.1.0 3.1.1 3.1.2 3.1.3 All 192 releases
mstore-api / mstore-api.php

mstore-api.php in MStore API – Create Native Android & iOS Apps On The Cloud 4.18.2, at mstore-api.php

1,323 lines 54.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Plugin Name: MStore API
4 * Plugin URI: https://github.com/inspireui/mstore-api
5 * Description: The MStore API Plugin which is used for the FluxBuilder and FluxStore Mobile App
6 * Version: 4.18.2
7 * Author: FluxBuilder
8 * Author URI: https://fluxbuilder.com
9 *
10 * Text Domain: MStore-Api
11 */
12
13 defined('ABSPATH') or wp_die('No script kiddies please!');
14
15
16 // use MStoreCheckout\Templates\MDetect;
17
18 include plugin_dir_path(__FILE__) . "templates/class-mobile-detect.php";
19 include plugin_dir_path(__FILE__) . "templates/class-rename-generate.php";
20 include_once plugin_dir_path(__FILE__) . "controllers/flutter-user.php";
21 include_once plugin_dir_path(__FILE__) . "controllers/flutter-home.php";
22 include_once plugin_dir_path(__FILE__) . "controllers/flutter-booking.php";
23 include_once plugin_dir_path(__FILE__) . "controllers/flutter-vendor-admin.php";
24 include_once plugin_dir_path(__FILE__) . "controllers/flutter-woo.php";
25 include_once plugin_dir_path(__FILE__) . "controllers/flutter-delivery.php";
26 include_once plugin_dir_path(__FILE__) . "functions/index.php";
27 include_once plugin_dir_path(__FILE__) . "functions/utils.php";
28 include_once plugin_dir_path(__FILE__) . "controllers/flutter-tera-wallet.php";
29 include_once plugin_dir_path(__FILE__) . "controllers/flutter-paytm.php";
30 include_once plugin_dir_path(__FILE__) . "controllers/flutter-paystack.php";
31 include_once plugin_dir_path(__FILE__) . "controllers/flutter-flutterwave.php";
32 include_once plugin_dir_path(__FILE__) . "controllers/flutter-myfatoorah.php";
33 include_once plugin_dir_path(__FILE__) . "controllers/flutter-midtrans.php";
34 include_once plugin_dir_path(__FILE__) . "controllers/flutter-paid-memberships-pro.php";
35 include_once plugin_dir_path(__FILE__) . "controllers/listing-rest-api/class.api.fields.php";
36 include_once plugin_dir_path(__FILE__) . "controllers/flutter-blog.php";
37 include_once plugin_dir_path(__FILE__) . "controllers/flutter-wholesale.php";
38 include_once plugin_dir_path(__FILE__) . "controllers/flutter-stripe.php";
39 include_once plugin_dir_path(__FILE__) . "controllers/flutter-notification.php";
40 include_once plugin_dir_path(__FILE__) . "controllers/flutter-thawani.php";
41 include_once plugin_dir_path(__FILE__) . "controllers/flutter-expresspay.php";
42 include_once plugin_dir_path(__FILE__) . "controllers/flutter-2c2p.php";
43 include_once plugin_dir_path(__FILE__) . "controllers/flutter-cc-avenue.php";
44 include_once plugin_dir_path(__FILE__) . "controllers/flutter-flow-flow.php";
45 include_once plugin_dir_path(__FILE__) . "controllers/flutter-store-locator.php";
46 include_once plugin_dir_path(__FILE__) . "controllers/flutter-composite-products.php";
47 include_once plugin_dir_path(__FILE__) . "controllers/flutter-b2bking.php";
48 include_once plugin_dir_path(__FILE__) . "controllers/flutter-review.php";
49 include_once plugin_dir_path(__FILE__) . "controllers/helpers/firebase-message-helper.php";
50 include_once plugin_dir_path(__FILE__) . "controllers/flutter-fib.php";
51 include_once plugin_dir_path(__FILE__) . "controllers/helpers/firebase-phone-auth-helper.php";
52 include_once plugin_dir_path(__FILE__) . "controllers/flutter-auction.php";
53 include_once plugin_dir_path(__FILE__) . "controllers/flutter-iyzico.php";
54 include_once plugin_dir_path(__FILE__) . "controllers/flutter-phonepe.php";
55 include_once plugin_dir_path(__FILE__) . "controllers/flutter-points-offline-store.php";
56 include_once plugin_dir_path(__FILE__) . "controllers/flutter-smart-cod.php";
57 include_once plugin_dir_path(__FILE__) . "controllers/flutter-discount-rules.php";
58 include_once plugin_dir_path(__FILE__) . "controllers/flutter-checkout.php";
59 include_once plugin_dir_path(__FILE__) . "controllers/flutter-razorpay.php";
60
61 if ( is_readable( __DIR__ . '/vendor/autoload.php' ) ) {
62 require __DIR__ . '/vendor/autoload.php';
63 }
64
65 class MstoreCheckOut
66 {
67 public $version = '4.18.2';
68
69 public function __construct()
70 {
71 define('MSTORE_CHECKOUT_VERSION', $this->version);
72 define('MSTORE_PLUGIN_FILE', __FILE__);
73
74 /**
75 * Prepare data before checkout by webview
76 */
77 add_action('template_redirect', 'flutter_prepare_checkout');
78
79 add_action( 'pre_get_posts', 'set_author_in_for_vendor_staff' );
80
81 include_once(ABSPATH . 'wp-admin/includes/plugin.php');
82 //include_once(ABSPATH . 'wp-includes/pluggable.php');
83
84 // //migrate old versions to re-verify purchase code automatically
85 // verifyPurchaseCodeAuto();
86
87 add_filter( 'get_avatar_url', array( $this, 'filter_avatar' ), 10, 3 );
88
89 if (is_plugin_active('woocommerce/woocommerce.php') == false) {
90 return 0;
91 }
92 add_action('woocommerce_init', 'woocommerce_mstore_init');
93 function woocommerce_mstore_init()
94 {
95 include_once plugin_dir_path(__FILE__) . "controllers/flutter-order.php";
96 include_once plugin_dir_path(__FILE__) . "controllers/flutter-multi-vendor.php";
97 include_once plugin_dir_path(__FILE__) . "controllers/flutter-vendor.php";
98 include_once plugin_dir_path(__FILE__) . "controllers/helpers/delivery-wcfm-helper.php";
99 include_once plugin_dir_path(__FILE__) . "controllers/helpers/delivery-wcfm-helper.php";
100 include_once plugin_dir_path(__FILE__) . "controllers/helpers/vendor-admin-woo-helper.php";
101 include_once plugin_dir_path(__FILE__) . "controllers/helpers/vendor-admin-wcfm-helper.php";
102 include_once plugin_dir_path(__FILE__) . "controllers/helpers/vendor-admin-dokan-helper.php";
103 include_once plugin_dir_path(__FILE__) . "controllers/flutter-customer.php";
104 include_once plugin_dir_path(__FILE__) . "functions/video-setting-embed.php";
105 }
106
107 add_filter('wp_rest_cache/allowed_endpoints', array($this, 'wprc_add_flutter_api_endpoints'));
108
109 $order = filter_has_var(INPUT_GET, 'code') && strlen(filter_input(INPUT_GET, 'code')) > 0 ? true : false;
110 if ($order) {
111 add_filter('woocommerce_is_checkout', '__return_true');
112 }
113
114 /*
115 add_filter( 'woocommerce_get_item_data', 'display_custom_product_field_data_mstore_api', 10, 2 );
116
117 function display_custom_product_field_data_mstore_api( $cart_data, $cart_item ) {
118
119 if( !empty( $cart_data ) ){
120 $custom_items = $cart_data;
121
122 $code = sanitize_text_field($_GET['code']) ?: get_transient( 'mstore_code' );
123 set_transient( 'mstore_code', $code, 600 );
124
125 global $wpdb;
126 $table_name = $wpdb->prefix . "mstore_checkout";
127 $item = $wpdb->get_row("SELECT * FROM $table_name WHERE code = '$code'");
128 if ($item) {
129 $data = json_decode(urldecode(base64_decode($item->order)), true);
130 $line_items = $data['line_items'];
131 $product_ids = [];
132 foreach($line_items as $line => $item) {
133 $product_ids[$item['product_id']] = $item;
134 }
135
136 if (array_key_exists($cart_item['product_id'], $product_ids)) {
137 if ($varian = $product_ids[$cart_item['product_id']]) {
138 $variations = $varian['meta_data'];
139 foreach($variations as $v => $f) {
140 preg_match('#\((.*?)\)#', $f['key'], $match);
141 $val = $match[1];
142 $custom_items[] = array(
143 'key' => $f['value'],
144 'value' => $val,
145 'display' => $val,
146 );
147 }
148 }
149 }
150 }
151
152 return $custom_items;
153 }
154 return $cart_data;
155 }
156
157
158 add_action( 'woocommerce_before_calculate_totals', 'add_custom_price_mstore_api' );
159
160 function add_custom_price_mstore_api( $cart_object ) {
161 foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
162 $add_price = 0;
163 if ($variations = $cart_item['variation']) {
164 foreach($variations as $v => $f) {
165 preg_match('#\((.*?)\)#', $v, $match);
166 if(is_array($match) && array_key_exists(1,$match)){
167 $val = $match[1];
168 $cents = filter_var($val, FILTER_SANITIZE_NUMBER_INT);
169 if(is_numeric($cents)){
170 $add_price += floatval($cents / 100);
171 }
172 }
173 }
174 }
175 $new_price = $cart_item['data']->get_price() + $add_price;
176 $cart_item['data']->set_price($new_price);
177 }
178 }
179 */
180
181 add_action('wp_print_scripts', array($this, 'handle_received_order_page'));
182
183 //add meta box shipping location in order detail
184 add_action('add_meta_boxes', 'mv_add_meta_boxes');
185 if (!function_exists('mv_add_meta_boxes')) {
186 function mv_add_meta_boxes()
187 {
188 add_meta_box('mv_other_fields', __('Shipping Location', 'woocommerce'), 'mv_add_other_fields_for_packaging', 'shop_order', 'side', 'core');
189 }
190 }
191 // Adding Meta field in the meta container admin shop_order pages
192 if (!function_exists('mv_add_other_fields_for_packaging')) {
193 function mv_add_other_fields_for_packaging()
194 {
195 global $post;
196 $note = $post->post_excerpt;
197 $items = explode("\n", $note);
198 if (strpos($items[0], "URL:") !== false) {
199 $url = str_replace("URL:", "", $items[0]);
200 echo esc_html('<iframe width="600" height="500" src="' . esc_url($url) . '"></iframe>');
201 }
202 }
203 }
204
205 register_activation_hook(__FILE__, array($this, 'create_custom_mstore_table'));
206
207 // Setup Ajax action hook
208 add_action('wp_ajax_mstore_delete_json_file', array($this, 'mstore_delete_json_file'));
209 add_action('wp_ajax_mstore_delete_apple_file', array($this, 'mstore_delete_apple_file'));
210 add_action('wp_ajax_mstore_delete_firebase_file', array($this, 'mstore_delete_firebase_file'));
211 add_action('wp_ajax_mstore_update_limit_product', array($this, 'mstore_update_limit_product'));
212 add_action('wp_ajax_mstore_update_new_order_title', array($this, 'mstore_update_new_order_title'));
213 add_action('wp_ajax_mstore_update_new_order_message', array($this, 'mstore_update_new_order_message'));
214 add_action('wp_ajax_mstore_update_status_order_title', array($this, 'mstore_update_status_order_title'));
215 add_action('wp_ajax_mstore_update_status_order_message', array($this, 'mstore_update_status_order_message'));
216
217 // listen changed order status to notify
218 add_action('woocommerce_order_status_changed', array($this, 'track_order_status_changed'), 9, 4);
219 add_action('woocommerce_checkout_update_order_meta', array($this, 'track_new_order'));
220 add_action('woocommerce_rest_insert_shop_order_object', array($this, 'track_api_new_order'), 10, 4);
221
222 //WCFM - WooCommerce Frontend Manager - Delivery
223 //Handle listen to assign delivery boy on the website
224 add_action( 'wcfmd_after_delivery_boy_assigned', array($this, 'track_delivery_boy_assigned'), 400, 6 );
225
226 $path = get_template_directory() . "/templates";
227 if (!file_exists($path)) {
228 mkdir($path, 0777, true);
229 }
230 if (file_exists($path)) {
231 $templatePath = plugin_dir_path(__FILE__) . "templates/mstore-api-template.php";
232 if (!copy($templatePath, $path . "/mstore-api-template.php")) {
233 return 0;
234 }
235 }
236 }
237
238 public function wprc_add_flutter_api_endpoints($allowed_endpoints){
239 if ( ! isset( $allowed_endpoints[ 'wc/v3' ] ) || ! in_array( 'products', $allowed_endpoints[ 'wc/v3' ] ) ) {
240 $allowed_endpoints[ 'wc/v3' ][] = 'products';
241 $allowed_endpoints[ 'wc/v3' ][] = 'products/categories';
242 $allowed_endpoints[ 'wc/v3' ][] = 'products/attributes';
243 }
244 if ( ! isset( $allowed_endpoints[ 'wc/v2' ] ) || ! in_array( 'products', $allowed_endpoints[ 'wc/v2' ] ) ) {
245 $allowed_endpoints[ 'wc/v2' ][] = 'products';
246 $allowed_endpoints[ 'wc/v2' ][] = 'products/categories';
247 $allowed_endpoints[ 'wc/v2' ][] = 'products/attributes';
248 }
249 return $allowed_endpoints;
250 }
251
252 public function filter_avatar($url, $id_or_email, $args)
253 {
254 $finder = false;
255 $user = false;
256
257 // Early return if id_or_email is empty
258 if (empty($id_or_email)) {
259 return $url;
260 }
261
262 if (is_numeric($id_or_email)) {
263 $user = get_user_by('id', absint($id_or_email));
264 } elseif (is_string($id_or_email) && is_email($id_or_email)) {
265 $user = get_user_by('email', $id_or_email);
266 } elseif ($id_or_email instanceof WP_User) {
267 $user = $id_or_email;
268 } elseif ($id_or_email instanceof WP_Post) {
269 $user = get_user_by('id', (int)$id_or_email->post_author);
270 } elseif ($id_or_email instanceof WP_Comment) {
271 if (!empty($id_or_email->user_id)) {
272 $user = get_user_by('id', (int)$id_or_email->user_id);
273 }
274 }
275
276 if ($user && !is_wp_error($user)) {
277 $avatar = get_user_meta($user->ID, 'user_avatar', true);
278 if (isset($avatar) && $avatar !== "" && !is_bool($avatar) && !empty($avatar[0])) {
279 return $avatar[0];
280 }
281 }
282
283 return $url;
284 }
285
286 function mstore_delete_json_file(){
287 if(checkIsAdmin(get_current_user_id())){
288 $id = sanitize_text_field($_REQUEST['id']);
289 $nonce = sanitize_text_field($_REQUEST['nonce']);
290 FlutterUtils::delete_config_file($id, $nonce);
291 }else{
292 wp_send_json_error('No Permission',401);
293 }
294 }
295
296 function mstore_delete_apple_file(){
297 if(checkIsAdmin(get_current_user_id())){
298 $nonce = sanitize_text_field($_REQUEST['nonce']);
299 FlutterAppleSignInUtils::delete_config_file($nonce);
300 wp_send_json('success',200);
301 }else{
302 wp_send_json_error('No Permission',401);
303 }
304 }
305
306 function mstore_delete_firebase_file(){
307 if(checkIsAdmin(get_current_user_id())){
308 $nonce = sanitize_text_field($_REQUEST['nonce']);
309 FirebaseMessageHelper::delete_config_file($nonce);
310 wp_send_json('success',200);
311 }else{
312 wp_send_json_error('No Permission',401);
313 }
314 }
315
316 function mstore_update_limit_product()
317 {
318 $nonce = sanitize_text_field($_REQUEST['nonce']);
319 if(checkIsAdmin(get_current_user_id()) && wp_verify_nonce($nonce, 'update_limit_product')){
320 $limit = sanitize_text_field($_REQUEST['limit']);
321 if (is_numeric($limit)) {
322 update_option("mstore_limit_product", intval($limit));
323 }
324 }else{
325 wp_send_json_error('No Permission',401);
326 }
327 }
328
329 function mstore_update_new_order_title()
330 {
331 $nonce = sanitize_text_field($_REQUEST['nonce']);
332 if(checkIsAdmin(get_current_user_id()) && wp_verify_nonce($nonce, 'update_new_order_title')){
333 $title = sanitize_text_field($_REQUEST['title']);
334 update_option("mstore_new_order_title", $title);
335 }else{
336 wp_send_json_error('No Permission',401);
337 }
338 }
339
340 function mstore_update_new_order_message()
341 {
342 $nonce = sanitize_text_field($_REQUEST['nonce']);
343 if(checkIsAdmin(get_current_user_id()) && wp_verify_nonce($nonce, 'update_new_order_message')){
344 $message = sanitize_text_field($_REQUEST['message']);
345 update_option("mstore_new_order_message", $message);
346 }else{
347 wp_send_json_error('No Permission',401);
348 }
349 }
350
351 function mstore_update_status_order_title()
352 {
353 $nonce = sanitize_text_field($_REQUEST['nonce']);
354 if(checkIsAdmin(get_current_user_id()) && wp_verify_nonce($nonce, 'update_status_order_title')){
355 $title = sanitize_text_field($_REQUEST['title']);
356 update_option("mstore_status_order_title", $title);
357 }else{
358 wp_send_json_error('No Permission',401);
359 }
360 }
361
362 function mstore_update_status_order_message()
363 {
364 $nonce = sanitize_text_field($_REQUEST['nonce']);
365 if(checkIsAdmin(get_current_user_id()) && wp_verify_nonce($nonce, 'update_status_order_message')){
366 $message = sanitize_text_field($_REQUEST['message']);
367 update_option("mstore_status_order_message", $message);
368 }else{
369 wp_send_json_error('No Permission',401);
370 }
371 }
372
373 // update order via website
374 function track_order_status_changed($id, $previous_status, $next_status)
375 {
376 trackOrderStatusChanged($id, $previous_status, $next_status);
377 }
378
379 // new order via website
380 function track_new_order($order_id)
381 {
382 trackNewOrder($order_id);
383 }
384
385 // New order or update order via API
386 function track_api_new_order($object, $request, $creating)
387 {
388 if ($creating) {
389 trackNewOrder($object->get_id());
390
391 // Update order attributes. Requires WooCommerce 8.5.0 or later.
392 // And make sure you have enabled `Order Attributes` in WooCommerce
393 // Settings > Advanced > Features.
394 // See: https://woocommerce.com/document/order-attribution-tracking/
395 do_action('woocommerce_store_api_checkout_update_order_from_request', $object, $request);
396 } else {
397 $body = $request->get_body_params();
398 if (isset($body['status'])) {
399 sendNotificationForOrderStatusUpdated($object->id, $body['status']);
400 }
401 }
402 }
403
404 function track_delivery_boy_assigned( $order_id, $order_item_id, $wcfm_tracking_data, $product_id, $wcfm_delivery_boy, $wcfm_messages ) {
405 $notification_message = strip_tags($wcfm_messages);
406 $title = "You have new notification";
407 pushNotificationForDeliveryBoy($wcfm_delivery_boy, $title, $notification_message);
408 }
409
410 public function handle_received_order_page()
411 {
412 // default return true for getting checkout library working
413 if (is_order_received_page()) {
414 $detect = new MDetect;
415 if ($detect->isMobile()) {
416 wp_register_style('mstore-order-custom-style', plugins_url('assets/css/mstore-order-style.css', MSTORE_PLUGIN_FILE));
417 wp_enqueue_style('mstore-order-custom-style');
418 }
419 }
420
421 }
422
423 function create_custom_mstore_table()
424 {
425 global $wpdb;
426 // include upgrade-functions for maybe_create_table;
427 if (!function_exists('maybe_create_table')) {
428 require_once ABSPATH . 'wp-admin/includes/upgrade.php';
429 }
430 $charset_collate = $wpdb->get_charset_collate();
431 $table_name = $wpdb->prefix . 'mstore_checkout';
432 $sql = "CREATE TABLE $table_name (
433 id mediumint(9) NOT NULL AUTO_INCREMENT,
434 `code` tinytext NOT NULL,
435 `order` text NOT NULL,
436 PRIMARY KEY (id)
437 ) $charset_collate;";
438 $success = maybe_create_table($table_name, $sql);
439 }
440 }
441
442 $mstoreCheckOut = new MstoreCheckOut();
443
444 // use JO\Module\Templater\Templater;
445 include plugin_dir_path(__FILE__) . "templates/class-templater.php";
446
447 add_action('plugins_loaded', 'load_mstore_templater');
448 function load_mstore_templater()
449 {
450
451 // add our new custom templates
452 $my_templater = new Templater(
453 array(
454 // YOUR_PLUGIN_DIR or plugin_dir_path(__FILE__)
455 'plugin_directory' => plugin_dir_path(__FILE__),
456 // should end with _ > prefix_
457 'plugin_prefix' => 'plugin_prefix_',
458 // templates directory inside your plugin
459 'plugin_template_directory' => 'templates',
460 )
461 );
462 $my_templater->add(
463 array(
464 'page' => array(
465 'mstore-api-template.php' => 'Page Custom Template',
466 ),
467 )
468 )->register();
469 }
470
471 //custom rest api
472 function flutter_users_routes()
473 {
474 $controller = new FlutterUserController();
475 $controller->register_routes();
476 }
477
478 add_action('rest_api_init', 'flutter_users_routes');
479 add_action('rest_api_init', 'mstore_check_payment_routes');
480 function mstore_check_payment_routes()
481 {
482 register_rest_route('order', '/verify', array(
483 'methods' => 'GET',
484 'callback' => 'mstore_check_payment',
485 'permission_callback' => function () {
486 return true;
487 },
488 )
489 );
490 }
491
492 function mstore_check_payment()
493 {
494 return true;
495 }
496
497
498 // Add menu Setting
499 add_action('admin_menu', 'mstore_plugin_setup_menu');
500
501 function mstore_plugin_setup_menu()
502 {
503 add_menu_page('MStore Api', 'MStore Api', 'manage_options', 'mstore-plugin', 'mstore_init');
504 }
505
506 function mstore_init()
507 {
508 load_template(dirname(__FILE__) . '/templates/mstore-api-admin-page.php');
509 }
510
511 add_filter('woocommerce_rest_prepare_product_variation_object', 'custom_woocommerce_rest_prepare_product_variation_object', 20, 3);
512 add_filter('woocommerce_rest_prepare_product_object', 'flutter_custom_change_product_response', 20, 3);
513 add_filter('woocommerce_rest_prepare_product_review', 'custom_product_review', 20, 3);
514 add_filter('woocommerce_rest_prepare_product_cat', 'custom_product_category', 20, 3);
515 add_filter('woocommerce_rest_prepare_shop_order_object', 'flutter_custom_change_order_response', 20, 3);
516 add_filter('woocommerce_rest_prepare_product_attribute', 'flutter_custom_change_product_attribute', 20, 3);
517 add_filter('woocommerce_rest_prepare_product_tag', 'flutter_custom_change_product_taxonomy', 20, 3);
518 add_filter('woocommerce_rest_prepare_product_brand', 'flutter_custom_change_product_taxonomy', 20, 3);
519 add_filter('woocommerce_rest_product_object_query', 'flutter_custom_rest_product_object_query', 10, 2);
520 add_filter('woocommerce_rest_product_tag_query', 'flutter_custom_rest_product_tag_query', 10, 2);
521 add_filter('woocommerce_rest_product_brand_query', 'flutter_custom_rest_product_brand_query', 10, 2);
522 add_filter('rest_product_collection_params', 'flutter_custom_rest_product_collection_params', 10, 1);
523 add_filter('posts_pre_query', 'flutter_custom_posts_pre_query', 10, 2);
524 add_filter('found_posts', 'flutter_custom_found_posts', 20, 2);
525
526 /**
527 * WooCommerce REST API: Random sorting for products.
528 *
529 * rest_{post_type}_collection_params
530 *
531 * @param array $params
532 * @return array
533 */
534 function flutter_custom_rest_product_collection_params($params)
535 {
536 $params['orderby']['enum'][] = 'rand';
537 return $params;
538 }
539
540 function flutter_custom_rest_product_tag_query($args, $request)
541 {
542 return flutter_custom_rest_product_taxomomy_query($args, $request, 'product_tag');
543 }
544
545 function flutter_custom_rest_product_brand_query($args, $request)
546 {
547 return flutter_custom_rest_product_taxomomy_query($args, $request, 'product_brand');
548 }
549
550 function flutter_custom_rest_product_taxomomy_query($args, $request, $taxonomy)
551 {
552 $hide_empty = isset($args['hide_empty']) && $args['hide_empty'] == true;
553
554 // `include` parameter can be an array or comma separated string
555 $include = wp_parse_id_list($args['include']);
556
557 // Get product count for all tags, brands related to the requested params (based on category, brand, etc.)
558 $terms = get_filtered_term_product_counts($request, $taxonomy, [], $hide_empty);
559
560 // Trick: Use the `include` parameter to fix the API problem below
561 // The page = 1 has no visible items (count = 0), the app does not show
562 // anything (include loadmore button). If the page = 2 has visible items,
563 // cannot do anything in app because it do not show load more button
564 foreach ($terms as $key => $term) {
565 if ($hide_empty) {
566 if ($term['term_count'] > 0) {
567 $include[] = $term['term_count_id'];
568 }
569 } else {
570 $include[] = $term['term_count_id'];
571 }
572 }
573
574 $args['include'] = implode(',', wp_parse_id_list($include));
575 return $args;
576 }
577
578 function flutter_custom_rest_product_object_query($args, $request)
579 {
580 $attrs = $request['attributes'];
581
582 if (is_string($attrs) && !empty($attrs)) {
583 $attrs = json_decode($attrs, true);
584 }
585
586 // Attributes filter.
587 if (!empty($attrs)) {
588 foreach ($attrs as $attr_key => $attr_value) {
589 $args['tax_query'][] = [
590 'taxonomy' => $attr_key,
591 'field' => 'term_id',
592 'terms' => explode(',', $attr_value),
593 ];
594 }
595 }
596
597 return $args;
598 }
599
600 function custom_product_category($response, $object, $request)
601 {
602 $id = $response->data['id'];
603 $children = get_term_children($id, 'product_cat');
604
605 if (empty($children)) {
606 $response->data['has_children'] = false;
607 } else {
608 $response->data['has_children'] = true;
609 }
610 return $response;
611 }
612
613 function custom_product_review($response, $object, $request)
614 {
615 if(is_plugin_active('woo-photo-reviews/woo-photo-reviews.php') || is_plugin_active('woocommerce-photo-reviews/woocommerce-photo-reviews.php')){
616 $id = $response->data['id'];
617 $image_post_ids = get_comment_meta( $id, 'reviews-images', true );
618 $image_arr = array();
619 if(!is_string($image_post_ids)){
620 foreach( $image_post_ids as $image_post_id ) {
621 $image_arr[] = wp_get_original_image_url( $image_post_id );
622 }
623 }
624 $response->data['images'] = $image_arr;
625 }
626 return $response;
627 }
628
629 function flutter_custom_change_order_response($response, $object, $request)
630 {
631 return customOrderResponse($response, $object, $request);
632 }
633
634 function flutter_custom_change_product_response($response, $object, $request)
635 {
636 return customProductResponse($response, $object, $request);
637 }
638
639 function flutter_custom_change_product_attribute($response, $item, $request)
640 {
641 $taxonomy = wc_attribute_taxonomy_name($item->attribute_name);
642
643 // Combine all attribute terms into the return result when getting
644 // attributes. Reduce api calls to get sub-attributes from the app
645 $options = get_terms([
646 'taxonomy' => $taxonomy,
647 'hide_empty' => false,
648 ]);
649
650 // Get list count of attribute terms based on attribute.
651 $terms = get_filtered_term_product_counts($request, $taxonomy);
652
653 $is_visible = false;
654 // Show this attribute if any attribute terms have product quantity > 0
655 foreach ($terms as $key => $term) {
656 $count = (int)$term['term_count'];
657 if ($is_visible == false && $count > 0) {
658 $is_visible = true;
659 }
660 // Update term count for options
661 foreach ($options as $option) {
662 if ($option->term_id == $term['term_count_id']) {
663 $option->count = $count;
664 break;
665 }
666 }
667 }
668
669 $response->data['terms'] = $options;
670
671 $response->data['is_visible'] = $is_visible;
672
673 return $response;
674 }
675
676 /// Custom response for product a tag or brand
677 function flutter_custom_change_product_taxonomy($response, $item, $request)
678 {
679 // There is only a maximum of 1 entry because term_ids is an array of a
680 // unique id
681 $terms = get_filtered_term_product_counts($request, $item->taxonomy, $item->term_id);
682
683 if (!empty($terms)) {
684 $term = $terms[0];
685 $count = (int)$term['term_count'];
686 $response->data['count'] = $count;
687 $response->data['is_visible'] = $count > 0;
688 } else {
689 $response->data['count'] = 0;
690 $response->data['is_visible'] = false;
691 }
692
693 return $response;
694 }
695
696 function custom_get_attribute_taxonomy_name( $slug, $product ) {
697 // Format slug so it matches attributes of the product.
698 $slug = wc_attribute_taxonomy_slug( $slug );
699 $attributes = $product->get_attributes();
700 $attribute = false;
701
702 // pa_ attributes.
703 if ( isset( $attributes[ wc_attribute_taxonomy_name( $slug ) ] ) ) {
704 $attribute = $attributes[ wc_attribute_taxonomy_name( $slug ) ];
705 } elseif ( isset( $attributes[ $slug ] ) ) {
706 $attribute = $attributes[ $slug ];
707 }
708
709 if ( ! $attribute ) {
710 return $slug;
711 }
712
713 // Taxonomy attribute name.
714 if ( $attribute->is_taxonomy() ) {
715 $taxonomy = $attribute->get_taxonomy_object();
716 return $taxonomy->attribute_label;
717 }
718
719 // Custom product attribute name.
720 return $attribute->get_name();
721 }
722
723 function custom_woocommerce_rest_prepare_product_variation_object($response, $object, $request)
724 {
725
726 global $woocommerce_wpml;
727
728 //update correct product price with tax setting
729 $response->data['price'] = wc_get_price_to_display( $object );
730 $response->data['regular_price'] = wc_get_price_to_display( $object, array( 'price' => $object->get_regular_price() ) );
731 $response->data['sale_price'] = wc_get_price_to_display( $object, array( 'price' => $object->get_sale_price() ) );
732
733 $is_purchased = false;
734 if (isset($request['user_id'])) {
735 $user_id = $request['user_id'];
736 $user_data = get_userdata($user_id);
737 $user_email = $user_data->user_email;
738 $is_purchased = wc_customer_bought_product($user_email, $user_id, $response->data['id']);
739 }
740 $response->data['is_purchased'] = $is_purchased;
741 if (!empty($woocommerce_wpml->multi_currency) && !empty($woocommerce_wpml->settings['currencies_order'])) {
742
743 $price = $response->data['price'];
744
745 foreach ($woocommerce_wpml->settings['currency_options'] as $key => $currency) {
746 $rate = (float)$currency["rate"];
747 $response->data['multi-currency-prices'][$key]['price'] = $rate == 0 ? $price : sprintf("%.2f", $price * $rate);
748 }
749 }
750
751 /*Update product price for subscription product*/
752 if($object->get_type() == 'subscription_variation'){
753 $meta_data = $response->data['meta_data'];
754 $sign_up_fee = null;
755 foreach ($meta_data as $meta_data_item) {
756 if ($meta_data_item->get_data()["key"] == "_subscription_sign_up_fee") {
757 $sign_up_fee = $meta_data_item->get_data()["value"];
758 }
759 }
760 if($sign_up_fee != null){
761 $response->data['regular_price']= $sign_up_fee;
762 $response->data['price']= $sign_up_fee;
763 }
764 }
765
766 if (class_exists('WooCommerceWholeSalePrices')) {
767 $meta_data = $response->data['meta_data'];
768 foreach ($meta_data as $v) {
769 $key = is_array($v) ? $v['key'] : $v->__get('key');
770 if ((strpos($key, '_wholesale_price') !== false && strpos($key, '_have_wholesale_price') === false) || (strpos($key, '_wholesale_sale_price') !== false && strpos($key, '_have_wholesale_sale_price') === false)) {
771 if($v->__get('value')){
772 $wholesale_price = wc_get_price_to_display( $object, array( 'price' => $v->__get('value') ) );
773 $v->__set("value", number_format($wholesale_price, 2, '.', ''));
774 $v->apply_changes();
775 }
776 }
777 }
778 }
779
780 $variation_product = wc_get_product( $response->data['id'] );
781 if($variation_product) {
782 $_product = wc_get_product( $variation_product->get_parent_id() );
783 $attributes = array();
784
785 foreach ( $variation_product->get_variation_attributes() as $attribute_name => $attribute ) {
786 $name = str_replace( 'attribute_', '', $attribute_name );
787
788 if ( empty( $attribute ) && '0' !== $attribute ) {
789 continue;
790 }
791
792 // Taxonomy-based attributes are prefixed with `pa_`, otherwise simply `attribute_`.
793 if ( 0 === strpos( $attribute_name, 'attribute_pa_' ) ) {
794 $option_term = get_term_by( 'slug', $attribute, $name );
795 $attributes[] = array(
796 'id' => wc_attribute_taxonomy_id_by_name( $name ),
797 'name' => custom_get_attribute_taxonomy_name( $name, $_product ),
798 'option' => $option_term && ! is_wp_error( $option_term ) ? $option_term->name : $attribute,
799 );
800 } else {
801 $attributes[] = array(
802 'id' => 0,
803 'name' => custom_get_attribute_taxonomy_name( $name, $_product ),
804 'option' => $attribute,
805 );
806 }
807 }
808 $response->data['attributes'] = $attributes;
809 }
810 return $response;
811 }
812
813 /**
814 * Wordpress REST API: Support Rest API with Relevanssi.
815 *
816 * Attaches to 'the_posts' filter hook, checks to see if there's a place for a
817 * search and runs relevanssi_do_query() if there is.
818 *
819 * https://www.relevanssi.com/user-manual/using-relevanssi-outside-search-pages/
820 *
821 * @param array $posts An array of post objects.
822 * @param WP_Query $query The WP_Query object, default false.
823 */
824 function flutter_custom_posts_pre_query($posts, $query)
825 {
826 if ($query->is_search() && defined('REST_REQUEST') && REST_REQUEST) {
827 if (function_exists('relevanssi_do_query')) {
828 $posts = relevanssi_do_query($query);
829 $query->relevanssi_found_posts = $query->found_posts;
830 return $posts;
831 }
832 }
833 return $posts;
834 }
835
836 /**
837 * Wordpress REST API: Customize `found_posts` in Rest API with Relevanssi.
838 *
839 * @param int $found_posts The number of posts found.
840 * @param WP_Query $query The WP_Query object.
841 */
842 function flutter_custom_found_posts($found_posts, $query)
843 {
844 if ($query->is_search() && defined('REST_REQUEST') && REST_REQUEST) {
845 if (function_exists('relevanssi_do_query')) {
846 return $query->relevanssi_found_posts;
847 }
848 }
849 return $found_posts;
850 }
851
852
853 // Prepare data before checkout by webview
854 function flutter_prepare_checkout()
855 {
856
857 if(empty($_GET) && isset($_SERVER['HTTP_REFERER'])){
858 $url_components = parse_url($_SERVER['HTTP_REFERER']);
859 if (isset($url_components['query'])) {
860 parse_str($url_components['query'], $params);
861 if(!empty($params)){
862 $_GET = $params;
863 }
864 }
865 }
866
867 if (isset($_GET['mobile']) && isset($_GET['code'])) {
868
869 $code = sanitize_text_field($_GET['code']);
870 global $wpdb;
871 $table_name = $wpdb->prefix . "mstore_checkout";
872 $sql = $wpdb->prepare("SELECT * FROM $table_name WHERE code = %s", $code);
873 $item = $wpdb->get_row($sql);
874 if ($item) {
875 $data = json_decode(urldecode(base64_decode($item->order)), true);
876 } else {
877 return var_dump("Can't not get the order");
878 }
879
880 $shipping = isset($data['shipping']) ? $data['shipping'] : NULL;
881 $billing = isset($data['billing']) ? $data['billing'] : $shipping;
882
883 if (isset($data['token'])) {
884 // Validate the cookie token
885 $userId = validateCookieLogin($data['token']);
886 if(!is_wp_error($userId)){
887 if (isset($billing)) {
888 if(isset($billing["first_name"]) && !empty($billing["first_name"])){
889 update_user_meta($userId, 'billing_first_name', $billing["first_name"]);
890 update_user_meta($userId, 'shipping_first_name', $billing["first_name"]);
891 }
892 if(isset($billing["last_name"]) && !empty($billing["last_name"])){
893 update_user_meta($userId, 'billing_last_name', $billing["last_name"]);
894 update_user_meta($userId, 'shipping_last_name', $billing["last_name"]);
895 }
896 if(isset($billing["company"]) && !empty($billing["company"])){
897 update_user_meta($userId, 'billing_company', $billing["company"]);
898 update_user_meta($userId, 'shipping_company', $billing["company"]);
899 }
900 if(isset($billing["address_1"]) && !empty($billing["address_1"])){
901 update_user_meta($userId, 'billing_address_1', $billing["address_1"]);
902 update_user_meta($userId, 'shipping_address_1', $billing["address_1"]);
903 }
904 if(isset($billing["address_2"]) && !empty($billing["address_2"])){
905 update_user_meta($userId, 'billing_address_2', $billing["address_2"]);
906 update_user_meta($userId, 'shipping_address_2', $billing["address_2"]);
907 }
908 if(isset($billing["city"]) && !empty($billing["city"])){
909 update_user_meta($userId, 'billing_city', $billing["city"]);
910 update_user_meta($userId, 'shipping_city', $billing["city"]);
911 }
912 if(isset($billing["state"]) && !empty($billing["state"])){
913 update_user_meta($userId, 'billing_state', $billing["state"]);
914 update_user_meta($userId, 'shipping_state', $billing["state"]);
915 }
916 if(isset($billing["postcode"]) && !empty($billing["postcode"])){
917 update_user_meta($userId, 'billing_postcode', $billing["postcode"]);
918 update_user_meta($userId, 'shipping_postcode', $billing["postcode"]);
919 }
920 if(isset($billing["country"]) && !empty($billing["country"])){
921 update_user_meta($userId, 'billing_country', $billing["country"]);
922 update_user_meta($userId, 'shipping_country', $billing["country"]);
923 }
924 if(isset($billing["email"]) && !empty($billing["email"])){
925 update_user_meta($userId, 'billing_email', $billing["email"]);
926 update_user_meta($userId, 'shipping_email', $billing["email"]);
927 }
928 if(isset($billing["phone"]) && !empty($billing["phone"])){
929 update_user_meta($userId, 'billing_phone', $billing["phone"]);
930 update_user_meta($userId, 'shipping_phone', $billing["phone"]);
931 }
932 } else {
933 $billing = [];
934 $shipping = [];
935
936 $billing["first_name"] = get_user_meta($userId, 'billing_first_name', true);
937 $billing["last_name"] = get_user_meta($userId, 'billing_last_name', true);
938 $billing["company"] = get_user_meta($userId, 'billing_company', true);
939 $billing["address_1"] = get_user_meta($userId, 'billing_address_1', true);
940 $billing["address_2"] = get_user_meta($userId, 'billing_address_2', true);
941 $billing["city"] = get_user_meta($userId, 'billing_city', true);
942 $billing["state"] = get_user_meta($userId, 'billing_state', true);
943 $billing["postcode"] = get_user_meta($userId, 'billing_postcode', true);
944 $billing["country"] = get_user_meta($userId, 'billing_country', true);
945 $billing["email"] = get_user_meta($userId, 'billing_email', true);
946 $billing["phone"] = get_user_meta($userId, 'billing_phone', true);
947
948 $shipping["first_name"] = get_user_meta($userId, 'shipping_first_name', true);
949 $shipping["last_name"] = get_user_meta($userId, 'shipping_last_name', true);
950 $shipping["company"] = get_user_meta($userId, 'shipping_company', true);
951 $shipping["address_1"] = get_user_meta($userId, 'shipping_address_1', true);
952 $shipping["address_2"] = get_user_meta($userId, 'shipping_address_2', true);
953 $shipping["city"] = get_user_meta($userId, 'shipping_city', true);
954 $shipping["state"] = get_user_meta($userId, 'shipping_state', true);
955 $shipping["postcode"] = get_user_meta($userId, 'shipping_postcode', true);
956 $shipping["country"] = get_user_meta($userId, 'shipping_country', true);
957 $shipping["email"] = get_user_meta($userId, 'shipping_email', true);
958 $shipping["phone"] = get_user_meta($userId, 'shipping_phone', true);
959
960 if (isset($billing["first_name"]) && !isset($shipping["first_name"])) {
961 $shipping = $billing;
962 }
963 if (!isset($billing["first_name"]) && isset($shipping["first_name"])) {
964 $billing = $shipping;
965 }
966 }
967
968 // Check user and authentication
969 $user = get_userdata($userId);
970 if ($user && (!is_user_logged_in() || get_current_user_id() !== $userId)) {
971 wp_set_current_user($userId, $user->user_login);
972 wp_set_auth_cookie($userId);
973
974 header("Refresh:0");
975 }
976 cleanupAppointmentCartData($userId);
977 }
978 } else {
979 if (is_user_logged_in()) {
980 wp_logout();
981 wp_set_current_user(0);
982 header("Refresh:0");
983 }
984 }
985
986 if (is_plugin_active('woocommerce/woocommerce.php') == true) {
987 //header("Content-Security-Policy: frame-ancestors 'self' *.yourdomain.com");
988 global $woocommerce;
989 WC()->session->set('refresh_totals', true);
990 WC()->cart->empty_cart();
991
992 if(class_exists('WC_Points_Rewards_Discount')){
993 foreach ($data['fee_lines'] as $fee) {
994 if($fee['name'] == 'Cart Discount'){
995 list($points, $monetary_value) = explode(':', get_option('wc_points_rewards_redeem_points_ratio', ''));
996 $cart_price_rate = floatval($monetary_value);
997 $cart_points_rate = intval($points);
998
999 WC()->session->set( 'wc_points_rewards_discount_amount', intval($fee['total']) * $cart_points_rate / $cart_price_rate * (-1) );
1000 // generate and set unique discount code
1001 $discount_code = WC_Points_Rewards_Discount::generate_discount_code();
1002 // apply the discount
1003 WC()->cart->add_discount( $discount_code );
1004 }
1005 }
1006 }
1007
1008 $products = $data['line_items'];
1009
1010 buildCartItemData($products, function($productId, $quantity, $variationId, $attributes, $cart_item_data){
1011 global $woocommerce;
1012 $woocommerce->cart->add_to_cart($productId, $quantity, $variationId, $attributes, $cart_item_data);
1013 });
1014
1015 if (isset($shipping)) {
1016 $woocommerce->customer->set_shipping_first_name($shipping["first_name"]);
1017 $woocommerce->customer->set_shipping_last_name($shipping["last_name"]);
1018 $woocommerce->customer->set_shipping_company($shipping["company"]);
1019 $woocommerce->customer->set_shipping_address_1($shipping["address_1"]);
1020 $woocommerce->customer->set_shipping_address_2($shipping["address_2"]);
1021 $woocommerce->customer->set_shipping_city($shipping["city"]);
1022 $woocommerce->customer->set_shipping_state($shipping["state"]);
1023 $woocommerce->customer->set_shipping_postcode($shipping["postcode"]);
1024 $woocommerce->customer->set_shipping_country($shipping["country"]);
1025 }
1026
1027 if (isset($billing)) {
1028 $woocommerce->customer->set_billing_first_name($billing["first_name"]);
1029 $woocommerce->customer->set_billing_last_name($billing["last_name"]);
1030 $woocommerce->customer->set_billing_company($billing["company"]);
1031 $woocommerce->customer->set_billing_address_1($billing["address_1"]);
1032 $woocommerce->customer->set_billing_address_2($billing["address_2"]);
1033 $woocommerce->customer->set_billing_city($billing["city"]);
1034 $woocommerce->customer->set_billing_state($billing["state"]);
1035 $woocommerce->customer->set_billing_postcode($billing["postcode"]);
1036 $woocommerce->customer->set_billing_country($billing["country"]);
1037 $woocommerce->customer->set_billing_email($billing["email"]);
1038 $woocommerce->customer->set_billing_phone($billing["phone"]);
1039 }
1040
1041 if (!empty($data['coupon_lines'])) {
1042 $coupons = $data['coupon_lines'];
1043 foreach ($coupons as $coupon) {
1044 $woocommerce->cart->add_discount($coupon['code']);
1045 }
1046 }
1047
1048 if (!empty($data['shipping_lines'])) {
1049 $shippingLines = $data['shipping_lines'];
1050 $shippingMethods = [];
1051 foreach ($shippingLines as $key => $shippingLine) {
1052 if (is_plugin_active('wc-multivendor-marketplace/wc-multivendor-marketplace.php') && !empty($shippingLine['meta_data'])) {
1053 $seller_meta = array_filter($shippingLine['meta_data'],function($item){
1054 return $item['key'] == 'seller_id';
1055 });
1056 if(!empty($seller_meta)){
1057 $shippingMethods[$seller_meta[0]['value']] = $shippingLine['method_id'];
1058 }else{
1059 $shippingMethods[] = $shippingLine['method_id'];
1060 }
1061 } else{
1062 $shippingMethods[] = $shippingLine['method_id'];
1063 }
1064 }
1065 WC()->session->set('chosen_shipping_methods', $shippingMethods);
1066 }
1067 if (!empty($data['payment_method'])) {
1068 WC()->session->set('chosen_payment_method', $data['payment_method']);
1069 }
1070
1071 if (isset($data['customer_note']) && !empty($data['customer_note'])) {
1072 $_POST["order_comments"] = sanitize_text_field($data['customer_note']);
1073 $checkout_fields = WC()->checkout->__get("checkout_fields");
1074 $checkout_fields["order"] = ["order_comments" => ["type" => "textarea", "class" => [], "label" => "Order notes", "placeholder" => "Notes about your order, e.g. special notes for delivery."]];
1075 WC()->checkout->__set("checkout_fields", $checkout_fields);
1076 }
1077 }
1078 }
1079
1080 if (isset($_GET['cookie'])) {
1081 $cookie = urldecode(base64_decode(sanitize_text_field($_GET['cookie'])));
1082 $userId = validateCookieLogin($cookie);
1083 if (!is_wp_error($userId)) {
1084 $user = get_userdata($userId);
1085 if ($user !== false) {
1086 $cookie_elements = explode('|', $cookie);
1087 if (count($cookie_elements) == 4) {
1088 list($username, $expiration, $token, $hmac) = $cookie_elements;
1089 $_COOKIE[LOGGED_IN_COOKIE] = $cookie;
1090 wp_set_current_user($userId, $user->user_login);
1091 wp_set_auth_cookie($userId, true, '', $token);
1092 }
1093
1094 if (isset($_GET['order_detail']) && isset($_GET['order_id']) && is_plugin_active('dokan-lite/dokan.php')) {
1095 $url = add_query_arg(
1096 [
1097 'order_id' => $_GET['order_id'],
1098 '_wpnonce' => wp_create_nonce('dokan_view_order'),
1099 ],
1100 dokan_get_navigation_url('orders')
1101 );
1102 wp_safe_redirect($url);
1103 die;
1104 }
1105
1106 if (isset($_GET['vendor_admin'])) {
1107 global $wp;
1108 $request = $wp->request;
1109 wp_redirect(esc_url_raw(home_url("/" . $request)));
1110 die;
1111 }
1112 }
1113 }
1114 }
1115 }
1116
1117 function set_author_in_for_vendor_staff( $query ) {
1118 global $post;
1119 if ( class_exists('WeDevs_Dokan') && dokan()->is_pro_exists() && isset( $query->query['post_type'] ) && $query->query['post_type'] === 'global_product_addon' && $post != null ) {
1120 $vendor = dokan_get_vendor_by_product( $post->ID );
1121
1122 // Check if $vendor is valid before proceeding
1123 if (!$vendor) {
1124 return;
1125 }
1126
1127 if ( function_exists( 'dokan_get_vendor_staff' ) ) {
1128 $vendor_staffs = dokan_get_vendor_staff( $vendor->get_id() );
1129 if ( ! in_array( $vendor->get_id(), $vendor_staffs, true ) ) {
1130 return;
1131 }
1132 $query->set( 'author__in', $vendor_staffs );
1133 }
1134 }
1135 }
1136
1137 // Add product image to order
1138 add_filter('woocommerce_rest_prepare_shop_order_object', 'custom_woocommerce_rest_prepare_shop_order_object', 10, 1);
1139 function custom_woocommerce_rest_prepare_shop_order_object($response)
1140 {
1141 if (empty($response->data) || empty($response->data['line_items'])) {
1142 return $response;
1143 }
1144 $api = new WC_REST_Products_Controller();
1145 $req = new WP_REST_Request('GET');
1146 $line_items = [];
1147 foreach ($response->data['line_items'] as $item) {
1148 $product_id = $item['product_id'];
1149 $req->set_query_params(["id" => $product_id]);
1150 $res = $api->get_item($req);
1151 if (is_wp_error($res)) {
1152 $item["product_data"] = null;
1153 } else {
1154 $item["product_data"] = $res->get_data();
1155 }
1156 $line_items[] = $item;
1157
1158 }
1159 $response->data['line_items'] = $line_items;
1160
1161 // Get payment method
1162 $payment_method = $response->data['payment_method'];
1163 $payment_method_title = $response->data['payment_method_title'];
1164 $order_id = $response->data['id'];
1165
1166 // Get default Bank transfer info
1167 if ($payment_method == 'bacs' && class_exists('WC_Gateway_BACS')) {
1168 $bacs = new WC_Gateway_BACS();
1169 $bacs_accounts = apply_filters('woocommerce_bacs_accounts', $bacs->account_details, $order_id);
1170 $response->data['bacs_info'] = $bacs_accounts;
1171 }
1172
1173 // Get other Bank transfer info
1174 if (strpos($payment_method, 'bank_transfer') !== false && is_plugin_active('fr-multi-bank-transfer-payment-gateways-for-woocommerce/fr-multi-bank-transfer-gateways-for-woocommerce.php')) {
1175 require_once ABSPATH . 'wp-content/plugins/fr-multi-bank-transfer-payment-gateways-for-woocommerce/includes/gateways/class-fr-multi-bank-transfer-gateways-for-woocommerce-bank-transfer.php';
1176
1177 $bacs = new Fr_Multi_Bank_Transfer_Gateways_For_Woocommerce_Bank_Transfer([
1178 'id' => $payment_method,
1179 'method_title' => $payment_method_title,
1180 ]);
1181 $bacs_accounts = apply_filters('woocommerce_bacs_accounts', $bacs->account_details, $order_id);
1182 $response->data['bacs_info'] = $bacs_accounts;
1183 }
1184
1185 return $response;
1186 }
1187
1188
1189 function mstore_register_order_refund_requested_order_status()
1190 {
1191 register_post_status('wc-refund-req', array(
1192 'label' => esc_attr__('Refund Requested'),
1193 'public' => true,
1194 'show_in_admin_status_list' => true,
1195 'show_in_admin_all_list' => true,
1196 'exclude_from_search' => false,
1197 'label_count' => _n_noop('Refund requested <span class="count">(%s)</span>', 'Refund requested <span class="count">(%s)</span>')
1198 ));
1199 }
1200
1201 add_action('init', 'mstore_register_order_refund_requested_order_status');
1202
1203
1204 function mstore_add_custom_order_statuses($order_statuses)
1205 {
1206 // Create new status array.
1207 $new_order_statuses = array();
1208 // Loop though statuses.
1209 foreach ($order_statuses as $key => $status) {
1210 // Add status to our new statuses.
1211 $new_order_statuses[$key] = $status;
1212 // Add our custom statuses.
1213 if ('wc-processing' === $key) {
1214 $new_order_statuses['wc-refund-req'] = esc_attr__('Refund Requested');
1215 }
1216 }
1217
1218 return $new_order_statuses;
1219 }
1220
1221 add_filter('wc_order_statuses', 'mstore_add_custom_order_statuses');
1222
1223
1224 function custom_status_bulk_edit($actions)
1225 {
1226 // Add order status changes.
1227 $actions['mark_refund-req'] = __('Change status to refund requested');
1228
1229 return $actions;
1230 }
1231
1232 add_filter('bulk_actions-edit-shop_order', 'custom_status_bulk_edit', 20, 1);
1233
1234 add_action('rest_api_init', 'get_promptpay_qrcode_routes');
1235 function get_promptpay_qrcode_routes()
1236 {
1237 register_rest_route('promptpay', '/detail' . '/(?P<id>[\d]+)', array(
1238 'methods' => 'GET',
1239 'callback' => function($request){
1240 $available_payment_methods = WC()->payment_gateways()->payment_gateways();
1241 $paymentMethod = $available_payment_methods['thai-promptpay-easy'];
1242 $order = wc_get_order($request['id'] );
1243 $thank_msg = $paymentMethod->thank_msg;
1244 $promptpay_id = $paymentMethod->promptpay_id;
1245 $promptpay_type = $paymentMethod->promptpay_type;
1246 $promptpay_name = $paymentMethod->promptpay_name;
1247 $include_price = $paymentMethod->include_price;
1248 $image_url = get_site_url() . "/wp-content/plugins/thai-promptpay-payment-easy-gateway-plugin/images/promptpay_qrcode/promptpay-qr-l.php?type=$promptpay_type&promptpay_id=$promptpay_id";
1249
1250 if($include_price=='yes'){
1251 $price = $order->get_total();
1252 $image_url .= "&price=$price&p=1";
1253 }
1254
1255
1256 return ['thank_msg' => $thank_msg, 'qrcode_url' => $image_url, 'promptpay_id' => $promptpay_id, 'promptpay_name' => $promptpay_name, 'promptpay_type' => $paymentMethod->promptpay_type_name[$promptpay_type]];
1257 },
1258 'permission_callback' => function () {
1259 return true;
1260 },
1261 )
1262 );
1263 }
1264
1265 // Check if Woo Variation Swatches is active before adding the filter
1266 if (!function_exists('add_variation_swatches_attribute_images_to_api')) {
1267 function add_variation_swatches_attribute_images_to_api($response, $product, $request) {
1268 // First check if the plugin is active
1269 if (!function_exists('woo_variation_swatches') || !class_exists('Woo_Variation_Swatches')) {
1270 return $response;
1271 }
1272
1273 $data = $response->get_data();
1274
1275 // Only proceed if product has attributes
1276 if (empty($data['attributes'])) {
1277 return $response;
1278 }
1279
1280 $product_attributes = $product->get_attributes();
1281
1282 foreach ($data['attributes'] as $key => $attribute) {
1283 $attribute_name = $attribute['name'];
1284 $attribute_obj = isset($product_attributes[$attribute_name]) ? $product_attributes[$attribute_name] : null;
1285
1286 if ($attribute_obj && $attribute_obj->is_taxonomy()) {
1287 $terms = wp_get_post_terms($product->get_id(), $attribute_name, ['fields' => 'all']);
1288
1289 foreach ($terms as $term_key => $term) {
1290 // Get image ID from term meta set by Woo Variation Swatches
1291 $image_id = get_term_meta($term->term_id, 'product_attribute_image', true);
1292
1293 if ($image_id) {
1294 $image_size = woo_variation_swatches()->get_option('attribute_image_size', 'variation_swatches_image_size');
1295 $image_src = wp_get_attachment_image_src($image_id, $image_size);
1296
1297 if ($image_src) {
1298 // Add image data to the term in the API response
1299 $data['attributes'][$key]['options'][$term_key] = [
1300 'term_id' => $term->term_id,
1301 'name' => $term->name,
1302 'slug' => $term->slug,
1303 'image' => [
1304 'src' => $image_src[0],
1305 'width' => $image_src[1],
1306 'height' => $image_src[2]
1307 ]
1308 ];
1309 }
1310 }
1311 }
1312 }
1313 }
1314
1315 $response->set_data($data);
1316 return $response;
1317 }
1318 }
1319
1320 // Only add the filter if the function exists (as an extra check)
1321 if (function_exists('add_variation_swatches_attribute_images_to_api')) {
1322 add_filter('woocommerce_rest_prepare_product_object', 'add_variation_swatches_attribute_images_to_api', 10, 3);
1323 }