3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Event;
38 use Friendica\Model\GServer;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Model\Post;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\ActivityPub;
47 use Friendica\Protocol\Delivery;
48 use Friendica\Protocol\Relay;
49 use Friendica\Util\DateTimeFormat;
50 use Friendica\Util\HTTPSignature;
51 use Friendica\Util\JsonLD;
52 use Friendica\Util\Network;
53 use Friendica\Util\Strings;
56 * ActivityPub Processor Protocol class
60 const CACHEKEY_FETCH_ACTIVITY = 'processor:fetchMissingActivity:';
61 const CACHEKEY_JUST_FETCHED = 'processor:isJustFetched:';
64 * Add an object id to the list of processed ids
70 private static function addActivityId(string $id)
72 DBA::delete('fetched-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
73 DBA::insert('fetched-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()]);
77 * Checks if the given object id has just been fetched
83 private static function isFetched(string $id): bool
85 return DBA::exists('fetched-activity', ['object-id' => $id]);
89 * Extracts the tag character (#, @, !) from mention links
94 public static function normalizeMentionLinks(string $body): string
96 $body = preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
97 $body = preg_replace('%([#@!])\[zrl=([^\[\]]*)](.*?)\[/zrl]%ism', '$1[url=$2]$3[/url]', $body);
102 * Convert the language array into a language JSON
104 * @param array $languages
105 * @return string language JSON
107 private static function processLanguages(array $languages): string
109 $codes = array_keys($languages);
111 foreach ($codes as $code) {
119 return json_encode($lang);
122 * Replaces emojis in the body
125 * @param string $body
126 * @param array $emojis
128 * @return string with replaced emojis
130 private static function replaceEmojis(int $uri_id, string $body, array $emojis): string
134 array_column($emojis, 'name'),
135 array_map(function ($emoji) {
136 return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
141 // We store the emoji here to be able to avoid storing it in the media
142 foreach ($emojis as $emoji) {
143 Post\Link::getByLink($uri_id, $emoji['href']);
149 * Store attached media files in the post-media table
152 * @param array $attachment
155 private static function storeAttachmentAsMedia(int $uriid, array $attachment)
157 if (empty($attachment['url'])) {
161 $data = ['uri-id' => $uriid];
162 $data['type'] = Post\Media::UNKNOWN;
163 $data['url'] = $attachment['url'];
164 $data['mimetype'] = $attachment['mediaType'] ?? null;
165 $data['height'] = $attachment['height'] ?? null;
166 $data['width'] = $attachment['width'] ?? null;
167 $data['size'] = $attachment['size'] ?? null;
168 $data['preview'] = $attachment['image'] ?? null;
169 $data['description'] = $attachment['name'] ?? null;
171 Post\Media::insert($data);
175 * Store attachment data
177 * @param array $activity
180 private static function storeAttachments(array $activity, array $item)
182 if (empty($activity['attachments'])) {
186 foreach ($activity['attachments'] as $attach) {
187 self::storeAttachmentAsMedia($item['uri-id'], $attach);
192 * Store question data
194 * @param array $activity
197 private static function storeQuestion(array $activity, array $item)
199 if (empty($activity['question'])) {
202 $question = ['multiple' => $activity['question']['multiple']];
204 if (!empty($activity['question']['voters'])) {
205 $question['voters'] = $activity['question']['voters'];
208 if (!empty($activity['question']['end-time'])) {
209 $question['end-time'] = DateTimeFormat::utc($activity['question']['end-time']);
212 Post\Question::update($item['uri-id'], $question);
214 foreach ($activity['question']['options'] as $key => $option) {
215 $option = ['name' => $option['name'], 'replies' => $option['replies']];
216 Post\QuestionOption::update($item['uri-id'], $key, $option);
219 Logger::debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]);
225 * @param array $activity Activity array
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 * @throws \ImagickException
229 public static function updateItem(array $activity)
231 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type', 'private'], ['uri' => $activity['id']]);
232 if (!DBA::isResult($item)) {
233 Logger::notice('No existing item, item will be created', ['uri' => $activity['id']]);
234 $item = self::createItem($activity, false);
236 Queue::remove($activity);
240 self::postItem($activity, $item);
244 $item['changed'] = DateTimeFormat::utcNow();
245 $item['edited'] = DateTimeFormat::utc($activity['updated']);
247 Post\Media::deleteByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE, Post\Media::HTML]);
248 $item = self::processContent($activity, $item);
250 Queue::remove($activity);
254 self::storeAttachments($activity, $item);
255 self::storeQuestion($activity, $item);
257 Post\History::add($item['uri-id'], $item);
258 Item::update($item, ['uri' => $activity['id']]);
260 Queue::remove($activity);
262 if ($activity['object_type'] == 'as:Event') {
263 $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
264 while ($post = DBA::fetch($posts)) {
265 self::updateEvent($post['event-id'], $activity);
271 * Update an existing event
273 * @param int $event_id
274 * @param array $activity
276 private static function updateEvent(int $event_id, array $activity)
278 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
280 $event['edited'] = DateTimeFormat::utc($activity['updated']);
281 $event['summary'] = HTML::toBBCode($activity['name']);
282 $event['desc'] = HTML::toBBCode($activity['content']);
283 if (!empty($activity['start-time'])) {
284 $event['start'] = DateTimeFormat::utc($activity['start-time']);
286 if (!empty($activity['end-time'])) {
287 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
289 $event['nofinish'] = empty($event['finish']);
290 $event['location'] = $activity['location'];
292 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
293 Event::store($event);
297 * Prepares data for a message
299 * @param array $activity Activity array
300 * @param bool $fetch_parents
302 * @return array Internal item
304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305 * @throws \ImagickException
307 public static function createItem(array $activity, bool $fetch_parents): array
310 $item['verb'] = Activity::POST;
311 $item['thr-parent'] = $activity['reply-to-id'];
313 if ($activity['reply-to-id'] == $activity['id']) {
314 $item['gravity'] = Item::GRAVITY_PARENT;
315 $item['object-type'] = Activity\ObjectType::NOTE;
317 $item['gravity'] = Item::GRAVITY_COMMENT;
318 $item['object-type'] = Activity\ObjectType::COMMENT;
321 if (!empty($activity['conversation'])) {
322 $item['conversation'] = $activity['conversation'];
323 } elseif (!empty($activity['context'])) {
324 $item['conversation'] = $activity['context'];
327 if (!empty($item['conversation'])) {
328 $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]);
329 if (!empty($conversation)) {
330 Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]);
331 $item['parent-uri'] = $conversation['uri'];
332 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
338 Logger::debug('Create Item', ['id' => $activity['id'], 'conversation' => $item['conversation'] ?? '']);
339 if (empty($activity['author']) && empty($activity['actor'])) {
340 Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]);
341 Queue::remove($activity);
345 if (!in_array(0, $activity['receiver']) || !DI::config()->get('system', 'fetch_parents')) {
346 $fetch_parents = false;
349 if ($fetch_parents && empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
350 $result = self::fetchParent($activity, !empty($conversation));
351 if (!empty($result) && ($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
352 $item['thr-parent'] = $result;
356 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
358 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != Item::GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
359 Logger::notice('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
360 if (!$fetch_parents) {
361 Queue::remove($activity);
366 $item['network'] = Protocol::ACTIVITYPUB;
367 $item['author-link'] = $activity['author'];
368 $item['author-id'] = Contact::getIdForURL($activity['author']);
369 $item['owner-link'] = $activity['actor'];
370 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
372 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
373 $item['private'] = Item::UNLISTED;
374 } elseif (in_array(0, $activity['receiver'])) {
375 $item['private'] = Item::PUBLIC;
377 $item['private'] = Item::PRIVATE;
380 if (!empty($activity['raw'])) {
381 $item['source'] = $activity['raw'];
384 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
386 if (isset($activity['push'])) {
387 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
390 if (!empty($activity['from-relay'])) {
391 $item['direction'] = Conversation::RELAY;
394 if ($activity['object_type'] == 'as:Article') {
395 $item['post-type'] = Item::PT_ARTICLE;
396 } elseif ($activity['object_type'] == 'as:Audio') {
397 $item['post-type'] = Item::PT_AUDIO;
398 } elseif ($activity['object_type'] == 'as:Document') {
399 $item['post-type'] = Item::PT_DOCUMENT;
400 } elseif ($activity['object_type'] == 'as:Event') {
401 $item['post-type'] = Item::PT_EVENT;
402 } elseif ($activity['object_type'] == 'as:Image') {
403 $item['post-type'] = Item::PT_IMAGE;
404 } elseif ($activity['object_type'] == 'as:Page') {
405 $item['post-type'] = Item::PT_PAGE;
406 } elseif ($activity['object_type'] == 'as:Question') {
407 $item['post-type'] = Item::PT_POLL;
408 } elseif ($activity['object_type'] == 'as:Video') {
409 $item['post-type'] = Item::PT_VIDEO;
411 $item['post-type'] = Item::PT_NOTE;
414 $item['isGroup'] = false;
416 if (!empty($activity['thread-completion'])) {
417 if ($activity['thread-completion'] != $item['owner-id']) {
418 $actor = Contact::getById($activity['thread-completion'], ['url']);
419 $item['causer-link'] = $actor['url'];
420 $item['causer-id'] = $activity['thread-completion'];
421 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
423 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
424 $item['causer-link'] = $item['owner-link'];
425 $item['causer-id'] = $item['owner-id'];
426 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
429 $item['owner-link'] = $item['author-link'];
430 $item['owner-id'] = $item['author-id'];
433 if (!$item['isGroup'] && !empty($activity['receiver_urls']['as:audience'])) {
434 foreach ($activity['receiver_urls']['as:audience'] as $audience) {
435 $actor = APContact::getByURL($audience, false);
436 if (($actor['type'] ?? 'Person') == 'Group') {
437 Logger::debug('Group post detected via audience.', ['audience' => $audience, 'actor' => $activity['actor'], 'author' => $activity['author']]);
438 $item['isGroup'] = true;
439 $item['group-link'] = $item['owner-link'] = $audience;
440 $item['owner-id'] = Contact::getIdForURL($audience);
445 $owner = APContact::getByURL($item['owner-link'], false);
448 if (!$item['isGroup'] && (($owner['type'] ?? 'Person') == 'Group')) {
449 Logger::debug('Group post detected via owner.', ['actor' => $activity['actor'], 'author' => $activity['author']]);
450 $item['isGroup'] = true;
451 $item['group-link'] = $item['owner-link'];
452 } elseif (!empty($item['causer-link'])) {
453 $causer = APContact::getByURL($item['causer-link'], false);
456 if (!$item['isGroup'] && (($causer['type'] ?? 'Person') == 'Group')) {
457 Logger::debug('Group post detected via causer.', ['actor' => $activity['actor'], 'author' => $activity['author'], 'causer' => $item['causer-link']]);
458 $item['isGroup'] = true;
459 $item['group-link'] = $item['causer-link'];
462 if (!empty($item['group-link']) && empty($item['causer-link'])) {
463 $item['causer-link'] = $item['group-link'];
464 $item['causer-id'] = Contact::getIdForURL($item['causer-link']);
467 $item['uri'] = $activity['id'];
469 if (empty($activity['published']) || empty($activity['updated'])) {
470 DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity]);
473 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
474 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
475 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
476 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
478 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
479 if (empty($item['uri-id'])) {
480 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
484 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
486 $item = self::processContent($activity, $item);
488 Logger::info('Message was not processed');
489 Queue::remove($activity);
493 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
495 self::storeAttachments($activity, $item);
496 self::storeQuestion($activity, $item);
498 // We received the post via AP, so we set the protocol of the server to AP
499 $contact = Contact::getById($item['author-id'], ['gsid']);
500 if (!empty($contact['gsid'])) {
501 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
504 if ($item['author-id'] != $item['owner-id']) {
505 $contact = Contact::getById($item['owner-id'], ['gsid']);
506 if (!empty($contact['gsid'])) {
507 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
515 * Fetch and process parent posts for the given activity
517 * @param array $activity
518 * @param bool $in_background
522 private static function fetchParent(array $activity, bool $in_background = false): string
524 if (self::isFetched($activity['reply-to-id'])) {
525 Logger::info('Id is already fetched', ['id' => $activity['reply-to-id']]);
529 self::addActivityId($activity['reply-to-id']);
531 $completion = $activity['completion-mode'] ?? Receiver::COMPLETION_NONE;
533 if (DI::config()->get('system', 'decoupled_receiver') && ($completion != Receiver::COMPLETION_MANUAL)) {
534 $in_background = true;
537 $recursion_depth = $activity['recursion-depth'] ?? 0;
539 if (!$in_background && ($recursion_depth < DI::config()->get('system', 'max_recursion_depth'))) {
540 Logger::info('Parent not found. Try to refetch it.', ['completion' => $completion, 'recursion-depth' => $recursion_depth, 'parent' => $activity['reply-to-id']]);
541 $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
542 if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
543 Logger::notice('The activity is gone, the queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
544 if (!empty($activity['entry-id'])) {
545 Queue::deleteById($activity['entry-id']);
547 } elseif (!empty($result)) {
548 $post = Post::selectFirstPost(['uri'], ['uri' => [$result, $activity['reply-to-id']]]);
549 if (!empty($post['uri'])) {
550 Logger::info('The activity has been fetched and created.', ['result' => $result, 'uri' => $post['uri']]);
553 Logger::notice('The activity exists but has not been created, the queue entry will be deleted.', ['parent' => $result]);
554 if (!empty($activity['entry-id'])) {
555 Queue::deleteById($activity['entry-id']);
560 } elseif (self::isActivityGone($activity['reply-to-id'])) {
561 Logger::notice('The activity is gone. We will not spawn a worker. The queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
562 if ($in_background) {
563 // fetching in background is done for all activities where we have got the conversation
564 // There we only delete the single activity and not the whole thread since we can store the
565 // other posts in the thread even with missing posts.
566 Queue::remove($activity);
567 } elseif (!empty($activity['entry-id'])) {
568 Queue::deleteById($activity['entry-id']);
571 } elseif ($in_background) {
572 Logger::notice('Fetching is done in the background.', ['parent' => $activity['reply-to-id']]);
574 Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
577 if (!Fetch::hasWorker($activity['reply-to-id'])) {
578 Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
579 Fetch::add($activity['reply-to-id']);
580 $activity['recursion-depth'] = 0;
581 $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_ASYNC);
582 Fetch::setWorkerId($activity['reply-to-id'], $wid);
584 Logger::debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]);
591 * Check if a given activity is no longer available
597 public static function isActivityGone(string $url): bool
600 $curlResult = HTTPSignature::fetchRaw($url, 0);
601 } catch (\Exception $exception) {
602 Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
606 if (Network::isUrlBlocked($url)) {
610 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
611 if (in_array($curlResult->getReturnCode(), [401, 404])) {
615 if ($curlResult->isSuccess()) {
616 $object = json_decode($curlResult->getBody(), true);
617 if (!empty($object)) {
618 $activity = JsonLD::compact($object);
619 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
623 } elseif ($curlResult->getReturnCode() == 0) {
624 $host = parse_url($url, PHP_URL_HOST);
625 if (!(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) {
635 * @param array $activity
636 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 * @throws \ImagickException
639 public static function deleteItem(array $activity)
641 $owner = Contact::getIdForURL($activity['actor']);
643 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
644 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
645 Queue::remove($activity);
649 * Prepare the item array for an activity
651 * @param array $activity Activity array
652 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
653 * @throws \ImagickException
655 public static function addTag(array $activity)
657 if (empty($activity['object_content']) || empty($activity['object_id'])) {
661 foreach ($activity['receiver'] as $receiver) {
662 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
663 if (!DBA::isResult($item)) {
664 // We don't fetch missing content for this purpose
668 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
669 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
673 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
674 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
679 * Prepare the item array for an activity
681 * @param array $activity Activity array
682 * @param string $verb Activity verb
683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
684 * @throws \ImagickException
686 public static function createActivity(array $activity, string $verb)
688 $activity['reply-to-id'] = $activity['object_id'];
689 $item = self::createItem($activity, false);
691 Logger::debug('Activity was not prepared', ['id' => $activity['object_id']]);
695 $item['verb'] = $verb;
696 $item['thr-parent'] = $activity['object_id'];
697 $item['gravity'] = Item::GRAVITY_ACTIVITY;
698 unset($item['post-type']);
699 $item['object-type'] = Activity\ObjectType::NOTE;
701 if (!empty($activity['content'])) {
702 $item['body'] = HTML::toBBCode($activity['content']);
705 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
707 self::postItem($activity, $item);
711 * Fetch the Uri-Id of a post for the "featured" collection
713 * @param array $activity
716 private static function getUriIdForFeaturedCollection(array $activity)
718 $actor = APContact::getByURL($activity['actor']);
723 // Refetch the account when the "featured" collection is missing.
724 // This can be removed in a future version (end of 2022 should be good).
725 if (empty($actor['featured'])) {
726 $actor = APContact::getByURL($activity['actor'], true);
732 $parent = Post::selectFirst(['uri-id', 'author-id'], ['uri' => $activity['object_id']]);
733 if (empty($parent['uri-id'])) {
734 if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
735 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
739 if (!empty($parent['uri-id'])) {
747 * Add a post to the "Featured" collection
749 * @param array $activity
751 public static function addToFeaturedCollection(array $activity)
753 $post = self::getUriIdForFeaturedCollection($activity);
758 Logger::debug('Add post to featured collection', ['post' => $post]);
760 Post\Collection::add($post['uri-id'], Post\Collection::FEATURED, $post['author-id']);
761 Queue::remove($activity);
765 * Remove a post to the "Featured" collection
767 * @param array $activity
769 public static function removeFromFeaturedCollection(array $activity)
771 $post = self::getUriIdForFeaturedCollection($activity);
773 Queue::remove($activity);
777 Logger::debug('Remove post from featured collection', ['post' => $post]);
779 Post\Collection::remove($post['uri-id'], Post\Collection::FEATURED);
780 Queue::remove($activity);
786 * @param array $activity Activity array
789 * @return int event id
792 public static function createEvent(array $activity, array $item): int
794 $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']);
795 $event['desc'] = HTML::toBBCode($activity['content'] ?? '');
796 if (!empty($activity['start-time'])) {
797 $event['start'] = DateTimeFormat::utc($activity['start-time']);
799 if (!empty($activity['end-time'])) {
800 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
802 $event['nofinish'] = empty($event['finish']);
803 $event['location'] = $activity['location'];
804 $event['cid'] = $item['contact-id'];
805 $event['uid'] = $item['uid'];
806 $event['uri'] = $item['uri'];
807 $event['edited'] = $item['edited'];
808 $event['private'] = $item['private'];
809 $event['guid'] = $item['guid'];
810 $event['plink'] = $item['plink'];
811 $event['network'] = $item['network'];
812 $event['protocol'] = $item['protocol'];
813 $event['direction'] = $item['direction'];
814 $event['source'] = $item['source'];
816 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
817 if (DBA::isResult($ev)) {
818 $event['id'] = $ev['id'];
821 $event_id = Event::store($event);
823 Logger::info('Event was stored', ['id' => $event_id]);
829 * Process the content
831 * @param array $activity Activity array
833 * @return array|bool Returns the item array or false if there was an unexpected occurrence
836 private static function processContent(array $activity, array $item)
838 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
839 $item['title'] = strip_tags($activity['name'] ?? '');
840 $content = Markdown::toBBCode($activity['content']);
841 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
842 $item['title'] = $activity['name'];
843 $content = $activity['content'];
845 // By default assume "text/html"
846 $item['title'] = HTML::toBBCode($activity['name'] ?? '');
847 $content = HTML::toBBCode($activity['content'] ?? '');
850 $item['title'] = trim(BBCode::toPlaintext($item['title']));
852 if (!empty($activity['languages'])) {
853 $item['language'] = self::processLanguages($activity['languages']);
856 if (!empty($activity['emojis'])) {
857 $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
860 $content = self::addMentionLinks($content, $activity['tags']);
862 if (!empty($activity['quote-url'])) {
863 $id = Item::fetchByLink($activity['quote-url'], 0, ActivityPub\Receiver::COMPLETION_ASYNC);
865 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
866 $item['quote-uri-id'] = $shared_item['uri-id'];
867 } elseif ($uri_id = ItemURI::getIdByURI($activity['quote-url'], false)) {
868 Logger::info('Quote was not fetched but the uri-id existed', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url'], 'uri-id' => $uri_id]);
869 $item['quote-uri-id'] = $uri_id;
871 Logger::info('Quote was not fetched', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url']]);
875 if (!empty($activity['source'])) {
876 $item['body'] = $activity['source'];
877 $item['raw-body'] = $content;
879 $quote_uri_id = Item::getQuoteUriId($item['body']);
880 if (empty($item['quote-uri-id']) && !empty($quote_uri_id)) {
881 $item['quote-uri-id'] = $quote_uri_id;
884 $item['body'] = BBCode::removeSharedData($item['body']);
886 $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
887 if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == Item::GRAVITY_COMMENT)) {
888 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
889 if (!DBA::isResult($parent)) {
890 Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
893 $content = self::removeImplicitMentionsFromBody($content, $parent);
895 $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
896 $item['raw-body'] = $item['body'] = $content;
899 if (!empty($item['author-id']) && ($item['author-id'] == $item['owner-id'])) {
900 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
901 $actor = APContact::getByURL($tag[2], false);
902 if (($actor['type'] ?? 'Person') == 'Group') {
903 Logger::debug('Group post detected via exclusive mention.', ['mention' => $actor['url'], 'actor' => $activity['actor'], 'author' => $activity['author']]);
904 $item['isGroup'] = true;
905 $item['group-link'] = $item['owner-link'] = $actor['url'];
906 $item['owner-id'] = Contact::getIdForURL($actor['url']);
912 self::storeFromBody($item);
913 self::storeTags($item['uri-id'], $activity['tags']);
915 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
917 $item['location'] = $activity['location'];
919 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
920 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
923 $item['app'] = $activity['generator'];
929 * Store hashtags and mentions
933 private static function storeFromBody(array $item)
935 // Make sure to delete all existing tags (can happen when called via the update functionality)
936 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
938 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
942 * Generate a GUID out of an URL of an ActivityPub post.
944 * @param string $url message URL
945 * @return string with GUID
947 private static function getGUIDByURL(string $url): string
949 $parsed = parse_url($url);
951 $host_hash = hash('crc32', $parsed['host']);
953 unset($parsed["scheme"]);
954 unset($parsed["host"]);
956 $path = implode("/", $parsed);
958 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
962 * Checks if an incoming message is wanted
964 * @param array $activity
966 * @return boolean Is the message wanted?
968 private static function isSolicitedMessage(array $activity, array $item): bool
970 // The checks are split to improve the support when searching why a message was accepted.
971 if (count($activity['receiver']) != 1) {
972 // The message has more than one receiver, so it is wanted.
973 Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
977 if ($item['private'] == Item::PRIVATE) {
978 // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
979 Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
983 if (!empty($activity['from-relay'])) {
984 // We check relay posts at another place. When it arrived here, the message is already checked.
985 Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
989 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUNCE])) {
990 // Manual completions and completions caused by reshares are allowed without any further checks.
991 Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
995 if ($item['gravity'] != Item::GRAVITY_PARENT) {
996 // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
997 // This can possibly be improved in the future.
998 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
1002 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
1003 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB, $activity['thread-completion'] ?? 0)) {
1004 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
1012 * Creates an item post
1014 * @param array $activity Activity data
1015 * @param array $item item array
1016 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1017 * @throws \ImagickException
1019 public static function postItem(array $activity, array $item)
1027 ksort($activity['receiver']);
1029 if (!self::isSolicitedMessage($activity, $item)) {
1030 DBA::delete('item-uri', ['id' => $item['uri-id']]);
1031 if (!empty($activity['entry-id'])) {
1032 Queue::deleteById($activity['entry-id']);
1037 foreach ($activity['receiver'] as $receiver) {
1038 if ($receiver == -1) {
1042 if (($receiver != 0) && empty($item['parent-uri-id']) && !empty($item['thr-parent-id'])) {
1043 $parent = Post::selectFirst(['parent-uri-id', 'parent-uri'], ['uri-id' => $item['thr-parent-id'], 'uid' => [0, $receiver]]);
1044 if (!empty($parent['parent-uri-id'])) {
1045 $item['parent-uri-id'] = $parent['parent-uri-id'];
1046 $item['parent-uri'] = $parent['parent-uri'];
1050 $item['uid'] = $receiver;
1052 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
1054 case Receiver::TARGET_TO:
1055 $item['post-reason'] = Item::PR_TO;
1057 case Receiver::TARGET_CC:
1058 $item['post-reason'] = Item::PR_CC;
1060 case Receiver::TARGET_BTO:
1061 $item['post-reason'] = Item::PR_BTO;
1063 case Receiver::TARGET_BCC:
1064 $item['post-reason'] = Item::PR_BCC;
1066 case Receiver::TARGET_AUDIENCE:
1067 $item['post-reason'] = Item::PR_AUDIENCE;
1069 case Receiver::TARGET_FOLLOWER:
1070 $item['post-reason'] = Item::PR_FOLLOWER;
1072 case Receiver::TARGET_ANSWER:
1073 $item['post-reason'] = Item::PR_COMMENT;
1075 case Receiver::TARGET_GLOBAL:
1076 $item['post-reason'] = Item::PR_GLOBAL;
1079 $item['post-reason'] = Item::PR_NONE;
1082 $item['post-reason'] = Item::getPostReason($item);
1084 if (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE])) {
1085 if (!empty($activity['from-relay'])) {
1086 $item['post-reason'] = Item::PR_RELAY;
1087 } elseif (!empty($activity['thread-completion'])) {
1088 $item['post-reason'] = Item::PR_FETCHED;
1089 } elseif (!empty($activity['push'])) {
1090 $item['post-reason'] = Item::PR_PUSHED;
1092 } elseif (($item['post-reason'] == Item::PR_FOLLOWER) && !empty($activity['from-relay'])) {
1093 // When a post arrives via a relay and we follow the author, we have to override the causer.
1094 // Otherwise the system assumes that we follow the relay. (See "addRowInformation")
1095 Logger::debug('Relay post for follower', ['receiver' => $receiver, 'guid' => $item['guid'], 'relay' => $activity['from-relay']]);
1096 $item['causer-id'] = ($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1099 if ($item['isGroup']) {
1100 $item['contact-id'] = Contact::getIdForURL($item['group-link'], $receiver);
1102 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $receiver);
1105 if (($receiver != 0) && empty($item['contact-id'])) {
1106 $item['contact-id'] = Contact::getIdForURL($activity['author']);
1109 if (!empty($activity['directmessage']) && self::postMail($item)) {
1113 if (($receiver != 0) && ($item['gravity'] == Item::GRAVITY_PARENT) && !in_array($item['post-reason'], [Item::PR_FOLLOWER, Item::PR_TAG, item::PR_TO, Item::PR_CC, Item::PR_AUDIENCE])) {
1114 if (!$item['isGroup']) {
1115 if ($item['post-reason'] == Item::PR_BCC) {
1116 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id'], 'url' => $item['uri']]);
1120 if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE)
1121 && in_array($activity['thread-children-type'] ?? '', Receiver::ACTIVITY_TYPES)) {
1122 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
1123 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
1129 $user = User::getById($receiver, ['account-type']);
1130 if (!empty($user['account-type'])) {
1131 $isGroup = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
1134 if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE)
1135 && ((!$isGroup && !$item['isGroup'] && ($activity['type'] != 'as:Announce'))
1136 || !Contact::isSharingByURL($activity['actor'], $receiver))) {
1137 Logger::info('Actor is a non sharer, is no group or it is no announce', ['uid' => $receiver, 'actor' => $activity['actor'], 'url' => $item['uri'], 'type' => $activity['type']]);
1141 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
1144 if (!self::hasParents($item, $receiver)) {
1148 if (($item['gravity'] != Item::GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
1149 $event_id = self::createEvent($activity, $item);
1151 $item = Event::getItemArrayForImportedId($event_id, $item);
1154 $item_id = Item::insert($item);
1156 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
1159 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
1160 if (($item['uid'] == 0) && (count($activity['receiver']) > 1)) {
1161 Logger::info('Public item was aborted. We skip for all users.', ['uri' => $item['uri']]);
1166 if ($item['uid'] == 0) {
1171 Queue::remove($activity);
1173 if ($success && Queue::hasChildren($item['uri']) && Post::exists(['uri' => $item['uri']])) {
1174 Queue::processReplyByUri($item['uri']);
1177 // Store send a follow request for every reshare - but only when the item had been stored
1178 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == Item::GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
1179 $author = APContact::getByURL($item['owner-link'], false);
1180 // We send automatic follow requests for reshared messages. (We don't need though for group posts)
1181 if ($author['type'] != 'Group') {
1182 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
1183 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
1189 * Checks if there are parent posts for the given receiver.
1190 * If not, then the system will try to add them.
1192 * @param array $item
1193 * @param integer $receiver
1196 private static function hasParents(array $item, int $receiver)
1198 if (($receiver == 0) || ($item['gravity'] == Item::GRAVITY_PARENT)) {
1202 $fields = ['causer-id' => $item['causer-id'] ?? $item['author-id'], 'post-reason' => Item::PR_FETCHED];
1206 if ($item['verb'] != Activity::ANNOUNCE) {
1207 switch (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer')) {
1208 case Item::COMPLETION_COMMENT:
1209 $add_parent = ($item['gravity'] != Item::GRAVITY_ACTIVITY);
1212 case Item::COMPLETION_NONE:
1213 $add_parent = false;
1219 $add_parent = Contact::isSharing($fields['causer-id'], $receiver);
1220 if (!$add_parent && ($item['author-id'] != $fields['causer-id'])) {
1221 $add_parent = Contact::isSharing($item['author-id'], $receiver);
1223 if (!$add_parent && !in_array($item['owner-id'], [$fields['causer-id'], $item['author-id']])) {
1224 $add_parent = Contact::isSharing($item['owner-id'], $receiver);
1228 $has_parents = false;
1230 if (!empty($item['parent-uri-id'])) {
1231 if (Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $receiver])) {
1232 $has_parents = true;
1233 } elseif ($add_parent && Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1234 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $receiver, $fields);
1235 $has_parents = (bool)$stored;
1237 Logger::notice('Inserted missing parent post', ['stored' => $stored, 'uid' => $receiver, 'parent' => $item['parent-uri']]);
1239 Logger::notice('Parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1242 } elseif ($add_parent) {
1243 Logger::debug('Parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1245 Logger::debug('Parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1249 if (empty($item['parent-uri-id']) || ($item['thr-parent-id'] != $item['parent-uri-id'])) {
1250 if (Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $receiver])) {
1251 $has_parents = true;
1252 } elseif (($has_parents || $add_parent) && Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => 0])) {
1253 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $receiver, $fields);
1254 $has_parents = $has_parents || (bool)$stored;
1256 Logger::notice('Inserted missing thread parent post', ['stored' => $stored, 'uid' => $receiver, 'thread-parent' => $item['thr-parent']]);
1258 Logger::notice('Thread parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1260 } elseif ($add_parent) {
1261 Logger::debug('Thread parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1263 Logger::debug('Thread parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1267 return $has_parents;
1271 * Store tags and mentions into the tag table
1273 * @param integer $uriid
1274 * @param array $tags
1276 private static function storeTags(int $uriid, array $tags = null)
1278 foreach ($tags as $tag) {
1279 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1283 $hash = substr($tag['name'], 0, 1);
1285 if ($tag['type'] == 'Mention') {
1286 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1287 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1288 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1289 $tag['name'] = substr($tag['name'], 1);
1291 $type = Tag::IMPLICIT_MENTION;
1293 if (!empty($tag['href'])) {
1294 $apcontact = APContact::getByURL($tag['href']);
1295 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1296 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1299 } elseif ($tag['type'] == 'Hashtag') {
1300 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1301 $tag['name'] = substr($tag['name'], 1);
1303 $type = Tag::HASHTAG;
1306 if (empty($tag['name'])) {
1310 Tag::store($uriid, $type, $tag['name'], $tag['href']);
1314 public static function storeReceivers(int $uriid, array $receivers)
1316 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC, 'as:audience' => Tag::AUDIENCE, 'as:attributedTo' => Tag::ATTRIBUTED] as $element => $type) {
1317 if (!empty($receivers[$element])) {
1318 foreach ($receivers[$element] as $receiver) {
1319 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1320 $name = Receiver::PUBLIC_COLLECTION;
1321 } elseif ($path = parse_url($receiver, PHP_URL_PATH)) {
1322 $name = trim($path, '/');
1323 } elseif ($host = parse_url($receiver, PHP_URL_HOST)) {
1326 Logger::warning('Unable to coerce name from receiver', ['element' => $element, 'type' => $type, 'receiver' => $receiver]);
1330 $target = Tag::getTargetType($receiver);
1331 Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1332 Tag::store($uriid, $type, $name, $receiver, $target);
1339 * Creates an mail post
1341 * @param array $item item array
1342 * @return int|bool New mail table row id or false on error
1343 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1345 private static function postMail(array $item): bool
1347 if (($item['gravity'] != Item::GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1348 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1352 if (!Contact::isFollower($item['contact-id'], $item['uid']) && !Contact::isSharing($item['contact-id'], $item['uid'])) {
1353 Logger::info('Contact is not a sharer or follower, mail will be discarded.', ['item' => $item]);
1357 Logger::info('Direct Message', $item);
1360 $msg['uid'] = $item['uid'];
1362 $msg['contact-id'] = $item['contact-id'];
1364 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1365 $msg['from-name'] = $contact['name'];
1366 $msg['from-url'] = $contact['url'];
1367 $msg['from-photo'] = $contact['photo'];
1369 $msg['uri'] = $item['uri'];
1370 $msg['created'] = $item['created'];
1372 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1373 if (DBA::isResult($parent)) {
1374 $msg['parent-uri'] = $parent['parent-uri'];
1375 $msg['title'] = $parent['title'];
1377 $msg['parent-uri'] = $item['thr-parent'];
1379 if (!empty($item['title'])) {
1380 $msg['title'] = $item['title'];
1381 } elseif (!empty($item['content-warning'])) {
1382 $msg['title'] = $item['content-warning'];
1384 // Trying to generate a title out of the body
1385 $title = $item['body'];
1387 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1388 $title = $matches[3];
1391 $title = trim(BBCode::toPlaintext($title));
1393 if (strlen($title) > 20) {
1394 $title = substr($title, 0, 20) . '...';
1397 $msg['title'] = $title;
1400 $msg['body'] = $item['body'];
1402 return Mail::insert($msg);
1406 * Fetch featured posts from a contact with the given url
1408 * @param string $url
1411 public static function fetchFeaturedPosts(string $url)
1413 Logger::info('Fetch featured posts', ['contact' => $url]);
1415 $apcontact = APContact::getByURL($url);
1416 if (empty($apcontact['featured'])) {
1417 Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1421 $pcid = Contact::getIdForURL($url, 0, false);
1423 Logger::notice('Contact not found', ['contact' => $url]);
1427 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1428 if (!empty($posts)) {
1429 $old_featured = array_column($posts, 'uri-id');
1434 $featured = ActivityPub::fetchItems($apcontact['featured']);
1435 if (empty($featured)) {
1436 Logger::info('Contact does not have featured posts', ['contact' => $url]);
1438 foreach ($old_featured as $uri_id) {
1439 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1440 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1448 foreach ($featured as $post) {
1449 if (empty($post['id'])) {
1452 $id = Item::fetchByLink($post['id'], 0, ActivityPub\Receiver::COMPLETION_ASYNC);
1454 $item = Post::selectFirst(['uri-id', 'featured', 'author-id'], ['id' => $id]);
1455 if (!empty($item['uri-id'])) {
1456 if (!$item['featured']) {
1457 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED, $item['author-id']);
1458 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1461 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1465 $index = array_search($item['uri-id'], $old_featured);
1466 if (!($index === false)) {
1467 unset($old_featured[$index]);
1473 foreach ($old_featured as $uri_id) {
1474 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1475 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1478 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1481 public static function fetchCachedActivity(string $url, int $uid): array
1483 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . hash('sha256', $url);
1484 $object = DI::cache()->get($cachekey);
1486 if (!is_null($object)) {
1487 if (!empty($object)) {
1488 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1490 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1495 $object = ActivityPub::fetchContent($url, $uid);
1496 if (empty($object)) {
1497 Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1498 // We perform negative caching.
1499 DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1503 if (empty($object['id'])) {
1504 Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1507 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1509 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1515 * Fetches missing posts
1517 * @param string $url message URL
1518 * @param array $child activity array with the child of this message
1519 * @param string $relay_actor Relay actor
1520 * @param int $completion Completion mode, see Receiver::COMPLETION_*
1521 * @param int $uid User id that is used to fetch the activity
1522 * @return string fetched message URL
1523 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1524 * @throws \ImagickException
1526 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL, int $uid = 0): string
1528 $object = self::fetchCachedActivity($url, $uid);
1529 if (empty($object)) {
1535 if (!empty($object['attributedTo'])) {
1536 $attributed_to = $object['attributedTo'];
1537 if (is_array($attributed_to)) {
1538 $compacted = JsonLD::compact($object);
1539 $attributed_to = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1541 $signer[] = $attributed_to;
1544 if (!empty($object['actor'])) {
1545 $object_actor = $object['actor'];
1546 } elseif (!empty($attributed_to)) {
1547 $object_actor = $attributed_to;
1553 $signer[] = $object_actor;
1555 if (!empty($child['author'])) {
1556 $actor = $child['author'];
1559 $actor = $object_actor;
1562 if (!empty($object['published'])) {
1563 $published = $object['published'];
1564 } elseif (!empty($child['published'])) {
1565 $published = $child['published'];
1567 $published = DateTimeFormat::utcNow();
1571 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1572 unset($object['@context']);
1573 $activity['id'] = $object['id'];
1574 $activity['to'] = $object['to'] ?? [];
1575 $activity['cc'] = $object['cc'] ?? [];
1576 $activity['audience'] = $object['audience'] ?? [];
1577 $activity['actor'] = $actor;
1578 $activity['object'] = $object;
1579 $activity['published'] = $published;
1580 $activity['type'] = 'Create';
1582 $ldactivity = JsonLD::compact($activity);
1584 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 0;
1586 if ($object_actor != $actor) {
1587 Contact::updateByUrlIfNeeded($object_actor);
1590 Contact::updateByUrlIfNeeded($actor);
1592 if (!empty($child['thread-completion'])) {
1593 $ldactivity['thread-completion'] = $child['thread-completion'];
1594 $ldactivity['completion-mode'] = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1596 $ldactivity['thread-completion'] = Contact::getIdForURL($relay_actor ?: $actor);
1597 $ldactivity['completion-mode'] = $completion;
1600 if ($completion == Receiver::COMPLETION_RELAY) {
1601 $ldactivity['from-relay'] = $ldactivity['thread-completion'];
1602 if (!self::acceptIncomingMessage($ldactivity, $object['id'])) {
1607 if (!empty($child['thread-children-type'])) {
1608 $ldactivity['thread-children-type'] = $child['thread-children-type'];
1609 } elseif (!empty($child['type'])) {
1610 $ldactivity['thread-children-type'] = $child['type'];
1612 $ldactivity['thread-children-type'] = 'as:Create';
1615 if (($completion == Receiver::COMPLETION_RELAY) && Queue::exists($url, 'as:Create')) {
1616 Logger::info('Activity has already been queued.', ['url' => $url, 'object' => $activity['id']]);
1617 } elseif (ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer, '', $completion)) {
1618 Logger::info('Activity had been fetched and processed.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1620 Logger::info('Activity had been fetched and will be processed later.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1623 return $activity['id'];
1627 * Test if incoming relay messages should be accepted
1629 * @param array $activity activity array
1630 * @param string $id object ID
1631 * @return boolean true if message is accepted
1633 private static function acceptIncomingMessage(array $activity, string $id): bool
1635 if (empty($activity['as:object'])) {
1636 Logger::info('No object field in activity - accepted', ['id' => $id]);
1640 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1641 $uriid = ItemURI::getIdByURI($replyto ?? '');
1642 if (Post::exists(['uri-id' => $uriid])) {
1643 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1647 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1648 $authorid = Contact::getIdForURL($attributed_to);
1650 $content = JsonLD::fetchElement($activity['as:object'], 'as:name', '@value') ?? '';
1651 $content .= ' ' . JsonLD::fetchElement($activity['as:object'], 'as:summary', '@value') ?? '';
1652 $content .= ' ' . HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1654 $attachments = JsonLD::fetchElementArray($activity['as:object'], 'as:attachment') ?? [];
1655 foreach ($attachments as $media) {
1656 if (!empty($media['as:summary'])) {
1657 $content .= ' ' . JsonLD::fetchElement($media, 'as:summary', '@value');
1659 if (!empty($media['as:name'])) {
1660 $content .= ' ' . JsonLD::fetchElement($media, 'as:name', '@value');
1665 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1666 if (!empty($tags)) {
1667 foreach ($tags as $tag) {
1668 if (($tag['type'] != 'Hashtag') && !strpos($tag['type'], ':Hashtag')) {
1671 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1675 return Relay::isSolicitedPost($messageTags, $content, $authorid, $id, Protocol::ACTIVITYPUB, $activity['thread-completion'] ?? 0);
1679 * perform a "follow" request
1681 * @param array $activity
1683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1684 * @throws \ImagickException
1686 public static function followUser(array $activity)
1688 $uid = User::getIdForURL($activity['object_id']);
1690 Queue::remove($activity);
1694 $owner = User::getOwnerDataById($uid);
1695 if (empty($owner)) {
1699 $cid = Contact::getIdForURL($activity['actor'], $uid);
1701 self::switchContact($cid);
1702 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1706 'author-id' => Contact::getIdForURL($activity['actor']),
1707 'author-link' => $activity['actor'],
1710 // Ensure that the contact has got the right network type
1711 self::switchContact($item['author-id']);
1713 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1714 if ($result === true) {
1715 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1718 $cid = Contact::getIdForURL($activity['actor'], $uid);
1723 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1724 self::transmitPendingEvents($cid, $owner['uid']);
1727 if (empty($contact)) {
1728 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1730 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1731 Queue::remove($activity);
1735 * Transmit pending events to the new follower
1737 * @param integer $cid Contact id
1738 * @param integer $uid User id
1741 private static function transmitPendingEvents(int $cid, int $uid)
1743 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1744 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1746 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1747 while ($event = DBA::fetch($events)) {
1748 $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1752 if (DI::config()->get('system', 'bulk_delivery')) {
1753 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1754 Worker::add(Worker::PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1756 Worker::add(Worker::PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1762 * Update the given profile
1764 * @param array $activity
1765 * @throws \Exception
1767 public static function updatePerson(array $activity)
1769 if (empty($activity['object_id'])) {
1773 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1774 Contact::updateFromProbeByURL($activity['object_id']);
1775 Queue::remove($activity);
1779 * Delete the given profile
1781 * @param array $activity
1783 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1785 public static function deletePerson(array $activity)
1787 if (empty($activity['object_id']) || empty($activity['actor'])) {
1788 Logger::info('Empty object id or actor.');
1789 Queue::remove($activity);
1793 if ($activity['object_id'] != $activity['actor']) {
1794 Logger::info('Object id does not match actor.');
1795 Queue::remove($activity);
1799 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1800 while ($contact = DBA::fetch($contacts)) {
1801 Contact::remove($contact['id']);
1803 DBA::close($contacts);
1805 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1806 Queue::remove($activity);
1810 * Add moved contacts as followers for all subscribers of the old contact
1812 * @param array $activity
1814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1816 public static function movePerson(array $activity)
1818 if (empty($activity['target_id']) || empty($activity['object_id'])) {
1819 Queue::remove($activity);
1823 if ($activity['object_id'] != $activity['actor']) {
1824 Logger::notice('Object is not the actor', ['activity' => $activity]);
1825 Queue::remove($activity);
1829 $from = Contact::getByURL($activity['object_id'], false, ['uri-id']);
1830 if (empty($from['uri-id'])) {
1831 Logger::info('Object not found', ['activity' => $activity]);
1832 Queue::remove($activity);
1836 $contacts = DBA::select('contact', ['uid', 'url'], ["`uri-id` = ? AND `uid` != ? AND `rel` IN (?, ?)", $from['uri-id'], 0, Contact::FRIEND, Contact::SHARING]);
1837 while ($from_contact = DBA::fetch($contacts)) {
1838 $result = Contact::createFromProbeForUser($from_contact['uid'], $activity['target_id']);
1839 Logger::debug('Follower added', ['from' => $from_contact, 'result' => $result]);
1841 DBA::close($contacts);
1842 Queue::remove($activity);
1846 * Blocks the user by the contact
1848 * @param array $activity
1850 * @throws \Exception
1852 public static function blockAccount(array $activity)
1854 $cid = Contact::getIdForURL($activity['actor']);
1859 $uid = User::getIdForURL($activity['object_id']);
1864 Contact\User::setIsBlocked($cid, $uid, true);
1866 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1867 Queue::remove($activity);
1871 * Unblocks the user by the contact
1873 * @param array $activity
1875 * @throws \Exception
1877 public static function unblockAccount(array $activity)
1879 $cid = Contact::getIdForURL($activity['actor']);
1884 $uid = User::getIdForURL($activity['object_object']);
1889 Contact\User::setIsBlocked($cid, $uid, false);
1891 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1892 Queue::remove($activity);
1898 * @param array $activity
1900 * @throws \Exception
1902 public static function ReportAccount(array $activity)
1904 $account = Contact::getByURL($activity['object_id'], null, ['id', 'gsid']);
1905 if (empty($account)) {
1906 Logger::info('Unknown account', ['activity' => $activity]);
1907 Queue::remove($activity);
1911 $reporter_id = Contact::getIdForURL($activity['actor']);
1912 if (empty($reporter_id)) {
1913 Logger::info('Unknown actor', ['activity' => $activity]);
1914 Queue::remove($activity);
1919 foreach ($activity['object_ids'] as $status_id) {
1920 $post = Post::selectFirst(['uri-id'], ['uri' => $status_id]);
1921 if (!empty($post['uri-id'])) {
1922 $uri_ids[] = $post['uri-id'];
1926 $report = DI::reportFactory()->createFromReportsRequest(System::getRules(true), $reporter_id, $account['id'], $account['gsid'], $activity['content'], 'other', false, $uri_ids);
1927 DI::report()->save($report);
1929 Logger::info('Stored report', ['reporter' => $reporter_id, 'account' => $account, 'comment' => $activity['content'], 'object_ids' => $activity['object_ids']]);
1933 * Accept a follow request
1935 * @param array $activity
1936 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1937 * @throws \ImagickException
1939 public static function acceptFollowUser(array $activity)
1941 if (!empty($activity['object_actor'])) {
1942 $uid = User::getIdForURL($activity['object_actor']);
1944 } elseif (!empty($activity['receiver']) && (count($activity['receiver']) == 1)) {
1945 $uid = array_shift($activity['receiver']);
1950 Logger::notice('User could not be detected', ['activity' => $activity]);
1951 Queue::remove($activity);
1955 $cid = Contact::getIdForURL($activity['actor'], $uid);
1957 Logger::notice('No contact found', ['actor' => $activity['actor']]);
1958 Queue::remove($activity);
1962 $id = Transmitter::activityIDFromContact($cid);
1963 if ($id == $activity['object_id']) {
1964 Logger::info('Successful id check', ['uid' => $uid, 'cid' => $cid]);
1966 Logger::info('Unsuccessful id check', ['uid' => $uid, 'cid' => $cid, 'id' => $id, 'object_id' => $activity['object_id']]);
1968 Queue::remove($activity);
1973 self::switchContact($cid);
1975 $fields = ['pending' => false];
1977 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1978 if ($contact['rel'] == Contact::FOLLOWER) {
1979 $fields['rel'] = Contact::FRIEND;
1982 $condition = ['id' => $cid];
1983 Contact::update($fields, $condition);
1984 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1985 Queue::remove($activity);
1989 * Reject a follow request
1991 * @param array $activity
1992 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1993 * @throws \ImagickException
1995 public static function rejectFollowUser(array $activity)
1997 $uid = User::getIdForURL($activity['object_actor']);
2002 $cid = Contact::getIdForURL($activity['actor'], $uid);
2004 Logger::info('No contact found', ['actor' => $activity['actor']]);
2008 self::switchContact($cid);
2010 $contact = Contact::getById($cid, ['rel']);
2011 if ($contact['rel'] == Contact::SHARING) {
2012 Contact::remove($cid);
2013 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
2014 } elseif ($contact['rel'] == Contact::FRIEND) {
2015 Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
2017 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
2019 Queue::remove($activity);
2023 * Undo activity like "like" or "dislike"
2025 * @param array $activity
2026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2027 * @throws \ImagickException
2029 public static function undoActivity(array $activity)
2031 if (empty($activity['object_id'])) {
2035 if (empty($activity['object_actor'])) {
2039 $author_id = Contact::getIdForURL($activity['object_actor']);
2040 if (empty($author_id)) {
2044 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => Item::GRAVITY_ACTIVITY]);
2045 Queue::remove($activity);
2049 * Activity to remove a follower
2051 * @param array $activity
2052 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2053 * @throws \ImagickException
2055 public static function undoFollowUser(array $activity)
2057 $uid = User::getIdForURL($activity['object_object']);
2062 $owner = User::getOwnerDataById($uid);
2063 if (empty($owner)) {
2067 $cid = Contact::getIdForURL($activity['actor'], $uid);
2069 Logger::info('No contact found', ['actor' => $activity['actor']]);
2073 self::switchContact($cid);
2075 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2076 if (!DBA::isResult($contact)) {
2080 Contact::removeFollower($contact);
2081 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
2082 Queue::remove($activity);
2086 * Switches a contact to AP if needed
2088 * @param integer $cid Contact ID
2090 * @throws \Exception
2092 private static function switchContact(int $cid)
2094 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
2095 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
2099 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
2100 Contact::updateFromProbe($cid);
2104 * Collects implicit mentions like:
2105 * - the author of the parent item
2106 * - all the mentioned conversants in the parent item
2108 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
2110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2112 private static function getImplicitMentionList(array $parent): array
2114 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
2116 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
2118 $implicit_mentions = [];
2119 if (empty($parent_author['url'])) {
2120 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
2122 $implicit_mentions[] = $parent_author['url'];
2123 $implicit_mentions[] = $parent_author['nurl'];
2124 $implicit_mentions[] = $parent_author['alias'];
2127 if (!empty($parent['alias'])) {
2128 $implicit_mentions[] = $parent['alias'];
2131 foreach ($parent_terms as $term) {
2132 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
2133 if (!empty($contact['url'])) {
2134 $implicit_mentions[] = $contact['url'];
2135 $implicit_mentions[] = $contact['nurl'];
2136 $implicit_mentions[] = $contact['alias'];
2140 return $implicit_mentions;
2144 * Strips from the body prepended implicit mentions
2146 * @param string $body
2147 * @param array $parent
2150 private static function removeImplicitMentionsFromBody(string $body, array $parent): string
2152 if (DI::config()->get('system', 'disable_implicit_mentions')) {
2156 $potential_mentions = self::getImplicitMentionList($parent);
2158 $kept_mentions = [];
2160 // Extract one prepended mention at a time from the body
2161 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
2162 if (!in_array($matches[2], $potential_mentions)) {
2163 $kept_mentions[] = $matches[1];
2166 $body = $matches[3];
2169 // Re-appending the kept mentions to the body after extraction
2170 $kept_mentions[] = $body;
2172 return implode('', $kept_mentions);
2176 * Adds links to string mentions
2178 * @param string $body
2179 * @param array $tags
2182 protected static function addMentionLinks(string $body, array $tags): string
2184 // This prevents links to be added again to Pleroma-style mention links
2185 $body = self::normalizeMentionLinks($body);
2187 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
2188 foreach ($tags as $tag) {
2189 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
2193 $hash = substr($tag['name'], 0, 1);
2194 $name = substr($tag['name'], 1);
2195 if (!in_array($hash, Tag::TAG_CHARACTER)) {
2197 $name = $tag['name'];
2200 if (Network::isValidHttpUrl($tag['href'])) {
2201 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);