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 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
98 if ($filetype == 'image') {
99 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
103 if (empty($attach['name'])) {
104 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
106 $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
108 } elseif ($filetype == 'audio') {
109 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
113 $item['body'] .= "\n[audio]" . $attach['url'] . '[/audio]';
114 } elseif ($filetype == 'video') {
115 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
119 $item['body'] .= "\n[video]" . $attach['url'] . '[/video]';
121 if (!empty($item["attach"])) {
122 $item["attach"] .= ',';
124 $item["attach"] = '';
126 if (!isset($attach['length'])) {
127 $attach['length'] = "0";
129 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.($attach['name'] ?? '') .'"[/attach]';
139 * @param array $activity Activity array
140 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
142 public static function updateItem($activity)
144 $item = Item::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
145 if (!DBA::isResult($item)) {
146 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
147 self::createItem($activity);
151 $item['changed'] = DateTimeFormat::utcNow();
152 $item['edited'] = DateTimeFormat::utc($activity['updated']);
154 $item = self::processContent($activity, $item);
159 Item::update($item, ['uri' => $activity['id']]);
163 * Prepares data for a message
165 * @param array $activity Activity array
166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
167 * @throws \ImagickException
169 public static function createItem($activity)
172 $item['verb'] = Activity::POST;
173 $item['thr-parent'] = $activity['reply-to-id'];
175 if ($activity['reply-to-id'] == $activity['id']) {
176 $item['gravity'] = GRAVITY_PARENT;
177 $item['object-type'] = Activity\ObjectType::NOTE;
179 $item['gravity'] = GRAVITY_COMMENT;
180 $item['object-type'] = Activity\ObjectType::COMMENT;
182 // Ensure that the comment reaches all receivers of the referring post
183 $activity['receiver'] = self::addReceivers($activity);
186 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
187 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
188 self::fetchMissingActivity($activity['reply-to-id'], $activity);
191 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
193 self::postItem($activity, $item);
199 * @param array $activity
200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
201 * @throws \ImagickException
203 public static function deleteItem($activity)
205 $owner = Contact::getIdForURL($activity['actor']);
207 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
208 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
212 * Prepare the item array for an activity
214 * @param array $activity Activity array
215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216 * @throws \ImagickException
218 public static function addTag($activity)
220 if (empty($activity['object_content']) || empty($activity['object_id'])) {
224 foreach ($activity['receiver'] as $receiver) {
225 $item = Item::selectFirst(['id', 'uri-id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
226 if (!DBA::isResult($item)) {
227 // We don't fetch missing content for this purpose
231 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
232 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
236 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
237 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
242 * Add users to the receiver list of the given public activity.
243 * This is used to ensure that the activity will be stored in every thread.
245 * @param array $activity Activity array
246 * @return array Modified receiver list
248 private static function addReceivers(array $activity)
250 if (!in_array(0, $activity['receiver'])) {
251 // Private activities will not be modified
252 return $activity['receiver'];
255 // Add all owners of the referring item to the receivers
256 $original = $receivers = $activity['receiver'];
257 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
258 while ($item = DBA::fetch($items)) {
259 $receivers['uid:' . $item['uid']] = $item['uid'];
263 if (count($original) != count($receivers)) {
264 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
271 * Prepare the item array for an activity
273 * @param array $activity Activity array
274 * @param string $verb Activity verb
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 * @throws \ImagickException
278 public static function createActivity($activity, $verb)
281 $item['verb'] = $verb;
282 $item['thr-parent'] = $activity['object_id'];
283 $item['gravity'] = GRAVITY_ACTIVITY;
284 $item['object-type'] = Activity\ObjectType::NOTE;
286 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
288 $activity['receiver'] = self::addReceivers($activity);
290 self::postItem($activity, $item);
296 * @param array $activity Activity array
300 public static function createEvent($activity, $item)
302 $event['summary'] = HTML::toBBCode($activity['name']);
303 $event['desc'] = HTML::toBBCode($activity['content']);
304 $event['start'] = $activity['start-time'];
305 $event['finish'] = $activity['end-time'];
306 $event['nofinish'] = empty($event['finish']);
307 $event['location'] = $activity['location'];
308 $event['adjust'] = true;
309 $event['cid'] = $item['contact-id'];
310 $event['uid'] = $item['uid'];
311 $event['uri'] = $item['uri'];
312 $event['edited'] = $item['edited'];
313 $event['private'] = $item['private'];
314 $event['guid'] = $item['guid'];
315 $event['plink'] = $item['plink'];
317 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
318 $ev = DBA::selectFirst('event', ['id'], $condition);
319 if (DBA::isResult($ev)) {
320 $event['id'] = $ev['id'];
323 $event_id = Event::store($event);
324 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
328 * Process the content
330 * @param array $activity Activity array
332 * @return array|bool Returns the item array or false if there was an unexpected occurrence
335 private static function processContent($activity, $item)
337 $item['title'] = HTML::toBBCode($activity['name']);
339 if (!empty($activity['source'])) {
340 $item['body'] = $activity['source'];
342 $content = HTML::toBBCode($activity['content']);
344 if (!empty($activity['emojis'])) {
345 $content = self::replaceEmojis($content, $activity['emojis']);
348 $content = self::convertMentions($content);
350 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
351 $item_private = !in_array(0, $activity['item_receiver']);
352 $parent = Item::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
353 if (!DBA::isResult($parent)) {
354 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
357 if ($item_private && ($parent['private'] == Item::PRIVATE)) {
358 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
362 $content = self::removeImplicitMentionsFromBody($content, $parent);
364 $item['content-warning'] = HTML::toBBCode($activity['summary']);
365 $item['body'] = $content;
368 self::storeFromBody($item);
369 self::storeTags($item['uri-id'], $activity['tags']);
371 $item['location'] = $activity['location'];
373 if (!empty($item['latitude']) && !empty($item['longitude'])) {
374 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
377 $item['app'] = $activity['generator'];
383 * Store hashtags and mentions
387 private static function storeFromBody(array $item)
389 // Make sure to delete all existing tags (can happen when called via the update functionality)
390 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
392 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
396 * Generate a GUID out of an URL
398 * @param string $url message URL
399 * @return string with GUID
401 private static function getGUIDByURL(string $url)
403 $parsed = parse_url($url);
405 $host_hash = hash('crc32', $parsed['host']);
407 unset($parsed["scheme"]);
408 unset($parsed["host"]);
410 $path = implode("/", $parsed);
412 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
416 * Creates an item post
418 * @param array $activity Activity data
419 * @param array $item item array
420 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
421 * @throws \ImagickException
423 private static function postItem($activity, $item)
425 /// @todo What to do with $activity['context']?
426 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
427 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
431 $item['network'] = Protocol::ACTIVITYPUB;
432 $item['author-link'] = $activity['author'];
433 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
434 $item['owner-link'] = $activity['actor'];
435 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
437 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
438 $item['private'] = Item::UNLISTED;
439 } elseif (in_array(0, $activity['receiver'])) {
440 $item['private'] = Item::PUBLIC;
442 $item['private'] = Item::PRIVATE;
445 if (!empty($activity['raw'])) {
446 $item['source'] = $activity['raw'];
447 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
448 $item['conversation-href'] = $activity['context'] ?? '';
449 $item['conversation-uri'] = $activity['conversation'] ?? '';
451 if (isset($activity['push'])) {
452 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
458 if (!empty($activity['thread-completion'])) {
459 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
460 $item['causer-link'] = $item['owner-link'];
461 $item['causer-id'] = $item['owner-id'];
463 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
464 $item['owner-link'] = $item['author-link'];
465 $item['owner-id'] = $item['author-id'];
467 $actor = APContact::getByURL($item['owner-link'], false);
468 $isForum = ($actor['type'] == 'Group');
471 $item['uri'] = $activity['id'];
473 $item['created'] = DateTimeFormat::utc($activity['published']);
474 $item['edited'] = DateTimeFormat::utc($activity['updated']);
475 $item['guid'] = $activity['diaspora:guid'] ?: $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
477 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
479 $item = self::processContent($activity, $item);
484 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
486 $item = self::constructAttachList($activity, $item);
490 foreach ($activity['receiver'] as $receiver) {
491 if ($receiver == -1) {
495 $item['uid'] = $receiver;
498 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
500 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
503 if (($receiver != 0) && empty($item['contact-id'])) {
504 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
507 if (!empty($activity['directmessage'])) {
508 self::postMail($activity, $item);
512 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
513 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
515 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
516 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
520 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
524 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
527 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
528 self::createEvent($activity, $item);
531 $item_id = Item::insert($item);
533 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
535 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
538 if ($item['uid'] == 0) {
543 // Store send a follow request for every reshare - but only when the item had been stored
544 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
545 $author = APContact::getByURL($item['owner-link'], false);
546 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
547 if ($author['type'] != 'Group') {
548 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
549 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
555 * Store tags and mentions into the tag table
557 * @param integer $uriid
560 private static function storeTags(int $uriid, array $tags = null)
562 foreach ($tags as $tag) {
563 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
567 $hash = substr($tag['name'], 0, 1);
569 if ($tag['type'] == 'Mention') {
570 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
571 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
572 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
573 $tag['name'] = substr($tag['name'], 1);
575 $type = Tag::IMPLICIT_MENTION;
577 if (!empty($tag['href'])) {
578 $apcontact = APContact::getByURL($tag['href']);
579 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
580 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
583 } elseif ($tag['type'] == 'Hashtag') {
584 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
585 $tag['name'] = substr($tag['name'], 1);
587 $type = Tag::HASHTAG;
590 if (empty($tag['name'])) {
594 Tag::store($uriid, $type, $tag['name'], $tag['href']);
599 * Creates an mail post
601 * @param array $activity Activity data
602 * @param array $item item array
603 * @return int|bool New mail table row id or false on error
604 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
606 private static function postMail($activity, $item)
608 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
609 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
613 Logger::info('Direct Message', $item);
616 $msg['uid'] = $item['uid'];
618 $msg['contact-id'] = $item['contact-id'];
620 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
621 $msg['from-name'] = $contact['name'];
622 $msg['from-url'] = $contact['url'];
623 $msg['from-photo'] = $contact['photo'];
625 $msg['uri'] = $item['uri'];
626 $msg['created'] = $item['created'];
628 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
629 if (DBA::isResult($parent)) {
630 $msg['parent-uri'] = $parent['parent-uri'];
631 $msg['title'] = $parent['title'];
633 $msg['parent-uri'] = $item['thr-parent'];
635 if (!empty($item['title'])) {
636 $msg['title'] = $item['title'];
637 } elseif (!empty($item['content-warning'])) {
638 $msg['title'] = $item['content-warning'];
640 // Trying to generate a title out of the body
641 $title = $item['body'];
643 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
644 $title = $matches[3];
647 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, BBCode::API, true), 0));
649 if (strlen($title) > 20) {
650 $title = substr($title, 0, 20) . '...';
653 $msg['title'] = $title;
656 $msg['body'] = $item['body'];
658 return Mail::insert($msg);
662 * Fetches missing posts
664 * @param string $url message URL
665 * @param array $child activity array with the child of this message
666 * @return string fetched message URL
667 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
669 public static function fetchMissingActivity($url, $child = [])
671 if (!empty($child['receiver'])) {
672 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
677 $object = ActivityPub::fetchContent($url, $uid);
678 if (empty($object)) {
679 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
683 if (empty($object['id'])) {
684 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
688 if (!empty($child['author'])) {
689 $actor = $child['author'];
690 } elseif (!empty($object['actor'])) {
691 $actor = $object['actor'];
692 } elseif (!empty($object['attributedTo'])) {
693 $actor = $object['attributedTo'];
699 if (!empty($object['published'])) {
700 $published = $object['published'];
701 } elseif (!empty($child['published'])) {
702 $published = $child['published'];
704 $published = DateTimeFormat::utcNow();
708 $activity['@context'] = $object['@context'];
709 unset($object['@context']);
710 $activity['id'] = $object['id'];
711 $activity['to'] = $object['to'] ?? [];
712 $activity['cc'] = $object['cc'] ?? [];
713 $activity['actor'] = $actor;
714 $activity['object'] = $object;
715 $activity['published'] = $published;
716 $activity['type'] = 'Create';
718 $ldactivity = JsonLD::compact($activity);
720 $ldactivity['thread-completion'] = true;
722 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity));
724 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
726 return $activity['id'];
730 * perform a "follow" request
732 * @param array $activity
733 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
734 * @throws \ImagickException
736 public static function followUser($activity)
738 $uid = User::getIdForURL($activity['object_id']);
743 $owner = User::getOwnerDataById($uid);
745 $cid = Contact::getIdForURL($activity['actor'], $uid);
747 self::switchContact($cid);
748 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
749 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
754 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
755 'author-link' => $activity['actor']];
757 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
759 // Ensure that the contact has got the right network type
760 self::switchContact($item['author-id']);
762 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
763 if ($result === true) {
764 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
767 $cid = Contact::getIdForURL($activity['actor'], $uid);
772 if (empty($contact)) {
773 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
776 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
780 * Update the given profile
782 * @param array $activity
785 public static function updatePerson($activity)
787 if (empty($activity['object_id'])) {
791 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
792 Contact::updateFromProbeByURL($activity['object_id'], true);
796 * Delete the given profile
798 * @param array $activity
799 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
801 public static function deletePerson($activity)
803 if (empty($activity['object_id']) || empty($activity['actor'])) {
804 Logger::log('Empty object id or actor.', Logger::DEBUG);
808 if ($activity['object_id'] != $activity['actor']) {
809 Logger::log('Object id does not match actor.', Logger::DEBUG);
813 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
814 while ($contact = DBA::fetch($contacts)) {
815 Contact::remove($contact['id']);
817 DBA::close($contacts);
819 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
823 * Accept a follow request
825 * @param array $activity
826 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
827 * @throws \ImagickException
829 public static function acceptFollowUser($activity)
831 $uid = User::getIdForURL($activity['object_actor']);
836 $cid = Contact::getIdForURL($activity['actor'], $uid);
838 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
842 self::switchContact($cid);
844 $fields = ['pending' => false];
846 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
847 if ($contact['rel'] == Contact::FOLLOWER) {
848 $fields['rel'] = Contact::FRIEND;
851 $condition = ['id' => $cid];
852 DBA::update('contact', $fields, $condition);
853 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
857 * Reject a follow request
859 * @param array $activity
860 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
861 * @throws \ImagickException
863 public static function rejectFollowUser($activity)
865 $uid = User::getIdForURL($activity['object_actor']);
870 $cid = Contact::getIdForURL($activity['actor'], $uid);
872 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
876 self::switchContact($cid);
878 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
879 Contact::remove($cid);
880 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
882 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
887 * Undo activity like "like" or "dislike"
889 * @param array $activity
890 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
891 * @throws \ImagickException
893 public static function undoActivity($activity)
895 if (empty($activity['object_id'])) {
899 if (empty($activity['object_actor'])) {
903 $author_id = Contact::getIdForURL($activity['object_actor']);
904 if (empty($author_id)) {
908 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
912 * Activity to remove a follower
914 * @param array $activity
915 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
916 * @throws \ImagickException
918 public static function undoFollowUser($activity)
920 $uid = User::getIdForURL($activity['object_object']);
925 $owner = User::getOwnerDataById($uid);
927 $cid = Contact::getIdForURL($activity['actor'], $uid);
929 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
933 self::switchContact($cid);
935 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
936 if (!DBA::isResult($contact)) {
940 Contact::removeFollower($owner, $contact);
941 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
945 * Switches a contact to AP if needed
947 * @param integer $cid Contact ID
950 private static function switchContact($cid)
952 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
953 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
957 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
958 Contact::updateFromProbe($cid);
962 * Collects implicit mentions like:
963 * - the author of the parent item
964 * - all the mentioned conversants in the parent item
966 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
968 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
970 private static function getImplicitMentionList(array $parent)
972 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
974 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
976 $implicit_mentions = [];
977 if (empty($parent_author)) {
978 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
980 $implicit_mentions[] = $parent_author['url'];
981 $implicit_mentions[] = $parent_author['nurl'];
982 $implicit_mentions[] = $parent_author['alias'];
985 if (!empty($parent['alias'])) {
986 $implicit_mentions[] = $parent['alias'];
989 foreach ($parent_terms as $term) {
990 $contact = Contact::getDetailsByURL($term['url'], 0);
991 if (!empty($contact)) {
992 $implicit_mentions[] = $contact['url'];
993 $implicit_mentions[] = $contact['nurl'];
994 $implicit_mentions[] = $contact['alias'];
998 return $implicit_mentions;
1002 * Strips from the body prepended implicit mentions
1004 * @param string $body
1005 * @param array $parent
1008 private static function removeImplicitMentionsFromBody(string $body, array $parent)
1010 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1014 $potential_mentions = self::getImplicitMentionList($parent);
1016 $kept_mentions = [];
1018 // Extract one prepended mention at a time from the body
1019 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1020 if (!in_array($matches[2], $potential_mentions)) {
1021 $kept_mentions[] = $matches[1];
1024 $body = $matches[3];
1027 // Re-appending the kept mentions to the body after extraction
1028 $kept_mentions[] = $body;
1030 return implode('', $kept_mentions);