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\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Database\DBA;
30 use Friendica\Model\APContact;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Conversation;
33 use Friendica\Model\Event;
34 use Friendica\Model\Item;
35 use Friendica\Model\ItemURI;
36 use Friendica\Model\Mail;
37 use Friendica\Model\Tag;
38 use Friendica\Model\User;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\JsonLD;
43 use Friendica\Util\Strings;
46 * ActivityPub Processor Protocol class
51 * Converts mentions from Pleroma into the Friendica format
55 * @return string converted body
57 private static function convertMentions($body)
59 $URLSearchString = "^\[\]";
60 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
66 * Replaces emojis in the body
68 * @param array $emojis
71 * @return string with replaced emojis
73 private static function replaceEmojis($body, array $emojis)
75 foreach ($emojis as $emoji) {
76 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
77 $body = str_replace($emoji['name'], $replace, $body);
83 * Add attachment data to the item array
85 * @param array $activity
90 private static function constructAttachList($activity, $item)
92 if (empty($activity['attachments'])) {
96 foreach ($activity['attachments'] as $attach) {
97 switch ($attach['type']) {
99 // Only one [attachment] tag is allowed
100 $existingAttachmentPos = strpos($item['body'], '[attachment');
101 if ($existingAttachmentPos !== false) {
102 $linkTitle = $attach['title'] ?: $attach['url'];
103 // Additional link attachments are prepended before the existing [attachment] tag
104 $item['body'] = substr_replace($item['body'], "\n[bookmark=" . $attach['url'] . ']' . $linkTitle . "[/bookmark]\n", $existingAttachmentPos, 0);
106 // Strip the link preview URL from the end of the body if any
107 $quotedUrl = preg_quote($attach['url'], '#');
108 $item['body'] = preg_replace("#\s*(?:\[bookmark={$quotedUrl}].+?\[/bookmark]|\[url={$quotedUrl}].+?\[/url]|\[url]{$quotedUrl}\[/url]|{$quotedUrl})\s*$#", '', $item['body']);
109 $item['body'] .= "\n[attachment type='link' url='" . $attach['url'] . "' title='" . htmlspecialchars($attach['title'] ?? '', ENT_QUOTES) . "' image='" . ($attach['image'] ?? '') . "']" . ($attach['desc'] ?? '') . '[/attachment]';
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 if (empty($attach['name'])) {
120 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
122 $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
124 } elseif ($filetype == 'audio') {
125 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
129 $item['body'] .= "\n[audio]" . $attach['url'] . '[/audio]';
130 } elseif ($filetype == 'video') {
131 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
135 $item['body'] .= "\n[video]" . $attach['url'] . '[/video]';
137 if (!empty($item["attach"])) {
138 $item["attach"] .= ',';
140 $item["attach"] = '';
143 $item["attach"] .= '[attach]href="' . $attach['url'] . '" length="' . ($attach['length'] ?? '0') . '" type="' . $attach['mediaType'] . '" title="' . ($attach['name'] ?? '') . '"[/attach]';
154 * @param array $activity Activity array
155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
157 public static function updateItem($activity)
159 $item = Item::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
160 if (!DBA::isResult($item)) {
161 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
162 self::createItem($activity);
166 $item['changed'] = DateTimeFormat::utcNow();
167 $item['edited'] = DateTimeFormat::utc($activity['updated']);
169 $item = self::processContent($activity, $item);
174 Item::update($item, ['uri' => $activity['id']]);
178 * Prepares data for a message
180 * @param array $activity Activity array
181 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
182 * @throws \ImagickException
184 public static function createItem($activity)
187 $item['verb'] = Activity::POST;
188 $item['thr-parent'] = $activity['reply-to-id'];
190 if ($activity['reply-to-id'] == $activity['id']) {
191 $item['gravity'] = GRAVITY_PARENT;
192 $item['object-type'] = Activity\ObjectType::NOTE;
194 $item['gravity'] = GRAVITY_COMMENT;
195 $item['object-type'] = Activity\ObjectType::COMMENT;
197 // Ensure that the comment reaches all receivers of the referring post
198 $activity['receiver'] = self::addReceivers($activity);
201 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
202 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
203 self::fetchMissingActivity($activity['reply-to-id'], $activity);
206 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
208 self::postItem($activity, $item);
214 * @param array $activity
215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216 * @throws \ImagickException
218 public static function deleteItem($activity)
220 $owner = Contact::getIdForURL($activity['actor']);
222 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
223 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
227 * Prepare the item array for an activity
229 * @param array $activity Activity array
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 * @throws \ImagickException
233 public static function addTag($activity)
235 if (empty($activity['object_content']) || empty($activity['object_id'])) {
239 foreach ($activity['receiver'] as $receiver) {
240 $item = Item::selectFirst(['id', 'uri-id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
241 if (!DBA::isResult($item)) {
242 // We don't fetch missing content for this purpose
246 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
247 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
251 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
252 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
257 * Add users to the receiver list of the given public activity.
258 * This is used to ensure that the activity will be stored in every thread.
260 * @param array $activity Activity array
261 * @return array Modified receiver list
263 private static function addReceivers(array $activity)
265 if (!in_array(0, $activity['receiver'])) {
266 // Private activities will not be modified
267 return $activity['receiver'];
270 // Add all owners of the referring item to the receivers
271 $original = $receivers = $activity['receiver'];
272 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
273 while ($item = DBA::fetch($items)) {
274 $receivers['uid:' . $item['uid']] = $item['uid'];
278 if (count($original) != count($receivers)) {
279 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
286 * Prepare the item array for an activity
288 * @param array $activity Activity array
289 * @param string $verb Activity verb
290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
291 * @throws \ImagickException
293 public static function createActivity($activity, $verb)
296 $item['verb'] = $verb;
297 $item['thr-parent'] = $activity['object_id'];
298 $item['gravity'] = GRAVITY_ACTIVITY;
299 $item['object-type'] = Activity\ObjectType::NOTE;
301 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
303 $activity['receiver'] = self::addReceivers($activity);
305 self::postItem($activity, $item);
311 * @param array $activity Activity array
315 public static function createEvent($activity, $item)
317 $event['summary'] = HTML::toBBCode($activity['name']);
318 $event['desc'] = HTML::toBBCode($activity['content']);
319 $event['start'] = $activity['start-time'];
320 $event['finish'] = $activity['end-time'];
321 $event['nofinish'] = empty($event['finish']);
322 $event['location'] = $activity['location'];
323 $event['adjust'] = true;
324 $event['cid'] = $item['contact-id'];
325 $event['uid'] = $item['uid'];
326 $event['uri'] = $item['uri'];
327 $event['edited'] = $item['edited'];
328 $event['private'] = $item['private'];
329 $event['guid'] = $item['guid'];
330 $event['plink'] = $item['plink'];
332 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
333 $ev = DBA::selectFirst('event', ['id'], $condition);
334 if (DBA::isResult($ev)) {
335 $event['id'] = $ev['id'];
338 $event_id = Event::store($event);
339 Logger::info('Event was stored', ['id' => $event_id]);
343 * Process the content
345 * @param array $activity Activity array
347 * @return array|bool Returns the item array or false if there was an unexpected occurrence
350 private static function processContent($activity, $item)
352 $item['title'] = HTML::toBBCode($activity['name']);
354 if (!empty($activity['source'])) {
355 $item['body'] = $activity['source'];
357 $content = HTML::toBBCode($activity['content']);
359 if (!empty($activity['emojis'])) {
360 $content = self::replaceEmojis($content, $activity['emojis']);
363 $content = self::convertMentions($content);
365 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
366 $item_private = !in_array(0, $activity['item_receiver']);
367 $parent = Item::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
368 if (!DBA::isResult($parent)) {
369 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
372 if ($item_private && ($parent['private'] != Item::PRIVATE)) {
373 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
377 $content = self::removeImplicitMentionsFromBody($content, $parent);
379 $item['content-warning'] = HTML::toBBCode($activity['summary']);
380 $item['body'] = $content;
383 self::storeFromBody($item);
384 self::storeTags($item['uri-id'], $activity['tags']);
386 $item['location'] = $activity['location'];
388 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
389 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
392 $item['app'] = $activity['generator'];
398 * Store hashtags and mentions
402 private static function storeFromBody(array $item)
404 // Make sure to delete all existing tags (can happen when called via the update functionality)
405 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
407 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
411 * Generate a GUID out of an URL
413 * @param string $url message URL
414 * @return string with GUID
416 private static function getGUIDByURL(string $url)
418 $parsed = parse_url($url);
420 $host_hash = hash('crc32', $parsed['host']);
422 unset($parsed["scheme"]);
423 unset($parsed["host"]);
425 $path = implode("/", $parsed);
427 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
431 * Creates an item post
433 * @param array $activity Activity data
434 * @param array $item item array
435 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
436 * @throws \ImagickException
438 private static function postItem($activity, $item)
440 /// @todo What to do with $activity['context']?
441 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
442 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
446 $item['network'] = Protocol::ACTIVITYPUB;
447 $item['author-link'] = $activity['author'];
448 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
449 $item['owner-link'] = $activity['actor'];
450 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
452 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
453 $item['private'] = Item::UNLISTED;
454 } elseif (in_array(0, $activity['receiver'])) {
455 $item['private'] = Item::PUBLIC;
457 $item['private'] = Item::PRIVATE;
460 if (!empty($activity['raw'])) {
461 $item['source'] = $activity['raw'];
462 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
463 $item['conversation-href'] = $activity['context'] ?? '';
464 $item['conversation-uri'] = $activity['conversation'] ?? '';
466 if (isset($activity['push'])) {
467 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
473 if (!empty($activity['thread-completion'])) {
474 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
475 $item['causer-link'] = $item['owner-link'];
476 $item['causer-id'] = $item['owner-id'];
478 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
479 $item['owner-link'] = $item['author-link'];
480 $item['owner-id'] = $item['author-id'];
482 $actor = APContact::getByURL($item['owner-link'], false);
483 $isForum = ($actor['type'] == 'Group');
486 $item['uri'] = $activity['id'];
488 $item['created'] = DateTimeFormat::utc($activity['published']);
489 $item['edited'] = DateTimeFormat::utc($activity['updated']);
490 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
491 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
493 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
495 $item = self::processContent($activity, $item);
500 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
502 $item = self::constructAttachList($activity, $item);
506 foreach ($activity['receiver'] as $receiver) {
507 if ($receiver == -1) {
511 $item['uid'] = $receiver;
514 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
516 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
519 if (($receiver != 0) && empty($item['contact-id'])) {
520 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
523 if (!empty($activity['directmessage'])) {
524 self::postMail($activity, $item);
528 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
529 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
531 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
532 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
536 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
540 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
543 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
544 self::createEvent($activity, $item);
547 $item_id = Item::insert($item);
549 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
551 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
554 if ($item['uid'] == 0) {
559 // Store send a follow request for every reshare - but only when the item had been stored
560 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
561 $author = APContact::getByURL($item['owner-link'], false);
562 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
563 if ($author['type'] != 'Group') {
564 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
565 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
571 * Store tags and mentions into the tag table
573 * @param integer $uriid
576 private static function storeTags(int $uriid, array $tags = null)
578 foreach ($tags as $tag) {
579 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
583 $hash = substr($tag['name'], 0, 1);
585 if ($tag['type'] == 'Mention') {
586 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
587 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
588 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
589 $tag['name'] = substr($tag['name'], 1);
591 $type = Tag::IMPLICIT_MENTION;
593 if (!empty($tag['href'])) {
594 $apcontact = APContact::getByURL($tag['href']);
595 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
596 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
599 } elseif ($tag['type'] == 'Hashtag') {
600 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
601 $tag['name'] = substr($tag['name'], 1);
603 $type = Tag::HASHTAG;
606 if (empty($tag['name'])) {
610 Tag::store($uriid, $type, $tag['name'], $tag['href']);
615 * Creates an mail post
617 * @param array $activity Activity data
618 * @param array $item item array
619 * @return int|bool New mail table row id or false on error
620 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
622 private static function postMail($activity, $item)
624 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
625 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
629 Logger::info('Direct Message', $item);
632 $msg['uid'] = $item['uid'];
634 $msg['contact-id'] = $item['contact-id'];
636 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
637 $msg['from-name'] = $contact['name'];
638 $msg['from-url'] = $contact['url'];
639 $msg['from-photo'] = $contact['photo'];
641 $msg['uri'] = $item['uri'];
642 $msg['created'] = $item['created'];
644 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
645 if (DBA::isResult($parent)) {
646 $msg['parent-uri'] = $parent['parent-uri'];
647 $msg['title'] = $parent['title'];
649 $msg['parent-uri'] = $item['thr-parent'];
651 if (!empty($item['title'])) {
652 $msg['title'] = $item['title'];
653 } elseif (!empty($item['content-warning'])) {
654 $msg['title'] = $item['content-warning'];
656 // Trying to generate a title out of the body
657 $title = $item['body'];
659 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
660 $title = $matches[3];
663 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, BBCode::API, true), 0));
665 if (strlen($title) > 20) {
666 $title = substr($title, 0, 20) . '...';
669 $msg['title'] = $title;
672 $msg['body'] = $item['body'];
674 return Mail::insert($msg);
678 * Fetches missing posts
680 * @param string $url message URL
681 * @param array $child activity array with the child of this message
682 * @return string fetched message URL
683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
685 public static function fetchMissingActivity($url, $child = [])
687 if (!empty($child['receiver'])) {
688 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
693 $object = ActivityPub::fetchContent($url, $uid);
694 if (empty($object)) {
695 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
699 if (empty($object['id'])) {
700 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
704 if (!empty($child['author'])) {
705 $actor = $child['author'];
706 } elseif (!empty($object['actor'])) {
707 $actor = $object['actor'];
708 } elseif (!empty($object['attributedTo'])) {
709 $actor = $object['attributedTo'];
715 if (!empty($object['published'])) {
716 $published = $object['published'];
717 } elseif (!empty($child['published'])) {
718 $published = $child['published'];
720 $published = DateTimeFormat::utcNow();
724 $activity['@context'] = $object['@context'];
725 unset($object['@context']);
726 $activity['id'] = $object['id'];
727 $activity['to'] = $object['to'] ?? [];
728 $activity['cc'] = $object['cc'] ?? [];
729 $activity['actor'] = $actor;
730 $activity['object'] = $object;
731 $activity['published'] = $published;
732 $activity['type'] = 'Create';
734 $ldactivity = JsonLD::compact($activity);
736 $ldactivity['thread-completion'] = true;
738 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity));
740 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
742 return $activity['id'];
746 * perform a "follow" request
748 * @param array $activity
749 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
750 * @throws \ImagickException
752 public static function followUser($activity)
754 $uid = User::getIdForURL($activity['object_id']);
759 $owner = User::getOwnerDataById($uid);
761 $cid = Contact::getIdForURL($activity['actor'], $uid);
763 self::switchContact($cid);
764 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
765 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
770 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
771 'author-link' => $activity['actor']];
773 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
775 // Ensure that the contact has got the right network type
776 self::switchContact($item['author-id']);
778 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
779 if ($result === true) {
780 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
783 $cid = Contact::getIdForURL($activity['actor'], $uid);
788 if (empty($contact)) {
789 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
792 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
796 * Update the given profile
798 * @param array $activity
801 public static function updatePerson($activity)
803 if (empty($activity['object_id'])) {
807 Logger::info('Updating profile', ['object' => $activity['object_id']]);
808 Contact::updateFromProbeByURL($activity['object_id'], true);
812 * Delete the given profile
814 * @param array $activity
815 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
817 public static function deletePerson($activity)
819 if (empty($activity['object_id']) || empty($activity['actor'])) {
820 Logger::info('Empty object id or actor.');
824 if ($activity['object_id'] != $activity['actor']) {
825 Logger::info('Object id does not match actor.');
829 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
830 while ($contact = DBA::fetch($contacts)) {
831 Contact::remove($contact['id']);
833 DBA::close($contacts);
835 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
839 * Accept a follow request
841 * @param array $activity
842 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
843 * @throws \ImagickException
845 public static function acceptFollowUser($activity)
847 $uid = User::getIdForURL($activity['object_actor']);
852 $cid = Contact::getIdForURL($activity['actor'], $uid);
854 Logger::info('No contact found', ['actor' => $activity['actor']]);
858 self::switchContact($cid);
860 $fields = ['pending' => false];
862 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
863 if ($contact['rel'] == Contact::FOLLOWER) {
864 $fields['rel'] = Contact::FRIEND;
867 $condition = ['id' => $cid];
868 DBA::update('contact', $fields, $condition);
869 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
873 * Reject a follow request
875 * @param array $activity
876 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
877 * @throws \ImagickException
879 public static function rejectFollowUser($activity)
881 $uid = User::getIdForURL($activity['object_actor']);
886 $cid = Contact::getIdForURL($activity['actor'], $uid);
888 Logger::info('No contact found', ['actor' => $activity['actor']]);
892 self::switchContact($cid);
894 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
895 Contact::remove($cid);
896 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
898 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
903 * Undo activity like "like" or "dislike"
905 * @param array $activity
906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
907 * @throws \ImagickException
909 public static function undoActivity($activity)
911 if (empty($activity['object_id'])) {
915 if (empty($activity['object_actor'])) {
919 $author_id = Contact::getIdForURL($activity['object_actor']);
920 if (empty($author_id)) {
924 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
928 * Activity to remove a follower
930 * @param array $activity
931 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932 * @throws \ImagickException
934 public static function undoFollowUser($activity)
936 $uid = User::getIdForURL($activity['object_object']);
941 $owner = User::getOwnerDataById($uid);
943 $cid = Contact::getIdForURL($activity['actor'], $uid);
945 Logger::info('No contact found', ['actor' => $activity['actor']]);
949 self::switchContact($cid);
951 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
952 if (!DBA::isResult($contact)) {
956 Contact::removeFollower($owner, $contact);
957 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
961 * Switches a contact to AP if needed
963 * @param integer $cid Contact ID
966 private static function switchContact($cid)
968 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
969 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
973 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
974 Contact::updateFromProbe($cid);
978 * Collects implicit mentions like:
979 * - the author of the parent item
980 * - all the mentioned conversants in the parent item
982 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
984 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
986 private static function getImplicitMentionList(array $parent)
988 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
990 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
992 $implicit_mentions = [];
993 if (empty($parent_author['url'])) {
994 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
996 $implicit_mentions[] = $parent_author['url'];
997 $implicit_mentions[] = $parent_author['nurl'];
998 $implicit_mentions[] = $parent_author['alias'];
1001 if (!empty($parent['alias'])) {
1002 $implicit_mentions[] = $parent['alias'];
1005 foreach ($parent_terms as $term) {
1006 $contact = Contact::getDetailsByURL($term['url'], 0);
1007 if (!empty($contact['url'])) {
1008 $implicit_mentions[] = $contact['url'];
1009 $implicit_mentions[] = $contact['nurl'];
1010 $implicit_mentions[] = $contact['alias'];
1014 return $implicit_mentions;
1018 * Strips from the body prepended implicit mentions
1020 * @param string $body
1021 * @param array $parent
1024 private static function removeImplicitMentionsFromBody(string $body, array $parent)
1026 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1030 $potential_mentions = self::getImplicitMentionList($parent);
1032 $kept_mentions = [];
1034 // Extract one prepended mention at a time from the body
1035 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1036 if (!in_array($matches[2], $potential_mentions)) {
1037 $kept_mentions[] = $matches[1];
1040 $body = $matches[3];
1043 // Re-appending the kept mentions to the body after extraction
1044 $kept_mentions[] = $body;
1046 return implode('', $kept_mentions);