PluginProbe
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses / 2.6.01
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses v2.6.01
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 1.1.0 All 77 releases
fluent-community / app / Http / Controllers / ProfileController.php

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

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