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 if (empty($attach['name'])) {
119 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
121 $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
123 } elseif ($filetype == 'audio') {
124 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
128 $item['body'] .= "\n[audio]" . $attach['url'] . '[/audio]';
129 } elseif ($filetype == 'video') {
130 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
134 $item['body'] .= "\n[video]" . $attach['url'] . '[/video]';
136 if (!empty($item["attach"])) {
137 $item["attach"] .= ',';
139 $item["attach"] = '';
142 $item["attach"] .= '[attach]href="' . $attach['url'] . '" length="' . ($attach['length'] ?? '0') . '" type="' . $attach['mediaType'] . '" title="' . ($attach['name'] ?? '') . '"[/attach]';
153 * @param array $activity Activity array
154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
156 public static function updateItem($activity)
158 $item = Item::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
159 if (!DBA::isResult($item)) {
160 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
161 $item = self::createItem($activity);
162 self::postItem($activity, $item);
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 * @return array Internal item
182 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
183 * @throws \ImagickException
185 public static function createItem($activity)
188 $item['verb'] = Activity::POST;
189 $item['thr-parent'] = $activity['reply-to-id'];
191 if ($activity['reply-to-id'] == $activity['id']) {
192 $item['gravity'] = GRAVITY_PARENT;
193 $item['object-type'] = Activity\ObjectType::NOTE;
195 $item['gravity'] = GRAVITY_COMMENT;
196 $item['object-type'] = Activity\ObjectType::COMMENT;
198 // Ensure that the comment reaches all receivers of the referring post
199 $activity['receiver'] = self::addReceivers($activity);
202 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
203 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
204 self::fetchMissingActivity($activity['reply-to-id'], $activity);
207 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
209 /// @todo What to do with $activity['context']?
210 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
211 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
215 $item['network'] = Protocol::ACTIVITYPUB;
216 $item['author-link'] = $activity['author'];
217 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, false);
218 $item['owner-link'] = $activity['actor'];
219 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, false);
221 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
222 $item['private'] = Item::UNLISTED;
223 } elseif (in_array(0, $activity['receiver'])) {
224 $item['private'] = Item::PUBLIC;
226 $item['private'] = Item::PRIVATE;
229 if (!empty($activity['raw'])) {
230 $item['source'] = $activity['raw'];
231 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
232 $item['conversation-href'] = $activity['context'] ?? '';
233 $item['conversation-uri'] = $activity['conversation'] ?? '';
235 if (isset($activity['push'])) {
236 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
240 $item['isForum'] = false;
242 if (!empty($activity['thread-completion'])) {
243 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
244 $item['causer-link'] = $item['owner-link'];
245 $item['causer-id'] = $item['owner-id'];
247 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
248 $item['owner-link'] = $item['author-link'];
249 $item['owner-id'] = $item['author-id'];
251 $actor = APContact::getByURL($item['owner-link'], false);
252 $item['isForum'] = ($actor['type'] == 'Group');
255 $item['uri'] = $activity['id'];
257 $item['created'] = DateTimeFormat::utc($activity['published']);
258 $item['edited'] = DateTimeFormat::utc($activity['updated']);
259 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
260 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
262 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
264 $item = self::processContent($activity, $item);
269 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
271 $item = self::constructAttachList($activity, $item);
279 * @param array $activity
280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
281 * @throws \ImagickException
283 public static function deleteItem($activity)
285 $owner = Contact::getIdForURL($activity['actor']);
287 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
288 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
292 * Prepare the item array for an activity
294 * @param array $activity Activity array
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
296 * @throws \ImagickException
298 public static function addTag($activity)
300 if (empty($activity['object_content']) || empty($activity['object_id'])) {
304 foreach ($activity['receiver'] as $receiver) {
305 $item = Item::selectFirst(['id', 'uri-id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
306 if (!DBA::isResult($item)) {
307 // We don't fetch missing content for this purpose
311 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
312 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
316 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
317 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
322 * Add users to the receiver list of the given public activity.
323 * This is used to ensure that the activity will be stored in every thread.
325 * @param array $activity Activity array
326 * @return array Modified receiver list
328 private static function addReceivers(array $activity)
330 if (!in_array(0, $activity['receiver'])) {
331 // Private activities will not be modified
332 return $activity['receiver'];
335 // Add all owners of the referring item to the receivers
336 $original = $receivers = $activity['receiver'];
337 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
338 while ($item = DBA::fetch($items)) {
339 $receivers['uid:' . $item['uid']] = $item['uid'];
343 if (count($original) != count($receivers)) {
344 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
351 * Prepare the item array for an activity
353 * @param array $activity Activity array
354 * @param string $verb Activity verb
355 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
356 * @throws \ImagickException
358 public static function createActivity($activity, $verb)
360 $item = self::createItem($activity);
361 $item['verb'] = $verb;
362 $item['thr-parent'] = $activity['object_id'];
363 $item['gravity'] = GRAVITY_ACTIVITY;
364 $item['object-type'] = Activity\ObjectType::NOTE;
366 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
368 $activity['receiver'] = self::addReceivers($activity);
370 self::postItem($activity, $item);
376 * @param array $activity Activity array
380 public static function createEvent($activity, $item)
382 $event['summary'] = HTML::toBBCode($activity['name']);
383 $event['desc'] = HTML::toBBCode($activity['content']);
384 $event['start'] = $activity['start-time'];
385 $event['finish'] = $activity['end-time'];
386 $event['nofinish'] = empty($event['finish']);
387 $event['location'] = $activity['location'];
388 $event['adjust'] = true;
389 $event['cid'] = $item['contact-id'];
390 $event['uid'] = $item['uid'];
391 $event['uri'] = $item['uri'];
392 $event['edited'] = $item['edited'];
393 $event['private'] = $item['private'];
394 $event['guid'] = $item['guid'];
395 $event['plink'] = $item['plink'];
397 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
398 $ev = DBA::selectFirst('event', ['id'], $condition);
399 if (DBA::isResult($ev)) {
400 $event['id'] = $ev['id'];
403 $event_id = Event::store($event);
404 Logger::info('Event was stored', ['id' => $event_id]);
408 * Process the content
410 * @param array $activity Activity array
412 * @return array|bool Returns the item array or false if there was an unexpected occurrence
415 private static function processContent($activity, $item)
417 $item['title'] = HTML::toBBCode($activity['name']);
419 if (!empty($activity['source'])) {
420 $item['body'] = $activity['source'];
422 $content = HTML::toBBCode($activity['content']);
424 if (!empty($activity['emojis'])) {
425 $content = self::replaceEmojis($content, $activity['emojis']);
428 $content = self::convertMentions($content);
430 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
431 $item_private = !in_array(0, $activity['item_receiver']);
432 $parent = Item::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
433 if (!DBA::isResult($parent)) {
434 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
437 if ($item_private && ($parent['private'] != Item::PRIVATE)) {
438 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
442 $content = self::removeImplicitMentionsFromBody($content, $parent);
444 $item['content-warning'] = HTML::toBBCode($activity['summary']);
445 $item['body'] = $content;
448 self::storeFromBody($item);
449 self::storeTags($item['uri-id'], $activity['tags']);
451 $item['location'] = $activity['location'];
453 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
454 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
457 $item['app'] = $activity['generator'];
463 * Store hashtags and mentions
467 private static function storeFromBody(array $item)
469 // Make sure to delete all existing tags (can happen when called via the update functionality)
470 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
472 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
476 * Generate a GUID out of an URL
478 * @param string $url message URL
479 * @return string with GUID
481 private static function getGUIDByURL(string $url)
483 $parsed = parse_url($url);
485 $host_hash = hash('crc32', $parsed['host']);
487 unset($parsed["scheme"]);
488 unset($parsed["host"]);
490 $path = implode("/", $parsed);
492 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
496 * Creates an item post
498 * @param array $activity Activity data
499 * @param array $item item array
500 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 * @throws \ImagickException
503 public static function postItem(array $activity, array $item)
507 foreach ($activity['receiver'] as $receiver) {
508 if ($receiver == -1) {
512 $item['uid'] = $receiver;
514 if ($item['isForum'] ?? false) {
515 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, false);
517 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, false);
520 if (($receiver != 0) && empty($item['contact-id'])) {
521 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, false);
524 if (!empty($activity['directmessage'])) {
525 self::postMail($activity, $item);
529 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
530 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
532 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
533 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
537 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
541 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
544 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
545 self::createEvent($activity, $item);
548 $item_id = Item::insert($item);
550 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
552 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
555 if ($item['uid'] == 0) {
560 // Store send a follow request for every reshare - but only when the item had been stored
561 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
562 $author = APContact::getByURL($item['owner-link'], false);
563 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
564 if ($author['type'] != 'Group') {
565 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
566 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
572 * Store tags and mentions into the tag table
574 * @param integer $uriid
577 private static function storeTags(int $uriid, array $tags = null)
579 foreach ($tags as $tag) {
580 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
584 $hash = substr($tag['name'], 0, 1);
586 if ($tag['type'] == 'Mention') {
587 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
588 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
589 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
590 $tag['name'] = substr($tag['name'], 1);
592 $type = Tag::IMPLICIT_MENTION;
594 if (!empty($tag['href'])) {
595 $apcontact = APContact::getByURL($tag['href']);
596 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
597 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
600 } elseif ($tag['type'] == 'Hashtag') {
601 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
602 $tag['name'] = substr($tag['name'], 1);
604 $type = Tag::HASHTAG;
607 if (empty($tag['name'])) {
611 Tag::store($uriid, $type, $tag['name'], $tag['href']);
616 * Creates an mail post
618 * @param array $activity Activity data
619 * @param array $item item array
620 * @return int|bool New mail table row id or false on error
621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
623 private static function postMail($activity, $item)
625 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
626 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
630 Logger::info('Direct Message', $item);
633 $msg['uid'] = $item['uid'];
635 $msg['contact-id'] = $item['contact-id'];
637 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
638 $msg['from-name'] = $contact['name'];
639 $msg['from-url'] = $contact['url'];
640 $msg['from-photo'] = $contact['photo'];
642 $msg['uri'] = $item['uri'];
643 $msg['created'] = $item['created'];
645 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
646 if (DBA::isResult($parent)) {
647 $msg['parent-uri'] = $parent['parent-uri'];
648 $msg['title'] = $parent['title'];
650 $msg['parent-uri'] = $item['thr-parent'];
652 if (!empty($item['title'])) {
653 $msg['title'] = $item['title'];
654 } elseif (!empty($item['content-warning'])) {
655 $msg['title'] = $item['content-warning'];
657 // Trying to generate a title out of the body
658 $title = $item['body'];
660 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
661 $title = $matches[3];
664 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, BBCode::API, true), 0));
666 if (strlen($title) > 20) {
667 $title = substr($title, 0, 20) . '...';
670 $msg['title'] = $title;
673 $msg['body'] = $item['body'];
675 return Mail::insert($msg);
679 * Fetches missing posts
681 * @param string $url message URL
682 * @param array $child activity array with the child of this message
683 * @return string fetched message URL
684 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
686 public static function fetchMissingActivity($url, $child = [])
688 if (!empty($child['receiver'])) {
689 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
694 $object = ActivityPub::fetchContent($url, $uid);
695 if (empty($object)) {
696 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
700 if (empty($object['id'])) {
701 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
705 if (!empty($child['author'])) {
706 $actor = $child['author'];
707 } elseif (!empty($object['actor'])) {
708 $actor = $object['actor'];
709 } elseif (!empty($object['attributedTo'])) {
710 $actor = $object['attributedTo'];
716 if (!empty($object['published'])) {
717 $published = $object['published'];
718 } elseif (!empty($child['published'])) {
719 $published = $child['published'];
721 $published = DateTimeFormat::utcNow();
725 $activity['@context'] = $object['@context'];
726 unset($object['@context']);
727 $activity['id'] = $object['id'];
728 $activity['to'] = $object['to'] ?? [];
729 $activity['cc'] = $object['cc'] ?? [];
730 $activity['actor'] = $actor;
731 $activity['object'] = $object;
732 $activity['published'] = $published;
733 $activity['type'] = 'Create';
735 $ldactivity = JsonLD::compact($activity);
737 $ldactivity['thread-completion'] = true;
739 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity));
741 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
743 return $activity['id'];
747 * perform a "follow" request
749 * @param array $activity
750 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
751 * @throws \ImagickException
753 public static function followUser($activity)
755 $uid = User::getIdForURL($activity['object_id']);
760 $owner = User::getOwnerDataById($uid);
762 $cid = Contact::getIdForURL($activity['actor'], $uid);
764 self::switchContact($cid);
765 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
766 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
771 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
772 'author-link' => $activity['actor']];
774 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
776 // Ensure that the contact has got the right network type
777 self::switchContact($item['author-id']);
779 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
780 if ($result === true) {
781 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
784 $cid = Contact::getIdForURL($activity['actor'], $uid);
789 if (empty($contact)) {
790 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
793 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
797 * Update the given profile
799 * @param array $activity
802 public static function updatePerson($activity)
804 if (empty($activity['object_id'])) {
808 Logger::info('Updating profile', ['object' => $activity['object_id']]);
809 Contact::updateFromProbeByURL($activity['object_id'], true);
813 * Delete the given profile
815 * @param array $activity
816 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
818 public static function deletePerson($activity)
820 if (empty($activity['object_id']) || empty($activity['actor'])) {
821 Logger::info('Empty object id or actor.');
825 if ($activity['object_id'] != $activity['actor']) {
826 Logger::info('Object id does not match actor.');
830 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
831 while ($contact = DBA::fetch($contacts)) {
832 Contact::remove($contact['id']);
834 DBA::close($contacts);
836 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
840 * Accept a follow request
842 * @param array $activity
843 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
844 * @throws \ImagickException
846 public static function acceptFollowUser($activity)
848 $uid = User::getIdForURL($activity['object_actor']);
853 $cid = Contact::getIdForURL($activity['actor'], $uid);
855 Logger::info('No contact found', ['actor' => $activity['actor']]);
859 self::switchContact($cid);
861 $fields = ['pending' => false];
863 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
864 if ($contact['rel'] == Contact::FOLLOWER) {
865 $fields['rel'] = Contact::FRIEND;
868 $condition = ['id' => $cid];
869 DBA::update('contact', $fields, $condition);
870 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
874 * Reject a follow request
876 * @param array $activity
877 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
878 * @throws \ImagickException
880 public static function rejectFollowUser($activity)
882 $uid = User::getIdForURL($activity['object_actor']);
887 $cid = Contact::getIdForURL($activity['actor'], $uid);
889 Logger::info('No contact found', ['actor' => $activity['actor']]);
893 self::switchContact($cid);
895 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
896 Contact::remove($cid);
897 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
899 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
904 * Undo activity like "like" or "dislike"
906 * @param array $activity
907 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
908 * @throws \ImagickException
910 public static function undoActivity($activity)
912 if (empty($activity['object_id'])) {
916 if (empty($activity['object_actor'])) {
920 $author_id = Contact::getIdForURL($activity['object_actor']);
921 if (empty($author_id)) {
925 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
929 * Activity to remove a follower
931 * @param array $activity
932 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
933 * @throws \ImagickException
935 public static function undoFollowUser($activity)
937 $uid = User::getIdForURL($activity['object_object']);
942 $owner = User::getOwnerDataById($uid);
944 $cid = Contact::getIdForURL($activity['actor'], $uid);
946 Logger::info('No contact found', ['actor' => $activity['actor']]);
950 self::switchContact($cid);
952 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
953 if (!DBA::isResult($contact)) {
957 Contact::removeFollower($owner, $contact);
958 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
962 * Switches a contact to AP if needed
964 * @param integer $cid Contact ID
967 private static function switchContact($cid)
969 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
970 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
974 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
975 Contact::updateFromProbe($cid);
979 * Collects implicit mentions like:
980 * - the author of the parent item
981 * - all the mentioned conversants in the parent item
983 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
987 private static function getImplicitMentionList(array $parent)
989 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
991 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
993 $implicit_mentions = [];
994 if (empty($parent_author['url'])) {
995 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
997 $implicit_mentions[] = $parent_author['url'];
998 $implicit_mentions[] = $parent_author['nurl'];
999 $implicit_mentions[] = $parent_author['alias'];
1002 if (!empty($parent['alias'])) {
1003 $implicit_mentions[] = $parent['alias'];
1006 foreach ($parent_terms as $term) {
1007 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1008 if (!empty($contact['url'])) {
1009 $implicit_mentions[] = $contact['url'];
1010 $implicit_mentions[] = $contact['nurl'];
1011 $implicit_mentions[] = $contact['alias'];
1015 return $implicit_mentions;
1019 * Strips from the body prepended implicit mentions
1021 * @param string $body
1022 * @param array $parent
1025 private static function removeImplicitMentionsFromBody(string $body, array $parent)
1027 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1031 $potential_mentions = self::getImplicitMentionList($parent);
1033 $kept_mentions = [];
1035 // Extract one prepended mention at a time from the body
1036 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1037 if (!in_array($matches[2], $potential_mentions)) {
1038 $kept_mentions[] = $matches[1];
1041 $body = $matches[3];
1044 // Re-appending the kept mentions to the body after extraction
1045 $kept_mentions[] = $body;
1047 return implode('', $kept_mentions);