3 * @copyright Copyright (C) 2020, Friendica
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\PageInfo;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Model\APContact;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\Event;
36 use Friendica\Model\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Mail;
39 use Friendica\Model\Tag;
40 use Friendica\Model\User;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\JsonLD;
45 use Friendica\Util\Strings;
48 * ActivityPub Processor Protocol class
53 * Converts mentions from Pleroma into the Friendica format
57 * @return string converted body
59 private static function convertMentions($body)
61 $URLSearchString = "^\[\]";
62 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
68 * Replaces emojis in the body
70 * @param array $emojis
73 * @return string with replaced emojis
75 private static function replaceEmojis($body, array $emojis)
77 foreach ($emojis as $emoji) {
78 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
79 $body = str_replace($emoji['name'], $replace, $body);
85 * Add attachment data to the item array
87 * @param array $activity
92 private static function constructAttachList($activity, $item)
94 if (empty($activity['attachments'])) {
98 foreach ($activity['attachments'] as $attach) {
99 switch ($attach['type']) {
102 'url' => $attach['url'],
103 'type' => $attach['type'],
104 'title' => $attach['title'] ?? '',
105 'text' => $attach['desc'] ?? '',
106 'image' => $attach['image'] ?? '',
110 $item['body'] = PageInfo::appendDataToBody($item['body'], $data);
113 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
114 if ($filetype == 'image') {
115 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
119 $item['body'] .= "\n";
121 // image is the preview/thumbnail URL
122 if (!empty($attach['image'])) {
123 $item['body'] .= '[url=' . $attach['url'] . ']';
124 $attach['url'] = $attach['image'];
127 if (empty($attach['name'])) {
128 $item['body'] .= '[img]' . $attach['url'] . '[/img]';
130 $item['body'] .= '[img=' . $attach['url'] . ']' . $attach['name'] . '[/img]';
133 if (!empty($attach['image'])) {
134 $item['body'] .= '[/url]';
136 } elseif ($filetype == 'audio') {
137 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
141 $item['body'] .= "\n[audio]" . $attach['url'] . '[/audio]';
142 } elseif ($filetype == 'video') {
143 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
147 $item['body'] .= "\n[video]" . $attach['url'] . '[/video]';
149 if (!empty($item["attach"])) {
150 $item["attach"] .= ',';
152 $item["attach"] = '';
155 $item["attach"] .= '[attach]href="' . $attach['url'] . '" length="' . ($attach['length'] ?? '0') . '" type="' . $attach['mediaType'] . '" title="' . ($attach['name'] ?? '') . '"[/attach]';
166 * @param array $activity Activity array
167 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 public static function updateItem($activity)
171 $item = Item::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
172 if (!DBA::isResult($item)) {
173 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
174 $item = self::createItem($activity);
175 self::postItem($activity, $item);
179 $item['changed'] = DateTimeFormat::utcNow();
180 $item['edited'] = DateTimeFormat::utc($activity['updated']);
182 $item = self::processContent($activity, $item);
187 Item::update($item, ['uri' => $activity['id']]);
191 * Prepares data for a message
193 * @param array $activity Activity array
194 * @return array Internal item
195 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
196 * @throws \ImagickException
198 public static function createItem($activity)
201 $item['verb'] = Activity::POST;
202 $item['thr-parent'] = $activity['reply-to-id'];
204 if ($activity['reply-to-id'] == $activity['id']) {
205 $item['gravity'] = GRAVITY_PARENT;
206 $item['object-type'] = Activity\ObjectType::NOTE;
208 $item['gravity'] = GRAVITY_COMMENT;
209 $item['object-type'] = Activity\ObjectType::COMMENT;
211 // Ensure that the comment reaches all receivers of the referring post
212 $activity['receiver'] = self::addReceivers($activity);
215 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
216 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
217 self::fetchMissingActivity($activity['reply-to-id'], $activity);
220 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
222 /// @todo What to do with $activity['context']?
223 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
224 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
228 $item['network'] = Protocol::ACTIVITYPUB;
229 $item['author-link'] = $activity['author'];
230 $item['author-id'] = Contact::getIdForURL($activity['author']);
231 $item['owner-link'] = $activity['actor'];
232 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
234 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
235 $item['private'] = Item::UNLISTED;
236 } elseif (in_array(0, $activity['receiver'])) {
237 $item['private'] = Item::PUBLIC;
239 $item['private'] = Item::PRIVATE;
242 if (!empty($activity['raw'])) {
243 $item['source'] = $activity['raw'];
244 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
245 $item['conversation-href'] = $activity['context'] ?? '';
246 $item['conversation-uri'] = $activity['conversation'] ?? '';
248 if (isset($activity['push'])) {
249 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
253 $item['isForum'] = false;
255 if (!empty($activity['thread-completion'])) {
256 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
257 $item['causer-link'] = $item['owner-link'];
258 $item['causer-id'] = $item['owner-id'];
260 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
261 $item['owner-link'] = $item['author-link'];
262 $item['owner-id'] = $item['author-id'];
264 $actor = APContact::getByURL($item['owner-link'], false);
265 $item['isForum'] = ($actor['type'] == 'Group');
268 $item['uri'] = $activity['id'];
270 $item['created'] = DateTimeFormat::utc($activity['published']);
271 $item['edited'] = DateTimeFormat::utc($activity['updated']);
272 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
273 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
275 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
277 $item = self::processContent($activity, $item);
282 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
284 $item = self::constructAttachList($activity, $item);
292 * @param array $activity
293 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
294 * @throws \ImagickException
296 public static function deleteItem($activity)
298 $owner = Contact::getIdForURL($activity['actor']);
300 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
301 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
305 * Prepare the item array for an activity
307 * @param array $activity Activity array
308 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
309 * @throws \ImagickException
311 public static function addTag($activity)
313 if (empty($activity['object_content']) || empty($activity['object_id'])) {
317 foreach ($activity['receiver'] as $receiver) {
318 $item = Item::selectFirst(['id', 'uri-id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
319 if (!DBA::isResult($item)) {
320 // We don't fetch missing content for this purpose
324 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
325 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
329 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
330 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
335 * Add users to the receiver list of the given public activity.
336 * This is used to ensure that the activity will be stored in every thread.
338 * @param array $activity Activity array
339 * @return array Modified receiver list
341 private static function addReceivers(array $activity)
343 if (!in_array(0, $activity['receiver'])) {
344 // Private activities will not be modified
345 return $activity['receiver'];
348 // Add all owners of the referring item to the receivers
349 $original = $receivers = $activity['receiver'];
350 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
351 while ($item = DBA::fetch($items)) {
352 $receivers['uid:' . $item['uid']] = $item['uid'];
356 if (count($original) != count($receivers)) {
357 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers, 'callstack' => System::callstack()]);
364 * Prepare the item array for an activity
366 * @param array $activity Activity array
367 * @param string $verb Activity verb
368 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
369 * @throws \ImagickException
371 public static function createActivity($activity, $verb)
373 $item = self::createItem($activity);
374 $item['verb'] = $verb;
375 $item['thr-parent'] = $activity['object_id'];
376 $item['gravity'] = GRAVITY_ACTIVITY;
377 $item['object-type'] = Activity\ObjectType::NOTE;
379 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
381 $activity['receiver'] = self::addReceivers($activity);
383 self::postItem($activity, $item);
389 * @param array $activity Activity array
393 public static function createEvent($activity, $item)
395 $event['summary'] = HTML::toBBCode($activity['name']);
396 $event['desc'] = HTML::toBBCode($activity['content']);
397 $event['start'] = $activity['start-time'];
398 $event['finish'] = $activity['end-time'];
399 $event['nofinish'] = empty($event['finish']);
400 $event['location'] = $activity['location'];
401 $event['adjust'] = true;
402 $event['cid'] = $item['contact-id'];
403 $event['uid'] = $item['uid'];
404 $event['uri'] = $item['uri'];
405 $event['edited'] = $item['edited'];
406 $event['private'] = $item['private'];
407 $event['guid'] = $item['guid'];
408 $event['plink'] = $item['plink'];
410 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
411 $ev = DBA::selectFirst('event', ['id'], $condition);
412 if (DBA::isResult($ev)) {
413 $event['id'] = $ev['id'];
416 $event_id = Event::store($event);
417 Logger::info('Event was stored', ['id' => $event_id]);
421 * Process the content
423 * @param array $activity Activity array
425 * @return array|bool Returns the item array or false if there was an unexpected occurrence
428 private static function processContent($activity, $item)
430 $item['title'] = HTML::toBBCode($activity['name']);
432 if (!empty($activity['source'])) {
433 $item['body'] = $activity['source'];
435 $content = HTML::toBBCode($activity['content']);
437 if (!empty($activity['emojis'])) {
438 $content = self::replaceEmojis($content, $activity['emojis']);
441 $content = self::convertMentions($content);
443 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
444 $item_private = !in_array(0, $activity['item_receiver']);
445 $parent = Item::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
446 if (!DBA::isResult($parent)) {
447 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
450 if ($item_private && ($parent['private'] != Item::PRIVATE)) {
451 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
455 $content = self::removeImplicitMentionsFromBody($content, $parent);
457 $item['content-warning'] = HTML::toBBCode($activity['summary']);
458 $item['body'] = $content;
461 self::storeFromBody($item);
462 self::storeTags($item['uri-id'], $activity['tags']);
464 $item['location'] = $activity['location'];
466 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
467 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
470 $item['app'] = $activity['generator'];
476 * Store hashtags and mentions
480 private static function storeFromBody(array $item)
482 // Make sure to delete all existing tags (can happen when called via the update functionality)
483 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
485 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
489 * Generate a GUID out of an URL
491 * @param string $url message URL
492 * @return string with GUID
494 private static function getGUIDByURL(string $url)
496 $parsed = parse_url($url);
498 $host_hash = hash('crc32', $parsed['host']);
500 unset($parsed["scheme"]);
501 unset($parsed["host"]);
503 $path = implode("/", $parsed);
505 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
509 * Creates an item post
511 * @param array $activity Activity data
512 * @param array $item item array
513 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
514 * @throws \ImagickException
516 public static function postItem(array $activity, array $item)
524 foreach ($activity['receiver'] as $receiver) {
525 if ($receiver == -1) {
529 $item['uid'] = $receiver;
531 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
533 case Receiver::TARGET_TO:
534 $item['post-type'] = Item::PT_TO;
536 case Receiver::TARGET_CC:
537 $item['post-type'] = Item::PT_CC;
539 case Receiver::TARGET_BTO:
540 $item['post-type'] = Item::PT_BTO;
542 case Receiver::TARGET_BCC:
543 $item['post-type'] = Item::PT_BCC;
545 case Receiver::TARGET_FOLLOWER:
546 $item['post-type'] = Item::PT_FOLLOWER;
548 case Receiver::TARGET_ANSWER:
549 $item['post-type'] = Item::PT_COMMENT;
552 $item['post-type'] = Item::PT_ARTICLE;
555 if ($item['isForum'] ?? false) {
556 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
558 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
561 if (($receiver != 0) && empty($item['contact-id'])) {
562 $item['contact-id'] = Contact::getIdForURL($activity['author']);
565 if (!empty($activity['directmessage'])) {
566 self::postMail($activity, $item);
570 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
571 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
573 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
574 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
578 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
582 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
585 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
586 self::createEvent($activity, $item);
589 $item_id = Item::insert($item);
591 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
593 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
596 if ($item['uid'] == 0) {
601 // Store send a follow request for every reshare - but only when the item had been stored
602 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
603 $author = APContact::getByURL($item['owner-link'], false);
604 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
605 if ($author['type'] != 'Group') {
606 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
607 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
613 * Store tags and mentions into the tag table
615 * @param integer $uriid
618 private static function storeTags(int $uriid, array $tags = null)
620 foreach ($tags as $tag) {
621 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
625 $hash = substr($tag['name'], 0, 1);
627 if ($tag['type'] == 'Mention') {
628 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
629 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
630 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
631 $tag['name'] = substr($tag['name'], 1);
633 $type = Tag::IMPLICIT_MENTION;
635 if (!empty($tag['href'])) {
636 $apcontact = APContact::getByURL($tag['href']);
637 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
638 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
641 } elseif ($tag['type'] == 'Hashtag') {
642 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
643 $tag['name'] = substr($tag['name'], 1);
645 $type = Tag::HASHTAG;
648 if (empty($tag['name'])) {
652 Tag::store($uriid, $type, $tag['name'], $tag['href']);
657 * Creates an mail post
659 * @param array $activity Activity data
660 * @param array $item item array
661 * @return int|bool New mail table row id or false on error
662 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
664 private static function postMail($activity, $item)
666 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
667 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
671 Logger::info('Direct Message', $item);
674 $msg['uid'] = $item['uid'];
676 $msg['contact-id'] = $item['contact-id'];
678 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
679 $msg['from-name'] = $contact['name'];
680 $msg['from-url'] = $contact['url'];
681 $msg['from-photo'] = $contact['photo'];
683 $msg['uri'] = $item['uri'];
684 $msg['created'] = $item['created'];
686 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
687 if (DBA::isResult($parent)) {
688 $msg['parent-uri'] = $parent['parent-uri'];
689 $msg['title'] = $parent['title'];
691 $msg['parent-uri'] = $item['thr-parent'];
693 if (!empty($item['title'])) {
694 $msg['title'] = $item['title'];
695 } elseif (!empty($item['content-warning'])) {
696 $msg['title'] = $item['content-warning'];
698 // Trying to generate a title out of the body
699 $title = $item['body'];
701 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
702 $title = $matches[3];
705 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, BBCode::API, true), 0));
707 if (strlen($title) > 20) {
708 $title = substr($title, 0, 20) . '...';
711 $msg['title'] = $title;
714 $msg['body'] = $item['body'];
716 return Mail::insert($msg);
720 * Fetches missing posts
722 * @param string $url message URL
723 * @param array $child activity array with the child of this message
724 * @return string fetched message URL
725 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
727 public static function fetchMissingActivity(string $url, array $child = [])
729 if (!empty($child['receiver'])) {
730 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
735 $object = ActivityPub::fetchContent($url, $uid);
736 if (empty($object)) {
737 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
741 if (empty($object['id'])) {
742 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
746 if (!empty($child['author'])) {
747 $actor = $child['author'];
748 } elseif (!empty($object['actor'])) {
749 $actor = $object['actor'];
750 } elseif (!empty($object['attributedTo'])) {
751 $actor = $object['attributedTo'];
757 if (!empty($object['published'])) {
758 $published = $object['published'];
759 } elseif (!empty($child['published'])) {
760 $published = $child['published'];
762 $published = DateTimeFormat::utcNow();
766 $activity['@context'] = $object['@context'];
767 unset($object['@context']);
768 $activity['id'] = $object['id'];
769 $activity['to'] = $object['to'] ?? [];
770 $activity['cc'] = $object['cc'] ?? [];
771 $activity['actor'] = $actor;
772 $activity['object'] = $object;
773 $activity['published'] = $published;
774 $activity['type'] = 'Create';
776 $ldactivity = JsonLD::compact($activity);
778 $ldactivity['thread-completion'] = true;
780 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, [$actor]);
782 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
784 return $activity['id'];
788 * perform a "follow" request
790 * @param array $activity
791 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
792 * @throws \ImagickException
794 public static function followUser($activity)
796 $uid = User::getIdForURL($activity['object_id']);
801 $owner = User::getOwnerDataById($uid);
806 $cid = Contact::getIdForURL($activity['actor'], $uid);
808 self::switchContact($cid);
809 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
810 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
815 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
816 'author-link' => $activity['actor']];
818 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
820 // Ensure that the contact has got the right network type
821 self::switchContact($item['author-id']);
823 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
824 if ($result === true) {
825 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
828 $cid = Contact::getIdForURL($activity['actor'], $uid);
833 if (empty($contact)) {
834 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
837 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
841 * Update the given profile
843 * @param array $activity
846 public static function updatePerson($activity)
848 if (empty($activity['object_id'])) {
852 Logger::info('Updating profile', ['object' => $activity['object_id']]);
853 Contact::updateFromProbeByURL($activity['object_id']);
857 * Delete the given profile
859 * @param array $activity
860 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
862 public static function deletePerson($activity)
864 if (empty($activity['object_id']) || empty($activity['actor'])) {
865 Logger::info('Empty object id or actor.');
869 if ($activity['object_id'] != $activity['actor']) {
870 Logger::info('Object id does not match actor.');
874 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
875 while ($contact = DBA::fetch($contacts)) {
876 Contact::remove($contact['id']);
878 DBA::close($contacts);
880 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
884 * Accept a follow request
886 * @param array $activity
887 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
888 * @throws \ImagickException
890 public static function acceptFollowUser($activity)
892 $uid = User::getIdForURL($activity['object_actor']);
897 $cid = Contact::getIdForURL($activity['actor'], $uid);
899 Logger::info('No contact found', ['actor' => $activity['actor']]);
903 self::switchContact($cid);
905 $fields = ['pending' => false];
907 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
908 if ($contact['rel'] == Contact::FOLLOWER) {
909 $fields['rel'] = Contact::FRIEND;
912 $condition = ['id' => $cid];
913 DBA::update('contact', $fields, $condition);
914 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
918 * Reject a follow request
920 * @param array $activity
921 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
922 * @throws \ImagickException
924 public static function rejectFollowUser($activity)
926 $uid = User::getIdForURL($activity['object_actor']);
931 $cid = Contact::getIdForURL($activity['actor'], $uid);
933 Logger::info('No contact found', ['actor' => $activity['actor']]);
937 self::switchContact($cid);
939 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
940 Contact::remove($cid);
941 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
943 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
948 * Undo activity like "like" or "dislike"
950 * @param array $activity
951 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
952 * @throws \ImagickException
954 public static function undoActivity($activity)
956 if (empty($activity['object_id'])) {
960 if (empty($activity['object_actor'])) {
964 $author_id = Contact::getIdForURL($activity['object_actor']);
965 if (empty($author_id)) {
969 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
973 * Activity to remove a follower
975 * @param array $activity
976 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
977 * @throws \ImagickException
979 public static function undoFollowUser($activity)
981 $uid = User::getIdForURL($activity['object_object']);
986 $owner = User::getOwnerDataById($uid);
991 $cid = Contact::getIdForURL($activity['actor'], $uid);
993 Logger::info('No contact found', ['actor' => $activity['actor']]);
997 self::switchContact($cid);
999 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1000 if (!DBA::isResult($contact)) {
1004 Contact::removeFollower($owner, $contact);
1005 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1009 * Switches a contact to AP if needed
1011 * @param integer $cid Contact ID
1012 * @throws \Exception
1014 private static function switchContact($cid)
1016 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1017 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1021 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1022 Contact::updateFromProbe($cid);
1026 * Collects implicit mentions like:
1027 * - the author of the parent item
1028 * - all the mentioned conversants in the parent item
1030 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1032 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1034 private static function getImplicitMentionList(array $parent)
1036 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1038 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1040 $implicit_mentions = [];
1041 if (empty($parent_author['url'])) {
1042 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
1044 $implicit_mentions[] = $parent_author['url'];
1045 $implicit_mentions[] = $parent_author['nurl'];
1046 $implicit_mentions[] = $parent_author['alias'];
1049 if (!empty($parent['alias'])) {
1050 $implicit_mentions[] = $parent['alias'];
1053 foreach ($parent_terms as $term) {
1054 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1055 if (!empty($contact['url'])) {
1056 $implicit_mentions[] = $contact['url'];
1057 $implicit_mentions[] = $contact['nurl'];
1058 $implicit_mentions[] = $contact['alias'];
1062 return $implicit_mentions;
1066 * Strips from the body prepended implicit mentions
1068 * @param string $body
1069 * @param array $parent
1072 private static function removeImplicitMentionsFromBody(string $body, array $parent)
1074 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1078 $potential_mentions = self::getImplicitMentionList($parent);
1080 $kept_mentions = [];
1082 // Extract one prepended mention at a time from the body
1083 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1084 if (!in_array($matches[2], $potential_mentions)) {
1085 $kept_mentions[] = $matches[1];
1088 $body = $matches[3];
1091 // Re-appending the kept mentions to the body after extraction
1092 $kept_mentions[] = $body;
1094 return implode('', $kept_mentions);