]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
6d94b1b49ee7166503f3b4baa19131f23fe65b65
[friendica.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                 foreach ($activity['receiver'] as $receiver) {
347                         $item['uid'] = $receiver;
348                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
349
350                         if (($receiver != 0) && empty($item['contact-id'])) {
351                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
352                         }
353
354                         if ($activity['object_type'] == 'as:Event') {
355                                 self::createEvent($activity, $item);
356                         }
357
358                         $item_id = Item::insert($item);
359                         Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
360                 }
361
362                 if (!$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
363                         $author = APContact::getByURL($item['owner-link'], false);
364                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
365                         if ($author['type'] != 'Group') {
366                                 Logger::log('Send follow request for ' . $item['uri'] . ' to ' . $item['author-link'], Logger::DEBUG);
367                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
368                         }
369                 }
370         }
371
372         /**
373          * Fetches missing posts
374          *
375          * @param $url
376          * @param $child
377          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
378          */
379         private static function fetchMissingActivity($url, $child)
380         {
381                 if (Config::get('system', 'ostatus_full_threads')) {
382                         return;
383                 }
384
385                 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
386
387                 $object = ActivityPub::fetchContent($url, $uid);
388                 if (empty($object)) {
389                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
390                         return;
391                 }
392
393                 if (empty($object['id'])) {
394                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
395                         return;
396                 }
397
398                 $activity = [];
399                 $activity['@context'] = $object['@context'];
400                 unset($object['@context']);
401                 $activity['id'] = $object['id'];
402                 $activity['to'] = defaults($object, 'to', []);
403                 $activity['cc'] = defaults($object, 'cc', []);
404                 $activity['actor'] = $child['author'];
405                 $activity['object'] = $object;
406                 $activity['published'] = defaults($object, 'published', $child['published']);
407                 $activity['type'] = 'Create';
408
409                 $ldactivity = JsonLD::compact($activity);
410
411                 $ldactivity['thread-completion'] = true;
412
413                 ActivityPub\Receiver::processActivity($ldactivity);
414                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
415         }
416
417         /**
418          * perform a "follow" request
419          *
420          * @param array $activity
421          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
422          * @throws \ImagickException
423          */
424         public static function followUser($activity)
425         {
426                 $uid = User::getIdForURL($activity['object_id']);
427                 if (empty($uid)) {
428                         return;
429                 }
430
431                 $owner = User::getOwnerDataById($uid);
432
433                 $cid = Contact::getIdForURL($activity['actor'], $uid);
434                 if (!empty($cid)) {
435                         self::switchContact($cid);
436                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
437                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
438                 } else {
439                         $contact = false;
440                 }
441
442                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
443                         'author-link' => $activity['actor']];
444
445                 // Ensure that the contact has got the right network type
446                 self::switchContact($item['author-id']);
447
448                 Contact::addRelationship($owner, $contact, $item);
449                 $cid = Contact::getIdForURL($activity['actor'], $uid);
450                 if (empty($cid)) {
451                         return;
452                 }
453
454                 if (empty($contact)) {
455                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
456                 }
457
458                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
459         }
460
461         /**
462          * Update the given profile
463          *
464          * @param array $activity
465          * @throws \Exception
466          */
467         public static function updatePerson($activity)
468         {
469                 if (empty($activity['object_id'])) {
470                         return;
471                 }
472
473                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
474                 APContact::getByURL($activity['object_id'], true);
475         }
476
477         /**
478          * Delete the given profile
479          *
480          * @param array $activity
481          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
482          */
483         public static function deletePerson($activity)
484         {
485                 if (empty($activity['object_id']) || empty($activity['actor'])) {
486                         Logger::log('Empty object id or actor.', Logger::DEBUG);
487                         return;
488                 }
489
490                 if ($activity['object_id'] != $activity['actor']) {
491                         Logger::log('Object id does not match actor.', Logger::DEBUG);
492                         return;
493                 }
494
495                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
496                 while ($contact = DBA::fetch($contacts)) {
497                         Contact::remove($contact['id']);
498                 }
499                 DBA::close($contacts);
500
501                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
502         }
503
504         /**
505          * Accept a follow request
506          *
507          * @param array $activity
508          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
509          * @throws \ImagickException
510          */
511         public static function acceptFollowUser($activity)
512         {
513                 $uid = User::getIdForURL($activity['object_actor']);
514                 if (empty($uid)) {
515                         return;
516                 }
517
518                 $cid = Contact::getIdForURL($activity['actor'], $uid);
519                 if (empty($cid)) {
520                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
521                         return;
522                 }
523
524                 self::switchContact($cid);
525
526                 $fields = ['pending' => false];
527
528                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
529                 if ($contact['rel'] == Contact::FOLLOWER) {
530                         $fields['rel'] = Contact::FRIEND;
531                 }
532
533                 $condition = ['id' => $cid];
534                 DBA::update('contact', $fields, $condition);
535                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
536         }
537
538         /**
539          * Reject a follow request
540          *
541          * @param array $activity
542          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
543          * @throws \ImagickException
544          */
545         public static function rejectFollowUser($activity)
546         {
547                 $uid = User::getIdForURL($activity['object_actor']);
548                 if (empty($uid)) {
549                         return;
550                 }
551
552                 $cid = Contact::getIdForURL($activity['actor'], $uid);
553                 if (empty($cid)) {
554                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
555                         return;
556                 }
557
558                 self::switchContact($cid);
559
560                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
561                         Contact::remove($cid);
562                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
563                 } else {
564                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
565                 }
566         }
567
568         /**
569          * Undo activity like "like" or "dislike"
570          *
571          * @param array $activity
572          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
573          * @throws \ImagickException
574          */
575         public static function undoActivity($activity)
576         {
577                 if (empty($activity['object_id'])) {
578                         return;
579                 }
580
581                 if (empty($activity['object_actor'])) {
582                         return;
583                 }
584
585                 $author_id = Contact::getIdForURL($activity['object_actor']);
586                 if (empty($author_id)) {
587                         return;
588                 }
589
590                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
591         }
592
593         /**
594          * Activity to remove a follower
595          *
596          * @param array $activity
597          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
598          * @throws \ImagickException
599          */
600         public static function undoFollowUser($activity)
601         {
602                 $uid = User::getIdForURL($activity['object_object']);
603                 if (empty($uid)) {
604                         return;
605                 }
606
607                 $owner = User::getOwnerDataById($uid);
608
609                 $cid = Contact::getIdForURL($activity['actor'], $uid);
610                 if (empty($cid)) {
611                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
612                         return;
613                 }
614
615                 self::switchContact($cid);
616
617                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
618                 if (!DBA::isResult($contact)) {
619                         return;
620                 }
621
622                 Contact::removeFollower($owner, $contact);
623                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
624         }
625
626         /**
627          * Switches a contact to AP if needed
628          *
629          * @param integer $cid Contact ID
630          * @throws \Exception
631          */
632         private static function switchContact($cid)
633         {
634                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
635                 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
636                         return;
637                 }
638
639                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
640                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
641         }
642
643         /**
644          * Collects implicit mentions like:
645          * - the author of the parent item
646          * - all the mentioned conversants in the parent item
647          *
648          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
649          * @return array
650          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
651          */
652         private static function getImplicitMentionList(array $parent)
653         {
654                 $parent_terms = Term::tagArrayFromItemId($parent['id'], [TERM_MENTION]);
655
656                 $implicit_mentions = [
657                         $parent['author-link']
658                 ];
659
660                 if ($parent['alias']) {
661                         $implicit_mentions[] = $parent['alias'];
662                 }
663
664                 foreach ($parent_terms as $term) {
665                         $contact = Contact::getDetailsByURL($term['url']);
666
667                         $implicit_mentions[] = $contact['url'];
668                         $implicit_mentions[] = $contact['nurl'];
669                         $implicit_mentions[] = $contact['alias'];
670                 }
671
672                 return $implicit_mentions;
673         }
674
675         /**
676          * Strips from the body prepended implicit mentions
677          *
678          * @param string $body
679          * @param array  $implicit_mentions List of profile URLs
680          * @return string
681          */
682         private static function removeImplicitMentionsFromBody($body, array $implicit_mentions)
683         {
684                 $kept_mentions = [];
685
686                 // Extract one prepended mention at a time from the body
687                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#mi', $body, $matches)) {
688                         if (!in_array($matches[2], $implicit_mentions) ) {
689                                 $kept_mentions[] = $matches[1];
690                         }
691
692                         $body = $matches[3];
693                 }
694
695                 // Re-appending the kept mentions to the body after extraction
696                 $kept_mentions[] = $body;
697
698                 return implode('', $kept_mentions);
699         }
700 }