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