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['author']) && empty($activity['actor'])) {
303 Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]);
307 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
308 $recursion_depth = $activity['recursion-depth'] ?? 0;
309 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
310 if ($recursion_depth < DI::config()->get('system', 'max_recursion_depth')) {
311 $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
312 if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
313 // Recursively delete this and all depending entries
314 Queue::deleteById($activity['entry-id']);
317 $fetch_by_worker = empty($result);
319 Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
320 $fetch_by_worker = true;
323 if ($fetch_by_worker && Queue::hasWorker($activity)) {
324 Logger::notice('There is already a worker task to fetch the post.', ['id' => $activity['id'], 'parent' => $activity['reply-to-id']]);
325 $fetch_by_worker = false;
326 if (!empty($conversation)) {
331 if ($fetch_by_worker) {
332 Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
333 $activity['recursion-depth'] = 0;
334 $wid = Worker::add(PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
335 Queue::setWorkerId($activity, $wid);
336 if (!empty($conversation)) {
339 } elseif (!empty($result)) {
340 if (($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
341 $item['thr-parent'] = $result;
346 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
348 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
349 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
353 $item['network'] = Protocol::ACTIVITYPUB;
354 $item['author-link'] = $activity['author'];
355 $item['author-id'] = Contact::getIdForURL($activity['author']);
356 $item['owner-link'] = $activity['actor'];
357 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
359 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
360 $item['private'] = Item::UNLISTED;
361 } elseif (in_array(0, $activity['receiver'])) {
362 $item['private'] = Item::PUBLIC;
364 $item['private'] = Item::PRIVATE;
367 if (!empty($activity['raw'])) {
368 $item['source'] = $activity['raw'];
369 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
372 if (isset($activity['push'])) {
373 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
376 if (!empty($activity['from-relay'])) {
377 $item['direction'] = Conversation::RELAY;
380 if ($activity['object_type'] == 'as:Article') {
381 $item['post-type'] = Item::PT_ARTICLE;
382 } elseif ($activity['object_type'] == 'as:Audio') {
383 $item['post-type'] = Item::PT_AUDIO;
384 } elseif ($activity['object_type'] == 'as:Document') {
385 $item['post-type'] = Item::PT_DOCUMENT;
386 } elseif ($activity['object_type'] == 'as:Event') {
387 $item['post-type'] = Item::PT_EVENT;
388 } elseif ($activity['object_type'] == 'as:Image') {
389 $item['post-type'] = Item::PT_IMAGE;
390 } elseif ($activity['object_type'] == 'as:Page') {
391 $item['post-type'] = Item::PT_PAGE;
392 } elseif ($activity['object_type'] == 'as:Question') {
393 $item['post-type'] = Item::PT_POLL;
394 } elseif ($activity['object_type'] == 'as:Video') {
395 $item['post-type'] = Item::PT_VIDEO;
397 $item['post-type'] = Item::PT_NOTE;
400 $item['isForum'] = false;
402 if (!empty($activity['thread-completion'])) {
403 if ($activity['thread-completion'] != $item['owner-id']) {
404 $actor = Contact::getById($activity['thread-completion'], ['url']);
405 $item['causer-link'] = $actor['url'];
406 $item['causer-id'] = $activity['thread-completion'];
407 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
409 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
410 $item['causer-link'] = $item['owner-link'];
411 $item['causer-id'] = $item['owner-id'];
412 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
415 $item['owner-link'] = $item['author-link'];
416 $item['owner-id'] = $item['author-id'];
418 $actor = APContact::getByURL($item['owner-link'], false);
419 $item['isForum'] = ($actor['type'] == 'Group');
422 $item['uri'] = $activity['id'];
424 if (empty($activity['published']) || empty($activity['updated'])) {
425 DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
428 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
429 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
430 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
431 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
433 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
434 if (empty($item['uri-id'])) {
435 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
439 $item = self::processContent($activity, $item);
441 Logger::info('Message was not processed');
445 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
447 self::storeAttachments($activity, $item);
448 self::storeQuestion($activity, $item);
450 // We received the post via AP, so we set the protocol of the server to AP
451 $contact = Contact::getById($item['author-id'], ['gsid']);
452 if (!empty($contact['gsid'])) {
453 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
456 if ($item['author-id'] != $item['owner-id']) {
457 $contact = Contact::getById($item['owner-id'], ['gsid']);
458 if (!empty($contact['gsid'])) {
459 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
467 * Check if a given activity is no longer available
473 public static function isActivityGone(string $url): bool
475 $curlResult = HTTPSignature::fetchRaw($url, 0);
477 if (Network::isUrlBlocked($url)) {
481 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
482 if (in_array($curlResult->getReturnCode(), [404])) {
486 $object = json_decode($curlResult->getBody(), true);
487 if (!empty($object)) {
488 $activity = JsonLD::compact($object);
489 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
499 * @param array $activity
500 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 * @throws \ImagickException
503 public static function deleteItem(array $activity)
505 $owner = Contact::getIdForURL($activity['actor']);
507 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
508 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
509 Queue::remove($activity);
513 * Prepare the item array for an activity
515 * @param array $activity Activity array
516 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
517 * @throws \ImagickException
519 public static function addTag(array $activity)
521 if (empty($activity['object_content']) || empty($activity['object_id'])) {
525 foreach ($activity['receiver'] as $receiver) {
526 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
527 if (!DBA::isResult($item)) {
528 // We don't fetch missing content for this purpose
532 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
533 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
537 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
538 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
543 * Prepare the item array for an activity
545 * @param array $activity Activity array
546 * @param string $verb Activity verb
547 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
548 * @throws \ImagickException
550 public static function createActivity(array $activity, string $verb)
552 $activity['reply-to-id'] = $activity['object_id'];
553 $item = self::createItem($activity);
558 $item['verb'] = $verb;
559 $item['thr-parent'] = $activity['object_id'];
560 $item['gravity'] = GRAVITY_ACTIVITY;
561 unset($item['post-type']);
562 $item['object-type'] = Activity\ObjectType::NOTE;
564 if (!empty($activity['content'])) {
565 $item['body'] = HTML::toBBCode($activity['content']);
568 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
570 self::postItem($activity, $item);
574 * Fetch the Uri-Id of a post for the "featured" collection
576 * @param array $activity
579 private static function getUriIdForFeaturedCollection(array $activity)
581 $actor = APContact::getByURL($activity['actor']);
586 // Refetch the account when the "featured" collection is missing.
587 // This can be removed in a future version (end of 2022 should be good).
588 if (empty($actor['featured'])) {
589 $actor = APContact::getByURL($activity['actor'], true);
595 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
596 if (empty($parent['uri-id'])) {
597 if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
598 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
602 if (!empty($parent['uri-id'])) {
603 return $parent['uri-id'];
610 * Add a post to the "Featured" collection
612 * @param array $activity
614 public static function addToFeaturedCollection(array $activity)
616 $uriid = self::getUriIdForFeaturedCollection($activity);
621 Logger::debug('Add post to featured collection', ['uri-id' => $uriid]);
623 Post\Collection::add($uriid, Post\Collection::FEATURED);
624 Queue::remove($activity);
628 * Remove a post to the "Featured" collection
630 * @param array $activity
632 public static function removeFromFeaturedCollection(array $activity)
634 $uriid = self::getUriIdForFeaturedCollection($activity);
639 Logger::debug('Remove post from featured collection', ['uri-id' => $uriid]);
641 Post\Collection::remove($uriid, Post\Collection::FEATURED);
642 Queue::remove($activity);
648 * @param array $activity Activity array
651 * @return int event id
654 public static function createEvent(array $activity, array $item): int
656 $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']);
657 $event['desc'] = HTML::toBBCode($activity['content']);
658 if (!empty($activity['start-time'])) {
659 $event['start'] = DateTimeFormat::utc($activity['start-time']);
661 if (!empty($activity['end-time'])) {
662 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
664 $event['nofinish'] = empty($event['finish']);
665 $event['location'] = $activity['location'];
666 $event['cid'] = $item['contact-id'];
667 $event['uid'] = $item['uid'];
668 $event['uri'] = $item['uri'];
669 $event['edited'] = $item['edited'];
670 $event['private'] = $item['private'];
671 $event['guid'] = $item['guid'];
672 $event['plink'] = $item['plink'];
673 $event['network'] = $item['network'];
674 $event['protocol'] = $item['protocol'];
675 $event['direction'] = $item['direction'];
676 $event['source'] = $item['source'];
678 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
679 if (DBA::isResult($ev)) {
680 $event['id'] = $ev['id'];
683 $event_id = Event::store($event);
685 Logger::info('Event was stored', ['id' => $event_id]);
691 * Process the content
693 * @param array $activity Activity array
695 * @return array|bool Returns the item array or false if there was an unexpected occurrence
698 private static function processContent(array $activity, array $item)
700 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
701 $item['title'] = strip_tags($activity['name']);
702 $content = Markdown::toBBCode($activity['content']);
703 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
704 $item['title'] = $activity['name'];
705 $content = $activity['content'];
707 // By default assume "text/html"
708 $item['title'] = HTML::toBBCode($activity['name'] ?? '');
709 $content = HTML::toBBCode($activity['content'] ?? '');
712 $item['title'] = trim(BBCode::toPlaintext($item['title']));
714 if (!empty($activity['languages'])) {
715 $item['language'] = self::processLanguages($activity['languages']);
718 if (!empty($activity['emojis'])) {
719 $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
722 $content = self::addMentionLinks($content, $activity['tags']);
724 if (!empty($activity['source'])) {
725 $item['body'] = $activity['source'];
726 $item['raw-body'] = $content;
727 $item['body'] = Item::improveSharedDataInBody($item);
729 $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
730 if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
731 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
732 if (!DBA::isResult($parent)) {
733 Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
736 if (($item['private'] == Item::PRIVATE) && ($parent['private'] != Item::PRIVATE)) {
737 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
741 $content = self::removeImplicitMentionsFromBody($content, $parent);
743 $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
744 $item['raw-body'] = $item['body'] = $content;
747 self::storeFromBody($item);
748 self::storeTags($item['uri-id'], $activity['tags']);
750 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
752 $item['location'] = $activity['location'];
754 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
755 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
758 $item['app'] = $activity['generator'];
764 * Store hashtags and mentions
768 private static function storeFromBody(array $item)
770 // Make sure to delete all existing tags (can happen when called via the update functionality)
771 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
773 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
777 * Generate a GUID out of an URL of an ActivityPub post.
779 * @param string $url message URL
780 * @return string with GUID
782 private static function getGUIDByURL(string $url): string
784 $parsed = parse_url($url);
786 $host_hash = hash('crc32', $parsed['host']);
788 unset($parsed["scheme"]);
789 unset($parsed["host"]);
791 $path = implode("/", $parsed);
793 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
797 * Checks if an incoming message is wanted
799 * @param array $activity
801 * @return boolean Is the message wanted?
803 private static function isSolicitedMessage(array $activity, array $item): bool
805 // The checks are split to improve the support when searching why a message was accepted.
806 if (count($activity['receiver']) != 1) {
807 // The message has more than one receiver, so it is wanted.
808 Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
812 if ($item['private'] == Item::PRIVATE) {
813 // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
814 Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
818 if (!empty($activity['from-relay'])) {
819 // We check relay posts at another place. When it arrived here, the message is already checked.
820 Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
824 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUCE])) {
825 // Manual completions and completions caused by reshares are allowed without any further checks.
826 Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
830 if ($item['gravity'] != GRAVITY_PARENT) {
831 // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
832 // This can possibly be improved in the future.
833 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
837 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
838 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB)) {
839 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
847 * Creates an item post
849 * @param array $activity Activity data
850 * @param array $item item array
851 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
852 * @throws \ImagickException
854 public static function postItem(array $activity, array $item)
862 ksort($activity['receiver']);
864 if (!self::isSolicitedMessage($activity, $item)) {
865 DBA::delete('item-uri', ['id' => $item['uri-id']]);
869 foreach ($activity['receiver'] as $receiver) {
870 if ($receiver == -1) {
874 $item['uid'] = $receiver;
876 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
878 case Receiver::TARGET_TO:
879 $item['post-reason'] = Item::PR_TO;
881 case Receiver::TARGET_CC:
882 $item['post-reason'] = Item::PR_CC;
884 case Receiver::TARGET_BTO:
885 $item['post-reason'] = Item::PR_BTO;
887 case Receiver::TARGET_BCC:
888 $item['post-reason'] = Item::PR_BCC;
890 case Receiver::TARGET_FOLLOWER:
891 $item['post-reason'] = Item::PR_FOLLOWER;
893 case Receiver::TARGET_ANSWER:
894 $item['post-reason'] = Item::PR_COMMENT;
896 case Receiver::TARGET_GLOBAL:
897 $item['post-reason'] = Item::PR_GLOBAL;
900 $item['post-reason'] = Item::PR_NONE;
903 if (!empty($activity['from-relay'])) {
904 $item['post-reason'] = Item::PR_RELAY;
905 } elseif (!empty($activity['thread-completion'])) {
906 $item['post-reason'] = Item::PR_FETCHED;
907 } elseif (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE]) && !empty($activity['push'])) {
908 $item['post-reason'] = Item::PR_PUSHED;
911 if ($item['isForum'] ?? false) {
912 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
914 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
917 if (($receiver != 0) && empty($item['contact-id'])) {
918 $item['contact-id'] = Contact::getIdForURL($activity['author']);
921 if (!empty($activity['directmessage'])) {
922 self::postMail($activity, $item);
926 if (!($item['isForum'] ?? false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT) && !Contact::isSharingByURL($activity['author'], $receiver)) {
927 if ($item['post-reason'] == Item::PR_BCC) {
928 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id']]);
933 !empty($activity['thread-children-type'])
934 && in_array($activity['thread-children-type'], Receiver::ACTIVITY_TYPES)
935 && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE
937 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
938 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
945 if ($receiver != 0) {
946 $user = User::getById($receiver, ['account-type']);
947 if (!empty($user['account-type'])) {
948 $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
952 if (!$is_forum && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
953 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
955 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
956 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
960 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
964 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
967 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
968 $event_id = self::createEvent($activity, $item);
970 $item = Event::getItemArrayForImportedId($event_id, $item);
973 $item_id = Item::insert($item);
975 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
978 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
981 if ($item['uid'] == 0) {
986 Queue::remove($activity);
988 if ($success && Queue::hasChildren($item['uri'])) {
989 Worker::add(PRIORITY_HIGH, 'ProcessReplyByUri', $item['uri']);
992 // Store send a follow request for every reshare - but only when the item had been stored
993 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
994 $author = APContact::getByURL($item['owner-link'], false);
995 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
996 if ($author['type'] != 'Group') {
997 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
998 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
1004 * Store tags and mentions into the tag table
1006 * @param integer $uriid
1007 * @param array $tags
1009 private static function storeTags(int $uriid, array $tags = null)
1011 foreach ($tags as $tag) {
1012 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1016 $hash = substr($tag['name'], 0, 1);
1018 if ($tag['type'] == 'Mention') {
1019 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1020 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1021 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1022 $tag['name'] = substr($tag['name'], 1);
1024 $type = Tag::IMPLICIT_MENTION;
1026 if (!empty($tag['href'])) {
1027 $apcontact = APContact::getByURL($tag['href']);
1028 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1029 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1032 } elseif ($tag['type'] == 'Hashtag') {
1033 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1034 $tag['name'] = substr($tag['name'], 1);
1036 $type = Tag::HASHTAG;
1039 if (empty($tag['name'])) {
1043 Tag::store($uriid, $type, $tag['name'], $tag['href']);
1047 public static function storeReceivers(int $uriid, array $receivers)
1049 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
1050 if (!empty($receivers[$element])) {
1051 foreach ($receivers[$element] as $receiver) {
1052 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1053 $name = Receiver::PUBLIC_COLLECTION;
1055 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
1058 $target = Tag::getTargetType($receiver);
1059 Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1060 Tag::store($uriid, $type, $name, $receiver, $target);
1067 * Creates an mail post
1069 * @param array $activity Activity data
1070 * @param array $item item array
1071 * @return int|bool New mail table row id or false on error
1072 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1074 private static function postMail(array $activity, array $item)
1076 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1077 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1081 Logger::info('Direct Message', $item);
1084 $msg['uid'] = $item['uid'];
1086 $msg['contact-id'] = $item['contact-id'];
1088 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1089 $msg['from-name'] = $contact['name'];
1090 $msg['from-url'] = $contact['url'];
1091 $msg['from-photo'] = $contact['photo'];
1093 $msg['uri'] = $item['uri'];
1094 $msg['created'] = $item['created'];
1096 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1097 if (DBA::isResult($parent)) {
1098 $msg['parent-uri'] = $parent['parent-uri'];
1099 $msg['title'] = $parent['title'];
1101 $msg['parent-uri'] = $item['thr-parent'];
1103 if (!empty($item['title'])) {
1104 $msg['title'] = $item['title'];
1105 } elseif (!empty($item['content-warning'])) {
1106 $msg['title'] = $item['content-warning'];
1108 // Trying to generate a title out of the body
1109 $title = $item['body'];
1111 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1112 $title = $matches[3];
1115 $title = trim(BBCode::toPlaintext($title));
1117 if (strlen($title) > 20) {
1118 $title = substr($title, 0, 20) . '...';
1121 $msg['title'] = $title;
1124 $msg['body'] = $item['body'];
1126 return Mail::insert($msg);
1130 * Fetch featured posts from a contact with the given url
1132 * @param string $url
1135 public static function fetchFeaturedPosts(string $url)
1137 Logger::info('Fetch featured posts', ['contact' => $url]);
1139 $apcontact = APContact::getByURL($url);
1140 if (empty($apcontact['featured'])) {
1141 Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1145 $pcid = Contact::getIdForURL($url, 0, false);
1147 Logger::info('Contact not found', ['contact' => $url]);
1151 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1152 if (!empty($posts)) {
1153 $old_featured = array_column($posts, 'uri-id');
1158 $featured = ActivityPub::fetchItems($apcontact['featured']);
1159 if (empty($featured)) {
1160 Logger::info('Contact does not have featured posts', ['contact' => $url]);
1162 foreach ($old_featured as $uri_id) {
1163 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1164 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1172 foreach ($featured as $post) {
1173 if (empty($post['id'])) {
1176 $id = Item::fetchByLink($post['id']);
1178 $item = Post::selectFirst(['uri-id', 'featured'], ['id' => $id]);
1179 if (!empty($item['uri-id'])) {
1180 if (!$item['featured']) {
1181 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED);
1182 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1185 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1189 $index = array_search($item['uri-id'], $old_featured);
1190 if (!($index === false)) {
1191 unset($old_featured[$index]);
1197 foreach ($old_featured as $uri_id) {
1198 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1199 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1202 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1205 public static function fetchCachedActivity(string $url, int $uid): array
1207 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . $url;
1208 $object = DI::cache()->get($cachekey);
1210 if (!is_null($object)) {
1211 if (!empty($object)) {
1212 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1214 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1219 $object = ActivityPub::fetchContent($url, $uid);
1220 if (empty($object)) {
1221 Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1222 // We perform negative caching.
1223 DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1227 if (empty($object['id'])) {
1228 Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1231 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1233 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1239 * Fetches missing posts
1241 * @param string $url message URL
1242 * @param array $child activity array with the child of this message
1243 * @param string $relay_actor Relay actor
1244 * @param int $completion Completion mode, see Receiver::COMPLETION_*
1245 * @return string fetched message URL
1246 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1247 * @throws \ImagickException
1249 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL): string
1251 if (!empty($child['receiver'])) {
1252 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
1257 $object = self::fetchCachedActivity($url, $uid);
1258 if (empty($object)) {
1264 if (!empty($object['attributedTo'])) {
1265 $attributed_to = $object['attributedTo'];
1266 if (is_array($attributed_to)) {
1267 $compacted = JsonLD::compact($object);
1268 $attributed_to = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1270 $signer[] = $attributed_to;
1273 if (!empty($object['actor'])) {
1274 $object_actor = $object['actor'];
1275 } elseif (!empty($attributed_to)) {
1276 $object_actor = $attributed_to;
1282 $signer[] = $object_actor;
1284 if (!empty($child['author'])) {
1285 $actor = $child['author'];
1288 $actor = $object_actor;
1291 if (!empty($object['published'])) {
1292 $published = $object['published'];
1293 } elseif (!empty($child['published'])) {
1294 $published = $child['published'];
1296 $published = DateTimeFormat::utcNow();
1300 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1301 unset($object['@context']);
1302 $activity['id'] = $object['id'];
1303 $activity['to'] = $object['to'] ?? [];
1304 $activity['cc'] = $object['cc'] ?? [];
1305 $activity['actor'] = $actor;
1306 $activity['object'] = $object;
1307 $activity['published'] = $published;
1308 $activity['type'] = 'Create';
1310 $ldactivity = JsonLD::compact($activity);
1312 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 1;
1314 if (!empty($relay_actor)) {
1315 $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
1316 $ldactivity['completion-mode'] = Receiver::COMPLETION_RELAY;
1317 } elseif (!empty($child['thread-completion'])) {
1318 $ldactivity['thread-completion'] = $child['thread-completion'];
1319 $ldactivity['completion-mode'] = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1321 $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
1322 $ldactivity['completion-mode'] = $completion;
1325 if (!empty($child['type'])) {
1326 $ldactivity['thread-children-type'] = $child['type'];
1329 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
1333 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
1335 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
1337 return $activity['id'];
1341 * Test if incoming relay messages should be accepted
1343 * @param array $activity activity array
1344 * @param string $id object ID
1345 * @return boolean true if message is accepted
1347 private static function acceptIncomingMessage(array $activity, string $id): bool
1349 if (empty($activity['as:object'])) {
1350 Logger::info('No object field in activity - accepted', ['id' => $id]);
1354 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1355 $uriid = ItemURI::getIdByURI($replyto ?? '');
1356 if (Post::exists(['uri-id' => $uriid])) {
1357 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1361 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1362 $authorid = Contact::getIdForURL($attributed_to);
1364 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1367 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1368 if (!empty($tags)) {
1369 foreach ($tags as $tag) {
1370 if ($tag['type'] != 'Hashtag') {
1373 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1377 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
1381 * perform a "follow" request
1383 * @param array $activity
1385 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1386 * @throws \ImagickException
1388 public static function followUser(array $activity)
1390 $uid = User::getIdForURL($activity['object_id']);
1392 Queue::remove($activity);
1396 $owner = User::getOwnerDataById($uid);
1397 if (empty($owner)) {
1401 $cid = Contact::getIdForURL($activity['actor'], $uid);
1403 self::switchContact($cid);
1404 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1408 'author-id' => Contact::getIdForURL($activity['actor']),
1409 'author-link' => $activity['actor'],
1412 // Ensure that the contact has got the right network type
1413 self::switchContact($item['author-id']);
1415 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1416 if ($result === true) {
1417 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1420 $cid = Contact::getIdForURL($activity['actor'], $uid);
1425 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1426 self::transmitPendingEvents($cid, $owner['uid']);
1429 if (empty($contact)) {
1430 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1432 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1433 Queue::remove($activity);
1437 * Transmit pending events to the new follower
1439 * @param integer $cid Contact id
1440 * @param integer $uid User id
1443 private static function transmitPendingEvents(int $cid, int $uid)
1445 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1446 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1448 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1449 while ($event = DBA::fetch($events)) {
1450 $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1454 if (DI::config()->get('system', 'bulk_delivery')) {
1455 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1456 Worker::add(PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1458 Worker::add(PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1464 * Update the given profile
1466 * @param array $activity
1467 * @throws \Exception
1469 public static function updatePerson(array $activity)
1471 if (empty($activity['object_id'])) {
1475 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1476 Contact::updateFromProbeByURL($activity['object_id']);
1477 Queue::remove($activity);
1481 * Delete the given profile
1483 * @param array $activity
1485 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1487 public static function deletePerson(array $activity)
1489 if (empty($activity['object_id']) || empty($activity['actor'])) {
1490 Logger::info('Empty object id or actor.');
1494 if ($activity['object_id'] != $activity['actor']) {
1495 Logger::info('Object id does not match actor.');
1499 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1500 while ($contact = DBA::fetch($contacts)) {
1501 Contact::remove($contact['id']);
1503 DBA::close($contacts);
1505 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1506 Queue::remove($activity);
1510 * Blocks the user by the contact
1512 * @param array $activity
1514 * @throws \Exception
1516 public static function blockAccount(array $activity)
1518 $cid = Contact::getIdForURL($activity['actor']);
1523 $uid = User::getIdForURL($activity['object_id']);
1528 Contact\User::setIsBlocked($cid, $uid, true);
1530 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1531 Queue::remove($activity);
1535 * Unblocks the user by the contact
1537 * @param array $activity
1539 * @throws \Exception
1541 public static function unblockAccount(array $activity)
1543 $cid = Contact::getIdForURL($activity['actor']);
1548 $uid = User::getIdForURL($activity['object_object']);
1553 Contact\User::setIsBlocked($cid, $uid, false);
1555 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1556 Queue::remove($activity);
1560 * Accept a follow request
1562 * @param array $activity
1563 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1564 * @throws \ImagickException
1566 public static function acceptFollowUser(array $activity)
1568 $uid = User::getIdForURL($activity['object_actor']);
1573 $cid = Contact::getIdForURL($activity['actor'], $uid);
1575 Logger::info('No contact found', ['actor' => $activity['actor']]);
1579 self::switchContact($cid);
1581 $fields = ['pending' => false];
1583 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1584 if ($contact['rel'] == Contact::FOLLOWER) {
1585 $fields['rel'] = Contact::FRIEND;
1588 $condition = ['id' => $cid];
1589 Contact::update($fields, $condition);
1590 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1591 Queue::remove($activity);
1595 * Reject a follow request
1597 * @param array $activity
1598 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1599 * @throws \ImagickException
1601 public static function rejectFollowUser(array $activity)
1603 $uid = User::getIdForURL($activity['object_actor']);
1608 $cid = Contact::getIdForURL($activity['actor'], $uid);
1610 Logger::info('No contact found', ['actor' => $activity['actor']]);
1614 self::switchContact($cid);
1616 $contact = Contact::getById($cid, ['rel']);
1617 if ($contact['rel'] == Contact::SHARING) {
1618 Contact::remove($cid);
1619 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1620 } elseif ($contact['rel'] == Contact::FRIEND) {
1621 Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1623 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1625 Queue::remove($activity);
1629 * Undo activity like "like" or "dislike"
1631 * @param array $activity
1632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1633 * @throws \ImagickException
1635 public static function undoActivity(array $activity)
1637 if (empty($activity['object_id'])) {
1641 if (empty($activity['object_actor'])) {
1645 $author_id = Contact::getIdForURL($activity['object_actor']);
1646 if (empty($author_id)) {
1650 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1651 Queue::remove($activity);
1655 * Activity to remove a follower
1657 * @param array $activity
1658 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1659 * @throws \ImagickException
1661 public static function undoFollowUser(array $activity)
1663 $uid = User::getIdForURL($activity['object_object']);
1668 $owner = User::getOwnerDataById($uid);
1669 if (empty($owner)) {
1673 $cid = Contact::getIdForURL($activity['actor'], $uid);
1675 Logger::info('No contact found', ['actor' => $activity['actor']]);
1679 self::switchContact($cid);
1681 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1682 if (!DBA::isResult($contact)) {
1686 Contact::removeFollower($contact);
1687 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1688 Queue::remove($activity);
1692 * Switches a contact to AP if needed
1694 * @param integer $cid Contact ID
1696 * @throws \Exception
1698 private static function switchContact(int $cid)
1700 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1701 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1705 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1706 Contact::updateFromProbe($cid);
1710 * Collects implicit mentions like:
1711 * - the author of the parent item
1712 * - all the mentioned conversants in the parent item
1714 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1716 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1718 private static function getImplicitMentionList(array $parent): array
1720 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1722 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1724 $implicit_mentions = [];
1725 if (empty($parent_author['url'])) {
1726 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1728 $implicit_mentions[] = $parent_author['url'];
1729 $implicit_mentions[] = $parent_author['nurl'];
1730 $implicit_mentions[] = $parent_author['alias'];
1733 if (!empty($parent['alias'])) {
1734 $implicit_mentions[] = $parent['alias'];
1737 foreach ($parent_terms as $term) {
1738 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1739 if (!empty($contact['url'])) {
1740 $implicit_mentions[] = $contact['url'];
1741 $implicit_mentions[] = $contact['nurl'];
1742 $implicit_mentions[] = $contact['alias'];
1746 return $implicit_mentions;
1750 * Strips from the body prepended implicit mentions
1752 * @param string $body
1753 * @param array $parent
1756 private static function removeImplicitMentionsFromBody(string $body, array $parent): string
1758 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1762 $potential_mentions = self::getImplicitMentionList($parent);
1764 $kept_mentions = [];
1766 // Extract one prepended mention at a time from the body
1767 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1768 if (!in_array($matches[2], $potential_mentions)) {
1769 $kept_mentions[] = $matches[1];
1772 $body = $matches[3];
1775 // Re-appending the kept mentions to the body after extraction
1776 $kept_mentions[] = $body;
1778 return implode('', $kept_mentions);
1782 * Adds links to string mentions
1784 * @param string $body
1785 * @param array $tags
1788 protected static function addMentionLinks(string $body, array $tags): string
1790 // This prevents links to be added again to Pleroma-style mention links
1791 $body = self::normalizeMentionLinks($body);
1793 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
1794 foreach ($tags as $tag) {
1795 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1799 $hash = substr($tag['name'], 0, 1);
1800 $name = substr($tag['name'], 1);
1801 if (!in_array($hash, Tag::TAG_CHARACTER)) {
1803 $name = $tag['name'];
1806 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);