3 * @file src/Protocol/ActivityPub/Processor.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Content\Text\BBCode;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Database\DBA;
14 use Friendica\Model\APContact;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Event;
17 use Friendica\Model\Item;
18 use Friendica\Model\Mail;
19 use Friendica\Model\Term;
20 use Friendica\Model\User;
21 use Friendica\Protocol\Activity;
22 use Friendica\Protocol\ActivityPub;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\JsonLD;
25 use Friendica\Util\Strings;
28 * ActivityPub Processor Protocol class
33 * Converts mentions from Pleroma into the Friendica format
37 * @return string converted body
39 private static function convertMentions($body)
41 $URLSearchString = "^\[\]";
42 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
48 * Replaces emojis in the body
50 * @param array $emojis
53 * @return string with replaced emojis
55 private static function replaceEmojis($body, array $emojis)
57 foreach ($emojis as $emoji) {
58 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
59 $body = str_replace($emoji['name'], $replace, $body);
65 * Constructs a string with tags for a given tag array
68 * @param boolean $sensitive
69 * @return string with tags
71 private static function constructTagString(array $tags = null, $sensitive = false)
78 foreach ($tags as $tag) {
79 if (in_array($tag['type'] ?? '', ['Mention', 'Hashtag'])) {
80 if (!empty($tag_text)) {
84 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
88 /// @todo add nsfw for $sensitive
94 * Add attachment data to the item array
96 * @param array $activity
101 private static function constructAttachList($activity, $item)
103 if (empty($activity['attachments'])) {
107 foreach ($activity['attachments'] as $attach) {
108 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
109 if ($filetype == 'image') {
110 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
114 if (empty($attach['name'])) {
115 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
117 $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
120 if (!empty($item["attach"])) {
121 $item["attach"] .= ',';
123 $item["attach"] = '';
125 if (!isset($attach['length'])) {
126 $attach['length'] = "0";
128 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.($attach['name'] ?? '') .'"[/attach]';
138 * @param array $activity Activity array
139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
141 public static function updateItem($activity)
143 $item = Item::selectFirst(['uri', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
144 if (!DBA::isResult($item)) {
145 Logger::warning('Unknown item', ['uri' => $activity['id']]);
149 $item['changed'] = DateTimeFormat::utcNow();
150 $item['edited'] = DateTimeFormat::utc($activity['updated']);
152 $item = self::processContent($activity, $item);
157 Item::update($item, ['uri' => $activity['id']]);
161 * Prepares data for a message
163 * @param array $activity Activity array
164 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
165 * @throws \ImagickException
167 public static function createItem($activity)
170 $item['verb'] = Activity::POST;
171 $item['thr-parent'] = $activity['reply-to-id'];
173 if ($activity['reply-to-id'] == $activity['id']) {
174 $item['gravity'] = GRAVITY_PARENT;
175 $item['object-type'] = Activity\ObjectType::NOTE;
177 $item['gravity'] = GRAVITY_COMMENT;
178 $item['object-type'] = Activity\ObjectType::COMMENT;
180 // Ensure that the comment reaches all receivers of the referring post
181 $activity['receiver'] = self::addReceivers($activity);
184 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
185 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
186 self::fetchMissingActivity($activity['reply-to-id'], $activity);
189 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
191 self::postItem($activity, $item);
197 * @param array $activity
198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
199 * @throws \ImagickException
201 public static function deleteItem($activity)
203 $owner = Contact::getIdForURL($activity['actor']);
205 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
206 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
210 * Prepare the item array for an activity
212 * @param array $activity Activity array
213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
214 * @throws \ImagickException
216 public static function addTag($activity)
218 if (empty($activity['object_content']) || empty($activity['object_id'])) {
222 foreach ($activity['receiver'] as $receiver) {
223 $item = Item::selectFirst(['id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
224 if (!DBA::isResult($item)) {
225 // We don't fetch missing content for this purpose
229 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
230 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
235 // - Check if "blocktag" is set
236 // - Check if actor is a contact
238 if (!stristr($item['tag'], trim($activity['object_content']))) {
239 $tag = $item['tag'] . (strlen($item['tag']) ? ',' : '') . '#[url=' . $activity['object_id'] . ']'. $activity['object_content'] . '[/url]';
240 Item::update(['tag' => $tag], ['id' => $item['id']]);
241 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
247 * Add users to the receiver list of the given public activity.
248 * This is used to ensure that the activity will be stored in every thread.
250 * @param array $activity Activity array
251 * @return array Modified receiver list
253 private static function addReceivers(array $activity)
255 if (!in_array(0, $activity['receiver'])) {
256 // Private activities will not be modified
257 return $activity['receiver'];
260 // Add all owners of the referring item to the receivers
261 $original = $receivers = $activity['receiver'];
262 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
263 while ($item = DBA::fetch($items)) {
264 $receivers['uid:' . $item['uid']] = $item['uid'];
268 if (count($original) != count($receivers)) {
269 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
276 * Prepare the item array for an activity
278 * @param array $activity Activity array
279 * @param string $verb Activity verb
280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
281 * @throws \ImagickException
283 public static function createActivity($activity, $verb)
286 $item['verb'] = $verb;
287 $item['thr-parent'] = $activity['object_id'];
288 $item['gravity'] = GRAVITY_ACTIVITY;
289 $item['object-type'] = Activity\ObjectType::NOTE;
291 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
293 $activity['receiver'] = self::addReceivers($activity);
295 self::postItem($activity, $item);
301 * @param array $activity Activity array
305 public static function createEvent($activity, $item)
307 $event['summary'] = HTML::toBBCode($activity['name']);
308 $event['desc'] = HTML::toBBCode($activity['content']);
309 $event['start'] = $activity['start-time'];
310 $event['finish'] = $activity['end-time'];
311 $event['nofinish'] = empty($event['finish']);
312 $event['location'] = $activity['location'];
313 $event['adjust'] = true;
314 $event['cid'] = $item['contact-id'];
315 $event['uid'] = $item['uid'];
316 $event['uri'] = $item['uri'];
317 $event['edited'] = $item['edited'];
318 $event['private'] = $item['private'];
319 $event['guid'] = $item['guid'];
320 $event['plink'] = $item['plink'];
322 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
323 $ev = DBA::selectFirst('event', ['id'], $condition);
324 if (DBA::isResult($ev)) {
325 $event['id'] = $ev['id'];
328 $event_id = Event::store($event);
329 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
333 * Process the content
335 * @param array $activity Activity array
337 * @return array|bool Returns the item array or false if there was an unexpected occurrence
340 private static function processContent($activity, $item)
342 $item['title'] = HTML::toBBCode($activity['name']);
344 if (!empty($activity['source'])) {
345 $item['body'] = $activity['source'];
347 $content = HTML::toBBCode($activity['content']);
349 if (!empty($activity['emojis'])) {
350 $content = self::replaceEmojis($content, $activity['emojis']);
353 $content = self::convertMentions($content);
355 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
356 $item_private = !in_array(0, $activity['item_receiver']);
357 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
358 if (!DBA::isResult($parent)) {
359 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
362 if ($item_private && !$parent['private']) {
363 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
367 $potential_implicit_mentions = self::getImplicitMentionList($parent);
368 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
369 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
371 $item['content-warning'] = HTML::toBBCode($activity['summary']);
372 $item['body'] = $content;
374 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
375 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
379 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
381 $item['location'] = $activity['location'];
383 if (!empty($item['latitude']) && !empty($item['longitude'])) {
384 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
387 $item['app'] = $activity['generator'];
393 * Generate a GUID out of an URL
395 * @param string $url message URL
396 * @return string with GUID
398 private static function getGUIDByURL(string $url)
400 $parsed = parse_url($url);
402 $host_hash = hash('crc32', $parsed['host']);
404 unset($parsed["scheme"]);
405 unset($parsed["host"]);
407 $path = implode("/", $parsed);
409 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
413 * Creates an item post
415 * @param array $activity Activity data
416 * @param array $item item array
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 * @throws \ImagickException
420 private static function postItem($activity, $item)
422 /// @todo What to do with $activity['context']?
423 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
424 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
428 $item['network'] = Protocol::ACTIVITYPUB;
429 $item['private'] = !in_array(0, $activity['receiver']);
430 $item['author-link'] = $activity['author'];
431 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
432 $item['owner-link'] = $activity['actor'];
433 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
437 if (!empty($activity['thread-completion'])) {
438 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
439 $item['causer-link'] = $item['owner-link'];
440 $item['causer-id'] = $item['owner-id'];
442 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
443 $item['owner-link'] = $item['author-link'];
444 $item['owner-id'] = $item['author-id'];
446 $actor = APContact::getByURL($item['owner-link'], false);
447 $isForum = ($actor['type'] == 'Group');
450 $item['uri'] = $activity['id'];
452 $item['created'] = DateTimeFormat::utc($activity['published']);
453 $item['edited'] = DateTimeFormat::utc($activity['updated']);
454 $item['guid'] = $activity['diaspora:guid'] ?: self::getGUIDByURL($item['uri']);
456 $item = self::processContent($activity, $item);
461 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
463 $item = self::constructAttachList($activity, $item);
467 foreach ($activity['receiver'] as $receiver) {
468 $item['uid'] = $receiver;
471 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
473 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
476 if (($receiver != 0) && empty($item['contact-id'])) {
477 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
480 if (!empty($activity['directmessage'])) {
481 self::postMail($activity, $item);
485 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
486 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
488 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
489 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
493 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
497 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
500 if ($activity['object_type'] == 'as:Event') {
501 self::createEvent($activity, $item);
504 $item_id = Item::insert($item);
506 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
508 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
511 if ($item['uid'] == 0) {
516 // Store send a follow request for every reshare - but only when the item had been stored
517 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
518 $author = APContact::getByURL($item['owner-link'], false);
519 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
520 if ($author['type'] != 'Group') {
521 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
522 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
528 * Creates an mail post
530 * @param array $activity Activity data
531 * @param array $item item array
532 * @return int|bool New mail table row id or false on error
533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
535 private static function postMail($activity, $item)
537 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
538 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
542 Logger::info('Direct Message', $item);
545 $msg['uid'] = $item['uid'];
547 $msg['contact-id'] = $item['contact-id'];
549 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
550 $msg['from-name'] = $contact['name'];
551 $msg['from-url'] = $contact['url'];
552 $msg['from-photo'] = $contact['photo'];
554 $msg['uri'] = $item['uri'];
555 $msg['created'] = $item['created'];
557 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
558 if (DBA::isResult($parent)) {
559 $msg['parent-uri'] = $parent['parent-uri'];
560 $msg['title'] = $parent['title'];
562 $msg['parent-uri'] = $item['thr-parent'];
564 if (!empty($item['title'])) {
565 $msg['title'] = $item['title'];
566 } elseif (!empty($item['content-warning'])) {
567 $msg['title'] = $item['content-warning'];
569 // Trying to generate a title out of the body
570 $title = $item['body'];
572 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
573 $title = $matches[3];
576 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
578 if (strlen($title) > 20) {
579 $title = substr($title, 0, 20) . '...';
582 $msg['title'] = $title;
585 $msg['body'] = $item['body'];
587 return Mail::insert($msg);
591 * Fetches missing posts
593 * @param string $url message URL
594 * @param array $child activity array with the child of this message
595 * @return boolean success
596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
598 public static function fetchMissingActivity($url, $child = [])
600 if (!empty($child['receiver'])) {
601 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
606 $object = ActivityPub::fetchContent($url, $uid);
607 if (empty($object)) {
608 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
612 if (empty($object['id'])) {
613 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
617 if (!empty($child['author'])) {
618 $actor = $child['author'];
619 } elseif (!empty($object['actor'])) {
620 $actor = $object['actor'];
621 } elseif (!empty($object['attributedTo'])) {
622 $actor = $object['attributedTo'];
628 if (!empty($object['published'])) {
629 $published = $object['published'];
630 } elseif (!empty($child['published'])) {
631 $published = $child['published'];
633 $published = DateTimeFormat::utcNow();
637 $activity['@context'] = $object['@context'];
638 unset($object['@context']);
639 $activity['id'] = $object['id'];
640 $activity['to'] = $object['to'] ?? [];
641 $activity['cc'] = $object['cc'] ?? [];
642 $activity['actor'] = $actor;
643 $activity['object'] = $object;
644 $activity['published'] = $published;
645 $activity['type'] = 'Create';
647 $ldactivity = JsonLD::compact($activity);
649 $ldactivity['thread-completion'] = true;
651 ActivityPub\Receiver::processActivity($ldactivity);
652 Logger::log('Activity ' . $url . ' had been fetched and processed.');
658 * perform a "follow" request
660 * @param array $activity
661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662 * @throws \ImagickException
664 public static function followUser($activity)
666 $uid = User::getIdForURL($activity['object_id']);
671 $owner = User::getOwnerDataById($uid);
673 $cid = Contact::getIdForURL($activity['actor'], $uid);
675 self::switchContact($cid);
676 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
677 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
682 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
683 'author-link' => $activity['actor']];
685 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
687 // Ensure that the contact has got the right network type
688 self::switchContact($item['author-id']);
690 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
691 if ($result === true) {
692 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
695 $cid = Contact::getIdForURL($activity['actor'], $uid);
700 if (empty($contact)) {
701 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
704 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
708 * Update the given profile
710 * @param array $activity
713 public static function updatePerson($activity)
715 if (empty($activity['object_id'])) {
719 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
720 Contact::updateFromProbeByURL($activity['object_id'], true);
724 * Delete the given profile
726 * @param array $activity
727 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
729 public static function deletePerson($activity)
731 if (empty($activity['object_id']) || empty($activity['actor'])) {
732 Logger::log('Empty object id or actor.', Logger::DEBUG);
736 if ($activity['object_id'] != $activity['actor']) {
737 Logger::log('Object id does not match actor.', Logger::DEBUG);
741 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
742 while ($contact = DBA::fetch($contacts)) {
743 Contact::remove($contact['id']);
745 DBA::close($contacts);
747 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
751 * Accept a follow request
753 * @param array $activity
754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
755 * @throws \ImagickException
757 public static function acceptFollowUser($activity)
759 $uid = User::getIdForURL($activity['object_actor']);
764 $cid = Contact::getIdForURL($activity['actor'], $uid);
766 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
770 self::switchContact($cid);
772 $fields = ['pending' => false];
774 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
775 if ($contact['rel'] == Contact::FOLLOWER) {
776 $fields['rel'] = Contact::FRIEND;
779 $condition = ['id' => $cid];
780 DBA::update('contact', $fields, $condition);
781 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
785 * Reject a follow request
787 * @param array $activity
788 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
789 * @throws \ImagickException
791 public static function rejectFollowUser($activity)
793 $uid = User::getIdForURL($activity['object_actor']);
798 $cid = Contact::getIdForURL($activity['actor'], $uid);
800 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
804 self::switchContact($cid);
806 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
807 Contact::remove($cid);
808 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
810 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
815 * Undo activity like "like" or "dislike"
817 * @param array $activity
818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
819 * @throws \ImagickException
821 public static function undoActivity($activity)
823 if (empty($activity['object_id'])) {
827 if (empty($activity['object_actor'])) {
831 $author_id = Contact::getIdForURL($activity['object_actor']);
832 if (empty($author_id)) {
836 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
840 * Activity to remove a follower
842 * @param array $activity
843 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
844 * @throws \ImagickException
846 public static function undoFollowUser($activity)
848 $uid = User::getIdForURL($activity['object_object']);
853 $owner = User::getOwnerDataById($uid);
855 $cid = Contact::getIdForURL($activity['actor'], $uid);
857 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
861 self::switchContact($cid);
863 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
864 if (!DBA::isResult($contact)) {
868 Contact::removeFollower($owner, $contact);
869 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
873 * Switches a contact to AP if needed
875 * @param integer $cid Contact ID
878 private static function switchContact($cid)
880 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
881 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
885 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
886 Contact::updateFromProbe($cid);
890 * Collects implicit mentions like:
891 * - the author of the parent item
892 * - all the mentioned conversants in the parent item
894 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
896 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
898 private static function getImplicitMentionList(array $parent)
900 if (Config::get('system', 'disable_implicit_mentions')) {
904 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
906 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
908 $implicit_mentions = [];
909 if (empty($parent_author)) {
910 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
912 $implicit_mentions[] = $parent_author['url'];
913 $implicit_mentions[] = $parent_author['nurl'];
914 $implicit_mentions[] = $parent_author['alias'];
917 if (!empty($parent['alias'])) {
918 $implicit_mentions[] = $parent['alias'];
921 foreach ($parent_terms as $term) {
922 $contact = Contact::getDetailsByURL($term['url'], 0);
923 if (!empty($contact)) {
924 $implicit_mentions[] = $contact['url'];
925 $implicit_mentions[] = $contact['nurl'];
926 $implicit_mentions[] = $contact['alias'];
930 return $implicit_mentions;
934 * Strips from the body prepended implicit mentions
936 * @param string $body
937 * @param array $potential_mentions
940 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
942 if (Config::get('system', 'disable_implicit_mentions')) {
948 // Extract one prepended mention at a time from the body
949 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
950 if (!in_array($matches[2], $potential_mentions)) {
951 $kept_mentions[] = $matches[1];
957 // Re-appending the kept mentions to the body after extraction
958 $kept_mentions[] = $body;
960 return implode('', $kept_mentions);
963 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
965 if (Config::get('system', 'disable_implicit_mentions')) {
966 return $activity_tags;
969 foreach ($activity_tags as $index => $tag) {
970 if (in_array($tag['href'], $potential_mentions)) {
971 $activity_tags[$index]['name'] = preg_replace(
972 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
973 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
974 $activity_tags[$index]['name'],
980 return $activity_tags;