3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Event;
38 use Friendica\Model\GServer;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Model\Post;
45 use Friendica\Model\Post\Engagement;
46 use Friendica\Protocol\Activity;
47 use Friendica\Protocol\ActivityPub;
48 use Friendica\Protocol\Delivery;
49 use Friendica\Protocol\Relay;
50 use Friendica\Util\DateTimeFormat;
51 use Friendica\Util\HTTPSignature;
52 use Friendica\Util\JsonLD;
53 use Friendica\Util\Network;
54 use Friendica\Util\Strings;
57 * ActivityPub Processor Protocol class
61 const CACHEKEY_FETCH_ACTIVITY = 'processor:fetchMissingActivity:';
62 const CACHEKEY_JUST_FETCHED = 'processor:isJustFetched:';
65 * Add an object id to the list of processed ids
71 private static function addActivityId(string $id)
73 DBA::delete('fetched-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
74 DBA::insert('fetched-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()]);
78 * Checks if the given object id has just been fetched
84 private static function isFetched(string $id): bool
86 return DBA::exists('fetched-activity', ['object-id' => $id]);
90 * Extracts the tag character (#, @, !) from mention links
95 public static function normalizeMentionLinks(string $body): string
97 $body = preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
98 $body = preg_replace('%([#@!])\[zrl=([^\[\]]*)](.*?)\[/zrl]%ism', '$1[url=$2]$3[/url]', $body);
103 * Convert the language array into a language JSON
105 * @param array $languages
106 * @return string language JSON
108 private static function processLanguages(array $languages): string
110 $codes = array_keys($languages);
112 foreach ($codes as $code) {
120 return json_encode($lang);
123 * Replaces emojis in the body
126 * @param string $body
127 * @param array $emojis
129 * @return string with replaced emojis
131 private static function replaceEmojis(int $uri_id, string $body, array $emojis): string
135 array_column($emojis, 'name'),
136 array_map(function ($emoji) {
137 return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
142 // We store the emoji here to be able to avoid storing it in the media
143 foreach ($emojis as $emoji) {
144 Post\Link::getByLink($uri_id, $emoji['href']);
150 * Store attached media files in the post-media table
153 * @param array $attachment
156 private static function storeAttachmentAsMedia(int $uriid, array $attachment)
158 if (empty($attachment['url'])) {
162 $data = ['uri-id' => $uriid];
163 $data['type'] = Post\Media::UNKNOWN;
164 $data['url'] = $attachment['url'];
165 $data['mimetype'] = $attachment['mediaType'] ?? null;
166 $data['height'] = $attachment['height'] ?? null;
167 $data['width'] = $attachment['width'] ?? null;
168 $data['size'] = $attachment['size'] ?? null;
169 $data['preview'] = $attachment['image'] ?? null;
170 $data['description'] = $attachment['name'] ?? null;
172 Post\Media::insert($data);
176 * Store attachment data
178 * @param array $activity
181 private static function storeAttachments(array $activity, array $item)
183 if (empty($activity['attachments'])) {
187 foreach ($activity['attachments'] as $attach) {
188 self::storeAttachmentAsMedia($item['uri-id'], $attach);
193 * Store question data
195 * @param array $activity
198 private static function storeQuestion(array $activity, array $item)
200 if (empty($activity['question'])) {
203 $question = ['multiple' => $activity['question']['multiple']];
205 if (!empty($activity['question']['voters'])) {
206 $question['voters'] = $activity['question']['voters'];
209 if (!empty($activity['question']['end-time'])) {
210 $question['end-time'] = DateTimeFormat::utc($activity['question']['end-time']);
213 Post\Question::update($item['uri-id'], $question);
215 foreach ($activity['question']['options'] as $key => $option) {
216 $option = ['name' => $option['name'], 'replies' => $option['replies']];
217 Post\QuestionOption::update($item['uri-id'], $key, $option);
220 Logger::debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]);
226 * @param array $activity Activity array
227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
228 * @throws \ImagickException
230 public static function updateItem(array $activity)
232 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type', 'private'], ['uri' => $activity['id']]);
233 if (!DBA::isResult($item)) {
234 Logger::notice('No existing item, item will be created', ['uri' => $activity['id']]);
235 $item = self::createItem($activity, false);
237 Queue::remove($activity);
241 self::postItem($activity, $item);
245 $item['changed'] = DateTimeFormat::utcNow();
246 $item['edited'] = DateTimeFormat::utc($activity['updated']);
248 Post\Media::deleteByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE, Post\Media::HTML]);
249 $item = self::processContent($activity, $item);
251 Queue::remove($activity);
255 self::storeAttachments($activity, $item);
256 self::storeQuestion($activity, $item);
258 Post\History::add($item['uri-id'], $item);
259 Item::update($item, ['uri' => $activity['id']]);
261 Queue::remove($activity);
263 if ($activity['object_type'] == 'as:Event') {
264 $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
265 while ($post = DBA::fetch($posts)) {
266 self::updateEvent($post['event-id'], $activity);
272 * Update an existing event
274 * @param int $event_id
275 * @param array $activity
277 private static function updateEvent(int $event_id, array $activity)
279 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
281 $event['edited'] = DateTimeFormat::utc($activity['updated']);
282 $event['summary'] = HTML::toBBCode($activity['name']);
283 $event['desc'] = HTML::toBBCode($activity['content']);
284 if (!empty($activity['start-time'])) {
285 $event['start'] = DateTimeFormat::utc($activity['start-time']);
287 if (!empty($activity['end-time'])) {
288 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
290 $event['nofinish'] = empty($event['finish']);
291 $event['location'] = $activity['location'];
293 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
294 Event::store($event);
298 * Prepares data for a message
300 * @param array $activity Activity array
301 * @param bool $fetch_parents
303 * @return array Internal item
305 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
306 * @throws \ImagickException
308 public static function createItem(array $activity, bool $fetch_parents): array
311 $item['verb'] = Activity::POST;
312 $item['thr-parent'] = $activity['reply-to-id'];
314 if ($activity['reply-to-id'] == $activity['id']) {
315 $item['gravity'] = Item::GRAVITY_PARENT;
316 $item['object-type'] = Activity\ObjectType::NOTE;
318 $item['gravity'] = Item::GRAVITY_COMMENT;
319 $item['object-type'] = Activity\ObjectType::COMMENT;
322 if (!empty($activity['conversation'])) {
323 $item['conversation'] = $activity['conversation'];
324 } elseif (!empty($activity['context'])) {
325 $item['conversation'] = $activity['context'];
328 if (!empty($item['conversation'])) {
329 $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]);
330 if (!empty($conversation)) {
331 Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]);
332 $item['parent-uri'] = $conversation['uri'];
333 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
339 Logger::debug('Create Item', ['id' => $activity['id'], 'conversation' => $item['conversation'] ?? '']);
340 if (empty($activity['author']) && empty($activity['actor'])) {
341 Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]);
342 Queue::remove($activity);
346 if (!in_array(0, $activity['receiver']) || !DI::config()->get('system', 'fetch_parents')) {
347 $fetch_parents = false;
350 if ($fetch_parents && empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
351 $result = self::fetchParent($activity, !empty($conversation));
352 if (!empty($result) && ($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
353 $item['thr-parent'] = $result;
357 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
359 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != Item::GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
360 Logger::notice('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
361 if (!$fetch_parents) {
362 Queue::remove($activity);
367 $item['network'] = Protocol::ACTIVITYPUB;
368 $item['author-link'] = $activity['author'];
369 $item['author-id'] = Contact::getIdForURL($activity['author']);
370 $item['owner-link'] = $activity['actor'];
371 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
373 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
374 $item['private'] = Item::UNLISTED;
375 } elseif (in_array(0, $activity['receiver'])) {
376 $item['private'] = Item::PUBLIC;
378 $item['private'] = Item::PRIVATE;
381 if (!empty($activity['raw'])) {
382 $item['source'] = $activity['raw'];
385 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
387 if (isset($activity['push'])) {
388 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
391 if (!empty($activity['from-relay'])) {
392 $item['direction'] = Conversation::RELAY;
395 if ($activity['object_type'] == 'as:Article') {
396 $item['post-type'] = Item::PT_ARTICLE;
397 } elseif ($activity['object_type'] == 'as:Audio') {
398 $item['post-type'] = Item::PT_AUDIO;
399 } elseif ($activity['object_type'] == 'as:Document') {
400 $item['post-type'] = Item::PT_DOCUMENT;
401 } elseif ($activity['object_type'] == 'as:Event') {
402 $item['post-type'] = Item::PT_EVENT;
403 } elseif ($activity['object_type'] == 'as:Image') {
404 $item['post-type'] = Item::PT_IMAGE;
405 } elseif ($activity['object_type'] == 'as:Page') {
406 $item['post-type'] = Item::PT_PAGE;
407 } elseif ($activity['object_type'] == 'as:Question') {
408 $item['post-type'] = Item::PT_POLL;
409 } elseif ($activity['object_type'] == 'as:Video') {
410 $item['post-type'] = Item::PT_VIDEO;
412 $item['post-type'] = Item::PT_NOTE;
415 $item['isGroup'] = false;
417 if (!empty($activity['thread-completion'])) {
418 if ($activity['thread-completion'] != $item['owner-id']) {
419 $actor = Contact::getById($activity['thread-completion'], ['url']);
420 $item['causer-link'] = $actor['url'];
421 $item['causer-id'] = $activity['thread-completion'];
422 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
424 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
425 $item['causer-link'] = $item['owner-link'];
426 $item['causer-id'] = $item['owner-id'];
427 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
430 $item['owner-link'] = $item['author-link'];
431 $item['owner-id'] = $item['author-id'];
434 if (!$item['isGroup'] && !empty($activity['receiver_urls']['as:audience'])) {
435 foreach ($activity['receiver_urls']['as:audience'] as $audience) {
436 $actor = APContact::getByURL($audience, false);
437 if (($actor['type'] ?? 'Person') == 'Group') {
438 Logger::debug('Group post detected via audience.', ['audience' => $audience, 'actor' => $activity['actor'], 'author' => $activity['author']]);
439 $item['isGroup'] = true;
440 $item['group-link'] = $item['owner-link'] = $audience;
441 $item['owner-id'] = Contact::getIdForURL($audience);
446 $owner = APContact::getByURL($item['owner-link'], false);
449 if (!$item['isGroup'] && (($owner['type'] ?? 'Person') == 'Group')) {
450 Logger::debug('Group post detected via owner.', ['actor' => $activity['actor'], 'author' => $activity['author']]);
451 $item['isGroup'] = true;
452 $item['group-link'] = $item['owner-link'];
453 } elseif (!empty($item['causer-link'])) {
454 $causer = APContact::getByURL($item['causer-link'], false);
457 if (!$item['isGroup'] && (($causer['type'] ?? 'Person') == 'Group')) {
458 Logger::debug('Group post detected via causer.', ['actor' => $activity['actor'], 'author' => $activity['author'], 'causer' => $item['causer-link']]);
459 $item['isGroup'] = true;
460 $item['group-link'] = $item['causer-link'];
463 if (!empty($item['group-link']) && empty($item['causer-link'])) {
464 $item['causer-link'] = $item['group-link'];
465 $item['causer-id'] = Contact::getIdForURL($item['causer-link']);
468 $item['uri'] = $activity['id'];
470 if (empty($activity['published']) || empty($activity['updated'])) {
471 DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity]);
474 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
475 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
476 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
477 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
479 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
480 if (empty($item['uri-id'])) {
481 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
485 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
487 $item = self::processContent($activity, $item);
489 Logger::info('Message was not processed');
490 Queue::remove($activity);
494 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
496 self::storeAttachments($activity, $item);
497 self::storeQuestion($activity, $item);
499 // We received the post via AP, so we set the protocol of the server to AP
500 $contact = Contact::getById($item['author-id'], ['gsid']);
501 if (!empty($contact['gsid'])) {
502 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
505 if ($item['author-id'] != $item['owner-id']) {
506 $contact = Contact::getById($item['owner-id'], ['gsid']);
507 if (!empty($contact['gsid'])) {
508 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
516 * Fetch and process parent posts for the given activity
518 * @param array $activity
519 * @param bool $in_background
523 private static function fetchParent(array $activity, bool $in_background = false): string
525 if (self::isFetched($activity['reply-to-id'])) {
526 Logger::info('Id is already fetched', ['id' => $activity['reply-to-id']]);
530 self::addActivityId($activity['reply-to-id']);
532 $completion = $activity['completion-mode'] ?? Receiver::COMPLETION_NONE;
534 if (DI::config()->get('system', 'decoupled_receiver') && ($completion != Receiver::COMPLETION_MANUAL)) {
535 $in_background = true;
538 $recursion_depth = $activity['recursion-depth'] ?? 0;
540 if (!$in_background && ($recursion_depth < DI::config()->get('system', 'max_recursion_depth'))) {
541 Logger::info('Parent not found. Try to refetch it.', ['completion' => $completion, 'recursion-depth' => $recursion_depth, 'parent' => $activity['reply-to-id']]);
542 $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
543 if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
544 Logger::notice('The activity is gone, the queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
545 if (!empty($activity['entry-id'])) {
546 Queue::deleteById($activity['entry-id']);
548 } elseif (!empty($result)) {
549 $post = Post::selectFirstPost(['uri'], ['uri' => [$result, $activity['reply-to-id']]]);
550 if (!empty($post['uri'])) {
551 Logger::info('The activity has been fetched and created.', ['result' => $result, 'uri' => $post['uri']]);
554 Logger::notice('The activity exists but has not been created, the queue entry will be deleted.', ['parent' => $result]);
555 if (!empty($activity['entry-id'])) {
556 Queue::deleteById($activity['entry-id']);
561 } elseif (self::isActivityGone($activity['reply-to-id'])) {
562 Logger::notice('The activity is gone. We will not spawn a worker. The queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
563 if ($in_background) {
564 // fetching in background is done for all activities where we have got the conversation
565 // There we only delete the single activity and not the whole thread since we can store the
566 // other posts in the thread even with missing posts.
567 Queue::remove($activity);
568 } elseif (!empty($activity['entry-id'])) {
569 Queue::deleteById($activity['entry-id']);
572 } elseif ($in_background) {
573 Logger::notice('Fetching is done in the background.', ['parent' => $activity['reply-to-id']]);
575 Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
578 if (!Fetch::hasWorker($activity['reply-to-id'])) {
579 Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
580 Fetch::add($activity['reply-to-id']);
581 $activity['recursion-depth'] = 0;
582 $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_ASYNC);
583 Fetch::setWorkerId($activity['reply-to-id'], $wid);
585 Logger::debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]);
592 * Check if a given activity is no longer available
598 public static function isActivityGone(string $url): bool
600 if (Network::isUrlBlocked($url)) {
605 $curlResult = HTTPSignature::fetchRaw($url, 0);
606 } catch (\Exception $exception) {
607 Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
611 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
612 if (in_array($curlResult->getReturnCode(), [401, 404])) {
616 if ($curlResult->isSuccess()) {
617 $object = json_decode($curlResult->getBody(), true);
618 if (!empty($object)) {
619 $activity = JsonLD::compact($object);
620 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
624 } elseif ($curlResult->getReturnCode() == 0) {
625 $host = parse_url($url, PHP_URL_HOST);
626 if (!(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) {
636 * @param array $activity
637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
638 * @throws \ImagickException
640 public static function deleteItem(array $activity)
642 $owner = Contact::getIdForURL($activity['actor']);
644 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
645 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
646 Queue::remove($activity);
650 * Prepare the item array for an activity
652 * @param array $activity Activity array
653 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
654 * @throws \ImagickException
656 public static function addTag(array $activity)
658 if (empty($activity['object_content']) || empty($activity['object_id'])) {
662 foreach ($activity['receiver'] as $receiver) {
663 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
664 if (!DBA::isResult($item)) {
665 // We don't fetch missing content for this purpose
669 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
670 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
674 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
675 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
680 * Prepare the item array for an activity
682 * @param array $activity Activity array
683 * @param string $verb Activity verb
684 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
685 * @throws \ImagickException
687 public static function createActivity(array $activity, string $verb)
689 $activity['reply-to-id'] = $activity['object_id'];
690 $item = self::createItem($activity, false);
692 Logger::debug('Activity was not prepared', ['id' => $activity['object_id']]);
696 $item['verb'] = $verb;
697 $item['thr-parent'] = $activity['object_id'];
698 $item['gravity'] = Item::GRAVITY_ACTIVITY;
699 unset($item['post-type']);
700 $item['object-type'] = Activity\ObjectType::NOTE;
702 if (!empty($activity['content'])) {
703 $item['body'] = HTML::toBBCode($activity['content']);
706 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
708 self::postItem($activity, $item);
712 * Fetch the Uri-Id of a post for the "featured" collection
714 * @param array $activity
717 private static function getUriIdForFeaturedCollection(array $activity)
719 $actor = APContact::getByURL($activity['actor']);
724 // Refetch the account when the "featured" collection is missing.
725 // This can be removed in a future version (end of 2022 should be good).
726 if (empty($actor['featured'])) {
727 $actor = APContact::getByURL($activity['actor'], true);
733 $parent = Post::selectFirst(['uri-id', 'author-id'], ['uri' => $activity['object_id']]);
734 if (empty($parent['uri-id'])) {
735 if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
736 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
740 if (!empty($parent['uri-id'])) {
748 * Add a post to the "Featured" collection
750 * @param array $activity
752 public static function addToFeaturedCollection(array $activity)
754 $post = self::getUriIdForFeaturedCollection($activity);
755 if (empty($post) || empty($post['author-id'])) {
756 Queue::remove($activity);
760 Logger::debug('Add post to featured collection', ['post' => $post]);
762 Post\Collection::add($post['uri-id'], Post\Collection::FEATURED, $post['author-id']);
763 Queue::remove($activity);
767 * Remove a post to the "Featured" collection
769 * @param array $activity
771 public static function removeFromFeaturedCollection(array $activity)
773 $post = self::getUriIdForFeaturedCollection($activity);
775 Queue::remove($activity);
779 Logger::debug('Remove post from featured collection', ['post' => $post]);
781 Post\Collection::remove($post['uri-id'], Post\Collection::FEATURED);
782 Queue::remove($activity);
788 * @param array $activity Activity array
791 * @return int event id
794 public static function createEvent(array $activity, array $item): int
796 $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']);
797 $event['desc'] = HTML::toBBCode($activity['content'] ?? '');
798 if (!empty($activity['start-time'])) {
799 $event['start'] = DateTimeFormat::utc($activity['start-time']);
801 if (!empty($activity['end-time'])) {
802 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
804 $event['nofinish'] = empty($event['finish']);
805 $event['location'] = $activity['location'];
806 $event['cid'] = $item['contact-id'];
807 $event['uid'] = $item['uid'];
808 $event['uri'] = $item['uri'];
809 $event['edited'] = $item['edited'];
810 $event['private'] = $item['private'];
811 $event['guid'] = $item['guid'];
812 $event['plink'] = $item['plink'];
813 $event['network'] = $item['network'];
814 $event['protocol'] = $item['protocol'];
815 $event['direction'] = $item['direction'];
816 $event['source'] = $item['source'];
818 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
819 if (DBA::isResult($ev)) {
820 $event['id'] = $ev['id'];
823 $event_id = Event::store($event);
825 Logger::info('Event was stored', ['id' => $event_id]);
831 * Process the content
833 * @param array $activity Activity array
835 * @return array|bool Returns the item array or false if there was an unexpected occurrence
838 private static function processContent(array $activity, array $item)
840 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
841 $item['title'] = strip_tags($activity['name'] ?? '');
842 $content = Markdown::toBBCode($activity['content']);
843 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
844 $item['title'] = $activity['name'];
845 $content = $activity['content'];
847 // By default assume "text/html"
848 $item['title'] = HTML::toBBCode($activity['name'] ?? '');
849 $content = HTML::toBBCode($activity['content'] ?? '');
852 $item['title'] = trim(BBCode::toPlaintext($item['title']));
854 if (!empty($activity['languages'])) {
855 $item['language'] = self::processLanguages($activity['languages']);
858 $item['transmitted-languages'] = $activity['transmitted-languages'];
860 if (!empty($activity['emojis'])) {
861 $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
864 $content = self::addMentionLinks($content, $activity['tags']);
866 if (!empty($activity['quote-url'])) {
867 $id = Item::fetchByLink($activity['quote-url'], 0, ActivityPub\Receiver::COMPLETION_ASYNC);
869 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
870 $item['quote-uri-id'] = $shared_item['uri-id'];
871 } elseif ($uri_id = ItemURI::getIdByURI($activity['quote-url'], false)) {
872 Logger::info('Quote was not fetched but the uri-id existed', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url'], 'uri-id' => $uri_id]);
873 $item['quote-uri-id'] = $uri_id;
875 Logger::info('Quote was not fetched', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url']]);
879 if (!empty($activity['source'])) {
880 $item['body'] = $activity['source'];
881 $item['raw-body'] = $content;
883 $quote_uri_id = Item::getQuoteUriId($item['body']);
884 if (empty($item['quote-uri-id']) && !empty($quote_uri_id)) {
885 $item['quote-uri-id'] = $quote_uri_id;
888 $item['body'] = BBCode::removeSharedData($item['body']);
890 $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
891 if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == Item::GRAVITY_COMMENT)) {
892 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
893 if (!DBA::isResult($parent)) {
894 Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
897 $content = self::removeImplicitMentionsFromBody($content, $parent);
899 $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
900 $item['raw-body'] = $item['body'] = $content;
903 if (!empty($item['author-id']) && ($item['author-id'] == $item['owner-id'])) {
904 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
905 $actor = APContact::getByURL($tag[2], false);
906 if (($actor['type'] ?? 'Person') == 'Group') {
907 Logger::debug('Group post detected via exclusive mention.', ['mention' => $actor['url'], 'actor' => $activity['actor'], 'author' => $activity['author']]);
908 $item['isGroup'] = true;
909 $item['group-link'] = $item['owner-link'] = $actor['url'];
910 $item['owner-id'] = Contact::getIdForURL($actor['url']);
916 self::storeFromBody($item);
917 self::storeTags($item['uri-id'], $activity['tags']);
919 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
921 $item['location'] = $activity['location'];
923 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
924 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
927 $item['app'] = $activity['generator'];
933 * Store hashtags and mentions
937 private static function storeFromBody(array $item)
939 // Make sure to delete all existing tags (can happen when called via the update functionality)
940 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
942 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
946 * Generate a GUID out of an URL of an ActivityPub post.
948 * @param string $url message URL
949 * @return string with GUID
951 private static function getGUIDByURL(string $url): string
953 $parsed = parse_url($url);
955 $host_hash = hash('crc32', $parsed['host']);
957 unset($parsed["scheme"]);
958 unset($parsed["host"]);
960 $path = implode("/", $parsed);
962 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
966 * Checks if an incoming message is wanted
968 * @param array $activity
970 * @return boolean Is the message wanted?
972 private static function isSolicitedMessage(array $activity, array $item): bool
974 // The checks are split to improve the support when searching why a message was accepted.
975 if (count($activity['receiver']) != 1) {
976 // The message has more than one receiver, so it is wanted.
977 Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
981 if ($item['private'] == Item::PRIVATE) {
982 // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
983 Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
987 if (!empty($activity['from-relay'])) {
988 // We check relay posts at another place. When it arrived here, the message is already checked.
989 Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
993 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUNCE])) {
994 // Manual completions and completions caused by reshares are allowed without any further checks.
995 Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
999 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1000 // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
1001 // This can possibly be improved in the future.
1002 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
1006 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
1007 if (Relay::isSolicitedPost($tags, $item['title'] . ' ' . ($item['content-warning'] ?? '') . ' ' . $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB, $activity['thread-completion'] ?? 0)) {
1008 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
1016 * Creates an item post
1018 * @param array $activity Activity data
1019 * @param array $item item array
1020 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1021 * @throws \ImagickException
1023 public static function postItem(array $activity, array $item)
1031 ksort($activity['receiver']);
1033 if (!self::isSolicitedMessage($activity, $item)) {
1034 DBA::delete('item-uri', ['id' => $item['uri-id']]);
1035 if (!empty($activity['entry-id'])) {
1036 Queue::deleteById($activity['entry-id']);
1041 foreach ($activity['receiver'] as $receiver) {
1042 if ($receiver == -1) {
1046 if (($receiver != 0) && empty($item['parent-uri-id']) && !empty($item['thr-parent-id'])) {
1047 $parent = Post::selectFirst(['parent-uri-id', 'parent-uri'], ['uri-id' => $item['thr-parent-id'], 'uid' => [0, $receiver]]);
1048 if (!empty($parent['parent-uri-id'])) {
1049 $item['parent-uri-id'] = $parent['parent-uri-id'];
1050 $item['parent-uri'] = $parent['parent-uri'];
1054 $item['uid'] = $receiver;
1056 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
1058 case Receiver::TARGET_TO:
1059 $item['post-reason'] = Item::PR_TO;
1061 case Receiver::TARGET_CC:
1062 $item['post-reason'] = Item::PR_CC;
1064 case Receiver::TARGET_BTO:
1065 $item['post-reason'] = Item::PR_BTO;
1067 case Receiver::TARGET_BCC:
1068 $item['post-reason'] = Item::PR_BCC;
1070 case Receiver::TARGET_AUDIENCE:
1071 $item['post-reason'] = Item::PR_AUDIENCE;
1073 case Receiver::TARGET_FOLLOWER:
1074 $item['post-reason'] = Item::PR_FOLLOWER;
1076 case Receiver::TARGET_ANSWER:
1077 $item['post-reason'] = Item::PR_COMMENT;
1079 case Receiver::TARGET_GLOBAL:
1080 $item['post-reason'] = Item::PR_GLOBAL;
1083 $item['post-reason'] = Item::PR_NONE;
1086 $item['post-reason'] = Item::getPostReason($item);
1088 if (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE])) {
1089 if (!empty($activity['from-relay'])) {
1090 $item['post-reason'] = Item::PR_RELAY;
1091 } elseif (!empty($activity['thread-completion'])) {
1092 $item['post-reason'] = Item::PR_FETCHED;
1093 } elseif (!empty($activity['push'])) {
1094 $item['post-reason'] = Item::PR_PUSHED;
1096 } elseif (($item['post-reason'] == Item::PR_FOLLOWER) && !empty($activity['from-relay'])) {
1097 // When a post arrives via a relay and we follow the author, we have to override the causer.
1098 // Otherwise the system assumes that we follow the relay. (See "addRowInformation")
1099 Logger::debug('Relay post for follower', ['receiver' => $receiver, 'guid' => $item['guid'], 'relay' => $activity['from-relay']]);
1100 $item['causer-id'] = ($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1103 if ($item['isGroup']) {
1104 $item['contact-id'] = Contact::getIdForURL($item['group-link'], $receiver);
1106 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $receiver);
1109 if (($receiver != 0) && empty($item['contact-id'])) {
1110 $item['contact-id'] = Contact::getIdForURL($activity['author']);
1113 if (!empty($activity['directmessage']) && self::postMail($item)) {
1117 if (($receiver != 0) && ($item['gravity'] == Item::GRAVITY_PARENT) && !in_array($item['post-reason'], [Item::PR_FOLLOWER, Item::PR_TAG, item::PR_TO, Item::PR_CC, Item::PR_AUDIENCE])) {
1118 if (!$item['isGroup']) {
1119 if ($item['post-reason'] == Item::PR_BCC) {
1120 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id'], 'url' => $item['uri']]);
1124 if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE)
1125 && in_array($activity['thread-children-type'] ?? '', Receiver::ACTIVITY_TYPES)) {
1126 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
1127 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
1133 $user = User::getById($receiver, ['account-type']);
1134 if (!empty($user['account-type'])) {
1135 $isGroup = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
1138 if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE)
1139 && ((!$isGroup && !$item['isGroup'] && ($activity['type'] != 'as:Announce'))
1140 || !Contact::isSharingByURL($activity['actor'], $receiver))) {
1141 Logger::info('Actor is a non sharer, is no group or it is no announce', ['uid' => $receiver, 'actor' => $activity['actor'], 'url' => $item['uri'], 'type' => $activity['type']]);
1145 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
1148 if (!self::hasParents($item, $receiver)) {
1152 if (($item['gravity'] != Item::GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
1153 $event_id = self::createEvent($activity, $item);
1155 $item = Event::getItemArrayForImportedId($event_id, $item);
1158 $item_id = Item::insert($item);
1160 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
1163 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
1164 if (($item['uid'] == 0) && (count($activity['receiver']) > 1)) {
1165 Logger::info('Public item was aborted. We skip for all users.', ['uri' => $item['uri']]);
1170 if ($item['uid'] == 0) {
1175 Queue::remove($activity);
1177 if ($success && Queue::hasChildren($item['uri']) && Post::exists(['uri' => $item['uri']])) {
1178 Queue::processReplyByUri($item['uri']);
1181 // Store send a follow request for every reshare - but only when the item had been stored
1182 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == Item::GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
1183 $author = APContact::getByURL($item['owner-link'], false);
1184 // We send automatic follow requests for reshared messages. (We don't need though for group posts)
1185 if ($author['type'] != 'Group') {
1186 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
1187 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
1193 * Checks if there are parent posts for the given receiver.
1194 * If not, then the system will try to add them.
1196 * @param array $item
1197 * @param integer $receiver
1200 private static function hasParents(array $item, int $receiver)
1202 if (($receiver == 0) || ($item['gravity'] == Item::GRAVITY_PARENT)) {
1206 $fields = ['causer-id' => $item['causer-id'] ?? $item['author-id'], 'post-reason' => Item::PR_FETCHED];
1210 if ($item['verb'] != Activity::ANNOUNCE) {
1211 switch (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer')) {
1212 case Item::COMPLETION_COMMENT:
1213 $add_parent = ($item['gravity'] != Item::GRAVITY_ACTIVITY);
1216 case Item::COMPLETION_NONE:
1217 $add_parent = false;
1223 $add_parent = Contact::isSharing($fields['causer-id'], $receiver);
1224 if (!$add_parent && ($item['author-id'] != $fields['causer-id'])) {
1225 $add_parent = Contact::isSharing($item['author-id'], $receiver);
1227 if (!$add_parent && !in_array($item['owner-id'], [$fields['causer-id'], $item['author-id']])) {
1228 $add_parent = Contact::isSharing($item['owner-id'], $receiver);
1232 $has_parents = false;
1234 if (!empty($item['parent-uri-id'])) {
1235 if (Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $receiver])) {
1236 $has_parents = true;
1237 } elseif ($add_parent && Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1238 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $receiver, $fields);
1239 $has_parents = (bool)$stored;
1241 Logger::notice('Inserted missing parent post', ['stored' => $stored, 'uid' => $receiver, 'parent' => $item['parent-uri']]);
1243 Logger::notice('Parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1246 } elseif ($add_parent) {
1247 Logger::debug('Parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1249 Logger::debug('Parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'parent' => $item['parent-uri']]);
1253 if (empty($item['parent-uri-id']) || ($item['thr-parent-id'] != $item['parent-uri-id'])) {
1254 if (Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $receiver])) {
1255 $has_parents = true;
1256 } elseif (($has_parents || $add_parent) && Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => 0])) {
1257 $stored = Item::storeForUserByUriId($item['thr-parent-id'], $receiver, $fields);
1258 $has_parents = $has_parents || (bool)$stored;
1260 Logger::notice('Inserted missing thread parent post', ['stored' => $stored, 'uid' => $receiver, 'thread-parent' => $item['thr-parent']]);
1262 Logger::notice('Thread parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1264 } elseif ($add_parent) {
1265 Logger::debug('Thread parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1267 Logger::debug('Thread parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]);
1271 return $has_parents;
1275 * Store tags and mentions into the tag table
1277 * @param integer $uriid
1278 * @param array $tags
1280 private static function storeTags(int $uriid, array $tags = null)
1282 foreach ($tags as $tag) {
1283 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1287 $hash = substr($tag['name'], 0, 1);
1289 if ($tag['type'] == 'Mention') {
1290 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1291 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1292 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1293 $tag['name'] = substr($tag['name'], 1);
1295 $type = Tag::IMPLICIT_MENTION;
1297 if (!empty($tag['href'])) {
1298 $apcontact = APContact::getByURL($tag['href']);
1299 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1300 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1303 } elseif ($tag['type'] == 'Hashtag') {
1304 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1305 $tag['name'] = substr($tag['name'], 1);
1307 $type = Tag::HASHTAG;
1310 if (empty($tag['name'])) {
1314 Tag::store($uriid, $type, $tag['name'], $tag['href']);
1318 public static function storeReceivers(int $uriid, array $receivers)
1320 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC, 'as:audience' => Tag::AUDIENCE, 'as:attributedTo' => Tag::ATTRIBUTED] as $element => $type) {
1321 if (!empty($receivers[$element])) {
1322 foreach ($receivers[$element] as $receiver) {
1323 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1324 $name = Receiver::PUBLIC_COLLECTION;
1325 } elseif ($path = parse_url($receiver, PHP_URL_PATH)) {
1326 $name = trim($path, '/');
1327 } elseif ($host = parse_url($receiver, PHP_URL_HOST)) {
1330 Logger::warning('Unable to coerce name from receiver', ['element' => $element, 'type' => $type, 'receiver' => $receiver]);
1334 $target = Tag::getTargetType($receiver);
1335 Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1336 Tag::store($uriid, $type, $name, $receiver, $target);
1343 * Creates an mail post
1345 * @param array $item item array
1346 * @return int|bool New mail table row id or false on error
1347 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1349 private static function postMail(array $item): bool
1351 if (($item['gravity'] != Item::GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1352 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1356 if (!Contact::isFollower($item['contact-id'], $item['uid']) && !Contact::isSharing($item['contact-id'], $item['uid'])) {
1357 Logger::info('Contact is not a sharer or follower, mail will be discarded.', ['item' => $item]);
1361 Logger::info('Direct Message', $item);
1364 $msg['uid'] = $item['uid'];
1366 $msg['contact-id'] = $item['contact-id'];
1368 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1369 $msg['from-name'] = $contact['name'];
1370 $msg['from-url'] = $contact['url'];
1371 $msg['from-photo'] = $contact['photo'];
1373 $msg['uri'] = $item['uri'];
1374 $msg['created'] = $item['created'];
1376 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1377 if (DBA::isResult($parent)) {
1378 $msg['parent-uri'] = $parent['parent-uri'];
1379 $msg['title'] = $parent['title'];
1381 $msg['parent-uri'] = $item['thr-parent'];
1383 if (!empty($item['title'])) {
1384 $msg['title'] = $item['title'];
1385 } elseif (!empty($item['content-warning'])) {
1386 $msg['title'] = $item['content-warning'];
1388 // Trying to generate a title out of the body
1389 $title = $item['body'];
1391 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1392 $title = $matches[3];
1395 $title = trim(BBCode::toPlaintext($title));
1397 if (strlen($title) > 20) {
1398 $title = substr($title, 0, 20) . '...';
1401 $msg['title'] = $title;
1404 $msg['body'] = $item['body'];
1406 return Mail::insert($msg);
1410 * Fetch featured posts from a contact with the given url
1412 * @param string $url
1415 public static function fetchFeaturedPosts(string $url)
1417 Logger::info('Fetch featured posts', ['contact' => $url]);
1419 $apcontact = APContact::getByURL($url);
1420 if (empty($apcontact['featured'])) {
1421 Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1425 $pcid = Contact::getIdForURL($url, 0, false);
1427 Logger::notice('Contact not found', ['contact' => $url]);
1431 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1432 if (!empty($posts)) {
1433 $old_featured = array_column($posts, 'uri-id');
1438 $featured = ActivityPub::fetchItems($apcontact['featured']);
1439 if (empty($featured)) {
1440 Logger::info('Contact does not have featured posts', ['contact' => $url]);
1442 foreach ($old_featured as $uri_id) {
1443 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1444 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1452 foreach ($featured as $post) {
1453 if (empty($post['id'])) {
1456 $id = Item::fetchByLink($post['id'], 0, ActivityPub\Receiver::COMPLETION_ASYNC);
1458 $item = Post::selectFirst(['uri-id', 'featured', 'author-id'], ['id' => $id]);
1459 if (!empty($item['uri-id'])) {
1460 if (!$item['featured']) {
1461 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED, $item['author-id']);
1462 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1465 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1469 $index = array_search($item['uri-id'], $old_featured);
1470 if (!($index === false)) {
1471 unset($old_featured[$index]);
1477 foreach ($old_featured as $uri_id) {
1478 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1479 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1482 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1485 public static function fetchCachedActivity(string $url, int $uid): array
1487 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . hash('sha256', $url);
1488 $object = DI::cache()->get($cachekey);
1490 if (!is_null($object)) {
1491 if (!empty($object)) {
1492 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1494 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1499 $object = HTTPSignature::fetch($url, $uid);
1500 if (empty($object)) {
1501 Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1502 // We perform negative caching.
1503 DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1507 if (empty($object['id'])) {
1508 Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1511 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1513 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1519 * Fetches missing posts
1521 * @param string $url message URL
1522 * @param array $child activity array with the child of this message
1523 * @param string $relay_actor Relay actor
1524 * @param int $completion Completion mode, see Receiver::COMPLETION_*
1525 * @param int $uid User id that is used to fetch the activity
1526 * @return string fetched message URL. An empty string indicates a temporary error, null indicates a permament error,
1527 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1528 * @throws \ImagickException
1530 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL, int $uid = 0): ?string
1532 if (Network::isUrlBlocked($url)) {
1537 $curlResult = HTTPSignature::fetchRaw($url, $uid);
1538 } catch (\Exception $exception) {
1539 Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
1543 if (empty($curlResult)) {
1547 $body = $curlResult->getBody();
1548 if (!$curlResult->isSuccess() || empty($body)) {
1549 if (in_array($curlResult->getReturnCode(), [403, 404, 406, 410])) {
1555 $object = json_decode($body, true);
1556 if (empty($object) || !is_array($object)) {
1557 $element = explode(';', $curlResult->getContentType());
1558 if (!in_array($element[0], ['application/activity+json', 'application/ld+json', 'application/json'])) {
1559 Logger::debug('Unexpected content-type', ['url' => $url, 'content-type' => $curlResult->getContentType()]);
1562 Logger::notice('Invalid JSON data', ['url' => $url, 'content-type' => $curlResult->getContentType(), 'body' => $body]);
1566 $ldobject = JsonLD::compact($object);
1570 $attributed_to = JsonLD::fetchElement($ldobject, 'as:attributedTo', '@id');
1571 if (!empty($attributed_to)) {
1572 $signer[] = $attributed_to;
1575 $object_actor = JsonLD::fetchElement($ldobject, 'as:actor', '@id');
1576 if (!empty($attributed_to)) {
1577 $object_actor = $attributed_to;
1583 $signer[] = $object_actor;
1585 if (!empty($child['author'])) {
1586 $actor = $child['author'];
1589 $actor = $object_actor;
1592 $type = JsonLD::fetchElement($ldobject, '@type');
1593 $object_id = JsonLD::fetchElement($ldobject, 'as:object', '@id');
1595 if (!in_array($type, Receiver::CONTENT_TYPES) && !empty($object_id)) {
1596 if (($type == 'as:Announce') && !empty($relay_actor) && ($completion = Receiver::COMPLETION_RELAY)) {
1597 if (Item::searchByLink($object_id)) {
1600 Logger::debug('Fetch announced activity', ['type' => $type, 'id' => $object_id, 'actor' => $relay_actor, 'signer' => $signer]);
1602 return self::fetchMissingActivity($object_id, $child, $relay_actor, $completion, $uid);
1604 $activity = $object;
1605 $ldactivity = $ldobject;
1606 } elseif (!empty($object['id'])) {
1607 $activity = self::getActivityForObject($object, $actor);
1608 $ldactivity = JsonLD::compact($activity);
1613 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 0;
1615 if ($object_actor != $actor) {
1616 Contact::updateByUrlIfNeeded($object_actor);
1619 Contact::updateByUrlIfNeeded($actor);
1621 if (!empty($child['thread-completion'])) {
1622 $ldactivity['thread-completion'] = $child['thread-completion'];
1623 $ldactivity['completion-mode'] = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1625 $ldactivity['thread-completion'] = Contact::getIdForURL($relay_actor ?: $actor);
1626 $ldactivity['completion-mode'] = $completion;
1629 if ($completion == Receiver::COMPLETION_RELAY) {
1630 $ldactivity['from-relay'] = $ldactivity['thread-completion'];
1631 if (in_array($type, Receiver::CONTENT_TYPES) && !self::acceptIncomingMessage($ldactivity)) {
1636 if (!empty($child['thread-children-type'])) {
1637 $ldactivity['thread-children-type'] = $child['thread-children-type'];
1638 } elseif (!empty($child['type'])) {
1639 $ldactivity['thread-children-type'] = $child['type'];
1641 $ldactivity['thread-children-type'] = 'as:Create';
1644 if (($completion == Receiver::COMPLETION_RELAY) && Queue::exists($url, 'as:Create')) {
1645 Logger::info('Activity has already been queued.', ['url' => $url, 'object' => $activity['id']]);
1646 } elseif (ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer, '', $completion)) {
1647 Logger::info('Activity had been fetched and processed.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1649 Logger::info('Activity had been fetched and will be processed later.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1652 return $activity['id'];
1655 private static function getActivityForObject(array $object, string $actor): array
1657 if (!empty($object['published'])) {
1658 $published = $object['published'];
1659 } elseif (!empty($child['published'])) {
1660 $published = $child['published'];
1662 $published = DateTimeFormat::utcNow();
1666 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1667 unset($object['@context']);
1668 $activity['id'] = $object['id'];
1669 $activity['to'] = $object['to'] ?? [];
1670 $activity['cc'] = $object['cc'] ?? [];
1671 $activity['audience'] = $object['audience'] ?? [];
1672 $activity['actor'] = $actor;
1673 $activity['object'] = $object;
1674 $activity['published'] = $published;
1675 $activity['type'] = 'Create';
1681 * Test if incoming relay messages should be accepted
1683 * @param array $activity activity array
1684 * @return boolean true if message is accepted
1686 private static function acceptIncomingMessage(array $activity): bool
1688 if (empty($activity['as:object'])) {
1689 $id = JsonLD::fetchElement($activity, '@id');
1690 Logger::info('No object field in activity - accepted', ['id' => $id]);
1694 $id = JsonLD::fetchElement($activity, 'as:object', '@id');
1696 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1697 $uriid = ItemURI::getIdByURI($replyto ?? '');
1698 if (Post::exists(['uri-id' => $uriid])) {
1699 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1703 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1704 $authorid = Contact::getIdForURL($attributed_to);
1706 $content = JsonLD::fetchElement($activity['as:object'], 'as:name', '@value') ?? '';
1707 $content .= ' ' . JsonLD::fetchElement($activity['as:object'], 'as:summary', '@value') ?? '';
1708 $content .= ' ' . HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1710 $attachments = JsonLD::fetchElementArray($activity['as:object'], 'as:attachment') ?? [];
1711 foreach ($attachments as $media) {
1712 if (!empty($media['as:summary'])) {
1713 $content .= ' ' . JsonLD::fetchElement($media, 'as:summary', '@value');
1715 if (!empty($media['as:name'])) {
1716 $content .= ' ' . JsonLD::fetchElement($media, 'as:name', '@value');
1721 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1722 if (!empty($tags)) {
1723 foreach ($tags as $tag) {
1724 if (($tag['type'] != 'Hashtag') && !strpos($tag['type'], ':Hashtag')) {
1727 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1731 $languages = self::getPostLanguages($activity['as:object'] ?? '');
1733 $wanted = Relay::isSolicitedPost($messageTags, $content, $authorid, $id, Protocol::ACTIVITYPUB, $activity['from-relay'], $languages);
1739 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience'] as $element) {
1740 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1741 if (empty($receiver_list)) {
1744 $receivers = array_merge($receivers, $receiver_list);
1747 $searchtext = Engagement::getSearchTextForActivity($content, $authorid, $messageTags, $receivers);
1748 $language = array_key_first(Item::getLanguageArray($content, 1, 0, $authorid));
1749 return DI::userDefinedChannel()->match($searchtext, $language);
1753 * Fetch the post language from the content
1755 * @param array $activity
1758 public static function getPostLanguages(array $activity): array
1760 $content = JsonLD::fetchElement($activity, 'as:content') ?? '';
1761 $languages = JsonLD::fetchElementArray($activity, 'as:content', '@language') ?? [];
1762 if (empty($languages)) {
1766 $iso639 = new \Matriphe\ISO639\ISO639;
1769 foreach ($languages as $language) {
1770 if ($language == $content) {
1773 $language = DI::l10n()->toISO6391($language);
1774 if (!in_array($language, array_column($iso639->allLanguages(), 0))) {
1777 $result[] = $language;
1783 * perform a "follow" request
1785 * @param array $activity
1787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1788 * @throws \ImagickException
1790 public static function followUser(array $activity)
1792 $uid = User::getIdForURL($activity['object_id']);
1794 Queue::remove($activity);
1798 $owner = User::getOwnerDataById($uid);
1799 if (empty($owner)) {
1803 $cid = Contact::getIdForURL($activity['actor'], $uid);
1805 self::switchContact($cid);
1806 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1810 'author-id' => Contact::getIdForURL($activity['actor']),
1811 'author-link' => $activity['actor'],
1814 // Ensure that the contact has got the right network type
1815 self::switchContact($item['author-id']);
1817 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1818 if ($result === true) {
1819 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1822 $cid = Contact::getIdForURL($activity['actor'], $uid);
1827 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1828 self::transmitPendingEvents($cid, $owner['uid']);
1831 if (empty($contact)) {
1832 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1834 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1835 Queue::remove($activity);
1839 * Transmit pending events to the new follower
1841 * @param integer $cid Contact id
1842 * @param integer $uid User id
1845 private static function transmitPendingEvents(int $cid, int $uid)
1847 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1848 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1850 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1851 while ($event = DBA::fetch($events)) {
1852 $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1856 if (DI::config()->get('system', 'bulk_delivery')) {
1857 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1858 Worker::add(Worker::PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1860 Worker::add(Worker::PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1866 * Update the given profile
1868 * @param array $activity
1869 * @throws \Exception
1871 public static function updatePerson(array $activity)
1873 if (empty($activity['object_id'])) {
1877 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1878 Contact::updateFromProbeByURL($activity['object_id']);
1879 Queue::remove($activity);
1883 * Delete the given profile
1885 * @param array $activity
1887 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1889 public static function deletePerson(array $activity)
1891 if (empty($activity['object_id']) || empty($activity['actor'])) {
1892 Logger::info('Empty object id or actor.');
1893 Queue::remove($activity);
1897 if ($activity['object_id'] != $activity['actor']) {
1898 Logger::info('Object id does not match actor.');
1899 Queue::remove($activity);
1903 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1904 while ($contact = DBA::fetch($contacts)) {
1905 Contact::remove($contact['id']);
1907 DBA::close($contacts);
1909 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1910 Queue::remove($activity);
1914 * Add moved contacts as followers for all subscribers of the old contact
1916 * @param array $activity
1918 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1920 public static function movePerson(array $activity)
1922 if (empty($activity['target_id']) || empty($activity['object_id'])) {
1923 Queue::remove($activity);
1927 if ($activity['object_id'] != $activity['actor']) {
1928 Logger::notice('Object is not the actor', ['activity' => $activity]);
1929 Queue::remove($activity);
1933 $from = Contact::getByURL($activity['object_id'], false, ['uri-id']);
1934 if (empty($from['uri-id'])) {
1935 Logger::info('Object not found', ['activity' => $activity]);
1936 Queue::remove($activity);
1940 $contacts = DBA::select('contact', ['uid', 'url'], ["`uri-id` = ? AND `uid` != ? AND `rel` IN (?, ?)", $from['uri-id'], 0, Contact::FRIEND, Contact::SHARING]);
1941 while ($from_contact = DBA::fetch($contacts)) {
1942 $result = Contact::createFromProbeForUser($from_contact['uid'], $activity['target_id']);
1943 Logger::debug('Follower added', ['from' => $from_contact, 'result' => $result]);
1945 DBA::close($contacts);
1946 Queue::remove($activity);
1950 * Blocks the user by the contact
1952 * @param array $activity
1954 * @throws \Exception
1956 public static function blockAccount(array $activity)
1958 $cid = Contact::getIdForURL($activity['actor']);
1963 $uid = User::getIdForURL($activity['object_id']);
1968 Contact\User::setIsBlocked($cid, $uid, true);
1970 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1971 Queue::remove($activity);
1975 * Unblocks the user by the contact
1977 * @param array $activity
1979 * @throws \Exception
1981 public static function unblockAccount(array $activity)
1983 $cid = Contact::getIdForURL($activity['actor']);
1988 $uid = User::getIdForURL($activity['object_object']);
1993 Contact\User::setIsBlocked($cid, $uid, false);
1995 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1996 Queue::remove($activity);
2002 * @param array $activity
2004 * @throws \Exception
2006 public static function ReportAccount(array $activity)
2008 $account = Contact::getByURL($activity['object_id'], null, ['id', 'gsid']);
2009 if (empty($account)) {
2010 Logger::info('Unknown account', ['activity' => $activity]);
2011 Queue::remove($activity);
2015 $reporter_id = Contact::getIdForURL($activity['actor']);
2016 if (empty($reporter_id)) {
2017 Logger::info('Unknown actor', ['activity' => $activity]);
2018 Queue::remove($activity);
2023 foreach ($activity['object_ids'] as $status_id) {
2024 $post = Post::selectFirst(['uri-id'], ['uri' => $status_id]);
2025 if (!empty($post['uri-id'])) {
2026 $uri_ids[] = $post['uri-id'];
2030 $report = DI::reportFactory()->createFromReportsRequest(System::getRules(true), $reporter_id, $account['id'], $account['gsid'], $activity['content'], 'other', false, $uri_ids);
2031 DI::report()->save($report);
2033 Logger::info('Stored report', ['reporter' => $reporter_id, 'account' => $account, 'comment' => $activity['content'], 'object_ids' => $activity['object_ids']]);
2037 * Accept a follow request
2039 * @param array $activity
2040 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2041 * @throws \ImagickException
2043 public static function acceptFollowUser(array $activity)
2045 if (!empty($activity['object_actor'])) {
2046 $uid = User::getIdForURL($activity['object_actor']);
2048 } elseif (!empty($activity['receiver']) && (count($activity['receiver']) == 1)) {
2049 $uid = array_shift($activity['receiver']);
2054 Logger::notice('User could not be detected', ['activity' => $activity]);
2055 Queue::remove($activity);
2059 $cid = Contact::getIdForURL($activity['actor'], $uid);
2061 Logger::notice('No contact found', ['actor' => $activity['actor']]);
2062 Queue::remove($activity);
2066 $id = Transmitter::activityIDFromContact($cid);
2067 if ($id == $activity['object_id']) {
2068 Logger::info('Successful id check', ['uid' => $uid, 'cid' => $cid]);
2070 Logger::info('Unsuccessful id check', ['uid' => $uid, 'cid' => $cid, 'id' => $id, 'object_id' => $activity['object_id']]);
2072 Queue::remove($activity);
2077 self::switchContact($cid);
2079 $fields = ['pending' => false];
2081 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
2082 if ($contact['rel'] == Contact::FOLLOWER) {
2083 $fields['rel'] = Contact::FRIEND;
2086 $condition = ['id' => $cid];
2087 Contact::update($fields, $condition);
2088 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
2089 Queue::remove($activity);
2093 * Reject a follow request
2095 * @param array $activity
2096 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2097 * @throws \ImagickException
2099 public static function rejectFollowUser(array $activity)
2101 $uid = User::getIdForURL($activity['object_actor']);
2106 $cid = Contact::getIdForURL($activity['actor'], $uid);
2108 Logger::info('No contact found', ['actor' => $activity['actor']]);
2112 self::switchContact($cid);
2114 $contact = Contact::getById($cid, ['rel']);
2115 if ($contact['rel'] == Contact::SHARING) {
2116 Contact::remove($cid);
2117 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
2118 } elseif ($contact['rel'] == Contact::FRIEND) {
2119 Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
2121 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
2123 Queue::remove($activity);
2127 * Undo activity like "like" or "dislike"
2129 * @param array $activity
2130 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2131 * @throws \ImagickException
2133 public static function undoActivity(array $activity)
2135 if (empty($activity['object_id'])) {
2139 if (empty($activity['object_actor'])) {
2143 $author_id = Contact::getIdForURL($activity['object_actor']);
2144 if (empty($author_id)) {
2148 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => Item::GRAVITY_ACTIVITY]);
2149 Queue::remove($activity);
2153 * Activity to remove a follower
2155 * @param array $activity
2156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2157 * @throws \ImagickException
2159 public static function undoFollowUser(array $activity)
2161 $uid = User::getIdForURL($activity['object_object']);
2166 $owner = User::getOwnerDataById($uid);
2167 if (empty($owner)) {
2171 $cid = Contact::getIdForURL($activity['actor'], $uid);
2173 Logger::info('No contact found', ['actor' => $activity['actor']]);
2177 self::switchContact($cid);
2179 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2180 if (!DBA::isResult($contact)) {
2184 Contact::removeFollower($contact);
2185 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
2186 Queue::remove($activity);
2190 * Switches a contact to AP if needed
2192 * @param integer $cid Contact ID
2194 * @throws \Exception
2196 private static function switchContact(int $cid)
2198 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
2199 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
2203 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
2204 Contact::updateFromProbe($cid);
2208 * Collects implicit mentions like:
2209 * - the author of the parent item
2210 * - all the mentioned conversants in the parent item
2212 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
2214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2216 private static function getImplicitMentionList(array $parent): array
2218 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
2220 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
2222 $implicit_mentions = [];
2223 if (empty($parent_author['url'])) {
2224 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
2226 $implicit_mentions[] = $parent_author['url'];
2227 $implicit_mentions[] = $parent_author['nurl'];
2228 $implicit_mentions[] = $parent_author['alias'];
2231 if (!empty($parent['alias'])) {
2232 $implicit_mentions[] = $parent['alias'];
2235 foreach ($parent_terms as $term) {
2236 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
2237 if (!empty($contact['url'])) {
2238 $implicit_mentions[] = $contact['url'];
2239 $implicit_mentions[] = $contact['nurl'];
2240 $implicit_mentions[] = $contact['alias'];
2244 return $implicit_mentions;
2248 * Strips from the body prepended implicit mentions
2250 * @param string $body
2251 * @param array $parent
2254 private static function removeImplicitMentionsFromBody(string $body, array $parent): string
2256 if (DI::config()->get('system', 'disable_implicit_mentions')) {
2260 $potential_mentions = self::getImplicitMentionList($parent);
2262 $kept_mentions = [];
2264 // Extract one prepended mention at a time from the body
2265 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
2266 if (!in_array($matches[2], $potential_mentions)) {
2267 $kept_mentions[] = $matches[1];
2270 $body = $matches[3];
2273 // Re-appending the kept mentions to the body after extraction
2274 $kept_mentions[] = $body;
2276 return implode('', $kept_mentions);
2280 * Adds links to string mentions
2282 * @param string $body
2283 * @param array $tags
2286 protected static function addMentionLinks(string $body, array $tags): string
2288 // This prevents links to be added again to Pleroma-style mention links
2289 $body = self::normalizeMentionLinks($body);
2291 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
2292 foreach ($tags as $tag) {
2293 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
2297 $hash = substr($tag['name'], 0, 1);
2298 $name = substr($tag['name'], 1);
2299 if (!in_array($hash, Tag::TAG_CHARACTER)) {
2301 $name = $tag['name'];
2304 if (Network::isValidHttpUrl($tag['href'])) {
2305 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);