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 $attachments
98 * @param boolean $no_images
100 * @return array array
102 private static function constructAttachList($attachments, $item, $no_images)
104 if (empty($attachments)) {
108 foreach ($attachments as $attach) {
109 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
110 if ($filetype == 'image') {
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;
182 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
183 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
184 self::fetchMissingActivity($activity['reply-to-id'], $activity);
187 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
189 self::postItem($activity, $item);
195 * @param array $activity
196 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
197 * @throws \ImagickException
199 public static function deleteItem($activity)
201 $owner = Contact::getIdForURL($activity['actor']);
203 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
204 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
208 * Prepare the item array for an activity
210 * @param array $activity Activity array
211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
212 * @throws \ImagickException
214 public static function addTag($activity)
216 if (empty($activity['object_content']) || empty($activity['object_id'])) {
220 foreach ($activity['receiver'] as $receiver) {
221 $item = Item::selectFirst(['id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
222 if (!DBA::isResult($item)) {
223 // We don't fetch missing content for this purpose
227 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
228 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
233 // - Check if "blocktag" is set
234 // - Check if actor is a contact
236 if (!stristr($item['tag'], trim($activity['object_content']))) {
237 $tag = $item['tag'] . (strlen($item['tag']) ? ',' : '') . '#[url=' . $activity['object_id'] . ']'. $activity['object_content'] . '[/url]';
238 Item::update(['tag' => $tag], ['id' => $item['id']]);
239 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
245 * Prepare the item array for an activity
247 * @param array $activity Activity array
248 * @param string $verb Activity verb
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 * @throws \ImagickException
252 public static function createActivity($activity, $verb)
255 $item['verb'] = $verb;
256 $item['thr-parent'] = $activity['object_id'];
257 $item['gravity'] = GRAVITY_ACTIVITY;
258 $item['object-type'] = Activity\ObjectType::NOTE;
260 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
262 self::postItem($activity, $item);
268 * @param array $activity Activity array
272 public static function createEvent($activity, $item)
274 $event['summary'] = HTML::toBBCode($activity['name']);
275 $event['desc'] = HTML::toBBCode($activity['content']);
276 $event['start'] = $activity['start-time'];
277 $event['finish'] = $activity['end-time'];
278 $event['nofinish'] = empty($event['finish']);
279 $event['location'] = $activity['location'];
280 $event['adjust'] = true;
281 $event['cid'] = $item['contact-id'];
282 $event['uid'] = $item['uid'];
283 $event['uri'] = $item['uri'];
284 $event['edited'] = $item['edited'];
285 $event['private'] = $item['private'];
286 $event['guid'] = $item['guid'];
287 $event['plink'] = $item['plink'];
289 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
290 $ev = DBA::selectFirst('event', ['id'], $condition);
291 if (DBA::isResult($ev)) {
292 $event['id'] = $ev['id'];
295 $event_id = Event::store($event);
296 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
300 * Process the content
302 * @param array $activity Activity array
304 * @return array|bool Returns the item array or false if there was an unexpected occurrence
307 private static function processContent($activity, $item)
309 $item['title'] = HTML::toBBCode($activity['name']);
311 if (!empty($activity['source'])) {
312 $item['body'] = $activity['source'];
314 $content = HTML::toBBCode($activity['content']);
316 if (!empty($activity['emojis'])) {
317 $content = self::replaceEmojis($content, $activity['emojis']);
320 $content = self::convertMentions($content);
322 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
323 $item_private = !in_array(0, $activity['item_receiver']);
324 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
325 if (!DBA::isResult($parent)) {
326 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
329 if ($item_private && !$parent['private']) {
330 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
334 $potential_implicit_mentions = self::getImplicitMentionList($parent);
335 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
336 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
338 $item['content-warning'] = HTML::toBBCode($activity['summary']);
339 $item['body'] = $content;
341 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
342 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
346 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
348 $item['location'] = $activity['location'];
350 if (!empty($item['latitude']) && !empty($item['longitude'])) {
351 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
354 $item['app'] = $activity['generator'];
360 * Creates an item post
362 * @param array $activity Activity data
363 * @param array $item item array
364 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
365 * @throws \ImagickException
367 private static function postItem($activity, $item)
369 /// @todo What to do with $activity['context']?
370 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
371 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
375 $item['network'] = Protocol::ACTIVITYPUB;
376 $item['private'] = !in_array(0, $activity['receiver']);
377 $item['author-link'] = $activity['author'];
378 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
379 $item['owner-link'] = $activity['actor'];
380 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
384 if (!empty($activity['thread-completion'])) {
385 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
386 $item['causer-link'] = $item['owner-link'];
387 $item['causer-id'] = $item['owner-id'];
389 Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
390 $item['owner-link'] = $item['author-link'];
391 $item['owner-id'] = $item['author-id'];
393 $actor = APContact::getByURL($item['owner-link'], false);
394 $isForum = ($actor['type'] == 'Group');
397 $item['uri'] = $activity['id'];
399 $item['created'] = DateTimeFormat::utc($activity['published']);
400 $item['edited'] = DateTimeFormat::utc($activity['updated']);
401 $item['guid'] = $activity['diaspora:guid'];
403 $item = self::processContent($activity, $item);
408 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
410 $item = self::constructAttachList($activity['attachments'], $item, !empty($activity['source']));
414 foreach ($activity['receiver'] as $receiver) {
415 $item['uid'] = $receiver;
418 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
420 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
423 if (($receiver != 0) && empty($item['contact-id'])) {
424 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
427 if (!empty($activity['directmessage'])) {
428 self::postMail($activity, $item);
432 if (PConfig::get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
433 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
435 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
436 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
440 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
444 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
447 if ($activity['object_type'] == 'as:Event') {
448 self::createEvent($activity, $item);
451 $item_id = Item::insert($item);
453 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
455 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
458 if ($item['uid'] == 0) {
463 // Store send a follow request for every reshare - but only when the item had been stored
464 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
465 $author = APContact::getByURL($item['owner-link'], false);
466 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
467 if ($author['type'] != 'Group') {
468 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
469 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
475 * Creates an mail post
477 * @param array $activity Activity data
478 * @param array $item item array
479 * @return int|bool New mail table row id or false on error
480 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
482 private static function postMail($activity, $item)
484 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
485 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
489 Logger::info('Direct Message', $item);
492 $msg['uid'] = $item['uid'];
494 $msg['contact-id'] = $item['contact-id'];
496 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
497 $msg['from-name'] = $contact['name'];
498 $msg['from-url'] = $contact['url'];
499 $msg['from-photo'] = $contact['photo'];
501 $msg['uri'] = $item['uri'];
502 $msg['created'] = $item['created'];
504 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
505 if (DBA::isResult($parent)) {
506 $msg['parent-uri'] = $parent['parent-uri'];
507 $msg['title'] = $parent['title'];
509 $msg['parent-uri'] = $item['thr-parent'];
511 if (!empty($item['title'])) {
512 $msg['title'] = $item['title'];
513 } elseif (!empty($item['content-warning'])) {
514 $msg['title'] = $item['content-warning'];
516 // Trying to generate a title out of the body
517 $title = $item['body'];
519 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
520 $title = $matches[3];
523 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
525 if (strlen($title) > 20) {
526 $title = substr($title, 0, 20) . '...';
529 $msg['title'] = $title;
532 $msg['body'] = $item['body'];
534 return Mail::insert($msg);
538 * Fetches missing posts
540 * @param string $url message URL
541 * @param array $child activity array with the child of this message
542 * @return boolean success
543 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
545 public static function fetchMissingActivity($url, $child = [])
547 if (!empty($child['receiver'])) {
548 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
553 $object = ActivityPub::fetchContent($url, $uid);
554 if (empty($object)) {
555 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
559 if (empty($object['id'])) {
560 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
564 if (!empty($child['author'])) {
565 $actor = $child['author'];
566 } elseif (!empty($object['actor'])) {
567 $actor = $object['actor'];
568 } elseif (!empty($object['attributedTo'])) {
569 $actor = $object['attributedTo'];
575 if (!empty($object['published'])) {
576 $published = $object['published'];
577 } elseif (!empty($child['published'])) {
578 $published = $child['published'];
580 $published = DateTimeFormat::utcNow();
584 $activity['@context'] = $object['@context'];
585 unset($object['@context']);
586 $activity['id'] = $object['id'];
587 $activity['to'] = $object['to'] ?? [];
588 $activity['cc'] = $object['cc'] ?? [];
589 $activity['actor'] = $actor;
590 $activity['object'] = $object;
591 $activity['published'] = $published;
592 $activity['type'] = 'Create';
594 $ldactivity = JsonLD::compact($activity);
596 $ldactivity['thread-completion'] = true;
598 ActivityPub\Receiver::processActivity($ldactivity);
599 Logger::log('Activity ' . $url . ' had been fetched and processed.');
605 * perform a "follow" request
607 * @param array $activity
608 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
609 * @throws \ImagickException
611 public static function followUser($activity)
613 $uid = User::getIdForURL($activity['object_id']);
618 $owner = User::getOwnerDataById($uid);
620 $cid = Contact::getIdForURL($activity['actor'], $uid);
622 self::switchContact($cid);
623 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
624 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
629 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
630 'author-link' => $activity['actor']];
632 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
634 // Ensure that the contact has got the right network type
635 self::switchContact($item['author-id']);
637 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
638 if ($result === true) {
639 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
642 $cid = Contact::getIdForURL($activity['actor'], $uid);
647 if (empty($contact)) {
648 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
651 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
655 * Update the given profile
657 * @param array $activity
660 public static function updatePerson($activity)
662 if (empty($activity['object_id'])) {
666 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
667 Contact::updateFromProbeByURL($activity['object_id'], true);
671 * Delete the given profile
673 * @param array $activity
674 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
676 public static function deletePerson($activity)
678 if (empty($activity['object_id']) || empty($activity['actor'])) {
679 Logger::log('Empty object id or actor.', Logger::DEBUG);
683 if ($activity['object_id'] != $activity['actor']) {
684 Logger::log('Object id does not match actor.', Logger::DEBUG);
688 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
689 while ($contact = DBA::fetch($contacts)) {
690 Contact::remove($contact['id']);
692 DBA::close($contacts);
694 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
698 * Accept a follow request
700 * @param array $activity
701 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
702 * @throws \ImagickException
704 public static function acceptFollowUser($activity)
706 $uid = User::getIdForURL($activity['object_actor']);
711 $cid = Contact::getIdForURL($activity['actor'], $uid);
713 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
717 self::switchContact($cid);
719 $fields = ['pending' => false];
721 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
722 if ($contact['rel'] == Contact::FOLLOWER) {
723 $fields['rel'] = Contact::FRIEND;
726 $condition = ['id' => $cid];
727 DBA::update('contact', $fields, $condition);
728 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
732 * Reject a follow request
734 * @param array $activity
735 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
736 * @throws \ImagickException
738 public static function rejectFollowUser($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 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
754 Contact::remove($cid);
755 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
757 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
762 * Undo activity like "like" or "dislike"
764 * @param array $activity
765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
766 * @throws \ImagickException
768 public static function undoActivity($activity)
770 if (empty($activity['object_id'])) {
774 if (empty($activity['object_actor'])) {
778 $author_id = Contact::getIdForURL($activity['object_actor']);
779 if (empty($author_id)) {
783 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
787 * Activity to remove a follower
789 * @param array $activity
790 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
791 * @throws \ImagickException
793 public static function undoFollowUser($activity)
795 $uid = User::getIdForURL($activity['object_object']);
800 $owner = User::getOwnerDataById($uid);
802 $cid = Contact::getIdForURL($activity['actor'], $uid);
804 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
808 self::switchContact($cid);
810 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
811 if (!DBA::isResult($contact)) {
815 Contact::removeFollower($owner, $contact);
816 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
820 * Switches a contact to AP if needed
822 * @param integer $cid Contact ID
825 private static function switchContact($cid)
827 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
828 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
832 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
833 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
837 * Collects implicit mentions like:
838 * - the author of the parent item
839 * - all the mentioned conversants in the parent item
841 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
843 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
845 private static function getImplicitMentionList(array $parent)
847 if (Config::get('system', 'disable_implicit_mentions')) {
851 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
853 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
855 $implicit_mentions = [];
856 if (empty($parent_author)) {
857 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
859 $implicit_mentions[] = $parent_author['url'];
860 $implicit_mentions[] = $parent_author['nurl'];
861 $implicit_mentions[] = $parent_author['alias'];
864 if (!empty($parent['alias'])) {
865 $implicit_mentions[] = $parent['alias'];
868 foreach ($parent_terms as $term) {
869 $contact = Contact::getDetailsByURL($term['url'], 0);
870 if (!empty($contact)) {
871 $implicit_mentions[] = $contact['url'];
872 $implicit_mentions[] = $contact['nurl'];
873 $implicit_mentions[] = $contact['alias'];
877 return $implicit_mentions;
881 * Strips from the body prepended implicit mentions
883 * @param string $body
884 * @param array $potential_mentions
887 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
889 if (Config::get('system', 'disable_implicit_mentions')) {
895 // Extract one prepended mention at a time from the body
896 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
897 if (!in_array($matches[2], $potential_mentions)) {
898 $kept_mentions[] = $matches[1];
904 // Re-appending the kept mentions to the body after extraction
905 $kept_mentions[] = $body;
907 return implode('', $kept_mentions);
910 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
912 if (Config::get('system', 'disable_implicit_mentions')) {
913 return $activity_tags;
916 foreach ($activity_tags as $index => $tag) {
917 if (in_array($tag['href'], $potential_mentions)) {
918 $activity_tags[$index]['name'] = preg_replace(
919 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
920 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
921 $activity_tags[$index]['name'],
927 return $activity_tags;