PluginProbe
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses / 1.0.97
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses v1.0.97
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 / Services / Helper.php

Helper.php in FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses 1.0.97, at app/Services/Helper.php

1,705 lines 61.2 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\Services;
4
5 use FluentCommunity\App\App;
6 use FluentCommunity\App\Functions\Utility;
7 use FluentCommunity\App\Hooks\Handlers\ActivationHandler;
8 use FluentCommunity\App\Models\BaseSpace;
9 use FluentCommunity\App\Models\Space;
10 use FluentCommunity\App\Models\Media;
11 use FluentCommunity\App\Models\Meta;
12 use FluentCommunity\App\Models\SpaceUserPivot;
13 use FluentCommunity\App\Models\User;
14 use FluentCommunity\App\Models\XProfile;
15 use FluentCommunity\Framework\Support\Arr;
16 use FluentCommunity\App\Models\SpaceGroup;
17
18 /**
19 * Helper class for various utility functions.
20 */
21 class Helper
22 {
23
24 public static function isRtl()
25 {
26 return apply_filters('fluent_community/is_rtl', is_rtl());
27 }
28
29 /**
30 * Get the portal slug.
31 *
32 * @return string The portal slug.
33 */
34 /**
35 * Get the portal slug.
36 *
37 * @return string The portal slug.
38 */
39 public static function getPortalSlug($forRoute = false)
40 {
41 $settings = get_option('fluent_community_settings', []);
42 if (isset($settings['slug'])) {
43 $slug = $settings['slug'];
44 } else {
45 $slug = 'portal';
46 }
47
48 if (defined('FLUENT_COMMUNITY_PORTAL_SLUG')) {
49 $slug = \FLUENT_COMMUNITY_PORTAL_SLUG;
50 }
51
52 $slug = apply_filters('fluent_community/portal_slug', $slug);
53
54 if (!$forRoute) {
55 return $slug;
56 }
57
58 $siteUrl = get_site_url();
59
60 $poralUrl = self::baseUrl('/');
61
62 // get the url without path
63 $siteUrl = str_replace(parse_url($siteUrl, PHP_URL_PATH), '', $siteUrl);
64
65 $slug = str_replace($siteUrl, '', $poralUrl);
66
67 // remove the first and last slashes
68 return trim($slug, '/');
69 }
70
71 /**
72 * Get the portal route type.
73 *
74 * @return string The portal route type.
75 */
76 public static function getPortalRouteType()
77 {
78 return apply_filters('fluent_community/portal_route_type', 'WebHistory');
79 }
80
81 /**
82 * Check if the portal is headless.
83 *
84 * @return bool True if headless, false otherwise.
85 */
86 public static function isHeadless()
87 {
88 return apply_filters('fluent_community/portal_page_headless', false);
89 }
90
91 /**
92 * Check if the portal has a color scheme.
93 *
94 * @return bool True if has color scheme, false otherwise.
95 */
96 public static function hasColorScheme()
97 {
98 $status = Utility::isCustomizationEnabled('dark_mode');
99 return apply_filters('fluent_community/has_color_scheme', $status);
100 }
101
102 /**
103 * Check if the user is a site admin.
104 *
105 * @param int|null $userId The user ID to check. If null, checks the current user.
106 * @return bool True if the user is a site admin, false otherwise.
107 */
108 public static function isSiteAdmin($userId = null)
109 {
110 $capability = apply_filters('fluent_community/super_admin_capability', 'manage_options');
111
112 if (!$capability) {
113 return false;
114 }
115
116 if ($userId === null) {
117 $userId = get_current_user_id();
118 }
119
120 if (!$userId) {
121 return false;
122 }
123
124 return user_can($userId, $capability);
125 }
126
127 public static function isModerator($user = null)
128 {
129 if (!$user) {
130 $user = self::getCurrentUser();
131 }
132 return $user && $user->isCommunityModerator();
133 }
134
135 /**
136 * Get the URL for an asset file.
137 *
138 * @param string $file The file name.
139 * @return string The full URL to the asset.
140 */
141 public static function assetUrl($file = '')
142 {
143 return FLUENT_COMMUNITY_PLUGIN_URL . 'assets/' . $file;
144 }
145
146 /**
147 * Get the base URL for the portal.
148 *
149 * @param string $path The path to append to the base URL.
150 * @return string The full base URL.
151 */
152 public static function baseUrl($path = '')
153 {
154 $baseUrl = apply_filters('fluent_community/base_url', home_url(self::getPortalSlug()));
155 $baseUrl = rtrim($baseUrl, '/');
156
157 if (self::getPortalRouteType() != 'hash') {
158 return $baseUrl . '/' . ltrim($path, '/');
159 }
160
161 if (!$path) {
162 return $baseUrl . '/';
163 }
164
165 return $baseUrl . '/#/' . ltrim($path, '/');
166 }
167
168 public static function getAuthUrl()
169 {
170 $settings = self::generalSettings();
171
172 return Arr::get($settings, 'cutsom_auth_url', '');
173 }
174
175 /**
176 * Get the space IDs for a user.
177 *
178 * @param int|null $userId The user ID. If null, uses the current user.
179 * @return array An array of space IDs.
180 */
181 public static function getUserSpaceIds($userId = null)
182 {
183 if (!$userId) {
184 $userId = get_current_user_id();
185 }
186
187 return SpaceUserPivot::where('user_id', $userId)
188 ->where('status', 'active')
189 ->pluck('space_id')
190 ->toArray();
191 }
192
193 public static function getUserSpaces($userId = null)
194 {
195 if (!$userId) {
196 $userId = get_current_user_id();
197 }
198
199 return Space::whereHas('members', function ($query) use ($userId) {
200 $query->where('user_id', $userId);
201 })->get();
202 }
203
204 /**
205 * Check if a user is in a specific space.
206 *
207 * @param int $userId The user ID.
208 * @param int $spaceId The space ID.
209 * @return bool True if the user is in the space, false otherwise.
210 */
211 public static function isUserInSpace($userId, $spaceId)
212 {
213 return SpaceUserPivot::where('user_id', $userId)
214 ->where('space_id', $spaceId)
215 ->where('status', 'active')
216 ->exists();
217 }
218
219 /**
220 * Generate HTML attributes from an array.
221 *
222 * @param array $atts An array of attribute key-value pairs.
223 * @return string The generated HTML attributes string.
224 */
225 public static function attrs($atts = [])
226 {
227 $text = '';
228
229 foreach ($atts as $key => $value) {
230 $text .= "$key=\"$value\" ";
231 }
232
233 return $text;
234 }
235
236 /**
237 * Get media from a URL.
238 *
239 * @param string|array $url The URL or an array containing URL information.
240 * @return Media|null The Media object if found, null otherwise.
241 */
242 public static function getMediaFromUrl($url)
243 {
244 if (is_array($url) && isset($url['provider'])) {
245 $provider = Arr::get($url, 'provider');
246
247 if ($provider == 'giphy') {
248 return null;
249 }
250
251 $url = Arr::get($url, 'url');
252 }
253
254 if (!$url) {
255 return null;
256 }
257
258 $parsedUrl = wp_parse_url($url, PHP_URL_QUERY);
259
260 if (!$parsedUrl) {
261 return null;
262 }
263
264 // Parse the query string to get the media_key value
265 parse_str($parsedUrl, $queryParams);
266
267 $key = Arr::get($queryParams, 'media_key');
268
269 if (!$key) {
270 return null;
271 }
272
273 return Media::where('media_key', $key)->first();
274 }
275
276 /**
277 * Get media items from multiple URLs.
278 *
279 * @param array $urls An array of URLs.
280 * @return array An array of Media objects.
281 */
282 public static function getMediaItemsFromUrl($urls)
283 {
284 $mediaItems = [];
285
286 foreach ($urls as $url) {
287 $media = self::getMediaFromUrl($url);
288
289 if ($media) {
290 $mediaItems[] = $media;
291 }
292 }
293
294 return $mediaItems;
295 }
296
297 /**
298 * Get general settings for the community.
299 *
300 * @param bool $cached Whether to use cached settings.
301 * @return array The general settings.
302 */
303 public static function generalSettings($cached = true)
304 {
305 static $settings = null;
306
307 if ($cached && $settings) {
308 return $settings;
309 }
310
311 $settings = get_option('fluent_community_settings', []);
312
313 $defaults = [
314 'site_title' => get_bloginfo('name'),
315 'slug' => 'portal',
316 'logo' => '',
317 'white_logo' => '',
318 'featured_image' => '',
319 'access' => [
320 'acess_level' => 'logged_in', // logged_in, public, role_based
321 'access_roles' => []
322 ],
323 'auth_form_type' => 'default',
324 'disable_global_posts' => 'yes',
325 'auth_content' => 'Please login first to access this page',
326 'auth_redirect' => '',
327 'restricted_role_content' => 'Sorry, you can not access to this page. Only authorized users can access this page.',
328 'auth_url' => '',
329 'cutsom_auth_url' => self::baseUrl('?fcom_action=auth'),
330 ];
331
332 $settings = wp_parse_args($settings, $defaults);
333 if ($settings['auth_form_type'] != 'custom' || empty($settings['auth_form_type'])) {
334 $settings['cutsom_auth_url'] = self::baseUrl('?fcom_action=auth');
335 }
336
337 if (defined('FLUENT_COMMUNITY_PORTAL_SLUG')) {
338 $settings['slug'] = \FLUENT_COMMUNITY_PORTAL_SLUG;
339 $settings['is_slug_defined'] = true;
340 } else {
341 unset($settings['is_slug_defined']);
342 }
343
344 return $settings;
345 }
346
347 public static function hasGlobalPost()
348 {
349 $settings = self::generalSettings();
350 $status = Arr::get($settings, 'disable_global_posts', '') != 'yes';
351
352 return apply_filters('fluent_community/has_global_post', $status);
353 }
354
355 /**
356 * Check if a user can access the portal.
357 *
358 * @param int|null $userId The user ID. If null, uses the current user.
359 * @return bool True if the user can access the portal, false otherwise.
360 */
361 public static function canAccessPortal($userId = null)
362 {
363 $settings = self::generalSettings();
364 $accessLevel = Arr::get($settings, 'access.acess_level');
365
366 if ($accessLevel == 'public') {
367 return apply_filters('fluent_community/can_access_portal', true);
368 }
369
370 if (!$userId) {
371 $userId = get_current_user_id();
372 }
373
374 if (!$userId) {
375 return apply_filters('fluent_community/can_access_portal', false);
376 }
377
378 if ($accessLevel == 'logged_in') {
379 return apply_filters('fluent_community/can_access_portal', true);
380 }
381
382 if (user_can($userId, 'edit_pages')) {
383 return apply_filters('fluent_community/can_access_portal', true);
384 }
385
386 $roles = Arr::get($settings, 'access.access_roles', []);
387
388 $user = get_user_by('ID', $userId);
389
390 if (!$user) {
391 return apply_filters('fluent_community/can_access_portal', false);
392 }
393
394 $result = !!array_intersect(array_values($user->roles), $roles);
395
396 if (!$result) {
397 return apply_filters('fluent_community/can_access_portal', false);
398 }
399
400 $xProfile = Helper::getCurrentProfile();
401
402 $result = $xProfile && $xProfile->status == 'active';
403
404 return apply_filters('fluent_community/can_access_portal', $result);
405 }
406
407 /**
408 * Get the portal route paths.
409 *
410 * @return array An array of portal route paths.
411 */
412 public static function portalRoutePaths()
413 {
414 return apply_filters('fluent_community/app_route_paths', [
415 'portal_home',
416 'space',
417 'discover',
418 'members',
419 'courses',
420 'u',
421 'leaderboards',
422 'chat',
423 'notifications',
424 'bookmarks',
425 'post',
426 'admin'
427 ]);
428 }
429
430 /**
431 * Get the current user's profile.
432 *
433 * @param bool $cached Whether to use cached profile.
434 * @return XProfile|null The user's profile or null if not found.
435 */
436 public static function getCurrentProfile($cached = true)
437 {
438 $userId = get_current_user_id();
439 if (!$userId) {
440 return null;
441 }
442
443 static $profile;
444
445 if ($profile && $cached) {
446 return $profile;
447 }
448
449 if (!$userId) {
450 return null;
451 }
452
453 $profile = XProfile::where('user_id', $userId)->first();
454
455 return $profile;
456 }
457
458 /**
459 * Get the current user Model.
460 *
461 * @param bool $cached Whether to use cached user.
462 * @return User|false The User model or false if not found.
463 */
464 public static function getCurrentUser($cached = true)
465 {
466 $userId = get_current_user_id();
467 if (!$userId) {
468 return false;
469 }
470
471 static $user;
472 if ($user && $cached) {
473 return $user;
474 }
475
476 $user = User::find($userId);
477
478 return $user;
479 }
480
481 /**
482 * Get the route paths for the community.
483 *
484 * @return array An array of route paths.
485 */
486 private static function getRoutePaths()
487 {
488 return [
489 'dashboard' => '/dashboard',
490 'all_feeds' => '/',
491 'single_feed' => '/post/:feed_slug',
492 'space_feeds' => '/space/:space/home',
493 'space_feed' => '/space/:space/post/:feed_slug',
494 'space_members' => '/space/:space/members',
495 'spaces' => '/discover/spaces',
496 'settings' => '/admin/settings',
497 'admin_moderators' => '/admin/settings/moderators',
498 'all_members' => '/members',
499 'user_profile' => '/u/:username/',
500 'user_communities' => '/u/:username/spaces',
501 'update_profile' => '/u/:username/update',
502 'discussions' => '/discussions',
503 'create_topic' => '/discussions/create-topic',
504 'topic' => '/discussions/topic/:slug',
505 'notifications' => '/notifications',
506 'bookmarks' => '/bookmarks',
507 'courses' => '/courses',
508 'view_course' => '/courses/view/:course_id/lessons',
509 'view_lesson' => '/courses/view/:course_id/lessons/:lesson_slug/view',
510 'manage_courses' => '/admin/manage-courses',
511 'edit_lessons' => '/admin/manage-courses/edit/:course_id/lessons',
512 'course_students' => '/admin/manage-courses/edit/:course_id/students',
513 'course_overview' => '/admin/manage-courses/edit/:course_id/overview',
514 'manage_leaderboard' => '/admin/manage-leaderboard',
515 ];
516 }
517
518 /**
519 * Get the URL for a JavaScript route.
520 *
521 * @param array $route The route information.
522 * @return string The URL for the route.
523 */
524 public static function getUrlByJsRoute($route = [])
525 {
526 $routePaths = self::getRoutePaths();
527
528 $routeName = Arr::get($route, 'name', '');
529
530 if (!$routeName || !isset($routePaths[$routeName])) {
531 return self::baseUrl();
532 }
533
534 $path = $routePaths[$routeName];
535
536 $params = (array)Arr::get($route, 'params', []);
537
538 if (!$params) {
539 return self::baseUrl($path);
540 }
541
542 $replaces = [];
543
544 foreach ($params as $paramKey => $paramValue) {
545 $replaces[':' . $paramKey] = $paramValue;
546 }
547
548 $path = str_replace(array_keys($replaces), array_values($replaces), $path);
549
550 return self::baseUrl($path);
551
552 }
553
554 /**
555 * Get the route name from a request path.
556 *
557 * @param string $path The request path.
558 * @return string|false The route name or false if not found.
559 */
560 public static function getRouteNameByRequestPath($path)
561 {
562 $path = '//' . $path;
563
564 if (strpos($path, '/u/')) {
565 return 'user_profile';
566 }
567
568 if (strpos($path, '/post/')) {
569 return 'feed_view';
570 }
571
572 if (strpos($path, '/lessons/')) {
573 return 'lesson_view';
574 }
575
576 if (strpos($path, '/course/')) {
577 return 'course_view';
578 }
579
580 if (strpos($path, '/space/') && !strpos($path, '/discover/spaces')) {
581 return 'community_view';
582 }
583
584 if (strpos($path, '/admin')) {
585 return 'admin';
586 }
587
588 return false;
589 }
590
591 /**
592 * Get a human-readable excerpt from content.
593 *
594 * @param string $content The content to extract from.
595 * @param int $length The maximum length of the excerpt.
596 * @return string The human-readable excerpt.
597 */
598 public static function getHumanExcerpt($content, $length = 100)
599 {
600 if ($content) {
601 $patterns = [
602 '/^#{1,6}\s+/m' => '',
603 // Bold and Italic: remove '*' and '_' symbols
604 '/(\*\*|__)(.*?)\1/' => '$2',
605 '/(\*|_)(.*?)\1/' => '$2',
606 // Code blocks: remove triple backticks
607 '/^```\s*\w*\s*\n([\s\S]*?)\n```\s*$/m' => '$1',
608 // Inline code: remove single backticks
609 '/`([^`]+)`/' => '$1',
610 // Blockquotes: remove '>' symbol
611 '/^\s*>\s?/m' => '',
612 // Horizontal rules: replace with empty line
613 '/^\s*([-*_])\1{2,}\s*$/m' => "\n",
614 // Links: keep only the link text
615 '/\[([^\]]+)\]\([^\)]+\)/' => '$1',
616 // Images: keep only the alt text
617 '/!\[([^\]]+)\]\([^\)]+\)/' => '$1',
618 // Strikethrough: remove '~~' symbols
619 '/~~(.*?)~~/' => '$1',
620 // Task lists: remove checkbox syntax
621 '/^\s*[-*+]\s+\[[ xX]\]\s+/m' => '',
622 ];
623
624 $content = preg_replace(array_keys($patterns), array_values($patterns), $content);
625
626 // remove all tags
627 $content = wp_strip_all_tags($content);
628 // remove new lines and tabs
629 $content = str_replace(["\r", "\n", "\t"], ' ', $content);
630 // remove multiple spaces
631 $content = preg_replace('/\s+/', ' ', $content);
632
633 // trim
634 $content = trim($content);
635 }
636
637 if (!$content) {
638 return '';
639 }
640
641 if (mb_strlen($content) <= $length) {
642 return $content;
643 }
644
645 // return the first $length chars of the content with ... at the end
646 return mb_substr($content, 0, $length) . '...';
647 }
648
649 /**
650 * Check if the portal is publicly accessible.
651 *
652 * @return bool True if publicly accessible, false otherwise.
653 */
654 public static function isPublicAccessible()
655 {
656 $settings = self::generalSettings();
657 return Arr::get($settings, 'access.acess_level') == 'public';
658 }
659
660 /**
661 * Get media by provider.
662 *
663 * @param array $images The array of images.
664 * @param string $provider The provider to filter by.
665 * @return array The filtered array of images.
666 */
667 public static function getMediaByProvider($images, $provider = 'uploader')
668 {
669 if (is_array($images)) {
670 return array_filter($images, function ($image) use ($provider) {
671 if (is_array($image)) {
672 if (isset($image['provider'])) {
673 return Arr::get($image, 'provider') == $provider;
674 }
675
676 return $provider === 'uploader'; // for existing images when no provider was set.
677 }
678 });
679 }
680
681 return [];
682 }
683
684 /**
685 * Get the community menu groups.
686 *
687 * @param User|null $user The user to get menu groups for.
688 * @return array The community menu groups.
689 */
690 public static function getCommunityMenuGroups($user = null)
691 {
692 if (!$user) {
693 $user = self::getCurrentUser();
694 }
695
696 $communityGroups = self::getAllCommunityGroups($user);
697
698 if ($communityGroups->isEmpty()) {
699 return [];
700 }
701
702 $isMod = $user && $user->isCommunityModerator();
703
704 $formattedGroups = [];
705
706 foreach ($communityGroups as $communityGroup) {
707 $spaces = $communityGroup->spaces;
708 $validSpaces = [];
709 $isShowAll = Arr::get($communityGroup->settings, 'always_show_spaces') === 'yes';
710
711 foreach ($spaces as $space) {
712 if ($isMod) {
713 $validSpaces[] = self::transformSpaceToLink($space);
714 continue;
715 }
716
717 if ($space->privacy === 'secret') {
718 if (!$user || !$space->getMembership($user->ID)) {
719 continue;
720 }
721 $validSpaces[] = self::transformSpaceToLink($space);
722 continue;
723 }
724
725 if ($isShowAll || $space->privacy = 'public') {
726 $validSpace = self::transformSpaceToLink($space);
727
728 if ($space->privacy == 'private') {
729 if (!$user || !$space->getMembership($user->ID)) {
730 $validSpace['show_lock'] = true;
731 }
732 }
733
734 $validSpaces[] = $validSpace;
735 continue;
736 }
737
738 if (!$user || $space->getMembership($user->ID)) {
739 continue;
740 }
741
742 $validSpaces[] = self::transformSpaceToLink($space);
743 }
744
745 if (!$validSpaces && !$isMod) {
746 continue;
747 }
748
749 $formattedGroups[] = [
750 'id' => $communityGroup->id,
751 'title' => $communityGroup->title,
752 'slug' => $communityGroup->slug,
753 'logo' => $communityGroup->logo,
754 'children' => $validSpaces
755 ];
756 }
757
758 return apply_filters('fluent_community/menu_groups_for_user', $formattedGroups, $user);
759 }
760
761 /**
762 * Transform a space to a link array.
763 *
764 * @param Space $space The space to transform.
765 * @return array The transformed space link array.
766 */
767 private static function transformSpaceToLink($space)
768 {
769
770 $logo = $space->logo;
771
772 $title = $space->title;
773
774 if ($space->status == 'draft') {
775 $title = $title . ' ' . __('(Draft)', 'fluent-community');
776 }
777
778 return [
779 'title' => $title,
780 'icon_image' => $logo,
781 'shape_svg' => !$logo ? Arr::get($space->settings, 'shape_svg', '') : '',
782 'emoji' => !$logo ? Arr::get($space->settings, 'emoji', '') : '',
783 'permalink' => $space->getPermalink(),
784 'link_classes' => 'space_menu_item route_url fcom_space_id_' . $space->id . ' fcom_space_' . $space->slug
785 ];
786 }
787
788 public static function isAlreadyOnboarded()
789 {
790 $communitySettings = get_option('fluent_community_settings', []);
791
792 return !empty($communitySettings);
793 }
794
795 /**
796 * Get all community groups.
797 *
798 * @param User $user The user to get groups for.
799 * @param bool $willCreate Whether to create a default group if none exist.
800 * @return \FluentCommunity\Framework\Support\Collection Collection of Groups
801 */
802 public static function getAllCommunityGroups($user, $willCreate = true)
803 {
804 $isModerator = $user && $user->isCommunityModerator();
805
806 $communityGroups = SpaceGroup::query()->orderBy('serial', 'ASC')
807 ->with([
808 'spaces' => function ($query) use ($isModerator) {
809 if ($isModerator) {
810 $query->orderBy('serial', 'ASC');
811 } else {
812 $query->where('status', 'published')
813 ->orderBy('serial', 'ASC');
814 }
815 }
816 ])
817 ->get();
818
819 if ($communityGroups->isEmpty() && $willCreate) {
820 $createdSpace = (new ActivationHandler(App::make()))->maybeCreateDefaultSpaceGroup();
821
822 if ($createdSpace) {
823 Space::where('type', 'community')->update([
824 'parent_id' => $createdSpace->id
825 ]);
826 }
827
828 return self::getAllCommunityGroups($user, false);
829 }
830
831 return $communityGroups;
832 }
833
834 /**
835 * Check if a feature is enabled.
836 *
837 * @param string $feature The feature to check.
838 * @return bool True if the feature is enabled, false otherwise.
839 */
840 public static function isFeatureEnabled($feature)
841 {
842 $features = Utility::getFeaturesConfig();
843
844 return isset($features[$feature]) && $features[$feature] === 'yes';
845 }
846
847 /**
848 * Get the menu items group.
849 *
850 * @param string $context The context for getting menu items.
851 * @return array The menu items group.
852 */
853 public static function getMenuItemsGroup($context = 'view')
854 {
855 static $menuGroups;
856
857 if ($menuGroups && $context === 'view') {
858 return $menuGroups;
859 }
860
861 $menuGroups = Utility::getOption('fluent_community_menu_groups', []);
862
863 $membersPageStatus = Utility::canViewMembersPage() ? 'yes' : 'no';
864
865 $defaultMainMenuItems = [
866 'all_feeds' => [
867 'slug' => 'all_feeds',
868 'title' => __('Feed', 'fluent-community'),
869 'is_system' => 'yes',
870 'is_locked' => 'yes',
871 'enabled' => 'yes',
872 'permalink' => self::baseUrl('/'),
873 'link_classes' => 'fcom_dashboard route_url',
874 'shape_svg' => '<svg width="20" height="18" viewBox="0 0 20 18" fill="none"><path fill-rule="evenodd" clip-rule="evenodd" d="M10 13.166H10.0075H10Z" fill="currentColor"/><path d="M10 13.166H10.0075" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M16.6666 6.08301V10.2497C16.6666 13.3924 16.6666 14.9637 15.6903 15.94C14.714 16.9163 13.1426 16.9163 9.99992 16.9163C6.85722 16.9163 5.28587 16.9163 4.30956 15.94C3.33325 14.9637 3.33325 13.3924 3.33325 10.2497V6.08301" stroke="currentColor" stroke-width="1.5"/><path d="M18.3333 7.74967L14.714 4.27925C12.4918 2.14842 11.3807 1.08301 9.99996 1.08301C8.61925 1.08301 7.50814 2.14842 5.28592 4.27924L1.66663 7.74967" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>'
875 ],
876 'spaces' => [
877 'slug' => 'spaces',
878 'title' => __('Spaces', 'fluent-community'),
879 'is_system' => 'yes',
880 'is_locked' => 'yes',
881 'enabled' => 'yes',
882 'permalink' => self::baseUrl('discover/spaces'),
883 'link_classes' => 'fcom_spaces route_url',
884 'shape_svg' => '<svg version="1.1" viewBox="0 0 128 128" xml:space="preserve"><g><path d="M64,42c-13.2,0-24,10.8-24,24s10.8,24,24,24s24-10.8,24-24S77.2,42,64,42z M64,82c-8.8,0-16-7.2-16-16s7.2-16,16-16 s16,7.2,16,16S72.8,82,64,82z"/><path d="M64,100.8c-14.9,0-29.2,6.2-39.4,17.1l-2.7,2.9l5.8,5.5l2.7-2.9c8.8-9.4,20.7-14.6,33.6-14.6s24.8,5.2,33.6,14.6l2.7,2.9 l5.8-5.5l-2.7-2.9C93.2,107.1,78.9,100.8,64,100.8z"/><path d="M97,47.9v8c9.4,0,18.1,3.8,24.6,10.7l5.8-5.5C119.6,52.7,108.5,47.9,97,47.9z"/><path d="M116.1,20c0-10.5-8.6-19.1-19.1-19.1S77.9,9.5,77.9,20S86.5,39.1,97,39.1S116.1,30.5,116.1,20z M85.9,20 c0-6.1,5-11.1,11.1-11.1s11.1,5,11.1,11.1s-5,11.1-11.1,11.1S85.9,26.1,85.9,20z"/><path d="M31,47.9c-11.5,0-22.6,4.8-30.4,13.2l5.8,5.5c6.4-6.9,15.2-10.7,24.6-10.7V47.9z"/><path d="M50.1,20C50.1,9.5,41.5,0.9,31,0.9S11.9,9.5,11.9,20S20.5,39.1,31,39.1S50.1,30.5,50.1,20z M31,31.1 c-6.1,0-11.1-5-11.1-11.1S24.9,8.9,31,8.9s11.1,5,11.1,11.1S37.1,31.1,31,31.1z"/></g></svg>'
885 ],
886 'all_courses' => [
887 'slug' => 'all_courses',
888 'title' => 'Courses',
889 'link_classes' => 'fcom_courses route_url',
890 'is_system' => 'yes',
891 'is_locked' => 'yes',
892 'enabled' => 'yes',
893 'is_unavailable' => self::isFeatureEnabled('course_module') ? 'no' : 'yes',
894 'permalink' => self::baseUrl('courses'),
895 'shape_svg' => '<svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M10.734 5.84746L14.7114 6.9072M9.88139 9.01146L11.8701 9.54132M9.98031 14.9723L10.7758 15.1843C13.0258 15.7838 14.1508 16.0835 15.037 15.5747C15.9233 15.0659 16.2247 13.9473 16.8276 11.71L17.6802 8.54599C18.2831 6.3087 18.5845 5.19006 18.0728 4.30879C17.5611 3.42752 16.4362 3.12778 14.1862 2.52831L13.3907 2.31636C11.1407 1.71688 10.0157 1.41714 9.12948 1.92594C8.24322 2.43474 7.94178 3.55338 7.3389 5.79067L6.4863 8.95466C5.88342 11.1919 5.58198 12.3106 6.09367 13.1919C6.60536 14.0731 7.73034 14.3729 9.98031 14.9723Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M9.99996 17.4559L9.20634 17.672C6.96165 18.2832 5.83931 18.5889 4.95512 18.0701C4.07093 17.5513 3.7702 16.4107 3.16874 14.1295L2.31814 10.9035C1.71668 8.62232 1.41595 7.48174 1.92643 6.58318C2.36802 5.80591 3.33329 5.83421 4.58329 5.83411" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>'
896 ],
897 'all_members' => [
898 'slug' => 'all_members',
899 'title' => __('Members', 'fluent-community'),
900 'is_system' => 'yes',
901 'is_locked' => 'yes',
902 'is_unavailable' => $membersPageStatus == 'yes' ? 'no' : 'yes',
903 'enabled' => $membersPageStatus,
904 'permalink' => self::baseUrl('members'),
905 'link_classes' => 'fcom_all_members route_url',
906 'shape_svg' => '<svg width="20" height="16" viewBox="0 0 20 16" fill="none"><path d="M17.3116 13C17.936 13 18.4327 12.6071 18.8786 12.0576C19.7915 10.9329 18.2927 10.034 17.721 9.59383C17.1399 9.14635 16.4911 8.89285 15.8332 8.83333M14.9999 7.16667C16.1505 7.16667 17.0832 6.23393 17.0832 5.08333C17.0832 3.93274 16.1505 3 14.9999 3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M2.68822 13C2.0638 13 1.56714 12.6071 1.12121 12.0576C0.208326 10.9329 1.70714 10.034 2.27879 9.59383C2.8599 9.14635 3.50874 8.89285 4.16659 8.83333M4.58325 7.16667C3.43266 7.16667 2.49992 6.23393 2.49992 5.08333C2.49992 3.93274 3.43266 3 4.58325 3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/><path d="M6.73642 10.592C5.88494 11.1185 3.65241 12.1936 5.01217 13.5389C5.6764 14.196 6.41619 14.666 7.34627 14.666H12.6536C13.5837 14.666 14.3234 14.196 14.9877 13.5389C16.3474 12.1936 14.1149 11.1185 13.2634 10.592C11.2667 9.35735 8.73313 9.35735 6.73642 10.592Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M12.9166 4.24967C12.9166 5.86051 11.6107 7.16634 9.99992 7.16634C8.38909 7.16634 7.08325 5.86051 7.08325 4.24967C7.08325 2.63884 8.38909 1.33301 9.99992 1.33301C11.6107 1.33301 12.9166 2.63884 12.9166 4.24967Z" stroke="currentColor" stroke-width="1.5"/></svg>',
907 ],
908 'leaderboard' => [
909 'slug' => 'leaderboard',
910 'is_system' => 'yes',
911 'is_locked' => 'yes',
912 'enabled' => 'yes',
913 'is_unavailable' => self::isFeatureEnabled('leader_board_module') ? 'no' : 'yes',
914 'title' => __('Leaderboard', 'fluent-community'),
915 'link_classes' => 'fcom_leaderboards route_url',
916 'permalink' => self::baseUrl('leaderboards'),
917 'shape_svg' => '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="currentColor"><path d="M160-200h160v-320H160v320Zm240 0h160v-560H400v560Zm240 0h160v-240H640v240ZM80-120v-480h240v-240h320v320h240v400H80Z"/></svg>'
918 ]
919 ];
920
921 $mainItems = Arr::get($menuGroups, 'mainMenuItems', []);
922
923 if ($mainItems && is_array($mainItems)) {
924 if (isset($mainItems['all_communities'])) {
925 $mainItems['spaces'] = $defaultMainMenuItems['spaces'];
926 unset($mainItems['all_communities']);
927 }
928
929 foreach ($mainItems as $index => &$item) {
930 if (empty($item['slug'])) {
931 unset($mainItems[$index]);
932 continue;
933 }
934 $defaultItem = Arr::get($defaultMainMenuItems, $item['slug'], []);
935 if ($defaultItem) {
936 $preservedKeys = ['is_system', 'is_locked', 'is_unavailable', 'slug', 'shape_svg'];
937 foreach ($preservedKeys as $key) {
938 if (isset($defaultItem[$key])) {
939 $item[$key] = Arr::get($defaultItem, $key);
940 }
941 }
942 if (Arr::get($defaultItem, 'is_system') === 'yes') {
943 $item['permalink'] = $defaultItem['permalink'];
944 $item['emoji'] = '';
945 $item['icon_image'] = '';
946 $item['link_classes'] = $defaultItem['link_classes'];
947 }
948 }
949 }
950 } else {
951 $mainItems = $defaultMainMenuItems;
952 }
953
954 $defaultProfileDropDownItems = [
955 'my_spaces' => [
956 'slug' => 'my_spaces',
957 'title' => __('My Spaces', 'fluent-community'),
958 'is_system' => 'yes',
959 'is_locked' => 'yes',
960 'enabled' => 'yes',
961 'permalink' => '#{{user_url}}/spaces',
962 'shape_svg' => '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0.5 16.5C0.5 14.9087 1.13214 13.3826 2.25736 12.2574C3.38258 11.1321 4.9087 10.5 6.5 10.5C8.0913 10.5 9.61742 11.1321 10.7426 12.2574C11.8679 13.3826 12.5 14.9087 12.5 16.5H11C11 15.3065 10.5259 14.1619 9.68198 13.318C8.83807 12.4741 7.69347 12 6.5 12C5.30653 12 4.16193 12.4741 3.31802 13.318C2.47411 14.1619 2 15.3065 2 16.5H0.5ZM6.5 9.75C4.01375 9.75 2 7.73625 2 5.25C2 2.76375 4.01375 0.75 6.5 0.75C8.98625 0.75 11 2.76375 11 5.25C11 7.73625 8.98625 9.75 6.5 9.75ZM6.5 8.25C8.1575 8.25 9.5 6.9075 9.5 5.25C9.5 3.5925 8.1575 2.25 6.5 2.25C4.8425 2.25 3.5 3.5925 3.5 5.25C3.5 6.9075 4.8425 8.25 6.5 8.25ZM12.713 11.0273C13.767 11.5019 14.6615 12.2709 15.2889 13.2418C15.9164 14.2126 16.2501 15.344 16.25 16.5H14.75C14.7502 15.633 14.4999 14.7844 14.0293 14.0562C13.5587 13.328 12.8878 12.7512 12.0972 12.3953L12.7123 11.0273H12.713ZM12.197 2.55975C12.9526 2.87122 13.5987 3.40015 14.0533 4.07942C14.5078 4.75869 14.7503 5.55768 14.75 6.375C14.7503 7.40425 14.3658 8.39642 13.6719 9.15662C12.978 9.91682 12.025 10.3901 11 10.4835V8.97375C11.5557 8.89416 12.0713 8.63851 12.471 8.24434C12.8707 7.85017 13.1335 7.33824 13.2209 6.7837C13.3082 6.22916 13.2155 5.66122 12.9563 5.16327C12.6971 4.66531 12.2851 4.26356 11.7808 4.017L12.197 2.55975Z" fill="currentColor"/></svg>'
963 ],
964 'bookmarks' => [
965 'slug' => 'bookmarks',
966 'title' => __('Bookmarks', 'fluent-community'),
967 'is_system' => 'yes',
968 'is_locked' => 'yes',
969 'enabled' => 'yes',
970 'permalink' => self::baseUrl('bookmarks'),
971 'shape_svg' => '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0.75 0.5H11.25C11.4489 0.5 11.6397 0.579018 11.7803 0.71967C11.921 0.860322 12 1.05109 12 1.25V15.6073C12.0001 15.6743 11.9822 15.7402 11.9482 15.7979C11.9142 15.8557 11.8653 15.9033 11.8066 15.9358C11.7479 15.9683 11.6816 15.9844 11.6146 15.9826C11.5476 15.9807 11.4823 15.9609 11.4255 15.9252L6 12.5225L0.5745 15.9245C0.517776 15.9601 0.452541 15.9799 0.385576 15.9818C0.318612 15.9837 0.252365 15.9676 0.193721 15.9352C0.135078 15.9029 0.0861801 15.8554 0.0521121 15.7977C0.0180441 15.74 4.98531e-05 15.6742 0 15.6073V1.25C0 1.05109 0.0790178 0.860322 0.21967 0.71967C0.360322 0.579018 0.551088 0.5 0.75 0.5ZM10.5 2H1.5V13.574L6 10.7533L10.5 13.574V2Z" fill="currentColor"/></svg>'
972 ],
973 'logout' => [
974 'slug' => 'logout',
975 'title' => __('Logout', 'fluent-community'),
976 'is_system' => 'yes',
977 'is_locked' => 'yes',
978 'enabled' => 'yes',
979 'permalink' => '#{{logout_url}}',
980 'shape_svg' => '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0.75 15.5C0.551088 15.5 0.360322 15.421 0.21967 15.2803C0.0790178 15.1397 0 14.9489 0 14.75V1.25C0 1.05109 0.0790178 0.860322 0.21967 0.71967C0.360322 0.579018 0.551088 0.5 0.75 0.5H11.25C11.4489 0.5 11.6397 0.579018 11.7803 0.71967C11.921 0.860322 12 1.05109 12 1.25V3.5H10.5V2H1.5V14H10.5V12.5H12V14.75C12 14.9489 11.921 15.1397 11.7803 15.2803C11.6397 15.421 11.4489 15.5 11.25 15.5H0.75ZM10.5 11V8.75H5.25V7.25H10.5V5L14.25 8L10.5 11Z" fill="currentColor"/></svg>'
981 ]
982 ];
983
984 $profileDropDownItems = Arr::get($menuGroups, 'profileDropdownItems', []);
985
986 if ($profileDropDownItems && is_array($profileDropDownItems)) {
987
988 unset($profileDropDownItems['profile']);
989
990 foreach ($profileDropDownItems as $index => &$item) {
991 if (empty($item['slug'])) {
992 unset($profileDropDownItems[$index]);
993 continue;
994 }
995 $defaultItem = Arr::get($defaultProfileDropDownItems, $item['slug'], []);
996 if ($defaultItem) {
997 $preservedKeys = ['is_system', 'is_locked', 'is_unavailable', 'slug', 'svg_icon'];
998 foreach ($preservedKeys as $key) {
999 if (isset($defaultItem[$key])) {
1000 $item[$key] = Arr::get($defaultItem, $key);
1001 }
1002 }
1003 if (Arr::get($defaultItem, 'is_system') === 'yes') {
1004 $item['permalink'] = $defaultItem['permalink'];
1005 if (empty($item['shape_svg'])) {
1006 $item['shape_svg'] = $defaultItem['shape_svg'];
1007 }
1008 }
1009 }
1010 }
1011 } else {
1012 $profileDropDownItems = $defaultProfileDropDownItems;
1013 }
1014
1015 $beforeCommunityMenuItems = Arr::get($menuGroups, 'beforeCommunityMenuItems', []);
1016 $afterCommunityMenuGroups = Arr::get($menuGroups, 'afterCommunityLinkGroups', []);
1017
1018 if (!is_array($beforeCommunityMenuItems)) {
1019 $beforeCommunityMenuItems = [];
1020 }
1021
1022 if (!is_array($afterCommunityMenuGroups)) {
1023 $afterCommunityMenuGroups = [];
1024 }
1025
1026 if ($context == 'view') {
1027 $mainItems = array_filter($mainItems, function ($item) {
1028 return Arr::get($item, 'enabled') === 'yes' && Arr::get($item, 'is_unavailable') !== 'yes';
1029 });
1030
1031 $profileDropDownItems = array_filter($profileDropDownItems, function ($item) {
1032 return Arr::get($item, 'enabled') === 'yes' && Arr::get($item, 'is_unavailable') !== 'yes';
1033 });
1034
1035 $beforeCommunityMenuItems = array_filter($beforeCommunityMenuItems, function ($item) {
1036 return Arr::get($item, 'enabled') === 'yes' && Arr::get($item, 'is_unavailable') !== 'yes';
1037 });
1038
1039 $validGroups = [];
1040 foreach ($afterCommunityMenuGroups as $group) {
1041 if (empty($group['items']) || !is_array($group['items'])) {
1042 continue;
1043 }
1044
1045 $group['items'] = array_filter($group['items'], function ($item) {
1046 return Arr::get($item, 'enabled') === 'yes' && Arr::get($item, 'is_unavailable') !== 'yes';
1047 });
1048
1049 if ($group['items']) {
1050 $validGroups[] = $group;
1051 }
1052 }
1053
1054 $afterCommunityMenuGroups = $validGroups;
1055 }
1056
1057 $menuGroups['mainMenuItems'] = $mainItems;
1058 $menuGroups['profileDropdownItems'] = $profileDropDownItems;
1059 $menuGroups['beforeCommunityMenuItems'] = $beforeCommunityMenuItems;
1060 $menuGroups['afterCommunityLinkGroups'] = $afterCommunityMenuGroups;
1061
1062 if ($context == 'view') {
1063 $menuGroups = apply_filters('fluent_community/menu_groups', $menuGroups);
1064 }
1065
1066 return $menuGroups;
1067 }
1068
1069 /**
1070 * Get the meta data for a space.
1071 *
1072 * @param int $spaceId The ID of the space.
1073 * @param string $key The meta key.
1074 * @param mixed $default The default value if the meta key is not found.
1075 * @return mixed The meta value or the default value if not found.
1076 */
1077 public static function getSpaceMeta($spaceId, $key, $default = null)
1078 {
1079 $meta = Meta::where('object_type', 'space')
1080 ->where('meta_key', $key)
1081 ->where('object_id', $spaceId)
1082 ->first();
1083
1084 if (!$meta) {
1085 return $default;
1086 }
1087
1088 return $meta->value;
1089 }
1090
1091 /**
1092 * Update the meta data for a space.
1093 *
1094 * @param int $spaceId The ID of the space.
1095 * @param string $key The meta key.
1096 * @param mixed $value The meta value.
1097 * @return Meta The updated meta object.
1098 */
1099 public static function updateSpaceMeta($spaceId, $key, $value)
1100 {
1101 $meta = Meta::where('object_type', 'space')
1102 ->where('meta_key', $key)
1103 ->where('object_id', $spaceId)
1104 ->first();
1105
1106 if ($meta) {
1107 $meta->value = $value;
1108 $meta->save();
1109 } else {
1110 $meta = Meta::create([
1111 'object_type' => 'space',
1112 'object_id' => $spaceId,
1113 'meta_key' => $key,
1114 'value' => $value
1115 ]);
1116 }
1117
1118 return $meta;
1119 }
1120
1121
1122 /**
1123 * Encrypt or decrypt a value.
1124 *
1125 * @param string $value The value to encrypt or decrypt.
1126 * @param string $type The type of operation ('e' for encrypt, 'd' for decrypt).
1127 * @return string|false The encrypted or decrypted value or false if an error occurs.
1128 */
1129 public static function encryptDecrypt($value, $type = 'e')
1130 {
1131 if (!$value) {
1132 return $value;
1133 }
1134
1135 if (!extension_loaded('openssl')) {
1136 return $value;
1137 }
1138
1139 if (defined('FLUENT_COM_ENCRYPT_SALT')) {
1140 $salt = FLUENT_COM_ENCRYPT_SALT;
1141 } else {
1142 $salt = (defined('LOGGED_IN_SALT') && '' !== LOGGED_IN_SALT) ? LOGGED_IN_SALT : 'this-is-a-fallback-salt-but-not-secure';
1143 }
1144
1145 if (defined('FLUENT_COM__ENCRYPT_KEY')) {
1146 $key = FLUENT_COM__ENCRYPT_KEY;
1147 } else {
1148 $key = (defined('LOGGED_IN_KEY') && '' !== LOGGED_IN_KEY) ? LOGGED_IN_KEY : 'this-is-a-fallback-key-but-not-secure';
1149 }
1150
1151 if ($type == 'e') {
1152 $method = 'aes-256-ctr';
1153 $ivlen = openssl_cipher_iv_length($method);
1154 $iv = openssl_random_pseudo_bytes($ivlen);
1155
1156 $raw_value = openssl_encrypt($value . $salt, $method, $key, 0, $iv);
1157 if (!$raw_value) {
1158 return false;
1159 }
1160
1161 return base64_encode($iv . $raw_value); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1162 }
1163
1164 $raw_value = base64_decode($value, true); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
1165
1166 $method = 'aes-256-ctr';
1167 $ivlen = openssl_cipher_iv_length($method);
1168 $iv = substr($raw_value, 0, $ivlen);
1169
1170 $raw_value = substr($raw_value, $ivlen);
1171
1172 $newValue = openssl_decrypt($raw_value, $method, $key, 0, $iv);
1173 if (!$newValue || substr($newValue, -strlen($salt)) !== $salt) {
1174 return false;
1175 }
1176
1177 return substr($newValue, 0, -strlen($salt));
1178 }
1179
1180
1181 /**
1182 * Get the welcome banner configuration.
1183 *
1184 * @return array The welcome banner configuration.
1185 */
1186 public static function getWelcomeBannerSettings()
1187 {
1188 return Utility::getFromCache('welcome_banner_settings', function () {
1189 $defaults = [
1190 'login' => [
1191 'enabled' => 'no',
1192 'description' => '',
1193 'mediaType' => 'image',
1194 'allowClose' => 'no',
1195 'bannerImage' => '',
1196 'bannerVideo' => [
1197 'type' => 'oembed',
1198 'url' => '',
1199 'content_type' => '',
1200 'provider' => '',
1201 'title' => '',
1202 'author_name' => '',
1203 'html' => ''
1204 ],
1205 'ctaButtons' => []
1206 ],
1207 'logout' => [
1208 'enabled' => 'no',
1209 'description' => '',
1210 'mediaType' => 'image',
1211 'useCustomUrl' => 'no',
1212 'bannerImage' => '',
1213 'bannerVideo' => [
1214 'type' => 'oembed',
1215 'url' => '',
1216 'content_type' => '',
1217 'provider' => '',
1218 'title' => '',
1219 'author_name' => '',
1220 'html' => ''
1221 ],
1222 'ctaButtons' => []
1223 ]
1224 ];
1225
1226 $settings = Utility::getOption('welcome_banner_settings', []);
1227
1228 $settings = wp_parse_args($settings, $defaults);
1229
1230 if (empty(Arr::get($settings, 'login.bannerVideo'))) {
1231 $settings['login']['bannerVideo'] = $defaults['login']['bannerVideo'];
1232 }
1233
1234 if (empty(Arr::get($settings, 'logout.bannerVideo'))) {
1235 $settings['logout']['bannerVideo'] = $defaults['logout']['bannerVideo'];
1236 }
1237
1238 return $settings;
1239 }, WEEK_IN_SECONDS);
1240 }
1241
1242 public static function getWelcomeBanner($view = 'login')
1243 {
1244 $settings = self::getWelcomeBannerSettings();
1245 $welcomeBanner = Arr::get($settings, $view, []);
1246 if (Arr::get($welcomeBanner, 'enabled') != 'yes') {
1247 return null;
1248 }
1249
1250 unset($welcomeBanner['description']);
1251
1252 if ($view == 'login') {
1253 return apply_filters('fluent_community/welcome_banner_for_logged_in', $welcomeBanner);
1254 }
1255
1256 return apply_filters('fluent_community/welcome_banner_for_guests', $welcomeBanner);
1257 }
1258
1259 public static function getEnabledFeedLinks()
1260 {
1261 $links = array_filter(self::getFeedLinks(), function ($item) {
1262 return Arr::get($item, 'enabled') == 'yes' && Arr::get($item, 'is_unavailable') != 'yes';
1263 });
1264
1265 return array_values($links);
1266 }
1267
1268 public static function getFeedLinks()
1269 {
1270 return Utility::getFromCache('feed_links', function () {
1271 return Utility::getOption('feed_links', []);
1272 }, WEEK_IN_SECONDS);
1273 }
1274
1275 public static function updateFeedLinks($links)
1276 {
1277 Utility::updateOption('feed_links', $links);
1278 Utility::setCache('feed_links', $links, WEEK_IN_SECONDS);
1279 }
1280
1281 /**
1282 * Get the full name of a WordPress user.
1283 *
1284 * @param int|null $id The ID of the user.
1285 * @return string The full name of the user.
1286 */
1287 public static function getWpUserFullName($id = null)
1288 {
1289 $id = $id ?: get_current_user_id();
1290 $user = get_user_by('ID', $id);
1291
1292 $fullName = $user->display_name;
1293 if ($user->first_name && $user->last_name) {
1294 $fullName = $user->first_name . ' ' . $user->last_name;
1295 }
1296
1297 return $fullName;
1298 }
1299
1300 /**
1301 * Get the onboarding settings.
1302 *
1303 * @return array The onboarding settings.
1304 */
1305 public static function getOnboardingSettings()
1306 {
1307 $default = [
1308 'is_onboarding_enabled' => 'no',
1309 'registration_page_url' => '',
1310 ];
1311
1312 $settings = Utility::getOption('onboarding_settings', $default);
1313
1314 return wp_parse_args($settings, $default);
1315 }
1316
1317 /**
1318 * Get all WordPress published pages.
1319 *
1320 * @return array An array of page data.
1321 */
1322 public static function getAllWpPublishedPage()
1323 {
1324 $posts = get_posts(array(
1325 'post_status' => 'publish',
1326 'numberposts' => -1,
1327 'post_type' => 'any',
1328 ));
1329
1330 return array_map(function ($post) {
1331 return array(
1332 'id' => $post->ID,
1333 'permalink' => get_permalink($post),
1334 'title' => get_the_title($post),
1335 );
1336 }, $posts);
1337 }
1338
1339 /**
1340 * Add a user to a space.
1341 *
1342 * @param Space | int $space space to add the user to.
1343 * @param int $userId The ID of the user to add.
1344 * @param string $role The role of the user in the space.
1345 * @param string $by The source of the action.
1346 * @return bool True if the user was added, false otherwise.
1347 */
1348 public static function addToSpace($space, $userId, $role = 'member', $by = 'self')
1349 {
1350 if (is_numeric($space)) {
1351 $space = BaseSpace::withoutGlobalScopes()->find($space);
1352 }
1353
1354 if (!$space) {
1355 return false;
1356 }
1357
1358 $user = User::find($userId);
1359
1360 if (!$user) {
1361 return false;
1362 }
1363
1364 $user->syncXProfile();
1365
1366 $exist = SpaceUserPivot::where('user_id', $userId)
1367 ->where('space_id', $space->id)
1368 ->first();
1369
1370 if ($exist) {
1371 if ($exist->status != 'active') {
1372 $exist->status = 'active';
1373 $exist->role = $role;
1374 $exist->save();
1375
1376 if ($space->type == 'course') {
1377 do_action('fluent_community/course/enrolled', $space, $userId, $by);
1378 } else {
1379 do_action('fluent_community/space/joined', $space, $userId, $by);
1380 }
1381
1382 return true;
1383 }
1384
1385 return false;
1386 }
1387
1388 SpaceUserPivot::create([
1389 'space_id' => $space->id,
1390 'role' => $role,
1391 'user_id' => $userId
1392 ]);
1393
1394 if ($space->type == 'course') {
1395 do_action('fluent_community/course/enrolled', $space, $userId, $by);
1396 } else {
1397 do_action('fluent_community/space/joined', $space, $userId, $by);
1398 }
1399
1400 return true;
1401 }
1402
1403 /**
1404 * Remove a user from a space if exist.
1405 *
1406 * @param int $userId The ID of the user.
1407 * @param int $spaceId The ID of the space.
1408 * @param string $by The source of the action. self | by_admin
1409 * @return bool True if the user is in the space, false otherwise.
1410 */
1411 public static function removeFromSpace($space, $userId, $by = 'self')
1412 {
1413 $user = User::find($userId);
1414 if (!$user) {
1415 return false;
1416 }
1417
1418 if (is_numeric($space)) {
1419 $space = BaseSpace::query()->withoutGlobalScopes()->find($space);
1420 }
1421
1422 if (!$space) {
1423 return false;
1424 }
1425
1426 if (!self::isUserInSpace($userId, $space->id)) {
1427 return false;
1428 }
1429
1430 SpaceUserPivot::bySpace($space->id)
1431 ->byUser($userId)
1432 ->delete();
1433
1434 $user->cacheAccessSpaces();
1435
1436 if ($space->type == 'course') {
1437 do_action('fluent_community/course/student_left', $space, $userId, $by);
1438 } else {
1439 do_action('fluent_community/space/user_left', $space, $userId, $by);
1440 }
1441
1442 return true;
1443 }
1444
1445 /**
1446 * Render a link with icon.
1447 *
1448 * @param array $link The link data.
1449 * @param string $linkClass Additional classes for the link.
1450 * @param string $fallback The fallback content if no icon is found.
1451 * @param bool $renderIcon Whether to render the icon or not.
1452 */
1453 public static function renderLink($link, $linkClass = '', $fallback = '<span class="fcom_no_avatar"></span>', $renderIcon = true)
1454 {
1455 $linkAtts = array_filter([
1456 'class' => trim($linkClass . ' ' . Arr::get($link, 'link_classes')) . ' fcom_compt_link',
1457 'target' => Arr::get($link, 'new_tab') === 'yes' ? '_blank' : '',
1458 'rel' => Arr::get($link, 'new_tab') === 'yes' ? 'noopener noreferrer' : '',
1459 ]);
1460 ?>
1461 <a aria-label="Go to <?php echo esc_attr(Arr::get($link, 'title')); ?> page"
1462 href="<?php echo esc_url($link['permalink']); ?>" <?php foreach ($linkAtts as $key => $value) {
1463 echo esc_attr($key) . '="' . esc_attr($value) . '"';
1464 } ?>>
1465 <?php $renderIcon && self::printLinkIcon($link, $fallback); ?>
1466 <span class="community_name"><?php echo wp_kses_post(Arr::get($link, 'title')); ?></span>
1467 <?php if (Arr::get($link, 'show_lock')): ?>
1468 <span class="fcom_space_lock">
1469 <i class="el-icon">
1470 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024">
1471 <path fill="currentColor"
1472 d="M224 448a32 32 0 0 0-32 32v384a32 32 0 0 0 32 32h576a32 32 0 0 0 32-32V480a32 32 0 0 0-32-32zm0-64h576a96 96 0 0 1 96 96v384a96 96 0 0 1-96 96H224a96 96 0 0 1-96-96V480a96 96 0 0 1 96-96"></path>
1473 <path fill="currentColor"
1474 d="M512 544a32 32 0 0 1 32 32v192a32 32 0 1 1-64 0V576a32 32 0 0 1 32-32m192-160v-64a192 192 0 1 0-384 0v64zM512 64a256 256 0 0 1 256 256v128H256V320A256 256 0 0 1 512 64"></path>
1475 </svg>
1476 </i>
1477 </span>
1478 <?php endif; ?>
1479
1480 </a>
1481 <?php
1482 }
1483
1484 /**
1485 * Print a link icon.
1486 *
1487 * @param array $link The link data.
1488 * @param string $fallback The fallback content if no icon is found.
1489 */
1490 public static function printLinkIcon($link, $fallback = '<span class="fcom_no_avatar"></span>')
1491 {
1492 ?>
1493 <?php if ($img = Arr::get($link, 'icon_image')): ?>
1494 <div class="community_avatar">
1495 <img alt="" src="<?php echo esc_url($img); ?>"/>
1496 </div>
1497 <?php elseif ($emoji = Arr::get($link, 'emoji')): ?>
1498 <div class="community_avatar">
1499 <span class="fcom_emoji"><?php echo esc_html($emoji); ?></span>
1500 </div>
1501 <?php elseif ($svg = Arr::get($link, 'shape_svg')): ?>
1502 <div class="community_avatar">
1503 <span class="fcom_shape"><i
1504 class="el-icon"><?php echo \FluentCommunity\App\Services\CustomSanitizer::sanitizeSvg($svg); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></i></span>
1505 </div>
1506 <?php else:
1507 echo '<div class="community_avatar">' . wp_kses_post($fallback) . '</div>';
1508 endif;
1509 }
1510
1511 /**
1512 * Get the IP address of the user.
1513 *
1514 * @param bool $anonymize Whether to anonymize the IP address.
1515 * @return string The IP address.
1516 */
1517 public static function getIp($anonymize = false)
1518 {
1519 static $ipAddress;
1520
1521 if ($ipAddress) {
1522 return $ipAddress;
1523 }
1524
1525 if (empty($_SERVER['REMOTE_ADDR'])) {
1526 // It's a local cli request
1527 return '127.0.0.1';
1528 }
1529
1530 $ipAddress = '';
1531 if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
1532 $ipAddress = sanitize_text_field(wp_unslash($_SERVER["REMOTE_ADDR"]));
1533 //If it's a valid Cloudflare request
1534 if (self::isCfIp($ipAddress)) {
1535 //Use the CF-Connecting-IP header.
1536 $ipAddress = sanitize_text_field(wp_unslash($_SERVER['HTTP_CF_CONNECTING_IP']));
1537 }
1538 } else if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
1539 // most probably it's local reverse proxy
1540 if (isset($_SERVER["HTTP_CLIENT_IP"])) {
1541 $ipAddress = sanitize_text_field(wp_unslash($_SERVER["HTTP_CLIENT_IP"]));
1542 } else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1543 $ipAddress = (string)rest_is_ip_address(trim(current(preg_split('/,/', sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']))))));
1544 }
1545 }
1546
1547 if (!$ipAddress) {
1548 $ipAddress = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
1549 }
1550
1551 $ipAddress = preg_replace('/^(\d+\.\d+\.\d+\.\d+):\d+$/', '\1', $ipAddress);
1552
1553 $ipAddress = apply_filters('fluent_auth/user_ip', $ipAddress);
1554
1555 if ($anonymize) {
1556 return wp_privacy_anonymize_ip($ipAddress);
1557 }
1558
1559 return $ipAddress;
1560 }
1561
1562 /**
1563 * Check if the IP address is from Cloudflare.
1564 *
1565 * @param string $ip The IP address to check.
1566 * @return bool True if the IP is from Cloudflare, false otherwise.
1567 */
1568 public static function isCfIp($ip = '')
1569 {
1570 if (!$ip && isset($_SERVER["REMOTE_ADDR"])) {
1571 $ip = sanitize_text_field(wp_unslash($_SERVER["REMOTE_ADDR"]));
1572 }
1573
1574 if (!$ip) {
1575 return false;
1576 }
1577
1578 $cloudflareIPRanges = array(
1579 '173.245.48.0/20',
1580 '103.21.244.0/22',
1581 '103.22.200.0/22',
1582 '103.31.4.0/22',
1583 '141.101.64.0/18',
1584 '108.162.192.0/18',
1585 '190.93.240.0/20',
1586 '188.114.96.0/20',
1587 '197.234.240.0/22',
1588 '198.41.128.0/17',
1589 '162.158.0.0/15',
1590 '104.16.0.0/13',
1591 '104.24.0.0/14',
1592 '172.64.0.0/13',
1593 '131.0.72.0/22',
1594 );
1595
1596 //Make sure that the request came via Cloudflare.
1597 foreach ($cloudflareIPRanges as $range) {
1598 //Use the ip_in_range function from Joomla.
1599 if (self::ipInRange($ip, $range)) {
1600 //IP is valid. Belongs to Cloudflare.
1601 return true;
1602 }
1603 }
1604
1605 return false;
1606 }
1607
1608 /**
1609 * Check if the IP address is in the given range.
1610 *
1611 * @param string $ip The IP address to check.
1612 * @param string $range The range to check against.
1613 * @return bool True if the IP is in the range, false otherwise.
1614 */
1615 private static function ipInRange($ip, $range)
1616 {
1617 if (strpos($range, '/') !== false) {
1618 // $range is in IP/NETMASK format
1619 list($range, $netmask) = explode('/', $range, 2);
1620 if (strpos($netmask, '.') !== false) {
1621 // $netmask is a 255.255.0.0 format
1622 $netmask = str_replace('*', '0', $netmask);
1623 $netmask_dec = ip2long($netmask);
1624 return ((ip2long($ip) & $netmask_dec) == (ip2long($range) & $netmask_dec));
1625 } else {
1626 // $netmask is a CIDR size block
1627 // fix the range argument
1628 $x = explode('.', $range);
1629 while (count($x) < 4) $x[] = '0';
1630 list($a, $b, $c, $d) = $x;
1631 $range = sprintf("%u.%u.%u.%u", empty($a) ? '0' : $a, empty($b) ? '0' : $b, empty($c) ? '0' : $c, empty($d) ? '0' : $d);
1632 $range_dec = ip2long($range);
1633 $ip_dec = ip2long($ip);
1634
1635 # Strategy 1 - Create the netmask with 'netmask' 1s and then fill it to 32 with 0s
1636 #$netmask_dec = bindec(str_pad('', $netmask, '1') . str_pad('', 32-$netmask, '0'));
1637
1638 # Strategy 2 - Use math to create it
1639 $wildcard_dec = pow(2, (32 - $netmask)) - 1;
1640 $netmask_dec = ~$wildcard_dec;
1641
1642 return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
1643 }
1644 } else {
1645 // range might be 255.255.*.* or 1.2.3.0-1.2.3.255
1646 if (strpos($range, '*') !== false) { // a.b.*.* format
1647 // Just convert to A-B format by setting * to 0 for A and 255 for B
1648 $lower = str_replace('*', '0', $range);
1649 $upper = str_replace('*', '255', $range);
1650 $range = "$lower-$upper";
1651 }
1652
1653 if (strpos($range, '-') !== false) { // A-B format
1654 list($lower, $upper) = explode('-', $range, 2);
1655 $lower_dec = (float)sprintf("%u", ip2long($lower));
1656 $upper_dec = (float)sprintf("%u", ip2long($upper));
1657 $ip_dec = (float)sprintf("%u", ip2long($ip));
1658 return (($ip_dec >= $lower_dec) && ($ip_dec <= $upper_dec));
1659 }
1660 return false;
1661 }
1662 }
1663
1664 public static function getPortalRequestPath($requestUri)
1665 {
1666 $portalSlug = self::getPortalSlug();
1667
1668 if ($portalSlug == $requestUri) {
1669 return 'portal_home';
1670 }
1671
1672 if (!$requestUri) {
1673 return false;
1674 }
1675
1676 if ($portalSlug) {
1677 // remove the portal slug from the request uri. Don't use str_replace as it will replace all occurrences
1678 $requestUri = substr($requestUri, strlen($portalSlug));
1679 }
1680
1681 $parts = explode('/', $requestUri);
1682 $start = $parts[0];
1683
1684 $routeStats = self::portalRoutePaths();
1685
1686 if (in_array($start, $routeStats)) {
1687 return $requestUri;
1688 }
1689 return false;
1690 }
1691
1692 public static function getTopicsConfig()
1693 {
1694 return Utility::getFromCache('topics_config', function () {
1695 $config = Utility::getOption('topics_config', []);
1696 $default = [
1697 'max_topics_per_post' => 1,
1698 'max_topics_per_space' => 20,
1699 'show_on_post_card' => 'yes'
1700 ];
1701 return wp_parse_args($config, $default);
1702 }, WEEK_IN_SECONDS);
1703 }
1704 }
1705