3 * @copyright Copyright (C) 2010-2022, 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;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Event;
37 use Friendica\Model\GServer;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Model\Post;
44 use Friendica\Network\HTTPException\InternalServerErrorException;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\ActivityPub;
47 use Friendica\Protocol\Relay;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\JsonLD;
50 use Friendica\Util\Strings;
53 * ActivityPub Processor Protocol class
58 * Extracts the tag character (#, @, !) from mention links
63 protected static function normalizeMentionLinks(string $body): string
65 return preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
69 * Convert the language array into a language JSON
71 * @param array $languages
72 * @return string language JSON
74 private static function processLanguages(array $languages)
76 $codes = array_keys($languages);
78 foreach ($codes as $code) {
86 return json_encode($lang);
89 * Replaces emojis in the body
91 * @param array $emojis
94 * @return string with replaced emojis
96 private static function replaceEmojis(int $uri_id, $body, array $emojis)
100 array_column($emojis, 'name'),
101 array_map(function ($emoji) {
102 return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
107 // We store the emoji here to be able to avoid storing it in the media
108 foreach ($emojis as $emoji) {
109 Post\Link::getByLink($uri_id, $emoji['href']);
115 * Store attached media files in the post-media table
118 * @param array $attachment
121 private static function storeAttachmentAsMedia(int $uriid, array $attachment)
123 if (empty($attachment['url'])) {
127 $data = ['uri-id' => $uriid];
128 $data['type'] = Post\Media::UNKNOWN;
129 $data['url'] = $attachment['url'];
130 $data['mimetype'] = $attachment['mediaType'] ?? null;
131 $data['height'] = $attachment['height'] ?? null;
132 $data['width'] = $attachment['width'] ?? null;
133 $data['size'] = $attachment['size'] ?? null;
134 $data['preview'] = $attachment['image'] ?? null;
135 $data['description'] = $attachment['name'] ?? null;
137 Post\Media::insert($data);
141 * Stire attachment data
143 * @param array $activity
146 private static function storeAttachments($activity, $item)
148 if (empty($activity['attachments'])) {
152 foreach ($activity['attachments'] as $attach) {
153 self::storeAttachmentAsMedia($item['uri-id'], $attach);
160 * @param array $activity Activity array
161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
163 public static function updateItem($activity)
165 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type'], ['uri' => $activity['id']]);
166 if (!DBA::isResult($item)) {
167 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
168 $item = self::createItem($activity);
173 self::postItem($activity, $item);
177 $item['changed'] = DateTimeFormat::utcNow();
178 $item['edited'] = DateTimeFormat::utc($activity['updated']);
180 $item = self::processContent($activity, $item);
182 self::storeAttachments($activity, $item);
188 Item::update($item, ['uri' => $activity['id']]);
190 if ($activity['object_type'] == 'as:Event') {
191 $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
192 while ($post = DBA::fetch($posts)) {
193 self::updateEvent($post['event-id'], $activity);
199 * Update an existing event
201 * @param int $event_id
202 * @param array $activity
204 private static function updateEvent(int $event_id, array $activity)
206 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
208 $event['edited'] = DateTimeFormat::utc($activity['updated']);
209 $event['summary'] = HTML::toBBCode($activity['name']);
210 $event['desc'] = HTML::toBBCode($activity['content']);
211 $event['start'] = $activity['start-time'];
212 $event['finish'] = $activity['end-time'];
213 $event['nofinish'] = empty($event['finish']);
214 $event['location'] = $activity['location'];
216 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
217 Event::store($event);
221 * Prepares data for a message
223 * @param array $activity Activity array
224 * @return array Internal item
225 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
226 * @throws \ImagickException
228 public static function createItem($activity)
231 $item['verb'] = Activity::POST;
232 $item['thr-parent'] = $activity['reply-to-id'];
234 if ($activity['reply-to-id'] == $activity['id']) {
235 $item['gravity'] = GRAVITY_PARENT;
236 $item['object-type'] = Activity\ObjectType::NOTE;
238 $item['gravity'] = GRAVITY_COMMENT;
239 $item['object-type'] = Activity\ObjectType::COMMENT;
242 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
243 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
244 self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
247 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
249 /// @todo What to do with $activity['context']?
250 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
251 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
255 $item['network'] = Protocol::ACTIVITYPUB;
256 $item['author-link'] = $activity['author'];
257 $item['author-id'] = Contact::getIdForURL($activity['author']);
258 $item['owner-link'] = $activity['actor'];
259 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
261 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
262 $item['private'] = Item::UNLISTED;
263 } elseif (in_array(0, $activity['receiver'])) {
264 $item['private'] = Item::PUBLIC;
266 $item['private'] = Item::PRIVATE;
269 if (!empty($activity['raw'])) {
270 $item['source'] = $activity['raw'];
271 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
272 $item['conversation-href'] = $activity['context'] ?? '';
273 $item['conversation-uri'] = $activity['conversation'] ?? '';
275 if (isset($activity['push'])) {
276 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
280 if (!empty($activity['from-relay'])) {
281 $item['direction'] = Conversation::RELAY;
284 if ($activity['object_type'] == 'as:Article') {
285 $item['post-type'] = Item::PT_ARTICLE;
286 } elseif ($activity['object_type'] == 'as:Audio') {
287 $item['post-type'] = Item::PT_AUDIO;
288 } elseif ($activity['object_type'] == 'as:Document') {
289 $item['post-type'] = Item::PT_DOCUMENT;
290 } elseif ($activity['object_type'] == 'as:Event') {
291 $item['post-type'] = Item::PT_EVENT;
292 } elseif ($activity['object_type'] == 'as:Image') {
293 $item['post-type'] = Item::PT_IMAGE;
294 } elseif ($activity['object_type'] == 'as:Page') {
295 $item['post-type'] = Item::PT_PAGE;
296 } elseif ($activity['object_type'] == 'as:Question') {
297 $item['post-type'] = Item::PT_POLL;
298 } elseif ($activity['object_type'] == 'as:Video') {
299 $item['post-type'] = Item::PT_VIDEO;
301 $item['post-type'] = Item::PT_NOTE;
304 $item['isForum'] = false;
306 if (!empty($activity['thread-completion'])) {
307 if ($activity['thread-completion'] != $item['owner-id']) {
308 $actor = Contact::getById($activity['thread-completion'], ['url']);
309 $item['causer-link'] = $actor['url'];
310 $item['causer-id'] = $activity['thread-completion'];
311 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
313 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
314 $item['causer-link'] = $item['owner-link'];
315 $item['causer-id'] = $item['owner-id'];
316 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
319 $item['owner-link'] = $item['author-link'];
320 $item['owner-id'] = $item['author-id'];
322 $actor = APContact::getByURL($item['owner-link'], false);
323 $item['isForum'] = ($actor['type'] == 'Group');
326 $item['uri'] = $activity['id'];
328 if (empty($activity['published']) || empty($activity['updated'])) {
329 DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
332 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
333 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
334 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
335 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
337 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
338 if (empty($item['uri-id'])) {
339 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
343 $item = self::processContent($activity, $item);
345 Logger::info('Message was not processed');
349 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
351 self::storeAttachments($activity, $item);
353 // We received the post via AP, so we set the protocol of the server to AP
354 $contact = Contact::getById($item['author-id'], ['gsid']);
355 if (!empty($contact['gsid'])) {
356 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
359 if ($item['author-id'] != $item['owner-id']) {
360 $contact = Contact::getById($item['owner-id'], ['gsid']);
361 if (!empty($contact['gsid'])) {
362 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
372 * @param array $activity
373 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
374 * @throws \ImagickException
376 public static function deleteItem($activity)
378 $owner = Contact::getIdForURL($activity['actor']);
380 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
381 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
385 * Prepare the item array for an activity
387 * @param array $activity Activity array
388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389 * @throws \ImagickException
391 public static function addTag($activity)
393 if (empty($activity['object_content']) || empty($activity['object_id'])) {
397 foreach ($activity['receiver'] as $receiver) {
398 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
399 if (!DBA::isResult($item)) {
400 // We don't fetch missing content for this purpose
404 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
405 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
409 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
410 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
415 * Prepare the item array for an activity
417 * @param array $activity Activity array
418 * @param string $verb Activity verb
419 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 * @throws \ImagickException
422 public static function createActivity($activity, $verb)
424 $item = self::createItem($activity);
429 $item['verb'] = $verb;
430 $item['thr-parent'] = $activity['object_id'];
431 $item['gravity'] = GRAVITY_ACTIVITY;
432 unset($item['post-type']);
433 $item['object-type'] = Activity\ObjectType::NOTE;
435 if (!empty($activity['content'])) {
436 $item['body'] = HTML::toBBCode($activity['content']);
439 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
441 self::postItem($activity, $item);
445 * Fetch the Uri-Id of a post for the "featured" collection
447 * @param array $activity
450 private static function getUriIdForFeaturedCollection(array $activity)
452 $actor = APContact::getByURL($activity['actor']);
457 // Refetch the account when the "featured" collection is missing.
458 // This can be removed in a future version (end of 2022 should be good).
459 if (empty($actor['featured'])) {
460 $actor = APContact::getByURL($activity['actor'], true);
466 if ($activity['target_id'] != $actor['featured']) {
470 $id = Contact::getIdForURL($activity['actor']);
475 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id'], 'author-id' => $id]);
476 if (!empty($parent['uri-id'])) {
477 return $parent['uri-id'];
484 * Add a post to the "Featured" collection
486 * @param array $activity
488 public static function addToFeaturedCollection(array $activity)
490 $uriid = self::getUriIdForFeaturedCollection($activity);
495 Logger::debug('Add post to featured collection', ['uri-id' => $uriid]);
497 // @todo Add functionality
501 * Remove a post to the "Featured" collection
503 * @param array $activity
505 public static function removeFromFeaturedCollection(array $activity)
507 $uriid = self::getUriIdForFeaturedCollection($activity);
512 Logger::debug('Remove post from featured collection', ['uri-id' => $uriid]);
514 // @todo Add functionality
520 * @param array $activity Activity array
523 * @return int event id
526 public static function createEvent($activity, $item)
528 $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']);
529 $event['desc'] = HTML::toBBCode($activity['content']);
530 $event['start'] = $activity['start-time'];
531 $event['finish'] = $activity['end-time'];
532 $event['nofinish'] = empty($event['finish']);
533 $event['location'] = $activity['location'];
534 $event['cid'] = $item['contact-id'];
535 $event['uid'] = $item['uid'];
536 $event['uri'] = $item['uri'];
537 $event['edited'] = $item['edited'];
538 $event['private'] = $item['private'];
539 $event['guid'] = $item['guid'];
540 $event['plink'] = $item['plink'];
541 $event['network'] = $item['network'];
542 $event['protocol'] = $item['protocol'];
543 $event['direction'] = $item['direction'];
544 $event['source'] = $item['source'];
546 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
547 if (DBA::isResult($ev)) {
548 $event['id'] = $ev['id'];
551 $event_id = Event::store($event);
553 Logger::info('Event was stored', ['id' => $event_id]);
559 * Process the content
561 * @param array $activity Activity array
563 * @return array|bool Returns the item array or false if there was an unexpected occurrence
566 private static function processContent($activity, $item)
568 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
569 $item['title'] = Markdown::toBBCode($activity['name']);
570 $content = Markdown::toBBCode($activity['content']);
571 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
572 $item['title'] = $activity['name'];
573 $content = $activity['content'];
575 // By default assume "text/html"
576 $item['title'] = HTML::toBBCode($activity['name']);
577 $content = HTML::toBBCode($activity['content']);
580 if (!empty($activity['languages'])) {
581 $item['language'] = self::processLanguages($activity['languages']);
584 if (!empty($activity['emojis'])) {
585 $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
588 $content = self::addMentionLinks($content, $activity['tags']);
590 if (!empty($activity['source'])) {
591 $item['body'] = $activity['source'];
592 $item['raw-body'] = $content;
593 $item['body'] = Item::improveSharedDataInBody($item);
595 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
596 $item_private = !in_array(0, $activity['item_receiver']);
597 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
598 if (!DBA::isResult($parent)) {
599 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
602 if ($item_private && ($parent['private'] != Item::PRIVATE)) {
603 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
607 $content = self::removeImplicitMentionsFromBody($content, $parent);
609 $item['content-warning'] = HTML::toBBCode($activity['summary']);
610 $item['raw-body'] = $item['body'] = $content;
613 self::storeFromBody($item);
614 self::storeTags($item['uri-id'], $activity['tags']);
616 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
618 $item['location'] = $activity['location'];
620 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
621 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
624 $item['app'] = $activity['generator'];
630 * Store hashtags and mentions
634 private static function storeFromBody(array $item)
636 // Make sure to delete all existing tags (can happen when called via the update functionality)
637 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
639 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
643 * Generate a GUID out of an URL of an ActivityPub post.
645 * @param string $url message URL
646 * @return string with GUID
648 private static function getGUIDByURL(string $url)
650 $parsed = parse_url($url);
652 $host_hash = hash('crc32', $parsed['host']);
654 unset($parsed["scheme"]);
655 unset($parsed["host"]);
657 $path = implode("/", $parsed);
659 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
663 * Checks if an incoming message is wanted
665 * @param array $activity
667 * @return boolean Is the message wanted?
669 private static function isSolicitedMessage(array $activity, array $item)
671 // The checks are split to improve the support when searching why a message was accepted.
672 if (count($activity['receiver']) != 1) {
673 // The message has more than one receiver, so it is wanted.
674 Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
678 if ($item['private'] == Item::PRIVATE) {
679 // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
680 Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
684 if (!empty($activity['from-relay'])) {
685 // We check relay posts at another place. When it arrived here, the message is already checked.
686 Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
690 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUCE])) {
691 // Manual completions and completions caused by reshares are allowed without any further checks.
692 Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
696 if ($item['gravity'] != GRAVITY_PARENT) {
697 // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
698 // This can possibly be improved in the future.
699 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
703 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
704 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB)) {
705 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
713 * Creates an item post
715 * @param array $activity Activity data
716 * @param array $item item array
717 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
718 * @throws \ImagickException
720 public static function postItem(array $activity, array $item)
727 ksort($activity['receiver']);
729 if (!self::isSolicitedMessage($activity, $item)) {
730 DBA::delete('item-uri', ['id' => $item['uri-id']]);
734 foreach ($activity['receiver'] as $receiver) {
735 if ($receiver == -1) {
739 $item['uid'] = $receiver;
741 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
743 case Receiver::TARGET_TO:
744 $item['post-reason'] = Item::PR_TO;
746 case Receiver::TARGET_CC:
747 $item['post-reason'] = Item::PR_CC;
749 case Receiver::TARGET_BTO:
750 $item['post-reason'] = Item::PR_BTO;
752 case Receiver::TARGET_BCC:
753 $item['post-reason'] = Item::PR_BCC;
755 case Receiver::TARGET_FOLLOWER:
756 $item['post-reason'] = Item::PR_FOLLOWER;
758 case Receiver::TARGET_ANSWER:
759 $item['post-reason'] = Item::PR_COMMENT;
761 case Receiver::TARGET_GLOBAL:
762 $item['post-reason'] = Item::PR_GLOBAL;
765 $item['post-reason'] = Item::PR_NONE;
768 if (!empty($activity['from-relay'])) {
769 $item['post-reason'] = Item::PR_RELAY;
770 } elseif (!empty($activity['thread-completion'])) {
771 $item['post-reason'] = Item::PR_FETCHED;
774 if ($item['isForum'] ?? false) {
775 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
777 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
780 if (($receiver != 0) && empty($item['contact-id'])) {
781 $item['contact-id'] = Contact::getIdForURL($activity['author']);
784 if (!empty($activity['directmessage'])) {
785 self::postMail($activity, $item);
789 if (!($item['isForum'] ?? false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT) && !Contact::isSharingByURL($activity['author'], $receiver)) {
790 if ($item['post-reason'] == Item::PR_BCC) {
791 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id']]);
796 !empty($activity['thread-children-type'])
797 && in_array($activity['thread-children-type'], Receiver::ACTIVITY_TYPES)
798 && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE
800 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
801 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
808 if ($receiver != 0) {
809 $user = User::getById($receiver, ['account-type']);
810 if (!empty($user['account-type'])) {
811 $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
815 if (!$is_forum && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
816 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
818 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
819 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
823 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
827 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
830 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
831 $event_id = self::createEvent($activity, $item);
833 $item = Event::getItemArrayForImportedId($event_id, $item);
836 $item_id = Item::insert($item);
838 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
840 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
843 if ($item['uid'] == 0) {
848 // Store send a follow request for every reshare - but only when the item had been stored
849 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
850 $author = APContact::getByURL($item['owner-link'], false);
851 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
852 if ($author['type'] != 'Group') {
853 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
854 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
860 * Store tags and mentions into the tag table
862 * @param integer $uriid
865 private static function storeTags(int $uriid, array $tags = null)
867 foreach ($tags as $tag) {
868 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
872 $hash = substr($tag['name'], 0, 1);
874 if ($tag['type'] == 'Mention') {
875 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
876 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
877 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
878 $tag['name'] = substr($tag['name'], 1);
880 $type = Tag::IMPLICIT_MENTION;
882 if (!empty($tag['href'])) {
883 $apcontact = APContact::getByURL($tag['href']);
884 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
885 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
888 } elseif ($tag['type'] == 'Hashtag') {
889 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
890 $tag['name'] = substr($tag['name'], 1);
892 $type = Tag::HASHTAG;
895 if (empty($tag['name'])) {
899 Tag::store($uriid, $type, $tag['name'], $tag['href']);
903 public static function storeReceivers(int $uriid, array $receivers)
905 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
906 if (!empty($receivers[$element])) {
907 foreach ($receivers[$element] as $receiver) {
908 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
909 $name = Receiver::PUBLIC_COLLECTION;
911 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
913 Tag::store($uriid, $type, $name, $receiver);
920 * Creates an mail post
922 * @param array $activity Activity data
923 * @param array $item item array
924 * @return int|bool New mail table row id or false on error
925 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
927 private static function postMail($activity, $item)
929 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
930 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
934 Logger::info('Direct Message', $item);
937 $msg['uid'] = $item['uid'];
939 $msg['contact-id'] = $item['contact-id'];
941 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
942 $msg['from-name'] = $contact['name'];
943 $msg['from-url'] = $contact['url'];
944 $msg['from-photo'] = $contact['photo'];
946 $msg['uri'] = $item['uri'];
947 $msg['created'] = $item['created'];
949 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
950 if (DBA::isResult($parent)) {
951 $msg['parent-uri'] = $parent['parent-uri'];
952 $msg['title'] = $parent['title'];
954 $msg['parent-uri'] = $item['thr-parent'];
956 if (!empty($item['title'])) {
957 $msg['title'] = $item['title'];
958 } elseif (!empty($item['content-warning'])) {
959 $msg['title'] = $item['content-warning'];
961 // Trying to generate a title out of the body
962 $title = $item['body'];
964 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
965 $title = $matches[3];
968 $title = trim(BBCode::toPlaintext($title));
970 if (strlen($title) > 20) {
971 $title = substr($title, 0, 20) . '...';
974 $msg['title'] = $title;
977 $msg['body'] = $item['body'];
979 return Mail::insert($msg);
983 * Fetches missing posts
985 * @param string $url message URL
986 * @param array $child activity array with the child of this message
987 * @param string $relay_actor Relay actor
988 * @param int $completion Completion mode, see Receiver::COMPLETION_*
989 * @return string fetched message URL
990 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
992 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL)
994 if (!empty($child['receiver'])) {
995 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
1000 $object = ActivityPub::fetchContent($url, $uid);
1001 if (empty($object)) {
1002 Logger::notice('Activity was not fetchable, aborting.', ['url' => $url]);
1006 if (empty($object['id'])) {
1007 Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1011 if (!empty($object['actor'])) {
1012 $object_actor = $object['actor'];
1013 } elseif (!empty($object['attributedTo'])) {
1014 $object_actor = $object['attributedTo'];
1015 if (is_array($object_actor)) {
1016 $compacted = JsonLD::compact($object);
1017 $object_actor = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1024 $signer = [$object_actor];
1026 if (!empty($child['author'])) {
1027 $actor = $child['author'];
1030 $actor = $object_actor;
1033 if (!empty($object['published'])) {
1034 $published = $object['published'];
1035 } elseif (!empty($child['published'])) {
1036 $published = $child['published'];
1038 $published = DateTimeFormat::utcNow();
1042 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1043 unset($object['@context']);
1044 $activity['id'] = $object['id'];
1045 $activity['to'] = $object['to'] ?? [];
1046 $activity['cc'] = $object['cc'] ?? [];
1047 $activity['actor'] = $actor;
1048 $activity['object'] = $object;
1049 $activity['published'] = $published;
1050 $activity['type'] = 'Create';
1052 $ldactivity = JsonLD::compact($activity);
1054 if (!empty($relay_actor)) {
1055 $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
1056 $ldactivity['completion-mode'] = Receiver::COMPLETION_RELAY;
1057 } elseif (!empty($child['thread-completion'])) {
1058 $ldactivity['thread-completion'] = $child['thread-completion'];
1059 $ldactivity['completion-mode'] = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1061 $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
1062 $ldactivity['completion-mode'] = $completion;
1065 if (!empty($child['type'])) {
1066 $ldactivity['thread-children-type'] = $child['type'];
1069 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
1073 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
1075 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
1077 return $activity['id'];
1081 * Test if incoming relay messages should be accepted
1083 * @param array $activity activity array
1084 * @param string $id object ID
1085 * @return boolean true if message is accepted
1087 private static function acceptIncomingMessage(array $activity, string $id)
1089 if (empty($activity['as:object'])) {
1090 Logger::info('No object field in activity - accepted', ['id' => $id]);
1094 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1095 $uriid = ItemURI::getIdByURI($replyto);
1096 if (Post::exists(['uri-id' => $uriid])) {
1097 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1101 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1102 $authorid = Contact::getIdForURL($attributed_to);
1104 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value'));
1107 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1108 if (!empty($tags)) {
1109 foreach ($tags as $tag) {
1110 if ($tag['type'] != 'Hashtag') {
1113 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1117 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
1121 * perform a "follow" request
1123 * @param array $activity
1124 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1125 * @throws \ImagickException
1127 public static function followUser($activity)
1129 $uid = User::getIdForURL($activity['object_id']);
1134 $owner = User::getOwnerDataById($uid);
1135 if (empty($owner)) {
1139 $cid = Contact::getIdForURL($activity['actor'], $uid);
1141 self::switchContact($cid);
1142 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1145 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
1146 'author-link' => $activity['actor']];
1148 // Ensure that the contact has got the right network type
1149 self::switchContact($item['author-id']);
1151 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1152 if ($result === true) {
1153 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1156 $cid = Contact::getIdForURL($activity['actor'], $uid);
1161 if (empty($contact)) {
1162 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1165 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1169 * Update the given profile
1171 * @param array $activity
1172 * @throws \Exception
1174 public static function updatePerson($activity)
1176 if (empty($activity['object_id'])) {
1180 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1181 Contact::updateFromProbeByURL($activity['object_id']);
1185 * Delete the given profile
1187 * @param array $activity
1188 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1190 public static function deletePerson($activity)
1192 if (empty($activity['object_id']) || empty($activity['actor'])) {
1193 Logger::info('Empty object id or actor.');
1197 if ($activity['object_id'] != $activity['actor']) {
1198 Logger::info('Object id does not match actor.');
1202 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1203 while ($contact = DBA::fetch($contacts)) {
1204 Contact::remove($contact['id']);
1206 DBA::close($contacts);
1208 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1212 * Accept a follow request
1214 * @param array $activity
1215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1216 * @throws \ImagickException
1218 public static function acceptFollowUser($activity)
1220 $uid = User::getIdForURL($activity['object_actor']);
1225 $cid = Contact::getIdForURL($activity['actor'], $uid);
1227 Logger::info('No contact found', ['actor' => $activity['actor']]);
1231 self::switchContact($cid);
1233 $fields = ['pending' => false];
1235 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1236 if ($contact['rel'] == Contact::FOLLOWER) {
1237 $fields['rel'] = Contact::FRIEND;
1240 $condition = ['id' => $cid];
1241 Contact::update($fields, $condition);
1242 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1246 * Reject a follow request
1248 * @param array $activity
1249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1250 * @throws \ImagickException
1252 public static function rejectFollowUser($activity)
1254 $uid = User::getIdForURL($activity['object_actor']);
1259 $cid = Contact::getIdForURL($activity['actor'], $uid);
1261 Logger::info('No contact found', ['actor' => $activity['actor']]);
1265 self::switchContact($cid);
1267 $contact = Contact::getById($cid, ['rel']);
1268 if ($contact['rel'] == Contact::SHARING) {
1269 Contact::remove($cid);
1270 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1271 } elseif ($contact['rel'] == Contact::FRIEND) {
1272 Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1274 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1279 * Undo activity like "like" or "dislike"
1281 * @param array $activity
1282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1283 * @throws \ImagickException
1285 public static function undoActivity($activity)
1287 if (empty($activity['object_id'])) {
1291 if (empty($activity['object_actor'])) {
1295 $author_id = Contact::getIdForURL($activity['object_actor']);
1296 if (empty($author_id)) {
1300 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1304 * Activity to remove a follower
1306 * @param array $activity
1307 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1308 * @throws \ImagickException
1310 public static function undoFollowUser($activity)
1312 $uid = User::getIdForURL($activity['object_object']);
1317 $owner = User::getOwnerDataById($uid);
1318 if (empty($owner)) {
1322 $cid = Contact::getIdForURL($activity['actor'], $uid);
1324 Logger::info('No contact found', ['actor' => $activity['actor']]);
1328 self::switchContact($cid);
1330 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1331 if (!DBA::isResult($contact)) {
1335 Contact::removeFollower($contact);
1336 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1340 * Switches a contact to AP if needed
1342 * @param integer $cid Contact ID
1343 * @throws \Exception
1345 private static function switchContact($cid)
1347 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1348 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1352 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1353 Contact::updateFromProbe($cid);
1357 * Collects implicit mentions like:
1358 * - the author of the parent item
1359 * - all the mentioned conversants in the parent item
1361 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1365 private static function getImplicitMentionList(array $parent)
1367 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1369 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1371 $implicit_mentions = [];
1372 if (empty($parent_author['url'])) {
1373 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1375 $implicit_mentions[] = $parent_author['url'];
1376 $implicit_mentions[] = $parent_author['nurl'];
1377 $implicit_mentions[] = $parent_author['alias'];
1380 if (!empty($parent['alias'])) {
1381 $implicit_mentions[] = $parent['alias'];
1384 foreach ($parent_terms as $term) {
1385 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1386 if (!empty($contact['url'])) {
1387 $implicit_mentions[] = $contact['url'];
1388 $implicit_mentions[] = $contact['nurl'];
1389 $implicit_mentions[] = $contact['alias'];
1393 return $implicit_mentions;
1397 * Strips from the body prepended implicit mentions
1399 * @param string $body
1400 * @param array $parent
1403 private static function removeImplicitMentionsFromBody(string $body, array $parent)
1405 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1409 $potential_mentions = self::getImplicitMentionList($parent);
1411 $kept_mentions = [];
1413 // Extract one prepended mention at a time from the body
1414 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1415 if (!in_array($matches[2], $potential_mentions)) {
1416 $kept_mentions[] = $matches[1];
1419 $body = $matches[3];
1422 // Re-appending the kept mentions to the body after extraction
1423 $kept_mentions[] = $body;
1425 return implode('', $kept_mentions);
1429 * Adds links to string mentions
1431 * @param string $body
1432 * @param array $tags
1435 protected static function addMentionLinks(string $body, array $tags): string
1437 // This prevents links to be added again to Pleroma-style mention links
1438 $body = self::normalizeMentionLinks($body);
1440 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
1441 foreach ($tags as $tag) {
1442 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1446 $hash = substr($tag['name'], 0, 1);
1447 $name = substr($tag['name'], 1);
1448 if (!in_array($hash, Tag::TAG_CHARACTER)) {
1450 $name = $tag['name'];
1453 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);