PluginProbe
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses / 2.4.01
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses v2.4.01
2.11.0 2.10.0 2.10.01 2.9.1 2.9.0 2.8.1 2.8.0 2.7.7 2.7.5 2.7.0 2.6.01 2.6.0 2.5.0 2.4.01 trunk 1.0.90 1.0.91 1.0.92 1.0.93 1.0.94 1.0.95 1.0.96 1.0.97 1.0.98 1.0.99 All 78 releases
fluent-community / app / Http / Controllers / ProfileController.php

ProfileController.php in FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses 2.4.01, at app/Http/Controllers/ProfileController.php

737 lines 28.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentCommunity\App\Http\Controllers;
4
5 use FluentCommunity\App\Functions\Utility;
6 use FluentCommunity\App\Models\Comment;
7 use FluentCommunity\App\Models\NotificationSubscription;
8 use FluentCommunity\App\Models\Space;
9 use FluentCommunity\App\Models\SpaceGroup;
10 use FluentCommunity\App\Models\User;
11 use FluentCommunity\App\Models\XProfile;
12 use FluentCommunity\App\Services\CustomSanitizer;
13 use FluentCommunity\App\Services\FeedsHelper;
14 use FluentCommunity\App\Services\Helper;
15 use FluentCommunity\App\Services\NotificationPref;
16 use FluentCommunity\App\Services\ProfileHelper;
17 use FluentCommunity\Framework\Http\Request\Request;
18 use FluentCommunity\Framework\Support\Arr;
19
20 class ProfileController extends Controller
21 {
22 public function getProfile(Request $request, $userName)
23 {
24 $xprofile = XProfile::where('username', $userName)
25 ->firstOrFail();
26
27 if ($xprofile->status != 'active' && !Helper::isModerator()) {
28 return $this->sendError([
29 'message' => __('This profile is not active', 'fluent-community'),
30 'status' => 403
31 ]);
32 }
33
34 $canViewProfile = Utility::canViewUserProfile($xprofile->user_id);
35
36 $user = get_user_by('ID', $xprofile->user_id);
37
38 $profile = [
39 'user_id' => $xprofile->user_id,
40 'is_verified' => $xprofile->is_verified,
41 'display_name' => $xprofile->display_name,
42 'username' => $xprofile->username,
43 'avatar' => $xprofile->avatar,
44 'cover_photo' => Arr::get($xprofile->meta, 'cover_photo'),
45 'total_points' => $xprofile->total_points,
46 'badge_slugs' => (array)Arr::get($xprofile->meta, 'badge_slug', []),
47 'status' => $xprofile->status,
48 'is_restricted' => !$canViewProfile,
49 'canViewUserSpaces' => ProfileHelper::canViewUserSpaces($xprofile->user_id, $this->getUser())
50 ];
51
52 if (Utility::showLastActivity()) {
53 $profile['last_activity'] = $xprofile->last_activity;
54 }
55
56 if ($canViewProfile) {
57 $profile['website'] = Arr::get($xprofile->meta, 'website');
58 $profile['created_at'] = $xprofile->created_at->format('Y-m-d H:i:s');
59 $profile['social_links'] = (object) Arr::get($xprofile->meta, 'social_links', []);
60 $profile['compilation_score'] = $xprofile->getCompletionScore();
61 $profile['short_description_rendered'] = wp_kses_post(FeedsHelper::mdToHtml($xprofile->short_description));
62 }
63
64 $currentUserId = get_current_user_id();
65
66 $isOwn = $xprofile->user_id == $currentUserId;
67
68 $isAdmin = Helper::isSiteAdmin($currentUserId);
69
70 if ($isOwn || $isAdmin) {
71 $enableUserSync = Utility::getPrivacySetting('enable_user_sync') === 'yes';
72 $nameArray = explode(' ', trim($xprofile->display_name));
73 $xprofileLastName = array_pop($nameArray);
74 $xprofileFirstName = implode(' ', $nameArray);
75
76 $profile['email'] = $user->user_email;
77 $profile['first_name'] = $enableUserSync ? $user->first_name : $xprofileFirstName;
78 $profile['last_name'] = $enableUserSync ? $user->last_name : $xprofileLastName;
79 $profile['short_description'] = $xprofile->short_description;
80 $profile['can_change_username'] = $isAdmin || Utility::getPrivacySetting('can_customize_username') === 'yes';
81 $profile['can_change_email'] = current_user_can('edit_users') || (Utility::getPrivacySetting('can_change_email') === 'yes' && $isOwn);
82 }
83
84 $profileBaseUrl = Helper::baseUrl('u/' . $xprofile->username . '/');
85
86 $profile['profile_navs'] = [
87 [
88 'slug' => 'user_profile',
89 'title' => __('About', 'fluent-community'),
90 'url' => $profileBaseUrl,
91 'wrapper_class' => 'fcom_profile_about',
92 'route' => [
93 'name' => 'user_profile'
94 ]
95 ],
96 [
97 'slug' => 'user_profile_feeds',
98 'title' => __('Posts', 'fluent-community'),
99 'wrapper_class' => 'fcom_profile_posts',
100 'url' => $profileBaseUrl . 'posts',
101 'route' => [
102 'name' => 'user_profile_feeds'
103 ]
104 ]
105 ];
106
107 if ($profile['canViewUserSpaces']) {
108 $profile['profile_navs'][] = [
109 'slug' => 'user_spaces',
110 'wrapper_class' => 'fcom_profile_spaces',
111 'title' => __('Spaces', 'fluent-community'),
112 'url' => $profileBaseUrl . 'spaces',
113 'route' => [
114 'name' => 'user_spaces'
115 ]
116 ];
117 }
118
119 $profile['profile_navs'][] = [
120 'slug' => 'user_comments',
121 'wrapper_class' => 'fcom_profile_comments',
122 'title' => __('Comments', 'fluent-community'),
123 'url' => $profileBaseUrl . 'comments',
124 'route' => [
125 'name' => 'user_comments'
126 ]
127 ];
128
129 $profile['profile_nav_actions'] = [];
130
131 $profile = apply_filters('fluent_community/profile_view_data', $profile, $xprofile);
132
133 return [
134 'profile' => $profile
135 ];
136 }
137
138 public function patchProfile(Request $request, $userName)
139 {
140 $xprofile = $this->verfifyAndGetProfile($userName);
141
142 $updateData = $request->get('data', []);
143
144 if (!empty($updateData['status']) && $updateData['status'] === 'deactivated' && $xprofile->status === 'active') {
145 // handle deactivation
146 $canDeactivate = Utility::getPrivacySetting('can_deactive_account') === 'yes' || Helper::isSiteAdmin();
147 if (!$canDeactivate) {
148 return $this->sendError([
149 'message' => __('You are not allowed to deactivate this account.', 'fluent-community')
150 ]);
151 }
152
153 $xprofile->status = '';
154 $xprofile->save();
155 update_user_meta($xprofile->user_id, '_fcom_deactivated_at', current_time('mysql'));
156 do_action('fluent_community/profile_deactivated', $xprofile);
157
158 return [
159 'message' => __('Your profile has been deactivated successfully.', 'fluent-community')
160 ];
161 }
162
163 $mediaTypes = ['cover_photo', 'avatar'];
164
165 foreach ($mediaTypes as $type) {
166 if (!empty($updateData[$type])) {
167 $media = Helper::getMediaFromUrl($updateData[$type]);
168 if (!$media || $media->is_active) {
169 return $this->sendError([
170 'message' => __('Invalid media image. Please upload a new one.', 'fluent-community')
171 ]);
172 }
173
174 $updateData[$type] = $media->public_url;
175
176 $media->update([
177 'is_active' => true,
178 'user_id' => $xprofile->user_id,
179 'object_source' => 'user_' . $type
180 ]);
181 }
182 }
183
184 $deletedMedias = [];
185
186 if (!empty($updateData['avatar'])) {
187
188 $deletedMedias[] = $xprofile->avatar;
189
190 $xprofile->avatar = $updateData['avatar'];
191
192 if (defined('FLUENTCRM')) {
193 $contact = $xprofile->contact;
194
195 if ($contact) {
196 $contact->update([
197 'avatar' => $updateData['avatar']
198 ]);
199 }
200 }
201
202 }
203
204 if (isset($updateData['cover_photo'])) {
205 $deletedMedias[] = Arr::get($xprofile->meta, 'cover_photo');
206 $xprofile->meta = wp_parse_args(['cover_photo' => $updateData['cover_photo']], $xprofile->meta);
207 }
208
209 $xprofile->save();
210
211 if ($deletedMedias = array_filter($deletedMedias)) {
212 do_action('fluent_community/remove_medias_by_url', $deletedMedias, [
213 'user_id' => $xprofile->user_id,
214 'object_sources' => ['user_avatar', 'user_cover_photo']
215 ]);
216 }
217
218 return [
219 'message' => __('Profile updated', 'fluent-community')
220 ];
221 }
222
223 public function updateProfile(Request $request, $userName)
224 {
225 $currentUser = $this->getUser(true);
226 $data = $request->get('data', []);
227
228 $xProfile = XProfile::where('username', $userName)->firstOrFail();
229
230 if ($xProfile->user_id != get_current_user_id()) {
231 if(!$currentUser->isCommunityModerator()) {
232 return $this->sendError([
233 'message' => __('You are not allowed to update this profile', 'fluent-community')
234 ]);
235 }
236 }
237
238 $this->validate($data, [
239 'first_name' => 'required',
240 ], [
241 'first_name.required' => __('First name is required', 'fluent-community')
242 ]);
243
244 $updateData = Arr::only($data, ['first_name', 'last_name', 'short_description', 'website']);
245
246 $updateData = apply_filters('fluent_community/update_profile_data', $updateData, $data, $xProfile);
247
248 $currentUser = User::findOrFail(get_current_user_id());
249 $meta = $xProfile->meta;
250
251 $userNameChanged = false;
252
253 if ($currentUser->isCommunityModerator()) {
254 $updateData['is_verified'] = Arr::get($data, 'is_verified') ? 1 : 0;
255 $updateData['status'] = Arr::get($data, 'status', 'active');
256 $userName = Arr::get($data, 'username');
257
258 if (user_can($xProfile->user_id, 'list_users')) {
259 $updateData['status'] = 'active';
260 }
261
262 if ($userName) {
263 // Check if username is exit or not
264 $userName = CustomSanitizer::sanitizeUserName($userName);
265
266 if (!$userName) {
267 return $this->sendError([
268 'message' => __('Invalid username. Only Latin characters with _ & - are allowed.', 'fluent-community')
269 ]);
270 }
271
272 if (XProfile::where('username', $userName)->where('user_id', '!=', $xProfile->user_id)->exists()) {
273 return $this->sendError([
274 'message' => __('Community Username already taken by someone else', 'fluent-community')
275 ]);
276 }
277
278 $userExist = get_user_by('user_login', $userName);
279
280 if ($userExist && $userExist->ID != $xProfile->user_id) {
281 return $this->sendError([
282 'message' => __('Username already taken by someone else. Please use a different username.', 'fluent-community')
283 ]);
284 }
285
286 $updateData['username'] = $userName;
287 $userNameChanged = $userName != $xProfile->username;
288 }
289
290 if (Helper::isFeatureEnabled('user_badge')) {
291 $badgeSlug = (array)Arr::get($data, 'badge_slugs', []);
292 $meta['badge_slug'] = $badgeSlug;
293 }
294 } else if (Utility::getPrivacySetting('can_customize_username')) {
295 $userName = Arr::get($data, 'username');
296
297 if ($xProfile->username != $userName) {
298 $userName = strtolower(CustomSanitizer::sanitizeUserName($userName));
299 if (!$userName) {
300 return $this->sendError([
301 'message' => __('Invalid username. Only Latin characters with _ & - are allowed.', 'fluent-community')
302 ]);
303 }
304
305 if (XProfile::where('username', $userName)->where('user_id', '!=', $xProfile->user_id)->exists()) {
306 return $this->sendError([
307 'message' => __('Community Username already taken by someone else', 'fluent-community')
308 ]);
309 }
310
311 if (strlen($userName) < 3) {
312 return $this->sendError([
313 'message' => __('Username should be at least 3 characters long.', 'fluent-community')
314 ]);
315 }
316
317 $reservedUserNames = ProfileHelper::getReservedUserNames();
318 if (in_array($userName, $reservedUserNames)) {
319 return $this->sendError([
320 'message' => __('Please use another username. This username is reserved', 'fluent-community')
321 ]);
322 }
323
324 $updateData['username'] = $userName;
325 $userNameChanged = true;
326 }
327 }
328
329 $updateData['display_name'] = trim(sanitize_text_field(Arr::get($data, 'first_name') . ' ' . Arr::get($data, 'last_name')));
330
331 $updateData['short_description'] = CustomSanitizer::unslashMarkdown(sanitize_textarea_field(trim(Arr::get($data, 'short_description'))));
332 $meta['website'] = sanitize_url(Arr::get($data, 'website'));
333 $socialLinks = Arr::get($data, 'social_links', []);
334
335 $maxDescriptionLength = apply_filters('fluent_community/max_profile_description_length', 5000);
336 if ($updateData['short_description'] && strlen($updateData['short_description']) > $maxDescriptionLength) {
337 return $this->sendError([
338 'message' => sprintf(
339 /* translators: %d: Maximum number of characters allowed in the profile bio. */
340 __('Profile bio should not exceed %d characters.', 'fluent-community'),
341 $maxDescriptionLength
342 )
343 ]);
344 }
345
346 if ($socialLinks) {
347 $socialLinks = array_filter($socialLinks);
348 $formattedSocialLinkes = [];
349 $socialLinkProviders = ProfileHelper::socialLinkProviders(true);
350 foreach ($socialLinks as $linkName => $socialLink) {
351 if (isset($socialLinkProviders[$linkName])) {
352 $formattedSocialLinkes[$linkName] = sanitize_text_field(trim($socialLink));
353 }
354 }
355 $meta['social_links'] = $formattedSocialLinkes;
356 }
357
358 $meta['short_description_rendered'] = wp_kses_post(FeedsHelper::mdToHtml($updateData['short_description']));
359
360 $updateData['meta'] = $meta;
361
362 $xProfile->fill($updateData);
363 $xProfile->save();
364
365 // Let's update the user's details
366 $xProfile->user->updateCustomData($updateData);
367 $xProfile->compilation_score = $xProfile->getCompletionScore();
368
369 if ($userNameChanged) {
370 return [
371 'message' => __('Profile has been updated', 'fluent-community'),
372 'profile' => $xProfile,
373 'redirect_url' => Helper::baseUrl('u/' . $xProfile->username . '/update')
374 ];
375 }
376
377 $isOwn = $xProfile->user_id == get_current_user_id();
378 $canEditUsers = current_user_can('edit_users');
379 if ($canEditUsers || (Utility::getPrivacySetting('can_change_email') === 'yes' && $isOwn)) {
380 $emailAddress = Arr::get($data, 'email');
381
382 if ($emailAddress && is_email($emailAddress) && $emailAddress != $xProfile->user->user_email) {
383 $owner_id = email_exists($emailAddress);
384 if ($owner_id && $owner_id != $xProfile->user_id) {
385 return $this->sendError([
386 'message' => __('Email address already taken by someone else. Please use a different email address.', 'fluent-community')
387 ]);
388 }
389
390 // Let's check if it's their own
391 $requireVerification = $isOwn && !$canEditUsers;
392 if ($requireVerification) {
393 $currentUser = get_user_by('ID', $xProfile->user_id);
394 ProfileHelper::sendConfirmationOnProfileEmailChange($currentUser, $emailAddress);
395 return [
396 'message' => __('Email address change is pending. Please check your inbox to verify the new email address.', 'fluent-community'),
397 'profile' => $xProfile
398 ];
399 }
400
401 wp_update_user([
402 'user_email' => $emailAddress,
403 'ID' => $xProfile->user_id
404 ]);
405 }
406 }
407
408 return [
409 'message' => __('Profile has been updated', 'fluent-community'),
410 'profile' => $xProfile
411 ];
412 }
413
414 public function getAllMemberships(Request $request, $userName)
415 {
416 $xProfile = XProfile::where('username', $userName)->firstOrFail();
417
418 $currentUser = $this->getUser();
419
420 if (!ProfileHelper::canViewUserSpaces($xProfile->user_id, $currentUser)) {
421 return $this->sendError([
422 'message' => __('You are not allowed to view this profile\'s membership.', 'fluent-community'),
423 'permission_failed' => true
424 ]);
425 }
426
427 $memberships = $xProfile->space_pivot()
428 ->where('status', 'active')
429 ->pluck('space_id');
430
431 return apply_filters('fluent_community/profile_all_memberships_api_response', [
432 'memberships' => $memberships
433 ], $request->all());
434 }
435
436 public function getSpaces(Request $request, $userName)
437 {
438 $xProfile = XProfile::where('username', $userName)->firstOrFail();
439 $currentUser = $this->getUser();
440
441 if (!ProfileHelper::canViewUserSpaces($xProfile->user_id, $currentUser)) {
442 return $this->sendError([
443 'message' => __('You are not allowed to view this profile\'s spaces.', 'fluent-community'),
444 'permission_failed' => true
445 ]);
446 }
447
448 if ($xProfile->user_id == get_current_user_id() || ($currentUser && $currentUser->isCommunityModerator())) {
449 $spaces = $xProfile->spaces()
450 ->wherePivot('status', 'active')
451 ->get();
452 } else {
453 $spaces = $xProfile->spaces()
454 ->whereIn('privacy', ['public', 'private'])
455 ->wherePivot('status', 'active')
456 ->get();
457 }
458
459 foreach ($spaces as $space) {
460 $shouldHideMembersCount = Arr::get($space->settings, 'hide_members_count') == 'yes';
461 $canViewMembers = $currentUser && $space->verifyUserPermisson($currentUser, 'can_view_members', false);
462 if ($shouldHideMembersCount && !$canViewMembers) {
463 $space->members_count = 0;
464 continue;
465 }
466 $space->members_count = $space->members()->count();
467 }
468
469 $data = [
470 'spaces' => $spaces
471 ];
472
473 return apply_filters('fluent_community/profile_spaces_api_response', $data, $request->all());
474 }
475
476 public function getComments(Request $request, $userName)
477 {
478 $xProfile = XProfile::where('username', $userName)->first();
479
480 if (!$xProfile) {
481 return $this->sendError([
482 'message' => __('Profile not found', 'fluent-community')
483 ]);
484 }
485
486 $currentUser = $this->getUser();
487 $hasAllAccess = $xProfile->user_id == get_current_user_id() || ($currentUser && $currentUser->isCommunityModerator());
488
489 $comments = Comment::where('user_id', $xProfile->user_id)
490 ->where('status', 'published')
491 ->with([
492 'post' => function ($q) {
493 $q->select(['id', 'title', 'message', 'type', 'space_id', 'slug', 'created_at'])
494 ->with([
495 'space' => function ($q) {
496 $q->select(['id', 'title', 'slug', 'type']);
497 }
498 ]);
499 }
500 ])
501 ->when(!$hasAllAccess, function ($q) {
502 $q->whereHas('post', function ($query) {
503 $query->byUserAccess(get_current_user_id());
504 $query->where('type', 'text');
505 });
506 })
507 ->orderBy('id', 'desc')
508 ->paginate();
509
510 $data = [
511 'comments' => $comments,
512 'xprofile' => $xProfile
513 ];
514
515 return apply_filters('fluent_community/profile_comments_api_response', $data, $request->all());
516 }
517
518 public function getNotificationPreferance(Request $request, $userName)
519 {
520 $emailPref = Utility::getEmailNotificationSettings();
521
522 $xProfile = $this->verfifyAndGetProfile($userName);
523
524 $globalPreferances = NotificationPref::getGlobalPrefs();
525
526 $userPrefs = NotificationSubscription::where('user_id', $xProfile->user_id)
527 ->select(['notification_type', 'is_read', 'object_id'])
528 ->get();
529
530 $userGlobalPrefs = [];
531 $spaceWisePrefs = [];
532 foreach ($userPrefs as $pref) {
533 if (!$pref->object_id) {
534 if ($pref->notification_type === 'message_email_frequency') {
535 $maps = [
536 0 => 'disabled',
537 1 => 'hourly',
538 2 => 'daily',
539 3 => 'weekly'
540 ];
541
542 if ($maps[$pref->is_read]) {
543 $userGlobalPrefs[$pref->notification_type] = $maps[$pref->is_read];
544 } else {
545 $userGlobalPrefs[$pref->notification_type] = 'default';
546 }
547 continue;
548 }
549 $userGlobalPrefs[$pref->notification_type] = $pref->is_read ? 'yes' : 'no';
550 } else {
551 if (empty($spaceWisePrefs[$pref->object_id])) {
552 $spaceWisePrefs[$pref->object_id] = [];
553 }
554 $spaceWisePrefs[$pref->object_id][$pref->notification_type] = $pref->is_read;
555 }
556 }
557
558 $messagingConfig = Utility::getOption('_messaging_settings', []);
559 $isGlobalPerUser = Arr::get($messagingConfig, 'messaging_email_frequency') == 'disabled';
560
561 $userGlobalPrefsDefaults = [
562 'digest_mail' => Arr::get($globalPreferances, 'digest_email_status') ? 'yes' : 'no',
563 'mention_mail' => Arr::get($globalPreferances, 'mention_mail') ? 'yes' : 'no',
564 'reply_my_com_mail' => Arr::get($globalPreferances, 'reply_my_com_mail') ? 'yes' : 'no',
565 'com_my_post_mail' => Arr::get($globalPreferances, 'com_my_post_mail') ? 'yes' : 'no',
566 'message_email_frequency' => $isGlobalPerUser ? 'disabled' : 'default'
567 ];
568
569 $userGlobalPrefs = wp_parse_args($userGlobalPrefs, $userGlobalPrefsDefaults);
570
571 $spaceGroups = SpaceGroup::with(['spaces' => function ($query) {
572 $query->whereHas('members', function ($q) {
573 $q->where('user_id', get_current_user_id())
574 ->where('status', 'active');
575 })
576 ->where('type', 'community');
577 }])
578 ->orderBy('serial', 'ASC')
579 ->get();
580
581 $formattedSpaceGroups = [];
582 foreach ($spaceGroups as $group) {
583 if ($group->spaces->isEmpty()) {
584 continue;
585 }
586 $formattedSpaces = [];
587 foreach ($group->spaces as $space) {
588
589 $pref = '';
590 if (isset($spaceWisePrefs[$space->id])) {
591 $perfs = (array)$spaceWisePrefs[$space->id];
592 if (!empty($perfs['np_by_member_mail'])) {
593 $pref = 'all_member_posts';
594 } else if (!empty($perfs['np_by_admin_mail'])) {
595 $pref = 'admin_only_posts';
596 }
597 }
598
599 $formattedSpaces[] = [
600 'id' => $space->id,
601 'title' => $space->title,
602 'icon' => $space->getIconMark(),
603 'pref' => $pref
604 ];
605 }
606 if ($formattedSpaces) {
607 $formattedSpaceGroups[] = [
608 'id' => $group->id,
609 'title' => $group->title,
610 'spaces' => $formattedSpaces
611 ];
612 }
613 }
614
615 // let's find the other spaces
616 $otherSpaces = Space::whereHas('members', function ($q) use ($xProfile) {
617 $q->where('user_id', $xProfile->user_id);
618 })
619 ->whereNull('parent_id')
620 ->orderBy('title', 'ASC')
621 ->get();
622
623 if (!$otherSpaces->isEmpty()) {
624 $formattedSpaces = [];
625 foreach ($otherSpaces as $space) {
626 $pref = '';
627 if (isset($spaceWisePrefs[$space->id])) {
628 $perfs = (array)$spaceWisePrefs[$space->id];
629 if (!empty($perfs['np_by_member_mail'])) {
630 $pref = 'all_member_posts';
631 } else if (!empty($perfs['np_by_admin_mail'])) {
632 $pref = 'admin_only_posts';
633 }
634 }
635
636 $formattedSpaces[] = [
637 'id' => $space->id,
638 'title' => $space->title,
639 'icon' => $space->getIconMark(),
640 'pref' => $pref
641 ];
642 }
643
644 $formattedSpaceGroups[] = [
645 'id' => 'other_space_group',
646 'title' => __('Other Spaces', 'fluent-community'),
647 'spaces' => $formattedSpaces
648 ];
649 }
650
651 $digestDay = (string)Arr::get($emailPref, 'digest_mail_day', 'tue');
652 if ($digestDay) {
653 $maps = [
654 'mon' => __('Monday', 'fluent-community'),
655 'tue' => __('Tuesday', 'fluent-community'),
656 'wed' => __('Wednesday', 'fluent-community'),
657 'thu' => __('Thursday', 'fluent-community'),
658 'fri' => __('Friday', 'fluent-community'),
659 'sat' => __('Saturday', 'fluent-community'),
660 'sun' => __('Sunday', 'fluent-community'),
661 ];
662 if (isset($maps[$digestDay])) {
663 $digestDay = $maps[$digestDay];
664 }
665 }
666
667 $data = [
668 'user_globals' => (object)$userGlobalPrefs,
669 'spaceGroups' => $formattedSpaceGroups,
670 'space_prefs' => $spaceWisePrefs,
671 'digestEmailDay' => $digestDay,
672 'default_messaging_email_frequency' => Arr::get($messagingConfig, 'messaging_email_status') !== 'yes' ? 'no' : Arr::get($messagingConfig, 'messaging_email_frequency'),
673 ];
674
675 return apply_filters('fluent_community/profile_notification_pref_api_response', $data, $request->all());
676 }
677
678 public function saveNotificationPreferance(Request $request, $userName)
679 {
680 $xProfile = $this->verfifyAndGetProfile($userName);
681
682 $userPrefs = $request->get('user_globals', []);
683 $sapcePrefs = $request->get('space_prefs', []);
684
685 $messagingPref = Arr::get($userPrefs, 'message_email_frequency');
686
687 $userPrefs = array_map(function ($item) {
688 return $item == 'yes' ? 1 : 0;
689 }, $userPrefs);
690
691 if ($messagingPref == 'hourly') {
692 $userPrefs['message_email_frequency'] = 1;
693 } else if ($messagingPref == 'daily') {
694 $userPrefs['message_email_frequency'] = 2;
695 } else if ($messagingPref == 'disabled') {
696 $userPrefs['message_email_frequency'] = 0;
697 } else if ($messagingPref == 'weekly') {
698 $userPrefs['message_email_frequency'] = 3;
699 } else {
700 unset($userPrefs['message_email_frequency']);
701 }
702
703 foreach ($sapcePrefs as $spaceId => $pref) {
704 $spaceId = (int)$spaceId;
705 if (!$pref || !$spaceId) {
706 continue;
707 }
708
709 if ($pref == 'all_member_posts') {
710 $userPrefs['np_by_member_mail_' . $spaceId] = 1;
711 $userPrefs['np_by_admin_mail_' . $spaceId] = 1;
712 } else if ($pref == 'admin_only_posts') {
713 $userPrefs['np_by_admin_mail_' . $spaceId] = 1;
714 }
715 }
716
717 NotificationPref::updateUserPrefs($xProfile->user_id, $userPrefs);
718
719 return [
720 'prefs' => $userPrefs,
721 'message' => __('Email Notification preferences have been updated', 'fluent-community')
722 ];
723 }
724
725 private function verfifyAndGetProfile($userName)
726 {
727 $xProfile = XProfile::where('username', $userName)->firstOrFail();
728
729 $currentUser = $this->getUser();
730 if ($xProfile->user_id != get_current_user_id() && (!$currentUser || !$currentUser->isCommunityModerator())) {
731 throw new \Exception('You are not allowed to update this profile');
732 }
733
734 return $xProfile;
735 }
736 }
737