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\PConfig;
12 use Friendica\Core\Protocol;
13 use Friendica\Database\DBA;
15 use Friendica\Model\APContact;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Event;
18 use Friendica\Model\Item;
19 use Friendica\Model\Mail;
20 use Friendica\Model\Term;
21 use Friendica\Model\User;
22 use Friendica\Protocol\Activity;
23 use Friendica\Protocol\ActivityPub;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\JsonLD;
26 use Friendica\Util\Strings;
29 * ActivityPub Processor Protocol class
34 * Converts mentions from Pleroma into the Friendica format
38 * @return string converted body
40 private static function convertMentions($body)
42 $URLSearchString = "^\[\]";
43 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
49 * Replaces emojis in the body
51 * @param array $emojis
54 * @return string with replaced emojis
56 private static function replaceEmojis($body, array $emojis)
58 foreach ($emojis as $emoji) {
59 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
60 $body = str_replace($emoji['name'], $replace, $body);
66 * Constructs a string with tags for a given tag array
69 * @param boolean $sensitive
70 * @return string with tags
72 private static function constructTagString(array $tags = null, $sensitive = false)
79 foreach ($tags as $tag) {
80 if (in_array($tag['type'] ?? '', ['Mention', 'Hashtag'])) {
81 if (!empty($tag_text)) {
85 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
89 /// @todo add nsfw for $sensitive
95 * Add attachment data to the item array
97 * @param array $activity
100 * @return array array
102 private static function constructAttachList($activity, $item)
104 if (empty($activity['attachments'])) {
108 foreach ($activity['attachments'] as $attach) {
109 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
110 if ($filetype == 'image') {
111 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
115 if (empty($attach['name'])) {
116 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
118 $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
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', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
145 if (!DBA::isResult($item)) {
146 Logger::warning('Unknown item', ['uri' => $activity['id']]);
150 $item['changed'] = DateTimeFormat::utcNow();
151 $item['edited'] = DateTimeFormat::utc($activity['updated']);
153 $item = self::processContent($activity, $item);
158 Item::update($item, ['uri' => $activity['id']]);
162 * Prepares data for a message
164 * @param array $activity Activity array
165 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
166 * @throws \ImagickException
168 public static function createItem($activity)
171 $item['verb'] = Activity::POST;
172 $item['thr-parent'] = $activity['reply-to-id'];
174 if ($activity['reply-to-id'] == $activity['id']) {
175 $item['gravity'] = GRAVITY_PARENT;
176 $item['object-type'] = Activity\ObjectType::NOTE;
178 $item['gravity'] = GRAVITY_COMMENT;
179 $item['object-type'] = Activity\ObjectType::COMMENT;
181 // Ensure that the comment reaches all receivers of the referring post
182 $activity['receiver'] = self::addReceivers($activity);
185 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
186 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
187 self::fetchMissingActivity($activity['reply-to-id'], $activity);
190 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
192 self::postItem($activity, $item);
198 * @param array $activity
199 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
200 * @throws \ImagickException
202 public static function deleteItem($activity)
204 $owner = Contact::getIdForURL($activity['actor']);
206 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
207 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
211 * Prepare the item array for an activity
213 * @param array $activity Activity array
214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
215 * @throws \ImagickException
217 public static function addTag($activity)
219 if (empty($activity['object_content']) || empty($activity['object_id'])) {
223 foreach ($activity['receiver'] as $receiver) {
224 $item = Item::selectFirst(['id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
225 if (!DBA::isResult($item)) {
226 // We don't fetch missing content for this purpose
230 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
231 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
236 // - Check if "blocktag" is set
237 // - Check if actor is a contact
239 if (!stristr($item['tag'], trim($activity['object_content']))) {
240 $tag = $item['tag'] . (strlen($item['tag']) ? ',' : '') . '#[url=' . $activity['object_id'] . ']'. $activity['object_content'] . '[/url]';
241 Item::update(['tag' => $tag], ['id' => $item['id']]);
242 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
248 * Add users to the receiver list of the given public activity.
249 * This is used to ensure that the activity will be stored in every thread.
251 * @param array $activity Activity array
252 * @return array Modified receiver list
254 private static function addReceivers(array $activity)
256 if (!in_array(0, $activity['receiver'])) {
257 // Private activities will not be modified
258 return $activity['receiver'];
261 // Add all owners of the referring item to the receivers
262 $original = $receivers = $activity['receiver'];
263 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
264 while ($item = DBA::fetch($items)) {
265 $receivers['uid:' . $item['uid']] = $item['uid'];
269 if (count($original) != count($receivers)) {
270 Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
277 * Prepare the item array for an activity
279 * @param array $activity Activity array
280 * @param string $verb Activity verb
281 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
282 * @throws \ImagickException
284 public static function createActivity($activity, $verb)
287 $item['verb'] = $verb;
288 $item['thr-parent'] = $activity['object_id'];
289 $item['gravity'] = GRAVITY_ACTIVITY;
290 $item['object-type'] = Activity\ObjectType::NOTE;
292 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
294 $activity['receiver'] = self::addReceivers($activity);
296 self::postItem($activity, $item);
302 * @param array $activity Activity array
306 public static function createEvent($activity, $item)
308 $event['summary'] = HTML::toBBCode($activity['name']);
309 $event['desc'] = HTML::toBBCode($activity['content']);
310 $event['start'] = $activity['start-time'];
311 $event['finish'] = $activity['end-time'];
312 $event['nofinish'] = empty($event['finish']);
313 $event['location'] = $activity['location'];
314 $event['adjust'] = true;
315 $event['cid'] = $item['contact-id'];
316 $event['uid'] = $item['uid'];
317 $event['uri'] = $item['uri'];
318 $event['edited'] = $item['edited'];
319 $event['private'] = $item['private'];
320 $event['guid'] = $item['guid'];
321 $event['plink'] = $item['plink'];
323 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
324 $ev = DBA::selectFirst('event', ['id'], $condition);
325 if (DBA::isResult($ev)) {
326 $event['id'] = $ev['id'];
329 $event_id = Event::store($event);
330 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
334 * Process the content
336 * @param array $activity Activity array
338 * @return array|bool Returns the item array or false if there was an unexpected occurrence
341 private static function processContent($activity, $item)
343 $item['title'] = HTML::toBBCode($activity['name']);
345 if (!empty($activity['source'])) {
346 $item['body'] = $activity['source'];
348 $content = HTML::toBBCode($activity['content']);
350 if (!empty($activity['emojis'])) {
351 $content = self::replaceEmojis($content, $activity['emojis']);
354 $content = self::convertMentions($content);
356 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
357 $item_private = !in_array(0, $activity['item_receiver']);
358 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
359 if (!DBA::isResult($parent)) {
360 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
363 if ($item_private && !$parent['private']) {
364 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
368 $potential_implicit_mentions = self::getImplicitMentionList($parent);
369 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
370 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
372 $item['content-warning'] = HTML::toBBCode($activity['summary']);
373 $item['body'] = $content;
375 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
376 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
380 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
382 $item['location'] = $activity['location'];
384 if (!empty($item['latitude']) && !empty($item['longitude'])) {
385 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
388 $item['app'] = $activity['generator'];
394 * Creates an item post
396 * @param array $activity Activity data
397 * @param array $item item array
398 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
399 * @throws \ImagickException
401 private static function postItem($activity, $item)
403 /// @todo What to do with $activity['context']?
404 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
405 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
409 $item['network'] = Protocol::ACTIVITYPUB;
410 $item['private'] = !in_array(0, $activity['receiver']);
411 $item['author-link'] = $activity['author'];
412 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
413 $item['owner-link'] = $activity['actor'];
414 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
418 if (!empty($activity['thread-completion'])) {
419 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
420 $item['causer-link'] = $item['owner-link'];
421 $item['causer-id'] = $item['owner-id'];
423 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
424 $item['owner-link'] = $item['author-link'];
425 $item['owner-id'] = $item['author-id'];
427 $actor = APContact::getByURL($item['owner-link'], false);
428 $isForum = ($actor['type'] == 'Group');
431 $item['uri'] = $activity['id'];
433 $item['created'] = DateTimeFormat::utc($activity['published']);
434 $item['edited'] = DateTimeFormat::utc($activity['updated']);
435 $item['guid'] = $activity['diaspora:guid'];
437 $item = self::processContent($activity, $item);
442 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
444 $item = self::constructAttachList($activity, $item);
448 foreach ($activity['receiver'] as $receiver) {
449 $item['uid'] = $receiver;
452 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
454 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
457 if (($receiver != 0) && empty($item['contact-id'])) {
458 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
461 if (!empty($activity['directmessage'])) {
462 self::postMail($activity, $item);
466 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
467 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
469 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
470 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
474 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
478 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
481 if ($activity['object_type'] == 'as:Event') {
482 self::createEvent($activity, $item);
485 $item_id = Item::insert($item);
487 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
489 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
492 if ($item['uid'] == 0) {
497 // Store send a follow request for every reshare - but only when the item had been stored
498 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
499 $author = APContact::getByURL($item['owner-link'], false);
500 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
501 if ($author['type'] != 'Group') {
502 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
503 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
509 * Creates an mail post
511 * @param array $activity Activity data
512 * @param array $item item array
513 * @return int|bool New mail table row id or false on error
514 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
516 private static function postMail($activity, $item)
518 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
519 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
523 Logger::info('Direct Message', $item);
526 $msg['uid'] = $item['uid'];
528 $msg['contact-id'] = $item['contact-id'];
530 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
531 $msg['from-name'] = $contact['name'];
532 $msg['from-url'] = $contact['url'];
533 $msg['from-photo'] = $contact['photo'];
535 $msg['uri'] = $item['uri'];
536 $msg['created'] = $item['created'];
538 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
539 if (DBA::isResult($parent)) {
540 $msg['parent-uri'] = $parent['parent-uri'];
541 $msg['title'] = $parent['title'];
543 $msg['parent-uri'] = $item['thr-parent'];
545 if (!empty($item['title'])) {
546 $msg['title'] = $item['title'];
547 } elseif (!empty($item['content-warning'])) {
548 $msg['title'] = $item['content-warning'];
550 // Trying to generate a title out of the body
551 $title = $item['body'];
553 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
554 $title = $matches[3];
557 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
559 if (strlen($title) > 20) {
560 $title = substr($title, 0, 20) . '...';
563 $msg['title'] = $title;
566 $msg['body'] = $item['body'];
568 return Mail::insert($msg);
572 * Fetches missing posts
574 * @param string $url message URL
575 * @param array $child activity array with the child of this message
576 * @return boolean success
577 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
579 public static function fetchMissingActivity($url, $child = [])
581 if (!empty($child['receiver'])) {
582 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
587 $object = ActivityPub::fetchContent($url, $uid);
588 if (empty($object)) {
589 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
593 if (empty($object['id'])) {
594 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
598 if (!empty($child['author'])) {
599 $actor = $child['author'];
600 } elseif (!empty($object['actor'])) {
601 $actor = $object['actor'];
602 } elseif (!empty($object['attributedTo'])) {
603 $actor = $object['attributedTo'];
609 if (!empty($object['published'])) {
610 $published = $object['published'];
611 } elseif (!empty($child['published'])) {
612 $published = $child['published'];
614 $published = DateTimeFormat::utcNow();
618 $activity['@context'] = $object['@context'];
619 unset($object['@context']);
620 $activity['id'] = $object['id'];
621 $activity['to'] = $object['to'] ?? [];
622 $activity['cc'] = $object['cc'] ?? [];
623 $activity['actor'] = $actor;
624 $activity['object'] = $object;
625 $activity['published'] = $published;
626 $activity['type'] = 'Create';
628 $ldactivity = JsonLD::compact($activity);
630 $ldactivity['thread-completion'] = true;
632 ActivityPub\Receiver::processActivity($ldactivity);
633 Logger::log('Activity ' . $url . ' had been fetched and processed.');
639 * perform a "follow" request
641 * @param array $activity
642 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
643 * @throws \ImagickException
645 public static function followUser($activity)
647 $uid = User::getIdForURL($activity['object_id']);
652 $owner = User::getOwnerDataById($uid);
654 $cid = Contact::getIdForURL($activity['actor'], $uid);
656 self::switchContact($cid);
657 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
658 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
663 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
664 'author-link' => $activity['actor']];
666 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
668 // Ensure that the contact has got the right network type
669 self::switchContact($item['author-id']);
671 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
672 if ($result === true) {
673 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
676 $cid = Contact::getIdForURL($activity['actor'], $uid);
681 if (empty($contact)) {
682 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
685 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
689 * Update the given profile
691 * @param array $activity
694 public static function updatePerson($activity)
696 if (empty($activity['object_id'])) {
700 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
701 Contact::updateFromProbeByURL($activity['object_id'], true);
705 * Delete the given profile
707 * @param array $activity
708 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
710 public static function deletePerson($activity)
712 if (empty($activity['object_id']) || empty($activity['actor'])) {
713 Logger::log('Empty object id or actor.', Logger::DEBUG);
717 if ($activity['object_id'] != $activity['actor']) {
718 Logger::log('Object id does not match actor.', Logger::DEBUG);
722 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
723 while ($contact = DBA::fetch($contacts)) {
724 Contact::remove($contact['id']);
726 DBA::close($contacts);
728 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
732 * Accept a follow request
734 * @param array $activity
735 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
736 * @throws \ImagickException
738 public static function acceptFollowUser($activity)
740 $uid = User::getIdForURL($activity['object_actor']);
745 $cid = Contact::getIdForURL($activity['actor'], $uid);
747 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
751 self::switchContact($cid);
753 $fields = ['pending' => false];
755 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
756 if ($contact['rel'] == Contact::FOLLOWER) {
757 $fields['rel'] = Contact::FRIEND;
760 $condition = ['id' => $cid];
761 DBA::update('contact', $fields, $condition);
762 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
766 * Reject a follow request
768 * @param array $activity
769 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
770 * @throws \ImagickException
772 public static function rejectFollowUser($activity)
774 $uid = User::getIdForURL($activity['object_actor']);
779 $cid = Contact::getIdForURL($activity['actor'], $uid);
781 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
785 self::switchContact($cid);
787 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
788 Contact::remove($cid);
789 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
791 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
796 * Undo activity like "like" or "dislike"
798 * @param array $activity
799 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
800 * @throws \ImagickException
802 public static function undoActivity($activity)
804 if (empty($activity['object_id'])) {
808 if (empty($activity['object_actor'])) {
812 $author_id = Contact::getIdForURL($activity['object_actor']);
813 if (empty($author_id)) {
817 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
821 * Activity to remove a follower
823 * @param array $activity
824 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
825 * @throws \ImagickException
827 public static function undoFollowUser($activity)
829 $uid = User::getIdForURL($activity['object_object']);
834 $owner = User::getOwnerDataById($uid);
836 $cid = Contact::getIdForURL($activity['actor'], $uid);
838 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
842 self::switchContact($cid);
844 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
845 if (!DBA::isResult($contact)) {
849 Contact::removeFollower($owner, $contact);
850 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
854 * Switches a contact to AP if needed
856 * @param integer $cid Contact ID
859 private static function switchContact($cid)
861 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
862 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
866 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
867 Contact::updateFromProbe($cid);
871 * Collects implicit mentions like:
872 * - the author of the parent item
873 * - all the mentioned conversants in the parent item
875 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
877 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
879 private static function getImplicitMentionList(array $parent)
881 if (Config::get('system', 'disable_implicit_mentions')) {
885 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
887 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
889 $implicit_mentions = [];
890 if (empty($parent_author)) {
891 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
893 $implicit_mentions[] = $parent_author['url'];
894 $implicit_mentions[] = $parent_author['nurl'];
895 $implicit_mentions[] = $parent_author['alias'];
898 if (!empty($parent['alias'])) {
899 $implicit_mentions[] = $parent['alias'];
902 foreach ($parent_terms as $term) {
903 $contact = Contact::getDetailsByURL($term['url'], 0);
904 if (!empty($contact)) {
905 $implicit_mentions[] = $contact['url'];
906 $implicit_mentions[] = $contact['nurl'];
907 $implicit_mentions[] = $contact['alias'];
911 return $implicit_mentions;
915 * Strips from the body prepended implicit mentions
917 * @param string $body
918 * @param array $potential_mentions
921 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
923 if (Config::get('system', 'disable_implicit_mentions')) {
929 // Extract one prepended mention at a time from the body
930 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
931 if (!in_array($matches[2], $potential_mentions)) {
932 $kept_mentions[] = $matches[1];
938 // Re-appending the kept mentions to the body after extraction
939 $kept_mentions[] = $body;
941 return implode('', $kept_mentions);
944 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
946 if (Config::get('system', 'disable_implicit_mentions')) {
947 return $activity_tags;
950 foreach ($activity_tags as $index => $tag) {
951 if (in_array($tag['href'], $potential_mentions)) {
952 $activity_tags[$index]['name'] = preg_replace(
953 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
954 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
955 $activity_tags[$index]['name'],
961 return $activity_tags;