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:';
62 * Extracts the tag character (#, @, !) from mention links
67 protected static function normalizeMentionLinks(string $body): string
69 return preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
73 * Convert the language array into a language JSON
75 * @param array $languages
76 * @return string language JSON
78 private static function processLanguages(array $languages): string
80 $codes = array_keys($languages);
82 foreach ($codes as $code) {
90 return json_encode($lang);
93 * Replaces emojis in the body
97 * @param array $emojis
99 * @return string with replaced emojis
101 private static function replaceEmojis(int $uri_id, string $body, array $emojis): string
105 array_column($emojis, 'name'),
106 array_map(function ($emoji) {
107 return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
112 // We store the emoji here to be able to avoid storing it in the media
113 foreach ($emojis as $emoji) {
114 Post\Link::getByLink($uri_id, $emoji['href']);
120 * Store attached media files in the post-media table
123 * @param array $attachment
126 private static function storeAttachmentAsMedia(int $uriid, array $attachment)
128 if (empty($attachment['url'])) {
132 $data = ['uri-id' => $uriid];
133 $data['type'] = Post\Media::UNKNOWN;
134 $data['url'] = $attachment['url'];
135 $data['mimetype'] = $attachment['mediaType'] ?? null;
136 $data['height'] = $attachment['height'] ?? null;
137 $data['width'] = $attachment['width'] ?? null;
138 $data['size'] = $attachment['size'] ?? null;
139 $data['preview'] = $attachment['image'] ?? null;
140 $data['description'] = $attachment['name'] ?? null;
142 Post\Media::insert($data);
146 * Stire attachment data
148 * @param array $activity
151 private static function storeAttachments(array $activity, array $item)
153 if (empty($activity['attachments'])) {
157 foreach ($activity['attachments'] as $attach) {
158 self::storeAttachmentAsMedia($item['uri-id'], $attach);
163 * Store attachment data
165 * @param array $activity
168 private static function storeQuestion(array $activity, array $item)
170 if (empty($activity['question'])) {
173 $question = ['multiple' => $activity['question']['multiple']];
175 if (!empty($activity['question']['voters'])) {
176 $question['voters'] = $activity['question']['voters'];
179 if (!empty($activity['question']['end-time'])) {
180 $question['end-time'] = DateTimeFormat::utc($activity['question']['end-time']);
183 Post\Question::update($item['uri-id'], $question);
185 foreach ($activity['question']['options'] as $key => $option) {
186 $option = ['name' => $option['name'], 'replies' => $option['replies']];
187 Post\QuestionOption::update($item['uri-id'], $key, $option);
190 Logger::debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]);
196 * @param array $activity Activity array
197 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
198 * @throws \ImagickException
200 public static function updateItem(array $activity)
202 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type'], ['uri' => $activity['id']]);
203 if (!DBA::isResult($item)) {
204 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
205 $item = self::createItem($activity);
210 self::postItem($activity, $item);
214 $item['changed'] = DateTimeFormat::utcNow();
215 $item['edited'] = DateTimeFormat::utc($activity['updated']);
217 $item = self::processContent($activity, $item);
222 self::storeAttachments($activity, $item);
223 self::storeQuestion($activity, $item);
225 Post\History::add($item['uri-id'], $item);
226 Item::update($item, ['uri' => $activity['id']]);
228 Queue::remove($activity);
230 if ($activity['object_type'] == 'as:Event') {
231 $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
232 while ($post = DBA::fetch($posts)) {
233 self::updateEvent($post['event-id'], $activity);
239 * Update an existing event
241 * @param int $event_id
242 * @param array $activity
244 private static function updateEvent(int $event_id, array $activity)
246 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
248 $event['edited'] = DateTimeFormat::utc($activity['updated']);
249 $event['summary'] = HTML::toBBCode($activity['name']);
250 $event['desc'] = HTML::toBBCode($activity['content']);
251 if (!empty($activity['start-time'])) {
252 $event['start'] = DateTimeFormat::utc($activity['start-time']);
254 if (!empty($activity['end-time'])) {
255 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
257 $event['nofinish'] = empty($event['finish']);
258 $event['location'] = $activity['location'];
260 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
261 Event::store($event);
265 * Prepares data for a message
267 * @param array $activity Activity array
268 * @return array Internal item
269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270 * @throws \ImagickException
272 public static function createItem(array $activity): array
275 $item['verb'] = Activity::POST;
276 $item['thr-parent'] = $activity['reply-to-id'];
278 if ($activity['reply-to-id'] == $activity['id']) {
279 $item['gravity'] = GRAVITY_PARENT;
280 $item['object-type'] = Activity\ObjectType::NOTE;
282 $item['gravity'] = GRAVITY_COMMENT;
283 $item['object-type'] = Activity\ObjectType::COMMENT;
286 if (!empty($activity['context'])) {
287 $item['conversation'] = $activity['context'];
288 } elseif (!empty($activity['conversation'])) {
289 $item['conversation'] = $activity['conversation'];
292 if (!empty($item['conversation'])) {
293 $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]);
294 if (!empty($conversation)) {
295 Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]);
296 $item['parent-uri'] = $conversation['uri'];
302 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
303 $recursion_depth = $activity['recursion-depth'] ?? 0;
304 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
305 if ($recursion_depth < DI::config()->get('system', 'max_recursion_depth')) {
306 $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
307 if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
308 // Recursively delete this and all depending entries
309 Queue::deleteById($activity['entry-id']);
312 $fetch_by_worker = empty($result);
314 Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
315 $fetch_by_worker = true;
318 if ($fetch_by_worker && Queue::hasWorker($activity)) {
319 Logger::notice('There is already a worker task to fetch the post.', ['id' => $activity['id'], 'parent' => $activity['reply-to-id']]);
320 $fetch_by_worker = false;
321 if (!empty($conversation)) {
326 if ($fetch_by_worker) {
327 Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
328 $activity['recursion-depth'] = 0;
329 $wid = Worker::add(PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
330 Queue::setWorkerId($activity, $wid);
331 if (!empty($conversation)) {
334 } elseif (!empty($result)) {
335 if (($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
336 $item['thr-parent'] = $result;
341 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
343 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
344 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
348 $item['network'] = Protocol::ACTIVITYPUB;
349 $item['author-link'] = $activity['author'];
350 $item['author-id'] = Contact::getIdForURL($activity['author']);
351 $item['owner-link'] = $activity['actor'];
352 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
354 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
355 $item['private'] = Item::UNLISTED;
356 } elseif (in_array(0, $activity['receiver'])) {
357 $item['private'] = Item::PUBLIC;
359 $item['private'] = Item::PRIVATE;
362 if (!empty($activity['raw'])) {
363 $item['source'] = $activity['raw'];
364 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
367 if (isset($activity['push'])) {
368 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
371 if (!empty($activity['from-relay'])) {
372 $item['direction'] = Conversation::RELAY;
375 if ($activity['object_type'] == 'as:Article') {
376 $item['post-type'] = Item::PT_ARTICLE;
377 } elseif ($activity['object_type'] == 'as:Audio') {
378 $item['post-type'] = Item::PT_AUDIO;
379 } elseif ($activity['object_type'] == 'as:Document') {
380 $item['post-type'] = Item::PT_DOCUMENT;
381 } elseif ($activity['object_type'] == 'as:Event') {
382 $item['post-type'] = Item::PT_EVENT;
383 } elseif ($activity['object_type'] == 'as:Image') {
384 $item['post-type'] = Item::PT_IMAGE;
385 } elseif ($activity['object_type'] == 'as:Page') {
386 $item['post-type'] = Item::PT_PAGE;
387 } elseif ($activity['object_type'] == 'as:Question') {
388 $item['post-type'] = Item::PT_POLL;
389 } elseif ($activity['object_type'] == 'as:Video') {
390 $item['post-type'] = Item::PT_VIDEO;
392 $item['post-type'] = Item::PT_NOTE;
395 $item['isForum'] = false;
397 if (!empty($activity['thread-completion'])) {
398 if ($activity['thread-completion'] != $item['owner-id']) {
399 $actor = Contact::getById($activity['thread-completion'], ['url']);
400 $item['causer-link'] = $actor['url'];
401 $item['causer-id'] = $activity['thread-completion'];
402 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
404 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
405 $item['causer-link'] = $item['owner-link'];
406 $item['causer-id'] = $item['owner-id'];
407 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
410 $item['owner-link'] = $item['author-link'];
411 $item['owner-id'] = $item['author-id'];
413 $actor = APContact::getByURL($item['owner-link'], false);
414 $item['isForum'] = ($actor['type'] == 'Group');
417 $item['uri'] = $activity['id'];
419 if (empty($activity['published']) || empty($activity['updated'])) {
420 DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
423 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
424 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
425 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
426 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
428 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
429 if (empty($item['uri-id'])) {
430 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
434 $item = self::processContent($activity, $item);
436 Logger::info('Message was not processed');
440 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
442 self::storeAttachments($activity, $item);
443 self::storeQuestion($activity, $item);
445 // We received the post via AP, so we set the protocol of the server to AP
446 $contact = Contact::getById($item['author-id'], ['gsid']);
447 if (!empty($contact['gsid'])) {
448 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
451 if ($item['author-id'] != $item['owner-id']) {
452 $contact = Contact::getById($item['owner-id'], ['gsid']);
453 if (!empty($contact['gsid'])) {
454 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
462 * Check if a given activity is no longer available
468 public static function isActivityGone(string $url): bool
470 $curlResult = HTTPSignature::fetchRaw($url, 0);
472 if (Network::isUrlBlocked($url)) {
476 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
477 if (in_array($curlResult->getReturnCode(), [404])) {
481 $object = json_decode($curlResult->getBody(), true);
482 if (!empty($object)) {
483 $activity = JsonLD::compact($object);
484 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
494 * @param array $activity
495 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
496 * @throws \ImagickException
498 public static function deleteItem(array $activity)
500 $owner = Contact::getIdForURL($activity['actor']);
502 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
503 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
504 Queue::remove($activity);
508 * Prepare the item array for an activity
510 * @param array $activity Activity array
511 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
512 * @throws \ImagickException
514 public static function addTag(array $activity)
516 if (empty($activity['object_content']) || empty($activity['object_id'])) {
520 foreach ($activity['receiver'] as $receiver) {
521 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
522 if (!DBA::isResult($item)) {
523 // We don't fetch missing content for this purpose
527 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
528 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
532 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
533 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
538 * Prepare the item array for an activity
540 * @param array $activity Activity array
541 * @param string $verb Activity verb
542 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
543 * @throws \ImagickException
545 public static function createActivity(array $activity, string $verb)
547 $activity['reply-to-id'] = $activity['object_id'];
548 $item = self::createItem($activity);
553 $item['verb'] = $verb;
554 $item['thr-parent'] = $activity['object_id'];
555 $item['gravity'] = GRAVITY_ACTIVITY;
556 unset($item['post-type']);
557 $item['object-type'] = Activity\ObjectType::NOTE;
559 if (!empty($activity['content'])) {
560 $item['body'] = HTML::toBBCode($activity['content']);
563 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
565 self::postItem($activity, $item);
569 * Fetch the Uri-Id of a post for the "featured" collection
571 * @param array $activity
574 private static function getUriIdForFeaturedCollection(array $activity)
576 $actor = APContact::getByURL($activity['actor']);
581 // Refetch the account when the "featured" collection is missing.
582 // This can be removed in a future version (end of 2022 should be good).
583 if (empty($actor['featured'])) {
584 $actor = APContact::getByURL($activity['actor'], true);
590 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
591 if (empty($parent['uri-id'])) {
592 if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
593 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
597 if (!empty($parent['uri-id'])) {
598 return $parent['uri-id'];
605 * Add a post to the "Featured" collection
607 * @param array $activity
609 public static function addToFeaturedCollection(array $activity)
611 $uriid = self::getUriIdForFeaturedCollection($activity);
616 Logger::debug('Add post to featured collection', ['uri-id' => $uriid]);
618 Post\Collection::add($uriid, Post\Collection::FEATURED);
619 Queue::remove($activity);
623 * Remove a post to the "Featured" collection
625 * @param array $activity
627 public static function removeFromFeaturedCollection(array $activity)
629 $uriid = self::getUriIdForFeaturedCollection($activity);
634 Logger::debug('Remove post from featured collection', ['uri-id' => $uriid]);
636 Post\Collection::remove($uriid, Post\Collection::FEATURED);
637 Queue::remove($activity);
643 * @param array $activity Activity array
646 * @return int event id
649 public static function createEvent(array $activity, array $item): int
651 $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']);
652 $event['desc'] = HTML::toBBCode($activity['content']);
653 if (!empty($activity['start-time'])) {
654 $event['start'] = DateTimeFormat::utc($activity['start-time']);
656 if (!empty($activity['end-time'])) {
657 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
659 $event['nofinish'] = empty($event['finish']);
660 $event['location'] = $activity['location'];
661 $event['cid'] = $item['contact-id'];
662 $event['uid'] = $item['uid'];
663 $event['uri'] = $item['uri'];
664 $event['edited'] = $item['edited'];
665 $event['private'] = $item['private'];
666 $event['guid'] = $item['guid'];
667 $event['plink'] = $item['plink'];
668 $event['network'] = $item['network'];
669 $event['protocol'] = $item['protocol'];
670 $event['direction'] = $item['direction'];
671 $event['source'] = $item['source'];
673 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
674 if (DBA::isResult($ev)) {
675 $event['id'] = $ev['id'];
678 $event_id = Event::store($event);
680 Logger::info('Event was stored', ['id' => $event_id]);
686 * Process the content
688 * @param array $activity Activity array
690 * @return array|bool Returns the item array or false if there was an unexpected occurrence
693 private static function processContent(array $activity, array $item)
695 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
696 $item['title'] = strip_tags($activity['name']);
697 $content = Markdown::toBBCode($activity['content']);
698 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
699 $item['title'] = $activity['name'];
700 $content = $activity['content'];
702 // By default assume "text/html"
703 $item['title'] = HTML::toBBCode($activity['name'] ?? '');
704 $content = HTML::toBBCode($activity['content'] ?? '');
707 $item['title'] = trim(BBCode::toPlaintext($item['title']));
709 if (!empty($activity['languages'])) {
710 $item['language'] = self::processLanguages($activity['languages']);
713 if (!empty($activity['emojis'])) {
714 $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
717 $content = self::addMentionLinks($content, $activity['tags']);
719 if (!empty($activity['source'])) {
720 $item['body'] = $activity['source'];
721 $item['raw-body'] = $content;
722 $item['body'] = Item::improveSharedDataInBody($item);
724 $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
725 if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
726 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
727 if (!DBA::isResult($parent)) {
728 Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
731 if (($item['private'] == Item::PRIVATE) && ($parent['private'] != Item::PRIVATE)) {
732 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
736 $content = self::removeImplicitMentionsFromBody($content, $parent);
738 $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
739 $item['raw-body'] = $item['body'] = $content;
742 self::storeFromBody($item);
743 self::storeTags($item['uri-id'], $activity['tags']);
745 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
747 $item['location'] = $activity['location'];
749 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
750 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
753 $item['app'] = $activity['generator'];
759 * Store hashtags and mentions
763 private static function storeFromBody(array $item)
765 // Make sure to delete all existing tags (can happen when called via the update functionality)
766 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
768 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
772 * Generate a GUID out of an URL of an ActivityPub post.
774 * @param string $url message URL
775 * @return string with GUID
777 private static function getGUIDByURL(string $url): string
779 $parsed = parse_url($url);
781 $host_hash = hash('crc32', $parsed['host']);
783 unset($parsed["scheme"]);
784 unset($parsed["host"]);
786 $path = implode("/", $parsed);
788 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
792 * Checks if an incoming message is wanted
794 * @param array $activity
796 * @return boolean Is the message wanted?
798 private static function isSolicitedMessage(array $activity, array $item): bool
800 // The checks are split to improve the support when searching why a message was accepted.
801 if (count($activity['receiver']) != 1) {
802 // The message has more than one receiver, so it is wanted.
803 Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
807 if ($item['private'] == Item::PRIVATE) {
808 // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
809 Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
813 if (!empty($activity['from-relay'])) {
814 // We check relay posts at another place. When it arrived here, the message is already checked.
815 Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
819 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUCE])) {
820 // Manual completions and completions caused by reshares are allowed without any further checks.
821 Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
825 if ($item['gravity'] != GRAVITY_PARENT) {
826 // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
827 // This can possibly be improved in the future.
828 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
832 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
833 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB)) {
834 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
842 * Creates an item post
844 * @param array $activity Activity data
845 * @param array $item item array
846 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
847 * @throws \ImagickException
849 public static function postItem(array $activity, array $item)
857 ksort($activity['receiver']);
859 if (!self::isSolicitedMessage($activity, $item)) {
860 DBA::delete('item-uri', ['id' => $item['uri-id']]);
864 foreach ($activity['receiver'] as $receiver) {
865 if ($receiver == -1) {
869 $item['uid'] = $receiver;
871 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
873 case Receiver::TARGET_TO:
874 $item['post-reason'] = Item::PR_TO;
876 case Receiver::TARGET_CC:
877 $item['post-reason'] = Item::PR_CC;
879 case Receiver::TARGET_BTO:
880 $item['post-reason'] = Item::PR_BTO;
882 case Receiver::TARGET_BCC:
883 $item['post-reason'] = Item::PR_BCC;
885 case Receiver::TARGET_FOLLOWER:
886 $item['post-reason'] = Item::PR_FOLLOWER;
888 case Receiver::TARGET_ANSWER:
889 $item['post-reason'] = Item::PR_COMMENT;
891 case Receiver::TARGET_GLOBAL:
892 $item['post-reason'] = Item::PR_GLOBAL;
895 $item['post-reason'] = Item::PR_NONE;
898 if (!empty($activity['from-relay'])) {
899 $item['post-reason'] = Item::PR_RELAY;
900 } elseif (!empty($activity['thread-completion'])) {
901 $item['post-reason'] = Item::PR_FETCHED;
902 } elseif (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE]) && !empty($activity['push'])) {
903 $item['post-reason'] = Item::PR_PUSHED;
906 if ($item['isForum'] ?? false) {
907 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
909 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
912 if (($receiver != 0) && empty($item['contact-id'])) {
913 $item['contact-id'] = Contact::getIdForURL($activity['author']);
916 if (!empty($activity['directmessage'])) {
917 self::postMail($activity, $item);
921 if (!($item['isForum'] ?? false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT) && !Contact::isSharingByURL($activity['author'] ?? '', $receiver)) {
922 if ($item['post-reason'] == Item::PR_BCC) {
923 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id']]);
928 !empty($activity['thread-children-type'])
929 && in_array($activity['thread-children-type'], Receiver::ACTIVITY_TYPES)
930 && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE
932 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
933 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
940 if ($receiver != 0) {
941 $user = User::getById($receiver, ['account-type']);
942 if (!empty($user['account-type'])) {
943 $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
947 if (!$is_forum && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
948 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
950 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
951 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
955 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
959 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
962 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
963 $event_id = self::createEvent($activity, $item);
965 $item = Event::getItemArrayForImportedId($event_id, $item);
968 $item_id = Item::insert($item);
970 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
973 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
976 if ($item['uid'] == 0) {
981 Queue::remove($activity);
983 if ($success && Queue::hasChildren($item['uri'])) {
984 Worker::add(PRIORITY_HIGH, 'ProcessReplyByUri', $item['uri']);
987 // Store send a follow request for every reshare - but only when the item had been stored
988 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
989 $author = APContact::getByURL($item['owner-link'], false);
990 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
991 if ($author['type'] != 'Group') {
992 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
993 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
999 * Store tags and mentions into the tag table
1001 * @param integer $uriid
1002 * @param array $tags
1004 private static function storeTags(int $uriid, array $tags = null)
1006 foreach ($tags as $tag) {
1007 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1011 $hash = substr($tag['name'], 0, 1);
1013 if ($tag['type'] == 'Mention') {
1014 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1015 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1016 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1017 $tag['name'] = substr($tag['name'], 1);
1019 $type = Tag::IMPLICIT_MENTION;
1021 if (!empty($tag['href'])) {
1022 $apcontact = APContact::getByURL($tag['href']);
1023 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1024 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1027 } elseif ($tag['type'] == 'Hashtag') {
1028 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1029 $tag['name'] = substr($tag['name'], 1);
1031 $type = Tag::HASHTAG;
1034 if (empty($tag['name'])) {
1038 Tag::store($uriid, $type, $tag['name'], $tag['href']);
1042 public static function storeReceivers(int $uriid, array $receivers)
1044 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
1045 if (!empty($receivers[$element])) {
1046 foreach ($receivers[$element] as $receiver) {
1047 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1048 $name = Receiver::PUBLIC_COLLECTION;
1050 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
1053 $target = Tag::getTargetType($receiver);
1054 Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1055 Tag::store($uriid, $type, $name, $receiver, $target);
1062 * Creates an mail post
1064 * @param array $activity Activity data
1065 * @param array $item item array
1066 * @return int|bool New mail table row id or false on error
1067 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1069 private static function postMail(array $activity, array $item)
1071 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1072 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1076 Logger::info('Direct Message', $item);
1079 $msg['uid'] = $item['uid'];
1081 $msg['contact-id'] = $item['contact-id'];
1083 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1084 $msg['from-name'] = $contact['name'];
1085 $msg['from-url'] = $contact['url'];
1086 $msg['from-photo'] = $contact['photo'];
1088 $msg['uri'] = $item['uri'];
1089 $msg['created'] = $item['created'];
1091 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1092 if (DBA::isResult($parent)) {
1093 $msg['parent-uri'] = $parent['parent-uri'];
1094 $msg['title'] = $parent['title'];
1096 $msg['parent-uri'] = $item['thr-parent'];
1098 if (!empty($item['title'])) {
1099 $msg['title'] = $item['title'];
1100 } elseif (!empty($item['content-warning'])) {
1101 $msg['title'] = $item['content-warning'];
1103 // Trying to generate a title out of the body
1104 $title = $item['body'];
1106 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1107 $title = $matches[3];
1110 $title = trim(BBCode::toPlaintext($title));
1112 if (strlen($title) > 20) {
1113 $title = substr($title, 0, 20) . '...';
1116 $msg['title'] = $title;
1119 $msg['body'] = $item['body'];
1121 return Mail::insert($msg);
1125 * Fetch featured posts from a contact with the given url
1127 * @param string $url
1130 public static function fetchFeaturedPosts(string $url)
1132 Logger::info('Fetch featured posts', ['contact' => $url]);
1134 $apcontact = APContact::getByURL($url);
1135 if (empty($apcontact['featured'])) {
1136 Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1140 $pcid = Contact::getIdForURL($url, 0, false);
1142 Logger::info('Contact not found', ['contact' => $url]);
1146 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1147 if (!empty($posts)) {
1148 $old_featured = array_column($posts, 'uri-id');
1153 $featured = ActivityPub::fetchItems($apcontact['featured']);
1154 if (empty($featured)) {
1155 Logger::info('Contact does not have featured posts', ['contact' => $url]);
1157 foreach ($old_featured as $uri_id) {
1158 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1159 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1167 foreach ($featured as $post) {
1168 if (empty($post['id'])) {
1171 $id = Item::fetchByLink($post['id']);
1173 $item = Post::selectFirst(['uri-id', 'featured'], ['id' => $id]);
1174 if (!empty($item['uri-id'])) {
1175 if (!$item['featured']) {
1176 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED);
1177 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1180 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1184 $index = array_search($item['uri-id'], $old_featured);
1185 if (!($index === false)) {
1186 unset($old_featured[$index]);
1192 foreach ($old_featured as $uri_id) {
1193 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1194 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1197 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1200 public static function fetchCachedActivity(string $url, int $uid): array
1202 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . $url;
1203 $object = DI::cache()->get($cachekey);
1205 if (!is_null($object)) {
1206 if (!empty($object)) {
1207 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1209 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1214 $object = ActivityPub::fetchContent($url, $uid);
1215 if (empty($object)) {
1216 Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1217 // We perform negative caching.
1218 DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1222 if (empty($object['id'])) {
1223 Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1226 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1228 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1234 * Fetches missing posts
1236 * @param string $url message URL
1237 * @param array $child activity array with the child of this message
1238 * @param string $relay_actor Relay actor
1239 * @param int $completion Completion mode, see Receiver::COMPLETION_*
1240 * @return string fetched message URL
1241 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1242 * @throws \ImagickException
1244 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL): string
1246 if (!empty($child['receiver'])) {
1247 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
1252 $object = self::fetchCachedActivity($url, $uid);
1253 if (empty($object)) {
1259 if (!empty($object['attributedTo'])) {
1260 $attributed_to = $object['attributedTo'];
1261 if (is_array($attributed_to)) {
1262 $compacted = JsonLD::compact($object);
1263 $attributed_to = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1265 $signer[] = $attributed_to;
1268 if (!empty($object['actor'])) {
1269 $object_actor = $object['actor'];
1270 } elseif (!empty($attributed_to)) {
1271 $object_actor = $attributed_to;
1277 $signer[] = $object_actor;
1279 if (!empty($child['author'])) {
1280 $actor = $child['author'];
1283 $actor = $object_actor;
1286 if (!empty($object['published'])) {
1287 $published = $object['published'];
1288 } elseif (!empty($child['published'])) {
1289 $published = $child['published'];
1291 $published = DateTimeFormat::utcNow();
1295 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1296 unset($object['@context']);
1297 $activity['id'] = $object['id'];
1298 $activity['to'] = $object['to'] ?? [];
1299 $activity['cc'] = $object['cc'] ?? [];
1300 $activity['actor'] = $actor;
1301 $activity['object'] = $object;
1302 $activity['published'] = $published;
1303 $activity['type'] = 'Create';
1305 $ldactivity = JsonLD::compact($activity);
1307 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 1;
1309 if (!empty($relay_actor)) {
1310 $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
1311 $ldactivity['completion-mode'] = Receiver::COMPLETION_RELAY;
1312 } elseif (!empty($child['thread-completion'])) {
1313 $ldactivity['thread-completion'] = $child['thread-completion'];
1314 $ldactivity['completion-mode'] = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1316 $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
1317 $ldactivity['completion-mode'] = $completion;
1320 if (!empty($child['type'])) {
1321 $ldactivity['thread-children-type'] = $child['type'];
1324 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
1328 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
1330 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
1332 return $activity['id'];
1336 * Test if incoming relay messages should be accepted
1338 * @param array $activity activity array
1339 * @param string $id object ID
1340 * @return boolean true if message is accepted
1342 private static function acceptIncomingMessage(array $activity, string $id): bool
1344 if (empty($activity['as:object'])) {
1345 Logger::info('No object field in activity - accepted', ['id' => $id]);
1349 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1350 $uriid = ItemURI::getIdByURI($replyto ?? '');
1351 if (Post::exists(['uri-id' => $uriid])) {
1352 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1356 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1357 $authorid = Contact::getIdForURL($attributed_to);
1359 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1362 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1363 if (!empty($tags)) {
1364 foreach ($tags as $tag) {
1365 if ($tag['type'] != 'Hashtag') {
1368 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1372 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
1376 * perform a "follow" request
1378 * @param array $activity
1380 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1381 * @throws \ImagickException
1383 public static function followUser(array $activity)
1385 $uid = User::getIdForURL($activity['object_id']);
1387 Queue::remove($activity);
1391 $owner = User::getOwnerDataById($uid);
1392 if (empty($owner)) {
1396 $cid = Contact::getIdForURL($activity['actor'], $uid);
1398 self::switchContact($cid);
1399 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1403 'author-id' => Contact::getIdForURL($activity['actor']),
1404 'author-link' => $activity['actor'],
1407 // Ensure that the contact has got the right network type
1408 self::switchContact($item['author-id']);
1410 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1411 if ($result === true) {
1412 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1415 $cid = Contact::getIdForURL($activity['actor'], $uid);
1420 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1421 self::transmitPendingEvents($cid, $owner['uid']);
1424 if (empty($contact)) {
1425 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1427 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1428 Queue::remove($activity);
1432 * Transmit pending events to the new follower
1434 * @param integer $cid Contact id
1435 * @param integer $uid User id
1438 private static function transmitPendingEvents(int $cid, int $uid)
1440 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1441 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1443 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1444 while ($event = DBA::fetch($events)) {
1445 $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1449 if (DI::config()->get('system', 'bulk_delivery')) {
1450 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1451 Worker::add(PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1453 Worker::add(PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1459 * Update the given profile
1461 * @param array $activity
1462 * @throws \Exception
1464 public static function updatePerson(array $activity)
1466 if (empty($activity['object_id'])) {
1470 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1471 Contact::updateFromProbeByURL($activity['object_id']);
1472 Queue::remove($activity);
1476 * Delete the given profile
1478 * @param array $activity
1480 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1482 public static function deletePerson(array $activity)
1484 if (empty($activity['object_id']) || empty($activity['actor'])) {
1485 Logger::info('Empty object id or actor.');
1489 if ($activity['object_id'] != $activity['actor']) {
1490 Logger::info('Object id does not match actor.');
1494 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1495 while ($contact = DBA::fetch($contacts)) {
1496 Contact::remove($contact['id']);
1498 DBA::close($contacts);
1500 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1501 Queue::remove($activity);
1505 * Blocks the user by the contact
1507 * @param array $activity
1509 * @throws \Exception
1511 public static function blockAccount(array $activity)
1513 $cid = Contact::getIdForURL($activity['actor']);
1518 $uid = User::getIdForURL($activity['object_id']);
1523 Contact\User::setIsBlocked($cid, $uid, true);
1525 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1526 Queue::remove($activity);
1530 * Unblocks the user by the contact
1532 * @param array $activity
1534 * @throws \Exception
1536 public static function unblockAccount(array $activity)
1538 $cid = Contact::getIdForURL($activity['actor']);
1543 $uid = User::getIdForURL($activity['object_object']);
1548 Contact\User::setIsBlocked($cid, $uid, false);
1550 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1551 Queue::remove($activity);
1555 * Accept a follow request
1557 * @param array $activity
1558 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1559 * @throws \ImagickException
1561 public static function acceptFollowUser(array $activity)
1563 $uid = User::getIdForURL($activity['object_actor']);
1568 $cid = Contact::getIdForURL($activity['actor'], $uid);
1570 Logger::info('No contact found', ['actor' => $activity['actor']]);
1574 self::switchContact($cid);
1576 $fields = ['pending' => false];
1578 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1579 if ($contact['rel'] == Contact::FOLLOWER) {
1580 $fields['rel'] = Contact::FRIEND;
1583 $condition = ['id' => $cid];
1584 Contact::update($fields, $condition);
1585 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1586 Queue::remove($activity);
1590 * Reject a follow request
1592 * @param array $activity
1593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1594 * @throws \ImagickException
1596 public static function rejectFollowUser(array $activity)
1598 $uid = User::getIdForURL($activity['object_actor']);
1603 $cid = Contact::getIdForURL($activity['actor'], $uid);
1605 Logger::info('No contact found', ['actor' => $activity['actor']]);
1609 self::switchContact($cid);
1611 $contact = Contact::getById($cid, ['rel']);
1612 if ($contact['rel'] == Contact::SHARING) {
1613 Contact::remove($cid);
1614 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1615 } elseif ($contact['rel'] == Contact::FRIEND) {
1616 Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1618 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1620 Queue::remove($activity);
1624 * Undo activity like "like" or "dislike"
1626 * @param array $activity
1627 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1628 * @throws \ImagickException
1630 public static function undoActivity(array $activity)
1632 if (empty($activity['object_id'])) {
1636 if (empty($activity['object_actor'])) {
1640 $author_id = Contact::getIdForURL($activity['object_actor']);
1641 if (empty($author_id)) {
1645 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1646 Queue::remove($activity);
1650 * Activity to remove a follower
1652 * @param array $activity
1653 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1654 * @throws \ImagickException
1656 public static function undoFollowUser(array $activity)
1658 $uid = User::getIdForURL($activity['object_object']);
1663 $owner = User::getOwnerDataById($uid);
1664 if (empty($owner)) {
1668 $cid = Contact::getIdForURL($activity['actor'], $uid);
1670 Logger::info('No contact found', ['actor' => $activity['actor']]);
1674 self::switchContact($cid);
1676 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1677 if (!DBA::isResult($contact)) {
1681 Contact::removeFollower($contact);
1682 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1683 Queue::remove($activity);
1687 * Switches a contact to AP if needed
1689 * @param integer $cid Contact ID
1691 * @throws \Exception
1693 private static function switchContact(int $cid)
1695 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1696 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1700 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1701 Contact::updateFromProbe($cid);
1705 * Collects implicit mentions like:
1706 * - the author of the parent item
1707 * - all the mentioned conversants in the parent item
1709 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1711 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1713 private static function getImplicitMentionList(array $parent): array
1715 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1717 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1719 $implicit_mentions = [];
1720 if (empty($parent_author['url'])) {
1721 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1723 $implicit_mentions[] = $parent_author['url'];
1724 $implicit_mentions[] = $parent_author['nurl'];
1725 $implicit_mentions[] = $parent_author['alias'];
1728 if (!empty($parent['alias'])) {
1729 $implicit_mentions[] = $parent['alias'];
1732 foreach ($parent_terms as $term) {
1733 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1734 if (!empty($contact['url'])) {
1735 $implicit_mentions[] = $contact['url'];
1736 $implicit_mentions[] = $contact['nurl'];
1737 $implicit_mentions[] = $contact['alias'];
1741 return $implicit_mentions;
1745 * Strips from the body prepended implicit mentions
1747 * @param string $body
1748 * @param array $parent
1751 private static function removeImplicitMentionsFromBody(string $body, array $parent): string
1753 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1757 $potential_mentions = self::getImplicitMentionList($parent);
1759 $kept_mentions = [];
1761 // Extract one prepended mention at a time from the body
1762 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1763 if (!in_array($matches[2], $potential_mentions)) {
1764 $kept_mentions[] = $matches[1];
1767 $body = $matches[3];
1770 // Re-appending the kept mentions to the body after extraction
1771 $kept_mentions[] = $body;
1773 return implode('', $kept_mentions);
1777 * Adds links to string mentions
1779 * @param string $body
1780 * @param array $tags
1783 protected static function addMentionLinks(string $body, array $tags): string
1785 // This prevents links to be added again to Pleroma-style mention links
1786 $body = self::normalizeMentionLinks($body);
1788 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
1789 foreach ($tags as $tag) {
1790 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1794 $hash = substr($tag['name'], 0, 1);
1795 $name = substr($tag['name'], 1);
1796 if (!in_array($hash, Tag::TAG_CHARACTER)) {
1798 $name = $tag['name'];
1801 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);