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\Logger;
10 use Friendica\Core\Protocol;
11 use Friendica\Database\DBA;
13 use Friendica\Model\APContact;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Event;
16 use Friendica\Model\Item;
17 use Friendica\Model\Mail;
18 use Friendica\Model\Term;
19 use Friendica\Model\User;
20 use Friendica\Protocol\Activity;
21 use Friendica\Protocol\ActivityPub;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\JsonLD;
24 use Friendica\Util\Strings;
27 * ActivityPub Processor Protocol class
32 * Converts mentions from Pleroma into the Friendica format
36 * @return string converted body
38 private static function convertMentions($body)
40 $URLSearchString = "^\[\]";
41 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
47 * Replaces emojis in the body
49 * @param array $emojis
52 * @return string with replaced emojis
54 private static function replaceEmojis($body, array $emojis)
56 foreach ($emojis as $emoji) {
57 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
58 $body = str_replace($emoji['name'], $replace, $body);
64 * Constructs a string with tags for a given tag array
67 * @param boolean $sensitive
68 * @return string with tags
70 private static function constructTagString(array $tags = null, $sensitive = false)
77 foreach ($tags as $tag) {
78 if (in_array($tag['type'] ?? '', ['Mention', 'Hashtag'])) {
79 if (!empty($tag_text)) {
83 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
87 /// @todo add nsfw for $sensitive
93 * Add attachment data to the item array
95 * @param array $activity
100 private static function constructAttachList($activity, $item)
102 if (empty($activity['attachments'])) {
106 foreach ($activity['attachments'] as $attach) {
107 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
108 if ($filetype == 'image') {
109 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
113 if (empty($attach['name'])) {
114 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
116 $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
119 if (!empty($item["attach"])) {
120 $item["attach"] .= ',';
122 $item["attach"] = '';
124 if (!isset($attach['length'])) {
125 $attach['length'] = "0";
127 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.($attach['name'] ?? '') .'"[/attach]';
137 * @param array $activity Activity array
138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
140 public static function updateItem($activity)
142 $item = Item::selectFirst(['uri', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
143 if (!DBA::isResult($item)) {
144 Logger::warning('Unknown item', ['uri' => $activity['id']]);
148 $item['changed'] = DateTimeFormat::utcNow();
149 $item['edited'] = DateTimeFormat::utc($activity['updated']);
151 $item = self::processContent($activity, $item);
156 Item::update($item, ['uri' => $activity['id']]);
160 * Prepares data for a message
162 * @param array $activity Activity array
163 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
164 * @throws \ImagickException
166 public static function createItem($activity)
169 $item['verb'] = Activity::POST;
170 $item['thr-parent'] = $activity['reply-to-id'];
172 if ($activity['reply-to-id'] == $activity['id']) {
173 $item['gravity'] = GRAVITY_PARENT;
174 $item['object-type'] = Activity\ObjectType::NOTE;
176 $item['gravity'] = GRAVITY_COMMENT;
177 $item['object-type'] = Activity\ObjectType::COMMENT;
179 // Ensure that the comment reaches all receivers of the referring post
180 $activity['receiver'] = self::addReceivers($activity);
183 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
184 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
185 self::fetchMissingActivity($activity['reply-to-id'], $activity);
188 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
190 self::postItem($activity, $item);
196 * @param array $activity
197 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
198 * @throws \ImagickException
200 public static function deleteItem($activity)
202 $owner = Contact::getIdForURL($activity['actor']);
204 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
205 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
209 * Prepare the item array for an activity
211 * @param array $activity Activity array
212 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
213 * @throws \ImagickException
215 public static function addTag($activity)
217 if (empty($activity['object_content']) || empty($activity['object_id'])) {
221 foreach ($activity['receiver'] as $receiver) {
222 $item = Item::selectFirst(['id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
223 if (!DBA::isResult($item)) {
224 // We don't fetch missing content for this purpose
228 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
229 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
234 // - Check if "blocktag" is set
235 // - Check if actor is a contact
237 if (!stristr($item['tag'], trim($activity['object_content']))) {
238 $tag = $item['tag'] . (strlen($item['tag']) ? ',' : '') . '#[url=' . $activity['object_id'] . ']'. $activity['object_content'] . '[/url]';
239 Item::update(['tag' => $tag], ['id' => $item['id']]);
240 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
246 * Add users to the receiver list of the given public activity.
247 * This is used to ensure that the activity will be stored in every thread.
249 * @param array $activity Activity array
250 * @return array Modified receiver list
252 private static function addReceivers(array $activity)
254 if (!in_array(0, $activity['receiver'])) {
255 // Private activities will not be modified
256 return $activity['receiver'];
259 // Add all owners of the referring item to the receivers
260 $original = $receivers = $activity['receiver'];
261 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
262 while ($item = DBA::fetch($items)) {
263 $receivers['uid:' . $item['uid']] = $item['uid'];
267 if (count($original) != count($receivers)) {
268 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
275 * Prepare the item array for an activity
277 * @param array $activity Activity array
278 * @param string $verb Activity verb
279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
280 * @throws \ImagickException
282 public static function createActivity($activity, $verb)
285 $item['verb'] = $verb;
286 $item['thr-parent'] = $activity['object_id'];
287 $item['gravity'] = GRAVITY_ACTIVITY;
288 $item['object-type'] = Activity\ObjectType::NOTE;
290 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
292 $activity['receiver'] = self::addReceivers($activity);
294 self::postItem($activity, $item);
300 * @param array $activity Activity array
304 public static function createEvent($activity, $item)
306 $event['summary'] = HTML::toBBCode($activity['name']);
307 $event['desc'] = HTML::toBBCode($activity['content']);
308 $event['start'] = $activity['start-time'];
309 $event['finish'] = $activity['end-time'];
310 $event['nofinish'] = empty($event['finish']);
311 $event['location'] = $activity['location'];
312 $event['adjust'] = true;
313 $event['cid'] = $item['contact-id'];
314 $event['uid'] = $item['uid'];
315 $event['uri'] = $item['uri'];
316 $event['edited'] = $item['edited'];
317 $event['private'] = $item['private'];
318 $event['guid'] = $item['guid'];
319 $event['plink'] = $item['plink'];
321 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
322 $ev = DBA::selectFirst('event', ['id'], $condition);
323 if (DBA::isResult($ev)) {
324 $event['id'] = $ev['id'];
327 $event_id = Event::store($event);
328 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
332 * Process the content
334 * @param array $activity Activity array
336 * @return array|bool Returns the item array or false if there was an unexpected occurrence
339 private static function processContent($activity, $item)
341 $item['title'] = HTML::toBBCode($activity['name']);
343 if (!empty($activity['source'])) {
344 $item['body'] = $activity['source'];
346 $content = HTML::toBBCode($activity['content']);
348 if (!empty($activity['emojis'])) {
349 $content = self::replaceEmojis($content, $activity['emojis']);
352 $content = self::convertMentions($content);
354 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
355 $item_private = !in_array(0, $activity['item_receiver']);
356 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
357 if (!DBA::isResult($parent)) {
358 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
361 if ($item_private && !$parent['private']) {
362 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
366 $potential_implicit_mentions = self::getImplicitMentionList($parent);
367 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
368 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
370 $item['content-warning'] = HTML::toBBCode($activity['summary']);
371 $item['body'] = $content;
373 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
374 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
378 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
380 $item['location'] = $activity['location'];
382 if (!empty($item['latitude']) && !empty($item['longitude'])) {
383 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
386 $item['app'] = $activity['generator'];
392 * Generate a GUID out of an URL
394 * @param string $url message URL
395 * @return string with GUID
397 private static function getGUIDByURL(string $url)
399 $parsed = parse_url($url);
401 $host_hash = hash('crc32', $parsed['host']);
403 unset($parsed["scheme"]);
404 unset($parsed["host"]);
406 $path = implode("/", $parsed);
408 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
412 * Creates an item post
414 * @param array $activity Activity data
415 * @param array $item item array
416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
417 * @throws \ImagickException
419 private static function postItem($activity, $item)
421 /// @todo What to do with $activity['context']?
422 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
423 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
427 $item['network'] = Protocol::ACTIVITYPUB;
428 $item['private'] = !in_array(0, $activity['receiver']);
429 $item['author-link'] = $activity['author'];
430 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
431 $item['owner-link'] = $activity['actor'];
432 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
436 if (!empty($activity['thread-completion'])) {
437 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
438 $item['causer-link'] = $item['owner-link'];
439 $item['causer-id'] = $item['owner-id'];
441 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
442 $item['owner-link'] = $item['author-link'];
443 $item['owner-id'] = $item['author-id'];
445 $actor = APContact::getByURL($item['owner-link'], false);
446 $isForum = ($actor['type'] == 'Group');
449 $item['uri'] = $activity['id'];
451 $item['created'] = DateTimeFormat::utc($activity['published']);
452 $item['edited'] = DateTimeFormat::utc($activity['updated']);
453 $item['guid'] = $activity['diaspora:guid'] ?: self::getGUIDByURL($item['uri']);
455 $item = self::processContent($activity, $item);
460 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
462 $item = self::constructAttachList($activity, $item);
466 foreach ($activity['receiver'] as $receiver) {
467 $item['uid'] = $receiver;
470 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
472 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
475 if (($receiver != 0) && empty($item['contact-id'])) {
476 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
479 if (!empty($activity['directmessage'])) {
480 self::postMail($activity, $item);
484 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
485 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
487 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
488 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
492 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
496 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
499 if ($activity['object_type'] == 'as:Event') {
500 self::createEvent($activity, $item);
503 $item_id = Item::insert($item);
505 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
507 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
510 if ($item['uid'] == 0) {
515 // Store send a follow request for every reshare - but only when the item had been stored
516 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
517 $author = APContact::getByURL($item['owner-link'], false);
518 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
519 if ($author['type'] != 'Group') {
520 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
521 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
527 * Creates an mail post
529 * @param array $activity Activity data
530 * @param array $item item array
531 * @return int|bool New mail table row id or false on error
532 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
534 private static function postMail($activity, $item)
536 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
537 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
541 Logger::info('Direct Message', $item);
544 $msg['uid'] = $item['uid'];
546 $msg['contact-id'] = $item['contact-id'];
548 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
549 $msg['from-name'] = $contact['name'];
550 $msg['from-url'] = $contact['url'];
551 $msg['from-photo'] = $contact['photo'];
553 $msg['uri'] = $item['uri'];
554 $msg['created'] = $item['created'];
556 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
557 if (DBA::isResult($parent)) {
558 $msg['parent-uri'] = $parent['parent-uri'];
559 $msg['title'] = $parent['title'];
561 $msg['parent-uri'] = $item['thr-parent'];
563 if (!empty($item['title'])) {
564 $msg['title'] = $item['title'];
565 } elseif (!empty($item['content-warning'])) {
566 $msg['title'] = $item['content-warning'];
568 // Trying to generate a title out of the body
569 $title = $item['body'];
571 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
572 $title = $matches[3];
575 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
577 if (strlen($title) > 20) {
578 $title = substr($title, 0, 20) . '...';
581 $msg['title'] = $title;
584 $msg['body'] = $item['body'];
586 return Mail::insert($msg);
590 * Fetches missing posts
592 * @param string $url message URL
593 * @param array $child activity array with the child of this message
594 * @return boolean success
595 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
597 public static function fetchMissingActivity($url, $child = [])
599 if (!empty($child['receiver'])) {
600 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
605 $object = ActivityPub::fetchContent($url, $uid);
606 if (empty($object)) {
607 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
611 if (empty($object['id'])) {
612 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
616 if (!empty($child['author'])) {
617 $actor = $child['author'];
618 } elseif (!empty($object['actor'])) {
619 $actor = $object['actor'];
620 } elseif (!empty($object['attributedTo'])) {
621 $actor = $object['attributedTo'];
627 if (!empty($object['published'])) {
628 $published = $object['published'];
629 } elseif (!empty($child['published'])) {
630 $published = $child['published'];
632 $published = DateTimeFormat::utcNow();
636 $activity['@context'] = $object['@context'];
637 unset($object['@context']);
638 $activity['id'] = $object['id'];
639 $activity['to'] = $object['to'] ?? [];
640 $activity['cc'] = $object['cc'] ?? [];
641 $activity['actor'] = $actor;
642 $activity['object'] = $object;
643 $activity['published'] = $published;
644 $activity['type'] = 'Create';
646 $ldactivity = JsonLD::compact($activity);
648 $ldactivity['thread-completion'] = true;
650 ActivityPub\Receiver::processActivity($ldactivity);
651 Logger::log('Activity ' . $url . ' had been fetched and processed.');
657 * perform a "follow" request
659 * @param array $activity
660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
661 * @throws \ImagickException
663 public static function followUser($activity)
665 $uid = User::getIdForURL($activity['object_id']);
670 $owner = User::getOwnerDataById($uid);
672 $cid = Contact::getIdForURL($activity['actor'], $uid);
674 self::switchContact($cid);
675 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
676 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
681 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
682 'author-link' => $activity['actor']];
684 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
686 // Ensure that the contact has got the right network type
687 self::switchContact($item['author-id']);
689 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
690 if ($result === true) {
691 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
694 $cid = Contact::getIdForURL($activity['actor'], $uid);
699 if (empty($contact)) {
700 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
703 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
707 * Update the given profile
709 * @param array $activity
712 public static function updatePerson($activity)
714 if (empty($activity['object_id'])) {
718 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
719 Contact::updateFromProbeByURL($activity['object_id'], true);
723 * Delete the given profile
725 * @param array $activity
726 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
728 public static function deletePerson($activity)
730 if (empty($activity['object_id']) || empty($activity['actor'])) {
731 Logger::log('Empty object id or actor.', Logger::DEBUG);
735 if ($activity['object_id'] != $activity['actor']) {
736 Logger::log('Object id does not match actor.', Logger::DEBUG);
740 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
741 while ($contact = DBA::fetch($contacts)) {
742 Contact::remove($contact['id']);
744 DBA::close($contacts);
746 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
750 * Accept a follow request
752 * @param array $activity
753 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
754 * @throws \ImagickException
756 public static function acceptFollowUser($activity)
758 $uid = User::getIdForURL($activity['object_actor']);
763 $cid = Contact::getIdForURL($activity['actor'], $uid);
765 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
769 self::switchContact($cid);
771 $fields = ['pending' => false];
773 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
774 if ($contact['rel'] == Contact::FOLLOWER) {
775 $fields['rel'] = Contact::FRIEND;
778 $condition = ['id' => $cid];
779 DBA::update('contact', $fields, $condition);
780 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
784 * Reject a follow request
786 * @param array $activity
787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
788 * @throws \ImagickException
790 public static function rejectFollowUser($activity)
792 $uid = User::getIdForURL($activity['object_actor']);
797 $cid = Contact::getIdForURL($activity['actor'], $uid);
799 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
803 self::switchContact($cid);
805 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
806 Contact::remove($cid);
807 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
809 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
814 * Undo activity like "like" or "dislike"
816 * @param array $activity
817 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
818 * @throws \ImagickException
820 public static function undoActivity($activity)
822 if (empty($activity['object_id'])) {
826 if (empty($activity['object_actor'])) {
830 $author_id = Contact::getIdForURL($activity['object_actor']);
831 if (empty($author_id)) {
835 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
839 * Activity to remove a follower
841 * @param array $activity
842 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
843 * @throws \ImagickException
845 public static function undoFollowUser($activity)
847 $uid = User::getIdForURL($activity['object_object']);
852 $owner = User::getOwnerDataById($uid);
854 $cid = Contact::getIdForURL($activity['actor'], $uid);
856 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
860 self::switchContact($cid);
862 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
863 if (!DBA::isResult($contact)) {
867 Contact::removeFollower($owner, $contact);
868 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
872 * Switches a contact to AP if needed
874 * @param integer $cid Contact ID
877 private static function switchContact($cid)
879 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
880 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
884 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
885 Contact::updateFromProbe($cid);
889 * Collects implicit mentions like:
890 * - the author of the parent item
891 * - all the mentioned conversants in the parent item
893 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
895 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
897 private static function getImplicitMentionList(array $parent)
899 if (DI::config()->get('system', 'disable_implicit_mentions')) {
903 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
905 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
907 $implicit_mentions = [];
908 if (empty($parent_author)) {
909 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
911 $implicit_mentions[] = $parent_author['url'];
912 $implicit_mentions[] = $parent_author['nurl'];
913 $implicit_mentions[] = $parent_author['alias'];
916 if (!empty($parent['alias'])) {
917 $implicit_mentions[] = $parent['alias'];
920 foreach ($parent_terms as $term) {
921 $contact = Contact::getDetailsByURL($term['url'], 0);
922 if (!empty($contact)) {
923 $implicit_mentions[] = $contact['url'];
924 $implicit_mentions[] = $contact['nurl'];
925 $implicit_mentions[] = $contact['alias'];
929 return $implicit_mentions;
933 * Strips from the body prepended implicit mentions
935 * @param string $body
936 * @param array $potential_mentions
939 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
941 if (DI::config()->get('system', 'disable_implicit_mentions')) {
947 // Extract one prepended mention at a time from the body
948 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
949 if (!in_array($matches[2], $potential_mentions)) {
950 $kept_mentions[] = $matches[1];
956 // Re-appending the kept mentions to the body after extraction
957 $kept_mentions[] = $body;
959 return implode('', $kept_mentions);
962 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
964 if (DI::config()->get('system', 'disable_implicit_mentions')) {
965 return $activity_tags;
968 foreach ($activity_tags as $index => $tag) {
969 if (in_array($tag['href'], $potential_mentions)) {
970 $activity_tags[$index]['name'] = preg_replace(
971 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
972 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
973 $activity_tags[$index]['name'],
979 return $activity_tags;