PluginProbe
Fluent Support – Helpdesk & Customer Support Ticket System / 2.3.2
Fluent Support – Helpdesk & Customer Support Ticket System v2.3.2
2.3.2 2.3.1 2.3.0 2.2.1 2.2.0 trunk 1.10.0 1.10.1 1.10.2 1.10.3 1.10.4 1.10.5 1.4.0 1.4.1 1.4.2 1.4.5 1.4.6 1.4.7 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.5.5 1.5.6 All 67 releases
fluent-support / app / Http / Controllers / AuthController.php

AuthController.php in Fluent Support – Helpdesk & Customer Support Ticket System 2.3.2, at app/Http/Controllers/AuthController.php

822 lines 28.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentSupport\App\Http\Controllers;
4
5 use FluentSupport\App\Models\Meta;
6 use FluentSupport\App\Services\Helper;
7 use FluentSupport\Framework\Support\Arr;
8 use FluentSupport\Framework\Http\Request\Request;
9 use FluentSupport\App\Hooks\Handlers\AuthHandler;
10 use FluentSupport\App\Hooks\Handlers\ReCaptchaHandler;
11 use FluentSupport\App\Hooks\Handlers\TwoFaHandler;
12 use FluentSupport\App\Hooks\Handlers\EmailVerificationHandler;
13
14
15 class AuthController extends Controller
16 {
17 /**
18 * signUp method will create new user submitted data from sign up form
19 * @param Request $request
20 * @return \WP_REST_Response
21 * @throws \FluentSupport\Framework\Validator\ValidationException
22 */
23 public function signup(Request $request)
24 {
25
26 if(Helper::getAuthProvider() !== 'fluent_support') {
27 return $this->sendError([
28 'message' => __('You are not allowed to signup using this form', 'fluent-support')
29 ]);
30 }
31
32 if (!wp_verify_nonce($request->getSafe('_fsupport_signup_nonce', 'sanitize_text_field'), 'fluent_support_signup_nonce')) {
33 return $this->sendError([
34 'message' => __('Security verification failed. Please try again', 'fluent-support')
35 ]);
36 }
37
38 $fields = AuthHandler::getSignupFields();
39
40 $rules = $this->getRules($fields);
41
42 $messages = $this->getMessages($rules);
43
44 /*
45 * Filter user signup form data
46 *
47 * @since v1.0.0
48 * @param array $formData
49 */
50 $formData = apply_filters('fluent_support/signup_form_data', $request->all());
51
52 /*
53 * Action before validate user signup
54 *
55 * @since v1.0.0
56 * @param array $formData
57 */
58 do_action('fluent_support/before_signup_validation', $formData);
59
60 $checkRecaptchaAvailability = $this->isRecaptchaApplicable('signup_form');
61 if ($checkRecaptchaAvailability && !$formData['_email_verification_hash']) {
62 $validateCaptcha = ReCaptchaHandler::validateRecaptcha($formData['g-recaptcha-response']);
63 if (!$validateCaptcha) {
64 return $this->response([
65 'message' => __('Your recaptcha is not verified', 'fluent-support')
66 ], 422);
67 }
68 }
69
70 $this->validate($formData, $rules, $messages);
71
72 if (empty($formData['_email_verification_token'])) {
73 $tokenHtml = EmailVerificationHandler::sendSignupEmailVerificationHtml($formData);
74
75 return $this->response([
76 'verification_html' => $tokenHtml
77 ]);
78 } else {
79 $token = $formData['_email_verification_token'];
80 $verificationHash = $formData['_email_verification_hash'];
81
82 $logHashMeta = Meta::where('object_type', 'fs_login_hashes',)
83 ->where('key', $verificationHash)
84 ->first();
85
86 if (!$logHashMeta) {
87 wp_send_json([
88 'message' => __('Please provide a valid verification code that was sent to your email address', 'fluent-support')
89 ], 422);
90 }
91
92 $logHash = Helper::safeUnserialize($logHashMeta->value);
93
94 if (!$logHash) {
95 wp_send_json([
96 'message' => __('Please provide a valid verification code that was sent to your email address', 'fluent-support')
97 ], 422);
98 }
99
100 // the code must still be unused and must not have been consumed by a prior request
101 if (($logHash['status'] ?? '') !== 'issued') {
102 wp_send_json([
103 'message' => __('Your verification code has already been used. Please try again', 'fluent-support')
104 ], 422);
105 }
106
107 // records created before the email-binding fix (or any other legacy/malformed record)
108 // have no bound email; treat them as invalid rather than proceeding with a null email
109 if (empty($logHash['email'])) {
110 wp_send_json([
111 'message' => __('Your verification code has expired. Please request a new one', 'fluent-support')
112 ], 422);
113 }
114
115 // check if it got expired or not
116 $validTill = $logHash['valid_till'] ?? '';
117 if (($logHash['used_count'] ?? 0) > 5 || ($validTill && strtotime($validTill) < current_time('timestamp'))) {
118 wp_send_json([
119 'message' => __('Your verification code has been expired. Please try again', 'fluent-support')
120 ], 422);
121 }
122
123 if (!wp_check_password($token, $logHash['two_fa_code_hash'])) {
124
125 $logHash['used_count'] += 1;
126 Meta::where('key', $logHash['login_hash'])->update([
127 'value' => maybe_serialize($logHash)
128 ]);
129
130 wp_send_json([
131 'message' => __('Please provide a valid verification code that was sent to your email address', 'fluent-support')
132 ], 422);
133 }
134
135 // atomically consume the code: only succeeds if the record is still in the exact
136 // state we just read, closing the race where two requests both pass the checks above
137 $consumed = Meta::where('key', $logHash['login_hash'])
138 ->where('object_type', 'fs_login_hashes')
139 ->where('value', $logHashMeta->value)
140 ->update([
141 'value' => maybe_serialize(array_merge($logHash, [
142 'used_count' => ($logHash['used_count'] ?? 0) + 1,
143 'status' => 'used',
144 ]))
145 ]);
146
147 if (!$consumed) {
148 wp_send_json([
149 'message' => __('Your verification code has already been used. Please try again', 'fluent-support')
150 ], 422);
151 }
152
153 // the email is now server-verified for this code; ignore whatever the client
154 // submitted and use the address the code was actually issued to, so the signup
155 // can never be completed against a different (e.g. victim's) email address
156 $formData['email'] = $logHash['email'];
157 }
158
159 /*
160 * Action After validate user signup validation success
161 *
162 * @since v1.0.0
163 * @param array $formData
164 */
165 do_action('fluent_support/after_signup_validation', $formData);
166
167 $userId = $this->createUser($formData);
168
169 if (is_wp_error($userId)) {
170 return $this->response(
171 apply_filters(
172 'fluent_support/signup_create_user_error',
173 ['error' => $userId->get_error_message()]
174 ), 423);
175 }
176
177 /*
178 * Action After creating WP user from ticket sign up form
179 *
180 * @since v1.0.0
181 * @param array $formData
182 */
183 do_action('fluent_support/after_creating_user');
184
185 $this->maybeUpdateUser($userId, $formData);
186 $this->addUserMetaData($userId, $formData);
187 $this->assignRole($userId);
188 $this->login($userId);
189
190 /*
191 * Filter for user signup complete message and redirect
192 *
193 * @since v1.0.0
194 * @param array $response
195 */
196 $response = apply_filters('fluent_support/signup_complete_response', [
197 'message' => __('Successfully registered to the site.', 'fluent-support'),
198 'redirect' => Arr::get($formData, '__redirect_to', Helper::getPortalBaseUrl())
199 ]);
200
201 return $this->response($response);
202 }
203
204 /**
205 * handleLogin method will perform login functionality and redirect
206 * @param Request $request
207 * @return \WP_REST_Response
208 */
209 public function handleLogin(Request $request)
210 {
211 if(Helper::getAuthProvider() !== 'fluent_support') {
212 return $this->sendError([
213 'message' => __('You are not allowed to login using this form', 'fluent-support')
214 ]);
215 }
216
217 if (!wp_verify_nonce($request->getSafe('_support_login_nonce', 'sanitize_text_field'), 'fsupport_login_nonce')) {
218 return $this->response([
219 'message' => __('Security verification failed', 'fluent-support')
220 ], 403);
221 }
222
223 $data = $request->all();
224
225 $checkRecaptchaAvailability = $this->isRecaptchaApplicable('login_form');
226 if ($checkRecaptchaAvailability) {
227 $validateCaptcha = ReCaptchaHandler::validateRecaptcha($data['g-recaptcha-response']);
228
229 if (!$validateCaptcha) {
230 return $this->response([
231 'message' => __('Your recaptcha is not verified', 'fluent-support')
232 ], 422);
233 }
234 }
235
236 if (empty($data['pwd']) || empty($data['log'])) {
237 return $this->response([
238 'message' => __('Email and Password is required', 'fluent-support')
239 ], 403);
240 }
241 $redirectUrl = Helper::getPortalBaseUrl();
242 if ($redirect = $request->getSafe('redirect_to', 'sanitize_text_field')) {
243 $redirectUrl = wp_validate_redirect($redirect, $redirectUrl);
244 }
245
246 if (get_current_user_id()) { // user already registered
247 return $this->sendSuccess([
248 'redirect' => $redirectUrl
249 ]);
250 }
251
252 $email = sanitize_user($data['log']);
253 $password = trim($data['pwd'] ?? '');
254
255 if (is_email($email)) {
256 $user = get_user_by('email', $email);
257 } else {
258 $user = get_user_by('login', $email);
259 }
260
261 // Rate limiting: per-IP bucket (5 attempts) + per-account bucket (20 attempts)
262 $ip = Helper::getIp();
263 $ipKey = $user
264 ? 'fs_login_ip_' . wp_hash($user->ID . '|' . $ip)
265 : 'fs_login_ip_' . wp_hash(strtolower($email) . '|' . $ip);
266 $accountKey = $user
267 ? 'fs_login_act_' . wp_hash($user->ID)
268 : 'fs_login_act_' . wp_hash(strtolower($email));
269
270 $ipAttempts = get_transient($ipKey);
271 $accountAttempts = get_transient($accountKey);
272
273 if (($ipAttempts !== false && $ipAttempts >= 5) || ($accountAttempts !== false && $accountAttempts >= 20)) {
274 return $this->sendError([
275 'message' => __('Too many login attempts. Please try again after 15 minutes.', 'fluent-support')
276 ], 429);
277 }
278
279 if (!$user) {
280 $user = new \WP_Error('authentication_failed', __('Invalid username, email address or incorrect password.', 'fluent-support'));
281
282 do_action('wp_login_failed', $email, $user);
283 $this->incrementLoginAttempts($ipKey);
284 $this->incrementLoginAttempts($accountKey);
285
286 return $this->response([
287 'message' => __('Email or Password is not valid. Please try again', 'fluent-support')
288 ], 403);
289
290 }
291
292 $twoFactorEnabled = Helper::getBusinessSettings('enable_two_fa');
293 if ('yes' === $twoFactorEnabled) {
294 if (!wp_check_password($password, $user->user_pass, $user->ID)) {
295 $this->incrementLoginAttempts($ipKey);
296 $this->incrementLoginAttempts($accountKey);
297
298 return $this->response([
299 'message' => __('Invalid username, email address or incorrect password.', 'fluent-support')
300 ], 403);
301 }
302
303 (new TwoFaHandler)->maybe2FaRedirect($user);
304 }
305
306 if (apply_filters('fluent_support_use_native_login', true)) {
307 $user = wp_signon();
308 if (is_wp_error($user)) {
309 $this->incrementLoginAttempts($ipKey);
310 $this->incrementLoginAttempts($accountKey);
311 return $this->response([
312 'message' => $user->get_error_message()
313 ], 403);
314 }
315
316 // Clear rate limits for the authenticated user
317 $authIpKey = 'fs_login_ip_' . wp_hash($user->ID . '|' . $ip);
318 $authAccountKey = 'fs_login_act_' . wp_hash($user->ID);
319 delete_transient($authIpKey);
320 delete_transient($authAccountKey);
321 return $this->sendSuccess([
322 'redirect' => $redirectUrl
323 ]);
324 }
325
326 if (wp_check_password($password, $user->user_pass, $user->ID)) {
327 delete_transient($ipKey);
328 delete_transient($accountKey);
329 $this->login($user->ID);
330 return $this->sendSuccess([
331 'redirect' => $redirectUrl
332 ]);
333 }
334
335 $this->incrementLoginAttempts($ipKey);
336 $this->incrementLoginAttempts($accountKey);
337
338 return $this->response([
339 'message' => __('Invalid username, email address or incorrect password.', 'fluent-support')
340 ], 403);
341 }
342
343 private function incrementLoginAttempts($rateLimitKey)
344 {
345 $attempts = get_transient($rateLimitKey);
346 if ($attempts === false) {
347 set_transient($rateLimitKey, 1, 15 * MINUTE_IN_SECONDS);
348 } else {
349 set_transient($rateLimitKey, $attempts + 1, 15 * MINUTE_IN_SECONDS);
350 }
351 }
352
353 public function isRecaptchaApplicable($formName)
354 {
355 $reCaptchaSettingsData = Meta::where('object_type', '_fs_recaptcha_settings')->first();
356 if(!isset($reCaptchaSettingsData->value)){
357 return false;
358 }
359 $reCaptchaData = Helper::safeUnserialize($reCaptchaSettingsData->value, []);
360 if(!isset($reCaptchaData['is_enabled']) || !isset($reCaptchaData['formContainingReCaptcha'])){
361 return false;
362 }
363 $isEnabled = filter_var($reCaptchaData['is_enabled'], FILTER_VALIDATE_BOOLEAN);
364 if (!$isEnabled) {
365 return false;
366 }
367 $formContainingReCaptcha = $reCaptchaData['formContainingReCaptcha'];
368 return 'yes' === $formContainingReCaptcha[$formName];
369 }
370
371 private function nativeLoginHandler($user, $info, $redirectUrl = '')
372 {
373 if (!$redirectUrl) {
374 $redirectUrl = Helper::getPortalBaseUrl();
375 }
376
377 $secure_cookie = is_ssl();
378 if (!$secure_cookie && !force_ssl_admin()) {
379 if (get_user_option('use_ssl', $user->ID)) {
380 $secure_cookie = true;
381 force_ssl_admin(true);
382 }
383 }
384
385 if (class_exists('\Limit_Login_Attempts')) {
386 global $limit_login_attempts_obj;
387 $limit_login_attempts_try = $limit_login_attempts_obj->wp_authenticate_user($user, false);
388 if (is_wp_error($limit_login_attempts_try)) {
389 return $this->response([
390 'message' => implode('<br/>', $limit_login_attempts_try->get_error_messages())
391 ], 403);
392 }
393 }
394
395 $user_signon = wp_signon($info, $secure_cookie);
396
397 // Note: No sanitization needed here as we're only checking emptiness, not using the cookie value
398 if (!is_wp_error($user_signon) && empty($_COOKIE[LOGGED_IN_COOKIE])) {
399 if (headers_sent()) {
400 return $this->response([
401 // translators: %1$s is the URL to WordPress cookies documentation, %2$s is the URL to WordPress support forums
402 'message' => sprintf(__('<strong>ERROR</strong>: Cookies are blocked due to unexpected output. For help, please see <a href="%1$s">this documentation</a> or try the <a href="%2$s">support forums</a>.', 'fluent-support'),
403 'https://codex.wordpress.org/Cookies', 'https://wordpress.org/support/')
404 ], 403);
405 }
406 }
407
408 if (is_wp_error($user_signon)) {
409 $errorMessage = __('Email or Password is not valid. Please try again', 'fluent-support');
410
411 if (class_exists('Limit_Login_Attempts')) {
412 global $limit_login_attempts_obj;
413 if ($limit_login_attempts_obj) {
414 $limit_login_attempts_obj->limit_login_failed($user->user_login);
415 $msg = $limit_login_attempts_obj->get_message();
416 if ($msg) {
417 $errorMessage = $msg;
418 }
419 }
420 }
421
422 return $this->response([
423 'message' => $errorMessage
424 ], 403);
425 }
426
427 // WP Last Login plugin compatibility
428 if (class_exists('\Obenland_Wp_Last_Login')) {
429 update_user_meta($user_signon->ID, 'wp-last-login', time());
430 }
431
432 return $this->sendSuccess([
433 'redirect' => $redirectUrl
434 ]);
435 }
436
437 /**
438 * getRules method will prepare the rules for the input field
439 * @param array $fields
440 * @return mixed
441 */
442 protected function getRules($fields = [])
443 {
444 $rules = [];
445
446 foreach ($fields as $fieldName => $field) {
447 if (array_key_exists('required', $field)) {
448 $rules[$fieldName] = 'required';
449 }
450
451 $pipe = array_key_exists($fieldName, $rules) ? '|' : '';
452
453 if ($field['type'] === 'email') {
454 $rules[$fieldName] = $rules[$fieldName] . $pipe . 'email';
455 } elseif ($field['type'] === 'password') {
456 $rules[$fieldName] = $rules[$fieldName] . $pipe . 'min:8';
457 }
458 }
459 /*
460 * Filter user signup validation rules
461 *
462 * @since v1.0.0
463 * @param array $rules
464 */
465 return apply_filters('fluent_support/signup_validation_rules', $rules);
466 }
467
468
469 public function resetPassword(Request $request)
470 {
471
472 if(Helper::getAuthProvider() !== 'fluent_support') {
473 return $this->sendError([
474 'message' => __('You are not allowed to reset password using this form', 'fluent-support')
475 ]);
476 }
477
478 $errors = new \WP_Error();
479
480 if (!wp_verify_nonce($request->getSafe('_fsupport_reset_pass_nonce', 'sanitize_text_field'), 'fluent_support_reset_pass_nonce')) {
481 return $this->sendError([
482 'message' => __('Security verification failed. Please try again', 'fluent-support')
483 ]);
484 }
485
486 $usernameOrEmail = trim(wp_unslash($request->getSafe('user_login', 'sanitize_text_field')));
487
488 if (!$usernameOrEmail) {
489 return $this->sendError([
490 'message' => 'Username or email is required'
491 ]);
492 }
493
494 // IP bucket is a generous volumetric backstop (shared office/NAT IPs can have many
495 // unrelated users). It runs before the account lookup so that probes for accounts
496 // that don't exist are throttled too. Keyed on the IP only, so a 429 here reveals
497 // nothing about whether any given account exists.
498 if (Helper::hitRateLimit('fs_reset_pass_ip_' . wp_hash(Helper::getIp()), 20)) {
499 return $this->sendError([
500 'message' => __('Too many password reset requests. Please try again after 15 minutes.', 'fluent-support')
501 ], 429);
502 }
503
504 $user_data = get_user_by('email', $usernameOrEmail);
505
506 if (!$user_data) {
507 $user_data = get_user_by('login', $usernameOrEmail);
508 }
509
510 if (!$user_data) {
511 return $this->sendResetPassResponse();
512 }
513
514 $user_data = apply_filters('lostpassword_user_data', $user_data, $errors);
515
516 do_action('lostpassword_post', $errors, $user_data);
517
518 $errors = apply_filters('lostpassword_errors', $errors, $user_data);
519
520 if ($errors->has_errors()) {
521 return $this->sendResetPassResponse();
522 }
523
524 if (!$user_data) {
525 return $this->sendResetPassResponse();
526 }
527
528 if (is_multisite() && !is_user_member_of_blog($user_data->ID, get_current_blog_id())) {
529 return $this->sendResetPassResponse();
530 }
531
532 // Redefining user_login ensures we return the right case in the email.
533 $user_login = $user_data->user_login;
534
535 do_action('retrieve_password', $user_login);
536
537 $allow = apply_filters('allow_password_reset', true, $user_data->ID);
538
539 if (!$allow || is_wp_error($allow)) {
540 return $this->sendResetPassResponse();
541 }
542
543
544 /*
545 * Filter reset password link text
546 *
547 * @since v1.5.7
548 * @param string $linkText
549 */
550 // translators: %s is the site name
551 $linkText = apply_filters("fluent_support/reset_password_link", sprintf(__('Reset your password for %s', 'fluent-support'), get_bloginfo('name')));
552
553 // Issuance cooldown. get_password_reset_key() rotates the stored key, invalidating
554 // any link already sitting in the account owner's inbox, so an unthrottled caller
555 // could deny password recovery indefinitely. Suppressing the duplicate issuance is
556 // safe: reset mail only ever goes to the account owner, so whoever triggered the
557 // first send has already put a working link in that inbox.
558 $cooldownKey = 'fs_reset_pass_sent_' . wp_hash($user_data->ID);
559
560 if (get_transient($cooldownKey)) {
561 return $this->sendResetPassResponse();
562 }
563
564 set_transient($cooldownKey, 1, 5 * MINUTE_IN_SECONDS);
565
566 $resetUrl = add_query_arg([
567 'action' => 'rp',
568 'key' => get_password_reset_key($user_data),
569 'login' => rawurlencode($user_data->user_login)
570 ], wp_login_url());
571
572 $resetLink = '<a href="' . $resetUrl . '">' . $linkText . '</a>';
573
574 /*
575 * Filter reset password email subject
576 *
577 * @since v1.5.7
578 * @param string $mailSubject
579 */
580 // translators: %s is the site name
581 $mailSubject = apply_filters("fluent_support/reset_password_mail_subject", sprintf(__('Reset your password for %s support portal', 'fluent-support'), get_bloginfo('name')));
582
583 // translators: %s is the user's first name
584 $message = '<p>' . sprintf(__('Hi %s,', 'fluent-support'), $user_data->first_name) . '</p>' .
585 '<p>' . __('Someone has requested a new password for the following account on WordPress:', 'fluent-support') . '</p>' .
586 // translators: %s is the username
587 '<p>' . sprintf(__('Username: %s', 'fluent-support'), $user_login) . '</p>' .
588 '<p>' . $resetLink . '</p>' .
589 '<p>' . __('If you did not request to reset your password, please ignore this email.', 'fluent-support') . '</p>';
590
591 /*
592 * Filter reset password email body text
593 *
594 * @since v1.5.7
595 * @param string $message
596 * @param object $user
597 * @param string $resetLink
598 */
599 $message = apply_filters('fluent_support/reset_password_message', $message, $user_data, $resetLink);
600
601 $headers = array('Content-Type: text/html; charset=UTF-8');
602
603 wp_mail($user_data->user_email, $mailSubject, $message, $headers);
604
605 return $this->sendResetPassResponse();
606 }
607
608 /**
609 * Single response for every password reset outcome.
610 *
611 * Whether the account exists, is disallowed, is not a member of this site or is
612 * inside the resend cooldown, the caller sees the same thing — otherwise the form
613 * confirms which usernames and email addresses are real.
614 *
615 * @return mixed
616 */
617 protected function sendResetPassResponse()
618 {
619 return $this->sendSuccess([
620 'message' => __('If an account matches that username or email, a password reset link has been sent. Please check your inbox, including the spam folder.', 'fluent-support')
621 ]);
622 }
623
624 /**
625 * getMessages message will return the validation message regarding sign up or sign in
626 * @param array $rules
627 * @return mixed
628 */
629 protected function getMessages($rules = [])
630 {
631 /*
632 * Filter user signup validation message
633 *
634 * @since v1.0.0
635 * @param array $arg
636 * @param array $rules
637 */
638 return apply_filters('fluent_support/signup_validation_messages', [], $rules);
639 }
640
641 /**
642 * createUser method will create new user
643 * @param array $formData
644 * @return mixed
645 */
646 public function createUser($formData = [])
647 {
648 /*
649 * Filter user signup email
650 *
651 * @since v1.0.0
652 * @param string $email
653 */
654 $email = apply_filters('fluent_support/signup_email', Arr::get($formData, 'email'));
655
656 /*
657 * Filter user signup username
658 *
659 * @since v1.0.0
660 * @param string $username
661 */
662 $userName = apply_filters('fluent_support/signup_username', Arr::get($formData, 'username'));
663
664 if (empty($formData['password'])) {
665 $password = wp_generate_password(16, true, true);
666 } else {
667 $password = $formData['password'];
668 }
669
670 /*
671 * Filter user signup password
672 *
673 * @since v1.0.0
674 * @param string $password
675 */
676 $password = apply_filters('fluent_support/signup_password', $password);
677
678 /*
679 * Action before creating WP user using Fluent Support signup form
680 *
681 * @since v1.0.0
682 * @param string $userName
683 * @param string $password
684 * @param string $email
685 */
686 do_action('fluent_support/before_creating_user', $userName, $password, $email);
687
688 $userId = wp_create_user($userName, $password, $email);
689
690 if (is_wp_error($userId)) {
691 return false;
692 }
693
694 return $userId;
695
696 }
697
698 /**
699 * maybeUpdateUser method will update user information if exists
700 * @param $userId
701 * @param $formData
702 */
703 public function maybeUpdateUser($userId, $formData)
704 {
705 $firstName = Arr::get($formData, 'first_name', '');
706 $lastName = Arr::get($formData, 'last_name', '');
707 $name = trim($firstName . ' ' . $lastName);
708
709 $data = array_filter([
710 'ID' => $userId,
711 'user_nicename' => $name,
712 'display_name' => $name,
713 'first_name' => $firstName,
714 'last_name' => $lastName,
715 ]);
716
717 if ($name) {
718 /*
719 * Action before updating a customer/user
720 *
721 * @since v1.0.0
722 * @param array $data
723 */
724 do_action('fluent_support/before_updating_user', $data);
725
726 /*
727 * Filter user updatable data
728 *
729 * @since v1.0.0
730 * @param $data
731 */
732 $updateUserData = apply_filters('fluent_support/update_user_data', $data);
733 wp_update_user($updateUserData);
734
735 /*
736 * Action after updating a customer/user
737 *
738 * @since v1.0.0
739 * @param array $data
740 */
741 do_action('fluent_support/after_updating_user', $data);
742 }
743 }
744
745 public function addUserMetaData($userId, $formData) {
746 $customFieldsKey = apply_filters('fluent_support/custom_registration_form_fields_key', Helper::getBusinessSettings('custom_registration_form_field'));
747
748 if (empty($customFieldsKey)) {
749 return;
750 }
751
752 foreach ($customFieldsKey as $key) {
753 if (isset($formData[$key])) {
754 $fieldValue = $formData[$key];
755 update_user_meta($userId, $key, $fieldValue);
756 }
757 }
758 }
759
760 /**
761 * assignRole method will assign role to a given user id
762 * @param $userId
763 */
764 protected function assignRole($userId)
765 {
766 $user = new \WP_User($userId);
767
768 /*
769 * Action before assigning role to registered user
770 *
771 * @since v1.0.0
772 * @param array $data
773 */
774 do_action('fluent_support/before_assigning_role', $user);
775 /*
776 * Filter user assignable role after signup
777 *
778 * @since v1.0.0
779 * @param string $setRole WordPress user role key
780 */
781 $setRole = apply_filters('fluent_support/user_role', 'subscriber');
782 $user->set_role($setRole);
783
784 /*
785 * Action after assigning role to registered user
786 *
787 * @since v1.0.0
788 * @param array $data
789 */
790 do_action('fluent_support/after_assigning_role', $user);
791 }
792
793
794 /**
795 * login method will clear existing cookies and set new cookie for a given user id
796 * @param $userId
797 */
798 protected function login($userId)
799 {
800 /*
801 * Action before login
802 *
803 * @since v1.0.0
804 * @param integer $userId
805 */
806 do_action('fluent_support/before_logging_in_user', $userId);
807
808 wp_clear_auth_cookie();
809 wp_set_current_user($userId);
810 wp_set_auth_cookie($userId);
811
812 /*
813 * Action after login
814 *
815 * @since v1.0.0
816 * @param integer $userId
817 */
818 do_action('fluent_support/after_logging_in_user', $userId);
819 }
820
821 }
822