PluginProbe
MStore API – Create Native Android & iOS Apps On The Cloud / 4.18.1
MStore API – Create Native Android & iOS Apps On The Cloud v4.18.1
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.1, at mstore-api.php

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