3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Event;
38 use Friendica\Model\GServer;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Model\Post;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\ActivityPub;
47 use Friendica\Protocol\Delivery;
48 use Friendica\Protocol\Relay;
49 use Friendica\Util\DateTimeFormat;
50 use Friendica\Util\HTTPSignature;
51 use Friendica\Util\JsonLD;
52 use Friendica\Util\Network;
53 use Friendica\Util\Strings;
56 * ActivityPub Processor Protocol class
60 const CACHEKEY_FETCH_ACTIVITY = 'processor:fetchMissingActivity:';
61 const CACHEKEY_JUST_FETCHED = 'processor:isJustFetched:';
64 * Add an object id to the list of processed ids
70 private static function addActivityId(string $id)
72 DBA::delete('fetched-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
73 DBA::insert('fetched-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()]);
77 * Checks if the given object id has just been fetched
83 private static function isFetched(string $id): bool
85 return DBA::exists('fetched-activity', ['object-id' => $id]);
89 * Extracts the tag character (#, @, !) from mention links
94 public static function normalizeMentionLinks(string $body): string
96 $body = preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
97 $body = preg_replace('%([#@!])\[zrl=([^\[\]]*)](.*?)\[/zrl]%ism', '$1[url=$2]$3[/url]', $body);
102 * Convert the language array into a language JSON
104 * @param array $languages
105 * @return string language JSON
107 private static function processLanguages(array $languages): string
109 $codes = array_keys($languages);
111 foreach ($codes as $code) {
119 return json_encode($lang);
122 * Replaces emojis in the body
125 * @param string $body
126 * @param array $emojis
128 * @return string with replaced emojis
130 private static function replaceEmojis(int $uri_id, string $body, array $emojis): string
134 array_column($emojis, 'name'),
135 array_map(function ($emoji) {
136 return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
141 // We store the emoji here to be able to avoid storing it in the media
142 foreach ($emojis as $emoji) {
143 Post\Link::getByLink($uri_id, $emoji['href']);
149 * Store attached media files in the post-media table
152 * @param array $attachment
155 private static function storeAttachmentAsMedia(int $uriid, array $attachment)
157 if (empty($attachment['url'])) {
161 $data = ['uri-id' => $uriid];
162 $data['type'] = Post\Media::UNKNOWN;
163 $data['url'] = $attachment['url'];
164 $data['mimetype'] = $attachment['mediaType'] ?? null;
165 $data['height'] = $attachment['height'] ?? null;
166 $data['width'] = $attachment['width'] ?? null;
167 $data['size'] = $attachment['size'] ?? null;
168 $data['preview'] = $attachment['image'] ?? null;
169 $data['description'] = $attachment['name'] ?? null;
171 Post\Media::insert($data);
175 * Store attachment data
177 * @param array $activity
180 private static function storeAttachments(array $activity, array $item)
182 if (empty($activity['attachments'])) {
186 foreach ($activity['attachments'] as $attach) {
187 self::storeAttachmentAsMedia($item['uri-id'], $attach);
192 * Store question data
194 * @param array $activity
197 private static function storeQuestion(array $activity, array $item)
199 if (empty($activity['question'])) {
202 $question = ['multiple' => $activity['question']['multiple']];
204 if (!empty($activity['question']['voters'])) {
205 $question['voters'] = $activity['question']['voters'];
208 if (!empty($activity['question']['end-time'])) {
209 $question['end-time'] = DateTimeFormat::utc($activity['question']['end-time']);
212 Post\Question::update($item['uri-id'], $question);
214 foreach ($activity['question']['options'] as $key => $option) {
215 $option = ['name' => $option['name'], 'replies' => $option['replies']];
216 Post\QuestionOption::update($item['uri-id'], $key, $option);
219 Logger::debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]);
225 * @param array $activity Activity array
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 * @throws \ImagickException
229 public static function updateItem(array $activity)
231 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type', 'private'], ['uri' => $activity['id']]);
232 if (!DBA::isResult($item)) {
233 Logger::notice('No existing item, item will be created', ['uri' => $activity['id']]);
234 $item = self::createItem($activity, false);
236 Queue::remove($activity);
240 self::postItem($activity, $item);
244 $item['changed'] = DateTimeFormat::utcNow();
245 $item['edited'] = DateTimeFormat::utc($activity['updated']);
247 Post\Media::deleteByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE, Post\Media::HTML]);
248 $item = self::processContent($activity, $item);
250 Queue::remove($activity);
254 self::storeAttachments($activity, $item);
255 self::storeQuestion($activity, $item);
257 Post\History::add($item['uri-id'], $item);
258 Item::update($item, ['uri' => $activity['id']]);
260 Queue::remove($activity);
262 if ($activity['object_type'] == 'as:Event') {
263 $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
264 while ($post = DBA::fetch($posts)) {
265 self::updateEvent($post['event-id'], $activity);
271 * Update an existing event
273 * @param int $event_id
274 * @param array $activity
276 private static function updateEvent(int $event_id, array $activity)
278 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
280 $event['edited'] = DateTimeFormat::utc($activity['updated']);
281 $event['summary'] = HTML::toBBCode($activity['name']);
282 $event['desc'] = HTML::toBBCode($activity['content']);
283 if (!empty($activity['start-time'])) {
284 $event['start'] = DateTimeFormat::utc($activity['start-time']);
286 if (!empty($activity['end-time'])) {
287 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
289 $event['nofinish'] = empty($event['finish']);
290 $event['location'] = $activity['location'];
292 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
293 Event::store($event);
297 * Prepares data for a message
299 * @param array $activity Activity array
300 * @param bool $fetch_parents
302 * @return array Internal item
304 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305 * @throws \ImagickException
307 public static function createItem(array $activity, bool $fetch_parents): array
310 $item['verb'] = Activity::POST;
311 $item['thr-parent'] = $activity['reply-to-id'];
313 if ($activity['reply-to-id'] == $activity['id']) {
314 $item['gravity'] = Item::GRAVITY_PARENT;
315 $item['object-type'] = Activity\ObjectType::NOTE;
317 $item['gravity'] = Item::GRAVITY_COMMENT;
318 $item['object-type'] = Activity\ObjectType::COMMENT;
321 if (!empty($activity['conversation'])) {
322 $item['conversation'] = $activity['conversation'];
323 } elseif (!empty($activity['context'])) {
324 $item['conversation'] = $activity['context'];
327 if (!empty($item['conversation'])) {
328 $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]);
329 if (!empty($conversation)) {
330 Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]);
331 $item['parent-uri'] = $conversation['uri'];
332 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
338 Logger::debug('Create Item', ['id' => $activity['id'], 'conversation' => $item['conversation'] ?? '']);
339 if (empty($activity['author']) && empty($activity['actor'])) {
340 Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]);
341 Queue::remove($activity);
345 if (!in_array(0, $activity['receiver']) || !DI::config()->get('system', 'fetch_parents')) {
346 $fetch_parents = false;
349 if ($fetch_parents && empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
350 $result = self::fetchParent($activity, !empty($conversation));
351 if (!empty($result)) {
352 if (($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
353 $item['thr-parent'] = $result;
355 } elseif (empty($conversation)) {
360 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
362 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != Item::GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
363 Logger::notice('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
364 if (!$fetch_parents) {
365 Queue::remove($activity);
370 $item['network'] = Protocol::ACTIVITYPUB;
371 $item['author-link'] = $activity['author'];
372 $item['author-id'] = Contact::getIdForURL($activity['author']);
373 $item['owner-link'] = $activity['actor'];
374 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
376 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
377 $item['private'] = Item::UNLISTED;
378 } elseif (in_array(0, $activity['receiver'])) {
379 $item['private'] = Item::PUBLIC;
381 $item['private'] = Item::PRIVATE;
384 if (!empty($activity['raw'])) {
385 $item['source'] = $activity['raw'];
388 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
390 if (isset($activity['push'])) {
391 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
394 if (!empty($activity['from-relay'])) {
395 $item['direction'] = Conversation::RELAY;
398 if ($activity['object_type'] == 'as:Article') {
399 $item['post-type'] = Item::PT_ARTICLE;
400 } elseif ($activity['object_type'] == 'as:Audio') {
401 $item['post-type'] = Item::PT_AUDIO;
402 } elseif ($activity['object_type'] == 'as:Document') {
403 $item['post-type'] = Item::PT_DOCUMENT;
404 } elseif ($activity['object_type'] == 'as:Event') {
405 $item['post-type'] = Item::PT_EVENT;
406 } elseif ($activity['object_type'] == 'as:Image') {
407 $item['post-type'] = Item::PT_IMAGE;
408 } elseif ($activity['object_type'] == 'as:Page') {
409 $item['post-type'] = Item::PT_PAGE;
410 } elseif ($activity['object_type'] == 'as:Question') {
411 $item['post-type'] = Item::PT_POLL;
412 } elseif ($activity['object_type'] == 'as:Video') {
413 $item['post-type'] = Item::PT_VIDEO;
415 $item['post-type'] = Item::PT_NOTE;
418 $item['isForum'] = false;
420 if (!empty($activity['thread-completion'])) {
421 if ($activity['thread-completion'] != $item['owner-id']) {
422 $actor = Contact::getById($activity['thread-completion'], ['url']);
423 $item['causer-link'] = $actor['url'];
424 $item['causer-id'] = $activity['thread-completion'];
425 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
427 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
428 $item['causer-link'] = $item['owner-link'];
429 $item['causer-id'] = $item['owner-id'];
430 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
433 $item['owner-link'] = $item['author-link'];
434 $item['owner-id'] = $item['author-id'];
436 $actor = APContact::getByURL($item['owner-link'], false);
437 $item['isForum'] = ($actor['type'] ?? 'Person') == 'Group';
440 $item['uri'] = $activity['id'];
442 if (empty($activity['published']) || empty($activity['updated'])) {
443 DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
446 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
447 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
448 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
449 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
451 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
452 if (empty($item['uri-id'])) {
453 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
457 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
459 $item = self::processContent($activity, $item);
461 Logger::info('Message was not processed');
462 Queue::remove($activity);
466 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
468 self::storeAttachments($activity, $item);
469 self::storeQuestion($activity, $item);
471 // We received the post via AP, so we set the protocol of the server to AP
472 $contact = Contact::getById($item['author-id'], ['gsid']);
473 if (!empty($contact['gsid'])) {
474 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
477 if ($item['author-id'] != $item['owner-id']) {
478 $contact = Contact::getById($item['owner-id'], ['gsid']);
479 if (!empty($contact['gsid'])) {
480 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
488 * Fetch and process parent posts for the given activity
490 * @param array $activity
491 * @param bool $in_background
495 private static function fetchParent(array $activity, bool $in_background = false): string
497 if (self::isFetched($activity['reply-to-id'])) {
498 Logger::info('Id is already fetched', ['id' => $activity['reply-to-id']]);
502 self::addActivityId($activity['reply-to-id']);
504 if (!DI::config()->get('system', 'fetch_by_worker')) {
505 $in_background = false;
508 $recursion_depth = $activity['recursion-depth'] ?? 0;
510 if (!$in_background && ($recursion_depth < DI::config()->get('system', 'max_recursion_depth'))) {
511 Logger::info('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
512 $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
513 if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
514 Logger::notice('The activity is gone, the queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
515 if (!empty($activity['entry-id'])) {
516 Queue::deleteById($activity['entry-id']);
519 } elseif (!empty($result)) {
520 $exists = Post::exists(['uri' => [$result, $activity['reply-to-id']]]);
522 Logger::info('The activity has been fetched and created.', ['parent' => $result]);
524 } elseif (DI::config()->get('system', 'fetch_by_worker') || DI::config()->get('system', 'decoupled_receiver')) {
525 Logger::info('The activity has been fetched and will hopefully be created later.', ['parent' => $result]);
527 Logger::notice('The activity exists but has not been created, the queue entry will be deleted.', ['parent' => $result]);
528 if (!empty($activity['entry-id'])) {
529 Queue::deleteById($activity['entry-id']);
534 if (empty($result) && !DI::config()->get('system', 'fetch_by_worker')) {
537 } elseif (self::isActivityGone($activity['reply-to-id'])) {
538 Logger::notice('The activity is gone. We will not spawn a worker. The queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
539 if ($in_background) {
540 // fetching in background is done for all activities where we have got the conversation
541 // There we only delete the single activity and not the whole thread since we can store the
542 // other posts in the thread even with missing posts.
543 Queue::remove($activity);
544 } elseif (!empty($activity['entry-id'])) {
545 Queue::deleteById($activity['entry-id']);
548 } elseif ($in_background) {
549 Logger::notice('Fetching is done in the background.', ['parent' => $activity['reply-to-id']]);
551 Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
554 if (!Fetch::hasWorker($activity['reply-to-id'])) {
555 Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
556 Fetch::add($activity['reply-to-id']);
557 $activity['recursion-depth'] = 0;
558 $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
559 Fetch::setWorkerId($activity['reply-to-id'], $wid);
561 Logger::debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]);
568 * Check if a given activity is no longer available
574 public static function isActivityGone(string $url): bool
577 $curlResult = HTTPSignature::fetchRaw($url, 0);
578 } catch (\Exception $exception) {
579 Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
583 if (Network::isUrlBlocked($url)) {
587 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
588 if (in_array($curlResult->getReturnCode(), [401, 404])) {
592 if ($curlResult->isSuccess()) {
593 $object = json_decode($curlResult->getBody(), true);
594 if (!empty($object)) {
595 $activity = JsonLD::compact($object);
596 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
600 } elseif ($curlResult->getReturnCode() == 0) {
601 $host = parse_url($url, PHP_URL_HOST);
602 if (!(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) {
612 * @param array $activity
613 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
614 * @throws \ImagickException
616 public static function deleteItem(array $activity)
618 $owner = Contact::getIdForURL($activity['actor']);
620 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
621 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
622 Queue::remove($activity);
626 * Prepare the item array for an activity
628 * @param array $activity Activity array
629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
630 * @throws \ImagickException
632 public static function addTag(array $activity)
634 if (empty($activity['object_content']) || empty($activity['object_id'])) {
638 foreach ($activity['receiver'] as $receiver) {
639 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
640 if (!DBA::isResult($item)) {
641 // We don't fetch missing content for this purpose
645 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
646 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
650 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
651 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
656 * Prepare the item array for an activity
658 * @param array $activity Activity array
659 * @param string $verb Activity verb
660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
661 * @throws \ImagickException
663 public static function createActivity(array $activity, string $verb)
665 $activity['reply-to-id'] = $activity['object_id'];
666 $item = self::createItem($activity, false);
668 Logger::debug('Activity was not prepared', ['id' => $activity['object_id']]);
672 $item['verb'] = $verb;
673 $item['thr-parent'] = $activity['object_id'];
674 $item['gravity'] = Item::GRAVITY_ACTIVITY;
675 unset($item['post-type']);
676 $item['object-type'] = Activity\ObjectType::NOTE;
678 if (!empty($activity['content'])) {
679 $item['body'] = HTML::toBBCode($activity['content']);
682 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
684 self::postItem($activity, $item);
688 * Fetch the Uri-Id of a post for the "featured" collection
690 * @param array $activity
693 private static function getUriIdForFeaturedCollection(array $activity)
695 $actor = APContact::getByURL($activity['actor']);
700 // Refetch the account when the "featured" collection is missing.
701 // This can be removed in a future version (end of 2022 should be good).
702 if (empty($actor['featured'])) {
703 $actor = APContact::getByURL($activity['actor'], true);
709 $parent = Post::selectFirst(['uri-id', 'author-id'], ['uri' => $activity['object_id']]);
710 if (empty($parent['uri-id'])) {
711 if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
712 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
716 if (!empty($parent['uri-id'])) {
724 * Add a post to the "Featured" collection
726 * @param array $activity
728 public static function addToFeaturedCollection(array $activity)
730 $post = self::getUriIdForFeaturedCollection($activity);
735 Logger::debug('Add post to featured collection', ['post' => $post]);
737 Post\Collection::add($post['uri-id'], Post\Collection::FEATURED, $post['author-id']);
738 Queue::remove($activity);
742 * Remove a post to the "Featured" collection
744 * @param array $activity
746 public static function removeFromFeaturedCollection(array $activity)
748 $post = self::getUriIdForFeaturedCollection($activity);
753 Logger::debug('Remove post from featured collection', ['post' => $post]);
755 Post\Collection::remove($post['uri-id'], Post\Collection::FEATURED);
756 Queue::remove($activity);
762 * @param array $activity Activity array
765 * @return int event id
768 public static function createEvent(array $activity, array $item): int
770 $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']);
771 $event['desc'] = HTML::toBBCode($activity['content'] ?? '');
772 if (!empty($activity['start-time'])) {
773 $event['start'] = DateTimeFormat::utc($activity['start-time']);
775 if (!empty($activity['end-time'])) {
776 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
778 $event['nofinish'] = empty($event['finish']);
779 $event['location'] = $activity['location'];
780 $event['cid'] = $item['contact-id'];
781 $event['uid'] = $item['uid'];
782 $event['uri'] = $item['uri'];
783 $event['edited'] = $item['edited'];
784 $event['private'] = $item['private'];
785 $event['guid'] = $item['guid'];
786 $event['plink'] = $item['plink'];
787 $event['network'] = $item['network'];
788 $event['protocol'] = $item['protocol'];
789 $event['direction'] = $item['direction'];
790 $event['source'] = $item['source'];
792 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
793 if (DBA::isResult($ev)) {
794 $event['id'] = $ev['id'];
797 $event_id = Event::store($event);
799 Logger::info('Event was stored', ['id' => $event_id]);
805 * Process the content
807 * @param array $activity Activity array
809 * @return array|bool Returns the item array or false if there was an unexpected occurrence
812 private static function processContent(array $activity, array $item)
814 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
815 $item['title'] = strip_tags($activity['name'] ?? '');
816 $content = Markdown::toBBCode($activity['content']);
817 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
818 $item['title'] = $activity['name'];
819 $content = $activity['content'];
821 // By default assume "text/html"
822 $item['title'] = HTML::toBBCode($activity['name'] ?? '');
823 $content = HTML::toBBCode($activity['content'] ?? '');
826 $item['title'] = trim(BBCode::toPlaintext($item['title']));
828 if (!empty($activity['languages'])) {
829 $item['language'] = self::processLanguages($activity['languages']);
832 if (!empty($activity['emojis'])) {
833 $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
836 $content = self::addMentionLinks($content, $activity['tags']);
838 if (!empty($activity['quote-url'])) {
839 $id = Item::fetchByLink($activity['quote-url']);
841 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
842 $item['quote-uri-id'] = $shared_item['uri-id'];
844 Logger::info('Quote was not fetched', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url']]);
848 if (!empty($activity['source'])) {
849 $item['body'] = $activity['source'];
850 $item['raw-body'] = $content;
852 $quote_uri_id = Item::getQuoteUriId($item['body']);
853 if (empty($item['quote-uri-id']) && !empty($quote_uri_id)) {
854 $item['quote-uri-id'] = $quote_uri_id;
857 $item['body'] = BBCode::removeSharedData($item['body']);
859 $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
860 if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == Item::GRAVITY_COMMENT)) {
861 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
862 if (!DBA::isResult($parent)) {
863 Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
866 $content = self::removeImplicitMentionsFromBody($content, $parent);
868 $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
869 $item['raw-body'] = $item['body'] = $content;
872 self::storeFromBody($item);
873 self::storeTags($item['uri-id'], $activity['tags']);
875 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
877 $item['location'] = $activity['location'];
879 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
880 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
883 $item['app'] = $activity['generator'];
889 * Store hashtags and mentions
893 private static function storeFromBody(array $item)
895 // Make sure to delete all existing tags (can happen when called via the update functionality)
896 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
898 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
902 * Generate a GUID out of an URL of an ActivityPub post.
904 * @param string $url message URL
905 * @return string with GUID
907 private static function getGUIDByURL(string $url): string
909 $parsed = parse_url($url);
911 $host_hash = hash('crc32', $parsed['host']);
913 unset($parsed["scheme"]);
914 unset($parsed["host"]);
916 $path = implode("/", $parsed);
918 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
922 * Checks if an incoming message is wanted
924 * @param array $activity
926 * @return boolean Is the message wanted?
928 private static function isSolicitedMessage(array $activity, array $item): bool
930 // The checks are split to improve the support when searching why a message was accepted.
931 if (count($activity['receiver']) != 1) {
932 // The message has more than one receiver, so it is wanted.
933 Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
937 if ($item['private'] == Item::PRIVATE) {
938 // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
939 Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
943 if (!empty($activity['from-relay'])) {
944 // We check relay posts at another place. When it arrived here, the message is already checked.
945 Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
949 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUNCE])) {
950 // Manual completions and completions caused by reshares are allowed without any further checks.
951 Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
955 if ($item['gravity'] != Item::GRAVITY_PARENT) {
956 // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
957 // This can possibly be improved in the future.
958 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
962 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
963 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB, $activity['thread-completion'] ?? 0)) {
964 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
972 * Creates an item post
974 * @param array $activity Activity data
975 * @param array $item item array
976 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
977 * @throws \ImagickException
979 public static function postItem(array $activity, array $item)
987 ksort($activity['receiver']);
989 if (!self::isSolicitedMessage($activity, $item)) {
990 DBA::delete('item-uri', ['id' => $item['uri-id']]);
991 if (!empty($activity['entry-id'])) {
992 Queue::deleteById($activity['entry-id']);
997 foreach ($activity['receiver'] as $receiver) {
998 if ($receiver == -1) {
1002 if (($receiver != 0) && empty($item['parent-uri-id']) && !empty($item['thr-parent-id'])) {
1003 $parent = Post::selectFirst(['parent-uri-id', 'parent-uri'], ['uri-id' => $item['thr-parent-id'], 'uid' => [0, $receiver]]);
1004 if (!empty($parent['parent-uri-id'])) {
1005 $item['parent-uri-id'] = $parent['parent-uri-id'];
1006 $item['parent-uri'] = $parent['parent-uri'];
1010 $item['uid'] = $receiver;
1012 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
1014 case Receiver::TARGET_TO:
1015 $item['post-reason'] = Item::PR_TO;
1017 case Receiver::TARGET_CC:
1018 $item['post-reason'] = Item::PR_CC;
1020 case Receiver::TARGET_BTO:
1021 $item['post-reason'] = Item::PR_BTO;
1023 case Receiver::TARGET_BCC:
1024 $item['post-reason'] = Item::PR_BCC;
1026 case Receiver::TARGET_FOLLOWER:
1027 $item['post-reason'] = Item::PR_FOLLOWER;
1029 case Receiver::TARGET_ANSWER:
1030 $item['post-reason'] = Item::PR_COMMENT;
1032 case Receiver::TARGET_GLOBAL:
1033 $item['post-reason'] = Item::PR_GLOBAL;
1036 $item['post-reason'] = Item::PR_NONE;
1039 $item['post-reason'] = Item::getPostReason($item);
1041 if (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE])) {
1042 if (!empty($activity['from-relay'])) {
1043 $item['post-reason'] = Item::PR_RELAY;
1044 } elseif (!empty($activity['thread-completion'])) {
1045 $item['post-reason'] = Item::PR_FETCHED;
1046 } elseif (!empty($activity['push'])) {
1047 $item['post-reason'] = Item::PR_PUSHED;
1049 } elseif (($item['post-reason'] == Item::PR_FOLLOWER) && !empty($activity['from-relay'])) {
1050 // When a post arrives via a relay and we follow the author, we have to override the causer.
1051 // Otherwise the system assumes that we follow the relay. (See "addRowInformation")
1052 Logger::debug('Relay post for follower', ['receiver' => $receiver, 'guid' => $item['guid'], 'relay' => $activity['from-relay']]);
1053 $item['causer-id'] = ($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1056 if ($item['isForum'] ?? false) {
1057 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
1059 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
1062 if (($receiver != 0) && empty($item['contact-id'])) {
1063 $item['contact-id'] = Contact::getIdForURL($activity['author']);
1066 if (!empty($activity['directmessage'])) {
1067 self::postMail($activity, $item);
1071 if (($receiver != 0) && ($item['gravity'] == Item::GRAVITY_PARENT) && !in_array($item['post-reason'], [Item::PR_FOLLOWER, Item::PR_TAG, item::PR_TO, Item::PR_CC])) {
1072 if (!($item['isForum'] ?? false)) {
1073 if ($item['post-reason'] == Item::PR_BCC) {
1074 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id'], 'url' => $item['uri']]);
1078 if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE)
1079 && in_array($activity['thread-children-type'] ?? '', Receiver::ACTIVITY_TYPES)) {
1080 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
1081 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
1087 $user = User::getById($receiver, ['account-type']);
1088 if (!empty($user['account-type'])) {
1089 $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
1092 if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE)
1093 && ((!$is_forum && !($item['isForum'] ?? false) && ($activity['type'] != 'as:Announce'))
1094 || !Contact::isSharingByURL($activity['actor'], $receiver))) {
1095 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']]);
1099 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
1102 if (!self::hasParents($item, $receiver)) {
1106 if (($item['gravity'] != Item::GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
1107 $event_id = self::createEvent($activity, $item);
1109 $item = Event::getItemArrayForImportedId($event_id, $item);
1112 $item_id = Item::insert($item);
1114 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
1117 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
1118 if (($item['uid'] == 0) && (count($activity['receiver']) > 1)) {
1119 Logger::info('Public item was aborted. We skip for all users.', ['uri' => $item['uri']]);
1124 if ($item['uid'] == 0) {
1129 Queue::remove($activity);
1131 if ($success && Queue::hasChildren($item['uri']) && Post::exists(['uri' => $item['uri']])) {
1132 Queue::processReplyByUri($item['uri']);
1135 // Store send a follow request for every reshare - but only when the item had been stored
1136 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == Item::GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
1137 $author = APContact::getByURL($item['owner-link'], false);
1138 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
1139 if ($author['type'] != 'Group') {
1140 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
1141 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
1147 * Checks if there are parent posts for the given receiver.
1148 * If not, then the system will try to add them.
1150 * @param array $item
1151 * @param integer $receiver
1154 private static function hasParents(array $item, int $receiver)
1156 if (($receiver == 0) || ($item['gravity'] == Item::GRAVITY_PARENT)) {
1160 $fields = ['causer-id' => $item['causer-id'] ?? $item['author-id'], 'post-reason' => Item::PR_FETCHED];
1164 if ($item['verb'] != Activity::ANNOUNCE) {
1165 switch (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer')) {
1166 case Item::COMPLETION_COMMENT:
1167 $add_parent = ($item['gravity'] != Item::GRAVITY_ACTIVITY);
1170 case Item::COMPLETION_NONE:
1171 $add_parent = false;
1177 $add_parent = Contact::isSharing($fields['causer-id'], $receiver);
1178 if (!$add_parent && ($item['author-id'] != $fields['causer-id'])) {
1179 $add_parent = Contact::isSharing($item['author-id'], $receiver);
1181 if (!$add_parent && !in_array($item['owner-id'], [$fields['causer-id'], $item['author-id']])) {
1182 $add_parent = Contact::isSharing($item['owner-id'], $receiver);
1186 $has_parents = false;
1188 if (!empty($item['parent-uri-id'])) {
1189 if (Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $receiver])) {
1190 $has_parents = true;
1191 } elseif ($add_parent && Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1192 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $receiver, $fields);
1193 $has_parents = (bool)$stored;
1195 Logger::notice('Inserted missing parent post', ['stored' => $stored, 'uid' => $receiver, 'parent' => $item['parent-uri']]);
1197 Logger::notice('Parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1200 } elseif ($add_parent) {
1201 Logger::debug('Parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1203 Logger::debug('Parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1207 if (empty($item['parent-uri-id']) || ($item['thr-parent-id'] != $item['parent-uri-id'])) {
1208 if (Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $receiver])) {
1209 $has_parents = true;
1210 } elseif (($has_parents || $add_parent) && Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => 0])) {
1211 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $receiver, $fields);
1212 $has_parents = $has_parents || (bool)$stored;
1214 Logger::notice('Inserted missing thread parent post', ['stored' => $stored, 'uid' => $receiver, 'thread-parent' => $item['thr-parent']]);
1216 Logger::notice('Thread parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1218 } elseif ($add_parent) {
1219 Logger::debug('Thread parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1221 Logger::debug('Thread parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1225 return $has_parents;
1229 * Store tags and mentions into the tag table
1231 * @param integer $uriid
1232 * @param array $tags
1234 private static function storeTags(int $uriid, array $tags = null)
1236 foreach ($tags as $tag) {
1237 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1241 $hash = substr($tag['name'], 0, 1);
1243 if ($tag['type'] == 'Mention') {
1244 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1245 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1246 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1247 $tag['name'] = substr($tag['name'], 1);
1249 $type = Tag::IMPLICIT_MENTION;
1251 if (!empty($tag['href'])) {
1252 $apcontact = APContact::getByURL($tag['href']);
1253 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1254 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1257 } elseif ($tag['type'] == 'Hashtag') {
1258 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1259 $tag['name'] = substr($tag['name'], 1);
1261 $type = Tag::HASHTAG;
1264 if (empty($tag['name'])) {
1268 Tag::store($uriid, $type, $tag['name'], $tag['href']);
1272 public static function storeReceivers(int $uriid, array $receivers)
1274 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
1275 if (!empty($receivers[$element])) {
1276 foreach ($receivers[$element] as $receiver) {
1277 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1278 $name = Receiver::PUBLIC_COLLECTION;
1279 } elseif ($path = parse_url($receiver, PHP_URL_PATH)) {
1280 $name = trim($path, '/');
1281 } elseif ($host = parse_url($receiver, PHP_URL_HOST)) {
1284 Logger::warning('Unable to coerce name from receiver', ['element' => $element, 'type' => $type, 'receiver' => $receiver]);
1288 $target = Tag::getTargetType($receiver);
1289 Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1290 Tag::store($uriid, $type, $name, $receiver, $target);
1297 * Creates an mail post
1299 * @param array $activity Activity data
1300 * @param array $item item array
1301 * @return int|bool New mail table row id or false on error
1302 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1304 private static function postMail(array $activity, array $item)
1306 if (($item['gravity'] != Item::GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1307 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1311 Logger::info('Direct Message', $item);
1314 $msg['uid'] = $item['uid'];
1316 $msg['contact-id'] = $item['contact-id'];
1318 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1319 $msg['from-name'] = $contact['name'];
1320 $msg['from-url'] = $contact['url'];
1321 $msg['from-photo'] = $contact['photo'];
1323 $msg['uri'] = $item['uri'];
1324 $msg['created'] = $item['created'];
1326 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1327 if (DBA::isResult($parent)) {
1328 $msg['parent-uri'] = $parent['parent-uri'];
1329 $msg['title'] = $parent['title'];
1331 $msg['parent-uri'] = $item['thr-parent'];
1333 if (!empty($item['title'])) {
1334 $msg['title'] = $item['title'];
1335 } elseif (!empty($item['content-warning'])) {
1336 $msg['title'] = $item['content-warning'];
1338 // Trying to generate a title out of the body
1339 $title = $item['body'];
1341 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1342 $title = $matches[3];
1345 $title = trim(BBCode::toPlaintext($title));
1347 if (strlen($title) > 20) {
1348 $title = substr($title, 0, 20) . '...';
1351 $msg['title'] = $title;
1354 $msg['body'] = $item['body'];
1356 return Mail::insert($msg);
1360 * Fetch featured posts from a contact with the given url
1362 * @param string $url
1365 public static function fetchFeaturedPosts(string $url)
1367 Logger::info('Fetch featured posts', ['contact' => $url]);
1369 $apcontact = APContact::getByURL($url);
1370 if (empty($apcontact['featured'])) {
1371 Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1375 $pcid = Contact::getIdForURL($url, 0, false);
1377 Logger::notice('Contact not found', ['contact' => $url]);
1381 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1382 if (!empty($posts)) {
1383 $old_featured = array_column($posts, 'uri-id');
1388 $featured = ActivityPub::fetchItems($apcontact['featured']);
1389 if (empty($featured)) {
1390 Logger::info('Contact does not have featured posts', ['contact' => $url]);
1392 foreach ($old_featured as $uri_id) {
1393 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1394 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1402 foreach ($featured as $post) {
1403 if (empty($post['id'])) {
1406 $id = Item::fetchByLink($post['id']);
1408 $item = Post::selectFirst(['uri-id', 'featured', 'author-id'], ['id' => $id]);
1409 if (!empty($item['uri-id'])) {
1410 if (!$item['featured']) {
1411 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED, $item['author-id']);
1412 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1415 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1419 $index = array_search($item['uri-id'], $old_featured);
1420 if (!($index === false)) {
1421 unset($old_featured[$index]);
1427 foreach ($old_featured as $uri_id) {
1428 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1429 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1432 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1435 public static function fetchCachedActivity(string $url, int $uid): array
1437 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . hash('sha256', $url);
1438 $object = DI::cache()->get($cachekey);
1440 if (!is_null($object)) {
1441 if (!empty($object)) {
1442 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1444 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1449 $object = ActivityPub::fetchContent($url, $uid);
1450 if (empty($object)) {
1451 Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1452 // We perform negative caching.
1453 DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1457 if (empty($object['id'])) {
1458 Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1461 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1463 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1469 * Fetches missing posts
1471 * @param string $url message URL
1472 * @param array $child activity array with the child of this message
1473 * @param string $relay_actor Relay actor
1474 * @param int $completion Completion mode, see Receiver::COMPLETION_*
1475 * @param int $uid User id that is used to fetch the activity
1476 * @return string fetched message URL
1477 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1478 * @throws \ImagickException
1480 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL, int $uid = 0): string
1482 $object = self::fetchCachedActivity($url, $uid);
1483 if (empty($object)) {
1489 if (!empty($object['attributedTo'])) {
1490 $attributed_to = $object['attributedTo'];
1491 if (is_array($attributed_to)) {
1492 $compacted = JsonLD::compact($object);
1493 $attributed_to = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1495 $signer[] = $attributed_to;
1498 if (!empty($object['actor'])) {
1499 $object_actor = $object['actor'];
1500 } elseif (!empty($attributed_to)) {
1501 $object_actor = $attributed_to;
1507 $signer[] = $object_actor;
1509 if (!empty($child['author'])) {
1510 $actor = $child['author'];
1513 $actor = $object_actor;
1516 if (!empty($object['published'])) {
1517 $published = $object['published'];
1518 } elseif (!empty($child['published'])) {
1519 $published = $child['published'];
1521 $published = DateTimeFormat::utcNow();
1525 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1526 unset($object['@context']);
1527 $activity['id'] = $object['id'];
1528 $activity['to'] = $object['to'] ?? [];
1529 $activity['cc'] = $object['cc'] ?? [];
1530 $activity['actor'] = $actor;
1531 $activity['object'] = $object;
1532 $activity['published'] = $published;
1533 $activity['type'] = 'Create';
1535 $ldactivity = JsonLD::compact($activity);
1537 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 0;
1539 if ($object_actor != $actor) {
1540 Contact::updateByUrlIfNeeded($object_actor);
1543 Contact::updateByUrlIfNeeded($actor);
1545 if (!empty($child['thread-completion'])) {
1546 $ldactivity['thread-completion'] = $child['thread-completion'];
1547 $ldactivity['completion-mode'] = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1549 $ldactivity['thread-completion'] = Contact::getIdForURL($relay_actor ?: $actor);
1550 $ldactivity['completion-mode'] = $completion;
1553 if ($completion == Receiver::COMPLETION_RELAY) {
1554 $ldactivity['from-relay'] = $ldactivity['thread-completion'];
1555 if (!self::acceptIncomingMessage($ldactivity, $object['id'])) {
1560 if (!empty($child['thread-children-type'])) {
1561 $ldactivity['thread-children-type'] = $child['thread-children-type'];
1562 } elseif (!empty($child['type'])) {
1563 $ldactivity['thread-children-type'] = $child['type'];
1565 $ldactivity['thread-children-type'] = 'as:Create';
1568 if (($completion == Receiver::COMPLETION_RELAY) && Queue::exists($url, 'as:Create')) {
1569 Logger::info('Activity has already been queued.', ['url' => $url, 'object' => $activity['id']]);
1570 } elseif (ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer, '', $completion)) {
1571 Logger::info('Activity had been fetched and processed.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1573 Logger::info('Activity had been fetched and will be processed later.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1576 return $activity['id'];
1580 * Test if incoming relay messages should be accepted
1582 * @param array $activity activity array
1583 * @param string $id object ID
1584 * @return boolean true if message is accepted
1586 private static function acceptIncomingMessage(array $activity, string $id): bool
1588 if (empty($activity['as:object'])) {
1589 Logger::info('No object field in activity - accepted', ['id' => $id]);
1593 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1594 $uriid = ItemURI::getIdByURI($replyto ?? '');
1595 if (Post::exists(['uri-id' => $uriid])) {
1596 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1600 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1601 $authorid = Contact::getIdForURL($attributed_to);
1603 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1606 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1607 if (!empty($tags)) {
1608 foreach ($tags as $tag) {
1609 if ($tag['type'] != 'Hashtag') {
1612 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1616 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB, $activity['thread-completion'] ?? 0);
1620 * perform a "follow" request
1622 * @param array $activity
1624 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1625 * @throws \ImagickException
1627 public static function followUser(array $activity)
1629 $uid = User::getIdForURL($activity['object_id']);
1631 Queue::remove($activity);
1635 $owner = User::getOwnerDataById($uid);
1636 if (empty($owner)) {
1640 $cid = Contact::getIdForURL($activity['actor'], $uid);
1642 self::switchContact($cid);
1643 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1647 'author-id' => Contact::getIdForURL($activity['actor']),
1648 'author-link' => $activity['actor'],
1651 // Ensure that the contact has got the right network type
1652 self::switchContact($item['author-id']);
1654 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1655 if ($result === true) {
1656 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1659 $cid = Contact::getIdForURL($activity['actor'], $uid);
1664 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1665 self::transmitPendingEvents($cid, $owner['uid']);
1668 if (empty($contact)) {
1669 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1671 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1672 Queue::remove($activity);
1676 * Transmit pending events to the new follower
1678 * @param integer $cid Contact id
1679 * @param integer $uid User id
1682 private static function transmitPendingEvents(int $cid, int $uid)
1684 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1685 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1687 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1688 while ($event = DBA::fetch($events)) {
1689 $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1693 if (DI::config()->get('system', 'bulk_delivery')) {
1694 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1695 Worker::add(Worker::PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1697 Worker::add(Worker::PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1703 * Update the given profile
1705 * @param array $activity
1706 * @throws \Exception
1708 public static function updatePerson(array $activity)
1710 if (empty($activity['object_id'])) {
1714 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1715 Contact::updateFromProbeByURL($activity['object_id']);
1716 Queue::remove($activity);
1720 * Delete the given profile
1722 * @param array $activity
1724 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1726 public static function deletePerson(array $activity)
1728 if (empty($activity['object_id']) || empty($activity['actor'])) {
1729 Logger::info('Empty object id or actor.');
1730 Queue::remove($activity);
1734 if ($activity['object_id'] != $activity['actor']) {
1735 Logger::info('Object id does not match actor.');
1736 Queue::remove($activity);
1740 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1741 while ($contact = DBA::fetch($contacts)) {
1742 Contact::remove($contact['id']);
1744 DBA::close($contacts);
1746 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1747 Queue::remove($activity);
1751 * Add moved contacts as followers for all subscribers of the old contact
1753 * @param array $activity
1755 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1757 public static function movePerson(array $activity)
1759 if (empty($activity['target_id']) || empty($activity['object_id'])) {
1760 Queue::remove($activity);
1764 if ($activity['object_id'] != $activity['actor']) {
1765 Logger::notice('Object is not the actor', ['activity' => $activity]);
1766 Queue::remove($activity);
1770 $from = Contact::getByURL($activity['object_id'], false, ['uri-id']);
1771 if (empty($from['uri-id'])) {
1772 Logger::info('Object not found', ['activity' => $activity]);
1773 Queue::remove($activity);
1777 $contacts = DBA::select('contact', ['uid', 'url'], ["`uri-id` = ? AND `uid` != ? AND `rel` IN (?, ?)", $from['uri-id'], 0, Contact::FRIEND, Contact::SHARING]);
1778 while ($from_contact = DBA::fetch($contacts)) {
1779 $result = Contact::createFromProbeForUser($from_contact['uid'], $activity['target_id']);
1780 Logger::debug('Follower added', ['from' => $from_contact, 'result' => $result]);
1782 DBA::close($contacts);
1783 Queue::remove($activity);
1787 * Blocks the user by the contact
1789 * @param array $activity
1791 * @throws \Exception
1793 public static function blockAccount(array $activity)
1795 $cid = Contact::getIdForURL($activity['actor']);
1800 $uid = User::getIdForURL($activity['object_id']);
1805 Contact\User::setIsBlocked($cid, $uid, true);
1807 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1808 Queue::remove($activity);
1812 * Unblocks the user by the contact
1814 * @param array $activity
1816 * @throws \Exception
1818 public static function unblockAccount(array $activity)
1820 $cid = Contact::getIdForURL($activity['actor']);
1825 $uid = User::getIdForURL($activity['object_object']);
1830 Contact\User::setIsBlocked($cid, $uid, false);
1832 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1833 Queue::remove($activity);
1839 * @param array $activity
1841 * @throws \Exception
1843 public static function ReportAccount(array $activity)
1845 $account_id = Contact::getIdForURL($activity['object_id']);
1846 if (empty($account_id)) {
1847 Logger::info('Unknown account', ['activity' => $activity]);
1848 Queue::remove($activity);
1852 $reporter_id = Contact::getIdForURL($activity['actor']);
1853 if (empty($reporter_id)) {
1854 Logger::info('Unknown actor', ['activity' => $activity]);
1855 Queue::remove($activity);
1860 foreach ($activity['object_ids'] as $status_id) {
1861 $post = Post::selectFirst(['uri-id'], ['uri' => $status_id]);
1862 if (!empty($post['uri-id'])) {
1863 $uri_ids[] = $post['uri-id'];
1867 $report = DI::reportFactory()->createFromReportsRequest($reporter_id, $account_id, $activity['content'], null, '', false, $uri_ids);
1868 DI::report()->save($report);
1870 Logger::info('Stored report', ['reporter' => $reporter_id, 'account_id' => $account_id, 'comment' => $activity['content'], 'object_ids' => $activity['object_ids']]);
1874 * Accept a follow request
1876 * @param array $activity
1877 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1878 * @throws \ImagickException
1880 public static function acceptFollowUser(array $activity)
1882 if (!empty($activity['object_actor'])) {
1883 $uid = User::getIdForURL($activity['object_actor']);
1885 } elseif (!empty($activity['receiver']) && (count($activity['receiver']) == 1)) {
1886 $uid = array_shift($activity['receiver']);
1891 Logger::notice('User could not be detected', ['activity' => $activity]);
1892 Queue::remove($activity);
1896 $cid = Contact::getIdForURL($activity['actor'], $uid);
1898 Logger::notice('No contact found', ['actor' => $activity['actor']]);
1899 Queue::remove($activity);
1903 $id = Transmitter::activityIDFromContact($cid);
1904 if ($id == $activity['object_id']) {
1905 Logger::info('Successful id check', ['uid' => $uid, 'cid' => $cid]);
1907 Logger::info('Unsuccessful id check', ['uid' => $uid, 'cid' => $cid, 'id' => $id, 'object_id' => $activity['object_id']]);
1909 Queue::remove($activity);
1914 self::switchContact($cid);
1916 $fields = ['pending' => false];
1918 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1919 if ($contact['rel'] == Contact::FOLLOWER) {
1920 $fields['rel'] = Contact::FRIEND;
1923 $condition = ['id' => $cid];
1924 Contact::update($fields, $condition);
1925 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1926 Queue::remove($activity);
1930 * Reject a follow request
1932 * @param array $activity
1933 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1934 * @throws \ImagickException
1936 public static function rejectFollowUser(array $activity)
1938 $uid = User::getIdForURL($activity['object_actor']);
1943 $cid = Contact::getIdForURL($activity['actor'], $uid);
1945 Logger::info('No contact found', ['actor' => $activity['actor']]);
1949 self::switchContact($cid);
1951 $contact = Contact::getById($cid, ['rel']);
1952 if ($contact['rel'] == Contact::SHARING) {
1953 Contact::remove($cid);
1954 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1955 } elseif ($contact['rel'] == Contact::FRIEND) {
1956 Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1958 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1960 Queue::remove($activity);
1964 * Undo activity like "like" or "dislike"
1966 * @param array $activity
1967 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1968 * @throws \ImagickException
1970 public static function undoActivity(array $activity)
1972 if (empty($activity['object_id'])) {
1976 if (empty($activity['object_actor'])) {
1980 $author_id = Contact::getIdForURL($activity['object_actor']);
1981 if (empty($author_id)) {
1985 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => Item::GRAVITY_ACTIVITY]);
1986 Queue::remove($activity);
1990 * Activity to remove a follower
1992 * @param array $activity
1993 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1994 * @throws \ImagickException
1996 public static function undoFollowUser(array $activity)
1998 $uid = User::getIdForURL($activity['object_object']);
2003 $owner = User::getOwnerDataById($uid);
2004 if (empty($owner)) {
2008 $cid = Contact::getIdForURL($activity['actor'], $uid);
2010 Logger::info('No contact found', ['actor' => $activity['actor']]);
2014 self::switchContact($cid);
2016 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2017 if (!DBA::isResult($contact)) {
2021 Contact::removeFollower($contact);
2022 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
2023 Queue::remove($activity);
2027 * Switches a contact to AP if needed
2029 * @param integer $cid Contact ID
2031 * @throws \Exception
2033 private static function switchContact(int $cid)
2035 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
2036 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
2040 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
2041 Contact::updateFromProbe($cid);
2045 * Collects implicit mentions like:
2046 * - the author of the parent item
2047 * - all the mentioned conversants in the parent item
2049 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
2051 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2053 private static function getImplicitMentionList(array $parent): array
2055 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
2057 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
2059 $implicit_mentions = [];
2060 if (empty($parent_author['url'])) {
2061 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
2063 $implicit_mentions[] = $parent_author['url'];
2064 $implicit_mentions[] = $parent_author['nurl'];
2065 $implicit_mentions[] = $parent_author['alias'];
2068 if (!empty($parent['alias'])) {
2069 $implicit_mentions[] = $parent['alias'];
2072 foreach ($parent_terms as $term) {
2073 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
2074 if (!empty($contact['url'])) {
2075 $implicit_mentions[] = $contact['url'];
2076 $implicit_mentions[] = $contact['nurl'];
2077 $implicit_mentions[] = $contact['alias'];
2081 return $implicit_mentions;
2085 * Strips from the body prepended implicit mentions
2087 * @param string $body
2088 * @param array $parent
2091 private static function removeImplicitMentionsFromBody(string $body, array $parent): string
2093 if (DI::config()->get('system', 'disable_implicit_mentions')) {
2097 $potential_mentions = self::getImplicitMentionList($parent);
2099 $kept_mentions = [];
2101 // Extract one prepended mention at a time from the body
2102 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
2103 if (!in_array($matches[2], $potential_mentions)) {
2104 $kept_mentions[] = $matches[1];
2107 $body = $matches[3];
2110 // Re-appending the kept mentions to the body after extraction
2111 $kept_mentions[] = $body;
2113 return implode('', $kept_mentions);
2117 * Adds links to string mentions
2119 * @param string $body
2120 * @param array $tags
2123 protected static function addMentionLinks(string $body, array $tags): string
2125 // This prevents links to be added again to Pleroma-style mention links
2126 $body = self::normalizeMentionLinks($body);
2128 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
2129 foreach ($tags as $tag) {
2130 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
2134 $hash = substr($tag['name'], 0, 1);
2135 $name = substr($tag['name'], 1);
2136 if (!in_array($hash, Tag::TAG_CHARACTER)) {
2138 $name = $tag['name'];
2141 if (Network::isValidHttpUrl($tag['href'])) {
2142 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);