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