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;
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\Relay;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\HTTPSignature;
50 use Friendica\Util\JsonLD;
51 use Friendica\Util\Network;
52 use Friendica\Util\Strings;
53 use Friendica\Worker\Delivery;
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 protected static function normalizeMentionLinks(string $body): string
96 return preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
100 * Convert the language array into a language JSON
102 * @param array $languages
103 * @return string language JSON
105 private static function processLanguages(array $languages): string
107 $codes = array_keys($languages);
109 foreach ($codes as $code) {
117 return json_encode($lang);
120 * Replaces emojis in the body
123 * @param string $body
124 * @param array $emojis
126 * @return string with replaced emojis
128 private static function replaceEmojis(int $uri_id, string $body, array $emojis): string
132 array_column($emojis, 'name'),
133 array_map(function ($emoji) {
134 return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
139 // We store the emoji here to be able to avoid storing it in the media
140 foreach ($emojis as $emoji) {
141 Post\Link::getByLink($uri_id, $emoji['href']);
147 * Store attached media files in the post-media table
150 * @param array $attachment
153 private static function storeAttachmentAsMedia(int $uriid, array $attachment)
155 if (empty($attachment['url'])) {
159 $data = ['uri-id' => $uriid];
160 $data['type'] = Post\Media::UNKNOWN;
161 $data['url'] = $attachment['url'];
162 $data['mimetype'] = $attachment['mediaType'] ?? null;
163 $data['height'] = $attachment['height'] ?? null;
164 $data['width'] = $attachment['width'] ?? null;
165 $data['size'] = $attachment['size'] ?? null;
166 $data['preview'] = $attachment['image'] ?? null;
167 $data['description'] = $attachment['name'] ?? null;
169 Post\Media::insert($data);
173 * Stire attachment data
175 * @param array $activity
178 private static function storeAttachments(array $activity, array $item)
180 if (empty($activity['attachments'])) {
184 foreach ($activity['attachments'] as $attach) {
185 self::storeAttachmentAsMedia($item['uri-id'], $attach);
190 * Store attachment data
192 * @param array $activity
195 private static function storeQuestion(array $activity, array $item)
197 if (empty($activity['question'])) {
200 $question = ['multiple' => $activity['question']['multiple']];
202 if (!empty($activity['question']['voters'])) {
203 $question['voters'] = $activity['question']['voters'];
206 if (!empty($activity['question']['end-time'])) {
207 $question['end-time'] = DateTimeFormat::utc($activity['question']['end-time']);
210 Post\Question::update($item['uri-id'], $question);
212 foreach ($activity['question']['options'] as $key => $option) {
213 $option = ['name' => $option['name'], 'replies' => $option['replies']];
214 Post\QuestionOption::update($item['uri-id'], $key, $option);
217 Logger::debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]);
223 * @param array $activity Activity array
224 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
225 * @throws \ImagickException
227 public static function updateItem(array $activity)
229 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type', 'private'], ['uri' => $activity['id']]);
230 if (!DBA::isResult($item)) {
231 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
232 $item = self::createItem($activity, false);
234 Queue::remove($activity);
238 self::postItem($activity, $item);
242 $item['changed'] = DateTimeFormat::utcNow();
243 $item['edited'] = DateTimeFormat::utc($activity['updated']);
245 $item = self::processContent($activity, $item);
247 Queue::remove($activity);
251 self::storeAttachments($activity, $item);
252 self::storeQuestion($activity, $item);
254 Post\History::add($item['uri-id'], $item);
255 Item::update($item, ['uri' => $activity['id']]);
257 Queue::remove($activity);
259 if ($activity['object_type'] == 'as:Event') {
260 $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
261 while ($post = DBA::fetch($posts)) {
262 self::updateEvent($post['event-id'], $activity);
268 * Update an existing event
270 * @param int $event_id
271 * @param array $activity
273 private static function updateEvent(int $event_id, array $activity)
275 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
277 $event['edited'] = DateTimeFormat::utc($activity['updated']);
278 $event['summary'] = HTML::toBBCode($activity['name']);
279 $event['desc'] = HTML::toBBCode($activity['content']);
280 if (!empty($activity['start-time'])) {
281 $event['start'] = DateTimeFormat::utc($activity['start-time']);
283 if (!empty($activity['end-time'])) {
284 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
286 $event['nofinish'] = empty($event['finish']);
287 $event['location'] = $activity['location'];
289 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
290 Event::store($event);
294 * Prepares data for a message
296 * @param array $activity Activity array
297 * @param bool $fetch_parents
299 * @return array Internal item
301 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
302 * @throws \ImagickException
304 public static function createItem(array $activity, bool $fetch_parents): array
307 $item['verb'] = Activity::POST;
308 $item['thr-parent'] = $activity['reply-to-id'];
310 if ($activity['reply-to-id'] == $activity['id']) {
311 $item['gravity'] = GRAVITY_PARENT;
312 $item['object-type'] = Activity\ObjectType::NOTE;
314 $item['gravity'] = GRAVITY_COMMENT;
315 $item['object-type'] = Activity\ObjectType::COMMENT;
318 if (!empty($activity['conversation'])) {
319 $item['conversation'] = $activity['conversation'];
320 } elseif (!empty($activity['context'])) {
321 $item['conversation'] = $activity['context'];
324 if (!empty($item['conversation'])) {
325 $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]);
326 if (!empty($conversation)) {
327 Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]);
328 $item['parent-uri'] = $conversation['uri'];
329 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
335 Logger::debug('Create Item', ['id' => $activity['id'], 'conversation' => $item['conversation'] ?? '']);
336 if (empty($activity['author']) && empty($activity['actor'])) {
337 Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]);
338 Queue::remove($activity);
342 if (!in_array(0, $activity['receiver']) || !DI::config()->get('system', 'fetch_parents')) {
343 $fetch_parents = false;
346 if ($fetch_parents && empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
347 $result = self::fetchParent($activity, !empty($conversation));
348 if (!empty($result)) {
349 if (($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
350 $item['thr-parent'] = $result;
352 } elseif (empty($conversation)) {
357 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
359 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
360 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
361 if (!$fetch_parents) {
362 Queue::remove($activity);
367 $item['network'] = Protocol::ACTIVITYPUB;
368 $item['author-link'] = $activity['author'];
369 $item['author-id'] = Contact::getIdForURL($activity['author']);
370 $item['owner-link'] = $activity['actor'];
371 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
373 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
374 $item['private'] = Item::UNLISTED;
375 } elseif (in_array(0, $activity['receiver'])) {
376 $item['private'] = Item::PUBLIC;
378 $item['private'] = Item::PRIVATE;
381 if (!empty($activity['raw'])) {
382 $item['source'] = $activity['raw'];
385 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
387 if (isset($activity['push'])) {
388 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
391 if (!empty($activity['from-relay'])) {
392 $item['direction'] = Conversation::RELAY;
395 if ($activity['object_type'] == 'as:Article') {
396 $item['post-type'] = Item::PT_ARTICLE;
397 } elseif ($activity['object_type'] == 'as:Audio') {
398 $item['post-type'] = Item::PT_AUDIO;
399 } elseif ($activity['object_type'] == 'as:Document') {
400 $item['post-type'] = Item::PT_DOCUMENT;
401 } elseif ($activity['object_type'] == 'as:Event') {
402 $item['post-type'] = Item::PT_EVENT;
403 } elseif ($activity['object_type'] == 'as:Image') {
404 $item['post-type'] = Item::PT_IMAGE;
405 } elseif ($activity['object_type'] == 'as:Page') {
406 $item['post-type'] = Item::PT_PAGE;
407 } elseif ($activity['object_type'] == 'as:Question') {
408 $item['post-type'] = Item::PT_POLL;
409 } elseif ($activity['object_type'] == 'as:Video') {
410 $item['post-type'] = Item::PT_VIDEO;
412 $item['post-type'] = Item::PT_NOTE;
415 $item['isForum'] = false;
417 if (!empty($activity['thread-completion'])) {
418 if ($activity['thread-completion'] != $item['owner-id']) {
419 $actor = Contact::getById($activity['thread-completion'], ['url']);
420 $item['causer-link'] = $actor['url'];
421 $item['causer-id'] = $activity['thread-completion'];
422 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
424 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
425 $item['causer-link'] = $item['owner-link'];
426 $item['causer-id'] = $item['owner-id'];
427 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
430 $item['owner-link'] = $item['author-link'];
431 $item['owner-id'] = $item['author-id'];
433 $actor = APContact::getByURL($item['owner-link'], false);
434 $item['isForum'] = ($actor['type'] == 'Group');
437 $item['uri'] = $activity['id'];
439 if (empty($activity['published']) || empty($activity['updated'])) {
440 DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
443 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
444 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
445 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
446 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
448 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
449 if (empty($item['uri-id'])) {
450 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
454 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
456 $item = self::processContent($activity, $item);
458 Logger::info('Message was not processed');
459 Queue::remove($activity);
463 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
465 self::storeAttachments($activity, $item);
466 self::storeQuestion($activity, $item);
468 // We received the post via AP, so we set the protocol of the server to AP
469 $contact = Contact::getById($item['author-id'], ['gsid']);
470 if (!empty($contact['gsid'])) {
471 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
474 if ($item['author-id'] != $item['owner-id']) {
475 $contact = Contact::getById($item['owner-id'], ['gsid']);
476 if (!empty($contact['gsid'])) {
477 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
485 * Fetch and process parent posts for the given activity
487 * @param array $activity
488 * @param bool $in_background
492 private static function fetchParent(array $activity, bool $in_background = false): string
494 if (self::isFetched($activity['reply-to-id'])) {
495 Logger::info('Id is already fetched', ['id' => $activity['reply-to-id']]);
499 self::addActivityId($activity['reply-to-id']);
501 if (!DI::config()->get('system', 'fetch_by_worker')) {
502 $in_background = false;
505 $recursion_depth = $activity['recursion-depth'] ?? 0;
507 if (!$in_background && ($recursion_depth < DI::config()->get('system', 'max_recursion_depth'))) {
508 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
509 $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
510 if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
511 Logger::notice('The activity is gone, the queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
512 if (!empty($activity['entry-id'])) {
513 Queue::deleteById($activity['entry-id']);
516 } elseif (!empty($result)) {
517 $exists = Post::exists(['uri' => [$result, $activity['reply-to-id']]]);
519 Logger::notice('The activity has been fetched and created.', ['parent' => $result]);
521 } elseif (DI::config()->get('system', 'fetch_by_worker') || DI::config()->get('system', 'decoupled_receiver')) {
522 Logger::notice('The activity has been fetched and will hopefully be created later.', ['parent' => $result]);
524 Logger::notice('The activity exists but has not been created, the queue entry will be deleted.', ['parent' => $result]);
525 if (!empty($activity['entry-id'])) {
526 Queue::deleteById($activity['entry-id']);
531 if (empty($result) && !DI::config()->get('system', 'fetch_by_worker')) {
534 } elseif (self::isActivityGone($activity['reply-to-id'])) {
535 Logger::notice('The activity is gone. We will not spawn a worker. The queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
536 if ($in_background) {
537 // fetching in background is done for all activities where we have got the conversation
538 // There we only delete the single activity and not the whole thread since we can store the
539 // other posts in the thread even with missing posts.
540 Queue::remove($activity);
541 } elseif (!empty($activity['entry-id'])) {
542 Queue::deleteById($activity['entry-id']);
545 } elseif ($in_background) {
546 Logger::notice('Fetching is done in the background.', ['parent' => $activity['reply-to-id']]);
548 Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
551 if (!Fetch::hasWorker($activity['reply-to-id'])) {
552 Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
553 Fetch::add($activity['reply-to-id']);
554 $activity['recursion-depth'] = 0;
555 $wid = Worker::add(PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
556 Fetch::setWorkerId($activity['reply-to-id'], $wid);
558 Logger::debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]);
565 * Check if a given activity is no longer available
571 public static function isActivityGone(string $url): bool
573 $curlResult = HTTPSignature::fetchRaw($url, 0);
575 if (Network::isUrlBlocked($url)) {
579 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
580 if (in_array($curlResult->getReturnCode(), [401, 404])) {
584 if ($curlResult->isSuccess()) {
585 $object = json_decode($curlResult->getBody(), true);
586 if (!empty($object)) {
587 $activity = JsonLD::compact($object);
588 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
592 } elseif ($curlResult->getReturnCode() == 0) {
593 $host = parse_url($url, PHP_URL_HOST);
594 if (!(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) {
604 * @param array $activity
605 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
606 * @throws \ImagickException
608 public static function deleteItem(array $activity)
610 $owner = Contact::getIdForURL($activity['actor']);
612 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
613 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
614 Queue::remove($activity);
618 * Prepare the item array for an activity
620 * @param array $activity Activity array
621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
622 * @throws \ImagickException
624 public static function addTag(array $activity)
626 if (empty($activity['object_content']) || empty($activity['object_id'])) {
630 foreach ($activity['receiver'] as $receiver) {
631 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
632 if (!DBA::isResult($item)) {
633 // We don't fetch missing content for this purpose
637 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
638 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
642 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
643 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
648 * Prepare the item array for an activity
650 * @param array $activity Activity array
651 * @param string $verb Activity verb
652 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
653 * @throws \ImagickException
655 public static function createActivity(array $activity, string $verb)
657 $activity['reply-to-id'] = $activity['object_id'];
658 $item = self::createItem($activity, false);
663 $item['verb'] = $verb;
664 $item['thr-parent'] = $activity['object_id'];
665 $item['gravity'] = GRAVITY_ACTIVITY;
666 unset($item['post-type']);
667 $item['object-type'] = Activity\ObjectType::NOTE;
669 if (!empty($activity['content'])) {
670 $item['body'] = HTML::toBBCode($activity['content']);
673 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
675 self::postItem($activity, $item);
679 * Fetch the Uri-Id of a post for the "featured" collection
681 * @param array $activity
684 private static function getUriIdForFeaturedCollection(array $activity)
686 $actor = APContact::getByURL($activity['actor']);
691 // Refetch the account when the "featured" collection is missing.
692 // This can be removed in a future version (end of 2022 should be good).
693 if (empty($actor['featured'])) {
694 $actor = APContact::getByURL($activity['actor'], true);
700 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
701 if (empty($parent['uri-id'])) {
702 if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
703 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
707 if (!empty($parent['uri-id'])) {
708 return $parent['uri-id'];
715 * Add a post to the "Featured" collection
717 * @param array $activity
719 public static function addToFeaturedCollection(array $activity)
721 $uriid = self::getUriIdForFeaturedCollection($activity);
726 Logger::debug('Add post to featured collection', ['uri-id' => $uriid]);
728 Post\Collection::add($uriid, Post\Collection::FEATURED);
729 Queue::remove($activity);
733 * Remove a post to the "Featured" collection
735 * @param array $activity
737 public static function removeFromFeaturedCollection(array $activity)
739 $uriid = self::getUriIdForFeaturedCollection($activity);
744 Logger::debug('Remove post from featured collection', ['uri-id' => $uriid]);
746 Post\Collection::remove($uriid, Post\Collection::FEATURED);
747 Queue::remove($activity);
753 * @param array $activity Activity array
756 * @return int event id
759 public static function createEvent(array $activity, array $item): int
761 $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']);
762 $event['desc'] = HTML::toBBCode($activity['content']);
763 if (!empty($activity['start-time'])) {
764 $event['start'] = DateTimeFormat::utc($activity['start-time']);
766 if (!empty($activity['end-time'])) {
767 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
769 $event['nofinish'] = empty($event['finish']);
770 $event['location'] = $activity['location'];
771 $event['cid'] = $item['contact-id'];
772 $event['uid'] = $item['uid'];
773 $event['uri'] = $item['uri'];
774 $event['edited'] = $item['edited'];
775 $event['private'] = $item['private'];
776 $event['guid'] = $item['guid'];
777 $event['plink'] = $item['plink'];
778 $event['network'] = $item['network'];
779 $event['protocol'] = $item['protocol'];
780 $event['direction'] = $item['direction'];
781 $event['source'] = $item['source'];
783 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
784 if (DBA::isResult($ev)) {
785 $event['id'] = $ev['id'];
788 $event_id = Event::store($event);
790 Logger::info('Event was stored', ['id' => $event_id]);
796 * Process the content
798 * @param array $activity Activity array
800 * @return array|bool Returns the item array or false if there was an unexpected occurrence
803 private static function processContent(array $activity, array $item)
805 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
806 $item['title'] = strip_tags($activity['name']);
807 $content = Markdown::toBBCode($activity['content']);
808 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
809 $item['title'] = $activity['name'];
810 $content = $activity['content'];
812 // By default assume "text/html"
813 $item['title'] = HTML::toBBCode($activity['name'] ?? '');
814 $content = HTML::toBBCode($activity['content'] ?? '');
817 $item['title'] = trim(BBCode::toPlaintext($item['title']));
819 if (!empty($activity['languages'])) {
820 $item['language'] = self::processLanguages($activity['languages']);
823 if (!empty($activity['emojis'])) {
824 $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
827 $content = self::addMentionLinks($content, $activity['tags']);
829 if (!empty($activity['source'])) {
830 $item['body'] = $activity['source'];
831 $item['raw-body'] = $content;
832 $item['body'] = Item::improveSharedDataInBody($item);
834 $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
835 if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
836 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
837 if (!DBA::isResult($parent)) {
838 Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
841 if (!empty($activity['type']) && in_array($activity['type'], Receiver::CONTENT_TYPES) && ($item['private'] == Item::PRIVATE) && ($parent['private'] != Item::PRIVATE)) {
842 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
846 $content = self::removeImplicitMentionsFromBody($content, $parent);
848 $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
849 $item['raw-body'] = $item['body'] = $content;
852 self::storeFromBody($item);
853 self::storeTags($item['uri-id'], $activity['tags']);
855 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
857 $item['location'] = $activity['location'];
859 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
860 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
863 $item['app'] = $activity['generator'];
869 * Store hashtags and mentions
873 private static function storeFromBody(array $item)
875 // Make sure to delete all existing tags (can happen when called via the update functionality)
876 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
878 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
882 * Generate a GUID out of an URL of an ActivityPub post.
884 * @param string $url message URL
885 * @return string with GUID
887 private static function getGUIDByURL(string $url): string
889 $parsed = parse_url($url);
891 $host_hash = hash('crc32', $parsed['host']);
893 unset($parsed["scheme"]);
894 unset($parsed["host"]);
896 $path = implode("/", $parsed);
898 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
902 * Checks if an incoming message is wanted
904 * @param array $activity
906 * @return boolean Is the message wanted?
908 private static function isSolicitedMessage(array $activity, array $item): bool
910 // The checks are split to improve the support when searching why a message was accepted.
911 if (count($activity['receiver']) != 1) {
912 // The message has more than one receiver, so it is wanted.
913 Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
917 if ($item['private'] == Item::PRIVATE) {
918 // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
919 Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
923 if (!empty($activity['from-relay'])) {
924 // We check relay posts at another place. When it arrived here, the message is already checked.
925 Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
929 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUCE])) {
930 // Manual completions and completions caused by reshares are allowed without any further checks.
931 Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
935 if ($item['gravity'] != GRAVITY_PARENT) {
936 // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
937 // This can possibly be improved in the future.
938 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
942 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
943 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB)) {
944 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
952 * Creates an item post
954 * @param array $activity Activity data
955 * @param array $item item array
956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
957 * @throws \ImagickException
959 public static function postItem(array $activity, array $item)
967 ksort($activity['receiver']);
969 if (!self::isSolicitedMessage($activity, $item)) {
970 DBA::delete('item-uri', ['id' => $item['uri-id']]);
971 if (!empty($activity['entry-id'])) {
972 Queue::deleteById($activity['entry-id']);
977 foreach ($activity['receiver'] as $receiver) {
978 if ($receiver == -1) {
982 $item['uid'] = $receiver;
984 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
986 case Receiver::TARGET_TO:
987 $item['post-reason'] = Item::PR_TO;
989 case Receiver::TARGET_CC:
990 $item['post-reason'] = Item::PR_CC;
992 case Receiver::TARGET_BTO:
993 $item['post-reason'] = Item::PR_BTO;
995 case Receiver::TARGET_BCC:
996 $item['post-reason'] = Item::PR_BCC;
998 case Receiver::TARGET_FOLLOWER:
999 $item['post-reason'] = Item::PR_FOLLOWER;
1001 case Receiver::TARGET_ANSWER:
1002 $item['post-reason'] = Item::PR_COMMENT;
1004 case Receiver::TARGET_GLOBAL:
1005 $item['post-reason'] = Item::PR_GLOBAL;
1008 $item['post-reason'] = Item::PR_NONE;
1011 $item['post-reason'] = Item::getPostReason($item);
1013 if (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE])) {
1014 if (!empty($activity['from-relay'])) {
1015 $item['post-reason'] = Item::PR_RELAY;
1016 } elseif (!empty($activity['thread-completion'])) {
1017 $item['post-reason'] = Item::PR_FETCHED;
1018 } elseif (!empty($activity['push'])) {
1019 $item['post-reason'] = Item::PR_PUSHED;
1023 if ($item['isForum'] ?? false) {
1024 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
1026 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
1029 if (($receiver != 0) && empty($item['contact-id'])) {
1030 $item['contact-id'] = Contact::getIdForURL($activity['author']);
1033 if (!empty($activity['directmessage'])) {
1034 self::postMail($activity, $item);
1038 if (($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT) && !in_array($item['post-reason'], [Item::PR_FOLLOWER, Item::PR_TAG, item::PR_TO, Item::PR_CC])) {
1039 if (!($item['isForum'] ?? false)) {
1040 if ($item['post-reason'] == Item::PR_BCC) {
1041 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id'], 'url' => $item['uri']]);
1045 if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE)
1046 && in_array($activity['thread-children-type'] ?? '', Receiver::ACTIVITY_TYPES)) {
1047 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
1048 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
1054 $user = User::getById($receiver, ['account-type']);
1055 if (!empty($user['account-type'])) {
1056 $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
1059 if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE)
1060 && ((!$is_forum && !($item['isForum'] ?? false) && ($activity['type'] != 'as:Announce'))
1061 || !Contact::isSharingByURL($activity['actor'], $receiver))) {
1062 Logger::info('Actor is a non sharer, is no forum or it is no announce', ['uid' => $receiver, 'actor' => $activity['actor'], 'url' => $item['uri'], 'type' => $activity['type']]);
1066 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
1069 if (!self::hasParents($item, $receiver)) {
1073 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
1074 $event_id = self::createEvent($activity, $item);
1076 $item = Event::getItemArrayForImportedId($event_id, $item);
1079 $item_id = Item::insert($item);
1081 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
1084 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
1085 if (($item['uid'] == 0) && (count($activity['receiver']) > 1)) {
1086 Logger::info('Public item was aborted. We skip for all users.', ['uri' => $item['uri']]);
1091 if ($item['uid'] == 0) {
1096 Queue::remove($activity);
1098 if ($success && Queue::hasChildren($item['uri']) && Post::exists(['uri' => $item['uri']])) {
1099 Queue::processReplyByUri($item['uri']);
1102 // Store send a follow request for every reshare - but only when the item had been stored
1103 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
1104 $author = APContact::getByURL($item['owner-link'], false);
1105 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
1106 if ($author['type'] != 'Group') {
1107 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
1108 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
1114 * Checks if there are parent posts for the given receiver.
1115 * If not, then the system will try to add them.
1117 * @param array $item
1118 * @param integer $receiver
1121 private static function hasParents(array $item, int $receiver)
1123 if (($receiver == 0) || ($item['gravity'] == GRAVITY_PARENT)) {
1127 $fields = ['causer-id' => $item['causer-id'] ?? $item['author-id'], 'post-reason' => Item::PR_FETCHED];
1129 $has_parents = false;
1131 if (!empty($item['parent-uri-id'])) {
1132 if (Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $receiver])) {
1133 $has_parents = true;
1134 } elseif (Post::exists(['uri-id' => $item['parent-uri'], 'uid' => 0])) {
1135 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $receiver, $fields);
1136 $has_parents = (bool)$stored;
1138 Logger::notice('Inserted missing parent post', ['stored' => $stored, 'uid' => $receiver, 'parent' => $item['parent-uri']]);
1140 Logger::notice('Parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1146 if (empty($item['parent-uri-id']) || ($item['thr-parent-id'] != $item['parent-uri-id'])) {
1147 if (Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $receiver])) {
1148 $has_parents = true;
1149 } elseif (Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => 0])) {
1150 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $receiver, $fields);
1151 $has_parents = $has_parents || (bool)$stored;
1153 Logger::notice('Inserted missing thread parent post', ['stored' => $stored, 'uid' => $receiver, 'thread-parent' => $item['thr-parent']]);
1155 Logger::notice('Thread parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1160 return $has_parents;
1164 * Store tags and mentions into the tag table
1166 * @param integer $uriid
1167 * @param array $tags
1169 private static function storeTags(int $uriid, array $tags = null)
1171 foreach ($tags as $tag) {
1172 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1176 $hash = substr($tag['name'], 0, 1);
1178 if ($tag['type'] == 'Mention') {
1179 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1180 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1181 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1182 $tag['name'] = substr($tag['name'], 1);
1184 $type = Tag::IMPLICIT_MENTION;
1186 if (!empty($tag['href'])) {
1187 $apcontact = APContact::getByURL($tag['href']);
1188 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1189 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1192 } elseif ($tag['type'] == 'Hashtag') {
1193 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1194 $tag['name'] = substr($tag['name'], 1);
1196 $type = Tag::HASHTAG;
1199 if (empty($tag['name'])) {
1203 Tag::store($uriid, $type, $tag['name'], $tag['href']);
1207 public static function storeReceivers(int $uriid, array $receivers)
1209 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
1210 if (!empty($receivers[$element])) {
1211 foreach ($receivers[$element] as $receiver) {
1212 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1213 $name = Receiver::PUBLIC_COLLECTION;
1215 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
1218 $target = Tag::getTargetType($receiver);
1219 Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1220 Tag::store($uriid, $type, $name, $receiver, $target);
1227 * Creates an mail post
1229 * @param array $activity Activity data
1230 * @param array $item item array
1231 * @return int|bool New mail table row id or false on error
1232 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1234 private static function postMail(array $activity, array $item)
1236 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1237 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1241 Logger::info('Direct Message', $item);
1244 $msg['uid'] = $item['uid'];
1246 $msg['contact-id'] = $item['contact-id'];
1248 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1249 $msg['from-name'] = $contact['name'];
1250 $msg['from-url'] = $contact['url'];
1251 $msg['from-photo'] = $contact['photo'];
1253 $msg['uri'] = $item['uri'];
1254 $msg['created'] = $item['created'];
1256 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1257 if (DBA::isResult($parent)) {
1258 $msg['parent-uri'] = $parent['parent-uri'];
1259 $msg['title'] = $parent['title'];
1261 $msg['parent-uri'] = $item['thr-parent'];
1263 if (!empty($item['title'])) {
1264 $msg['title'] = $item['title'];
1265 } elseif (!empty($item['content-warning'])) {
1266 $msg['title'] = $item['content-warning'];
1268 // Trying to generate a title out of the body
1269 $title = $item['body'];
1271 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1272 $title = $matches[3];
1275 $title = trim(BBCode::toPlaintext($title));
1277 if (strlen($title) > 20) {
1278 $title = substr($title, 0, 20) . '...';
1281 $msg['title'] = $title;
1284 $msg['body'] = $item['body'];
1286 return Mail::insert($msg);
1290 * Fetch featured posts from a contact with the given url
1292 * @param string $url
1295 public static function fetchFeaturedPosts(string $url)
1297 Logger::info('Fetch featured posts', ['contact' => $url]);
1299 $apcontact = APContact::getByURL($url);
1300 if (empty($apcontact['featured'])) {
1301 Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1305 $pcid = Contact::getIdForURL($url, 0, false);
1307 Logger::info('Contact not found', ['contact' => $url]);
1311 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1312 if (!empty($posts)) {
1313 $old_featured = array_column($posts, 'uri-id');
1318 $featured = ActivityPub::fetchItems($apcontact['featured']);
1319 if (empty($featured)) {
1320 Logger::info('Contact does not have featured posts', ['contact' => $url]);
1322 foreach ($old_featured as $uri_id) {
1323 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1324 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1332 foreach ($featured as $post) {
1333 if (empty($post['id'])) {
1336 $id = Item::fetchByLink($post['id']);
1338 $item = Post::selectFirst(['uri-id', 'featured'], ['id' => $id]);
1339 if (!empty($item['uri-id'])) {
1340 if (!$item['featured']) {
1341 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED);
1342 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1345 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1349 $index = array_search($item['uri-id'], $old_featured);
1350 if (!($index === false)) {
1351 unset($old_featured[$index]);
1357 foreach ($old_featured as $uri_id) {
1358 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1359 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1362 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1365 public static function fetchCachedActivity(string $url, int $uid): array
1367 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . $url;
1368 $object = DI::cache()->get($cachekey);
1370 if (!is_null($object)) {
1371 if (!empty($object)) {
1372 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1374 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1379 $object = ActivityPub::fetchContent($url, $uid);
1380 if (empty($object)) {
1381 Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1382 // We perform negative caching.
1383 DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1387 if (empty($object['id'])) {
1388 Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1391 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1393 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1399 * Fetches missing posts
1401 * @param string $url message URL
1402 * @param array $child activity array with the child of this message
1403 * @param string $relay_actor Relay actor
1404 * @param int $completion Completion mode, see Receiver::COMPLETION_*
1405 * @return string fetched message URL
1406 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1407 * @throws \ImagickException
1409 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL): string
1411 $object = self::fetchCachedActivity($url, 0);
1412 if (empty($object)) {
1418 if (!empty($object['attributedTo'])) {
1419 $attributed_to = $object['attributedTo'];
1420 if (is_array($attributed_to)) {
1421 $compacted = JsonLD::compact($object);
1422 $attributed_to = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1424 $signer[] = $attributed_to;
1427 if (!empty($object['actor'])) {
1428 $object_actor = $object['actor'];
1429 } elseif (!empty($attributed_to)) {
1430 $object_actor = $attributed_to;
1436 $signer[] = $object_actor;
1438 if (!empty($child['author'])) {
1439 $actor = $child['author'];
1442 $actor = $object_actor;
1445 if (!empty($object['published'])) {
1446 $published = $object['published'];
1447 } elseif (!empty($child['published'])) {
1448 $published = $child['published'];
1450 $published = DateTimeFormat::utcNow();
1454 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1455 unset($object['@context']);
1456 $activity['id'] = $object['id'];
1457 $activity['to'] = $object['to'] ?? [];
1458 $activity['cc'] = $object['cc'] ?? [];
1459 $activity['actor'] = $actor;
1460 $activity['object'] = $object;
1461 $activity['published'] = $published;
1462 $activity['type'] = 'Create';
1464 $ldactivity = JsonLD::compact($activity);
1466 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 0;
1468 if (!empty($relay_actor)) {
1469 $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
1470 $ldactivity['completion-mode'] = Receiver::COMPLETION_RELAY;
1471 } elseif (!empty($child['thread-completion'])) {
1472 $ldactivity['thread-completion'] = $child['thread-completion'];
1473 $ldactivity['completion-mode'] = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1475 $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
1476 $ldactivity['completion-mode'] = $completion;
1479 if (!empty($child['thread-children-type'])) {
1480 $ldactivity['thread-children-type'] = $child['thread-children-type'];
1481 } elseif (!empty($child['type'])) {
1482 $ldactivity['thread-children-type'] = $child['type'];
1484 $ldactivity['thread-children-type'] = 'as:Create';
1487 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
1491 if (($completion == Receiver::COMPLETION_RELAY) && Queue::exists($url, 'as:Create')) {
1492 Logger::notice('Activity has already been queued.', ['url' => $url, 'object' => $activity['id']]);
1493 } elseif (ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), 0, true, false, $signer, '', $completion)) {
1494 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1496 Logger::notice('Activity had been fetched and will be processed later.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1499 return $activity['id'];
1503 * Test if incoming relay messages should be accepted
1505 * @param array $activity activity array
1506 * @param string $id object ID
1507 * @return boolean true if message is accepted
1509 private static function acceptIncomingMessage(array $activity, string $id): bool
1511 if (empty($activity['as:object'])) {
1512 Logger::info('No object field in activity - accepted', ['id' => $id]);
1516 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1517 $uriid = ItemURI::getIdByURI($replyto ?? '');
1518 if (Post::exists(['uri-id' => $uriid])) {
1519 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1523 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1524 $authorid = Contact::getIdForURL($attributed_to);
1526 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1529 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1530 if (!empty($tags)) {
1531 foreach ($tags as $tag) {
1532 if ($tag['type'] != 'Hashtag') {
1535 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1539 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
1543 * perform a "follow" request
1545 * @param array $activity
1547 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1548 * @throws \ImagickException
1550 public static function followUser(array $activity)
1552 $uid = User::getIdForURL($activity['object_id']);
1554 Queue::remove($activity);
1558 $owner = User::getOwnerDataById($uid);
1559 if (empty($owner)) {
1563 $cid = Contact::getIdForURL($activity['actor'], $uid);
1565 self::switchContact($cid);
1566 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1570 'author-id' => Contact::getIdForURL($activity['actor']),
1571 'author-link' => $activity['actor'],
1574 // Ensure that the contact has got the right network type
1575 self::switchContact($item['author-id']);
1577 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1578 if ($result === true) {
1579 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1582 $cid = Contact::getIdForURL($activity['actor'], $uid);
1587 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1588 self::transmitPendingEvents($cid, $owner['uid']);
1591 if (empty($contact)) {
1592 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1594 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1595 Queue::remove($activity);
1599 * Transmit pending events to the new follower
1601 * @param integer $cid Contact id
1602 * @param integer $uid User id
1605 private static function transmitPendingEvents(int $cid, int $uid)
1607 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1608 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1610 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1611 while ($event = DBA::fetch($events)) {
1612 $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1616 if (DI::config()->get('system', 'bulk_delivery')) {
1617 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1618 Worker::add(PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1620 Worker::add(PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1626 * Update the given profile
1628 * @param array $activity
1629 * @throws \Exception
1631 public static function updatePerson(array $activity)
1633 if (empty($activity['object_id'])) {
1637 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1638 Contact::updateFromProbeByURL($activity['object_id']);
1639 Queue::remove($activity);
1643 * Delete the given profile
1645 * @param array $activity
1647 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1649 public static function deletePerson(array $activity)
1651 if (empty($activity['object_id']) || empty($activity['actor'])) {
1652 Logger::info('Empty object id or actor.');
1656 if ($activity['object_id'] != $activity['actor']) {
1657 Logger::info('Object id does not match actor.');
1661 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1662 while ($contact = DBA::fetch($contacts)) {
1663 Contact::remove($contact['id']);
1665 DBA::close($contacts);
1667 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1668 Queue::remove($activity);
1672 * Blocks the user by the contact
1674 * @param array $activity
1676 * @throws \Exception
1678 public static function blockAccount(array $activity)
1680 $cid = Contact::getIdForURL($activity['actor']);
1685 $uid = User::getIdForURL($activity['object_id']);
1690 Contact\User::setIsBlocked($cid, $uid, true);
1692 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1693 Queue::remove($activity);
1697 * Unblocks the user by the contact
1699 * @param array $activity
1701 * @throws \Exception
1703 public static function unblockAccount(array $activity)
1705 $cid = Contact::getIdForURL($activity['actor']);
1710 $uid = User::getIdForURL($activity['object_object']);
1715 Contact\User::setIsBlocked($cid, $uid, false);
1717 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1718 Queue::remove($activity);
1722 * Accept a follow request
1724 * @param array $activity
1725 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1726 * @throws \ImagickException
1728 public static function acceptFollowUser(array $activity)
1730 $uid = User::getIdForURL($activity['object_actor']);
1735 $cid = Contact::getIdForURL($activity['actor'], $uid);
1737 Logger::info('No contact found', ['actor' => $activity['actor']]);
1741 self::switchContact($cid);
1743 $fields = ['pending' => false];
1745 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1746 if ($contact['rel'] == Contact::FOLLOWER) {
1747 $fields['rel'] = Contact::FRIEND;
1750 $condition = ['id' => $cid];
1751 Contact::update($fields, $condition);
1752 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1753 Queue::remove($activity);
1757 * Reject a follow request
1759 * @param array $activity
1760 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1761 * @throws \ImagickException
1763 public static function rejectFollowUser(array $activity)
1765 $uid = User::getIdForURL($activity['object_actor']);
1770 $cid = Contact::getIdForURL($activity['actor'], $uid);
1772 Logger::info('No contact found', ['actor' => $activity['actor']]);
1776 self::switchContact($cid);
1778 $contact = Contact::getById($cid, ['rel']);
1779 if ($contact['rel'] == Contact::SHARING) {
1780 Contact::remove($cid);
1781 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1782 } elseif ($contact['rel'] == Contact::FRIEND) {
1783 Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1785 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1787 Queue::remove($activity);
1791 * Undo activity like "like" or "dislike"
1793 * @param array $activity
1794 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1795 * @throws \ImagickException
1797 public static function undoActivity(array $activity)
1799 if (empty($activity['object_id'])) {
1803 if (empty($activity['object_actor'])) {
1807 $author_id = Contact::getIdForURL($activity['object_actor']);
1808 if (empty($author_id)) {
1812 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1813 Queue::remove($activity);
1817 * Activity to remove a follower
1819 * @param array $activity
1820 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1821 * @throws \ImagickException
1823 public static function undoFollowUser(array $activity)
1825 $uid = User::getIdForURL($activity['object_object']);
1830 $owner = User::getOwnerDataById($uid);
1831 if (empty($owner)) {
1835 $cid = Contact::getIdForURL($activity['actor'], $uid);
1837 Logger::info('No contact found', ['actor' => $activity['actor']]);
1841 self::switchContact($cid);
1843 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1844 if (!DBA::isResult($contact)) {
1848 Contact::removeFollower($contact);
1849 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1850 Queue::remove($activity);
1854 * Switches a contact to AP if needed
1856 * @param integer $cid Contact ID
1858 * @throws \Exception
1860 private static function switchContact(int $cid)
1862 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1863 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1867 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1868 Contact::updateFromProbe($cid);
1872 * Collects implicit mentions like:
1873 * - the author of the parent item
1874 * - all the mentioned conversants in the parent item
1876 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1878 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1880 private static function getImplicitMentionList(array $parent): array
1882 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1884 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1886 $implicit_mentions = [];
1887 if (empty($parent_author['url'])) {
1888 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1890 $implicit_mentions[] = $parent_author['url'];
1891 $implicit_mentions[] = $parent_author['nurl'];
1892 $implicit_mentions[] = $parent_author['alias'];
1895 if (!empty($parent['alias'])) {
1896 $implicit_mentions[] = $parent['alias'];
1899 foreach ($parent_terms as $term) {
1900 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1901 if (!empty($contact['url'])) {
1902 $implicit_mentions[] = $contact['url'];
1903 $implicit_mentions[] = $contact['nurl'];
1904 $implicit_mentions[] = $contact['alias'];
1908 return $implicit_mentions;
1912 * Strips from the body prepended implicit mentions
1914 * @param string $body
1915 * @param array $parent
1918 private static function removeImplicitMentionsFromBody(string $body, array $parent): string
1920 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1924 $potential_mentions = self::getImplicitMentionList($parent);
1926 $kept_mentions = [];
1928 // Extract one prepended mention at a time from the body
1929 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1930 if (!in_array($matches[2], $potential_mentions)) {
1931 $kept_mentions[] = $matches[1];
1934 $body = $matches[3];
1937 // Re-appending the kept mentions to the body after extraction
1938 $kept_mentions[] = $body;
1940 return implode('', $kept_mentions);
1944 * Adds links to string mentions
1946 * @param string $body
1947 * @param array $tags
1950 protected static function addMentionLinks(string $body, array $tags): string
1952 // This prevents links to be added again to Pleroma-style mention links
1953 $body = self::normalizeMentionLinks($body);
1955 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
1956 foreach ($tags as $tag) {
1957 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1961 $hash = substr($tag['name'], 0, 1);
1962 $name = substr($tag['name'], 1);
1963 if (!in_array($hash, Tag::TAG_CHARACTER)) {
1965 $name = $tag['name'];
1968 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);