PluginProbe
MStore API – Create Native Android & iOS Apps On The Cloud / trunk
MStore API – Create Native Android & iOS Apps On The Cloud vtrunk
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 / controllers / flutter-user.php

flutter-user.php in MStore API – Create Native Android & iOS Apps On The Cloud trunk, at controllers/flutter-user.php

2,053 lines 78.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 if ( ! defined( 'ABSPATH' ) ) {
4 exit;
5 }
6
7 require_once(__DIR__ . '/flutter-base.php');
8 require_once(__DIR__ . '/helpers/apple-sign-in-helper.php');
9 require_once(__DIR__ . '/helpers/facebook-jwt-helper.php');
10 require_once(__DIR__ . '/helpers/firebase-phone-auth-helper.php');
11
12 class FlutterUserController extends FlutterBaseController
13 {
14 private function mstore_get_network_site_name() {
15 if ( function_exists( 'get_network' ) ) {
16 $network = get_network();
17 if ( $network && isset( $network->site_name ) ) {
18 return $network->site_name;
19 }
20 }
21
22 return wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
23 }
24
25 private $allowed_profile_meta_keys = array(
26 'billing_first_name',
27 'billing_last_name',
28 'billing_company',
29 'billing_address_1',
30 'billing_address_2',
31 'billing_city',
32 'billing_state',
33 'billing_postcode',
34 'billing_country',
35 'billing_email',
36 'billing_phone',
37 'shipping_first_name',
38 'shipping_last_name',
39 'shipping_company',
40 'shipping_address_1',
41 'shipping_address_2',
42 'shipping_city',
43 'shipping_state',
44 'shipping_postcode',
45 'shipping_country',
46 'shipping_email',
47 'shipping_phone',
48 );
49
50 /**
51 * Endpoint namespace
52 *
53 * @var string
54 */
55 protected $namespace = 'api/flutter_user';
56
57 public function __construct() {}
58
59 private function sanitize_profile_text($value)
60 {
61 if (is_scalar($value)) {
62 return sanitize_text_field(wp_unslash((string)$value));
63 }
64
65 return '';
66 }
67
68 private function sanitize_profile_meta_value($meta_key, $value)
69 {
70 if (!is_scalar($value)) {
71 return '';
72 }
73
74 $value = wp_unslash((string)$value);
75
76 switch ($meta_key) {
77 case 'billing_email':
78 case 'shipping_email':
79 return sanitize_email($value);
80 case 'billing_postcode':
81 case 'shipping_postcode':
82 return wc_clean($value);
83 default:
84 return sanitize_text_field($value);
85 }
86 }
87
88 /// Jetpack -> Settings -> Security -> Account Protection
89 private function is_jetpack_account_protection_enabled()
90 {
91 if (!class_exists('Automattic\\Jetpack\\Account_Protection\\Account_Protection')) {
92 return false;
93 }
94
95 try {
96 $account_protection = Automattic\Jetpack\Account_Protection\Account_Protection::instance();
97 if (!method_exists($account_protection, 'is_enabled')) {
98 return false;
99 }
100
101 return (bool) $account_protection->is_enabled();
102 } catch (Throwable $e) {
103 return false;
104 }
105 }
106
107 private function is_jetpack_password_compromised($password)
108 {
109 if (!$this->is_jetpack_account_protection_enabled()) {
110 return false;
111 }
112
113 if (!class_exists('Automattic\\Jetpack\\Account_Protection\\Validation_Service')) {
114 return false;
115 }
116
117 try {
118 $validation_service = new Automattic\Jetpack\Account_Protection\Validation_Service();
119 return (bool) $validation_service->is_leaked_password((string) $password);
120 } catch (Throwable $e) {
121 return false;
122 }
123 }
124
125 private function sanitize_meta_data($meta_data)
126 {
127 $sanitized_meta_data = array();
128
129 if (!is_array($meta_data)) {
130 return $sanitized_meta_data;
131 }
132
133 foreach ($meta_data as $item) {
134 if (!is_object($item) && !is_array($item)) {
135 continue;
136 }
137
138 $key = is_array($item) ? ($item['key'] ?? null) : ($item->key ?? null);
139 $value = is_array($item) ? ($item['value'] ?? null) : ($item->value ?? null);
140
141 if (!is_string($key) || !in_array($key, $this->allowed_profile_meta_keys, true)) {
142 continue;
143 }
144
145 if (!is_scalar($value)) {
146 continue;
147 }
148
149 $sanitized_value = $this->sanitize_profile_meta_value($key, $value);
150 $sanitized_meta_data[$key] = $sanitized_value;
151 }
152
153 return $sanitized_meta_data;
154 }
155
156 public function register_routes()
157 {
158 register_rest_route($this->namespace, '/reset-password', array(
159 array(
160 'methods' => 'POST',
161 'callback' => array($this, 'reset_password'),
162 'permission_callback' => function () {
163 return parent::checkApiPermission();
164 }
165 ),
166 ));
167
168 register_rest_route($this->namespace, '/notification', array(
169 array(
170 'methods' => 'POST',
171 'callback' => array($this, 'chat_notification'),
172 'permission_callback' => function () {
173 return parent::checkApiPermission();
174 }
175 ),
176 ));
177
178 register_rest_route($this->namespace, '/sign_up', array(
179 array(
180 'methods' => 'POST',
181 'callback' => array($this, 'register'),
182 'permission_callback' => function () {
183 return parent::checkApiPermission();
184 }
185 ),
186 ));
187 register_rest_route($this->namespace, '/sign_up_2', array(
188 array(
189 'methods' => 'POST',
190 'callback' => array($this, 'register'),
191 'permission_callback' => function () {
192 return parent::checkApiPermission();
193 }
194 ),
195 ));
196
197 register_rest_route($this->namespace, '/register', array(
198 array(
199 'methods' => 'POST',
200 'callback' => array($this, 'register'),
201 'permission_callback' => function () {
202 return parent::checkApiPermission();
203 }
204 ),
205 ));
206
207 register_rest_route($this->namespace, '/generate_auth_cookie', array(
208 array(
209 'methods' => 'POST',
210 'callback' => array($this, 'generate_auth_cookie'),
211 'permission_callback' => function () {
212 return parent::checkApiPermission();
213 }
214 ),
215 ));
216
217 register_rest_route($this->namespace, '/fb_connect', array(
218 array(
219 'methods' => 'GET',
220 'callback' => array($this, 'fb_connect'),
221 'permission_callback' => function () {
222 return parent::checkApiPermission();
223 }
224 ),
225 ));
226
227 register_rest_route($this->namespace, '/sms_login', array(
228 array(
229 'methods' => 'GET',
230 'callback' => array($this, 'sms_login'),
231 'permission_callback' => function () {
232 return parent::checkApiPermission();
233 }
234 ),
235 ));
236
237 register_rest_route($this->namespace, '/firebase_sms', array(
238 array(
239 'methods' => 'POST',
240 'callback' => function ($request) {
241 $phone = $this->firebase_sms_verify_id_token($request);
242 if (is_wp_error($phone)) {
243 return $phone;
244 }
245 return $this->firebase_sms_login($phone);
246 },
247 'permission_callback' => function () {
248 return parent::checkApiPermission();
249 }
250 ),
251 ));
252
253 register_rest_route($this->namespace, '/firebase_sms_v2', array(
254 array(
255 'methods' => 'POST',
256 'callback' => function ($request) {
257 $phone = $this->firebase_sms_verify_id_token($request);
258 if (is_wp_error($phone)) {
259 return $phone;
260 }
261 return $this->firebase_sms_login_v2($phone);
262 },
263 'permission_callback' => function () {
264 return parent::checkApiPermission();
265 }
266 ),
267 ));
268
269 register_rest_route($this->namespace, '/apple_login_2', array(
270 array(
271 'methods' => 'POST',
272 'callback' => array($this, 'apple_login'),
273 'permission_callback' => function () {
274 return parent::checkApiPermission();
275 }
276 ),
277 ));
278
279 register_rest_route($this->namespace, '/google_login', array(
280 array(
281 'methods' => 'GET',
282 'callback' => array($this, 'google_login'),
283 'permission_callback' => function () {
284 return parent::checkApiPermission();
285 }
286 ),
287 ));
288
289 register_rest_route($this->namespace, '/post_comment', array(
290 array(
291 'methods' => 'GET',
292 'callback' => array($this, 'post_comment'),
293 'permission_callback' => function () {
294 return parent::checkApiPermission();
295 }
296 ),
297 ));
298
299 register_rest_route($this->namespace, '/get_currentuserinfo', array(
300 array(
301 'methods' => 'GET',
302 'callback' => array($this, 'get_currentuserinfo'),
303 'permission_callback' => function () {
304 return parent::checkApiPermission();
305 }
306 ),
307 ));
308
309 register_rest_route($this->namespace, '/get_points', array(
310 array(
311 'methods' => 'GET',
312 'callback' => array($this, 'get_points'),
313 'permission_callback' => function () {
314 return parent::checkApiPermission();
315 }
316 ),
317 ));
318
319 register_rest_route($this->namespace, '/update_user_profile', array(
320 array(
321 'methods' => 'POST',
322 'callback' => array($this, 'update_user_profile'),
323 'permission_callback' => function () {
324 return parent::checkApiPermission();
325 }
326 ),
327 ));
328
329 register_rest_route($this->namespace, '/checkout', array(
330 array(
331 'methods' => 'POST',
332 'callback' => array($this, 'prepare_checkout'),
333 'permission_callback' => function () {
334 return parent::checkApiPermission();
335 }
336 ),
337 ));
338
339 register_rest_route($this->namespace, '/get_currency_rates', array(
340 array(
341 'methods' => 'GET',
342 'callback' => array($this, 'get_currency_rates'),
343 'permission_callback' => function () {
344 return parent::checkApiPermission();
345 }
346 ),
347 ));
348
349 register_rest_route($this->namespace, '/get_countries', array(
350 array(
351 'methods' => 'GET',
352 'callback' => array($this, 'get_countries'),
353 'permission_callback' => function () {
354 return parent::checkApiPermission();
355 }
356 ),
357 ));
358
359 register_rest_route($this->namespace, '/get_states', array(
360 array(
361 'methods' => 'GET',
362 'callback' => array($this, 'get_states'),
363 'permission_callback' => function () {
364 return parent::checkApiPermission();
365 }
366 ),
367 ));
368
369 register_rest_route($this->namespace, '/check-user', array(
370 array(
371 'methods' => 'GET',
372 'callback' => array($this, 'check_user'),
373 'permission_callback' => function () {
374 return parent::checkApiPermission();
375 }
376 ),
377 ));
378
379 register_rest_route($this->namespace, '/digits/register/check', array(
380 array(
381 'methods' => 'POST',
382 'callback' => array($this, 'digits_register_check'),
383 'permission_callback' => function () {
384 return parent::checkApiPermission();
385 }
386 ),
387 ));
388
389 register_rest_route($this->namespace, '/digits/register', array(
390 array(
391 'methods' => 'POST',
392 'callback' => array($this, 'digits_register'),
393 'permission_callback' => function () {
394 return parent::checkApiPermission();
395 }
396 ),
397 ));
398
399 register_rest_route($this->namespace, '/digits/login/check', array(
400 array(
401 'methods' => 'POST',
402 'callback' => array($this, 'digits_login_check'),
403 'permission_callback' => function () {
404 return parent::checkApiPermission();
405 }
406 ),
407 ));
408
409 register_rest_route($this->namespace, '/digits/login', array(
410 array(
411 'methods' => 'POST',
412 'callback' => array($this, 'digits_login'),
413 'permission_callback' => function () {
414 return parent::checkApiPermission();
415 }
416 ),
417 ));
418
419 register_rest_route($this->namespace, '/digits/send_otp', array(
420 array(
421 'methods' => 'POST',
422 'callback' => array($this, 'digits_send_otp'),
423 'permission_callback' => function () {
424 return parent::checkApiPermission();
425 }
426 ),
427 ));
428
429 register_rest_route($this->namespace, '/digits/resend_otp', array(
430 array(
431 'methods' => 'POST',
432 'callback' => array($this, 'digits_resend_otp'),
433 'permission_callback' => function () {
434 return parent::checkApiPermission();
435 }
436 ),
437 ));
438
439 register_rest_route($this->namespace, '/delete_account', array(
440 array(
441 'methods' => WP_REST_Server::DELETABLE,
442 'callback' => array($this, 'delete_account'),
443 'permission_callback' => array($this, 'custom_delete_item_permissions_check'),
444 ),
445 ));
446 }
447
448
449 /**
450 * Simple per-IP throttle for endpoints that must stay public.
451 *
452 * @param string $action Bucket name.
453 * @param int $limit Allowed requests within the window.
454 * @param int $window Window length in seconds.
455 * @return bool True when the request is allowed.
456 */
457 private function check_request_rate_limit($action, $limit = 20, $window = 300)
458 {
459 $ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '';
460 if ('' === $ip) {
461 return true;
462 }
463 $key = 'mstore_rl_' . md5($action . '|' . $ip);
464 $count = (int)get_transient($key);
465 if ($count >= $limit) {
466 return false;
467 }
468 set_transient($key, $count + 1, $window);
469 return true;
470 }
471
472 public function check_user($request)
473 {
474 // This endpoint is used before login (registration / phone login), so it cannot
475 // require authentication. Throttle it instead to prevent account enumeration.
476 if (!$this->check_request_rate_limit('check_user')) {
477 return parent::sendError("too_many_requests", "Too many requests. Please try again later.", 429);
478 }
479
480 $phone = isset($request['phone']) ? preg_replace('/[^\d+\-().\s]/', '', sanitize_text_field($request['phone'])) : null;
481 $username = isset($request['username']) ? sanitize_text_field($request['username']) : null;
482 if (isset($phone)) {
483 $args = array('meta_key' => 'registered_phone_number', 'meta_value' => $phone);
484 $search_users = get_users($args);
485 if (empty($search_users)) {
486 return false;
487 }
488 }
489 if (isset($username)) {
490 if (strpos($username, '@')) {
491 $user_data = get_user_by('email', trim(wp_unslash($username)));
492 } else {
493 $login = trim($username);
494 $user_data = get_user_by('login', $login);
495 }
496 if (empty($user_data)) {
497 return false;
498 }
499 }
500
501 return true;
502 }
503
504
505 public function reset_password()
506 {
507 $json = file_get_contents('php://input');
508 $params = json_decode($json, TRUE);
509 $usernameReq = $params["user_login"];
510
511 if (empty($usernameReq) || !is_string($usernameReq)) {
512 return parent::sendError("empty_username", "Enter a username or email address.", 400);
513 } elseif (strpos($usernameReq, '@')) {
514 $user_data = get_user_by('email', trim(wp_unslash($usernameReq)));
515 if (empty($user_data)) {
516 return parent::sendError("invalid_email", "There is no account with that username or email address.", 404);
517 }
518 } else {
519 $login = trim($usernameReq);
520 $user_data = get_user_by('login', $login);
521 }
522 if (!$user_data) {
523 return parent::sendError("invalid_email", "There is no account with that username or email address.", 404);
524 }
525
526 $user_login = $user_data->user_login;
527 $user_email = $user_data->user_email;
528 $key = get_password_reset_key($user_data);
529
530 if (is_wp_error($key)) {
531 return $key;
532 }
533
534 if (is_multisite()) {
535 $site_name = $this->mstore_get_network_site_name();
536 } else {
537 $site_name = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
538 }
539
540 $message = __('Someone has requested a password reset for the following account:', 'mstore-api') . "\r\n\r\n";
541 $message .= sprintf(
542 /* translators: %s: site name. */
543 __('Site Name: %s', 'mstore-api'),
544 $site_name
545 ) . "\r\n\r\n";
546 $message .= sprintf(
547 /* translators: %s: user login. */
548 __('Username: %s', 'mstore-api'),
549 $user_login
550 ) . "\r\n\r\n";
551 $message .= __('If this was a mistake, just ignore this email and nothing will happen.', 'mstore-api') . "\r\n\r\n";
552 $message .= __('To reset your password, visit the following address:', 'mstore-api') . "\r\n\r\n";
553 $message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . "\r\n";
554 $title = sprintf(
555 /* translators: %s: site name. */
556 __('[%s] Password Reset', 'mstore-api'),
557 $site_name
558 );
559 $title = apply_filters('retrieve_password_title', $title, $user_login, $user_data);
560 $message = apply_filters('retrieve_password_message', $message, $key, $user_login, $user_data);
561
562 wp_mail($user_email, wp_specialchars_decode($title), $message);
563
564 return new WP_REST_Response(array(
565 'status' => 'success',
566 ), 200);;
567 }
568
569 public function register()
570 {
571 if (!get_option('users_can_register')) {
572 return parent::sendError("disabled_register", "Registration is not enabled.", 400);
573 }
574 $json = file_get_contents('php://input');
575 $params = json_decode($json, TRUE);
576
577 // Backward compatible: accept 'username'/'email' or 'user_login'/'user_email'
578 $user_login = $params['user_login'] ?? $params['username'] ?? '';
579 $user_email = $params['user_email'] ?? $params['email'] ?? '';
580 $user_pass = $params['user_pass'] ?? '';
581
582 // If user_login is an email, extract local part as login and use full value as email
583 if (is_email($user_login)) {
584 if (empty($user_email)) {
585 $user_email = $user_login;
586 }
587 $user_login = explode('@', $user_login)[0];
588 }
589
590 $user_login = sanitize_user($user_login, true);
591 if (empty($user_login)) {
592 return parent::sendError("invalid_username", "Username is invalid.", 400);
593 }
594
595 if (array_key_exists('referral_code', $params)) {
596 $referralCodeReq = $params["referral_code"];
597 }
598
599 if (isset($params['wcfm_membership_application_status'])) {
600 $wcfm_membership_application_status = $params['wcfm_membership_application_status'];
601 }
602
603 if (isset($params["seconds"])) {
604 $seconds = (int)$params["seconds"];
605 } else {
606 $seconds = 1209600;
607 }
608
609 // WP core: user_login is required
610 if (empty($user_login) || !validate_username($user_login)) {
611 return parent::sendError("invalid_username", "Username is invalid.", 400);
612 }
613 if (username_exists($user_login)) {
614 return parent::sendError("existed_username", "Username already exists.", 400);
615 }
616
617 // WP core: user_email is optional, but if provided must be valid and unique
618 if (!empty($user_email)) {
619 $user_email = sanitize_email($user_email);
620 if (!is_email($user_email)) {
621 return parent::sendError("invalid_email", "E-mail address is invalid.", 400);
622 }
623 if (email_exists($user_email)) {
624 return parent::sendError("existed_email", "E-mail address is already in use.", 400);
625 }
626 }
627
628 // WP core: user_pass is optional, auto-generate if not provided.
629 // Jetpack: reject passwords found in public data breaches when supplied by the client.
630 if (empty($user_pass)) {
631 $user_pass = wp_generate_password();
632 } elseif ($this->is_jetpack_password_compromised($user_pass)) {
633 return parent::sendError(
634 'compromised_password',
635 'This password has been found in a public data breach. Please choose a stronger, unique password.',
636 400
637 );
638 }
639
640 // Normalize params for the allowed_params loop
641 $params['user_login'] = $user_login;
642 $params['user_email'] = $user_email;
643 $params['user_pass'] = $user_pass;
644
645 $allowed_params = array(
646 'user_login',
647 'user_email',
648 'user_pass',
649 'display_name',
650 'user_url',
651 'nickname',
652 'first_name',
653 'last_name',
654 'description',
655 'rich_editing',
656 'user_registered',
657 'jabber',
658 'aim',
659 'yim',
660 'comment_shortcuts',
661 'admin_color',
662 'use_ssl',
663 'show_admin_bar_front',
664 );
665
666 $dataRequest = $params;
667
668 foreach ($dataRequest as $field => $value) {
669 if (in_array($field, $allowed_params)) {
670 $user[$field] = trim(sanitize_text_field($value));
671 }
672 }
673
674 $default_role = class_exists('WooCommerce') ? 'customer' : get_option('default_role');
675
676 // Define safe roles that can be set during self-registration (non-elevated roles)
677 $safe_registration_roles = array('seller', 'wcfm_vendor', 'wcfm_delivery_boy', 'driver', 'owner', 'customer', 'subscriber');
678
679 $requested_role = '';
680 if (array_key_exists('role', $params)) {
681 $requested_role = sanitize_key($params['role']);
682 }
683
684 // Security: Prevent unauthenticated self-registration from setting elevated roles
685 // Allow safe vendor/delivery roles, but require authentication for admin/manager roles
686 if (!empty($requested_role) && get_role($requested_role)) {
687 if (in_array($requested_role, $safe_registration_roles, true)) {
688 // Safe role: can be set without authentication (seller, delivery, etc.)
689 $user['role'] = $requested_role;
690 } elseif (is_user_logged_in() && current_user_can('create_users')) {
691 // Elevated role: requires authentication and create_users capability
692 $user['role'] = $requested_role;
693 } else {
694 // Not safe and not authorized: use default
695 $user['role'] = $default_role;
696 }
697 } else {
698 $user['role'] = $default_role;
699 }
700 $_POST['user_role'] = $user['role']; //fix to register account with role in listeo
701
702 if (isset($referralCodeReq) && $referralCodeReq) {
703 $_COOKIE['woo_wallet_referral'] = sanitize_text_field(wp_unslash($referralCodeReq));
704 }
705
706 $user_id = wp_insert_user($user);
707
708 if (is_wp_error($user_id)) {
709 return parent::sendError($user_id->get_error_code(), $user_id->get_error_message(), 400);
710 }
711
712 // Reapply role to override WooCommerce's automatic assignment
713 if (isset($user['role']) && !empty($user['role'])) {
714 $wp_user = new WP_User($user_id);
715 $wp_user->set_role($user['role']);
716 }
717
718 if (isset($params["phone"])) {
719 $phone = preg_replace('/[^\d+\-().\s]/', '', sanitize_text_field($params["phone"]));
720 update_user_meta($user_id, 'billing_phone', $phone);
721 update_user_meta($user_id, 'registered_phone_number', $phone);
722 }
723
724 wp_new_user_notification($user_id, null, 'both');
725
726 if (isset($wcfm_membership_application_status) && $wcfm_membership_application_status == 'pending') {
727 // Check if WCFM is configured for auto-approval
728 $auto_approve = false;
729 if (is_plugin_active('wc-multivendor-marketplace/wc-multivendor-marketplace.php') && class_exists('WCFMmp')) {
730 $wcfm_membership_options = get_option('wcfm_membership_options', array());
731 $membership_reject_rules = isset($wcfm_membership_options['membership_reject_rules']) ?
732 $wcfm_membership_options['membership_reject_rules'] : array();
733 $required_approval = isset($membership_reject_rules['required_approval']) ?
734 $membership_reject_rules['required_approval'] : 'no';
735
736 // 'no' = no approval needed = auto-approve TRUE
737 $auto_approve = ($required_approval === 'no');
738 }
739
740 // Set vendor meta data
741 update_user_meta($user_id, 'store_name', $user['display_name']);
742
743 //fix crash when approve membership in WCFM
744 $wcfmvm_static_infos = (array) get_user_meta($user_id, 'wcfmvm_static_infos', true);
745 $wcfm_phone = isset($params["phone"]) ? preg_replace('/[^\d+\-().\s]/', '', sanitize_text_field($params["phone"])) : '';
746 $wcfmvm_static_infos['phone'] = $wcfm_phone;
747 update_user_meta($user_id, 'wcfmvm_static_infos', $wcfmvm_static_infos);
748 update_user_meta($user_id, 'billing_phone', $wcfm_phone);
749
750 if ($auto_approve && get_role('wcfm_vendor')) {
751 // Auto-approve: upgrade to wcfm_vendor role
752 $wp_user = new WP_User($user_id);
753 $wp_user->set_role('wcfm_vendor');
754 } else {
755 // Manual approval: keep as subscriber and send email to admin
756 update_user_meta($user_id, 'temp_wcfm_membership', true);
757 global $WCFMvm;
758 if (is_object($WCFMvm) && method_exists($WCFMvm, 'send_approval_reminder_admin')) {
759 $WCFMvm->send_approval_reminder_admin($user_id);
760 }
761 }
762 }
763
764 if (isset($params['dokan_enable_selling'])) {
765 // Check if Dokan is configured for auto-approval
766 if (is_plugin_active('dokan-lite/dokan.php') || is_plugin_active('dokan-pro/dokan-pro.php')) {
767 $dokan_settings = (array) get_option('dokan_selling', array());
768 $auto_approve = isset($dokan_settings['new_seller_enable_selling']) &&
769 $dokan_settings['new_seller_enable_selling'] === 'automatically';
770
771 // Set 'yes' if auto-approval is enabled, otherwise 'no' (pending)
772 update_user_meta($user_id, 'dokan_enable_selling', $auto_approve ? 'yes' : 'no');
773 } else {
774 // Fallback: default to pending if Dokan is not active
775 update_user_meta($user_id, 'dokan_enable_selling', 'no');
776 }
777 }
778 $cookie = generateCookieByUserId($user_id, $seconds);
779
780 return array(
781 "cookie" => $cookie,
782 "user_id" => $user_id,
783 );
784 }
785
786
787 private function get_shipping_address($userId)
788 {
789 $shipping = [];
790
791 $shipping["first_name"] = get_user_meta($userId, 'shipping_first_name', true);
792 $shipping["last_name"] = get_user_meta($userId, 'shipping_last_name', true);
793 $shipping["company"] = get_user_meta($userId, 'shipping_company', true);
794 $shipping["address_1"] = get_user_meta($userId, 'shipping_address_1', true);
795 $shipping["address_2"] = get_user_meta($userId, 'shipping_address_2', true);
796 $shipping["city"] = get_user_meta($userId, 'shipping_city', true);
797 $shipping["state"] = get_user_meta($userId, 'shipping_state', true);
798 $shipping["postcode"] = get_user_meta($userId, 'shipping_postcode', true);
799 $shipping["country"] = get_user_meta($userId, 'shipping_country', true);
800 $shipping["email"] = get_user_meta($userId, 'shipping_email', true);
801 $shipping["phone"] = get_user_meta($userId, 'shipping_phone', true);
802
803 if (empty($shipping["first_name"]) && empty($shipping["last_name"]) && empty($shipping["company"]) && empty($shipping["address_1"]) && empty($shipping["address_2"]) && empty($shipping["city"]) && empty($shipping["state"]) && empty($shipping["postcode"]) && empty($shipping["country"]) && empty($shipping["email"]) && empty($shipping["phone"])) {
804 return null;
805 }
806 return $shipping;
807 }
808
809 private function get_billing_address($userId)
810 {
811 $billing = [];
812
813 $billing["first_name"] = get_user_meta($userId, 'billing_first_name', true);
814 $billing["last_name"] = get_user_meta($userId, 'billing_last_name', true);
815 $billing["company"] = get_user_meta($userId, 'billing_company', true);
816 $billing["address_1"] = get_user_meta($userId, 'billing_address_1', true);
817 $billing["address_2"] = get_user_meta($userId, 'billing_address_2', true);
818 $billing["city"] = get_user_meta($userId, 'billing_city', true);
819 $billing["state"] = get_user_meta($userId, 'billing_state', true);
820 $billing["postcode"] = get_user_meta($userId, 'billing_postcode', true);
821 $billing["country"] = get_user_meta($userId, 'billing_country', true);
822 $billing["email"] = get_user_meta($userId, 'billing_email', true);
823 $billing["phone"] = get_user_meta($userId, 'billing_phone', true);
824
825 if (empty($billing["first_name"]) && empty($billing["last_name"]) && empty($billing["company"]) && empty($billing["address_1"]) && empty($billing["address_2"]) && empty($billing["city"]) && empty($billing["state"]) && empty($billing["postcode"]) && empty($billing["country"]) && empty($billing["email"]) && empty($billing["phone"])) {
826 return null;
827 }
828
829 return $billing;
830 }
831
832 function getResponseUserInfo($user)
833 {
834 $shipping = $this->get_shipping_address($user->ID);
835 $billing = $this->get_billing_address($user->ID);
836 $avatar = get_user_meta($user->ID, 'user_avatar', true);
837 if (!isset($avatar) || $avatar == "" || is_bool($avatar)) {
838 $avatar = get_avatar_url($user->ID);
839 } else {
840 $avatar = $avatar[0];
841 }
842 $is_driver_available = false;
843
844 if (mstore_is_lddfw_active()) {
845 $is_driver_available = filter_var(
846 get_user_meta($user->ID, 'lddfw_driver_availability', true),
847 FILTER_VALIDATE_BOOLEAN
848 );
849 } else if (mstore_is_ddwc_active()) {
850 $is_driver_available = filter_var(
851 get_user_meta($user->ID, 'ddwc_driver_availability', true),
852 FILTER_VALIDATE_BOOLEAN
853 );
854 } else {
855 $is_driver_available = in_array('administrator', $user->roles) || in_array('wcfm_delivery_boy', $user->roles);
856 }
857
858 // Check order status change capability
859 $order_status_change = false;
860
861 // Check vendor auto approval setting
862 $vendor_auto_approve_selling = false;
863
864 // Check for Dokan
865 if (is_plugin_active('dokan-lite/dokan.php') || is_plugin_active('dokan-pro/dokan-pro.php')) {
866 $dokan_settings = (array) get_option('dokan_selling', array());
867
868 // Order Status Change capability
869 $order_status_change = isset($dokan_settings['order_status_change']) ?
870 filter_var($dokan_settings['order_status_change'], FILTER_VALIDATE_BOOLEAN) : false;
871
872 // Enable Selling option (select field: 'automatically' or 'manual')
873 $vendor_auto_approve_selling = isset($dokan_settings['new_seller_enable_selling']) ?
874 ($dokan_settings['new_seller_enable_selling'] === 'automatically') : false;
875 }
876 // Check for WCFM Core (only if Dokan is not active)
877 elseif (is_plugin_active('wc-frontend-manager/wc_frontend_manager.php') && class_exists('WCFM')) {
878 global $WCFM;
879
880 // Order Status Change capability
881 $order_status_change = $WCFM->wcfm_vendor_support->wcfm_vendor_has_capability($user->ID, 'order_status_update');
882
883 // Check for WCFM Marketplace (vendor auto-approval setting)
884 if (is_plugin_active('wc-multivendor-marketplace/wc-multivendor-marketplace.php') && class_exists('WCFMmp')) {
885 // Required Approval setting from WCFM Marketplace
886 $wcfm_membership_options = get_option('wcfm_membership_options', array());
887 $membership_reject_rules = isset($wcfm_membership_options['membership_reject_rules']) ?
888 $wcfm_membership_options['membership_reject_rules'] : array();
889 $required_approval = isset($membership_reject_rules['required_approval']) ?
890 $membership_reject_rules['required_approval'] : 'no';
891
892 // 'yes' = requires approval = auto-approve FALSE
893 // 'no' = no approval needed = auto-approve TRUE
894 $vendor_auto_approve_selling = ($required_approval === 'no');
895 }
896 }
897
898 // If user is admin, always allow order status change
899 if (in_array('administrator', $user->roles)) {
900 $order_status_change = true;
901 }
902
903 return array(
904 "id" => $user->ID,
905 "username" => $user->user_login,
906 "nicename" => $user->user_nicename,
907 "email" => $user->user_email,
908 "url" => $user->user_url,
909 "registered" => $user->user_registered,
910 "displayname" => $user->display_name,
911 "firstname" => $user->first_name,
912 "lastname" => $user->last_name,
913 "nickname" => $user->nickname,
914 "description" => $user->user_description,
915 "capabilities" => $user->wp_capabilities,
916 "role" => $user->roles,
917 "shipping" => $shipping,
918 "billing" => $billing,
919 "avatar" => $avatar,
920 "is_driver_available" => $is_driver_available,
921 "dokan_enable_selling" => $user->dokan_enable_selling,
922 "order_status_change" => (bool)$order_status_change,
923 "vendor_auto_approve_selling" => (bool)$vendor_auto_approve_selling
924 );
925 }
926
927 public function generate_auth_cookie()
928 {
929 $json = file_get_contents('php://input');
930 $params = json_decode($json, TRUE);
931 if (!isset($params["username"]) || !isset($params["password"])) {
932 return parent::sendError("invalid_login", "Invalid params", 400);
933 }
934 $username = $params["username"];
935 $password = $params["password"];
936 if (!is_string($username) || !is_string($password)) {
937 return parent::sendError("invalid_login", "Invalid request format.", 400);
938 }
939
940 if (isset($params["seconds"])) {
941 $seconds = (int)$params["seconds"];
942 } else {
943 $seconds = 1209600;
944 }
945
946 if ($this->is_jetpack_account_protection_enabled()) {
947 $candidate_user = is_email($username)
948 ? get_user_by('email', $username)
949 : get_user_by('login', $username);
950
951 if ($candidate_user instanceof WP_User && wp_check_password($password, $candidate_user->user_pass, $candidate_user->ID)) {
952 if ($this->is_jetpack_password_compromised($password)) {
953 return parent::sendError(
954 'compromised_password',
955 'Your password has been found in a public data breach. Please reset your password via email before logging in.',
956 401
957 );
958 }
959 }
960 }
961
962 $_POST['action'] = 'listeoajaxlogin'; //fix to return json if login error in listeo
963 $user = wp_authenticate($username, $password);
964
965 if (is_wp_error($user)) {
966 $error_code = $user->get_error_code();
967 if ($error_code === 'compromised_password') {
968 return parent::sendError(
969 'compromised_password',
970 'Your password has been found in a public data breach. Please reset your password via email before logging in.',
971 401
972 );
973 }
974 return parent::sendError($user->get_error_code(), "Invalid username/email and/or password.", 401);
975 }
976
977 if (get_user_meta($user->ID, 'b2bking_account_approved', true) === 'no') {
978 return parent::sendError("account_pending_approval", "Your account is pending approval.", 401);
979 }
980
981 $cookie = generateCookieByUserId($user->ID, $seconds);
982
983 return array(
984 "cookie" => $cookie,
985 "cookie_name" => LOGGED_IN_COOKIE,
986 "user" => $this->getResponseUserInfo($user),
987 );
988 }
989
990 function createSocialAccount($email, $name, $firstName, $lastName)
991 {
992 $email_exists = email_exists($email);
993 if ($email_exists) {
994 $user = get_user_by('email', $email);
995 $user_id = $user->ID;
996 } else {
997 // Extract and sanitize the username from the email local part
998 $userName = sanitize_user(explode('@', $email)[0], true);
999
1000 // Fall back to a random name if the local part had no valid characters
1001 if (empty($userName)) {
1002 $userName = 'user_' . time() . '_' . wp_rand(1000, 9999);
1003 }
1004
1005 // Append an incrementing counter to guarantee uniqueness
1006 $baseUserName = $userName;
1007 $i = 0;
1008 while (username_exists($userName)) {
1009 $i++;
1010 $userName = $baseUserName . '.' . $i;
1011 }
1012 $random_password = wp_generate_password($length = 12, $include_standard_special_chars = false);
1013 $userdata = array(
1014 'user_login' => $userName,
1015 'user_email' => $email,
1016 'user_pass' => $random_password,
1017 'display_name' => $name,
1018 'first_name' => $firstName,
1019 'last_name' => $lastName
1020 );
1021 $user_id = wp_insert_user($userdata);
1022 if (is_wp_error($user_id)) {
1023 return $user_id;
1024 }
1025 }
1026
1027 $cookie = generateCookieByUserId($user_id);
1028 $user = get_userdata($user_id);
1029
1030 $response['wp_user_id'] = $user_id;
1031 $response['cookie'] = $cookie;
1032 $response['user_login'] = $user->user_login;
1033 $response['user'] = $this->getResponseUserInfo($user);
1034 return $response;
1035 }
1036
1037 public function fb_connect($request)
1038 {
1039 $fields = 'id,name,first_name,last_name,email';
1040 $access_token = $request["access_token"];
1041 if (!isset($access_token)) {
1042 return parent::sendError("invalid_login", "You must include a 'access_token' variable. Get the valid access_token for this app from Facebook API.", 400);
1043 }
1044
1045 $result = [];
1046
1047 // If token is an AuthenticationToken (in case of limited login for
1048 // iOS), validate the JWT and return the payload
1049 $jwt = FacebookJWTHelper::validateJWT($access_token);
1050
1051 if ($jwt['success']) {
1052 $decodedPayload = $jwt['decoded']['payload'];
1053 $result["email"] = $decodedPayload->email;
1054 $result["name"] = $decodedPayload->name;
1055 $result["first_name"] = $decodedPayload->given_name;
1056 $result["last_name"] = $decodedPayload->family_name;
1057 } else {
1058 $url = 'https://graph.facebook.com/me/?fields=' . $fields . '&access_token=' . $access_token;
1059 $payload = wp_remote_retrieve_body(wp_remote_get($url));
1060 $result = json_decode($payload, true);
1061 }
1062
1063 if (isset($result["email"])) {
1064 return $this->createSocialAccount($result["email"], $result['name'], $result['first_name'], $result['last_name']);
1065 } else {
1066 return parent::sendError("invalid_login", "Your 'access_token' did not return email of the user. Without 'email' user can't be logged in or registered. Get user email extended permission while joining the Facebook app.", 400);
1067 }
1068 }
1069
1070 public function sms_login($request)
1071 {
1072 $access_token = $request["access_token"];
1073 if (!isset($access_token)) {
1074 return parent::sendError("invalid_login", "You must include a 'access_token' variable. Get the valid access_token for this app from Facebook API.", 400);
1075 }
1076 $url = 'https://graph.accountkit.com/v1.3/me/?access_token=' . $access_token;
1077
1078 $WP_Http_Curl = new WP_Http_Curl();
1079 $result = $WP_Http_Curl->request($url, array(
1080 'method' => 'GET',
1081 'timeout' => 5,
1082 'redirection' => 5,
1083 'httpversion' => '1.0',
1084 'blocking' => true,
1085 'headers' => array(),
1086 'body' => null,
1087 'cookies' => array(),
1088 ));
1089
1090 $result = json_decode($result, true);
1091
1092 if (isset($result["phone"])) {
1093 $user_name = $result["phone"]["number"];
1094 $user_email = $result["phone"]["number"] . "@flutter.io";
1095 return $this->createSocialAccount($user_email, $user_name, $user_name, "");
1096 } else {
1097 return parent::sendError("invalid_login", "Your 'access_token' did not return email of the user. Without 'email' user can't be logged in or registered. Get user email extended permission while joining the Facebook app.", 400);
1098 }
1099 }
1100
1101 private function firebase_sms_verify_id_token($request)
1102 {
1103 $json = file_get_contents('php://input');
1104 $params = json_decode($json, TRUE);
1105
1106 $id_token = $params["id_token"];
1107 if (!isset($id_token)) {
1108 return parent::sendError("invalid_login", "id_token is required", 400);
1109 }
1110
1111 $helper = new FirebasePhoneAuthHelper();
1112 $result = $helper->verify_id_token($id_token);
1113
1114 if (is_wp_error($result)) {
1115 return $result;
1116 }
1117 if ($result == false) {
1118 return parent::sendError("invalid_login", "id_token is invalid.", 400);
1119 }
1120 return $result;
1121 }
1122
1123 /**
1124 * Phone number spellings an existing account may have been created under.
1125 *
1126 * Before signature verification was added, the token payload was run through
1127 * urldecode(), which turns the '+' of an E.164 number into a space that trim()
1128 * then removed - so accounts created by older builds are keyed on the digits
1129 * alone. Proper base64url decoding keeps the '+', so both spellings have to be
1130 * considered when locating an existing account, or returning users silently
1131 * get a brand new one.
1132 *
1133 * @param string $phone
1134 * @return string[] Most canonical first.
1135 */
1136 private function firebase_phone_candidates($phone)
1137 {
1138 $candidates = array($phone);
1139
1140 $stripped = ltrim($phone, '+');
1141 if ($stripped !== '' && $stripped !== $phone) {
1142 $candidates[] = $stripped;
1143 }
1144
1145 return $candidates;
1146 }
1147
1148 private function firebase_login_domain()
1149 {
1150 $domain = $_SERVER['SERVER_NAME'] == 'default_server' ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
1151 if (count(explode(".", $domain)) == 1) {
1152 $domain = "flutter.io";
1153 }
1154 return $domain;
1155 }
1156
1157 private function firebase_sms_login($phone)
1158 {
1159 if (!isset($phone)) {
1160 return parent::sendError("invalid_login", "You must include a 'phone' variable.", 400);
1161 }
1162 $domain = $this->firebase_login_domain();
1163
1164 $user_name = $phone;
1165 $user_email = $phone . "@" . $domain;
1166
1167 // Reuse the account an older build created for this number rather than
1168 // creating a duplicate under the new spelling.
1169 if (!email_exists($user_email)) {
1170 foreach ($this->firebase_phone_candidates($phone) as $candidate) {
1171 $legacy_email = $candidate . "@" . $domain;
1172 if (email_exists($legacy_email)) {
1173 $user_email = $legacy_email;
1174 $user_name = $candidate;
1175 break;
1176 }
1177 }
1178 }
1179
1180 return $this->createSocialAccount($user_email, $user_name, $user_name, "");
1181 }
1182
1183 private function firebase_sms_login_v2($phone)
1184 {
1185 if (!isset($phone)) {
1186 return parent::sendError("invalid_login", "You must include a 'phone' variable.", 400);
1187 }
1188
1189 // registered_phone_number is stored in whichever spelling the app sent at
1190 // registration time, so try the canonical form before the legacy one.
1191 $search_users = array();
1192 foreach ($this->firebase_phone_candidates($phone) as $candidate) {
1193 $search_users = get_users(array(
1194 'meta_key' => 'registered_phone_number',
1195 'meta_value' => $candidate,
1196 ));
1197 if (!empty($search_users)) {
1198 break;
1199 }
1200 }
1201
1202 if (empty($search_users)) {
1203 $domain = $this->firebase_login_domain();
1204
1205 $user = false;
1206 foreach ($this->firebase_phone_candidates($phone) as $candidate) {
1207 $user = get_user_by('email', $candidate . "@" . $domain);
1208 if ($user) {
1209 break;
1210 }
1211 }
1212
1213 if (!$user) {
1214 return parent::sendError("invalid_login", "User does not exist", 400);
1215 }
1216 $cookie = generateCookieByUserId($user->ID);
1217 $response['wp_user_id'] = $user->ID;
1218 $response['cookie'] = $cookie;
1219 $response['user_login'] = $user->user_login;
1220 $response['user'] = $this->getResponseUserInfo($user);
1221 return $response;
1222 }
1223 if (count($search_users) > 1) {
1224 return parent::sendError("invalid_login", "Too many users with the same phone number", 400);
1225 }
1226 $user = $search_users[0];
1227 $cookie = generateCookieByUserId($user->ID);
1228 $response['wp_user_id'] = $user->ID;
1229 $response['cookie'] = $cookie;
1230 $response['user_login'] = $user->user_login;
1231 $response['user'] = $this->getResponseUserInfo($user);
1232 return $response;
1233 }
1234
1235
1236 function jwtDecode($token)
1237 {
1238 $splitToken = explode(".", $token);
1239 $payloadBase64 = $splitToken[1]; // Payload is always the index 1
1240 $decodedPayload = json_decode(urldecode(base64_decode($payloadBase64)), true);
1241 return $decodedPayload;
1242 }
1243
1244 public function apple_login($request)
1245 {
1246 $json = file_get_contents('php://input');
1247 $params = json_decode($json, TRUE);
1248 $authorization_code = $params["authorization_code"];
1249 $firstName = $params["first_name"];
1250 $lastName = $params["last_name"];
1251 $teamId = $params["team_id"];
1252 $bundleId = $params["bundle_id"];
1253 if (!FlutterAppleSignInUtils::is_file_existed()) {
1254 return parent::sendError("invalid_login", "You need to upload AuthKey_XXXX.p8 file to MStore Api plugin", 400);
1255 }
1256 $token = AppleSignInHelper::generate_token($bundleId, $teamId, $authorization_code);
1257 if ($token == false || is_wp_error($token)) {
1258 return is_wp_error($token) ? $token : parent::sendError("invalid_login", "Invalid authorization_code", 400);
1259 }
1260 $decoded = $this->jwtDecode($token);
1261 $user_email = $decoded["email"];
1262 if (!isset($user_email)) {
1263 return parent::sendError("invalid_login", "Can't get the email to create account.", 400);
1264 }
1265 $display_name = explode("@", $user_email)[0];
1266 if (isset($firstName) && isset($lastName) && !empty($firstName)) {
1267 $display_name = $firstName . ' ' . $lastName;
1268 } else {
1269 $firstName = $display_name;
1270 $lastName = "";
1271 }
1272
1273 return $this->createSocialAccount($user_email, $display_name, $firstName, $lastName);
1274 }
1275
1276 public function google_login($request)
1277 {
1278 $access_token = $request["access_token"];
1279 if (!isset($access_token)) {
1280 return parent::sendError("invalid_login", "You must include a 'access_token' variable. Get the valid access_token for this app from Google API.", 400);
1281 }
1282
1283 $url = 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' . $access_token;
1284
1285 $result = wp_remote_retrieve_body(wp_remote_get($url));
1286
1287 $result = json_decode($result, true);
1288 if (isset($result["email"])) {
1289 $firstName = $result["given_name"];
1290 $lastName = $result["family_name"];
1291 $email = $result["email"];
1292 $display_name = $firstName . " " . $lastName;
1293 return $this->createSocialAccount($email, $display_name, $firstName, $lastName);
1294 } else {
1295 return parent::sendError("invalid_login", "Your 'token' did not return email of the user. Without 'email' user can't be logged in or registered. Get user email extended permission while joining the Google app.", 400);
1296 }
1297 }
1298
1299 /*
1300 * Post commment function
1301 */
1302 public function post_comment($request)
1303 {
1304 $cookie = $request["cookie"];
1305 $user_id = validateCookieLogin($cookie);
1306 if (is_wp_error($user_id)) {
1307 return $user_id;
1308 }
1309 if (!$request["post_id"]) {
1310 return parent::sendError("invalid_data", "No post specified. Include 'post_id' var in your request.", 400);
1311 } elseif (!$request["content"]) {
1312 return parent::sendError("invalid_data", "Please include 'content' var in your request.", 400);
1313 }
1314
1315 $comment_approved = 0;
1316 $user_info = get_userdata($user_id);
1317 $time = current_time('mysql');
1318 $agent = filter_has_var(INPUT_SERVER, 'HTTP_USER_AGENT') ? filter_input(INPUT_SERVER, 'HTTP_USER_AGENT') : 'Mozilla';
1319 $ips = filter_has_var(INPUT_SERVER, 'REMOTE_ADDR') ? filter_input(INPUT_SERVER, 'REMOTE_ADDR') : '127.0.0.1';
1320 $data = array(
1321 'comment_post_ID' => $request["post_id"],
1322 'comment_author' => $user_info->user_login,
1323 'comment_author_email' => $user_info->user_email,
1324 'comment_author_url' => $user_info->user_url,
1325 'comment_content' => $request["content"],
1326 'comment_type' => '',
1327 'comment_parent' => 0,
1328 'user_id' => $user_info->ID,
1329 'comment_author_IP' => $ips,
1330 'comment_agent' => $agent,
1331 'comment_date' => $time,
1332 'comment_approved' => $comment_approved,
1333 );
1334 //print_r($data);
1335 $comment_id = wp_insert_comment($data);
1336 //add metafields
1337 $meta = json_decode(stripcslashes($request["meta"]), true);
1338 //extra function
1339 add_comment_meta($comment_id, 'rating', $meta['rating']);
1340 add_comment_meta($comment_id, 'verified', 0);
1341
1342 return array(
1343 "comment_id" => $comment_id,
1344 );
1345 }
1346
1347 public function get_currentuserinfo($request)
1348 {
1349 $cookie = $request["cookie"];
1350 if (isset($request["token"])) {
1351 $cookie = mstore_decode_user_cookie($request["token"]);
1352 }
1353 $user_id = validateCookieLogin($cookie);
1354 if (is_wp_error($user_id)) {
1355 return $user_id;
1356 }
1357 $user = get_userdata($user_id);
1358 return array(
1359 "user" => $this->getResponseUserInfo($user)
1360 );
1361 }
1362
1363 /**
1364 * Get Point Reward by User ID
1365 *
1366 * @return void
1367 */
1368 function get_points($request)
1369 {
1370 global $wc_points_rewards;
1371
1372 if (!class_exists('WC_Points_Rewards_Manager') || !class_exists('WC_Points_Rewards_Points_Log') || !isset($wc_points_rewards)) {
1373 return parent::send_invalid_plugin_error("You need to install WooCommerce Points and Rewards plugin to use this api");
1374 }
1375
1376 $auth_user_id = $this->get_authenticated_user_id($request);
1377 if (is_wp_error($auth_user_id)) {
1378 return $auth_user_id;
1379 }
1380
1381 $user_id = isset($request['user_id']) ? (int)$request['user_id'] : 0;
1382 if (empty($user_id)) {
1383 $user_id = $auth_user_id;
1384 }
1385
1386 // A user may only read their own points balance and log.
1387 if ($user_id !== $auth_user_id && !user_can($auth_user_id, 'list_users')) {
1388 return parent::sendError("unauthorized", "You are not allowed to do this", 401);
1389 }
1390
1391 $current_page = isset($request['page']) ? (int)$request['page'] : 0;
1392
1393 $points_balance = WC_Points_Rewards_Manager::get_users_points($user_id);
1394 $points_label = $wc_points_rewards->get_points_label($points_balance);
1395 $count = apply_filters('wc_points_rewards_my_account_points_events', 5, $user_id);
1396 $current_page = empty($current_page) ? 1 : absint($current_page);
1397
1398 $args = array(
1399 'calc_found_rows' => true,
1400 'orderby' => array(
1401 'field' => 'date',
1402 'order' => 'DESC',
1403 ),
1404 'per_page' => $count,
1405 'paged' => $current_page,
1406 'user' => $user_id,
1407 );
1408 $total_rows = WC_Points_Rewards_Points_Log::$found_rows;
1409 $events = WC_Points_Rewards_Points_Log::get_points_log_entries($args);
1410
1411 return array(
1412 'points_balance' => $points_balance,
1413 'points_label' => $points_label,
1414 'total_rows' => $total_rows,
1415 'page' => $current_page,
1416 'count' => $count,
1417 'events' => $events
1418 );
1419 }
1420
1421 /**
1422 * Resolve the user making the request from the cookie/token parameter,
1423 * the User-Cookie header or the current WordPress authentication context.
1424 *
1425 * @param WP_REST_Request $request Current request.
1426 * @return int|WP_Error Authenticated user ID or an error when not logged in.
1427 */
1428 private function get_authenticated_user_id($request)
1429 {
1430 $cookie = null;
1431 if (isset($request["token"]) && is_string($request["token"])) {
1432 $cookie = mstore_decode_user_cookie($request["token"]);
1433 } elseif (isset($request["cookie"]) && is_string($request["cookie"])) {
1434 $cookie = $request["cookie"];
1435 } elseif (is_object($request) && method_exists($request, 'get_header')) {
1436 $header_cookie = $request->get_header("User-Cookie");
1437 if (!empty($header_cookie)) {
1438 $cookie = get_header_user_cookie($header_cookie);
1439 }
1440 }
1441
1442 if (!empty($cookie)) {
1443 $user_id = validateCookieLogin($cookie);
1444 if (!is_wp_error($user_id)) {
1445 return (int)$user_id;
1446 }
1447 }
1448
1449 // Fallback to any other authentication layer (JWT, application password, cookie).
1450 $current_user_id = get_current_user_id();
1451 if (!empty($current_user_id)) {
1452 return (int)$current_user_id;
1453 }
1454
1455 return parent::sendError("unauthorized", "You are not allowed to do this", 401);
1456 }
1457
1458 function update_user_profile()
1459 {
1460 $json = file_get_contents('php://input');
1461 $params = json_decode($json);
1462 if (!is_object($params)) {
1463 return new WP_Error("invalid_request", "Invalid request payload.", array('status' => 400));
1464 }
1465 if (!isset($params->cookie) || !is_string($params->cookie) || '' === trim($params->cookie)) {
1466 return new WP_Error("invalid_cookie", "Missing or invalid cookie parameter.", array('status' => 400));
1467 }
1468 $cookie = $params->cookie;
1469 $user_id = validateCookieLogin($cookie);
1470 if (is_wp_error($user_id)) {
1471 return $user_id;
1472 }
1473
1474 // WP core: ID is the only required field for wp_update_user
1475 $user_update = array('ID' => $user_id);
1476 $pending_meta_updates = array();
1477 $pending_avatar = null;
1478 if (isset($params->user_pass)) {
1479 $user_update['user_pass'] = $params->user_pass;
1480 }
1481 if (isset($params->user_nicename)) {
1482 if (!is_scalar($params->user_nicename)) {
1483 return new WP_Error("invalid_user_nicename", "Invalid user nicename.", array('status' => 400));
1484
1485 }
1486 $user_update['user_nicename'] = sanitize_title((string) $params->user_nicename);
1487 }
1488
1489 if (isset($params->user_email)) {
1490 if (!is_scalar($params->user_email)) {
1491 return new WP_Error("invalid_user_email", "Invalid email address.", array('status' => 400));
1492 }
1493
1494 $user_email = sanitize_email((string) $params->user_email);
1495 if ($user_email === '' || !is_email($user_email)) {
1496 return new WP_Error("invalid_user_email", "Invalid email address.", array('status' => 400));
1497 }
1498 $user_update['user_email'] = $user_email;
1499 }
1500
1501 if (isset($params->user_url)) {
1502 if (!is_scalar($params->user_url)) {
1503 return new WP_Error("invalid_user_url", "Invalid user URL.", array('status' => 400));
1504 }
1505
1506 $raw_user_url = (string) $params->user_url;
1507 $user_url = esc_url_raw($raw_user_url);
1508 if ($raw_user_url !== '' && $user_url === '') {
1509 return new WP_Error("invalid_user_url", "Invalid user URL.", array('status' => 400));
1510 }
1511
1512 $user_update['user_url'] = $user_url;
1513 }
1514 if (isset($params->display_name)) {
1515 $user_update['display_name'] = $this->sanitize_profile_text($params->display_name);
1516 }
1517 if (isset($params->first_name)) {
1518 $first_name = $this->sanitize_profile_text($params->first_name);
1519 $user_update['first_name'] = $first_name;
1520 $pending_meta_updates['shipping_first_name'] = $first_name;
1521 $pending_meta_updates['billing_first_name'] = $first_name;
1522 }
1523 if (isset($params->last_name)) {
1524 $last_name = $this->sanitize_profile_text($params->last_name);
1525 $user_update['last_name'] = $last_name;
1526 $pending_meta_updates['shipping_last_name'] = $last_name;
1527 $pending_meta_updates['billing_last_name'] = $last_name;
1528 }
1529 if (isset($params->phone)) {
1530 $phone = $this->sanitize_profile_text($params->phone);
1531 $pending_meta_updates['shipping_phone'] = $phone;
1532 $pending_meta_updates['billing_phone'] = $phone;
1533 }
1534 if (isset($params->shipping_company)) {
1535 $shipping_company = $this->sanitize_profile_text($params->shipping_company);
1536 $pending_meta_updates['shipping_company'] = $shipping_company;
1537 $pending_meta_updates['billing_company'] = $shipping_company;
1538 }
1539 if (isset($params->shipping_state)) {
1540 $shipping_state = $this->sanitize_profile_text($params->shipping_state);
1541 $pending_meta_updates['shipping_state'] = $shipping_state;
1542 $pending_meta_updates['billing_state'] = $shipping_state;
1543 }
1544 if (isset($params->shipping_address_1)) {
1545 $shipping_address_1 = $this->sanitize_profile_text($params->shipping_address_1);
1546 $pending_meta_updates['shipping_address_1'] = $shipping_address_1;
1547 $pending_meta_updates['billing_address_1'] = $shipping_address_1;
1548 }
1549 if (isset($params->shipping_address_2)) {
1550 $shipping_address_2 = $this->sanitize_profile_text($params->shipping_address_2);
1551 $pending_meta_updates['shipping_address_2'] = $shipping_address_2;
1552 $pending_meta_updates['billing_address_2'] = $shipping_address_2;
1553 }
1554 if (isset($params->shipping_city)) {
1555 $shipping_city = $this->sanitize_profile_text($params->shipping_city);
1556 $pending_meta_updates['shipping_city'] = $shipping_city;
1557 $pending_meta_updates['billing_city'] = $shipping_city;
1558 }
1559 if (isset($params->shipping_country)) {
1560 $shipping_country = $this->sanitize_profile_text($params->shipping_country);
1561 $pending_meta_updates['shipping_country'] = $shipping_country;
1562 $pending_meta_updates['billing_country'] = $shipping_country;
1563 }
1564 if (isset($params->shipping_postcode)) {
1565 $shipping_postcode = wc_clean(wp_unslash((string)$params->shipping_postcode));
1566 $pending_meta_updates['shipping_postcode'] = $shipping_postcode;
1567 $pending_meta_updates['billing_postcode'] = $shipping_postcode;
1568 }
1569 $pending_meta_updates = array_merge(
1570 $pending_meta_updates,
1571 $this->sanitize_meta_data($params->meta_data ?? null)
1572 );
1573
1574 if (isset($params->avatar)) {
1575 $pending_avatar = $params->avatar;
1576 }
1577
1578
1579 $user_data = wp_update_user($user_update);
1580
1581 if (is_wp_error($user_data)) {
1582 return $user_data;
1583 }
1584
1585 foreach ($pending_meta_updates as $meta_key => $meta_value) {
1586 update_user_meta($user_id, $meta_key, $meta_value, '');
1587 }
1588
1589 if ($pending_avatar !== null) {
1590 $count = 1;
1591 try {
1592 $attachment_id = upload_image_from_mobile($pending_avatar, $count, $user_id);
1593 $url = wp_get_attachment_image_src($attachment_id);
1594 update_user_meta($user_id, 'user_avatar', $url, '');
1595 } catch (Exception $e) {
1596 return new WP_Error("invalid_avatar", $e->getMessage(), array('status' => 400));
1597 }
1598 }
1599
1600 $user = get_userdata($user_id);
1601
1602 if (isset($params->deviceToken)) {
1603 $device_token = $this->sanitize_profile_text($params->deviceToken);
1604 if (isset($params->is_manager) && $params->is_manager) {
1605 update_user_meta($user_id, "mstore_manager_device_token", $device_token);
1606 } else if (isset($params->is_delivery) && $params->is_delivery) {
1607 update_user_meta($user_id, "mstore_delivery_device_token", $device_token);
1608 }
1609 if (!isset($params->is_delivery) && !isset($params->is_manager)) {
1610 update_user_meta($user_id, "mstore_device_token", $device_token);
1611 }
1612 if (in_array('wcfm_delivery_boy', (array)$user->roles) || in_array('driver', (array)$user->roles)) {
1613 update_user_meta($user_id, "mstore_delivery_device_token", $device_token);
1614 }
1615 }
1616
1617 return $this->getResponseUserInfo($user);
1618 }
1619
1620 function prepare_checkout()
1621 {
1622 global $json_api;
1623 $json = file_get_contents('php://input');
1624 $params = json_decode($json);
1625 $order = $params->order;
1626 if (!isset($order)) {
1627 return parent::sendError("invalid_checkout", "You must include a 'order' var in your request", 400);
1628 }
1629 global $wpdb;
1630 $table_name = $wpdb->prefix . "mstore_checkout";
1631
1632 $code = md5(wp_rand() . strtotime("now"));
1633 $success = $wpdb->insert(
1634 $table_name,
1635 array(
1636 'code' => $code,
1637 'order' => $order
1638 )
1639 );
1640 if ($success) {
1641 return $code;
1642 } else {
1643 return parent::sendError("error_insert_database", "Can't insert to database", 400);
1644 }
1645 }
1646
1647 public function get_currency_rates()
1648 {
1649 global $woocommerce_wpml;
1650
1651 if (!empty($woocommerce_wpml->multi_currency) && !empty($woocommerce_wpml->settings['currencies_order'])) {
1652 return $woocommerce_wpml->settings['currency_options'];
1653 }
1654 return parent::send_invalid_plugin_error("WooCommerce WPML hasn't been installed yet.");
1655 }
1656
1657 public function get_countries()
1658 {
1659 $wc_countries = new WC_Countries();
1660 $array = $wc_countries->get_countries();
1661 $keys = array_keys($array);
1662 $countries = array();
1663 for ($i = 0; $i < count($keys); $i++) {
1664 $countries[] = ["code" => $keys[$i], "name" => $array[$keys[$i]]];
1665 }
1666 return $countries;
1667 }
1668
1669 public function get_states($request)
1670 {
1671 $wc_countries = new WC_Countries();
1672 $array = $wc_countries->get_states($request["country_code"]);
1673 if ($array) {
1674 $keys = array_keys($array);
1675 $states = array();
1676 for ($i = 0; $i < count($keys); $i++) {
1677 $states[] = ["code" => $keys[$i], "name" => $array[$keys[$i]]];
1678 }
1679 return $states;
1680 } else {
1681 return [];
1682 }
1683 }
1684
1685 function chat_notification()
1686 {
1687 $json = file_get_contents('php://input');
1688 $params = json_decode($json, TRUE);
1689 $token = $params['token'];
1690 if (isset($token)) {
1691 $cookie = mstore_decode_user_cookie($token);
1692 } else {
1693 return parent::sendError("unauthorized", "You are not allowed to do this", 401);
1694 }
1695 $user_id = validateCookieLogin($cookie);
1696 if (is_wp_error($user_id)) {
1697 return $user_id;
1698 }
1699 $receiver_email = $params['receiver'];
1700 $sender_name = $params['sender'];
1701 if (is_email($sender_name)) {
1702 $sender = get_user_by('email', $sender_name);
1703 $sender_name = $sender->display_name;
1704 }
1705 $receiver = get_user_by('email', $receiver_email);
1706
1707 if (!$receiver) {
1708 return parent::sendError("invalid_user", "User does not exist in this world. Please re-check user's existence with the Creator :)", 401);
1709 }
1710
1711 $message = $params['message'];
1712
1713 pushNotificationForUser($receiver->ID, $sender_name, $message);
1714 if (!is_plugin_active('onesignal-free-web-push-notifications/onesignal.php')) { //fix duplicate notification if onesignal
1715 pushNotificationForVendor($receiver->ID, $sender_name, $message);
1716 }
1717 }
1718
1719 function mstore_digrest_set_variables()
1720 {
1721 $json = file_get_contents('php://input');
1722 $params = json_decode($json, TRUE);
1723
1724 $_POST['digits'] = 1;
1725
1726 if (function_exists('dig_isWhatsAppEnabled') && dig_isWhatsAppEnabled() && !empty($params['whatsapp'])) {
1727 $_POST['whatsapp'] = 1;
1728 }
1729
1730 if (isset($params['type'])) {
1731 $type = $params['type'];
1732 if ($type == 'login') {
1733 $_REQUEST['login'] = 1;
1734 }
1735 if ($type == 'register') {
1736 $_REQUEST['login'] = 2;
1737 } else if ($type == 'resetpass') {
1738 $_REQUEST['login'] = 3;
1739 } else if ($type == 'update') {
1740 $_REQUEST['login'] = 11;
1741 }
1742 } else {
1743 $_REQUEST['login'] = 2;
1744 }
1745
1746 if (isset($params['mobile'])) {
1747 $_POST['digits_reg_mail'] = $params['mobile'];
1748 }
1749
1750 if (!empty($params['email'])) {
1751 $_POST['dig_reg_mail'] = $params['email'];
1752 }
1753
1754 if (!empty($params['username'])) {
1755 $_POST['digits_reg_username'] = $params['username'];
1756 $_POST['digits_reg_name'] = $params['username'];
1757 } else if (isset($params['country_code']) && isset($params['mobile'])) {
1758 $phone_username = preg_replace('/[^0-9]/', '', $params['country_code'] . $params['mobile']);
1759 $_POST['digits_reg_username'] = $phone_username;
1760 $_POST['digits_reg_name'] = $phone_username;
1761 }
1762
1763 if (isset($params['name'])) {
1764 $_POST['digits_reg_name'] = $params['name'];
1765 }
1766 if (isset($params['last_name'])) {
1767 $_POST['digits_reg_lastname'] = $params['last_name'];
1768 }
1769 if (isset($params['country_code'])) {
1770 $_POST['digregcode'] = $params['country_code'];
1771 }
1772 if (isset($params['otp'])) {
1773 $_POST['dig_otp'] = $params['otp'];
1774 }
1775 $_POST['ftoken'] = $params['ftoken'] ?? '';
1776 $_REQUEST['ftoken'] = $params['ftoken'] ?? '';
1777
1778 $_REQUEST['csrf'] = wp_create_nonce('crsf-otp');
1779 $_POST['csrf'] = wp_create_nonce('crsf-otp');
1780
1781 $_POST['dig_nounce'] = wp_create_nonce('dig_form');
1782 $_POST['crsf-otp'] = wp_create_nonce('crsf-otp');
1783
1784 if (isset($params['password'])) {
1785 $_POST['digits_reg_password'] = $params['password'];
1786 } else {
1787 $_POST['digits_reg_password'] = wp_generate_password();
1788 }
1789
1790 $reg_custom_fields_data = get_option("dig_reg_custom_field_data", "e30=");
1791 if (!empty($reg_custom_fields_data)) {
1792 $reg_custom_fields = stripslashes(base64_decode($reg_custom_fields_data));
1793 $reg_custom_fields = json_decode($reg_custom_fields, true);
1794 if (is_array($reg_custom_fields)) {
1795 foreach ($reg_custom_fields as $key => $values) {
1796 $required = $values['required'];
1797 if ($required == 1) {
1798 $meta_key = function_exists('cust_dig_filter_string') ? cust_dig_filter_string($values['meta_key']) : sanitize_key($values['meta_key']);
1799 $post_index = 'digits_reg_' . $meta_key;
1800 $_POST[$post_index] = '1';
1801 }
1802 }
1803 }
1804 }
1805 $_REQUEST['json'] = 1;
1806
1807 if (isset($params['referral_code'])) {
1808 $_COOKIE['woo_wallet_referral'] = sanitize_text_field(wp_unslash($params['referral_code']));
1809 }
1810 }
1811
1812 function digits_register_check()
1813 {
1814 if (!function_exists('digits_create_user')) {
1815 return parent::sendError("plugin_not_found", "Please install the DIGITS: Wordpress Mobile Number Signup and Login plugin", 400);
1816 }
1817
1818 $json = file_get_contents('php://input');
1819 $params = json_decode($json, TRUE);
1820
1821 if (empty($params['country_code'])) {
1822 return parent::sendError("invalid_country_code", 'Country code is required', 400);
1823 }
1824
1825 if (empty($params['mobile'])) {
1826 return parent::sendError("invalid_mobile", 'Mobile is required', 400);
1827 }
1828
1829 $mob = $params['country_code'] . $params['mobile'];
1830 $mobuser = getUserFromPhone($mob);
1831 if ($mobuser != null || username_exists($mob)) {
1832 return parent::sendError("existed_mobile", 'Mobile Number already in use!', 400);
1833 }
1834
1835 if (!empty($params['email']) && email_exists($params['email'])) {
1836 return parent::sendError("existed_email", 'Email already in use!', 400);
1837 }
1838
1839 if (!empty($params['username']) && username_exists($params['username'])) {
1840 return parent::sendError("existed_username", 'Username already in use!', 400);
1841 }
1842
1843 return true;
1844 }
1845
1846 function digits_register()
1847 {
1848 if (!function_exists('digits_create_user')) {
1849 return parent::sendError("plugin_not_found", "Please install the DIGITS: Wordpress Mobile Number Signup and Login plugin", 400);
1850 }
1851
1852 define('REST_REQUEST', true);
1853 $this->mstore_digrest_set_variables();
1854 $userId = null;
1855 add_filter('digits_user_created_response', function ($data, $user_id) {
1856 $data['user_id'] = $user_id;
1857 return $data;
1858 }, 10, 2);
1859 $data = digits_create_user();
1860 define('REST_REQUEST', false);
1861 remove_filter('digits_user_created_response', '__return_false', 10);
1862
1863 if ($data['success'] === false) {
1864 $message = explode("<br />", $data['data']['msg'])[0];
1865
1866 // Some Digits setups still require an email field at plugin level.
1867 if (empty($_POST['dig_reg_mail']) && preg_match('/email/i', wp_strip_all_tags($message))) {
1868 return parent::sendError("email_required", "This Digits configuration requires email. Please provide email or disable email-required in Digits settings.", 400);
1869 }
1870
1871 return parent::sendError("invalid_data", $message, 400);
1872 } else {
1873 $user_id = $data['user_id'];
1874
1875 $json = file_get_contents('php://input');
1876 $params = json_decode($json, TRUE);
1877 if (!empty($params['country_code']) && !empty($params['mobile'])) {
1878 $country_code = preg_replace('/[^\d+]/', '', sanitize_text_field($params['country_code']));
1879 $mobile = preg_replace('/[^\d]/', '', sanitize_text_field($params['mobile']));
1880 $phone = $country_code . $mobile;
1881 update_user_meta($user_id, 'billing_phone', $phone);
1882 update_user_meta($user_id, 'registered_phone_number', $phone);
1883 update_user_meta($user_id, 'digt_countrycode', $country_code);
1884 update_user_meta($user_id, 'digits_phone_no', $mobile);
1885 update_user_meta($user_id, 'digits_phone', $phone);
1886 }
1887
1888 $update_data = array('ID' => $user_id);
1889 if (!empty($params['name'])) {
1890 $update_data['first_name'] = sanitize_text_field($params['name']);
1891 $update_data['display_name'] = sanitize_text_field($params['name']);
1892 }
1893 if (!empty($params['last_name'])) {
1894 $update_data['last_name'] = sanitize_text_field($params['last_name']);
1895 if (!empty($params['name'])) {
1896 $update_data['display_name'] = sanitize_text_field($params['name'] . ' ' . $params['last_name']);
1897 }
1898 }
1899 if (!empty($params['email'])) {
1900 $update_data['user_email'] = sanitize_email($params['email']);
1901 }
1902 if (count($update_data) > 1) {
1903 wp_update_user($update_data);
1904 }
1905
1906 $cookie = generateCookieByUserId($user_id);
1907 $user = get_userdata($user_id);
1908
1909 $response['wp_user_id'] = $user_id;
1910 $response['cookie'] = $cookie;
1911 $response['user_login'] = $user->user_login;
1912 $response['user'] = $this->getResponseUserInfo($user);
1913 return $response;
1914 }
1915 }
1916
1917 function digits_login_check()
1918 {
1919 if (!function_exists('digits_create_user')) {
1920 return parent::sendError("plugin_not_found", "Please install the DIGITS: Wordpress Mobile Number Signup and Login plugin", 400);
1921 }
1922
1923 $json = file_get_contents('php://input');
1924 $params = json_decode($json, TRUE);
1925
1926 if (empty($params['country_code'])) {
1927 return parent::sendError("invalid_country_code", 'Country code is required', 400);
1928 }
1929
1930 if (empty($params['mobile'])) {
1931 return parent::sendError("invalid_mobile", 'Mobile is required', 400);
1932 }
1933
1934 $mob = $params['country_code'] . $params['mobile'];
1935 $mobuser = getUserFromPhone($mob);
1936 if ($mobuser == null) {
1937 return parent::sendError("not_existed_mobile", 'Phone number is not registered!', 400);
1938 }
1939
1940 return true;
1941 }
1942
1943 function digits_login()
1944 {
1945 if (!function_exists('dig_validateMobileNumber')) {
1946 return parent::sendError("plugin_not_found", "Please install the DIGITS: Wordpress Mobile Number Signup and Login plugin", 400);
1947 }
1948
1949 $this->mstore_digrest_set_variables();
1950
1951 $otp = $_POST['dig_otp'];
1952 $validateMob = dig_validateMobileNumber($_POST['digregcode'], $_POST['digits_reg_mail'], $otp, null, 1, null, false);
1953
1954 if ($validateMob['success'] === false) {
1955 return parent::sendError("invalid_data", $validateMob['msg'], 400);
1956 }
1957
1958 $user = getUserFromPhone($validateMob['countrycode'] . $validateMob['mobile']);
1959 $cookie = generateCookieByUserId($user->ID);
1960 $response['wp_user_id'] = $user->ID;
1961 $response['cookie'] = $cookie;
1962 $response['user_login'] = $user->user_login;
1963 $response['user'] = $this->getResponseUserInfo($user);
1964 return $response;
1965 }
1966
1967 function digits_send_otp()
1968 {
1969 if (!function_exists('digits_create_user')) {
1970 return parent::sendError("plugin_not_found", "Please install the DIGITS: Wordpress Mobile Number Signup and Login plugin", 400);
1971 }
1972
1973 $json = file_get_contents('php://input');
1974 $params = json_decode($json, TRUE);
1975
1976 if (empty($params['country_code'])) {
1977 return parent::sendError("invalid_country_code", 'Country code is required', 400);
1978 }
1979
1980 if (empty($params['mobile'])) {
1981 return parent::sendError("invalid_mobile", 'Mobile is required', 400);
1982 }
1983
1984 $_REQUEST['countrycode'] = $params['country_code'];
1985 $_REQUEST['mobileNo'] = $params['mobile'];
1986 $_REQUEST['type'] = $params['type'];
1987
1988 $this->mstore_digrest_set_variables();
1989
1990
1991 $_REQUEST['csrf'] = wp_create_nonce('dig_form');
1992 $_POST['csrf'] = wp_create_nonce('dig_form');
1993
1994 do_action('wp_ajax_nopriv_digits_check_mob');
1995 }
1996
1997 function digits_resend_otp()
1998 {
1999 if (!function_exists('digits_resendotp')) {
2000 return parent::sendError("plugin_not_found", "Please install the DIGITS: Wordpress Mobile Number Signup and Login plugin", 400);
2001 }
2002
2003 $json = file_get_contents('php://input');
2004 $params = json_decode($json, TRUE);
2005
2006 if (empty($params['country_code'])) {
2007 return parent::sendError("invalid_country_code", 'Country code is required', 400);
2008 }
2009
2010 if (empty($params['mobile'])) {
2011 return parent::sendError("invalid_mobile", 'Mobile is required', 400);
2012 }
2013
2014 $_REQUEST['countrycode'] = $params['country_code'];
2015 $_REQUEST['mobileNo'] = $params['mobile'];
2016 $_REQUEST['type'] = $params['type'];
2017
2018 $this->mstore_digrest_set_variables();
2019
2020
2021 $_REQUEST['csrf'] = wp_create_nonce('dig_form');
2022 $_POST['csrf'] = wp_create_nonce('dig_form');
2023
2024 digits_resendotp();
2025 }
2026
2027
2028 function custom_delete_item_permissions_check($request)
2029 {
2030 $cookie = get_header_user_cookie($request->get_header("User-Cookie"));
2031 if (isset($cookie) && $cookie != null && parent::checkApiPermission()) {
2032 $user_id = validateCookieLogin($cookie);
2033 if (is_wp_error($user_id)) {
2034 return false;
2035 }
2036 $request["id"] = $user_id;
2037 return true;
2038 } else {
2039 return false;
2040 }
2041 }
2042
2043 function delete_account($request)
2044 {
2045 if (checkWhiteListAccounts($request["id"])) {
2046 return parent::sendError("invalid_account", "This account can't delete", 400);
2047 } else {
2048 require_once(ABSPATH . 'wp-admin/includes/user.php');
2049 return wp_delete_user($request["id"]);
2050 }
2051 }
2052 }
2053