PluginProbe
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses / 1.0.99
FluentCommunity – Ultra-Fast High-Performance Social Network, Community, LMS & Online Courses v1.0.99
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 / FeedsController.php

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

806 lines 26.6 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\Media;
7 use FluentCommunity\App\Models\NotificationSubscriber;
8 use FluentCommunity\App\Models\Space;
9 use FluentCommunity\App\Models\User;
10 use FluentCommunity\App\Services\CustomSanitizer;
11 use FluentCommunity\App\Services\FeedsHelper;
12 use FluentCommunity\App\Services\Helper;
13 use FluentCommunity\App\Services\Libs\FileSystem;
14 use FluentCommunity\App\Services\ProfileHelper;
15 use FluentCommunity\App\Services\RemoteUrlParser;
16 use FluentCommunity\Framework\Http\Request\Request;
17 use FluentCommunity\App\Models\Comment;
18 use FluentCommunity\App\Models\Feed;
19 use FluentCommunity\App\Models\Reaction;
20 use FluentCommunity\App\Models\BaseSpace;
21 use FluentCommunity\Framework\Support\Arr;
22
23 class FeedsController extends Controller
24 {
25 public function get(Request $request)
26 {
27 $bySpace = $request->get('space');
28 $userId = $request->getSafe('user_id', 'intval', '');
29 $selectedTopic = $request->getSafe('topic_slug', 'sanitize_text_field', '');
30 $search = $request->get('search');
31 if ($bySpace) {
32 // just for validation
33 $space = BaseSpace::where('slug', $bySpace)->first();
34 if (!$space) {
35 return $this->sendError('Invalid space slug');
36 }
37 }
38
39 $feedsQuery = Feed::where('status', 'published')
40 ->select(Feed::$publicColumns)
41 ->with([
42 'xprofile' => function ($q) {
43 $q->select(ProfileHelper::getXProfilePublicFields());
44 },
45 'comments.xprofile' => function ($q) {
46 $q->select(ProfileHelper::getXProfilePublicFields());
47 },
48 'space',
49 'reactions' => function ($q) {
50 $q->with([
51 'xprofile' => function ($query) {
52 $query->select(['user_id', 'avatar']);
53 }
54 ])
55 ->where('type', 'like')
56 ->limit(3);
57 },
58 'terms' => function ($q) {
59 $q->select(['title', 'slug'])
60 ->where('taxonomy_name', 'post_topic');
61 }
62 ]
63 )
64 ->searchBy($search)
65 ->byTopicSlug($selectedTopic)
66 ->customOrderBy($request->get('type', ''));
67
68 $stickyFeed = null;
69
70 $disableSticky = $request->get('disable_sticky', '') == 'yes' || !!$search || !!$selectedTopic;
71
72 if($bySpace) {
73 $feedsQuery = $feedsQuery->filterBySpaceSlug($bySpace);
74 }
75
76 if ($bySpace && !$disableSticky) {
77 $feedsQuery = $feedsQuery->where('is_sticky', 0);
78 if ($request->page == 1) {
79 $stickyFeed = Feed::where('space_id', $space->id)
80 ->where('is_sticky', 1)
81 ->with([
82 'xprofile' => function ($q) {
83 $q->select(ProfileHelper::getXProfilePublicFields());
84 },
85 'comments.xprofile' => function ($q) {
86 $q->select(ProfileHelper::getXProfilePublicFields());
87 },
88 'space'
89 ]
90 )
91 ->first();
92 }
93 }
94
95 if ($userId) {
96 $feedsQuery = $feedsQuery->where('user_id', $userId);
97 if ($userId != get_current_user_id()) {
98 $feedsQuery = $feedsQuery->byUserAccess(get_current_user_id());
99 }
100 } else {
101 $feedsQuery->byUserAccess(get_current_user_id());
102 }
103
104 do_action_ref_array('fluent_community/feeds_query', [&$feedsQuery, $request->all()]);
105
106 $feeds = $feedsQuery->paginate();
107
108 // add $stickyFeed to the first page
109 if ($stickyFeed) {
110 $stickyFeed = $this->transformFeed($stickyFeed);
111 }
112
113 $feeds->getCollection()->each(function ($feed) {
114 $this->transformFeed($feed);
115 });
116
117 $data = [
118 'feeds' => $feeds,
119 'sticky' => $stickyFeed
120 ];
121
122 $isMainFeed = $request->get('page') == 1 && !$search && !$userId;
123 if ($isMainFeed && get_current_user_id()) {
124 $data['last_fetched_timestamp'] = current_time('timestamp');
125 }
126
127 return $data;
128 }
129
130 public function getFeedBySlug(Request $request, $feed_slug)
131 {
132 if ($request->get('context') == 'edit') {
133 $feed = Feed::where('slug', $feed_slug)->first();
134
135 if (!$feed || !$feed->hasEditAccess(get_current_user_id())) {
136 return $this->sendError([
137 'message' => 'You do not have permission to edit this feed'
138 ]);
139 }
140
141 return [
142 'feed' => FeedsHelper::transformForEdit($feed)
143 ];
144 }
145
146 $feed = Feed::where('slug', $feed_slug)
147 ->select(Feed::$publicColumns)
148 ->with([
149 'xprofile' => function ($q) {
150 $q->select(ProfileHelper::getXProfilePublicFields());
151 },
152 'space',
153 'comments.xprofile' => function ($q) {
154 $q->select(ProfileHelper::getXProfilePublicFields());
155 },
156 'reactions' => function ($q) {
157 $q->with([
158 'xprofile' => function ($query) {
159 $query->select(['user_id', 'avatar']);
160 }
161 ])
162 ->where('type', 'like')
163 ->limit(3);
164 },
165 'terms' => function ($q) {
166 $q->select(['title', 'slug'])
167 ->where('taxonomy_name', 'post_topic');
168 }
169 ])
170 ->byUserAccess($this->getUserId())
171 ->first();
172
173 if (!$feed) {
174 return $this->sendError([
175 'message' => __('The feed could not be found', 'fluent-commuity')
176 ], 404);
177 }
178
179 $this->transformFeed($feed);
180
181 return [
182 'feed' => $feed
183 ];
184 }
185
186 public function getBookmarks(Request $request)
187 {
188 $userId = get_current_user_id();
189
190 $feedsQuery = Feed::where('status', 'published')
191 ->select(Feed::$publicColumns)
192 ->with([
193 'xprofile' => function ($q) {
194 $q->select(ProfileHelper::getXProfilePublicFields());
195 },
196 'comments.xprofile' => function ($q) {
197 $q->select(ProfileHelper::getXProfilePublicFields());
198 },
199 'space'
200 ]
201 )
202 ->byBookMarked($userId)
203 ->byUserAccess($userId)
204 ->searchBy($request->get('search'));
205
206
207 if ($type = $request->get('type')) {
208 $feedsQuery = $feedsQuery->where('type', $type);
209 }
210
211 $feeds = $feedsQuery->orderBy('id', 'DESC')
212 ->paginate();
213
214 $feeds->getCollection()->each(function ($feed) {
215 $this->transformFeed($feed);
216 });
217
218 $data = [
219 'feeds' => $feeds
220 ];
221
222 if ($request->get('page') == 1) {
223 $lastItem = FeedsHelper::getLastFeedId();
224 if ($lastItem) {
225 $data['last_id'] = $lastItem;
226 }
227 }
228
229 return $data;
230 }
231
232 public function store(Request $request)
233 {
234 $user = $this->getUser(true);
235 do_action('fluent_community/check_rate_limit/create_post', $user);
236 $requestData = $request->all();
237
238 $data = $this->sanitizeAndValidateData($requestData);
239
240 if ($isDulicate = $this->checkForDuplicatePost($user->ID, $data['message'])) {
241 return $isDulicate;
242 }
243
244 $feed = new Feed();
245 $feed->user_id = $user->ID;
246
247 if ($spaceSlug = $request->get('space')) {
248 $data['space_id'] = $this->validateAndSetSpace($spaceSlug, $user);
249 } else if (!Helper::hasGlobalPost()) {
250 return $this->sendError([
251 'message' => __('Please select a valid space to post in.', 'fluent-community')
252 ]);
253 }
254
255 $message = $data['message'];
256 $mentions = FeedsHelper::getMentions($data['message'], Arr::get($data, 'space_id'));
257 if ($mentions) {
258 $data['message'] = $message;
259 $message = $mentions['text'];
260 }
261
262 // replace new line with br
263 $data['message_rendered'] = wp_kses_post(FeedsHelper::mdToHtml($message));
264
265 [$data, $mediaItems] = FeedsHelper::processFeedMetaData($data, $requestData);
266
267 $data = apply_filters('fluent_community/feed/new_feed_data', $data, $requestData);
268
269 $feed->fill($data);
270
271 $feed->save();
272
273 if ($mediaItems) {
274 $this->saveMediaItems($feed, $mediaItems);
275 }
276
277 $this->handleMentions($feed, $mentions ?? []);
278
279 $feed->load(['xprofile', 'comments.xprofile']);
280 if ($feed->space_id) {
281 $feed->load(['space']);
282 $topicIds = (array)$request->get('topic_ids', []);
283 // take only max topics per post
284 if ($topicIds) {
285 $topicsConfig = Helper::getTopicsConfig();
286 $topicIds = array_slice($topicIds, 0, $topicsConfig['max_topics_per_post']);
287 $feed->attachTopics($topicIds, false);
288 }
289 }
290
291 do_action('fluent_community/feed/created', $feed);
292 if ($feed->space_id) {
293 do_action('fluent_community/space_feed/created', $feed);
294 }
295
296 return [
297 'feed' => $this->transformFeed($feed),
298 'message' => __('Your post has been published', 'fluent-community'),
299 'last_fetched_timestamp' => current_time('timestamp')
300 ];
301 }
302
303 public function update(Request $request, $feedId)
304 {
305 $requestData = $request->all();
306 $data = $this->sanitizeAndValidateData($requestData);
307 $user = $this->getUser(true);
308 $existingFeed = Feed::findOrFail($feedId);
309 $user->canEditFeed($existingFeed, true);
310
311 $message = $data['message'];
312 $mentions = FeedsHelper::getMentions($data['message'], Arr::get($data, 'space_id'));
313 if ($mentions) {
314 $data['message'] = $message;
315 $message = $mentions['text'];
316 }
317
318 // replace new line with br
319 $data['message_rendered'] = wp_kses_post(FeedsHelper::mdToHtml($message));
320
321 [$data, $mediaItems] = FeedsHelper::processFeedMetaData($data, $requestData, $existingFeed);
322
323 $data = apply_filters('fluent_community/feed/update_feed_data', $data, $requestData);
324
325 if ($message != $existingFeed->message) {
326 $data['meta']['last_edited'] = [
327 'user_id' => $user->ID,
328 'time' => current_time('mysql')
329 ];
330 }
331
332 $data = apply_filters('fluent_community/feed/update_data', $data, $existingFeed);
333 $existingFeed->fill($data);
334 $dirty = $existingFeed->getDirty();
335
336 $existingFeed->fill($data);
337 $existingFeed->save();
338
339 if ($message != $existingFeed->message) {
340 $editHistory = $existingFeed->getCustomMeta('_edit_history', []);
341 if (!$editHistory) {
342 $editHistory = [];
343 }
344
345 $editHistory[] = array_filter([
346 'user_id' => $user->ID,
347 'time' => current_time('mysql'),
348 'prev_message' => $existingFeed->message,
349 'prev_title' => $existingFeed->title
350 ]);
351
352 // get last 5 edit history
353 $editHistory = array_slice($editHistory, -5);
354 $existingFeed->updateCustomMeta('_edit_history', $editHistory);
355 }
356
357 if ($mediaItems) {
358 $this->saveMediaItems($existingFeed, $mediaItems);
359 }
360
361 $existingFeed->load(['xprofile', 'comments.xprofile']);
362
363 if ($existingFeed->space_id) {
364 $existingFeed->load(['space']);
365 $topicIds = (array)Arr::get($requestData, 'topic_ids', []);
366 // take only max topics per post
367 if ($topicIds) {
368 $topicsConfig = Helper::getTopicsConfig();
369 $topicIds = array_slice($topicIds, 0, $topicsConfig['max_topics_per_post']);
370 $existingFeed->attachTopics($topicIds, true);
371 }
372 }
373
374 if ($dirty) {
375 do_action('fluent_community/feed/updated', $existingFeed, $dirty);
376 if ($existingFeed->space_id) {
377 do_action('fluent_community/space_feed/updated', $existingFeed);
378 }
379 }
380
381 return [
382 'feed' => $this->transformFeed($existingFeed),
383 'message' => __('Your post has been updated', 'fluent-community')
384 ];
385 }
386
387 public function patchFeed(Request $request, $feedId)
388 {
389 $feed = Feed::findOrFail($feedId);
390 $user = $this->getUser(true);
391
392 $isMod = $user->isCommunityModerator();
393 $isAuthor = $feed->user_id == $user->ID;
394
395 if (!$isMod && !$isAuthor) {
396 return $this->sendError([
397 'message' => __('You do not have permission to perform this action', 'fluent-community')
398 ]);
399 }
400
401 $allData = $request->all();
402 $validKeys = ['is_sticky', 'priority', 'comments_disabled'];
403
404 if (!$isMod) {
405 $validKeys = ['comments_disabled'];
406 }
407
408 $data = Arr::only($allData, $validKeys);
409
410 $data = array_map('intval', $data);
411
412 if (isset($data['is_sticky'])) {
413 $data['is_sticky'] = $data['is_sticky'] ? 1 : 0;
414 if ($data['is_sticky'] && $feed->space_id) {
415 // remove all the sticky posts from the space
416 Feed::where('space_id', $feed->space_id)->update(['is_sticky' => 0]);
417 }
418 }
419
420 if (isset($data['comments_disabled'])) {
421 $meta = $feed->meta;
422 $meta['comments_disabled'] = $data['comments_disabled'] ? 'yes' : 'no';
423 $data['meta'] = $meta;
424 }
425
426
427 if ($data) {
428 $feed->fill($data);
429 $dirty = $feed->getDirty();
430 if ($dirty) {
431 $feed->save();
432 do_action('fluent_community/feed/updated', $feed, $dirty);
433 }
434 }
435
436 return [
437 'feed' => $feed,
438 'message' => __('Feed updated', 'fluent-community')
439 ];
440 }
441
442 public function getLinks(Request $request)
443 {
444 return [
445 'links' => Helper::getFeedLinks()
446 ];
447 }
448
449 public function updateLinks(Request $request)
450 {
451 $links = $request->get('links', []);
452
453 $links = array_map(function ($link) {
454 return CustomSanitizer::santizeLinkItem($link);
455 }, $links);
456
457 Helper::updateFeedLinks($links);
458
459 return [
460 'message' => __('Links have been updated.', 'fluent-community'),
461 'links' => $links
462 ];
463 }
464
465 private function saveMediaItems($feed, $mediaItems)
466 {
467 foreach ($mediaItems as $media) {
468 $media->feed_id = $feed->id;
469 $media->is_active = 1;
470 $media->object_source = 'feed';
471 $media->save();
472 }
473 }
474
475 private function handleMentions($feed, $mentions)
476 {
477 if ($mentions) {
478 do_action('fluent_community/feed_mentioned', $feed, $mentions['users']);
479 }
480 }
481
482 private function sanitizeAndValidateData($data)
483 {
484 $data['type'] = 'text';
485
486 $this->validate($data, [
487 'message' => 'required'
488 ], [
489 'message.required' => __('Message is required', 'fluent-community'),
490 ]);
491
492 return FeedsHelper::sanitizeAndValidateData($data);
493 }
494
495 private function checkForDuplicatePost($userId, $message)
496 {
497 $message = trim($message);
498
499 $exist = Feed::where('user_id', $userId)
500 ->where('message', $message)
501 ->where('created_at', '>', gmdate('Y-m-d H:i:s', current_time('timestamp') - 7 * 24 * 60 * 60))
502 ->first();
503
504 if ($exist) {
505 return $this->sendError(['message' => 'No duplicate post please!']);
506 }
507
508 return false;
509 }
510
511 private function validateAndSetSpace($spaceSlug, $user)
512 {
513 if ($spaceSlug == '__self__post__') {
514 if (!Helper::hasGlobalPost()) {
515 throw new \Exception(__('Please select a valid space to post in', 'fluent-community'));
516 }
517
518 return null;
519 }
520
521 $space = Space::where('slug', $spaceSlug)->first();
522
523 if (!$space) {
524 throw new \Exception(__('Please select a valid space to post in', 'fluent-community'));
525 }
526
527 $user->verifySpacePermission('can_create_post', $space);
528
529 return $space->id;
530 }
531
532 public function deleteFeed(Request $request, $feed_id)
533 {
534 $feed = Feed::findOrFail($feed_id);
535
536 $user = User::find(get_current_user_id());
537 $user->canDeleteFeed($feed, true);
538 do_action('fluent_community/feed/before_deleted', $feed);
539 $feed->delete();
540
541 do_action('fluent_community/feed/deleted', $feed_id);
542
543 return [
544 'message' => 'Feed has been deleted successfully'
545 ];
546 }
547
548 public function deleteMediaPreview(Request $request, $feed_id)
549 {
550 $feed = Feed::findOrFail($feed_id);
551 $user = User::find(get_current_user_id());
552 $user->canDeleteFeed($feed, true);
553
554 do_action('fluent_community/feed/media_deleted', $feed->media);
555
556 $meta = $feed->meta;
557 $meta['media_preview'] = null;
558
559 $feed->meta = $meta;
560 $feed->save();
561
562 return [
563 'message' => __('Media preview image has been removed successfully.', 'fluent-community')
564 ];
565 }
566
567 public function handleMediaUpload(Request $request)
568 {
569 $allowedTypes = implode(
570 ',',
571 apply_filters('fluent_community/support_attachment_types', [
572 'image/jpeg',
573 'image/pjpeg',
574 'image/jpeg',
575 'image/pjpeg',
576 'image/png',
577 'image/gif',
578 'image/webp'
579 ])
580 );
581
582 $files = $this->validate($this->request->files(), [
583 'file' => 'mimetypes:' . $allowedTypes,
584 ], [
585 'file.mimetypes' => __('The file must be an image type.', 'fluent-community')
586 ]);
587
588 $uploadedFiles = FileSystem::put($files);
589
590 $file = $uploadedFiles[0];
591
592 $willWebPConvert = apply_filters('fluent_community/convert_image_to_webp', true, $file);
593
594 if ($request->get('resize') && $maxWidth = $request->get('max_width')) {
595 $upload_dir = wp_upload_dir();
596 $fileUrl = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $file['url']);
597
598 $editor = wp_get_image_editor($fileUrl);
599
600 if (!is_wp_error($editor) && $editor->get_size()['width'] > $maxWidth) {
601 // Current file extension
602 $ext = pathinfo($file['url'], PATHINFO_EXTENSION);
603 $imageExtensions = ['jpg', 'jpeg', 'png', 'gif'];
604
605 $willConvert = in_array($ext, $imageExtensions) && $willWebPConvert;
606
607 if ($willConvert) {
608 $imageExtensions = array_map(function ($ext) {
609 return '.' . $ext;
610 }, $imageExtensions);
611 $fileUrl = str_replace($imageExtensions, '.webp', $fileUrl);
612 $file['file'] = str_replace($imageExtensions, '.webp', $file['file']);
613 $file['url'] = str_replace($imageExtensions, '.webp', $file['url']);
614 $file['type'] = 'image/webp';
615 }
616
617 // resize the image
618 $editor->resize($maxWidth, null, false);
619 $editor->set_quality(90);
620 if ($willConvert) {
621 $editor->save($fileUrl, 'image/webp');
622 // remove original file now
623 wp_delete_file(str_replace('.webp', '.' . $ext, $fileUrl));
624 $file['is_converted'] = true;
625 } else {
626 $editor->save($fileUrl);
627 }
628
629 $file['meta'] = [
630 'width' => $editor->get_size()['width'],
631 'height' => $editor->get_size()['height']
632 ];
633 }
634 $file['path'] = $upload_dir['basedir'] . '/fluent-community/' . $file['file'];
635 } else {
636 $upload_dir = wp_upload_dir();
637 $file['path'] = $upload_dir['basedir'] . '/fluent-community/' . $file['file'];
638 }
639
640 if ($willWebPConvert && empty($file['is_converted']) && !$request->get('skip_convert')) {
641 $path = $file['path'];
642 $extension = pathinfo($path, PATHINFO_EXTENSION);
643
644 $convertFromExtensions = ['png', 'jpg', 'jpeg', 'gif'];
645 if ($extension != 'webp' && in_array($extension, $convertFromExtensions)) {
646 // Let's convert to webp
647 $editor = wp_get_image_editor($file['path']);
648 if (!is_wp_error($editor)) {
649 $orginalPath = $file['path'];
650 $file['path'] = str_replace('.' . $extension, '.webp', $file['path']);
651 $file['url'] = str_replace('.' . $extension, '.webp', $file['url']);
652 $file['type'] = 'image/webp';
653 $editor->save($file['path'], 'image/webp');
654 wp_delete_file($orginalPath);
655
656 $file['meta'] = [
657 'width' => $editor->get_size()['width'],
658 'height' => $editor->get_size()['height']
659 ];
660 }
661 }
662 }
663
664 $mediaData = [
665 'media_type' => $file['type'],
666 'driver' => 'local',
667 'media_path' => $file['path'],
668 'media_url' => $file['url'],
669 'settings' => Arr::get($file, 'meta', [])
670 ];
671
672 $mediaData = apply_filters('fluent_community/media_upload_data', $mediaData, $file);
673
674 if (is_wp_error($mediaData)) {
675 return $this->sendError([
676 'message' => $mediaData->get_error_message(),
677 'errors' => $mediaData->get_error_data()
678 ]);
679 }
680
681 if (!$mediaData) {
682 return $this->sendError([
683 'message' => 'Error while uploading the media'
684 ]);
685 }
686
687 // Let's create the media now
688 $media = Media::create($mediaData);
689
690 $mediaUrl = $media->public_url;
691
692 $mediaUrl = add_query_arg([
693 'media_key' => $media->media_key,
694 ], $mediaUrl);
695
696 return [
697 'media' => [
698 'url' => $mediaUrl,
699 'media_key' => $media->media_key,
700 'type' => $media->media_type,
701 'width' => Arr::get($media->settings, 'width'),
702 'height' => Arr::get($media->settings, 'height')
703 ]
704 ];
705 }
706
707 public function getTicker(Request $request)
708 {
709 do_action('fluent_communit/track_activity');
710 $lastLoadedTimeStamp = $request->get('last_fetched_timestamp');
711
712 //check if $lastLoadedTimeStamp is valid date
713 if (!$lastLoadedTimeStamp || (current_time('timestamp') - $lastLoadedTimeStamp) > HOUR_IN_SECONDS) {
714 return [
715 'last_fetched_timestamp' => current_time('timestamp'),
716 'error' => 'Invalid timestamp',
717 'given' => $lastLoadedTimeStamp
718 ];
719 }
720
721 $userId = get_current_user_id();
722 if (!$userId) {
723 return [
724 'last_fetched_timestamp' => current_time('timestamp'),
725 'error' => 'Invalid user'
726 ];
727 }
728
729 $newItemsCount = Feed::where('created_at', '>', date('Y-m-d H:i:s', $lastLoadedTimeStamp))
730 ->where('status', 'published')
731 ->byUserAccess(get_current_user_id())
732 ->count();
733
734 $notificationCount = NotificationSubscriber::unread()->where('user_id', $userId)->count();
735
736 return apply_filters('fluent_community/feed_ticker', [
737 'last_fetched_timestamp' => current_time('timestamp'),
738 'new_items_count' => $newItemsCount > 10 ? 10 : $newItemsCount,
739 'unread_notification_count' => $notificationCount
740 ]);
741 }
742
743 public function getOembed(Request $request)
744 {
745 $url = $request->get('url');
746 // check if the url is valid
747 $metaData = RemoteUrlParser::parse($url);
748
749 if ($metaData && !is_wp_error($metaData)) {
750 return [
751 'oembed' => $metaData
752 ];
753 }
754
755 return $this->send([
756 'message' => 'No oembed data found',
757 'url' => $url
758 ]);
759 }
760
761 public function markdownToHtml(Request $request)
762 {
763 $message = trim(sanitize_textarea_field($request->get('text', '')));
764
765 $html = FeedsHelper::mdToHtml($message);
766
767 return [
768 'html' => $html
769 ];
770 }
771
772 private function transformFeed(Feed $feed)
773 {
774 $userId = $this->getUserId();
775 if ($userId) {
776 $feed->has_user_react = $feed->hasUserReact($userId, 'like');
777 $feed->bookmarked = $feed->hasUserReact($userId, 'bookmark');
778
779 $likedIds = FeedsHelper::getLikedIdsByUserFeedId($feed->id, get_current_user_id());
780 $feed->comments->each(function ($comment) use ($likedIds) {
781 if ($likedIds && in_array($comment->id, $likedIds)) {
782 $comment->liked = 1;
783 }
784 });
785
786 if ($feed->content_type == 'survey') {
787 $votedOptions = $feed->getSurveyCastsByUserId($userId);
788
789 if ($votedOptions) {
790 $surveyConfig = Arr::get($feed->meta, 'survey_config', []);
791 foreach ($surveyConfig['options'] as $index => $option) {
792 if (in_array($option['slug'], $votedOptions)) {
793 $surveyConfig['options'][$index]['voted'] = true;
794 }
795 }
796 $meta = $feed->meta;
797 $meta['survey_config'] = $surveyConfig;
798 $feed->meta = $meta;
799 }
800 }
801 }
802
803 return $feed;
804 }
805 }
806