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\Database\DBA;
31 use Friendica\Model\APContact;
32 use Friendica\Model\Contact;
33 use Friendica\Model\Conversation;
34 use Friendica\Model\Event;
35 use Friendica\Model\Item;
36 use Friendica\Model\ItemURI;
37 use Friendica\Model\Mail;
38 use Friendica\Model\Tag;
39 use Friendica\Model\User;
40 use Friendica\Protocol\Activity;
41 use Friendica\Protocol\ActivityPub;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\JsonLD;
44 use Friendica\Util\Strings;
47 * ActivityPub Processor Protocol class
52 * Converts mentions from Pleroma into the Friendica format
56 * @return string converted body
58 private static function convertMentions($body)
60 $URLSearchString = "^\[\]";
61 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
67 * Replaces emojis in the body
69 * @param array $emojis
72 * @return string with replaced emojis
74 private static function replaceEmojis($body, array $emojis)
76 foreach ($emojis as $emoji) {
77 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
78 $body = str_replace($emoji['name'], $replace, $body);
84 * Add attachment data to the item array
86 * @param array $activity
91 private static function constructAttachList($activity, $item)
93 if (empty($activity['attachments'])) {
97 foreach ($activity['attachments'] as $attach) {
98 switch ($attach['type']) {
101 'url' => $attach['url'],
102 'type' => $attach['type'],
103 'title' => $attach['title'] ?? '',
104 'text' => $attach['desc'] ?? '',
105 'image' => $attach['image'] ?? '',
109 $item['body'] = PageInfo::appendDataToBody($item['body'], $data);
112 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
113 if ($filetype == 'image') {
114 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
118 $item['body'] .= "\n";
120 // image is the preview/thumbnail URL
121 if (!empty($attach['image'])) {
122 $item['body'] .= '[url=' . $attach['url'] . ']';
123 $attach['url'] = $attach['image'];
126 if (empty($attach['name'])) {
127 $item['body'] .= '[img]' . $attach['url'] . '[/img]';
129 $item['body'] .= '[img=' . $attach['url'] . ']' . $attach['name'] . '[/img]';
132 if (!empty($attach['image'])) {
133 $item['body'] .= '[/url]';
135 } elseif ($filetype == 'audio') {
136 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
140 $item['body'] .= "\n[audio]" . $attach['url'] . '[/audio]';
141 } elseif ($filetype == 'video') {
142 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
146 $item['body'] .= "\n[video]" . $attach['url'] . '[/video]';
148 if (!empty($item["attach"])) {
149 $item["attach"] .= ',';
151 $item["attach"] = '';
154 $item["attach"] .= '[attach]href="' . $attach['url'] . '" length="' . ($attach['length'] ?? '0') . '" type="' . $attach['mediaType'] . '" title="' . ($attach['name'] ?? '') . '"[/attach]';
165 * @param array $activity Activity array
166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
168 public static function updateItem($activity)
170 $item = Item::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
171 if (!DBA::isResult($item)) {
172 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
173 $item = self::createItem($activity);
174 self::postItem($activity, $item);
178 $item['changed'] = DateTimeFormat::utcNow();
179 $item['edited'] = DateTimeFormat::utc($activity['updated']);
181 $item = self::processContent($activity, $item);
186 Item::update($item, ['uri' => $activity['id']]);
190 * Prepares data for a message
192 * @param array $activity Activity array
193 * @return array Internal item
194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
195 * @throws \ImagickException
197 public static function createItem($activity)
200 $item['verb'] = Activity::POST;
201 $item['thr-parent'] = $activity['reply-to-id'];
203 if ($activity['reply-to-id'] == $activity['id']) {
204 $item['gravity'] = GRAVITY_PARENT;
205 $item['object-type'] = Activity\ObjectType::NOTE;
207 $item['gravity'] = GRAVITY_COMMENT;
208 $item['object-type'] = Activity\ObjectType::COMMENT;
211 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
212 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
213 self::fetchMissingActivity($activity['reply-to-id'], $activity);
216 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
218 /// @todo What to do with $activity['context']?
219 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
220 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
224 $item['network'] = Protocol::ACTIVITYPUB;
225 $item['author-link'] = $activity['author'];
226 $item['author-id'] = Contact::getIdForURL($activity['author']);
227 $item['owner-link'] = $activity['actor'];
228 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
230 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
231 $item['private'] = Item::UNLISTED;
232 } elseif (in_array(0, $activity['receiver'])) {
233 $item['private'] = Item::PUBLIC;
235 $item['private'] = Item::PRIVATE;
238 if (!empty($activity['raw'])) {
239 $item['source'] = $activity['raw'];
240 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
241 $item['conversation-href'] = $activity['context'] ?? '';
242 $item['conversation-uri'] = $activity['conversation'] ?? '';
244 if (isset($activity['push'])) {
245 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
249 $item['isForum'] = false;
251 if (!empty($activity['thread-completion'])) {
252 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
253 $item['causer-link'] = $item['owner-link'];
254 $item['causer-id'] = $item['owner-id'];
256 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
257 $item['owner-link'] = $item['author-link'];
258 $item['owner-id'] = $item['author-id'];
260 $actor = APContact::getByURL($item['owner-link'], false);
261 $item['isForum'] = ($actor['type'] == 'Group');
264 $item['uri'] = $activity['id'];
266 $item['created'] = DateTimeFormat::utc($activity['published']);
267 $item['edited'] = DateTimeFormat::utc($activity['updated']);
268 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
269 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
271 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
273 $item = self::processContent($activity, $item);
275 Logger::info('Message was not processed');
279 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
281 $item = self::constructAttachList($activity, $item);
289 * @param array $activity
290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
291 * @throws \ImagickException
293 public static function deleteItem($activity)
295 $owner = Contact::getIdForURL($activity['actor']);
297 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
298 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
302 * Prepare the item array for an activity
304 * @param array $activity Activity array
305 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
306 * @throws \ImagickException
308 public static function addTag($activity)
310 if (empty($activity['object_content']) || empty($activity['object_id'])) {
314 foreach ($activity['receiver'] as $receiver) {
315 $item = Item::selectFirst(['id', 'uri-id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
316 if (!DBA::isResult($item)) {
317 // We don't fetch missing content for this purpose
321 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
322 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
326 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
327 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
332 * Prepare the item array for an activity
334 * @param array $activity Activity array
335 * @param string $verb Activity verb
336 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
337 * @throws \ImagickException
339 public static function createActivity($activity, $verb)
341 $item = self::createItem($activity);
342 $item['verb'] = $verb;
343 $item['thr-parent'] = $activity['object_id'];
344 $item['gravity'] = GRAVITY_ACTIVITY;
345 $item['object-type'] = Activity\ObjectType::NOTE;
347 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
349 self::postItem($activity, $item);
355 * @param array $activity Activity array
359 public static function createEvent($activity, $item)
361 $event['summary'] = HTML::toBBCode($activity['name']);
362 $event['desc'] = HTML::toBBCode($activity['content']);
363 $event['start'] = $activity['start-time'];
364 $event['finish'] = $activity['end-time'];
365 $event['nofinish'] = empty($event['finish']);
366 $event['location'] = $activity['location'];
367 $event['adjust'] = true;
368 $event['cid'] = $item['contact-id'];
369 $event['uid'] = $item['uid'];
370 $event['uri'] = $item['uri'];
371 $event['edited'] = $item['edited'];
372 $event['private'] = $item['private'];
373 $event['guid'] = $item['guid'];
374 $event['plink'] = $item['plink'];
376 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
377 $ev = DBA::selectFirst('event', ['id'], $condition);
378 if (DBA::isResult($ev)) {
379 $event['id'] = $ev['id'];
382 $event_id = Event::store($event);
383 Logger::info('Event was stored', ['id' => $event_id]);
387 * Process the content
389 * @param array $activity Activity array
391 * @return array|bool Returns the item array or false if there was an unexpected occurrence
394 private static function processContent($activity, $item)
396 $item['title'] = HTML::toBBCode($activity['name']);
398 if (!empty($activity['source'])) {
399 $item['body'] = $activity['source'];
401 $content = HTML::toBBCode($activity['content']);
403 if (!empty($activity['emojis'])) {
404 $content = self::replaceEmojis($content, $activity['emojis']);
407 $content = self::convertMentions($content);
409 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
410 $item_private = !in_array(0, $activity['item_receiver']);
411 $parent = Item::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
412 if (!DBA::isResult($parent)) {
413 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
416 if ($item_private && ($parent['private'] != Item::PRIVATE)) {
417 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
421 $content = self::removeImplicitMentionsFromBody($content, $parent);
423 $item['content-warning'] = HTML::toBBCode($activity['summary']);
424 $item['body'] = $content;
427 self::storeFromBody($item);
428 self::storeTags($item['uri-id'], $activity['tags']);
430 $item['location'] = $activity['location'];
432 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
433 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
436 $item['app'] = $activity['generator'];
442 * Store hashtags and mentions
446 private static function storeFromBody(array $item)
448 // Make sure to delete all existing tags (can happen when called via the update functionality)
449 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
451 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
455 * Generate a GUID out of an URL
457 * @param string $url message URL
458 * @return string with GUID
460 private static function getGUIDByURL(string $url)
462 $parsed = parse_url($url);
464 $host_hash = hash('crc32', $parsed['host']);
466 unset($parsed["scheme"]);
467 unset($parsed["host"]);
469 $path = implode("/", $parsed);
471 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
475 * Creates an item post
477 * @param array $activity Activity data
478 * @param array $item item array
479 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
480 * @throws \ImagickException
482 public static function postItem(array $activity, array $item)
490 foreach ($activity['receiver'] as $receiver) {
491 if ($receiver == -1) {
495 $item['uid'] = $receiver;
497 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
499 case Receiver::TARGET_TO:
500 $item['post-type'] = Item::PT_TO;
502 case Receiver::TARGET_CC:
503 $item['post-type'] = Item::PT_CC;
505 case Receiver::TARGET_BTO:
506 $item['post-type'] = Item::PT_BTO;
508 case Receiver::TARGET_BCC:
509 $item['post-type'] = Item::PT_BCC;
511 case Receiver::TARGET_FOLLOWER:
512 $item['post-type'] = Item::PT_FOLLOWER;
514 case Receiver::TARGET_ANSWER:
515 $item['post-type'] = Item::PT_COMMENT;
517 case Receiver::TARGET_GLOBAL:
518 $item['post-type'] = Item::PT_GLOBAL;
521 $item['post-type'] = Item::PT_ARTICLE;
524 if (in_array($item['post-type'], [Item::PT_GLOBAL, Item::PT_ARTICLE]) && !empty($activity['from-relay'])) {
525 $item['post-type'] = Item::PT_RELAY;
528 if ($item['isForum'] ?? false) {
529 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
531 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
534 if (($receiver != 0) && empty($item['contact-id'])) {
535 $item['contact-id'] = Contact::getIdForURL($activity['author']);
538 if (!empty($activity['directmessage'])) {
539 self::postMail($activity, $item);
543 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
544 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
546 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
547 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
551 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
555 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
558 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
559 self::createEvent($activity, $item);
562 $item_id = Item::insert($item);
564 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
566 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
569 if ($item['uid'] == 0) {
574 // Store send a follow request for every reshare - but only when the item had been stored
575 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
576 $author = APContact::getByURL($item['owner-link'], false);
577 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
578 if ($author['type'] != 'Group') {
579 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
580 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
586 * Store tags and mentions into the tag table
588 * @param integer $uriid
591 private static function storeTags(int $uriid, array $tags = null)
593 foreach ($tags as $tag) {
594 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
598 $hash = substr($tag['name'], 0, 1);
600 if ($tag['type'] == 'Mention') {
601 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
602 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
603 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
604 $tag['name'] = substr($tag['name'], 1);
606 $type = Tag::IMPLICIT_MENTION;
608 if (!empty($tag['href'])) {
609 $apcontact = APContact::getByURL($tag['href']);
610 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
611 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
614 } elseif ($tag['type'] == 'Hashtag') {
615 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
616 $tag['name'] = substr($tag['name'], 1);
618 $type = Tag::HASHTAG;
621 if (empty($tag['name'])) {
625 Tag::store($uriid, $type, $tag['name'], $tag['href']);
630 * Creates an mail post
632 * @param array $activity Activity data
633 * @param array $item item array
634 * @return int|bool New mail table row id or false on error
635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 private static function postMail($activity, $item)
639 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
640 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
644 Logger::info('Direct Message', $item);
647 $msg['uid'] = $item['uid'];
649 $msg['contact-id'] = $item['contact-id'];
651 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
652 $msg['from-name'] = $contact['name'];
653 $msg['from-url'] = $contact['url'];
654 $msg['from-photo'] = $contact['photo'];
656 $msg['uri'] = $item['uri'];
657 $msg['created'] = $item['created'];
659 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
660 if (DBA::isResult($parent)) {
661 $msg['parent-uri'] = $parent['parent-uri'];
662 $msg['title'] = $parent['title'];
664 $msg['parent-uri'] = $item['thr-parent'];
666 if (!empty($item['title'])) {
667 $msg['title'] = $item['title'];
668 } elseif (!empty($item['content-warning'])) {
669 $msg['title'] = $item['content-warning'];
671 // Trying to generate a title out of the body
672 $title = $item['body'];
674 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
675 $title = $matches[3];
678 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, BBCode::API, true), 0));
680 if (strlen($title) > 20) {
681 $title = substr($title, 0, 20) . '...';
684 $msg['title'] = $title;
687 $msg['body'] = $item['body'];
689 return Mail::insert($msg);
693 * Fetches missing posts
695 * @param string $url message URL
696 * @param array $child activity array with the child of this message
697 * @param bool $relaymode Posts arrived via relay
698 * @return string fetched message URL
699 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
701 public static function fetchMissingActivity(string $url, array $child = [], bool $relaymode = false)
703 if (!empty($child['receiver'])) {
704 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
709 $object = ActivityPub::fetchContent($url, $uid);
710 if (empty($object)) {
711 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
715 if (empty($object['id'])) {
716 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
720 if (!empty($object['actor'])) {
721 $object_actor = $object['actor'];
722 } elseif (!empty($object['attributedTo'])) {
723 $object_actor = $object['attributedTo'];
729 $signer = [$object_actor];
731 if (!empty($child['author'])) {
732 $actor = $child['author'];
735 $actor = $object_actor;
738 if (!empty($object['published'])) {
739 $published = $object['published'];
740 } elseif (!empty($child['published'])) {
741 $published = $child['published'];
743 $published = DateTimeFormat::utcNow();
747 $activity['@context'] = $object['@context'];
748 unset($object['@context']);
749 $activity['id'] = $object['id'];
750 $activity['to'] = $object['to'] ?? [];
751 $activity['cc'] = $object['cc'] ?? [];
752 $activity['actor'] = $actor;
753 $activity['object'] = $object;
754 $activity['published'] = $published;
755 $activity['type'] = 'Create';
757 $ldactivity = JsonLD::compact($activity);
759 $ldactivity['thread-completion'] = true;
760 $ldactivity['from-relay'] = $relaymode;
762 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
764 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
766 return $activity['id'];
770 * perform a "follow" request
772 * @param array $activity
773 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
774 * @throws \ImagickException
776 public static function followUser($activity)
778 $uid = User::getIdForURL($activity['object_id']);
783 $owner = User::getOwnerDataById($uid);
788 $cid = Contact::getIdForURL($activity['actor'], $uid);
790 self::switchContact($cid);
791 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
792 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
797 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
798 'author-link' => $activity['actor']];
800 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
802 // Ensure that the contact has got the right network type
803 self::switchContact($item['author-id']);
805 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
806 if ($result === true) {
807 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
810 $cid = Contact::getIdForURL($activity['actor'], $uid);
815 if (empty($contact)) {
816 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
819 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
823 * Update the given profile
825 * @param array $activity
828 public static function updatePerson($activity)
830 if (empty($activity['object_id'])) {
834 Logger::info('Updating profile', ['object' => $activity['object_id']]);
835 Contact::updateFromProbeByURL($activity['object_id']);
839 * Delete the given profile
841 * @param array $activity
842 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
844 public static function deletePerson($activity)
846 if (empty($activity['object_id']) || empty($activity['actor'])) {
847 Logger::info('Empty object id or actor.');
851 if ($activity['object_id'] != $activity['actor']) {
852 Logger::info('Object id does not match actor.');
856 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
857 while ($contact = DBA::fetch($contacts)) {
858 Contact::remove($contact['id']);
860 DBA::close($contacts);
862 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
866 * Accept a follow request
868 * @param array $activity
869 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
870 * @throws \ImagickException
872 public static function acceptFollowUser($activity)
874 $uid = User::getIdForURL($activity['object_actor']);
879 $cid = Contact::getIdForURL($activity['actor'], $uid);
881 Logger::info('No contact found', ['actor' => $activity['actor']]);
885 self::switchContact($cid);
887 $fields = ['pending' => false];
889 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
890 if ($contact['rel'] == Contact::FOLLOWER) {
891 $fields['rel'] = Contact::FRIEND;
894 $condition = ['id' => $cid];
895 DBA::update('contact', $fields, $condition);
896 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
900 * Reject a follow request
902 * @param array $activity
903 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
904 * @throws \ImagickException
906 public static function rejectFollowUser($activity)
908 $uid = User::getIdForURL($activity['object_actor']);
913 $cid = Contact::getIdForURL($activity['actor'], $uid);
915 Logger::info('No contact found', ['actor' => $activity['actor']]);
919 self::switchContact($cid);
921 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
922 Contact::remove($cid);
923 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
925 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
930 * Undo activity like "like" or "dislike"
932 * @param array $activity
933 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
934 * @throws \ImagickException
936 public static function undoActivity($activity)
938 if (empty($activity['object_id'])) {
942 if (empty($activity['object_actor'])) {
946 $author_id = Contact::getIdForURL($activity['object_actor']);
947 if (empty($author_id)) {
951 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
955 * Activity to remove a follower
957 * @param array $activity
958 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
959 * @throws \ImagickException
961 public static function undoFollowUser($activity)
963 $uid = User::getIdForURL($activity['object_object']);
968 $owner = User::getOwnerDataById($uid);
973 $cid = Contact::getIdForURL($activity['actor'], $uid);
975 Logger::info('No contact found', ['actor' => $activity['actor']]);
979 self::switchContact($cid);
981 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
982 if (!DBA::isResult($contact)) {
986 Contact::removeFollower($owner, $contact);
987 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
991 * Switches a contact to AP if needed
993 * @param integer $cid Contact ID
996 private static function switchContact($cid)
998 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
999 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1003 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1004 Contact::updateFromProbe($cid);
1008 * Collects implicit mentions like:
1009 * - the author of the parent item
1010 * - all the mentioned conversants in the parent item
1012 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1014 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1016 private static function getImplicitMentionList(array $parent)
1018 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1020 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1022 $implicit_mentions = [];
1023 if (empty($parent_author['url'])) {
1024 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
1026 $implicit_mentions[] = $parent_author['url'];
1027 $implicit_mentions[] = $parent_author['nurl'];
1028 $implicit_mentions[] = $parent_author['alias'];
1031 if (!empty($parent['alias'])) {
1032 $implicit_mentions[] = $parent['alias'];
1035 foreach ($parent_terms as $term) {
1036 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1037 if (!empty($contact['url'])) {
1038 $implicit_mentions[] = $contact['url'];
1039 $implicit_mentions[] = $contact['nurl'];
1040 $implicit_mentions[] = $contact['alias'];
1044 return $implicit_mentions;
1048 * Strips from the body prepended implicit mentions
1050 * @param string $body
1051 * @param array $parent
1054 private static function removeImplicitMentionsFromBody(string $body, array $parent)
1056 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1060 $potential_mentions = self::getImplicitMentionList($parent);
1062 $kept_mentions = [];
1064 // Extract one prepended mention at a time from the body
1065 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1066 if (!in_array($matches[2], $potential_mentions)) {
1067 $kept_mentions[] = $matches[1];
1070 $body = $matches[3];
1073 // Re-appending the kept mentions to the body after extraction
1074 $kept_mentions[] = $body;
1076 return implode('', $kept_mentions);