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;
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 * Creates an item post
395 * @param array $activity Activity data
396 * @param array $item item array
397 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
398 * @throws \ImagickException
400 private static function postItem($activity, $item)
402 /// @todo What to do with $activity['context']?
403 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
404 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
408 $item['network'] = Protocol::ACTIVITYPUB;
409 $item['private'] = !in_array(0, $activity['receiver']);
410 $item['author-link'] = $activity['author'];
411 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
412 $item['owner-link'] = $activity['actor'];
413 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
417 if (!empty($activity['thread-completion'])) {
418 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
419 $item['causer-link'] = $item['owner-link'];
420 $item['causer-id'] = $item['owner-id'];
422 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
423 $item['owner-link'] = $item['author-link'];
424 $item['owner-id'] = $item['author-id'];
426 $actor = APContact::getByURL($item['owner-link'], false);
427 $isForum = ($actor['type'] == 'Group');
430 $item['uri'] = $activity['id'];
432 $item['created'] = DateTimeFormat::utc($activity['published']);
433 $item['edited'] = DateTimeFormat::utc($activity['updated']);
434 $item['guid'] = $activity['diaspora:guid'];
436 $item = self::processContent($activity, $item);
441 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
443 $item = self::constructAttachList($activity, $item);
447 foreach ($activity['receiver'] as $receiver) {
448 $item['uid'] = $receiver;
451 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
453 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
456 if (($receiver != 0) && empty($item['contact-id'])) {
457 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
460 if (!empty($activity['directmessage'])) {
461 self::postMail($activity, $item);
465 if (PConfig::get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
466 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
468 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
469 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
473 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
477 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
480 if ($activity['object_type'] == 'as:Event') {
481 self::createEvent($activity, $item);
484 $item_id = Item::insert($item);
486 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
488 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
491 if ($item['uid'] == 0) {
496 // Store send a follow request for every reshare - but only when the item had been stored
497 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
498 $author = APContact::getByURL($item['owner-link'], false);
499 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
500 if ($author['type'] != 'Group') {
501 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
502 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
508 * Creates an mail post
510 * @param array $activity Activity data
511 * @param array $item item array
512 * @return int|bool New mail table row id or false on error
513 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
515 private static function postMail($activity, $item)
517 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
518 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
522 Logger::info('Direct Message', $item);
525 $msg['uid'] = $item['uid'];
527 $msg['contact-id'] = $item['contact-id'];
529 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
530 $msg['from-name'] = $contact['name'];
531 $msg['from-url'] = $contact['url'];
532 $msg['from-photo'] = $contact['photo'];
534 $msg['uri'] = $item['uri'];
535 $msg['created'] = $item['created'];
537 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
538 if (DBA::isResult($parent)) {
539 $msg['parent-uri'] = $parent['parent-uri'];
540 $msg['title'] = $parent['title'];
542 $msg['parent-uri'] = $item['thr-parent'];
544 if (!empty($item['title'])) {
545 $msg['title'] = $item['title'];
546 } elseif (!empty($item['content-warning'])) {
547 $msg['title'] = $item['content-warning'];
549 // Trying to generate a title out of the body
550 $title = $item['body'];
552 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
553 $title = $matches[3];
556 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
558 if (strlen($title) > 20) {
559 $title = substr($title, 0, 20) . '...';
562 $msg['title'] = $title;
565 $msg['body'] = $item['body'];
567 return Mail::insert($msg);
571 * Fetches missing posts
573 * @param string $url message URL
574 * @param array $child activity array with the child of this message
575 * @return boolean success
576 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
578 public static function fetchMissingActivity($url, $child = [])
580 if (!empty($child['receiver'])) {
581 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
586 $object = ActivityPub::fetchContent($url, $uid);
587 if (empty($object)) {
588 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
592 if (empty($object['id'])) {
593 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
597 if (!empty($child['author'])) {
598 $actor = $child['author'];
599 } elseif (!empty($object['actor'])) {
600 $actor = $object['actor'];
601 } elseif (!empty($object['attributedTo'])) {
602 $actor = $object['attributedTo'];
608 if (!empty($object['published'])) {
609 $published = $object['published'];
610 } elseif (!empty($child['published'])) {
611 $published = $child['published'];
613 $published = DateTimeFormat::utcNow();
617 $activity['@context'] = $object['@context'];
618 unset($object['@context']);
619 $activity['id'] = $object['id'];
620 $activity['to'] = $object['to'] ?? [];
621 $activity['cc'] = $object['cc'] ?? [];
622 $activity['actor'] = $actor;
623 $activity['object'] = $object;
624 $activity['published'] = $published;
625 $activity['type'] = 'Create';
627 $ldactivity = JsonLD::compact($activity);
629 $ldactivity['thread-completion'] = true;
631 ActivityPub\Receiver::processActivity($ldactivity);
632 Logger::log('Activity ' . $url . ' had been fetched and processed.');
638 * perform a "follow" request
640 * @param array $activity
641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
642 * @throws \ImagickException
644 public static function followUser($activity)
646 $uid = User::getIdForURL($activity['object_id']);
651 $owner = User::getOwnerDataById($uid);
653 $cid = Contact::getIdForURL($activity['actor'], $uid);
655 self::switchContact($cid);
656 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
657 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
662 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
663 'author-link' => $activity['actor']];
665 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
667 // Ensure that the contact has got the right network type
668 self::switchContact($item['author-id']);
670 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
671 if ($result === true) {
672 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
675 $cid = Contact::getIdForURL($activity['actor'], $uid);
680 if (empty($contact)) {
681 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
684 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
688 * Update the given profile
690 * @param array $activity
693 public static function updatePerson($activity)
695 if (empty($activity['object_id'])) {
699 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
700 Contact::updateFromProbeByURL($activity['object_id'], true);
704 * Delete the given profile
706 * @param array $activity
707 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
709 public static function deletePerson($activity)
711 if (empty($activity['object_id']) || empty($activity['actor'])) {
712 Logger::log('Empty object id or actor.', Logger::DEBUG);
716 if ($activity['object_id'] != $activity['actor']) {
717 Logger::log('Object id does not match actor.', Logger::DEBUG);
721 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
722 while ($contact = DBA::fetch($contacts)) {
723 Contact::remove($contact['id']);
725 DBA::close($contacts);
727 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
731 * Accept a follow request
733 * @param array $activity
734 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
735 * @throws \ImagickException
737 public static function acceptFollowUser($activity)
739 $uid = User::getIdForURL($activity['object_actor']);
744 $cid = Contact::getIdForURL($activity['actor'], $uid);
746 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
750 self::switchContact($cid);
752 $fields = ['pending' => false];
754 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
755 if ($contact['rel'] == Contact::FOLLOWER) {
756 $fields['rel'] = Contact::FRIEND;
759 $condition = ['id' => $cid];
760 DBA::update('contact', $fields, $condition);
761 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
765 * Reject a follow request
767 * @param array $activity
768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
769 * @throws \ImagickException
771 public static function rejectFollowUser($activity)
773 $uid = User::getIdForURL($activity['object_actor']);
778 $cid = Contact::getIdForURL($activity['actor'], $uid);
780 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
784 self::switchContact($cid);
786 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
787 Contact::remove($cid);
788 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
790 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
795 * Undo activity like "like" or "dislike"
797 * @param array $activity
798 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
799 * @throws \ImagickException
801 public static function undoActivity($activity)
803 if (empty($activity['object_id'])) {
807 if (empty($activity['object_actor'])) {
811 $author_id = Contact::getIdForURL($activity['object_actor']);
812 if (empty($author_id)) {
816 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
820 * Activity to remove a follower
822 * @param array $activity
823 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
824 * @throws \ImagickException
826 public static function undoFollowUser($activity)
828 $uid = User::getIdForURL($activity['object_object']);
833 $owner = User::getOwnerDataById($uid);
835 $cid = Contact::getIdForURL($activity['actor'], $uid);
837 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
841 self::switchContact($cid);
843 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
844 if (!DBA::isResult($contact)) {
848 Contact::removeFollower($owner, $contact);
849 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
853 * Switches a contact to AP if needed
855 * @param integer $cid Contact ID
858 private static function switchContact($cid)
860 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
861 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
865 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
866 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
870 * Collects implicit mentions like:
871 * - the author of the parent item
872 * - all the mentioned conversants in the parent item
874 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
876 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
878 private static function getImplicitMentionList(array $parent)
880 if (Config::get('system', 'disable_implicit_mentions')) {
884 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
886 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
888 $implicit_mentions = [];
889 if (empty($parent_author)) {
890 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
892 $implicit_mentions[] = $parent_author['url'];
893 $implicit_mentions[] = $parent_author['nurl'];
894 $implicit_mentions[] = $parent_author['alias'];
897 if (!empty($parent['alias'])) {
898 $implicit_mentions[] = $parent['alias'];
901 foreach ($parent_terms as $term) {
902 $contact = Contact::getDetailsByURL($term['url'], 0);
903 if (!empty($contact)) {
904 $implicit_mentions[] = $contact['url'];
905 $implicit_mentions[] = $contact['nurl'];
906 $implicit_mentions[] = $contact['alias'];
910 return $implicit_mentions;
914 * Strips from the body prepended implicit mentions
916 * @param string $body
917 * @param array $potential_mentions
920 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
922 if (Config::get('system', 'disable_implicit_mentions')) {
928 // Extract one prepended mention at a time from the body
929 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
930 if (!in_array($matches[2], $potential_mentions)) {
931 $kept_mentions[] = $matches[1];
937 // Re-appending the kept mentions to the body after extraction
938 $kept_mentions[] = $body;
940 return implode('', $kept_mentions);
943 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
945 if (Config::get('system', 'disable_implicit_mentions')) {
946 return $activity_tags;
949 foreach ($activity_tags as $index => $tag) {
950 if (in_array($tag['href'], $potential_mentions)) {
951 $activity_tags[$index]['name'] = preg_replace(
952 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
953 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
954 $activity_tags[$index]['name'],
960 return $activity_tags;