This now should really prevent sending the follow requests only once
[friendica.git/.git] / src / Protocol / ActivityPub / Processor.php
1 <?php
2 /**
3  * @file src/Protocol/ActivityPub/Processor.php
4  */
5 namespace Friendica\Protocol\ActivityPub;
6
7 use Friendica\Database\DBA;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Model\Contact;
13 use Friendica\Model\APContact;
14 use Friendica\Model\Item;
15 use Friendica\Model\Event;
16 use Friendica\Model\Term;
17 use Friendica\Model\User;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\JsonLD;
21 use Friendica\Util\Strings;
22
23 /**
24  * ActivityPub Processor Protocol class
25  */
26 class Processor
27 {
28         /**
29          * Converts mentions from Pleroma into the Friendica format
30          *
31          * @param string $body
32          *
33          * @return string converted body
34          */
35         private static function convertMentions($body)
36         {
37                 $URLSearchString = "^\[\]";
38                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
39
40                 return $body;
41         }
42
43         /**
44          * Replaces emojis in the body
45          *
46          * @param array $emojis
47          * @param string $body
48          *
49          * @return string with replaced emojis
50          */
51         public static function replaceEmojis($body, array $emojis)
52         {
53                 foreach ($emojis as $emoji) {
54                         $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
55                         $body = str_replace($emoji['name'], $replace, $body);
56                 }
57                 return $body;
58         }
59
60         /**
61          * Constructs a string with tags for a given tag array
62          *
63          * @param array   $tags
64          * @param boolean $sensitive
65          * @param array   $implicit_mentions List of profile URLs to skip
66          * @return string with tags
67          */
68         private static function constructTagString($tags, $sensitive, array $implicit_mentions)
69         {
70                 if (empty($tags)) {
71                         return '';
72                 }
73
74                 $tag_text = '';
75                 foreach ($tags as $tag) {
76                         if (in_array(defaults($tag, 'type', ''), ['Mention', 'Hashtag']) && !in_array($tag['href'], $implicit_mentions)) {
77                                 if (!empty($tag_text)) {
78                                         $tag_text .= ',';
79                                 }
80
81                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
82                         }
83                 }
84
85                 /// @todo add nsfw for $sensitive
86
87                 return $tag_text;
88         }
89
90         /**
91          * Add attachment data to the item array
92          *
93          * @param array $attachments
94          * @param array $item
95          *
96          * @return array array
97          */
98         private static function constructAttachList($attachments, $item)
99         {
100                 if (empty($attachments)) {
101                         return $item;
102                 }
103
104                 foreach ($attachments as $attach) {
105                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
106                         if ($filetype == 'image') {
107                                 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
108                         } else {
109                                 if (!empty($item["attach"])) {
110                                         $item["attach"] .= ',';
111                                 } else {
112                                         $item["attach"] = '';
113                                 }
114                                 if (!isset($attach['length'])) {
115                                         $attach['length'] = "0";
116                                 }
117                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
118                         }
119                 }
120
121                 return $item;
122         }
123
124         /**
125          * Updates a message
126          *
127          * @param array $activity Activity array
128          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129          */
130         public static function updateItem($activity)
131         {
132                 $item = Item::selectFirst(['uri', 'parent-uri', 'gravity'], ['uri' => $activity['id']]);
133                 if (!DBA::isResult($item)) {
134                         Logger::warning('Unknown item', ['uri' => $activity['id']]);
135                         return;
136                 }
137
138                 $item['changed'] = DateTimeFormat::utcNow();
139                 $item['edited'] = $activity['updated'];
140                 $item['title'] = HTML::toBBCode($activity['name']);
141                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
142
143                 $content = HTML::toBBCode($activity['content']);
144                 $content = self::replaceEmojis($content, $activity['emojis']);
145                 $content = self::convertMentions($content);
146
147                 $implicit_mentions = [];
148                 if (($item['parent-uri'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
149                         $parent = Item::selectFirst(['id', 'author-link', 'alias'], ['uri' => $item['parent-uri']]);
150                         if (!DBA::isResult($parent)) {
151                                 Logger::warning('Unknown parent item.', ['uri' => $item['parent-uri']]);
152                                 return;
153                         }
154
155                         $implicit_mentions = self::getImplicitMentionList($parent);
156                         $content = self::removeImplicitMentionsFromBody($content, $implicit_mentions);
157                 }
158
159                 $item['body'] = $content;
160                 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive'], $implicit_mentions);
161
162                 Item::update($item, ['uri' => $activity['id']]);
163         }
164
165         /**
166          * Prepares data for a message
167          *
168          * @param array $activity Activity array
169          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
170          * @throws \ImagickException
171          */
172         public static function createItem($activity)
173         {
174                 $item = [];
175                 $item['verb'] = ACTIVITY_POST;
176                 $item['parent-uri'] = $activity['reply-to-id'];
177
178                 if ($activity['reply-to-id'] == $activity['id']) {
179                         $item['gravity'] = GRAVITY_PARENT;
180                         $item['object-type'] = ACTIVITY_OBJ_NOTE;
181                 } else {
182                         $item['gravity'] = GRAVITY_COMMENT;
183                         $item['object-type'] = ACTIVITY_OBJ_COMMENT;
184                 }
185
186                 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
187                         Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
188                         self::fetchMissingActivity($activity['reply-to-id'], $activity);
189                 }
190
191                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
192
193                 self::postItem($activity, $item);
194         }
195
196         /**
197          * Delete items
198          *
199          * @param array $activity
200          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
201          * @throws \ImagickException
202          */
203         public static function deleteItem($activity)
204         {
205                 $owner = Contact::getIdForURL($activity['actor']);
206
207                 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
208                 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
209         }
210
211         /**
212          * Prepare the item array for an activity
213          *
214          * @param array  $activity Activity array
215          * @param string $verb     Activity verb
216          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
217          * @throws \ImagickException
218          */
219         public static function createActivity($activity, $verb)
220         {
221                 $item = [];
222                 $item['verb'] = $verb;
223                 $item['parent-uri'] = $activity['object_id'];
224                 $item['gravity'] = GRAVITY_ACTIVITY;
225                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
226
227                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
228
229                 self::postItem($activity, $item);
230         }
231
232         /**
233          * Create an event
234          *
235          * @param array $activity Activity array
236          * @param array $item
237          * @throws \Exception
238          */
239         public static function createEvent($activity, $item)
240         {
241                 $event['summary']  = HTML::toBBCode($activity['name']);
242                 $event['desc']     = HTML::toBBCode($activity['content']);
243                 $event['start']    = $activity['start-time'];
244                 $event['finish']   = $activity['end-time'];
245                 $event['nofinish'] = empty($event['finish']);
246                 $event['location'] = $activity['location'];
247                 $event['adjust']   = true;
248                 $event['cid']      = $item['contact-id'];
249                 $event['uid']      = $item['uid'];
250                 $event['uri']      = $item['uri'];
251                 $event['edited']   = $item['edited'];
252                 $event['private']  = $item['private'];
253                 $event['guid']     = $item['guid'];
254                 $event['plink']    = $item['plink'];
255
256                 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
257                 $ev = DBA::selectFirst('event', ['id'], $condition);
258                 if (DBA::isResult($ev)) {
259                         $event['id'] = $ev['id'];
260                 }
261
262                 $event_id = Event::store($event);
263                 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
264         }
265
266         /**
267          * Creates an item post
268          *
269          * @param array $activity Activity data
270          * @param array $item     item array
271          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272          * @throws \ImagickException
273          */
274         private static function postItem($activity, $item)
275         {
276                 /// @todo What to do with $activity['context']?
277
278                 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
279                         Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', Logger::DEBUG);
280                         return;
281                 }
282
283                 $item['network'] = Protocol::ACTIVITYPUB;
284                 $item['private'] = !in_array(0, $activity['receiver']);
285                 $item['author-link'] = $activity['author'];
286                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
287
288                 if (empty($activity['thread-completion'])) {
289                         $item['owner-link'] = $activity['actor'];
290                         $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
291                 } else {
292                         Logger::log('Ignoring actor because of thread completion.', Logger::DEBUG);
293                         $item['owner-link'] = $item['author-link'];
294                         $item['owner-id'] = $item['author-id'];
295                 }
296
297                 $item['uri'] = $activity['id'];
298                 $content = HTML::toBBCode($activity['content']);
299                 $content = self::replaceEmojis($content, $activity['emojis']);
300                 $content = self::convertMentions($content);
301
302                 $implicit_mentions = [];
303
304                 if (($item['parent-uri'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
305                         $item_private = !in_array(0, $activity['item_receiver']);
306                         $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['parent-uri']]);
307                         if (!DBA::isResult($parent)) {
308                                 return;
309                         }
310                         if ($item_private && !$parent['private']) {
311                                 Logger::log('Item ' . $item['uri'] . ' is private but the parent ' . $item['parent-uri'] . ' is not. So we drop it.');
312                                 return;
313                         }
314
315                         $implicit_mentions = self::getImplicitMentionList($parent);
316                         $content = self::removeImplicitMentionsFromBody($content, $implicit_mentions);
317                 }
318
319                 $item['created'] = $activity['published'];
320                 $item['edited'] = $activity['updated'];
321                 $item['guid'] = $activity['diaspora:guid'];
322                 $item['title'] = HTML::toBBCode($activity['name']);
323                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
324                 $item['body'] = $content;
325
326                 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
327                         $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
328                 }
329
330                 $item['location'] = $activity['location'];
331
332                 if (!empty($item['latitude']) && !empty($item['longitude'])) {
333                         $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
334                 }
335
336                 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive'], $implicit_mentions);
337                 $item['app'] = $activity['generator'];
338                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
339
340                 $item = self::constructAttachList($activity['attachments'], $item);
341
342                 if (!empty($activity['source'])) {
343                         $item['body'] = $activity['source'];
344                 }
345
346                 $stored = false;
347
348                 foreach ($activity['receiver'] as $receiver) {
349                         $item['uid'] = $receiver;
350                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
351
352                         if (($receiver != 0) && empty($item['contact-id'])) {
353                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
354                         }
355
356                         if ($activity['object_type'] == 'as:Event') {
357                                 self::createEvent($activity, $item);
358                         }
359
360                         $item_id = Item::insert($item);
361                         Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
362
363                         if ($item['uid'] == 0) {
364                                 $stored = $item_id;
365                         }
366                 }
367
368                 // Store send a follow request for every reshare - but only when the item had been stored
369                 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
370                         $author = APContact::getByURL($item['owner-link'], false);
371                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
372                         if ($author['type'] != 'Group') {
373                                 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
374                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
375                         }
376                 }
377         }
378
379         /**
380          * Fetches missing posts
381          *
382          * @param $url
383          * @param $child
384          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
385          */
386         private static function fetchMissingActivity($url, $child)
387         {
388                 if (Config::get('system', 'ostatus_full_threads')) {
389                         return;
390                 }
391
392                 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
393
394                 $object = ActivityPub::fetchContent($url, $uid);
395                 if (empty($object)) {
396                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
397                         return;
398                 }
399
400                 if (empty($object['id'])) {
401                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
402                         return;
403                 }
404
405                 $activity = [];
406                 $activity['@context'] = $object['@context'];
407                 unset($object['@context']);
408                 $activity['id'] = $object['id'];
409                 $activity['to'] = defaults($object, 'to', []);
410                 $activity['cc'] = defaults($object, 'cc', []);
411                 $activity['actor'] = $child['author'];
412                 $activity['object'] = $object;
413                 $activity['published'] = defaults($object, 'published', $child['published']);
414                 $activity['type'] = 'Create';
415
416                 $ldactivity = JsonLD::compact($activity);
417
418                 $ldactivity['thread-completion'] = true;
419
420                 ActivityPub\Receiver::processActivity($ldactivity);
421                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
422         }
423
424         /**
425          * perform a "follow" request
426          *
427          * @param array $activity
428          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
429          * @throws \ImagickException
430          */
431         public static function followUser($activity)
432         {
433                 $uid = User::getIdForURL($activity['object_id']);
434                 if (empty($uid)) {
435                         return;
436                 }
437
438                 $owner = User::getOwnerDataById($uid);
439
440                 $cid = Contact::getIdForURL($activity['actor'], $uid);
441                 if (!empty($cid)) {
442                         self::switchContact($cid);
443                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
444                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
445                 } else {
446                         $contact = false;
447                 }
448
449                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
450                         'author-link' => $activity['actor']];
451
452                 // Ensure that the contact has got the right network type
453                 self::switchContact($item['author-id']);
454
455                 Contact::addRelationship($owner, $contact, $item);
456                 $cid = Contact::getIdForURL($activity['actor'], $uid);
457                 if (empty($cid)) {
458                         return;
459                 }
460
461                 if (empty($contact)) {
462                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
463                 }
464
465                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
466         }
467
468         /**
469          * Update the given profile
470          *
471          * @param array $activity
472          * @throws \Exception
473          */
474         public static function updatePerson($activity)
475         {
476                 if (empty($activity['object_id'])) {
477                         return;
478                 }
479
480                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
481                 APContact::getByURL($activity['object_id'], true);
482         }
483
484         /**
485          * Delete the given profile
486          *
487          * @param array $activity
488          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489          */
490         public static function deletePerson($activity)
491         {
492                 if (empty($activity['object_id']) || empty($activity['actor'])) {
493                         Logger::log('Empty object id or actor.', Logger::DEBUG);
494                         return;
495                 }
496
497                 if ($activity['object_id'] != $activity['actor']) {
498                         Logger::log('Object id does not match actor.', Logger::DEBUG);
499                         return;
500                 }
501
502                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
503                 while ($contact = DBA::fetch($contacts)) {
504                         Contact::remove($contact['id']);
505                 }
506                 DBA::close($contacts);
507
508                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
509         }
510
511         /**
512          * Accept a follow request
513          *
514          * @param array $activity
515          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
516          * @throws \ImagickException
517          */
518         public static function acceptFollowUser($activity)
519         {
520                 $uid = User::getIdForURL($activity['object_actor']);
521                 if (empty($uid)) {
522                         return;
523                 }
524
525                 $cid = Contact::getIdForURL($activity['actor'], $uid);
526                 if (empty($cid)) {
527                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
528                         return;
529                 }
530
531                 self::switchContact($cid);
532
533                 $fields = ['pending' => false];
534
535                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
536                 if ($contact['rel'] == Contact::FOLLOWER) {
537                         $fields['rel'] = Contact::FRIEND;
538                 }
539
540                 $condition = ['id' => $cid];
541                 DBA::update('contact', $fields, $condition);
542                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
543         }
544
545         /**
546          * Reject a follow request
547          *
548          * @param array $activity
549          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
550          * @throws \ImagickException
551          */
552         public static function rejectFollowUser($activity)
553         {
554                 $uid = User::getIdForURL($activity['object_actor']);
555                 if (empty($uid)) {
556                         return;
557                 }
558
559                 $cid = Contact::getIdForURL($activity['actor'], $uid);
560                 if (empty($cid)) {
561                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
562                         return;
563                 }
564
565                 self::switchContact($cid);
566
567                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
568                         Contact::remove($cid);
569                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
570                 } else {
571                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
572                 }
573         }
574
575         /**
576          * Undo activity like "like" or "dislike"
577          *
578          * @param array $activity
579          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
580          * @throws \ImagickException
581          */
582         public static function undoActivity($activity)
583         {
584                 if (empty($activity['object_id'])) {
585                         return;
586                 }
587
588                 if (empty($activity['object_actor'])) {
589                         return;
590                 }
591
592                 $author_id = Contact::getIdForURL($activity['object_actor']);
593                 if (empty($author_id)) {
594                         return;
595                 }
596
597                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
598         }
599
600         /**
601          * Activity to remove a follower
602          *
603          * @param array $activity
604          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
605          * @throws \ImagickException
606          */
607         public static function undoFollowUser($activity)
608         {
609                 $uid = User::getIdForURL($activity['object_object']);
610                 if (empty($uid)) {
611                         return;
612                 }
613
614                 $owner = User::getOwnerDataById($uid);
615
616                 $cid = Contact::getIdForURL($activity['actor'], $uid);
617                 if (empty($cid)) {
618                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
619                         return;
620                 }
621
622                 self::switchContact($cid);
623
624                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
625                 if (!DBA::isResult($contact)) {
626                         return;
627                 }
628
629                 Contact::removeFollower($owner, $contact);
630                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
631         }
632
633         /**
634          * Switches a contact to AP if needed
635          *
636          * @param integer $cid Contact ID
637          * @throws \Exception
638          */
639         private static function switchContact($cid)
640         {
641                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
642                 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
643                         return;
644                 }
645
646                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
647                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
648         }
649
650         /**
651          * Collects implicit mentions like:
652          * - the author of the parent item
653          * - all the mentioned conversants in the parent item
654          *
655          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
656          * @return array
657          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
658          */
659         private static function getImplicitMentionList(array $parent)
660         {
661                 $parent_terms = Term::tagArrayFromItemId($parent['id'], [TERM_MENTION]);
662
663                 $implicit_mentions = [
664                         $parent['author-link']
665                 ];
666
667                 if ($parent['alias']) {
668                         $implicit_mentions[] = $parent['alias'];
669                 }
670
671                 foreach ($parent_terms as $term) {
672                         $contact = Contact::getDetailsByURL($term['url'], 0);
673                         if (!empty($contact)) {
674                                 $implicit_mentions[] = $contact['url'];
675                                 $implicit_mentions[] = $contact['nurl'];
676                                 $implicit_mentions[] = $contact['alias'];
677                         }
678                 }
679
680                 return $implicit_mentions;
681         }
682
683         /**
684          * Strips from the body prepended implicit mentions
685          *
686          * @param string $body
687          * @param array  $implicit_mentions List of profile URLs
688          * @return string
689          */
690         private static function removeImplicitMentionsFromBody($body, array $implicit_mentions)
691         {
692                 $kept_mentions = [];
693
694                 // Extract one prepended mention at a time from the body
695                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#mi', $body, $matches)) {
696                         if (!in_array($matches[2], $implicit_mentions) ) {
697                                 $kept_mentions[] = $matches[1];
698                         }
699
700                         $body = $matches[3];
701                 }
702
703                 // Re-appending the kept mentions to the body after extraction
704                 $kept_mentions[] = $body;
705
706                 return implode('', $kept_mentions);
707         }
708 }