Merge pull request #6839 from MrPetovan/bug/6829-fix-implicit-mention-regex
[friendica.git/.git] / src / Protocol / ActivityPub / Processor.php
1 <?php
2 /**
3  * @file src/Protocol/ActivityPub/Processor.php
4  */
5 namespace Friendica\Protocol\ActivityPub;
6
7 use Friendica\Database\DBA;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Model\Contact;
13 use Friendica\Model\APContact;
14 use Friendica\Model\Item;
15 use Friendica\Model\Event;
16 use Friendica\Model\Term;
17 use Friendica\Model\User;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\JsonLD;
21 use Friendica\Util\Strings;
22
23 /**
24  * ActivityPub Processor Protocol class
25  */
26 class Processor
27 {
28         /**
29          * Converts mentions from Pleroma into the Friendica format
30          *
31          * @param string $body
32          *
33          * @return string converted body
34          */
35         private static function convertMentions($body)
36         {
37                 $URLSearchString = "^\[\]";
38                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
39
40                 return $body;
41         }
42
43         /**
44          * Replaces emojis in the body
45          *
46          * @param array $emojis
47          * @param string $body
48          *
49          * @return string with replaced emojis
50          */
51         public static function replaceEmojis($body, array $emojis)
52         {
53                 foreach ($emojis as $emoji) {
54                         $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
55                         $body = str_replace($emoji['name'], $replace, $body);
56                 }
57                 return $body;
58         }
59
60         /**
61          * Constructs a string with tags for a given tag array
62          *
63          * @param array   $tags
64          * @param boolean $sensitive
65          * @param array   $implicit_mentions List of profile URLs to skip
66          * @return string with tags
67          */
68         private static function constructTagString(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                 $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                 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
148                         $parent = Item::selectFirst(['id', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
149                         if (!DBA::isResult($parent)) {
150                                 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
151                                 return;
152                         }
153
154                         $potential_implicit_mentions = self::getImplicitMentionList($parent);
155                         $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
156                         $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
157                 }
158
159                 $item['body'] = $content;
160                 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
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['thr-parent'] = $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['thr-parent'] = $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['thr-parent']])) {
279                         Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
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::info('Ignoring actor because of thread completion.');
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                 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
303                         $item_private = !in_array(0, $activity['item_receiver']);
304                         $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
305                         if (!DBA::isResult($parent)) {
306                                 return;
307                         }
308                         if ($item_private && !$parent['private']) {
309                                 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
310                                 return;
311                         }
312
313                         $potential_implicit_mentions = self::getImplicitMentionList($parent);
314                         $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
315                         $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
316                 }
317
318                 $item['created'] = $activity['published'];
319                 $item['edited'] = $activity['updated'];
320                 $item['guid'] = $activity['diaspora:guid'];
321                 $item['title'] = HTML::toBBCode($activity['name']);
322                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
323                 $item['body'] = $content;
324
325                 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
326                         $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
327                 }
328
329                 $item['location'] = $activity['location'];
330
331                 if (!empty($item['latitude']) && !empty($item['longitude'])) {
332                         $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
333                 }
334
335                 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
336                 $item['app'] = $activity['generator'];
337                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
338
339                 $item = self::constructAttachList($activity['attachments'], $item);
340
341                 if (!empty($activity['source'])) {
342                         $item['body'] = $activity['source'];
343                 }
344
345                 $stored = false;
346
347                 foreach ($activity['receiver'] as $receiver) {
348                         $item['uid'] = $receiver;
349                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
350
351                         if (($receiver != 0) && empty($item['contact-id'])) {
352                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
353                         }
354
355                         if ($activity['object_type'] == 'as:Event') {
356                                 self::createEvent($activity, $item);
357                         }
358
359                         $item_id = Item::insert($item);
360                         if ($item_id) {
361                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
362                         } else {
363                                 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
364                         }
365
366                         if ($item['uid'] == 0) {
367                                 $stored = $item_id;
368                         }
369                 }
370
371                 // Store send a follow request for every reshare - but only when the item had been stored
372                 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
373                         $author = APContact::getByURL($item['owner-link'], false);
374                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
375                         if ($author['type'] != 'Group') {
376                                 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
377                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
378                         }
379                 }
380         }
381
382         /**
383          * Fetches missing posts
384          *
385          * @param $url
386          * @param $child
387          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
388          */
389         private static function fetchMissingActivity($url, $child)
390         {
391                 if (Config::get('system', 'ostatus_full_threads')) {
392                         return;
393                 }
394
395                 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
396
397                 $object = ActivityPub::fetchContent($url, $uid);
398                 if (empty($object)) {
399                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
400                         return;
401                 }
402
403                 if (empty($object['id'])) {
404                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
405                         return;
406                 }
407
408                 $activity = [];
409                 $activity['@context'] = $object['@context'];
410                 unset($object['@context']);
411                 $activity['id'] = $object['id'];
412                 $activity['to'] = defaults($object, 'to', []);
413                 $activity['cc'] = defaults($object, 'cc', []);
414                 $activity['actor'] = $child['author'];
415                 $activity['object'] = $object;
416                 $activity['published'] = defaults($object, 'published', $child['published']);
417                 $activity['type'] = 'Create';
418
419                 $ldactivity = JsonLD::compact($activity);
420
421                 $ldactivity['thread-completion'] = true;
422
423                 ActivityPub\Receiver::processActivity($ldactivity);
424                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
425         }
426
427         /**
428          * perform a "follow" request
429          *
430          * @param array $activity
431          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
432          * @throws \ImagickException
433          */
434         public static function followUser($activity)
435         {
436                 $uid = User::getIdForURL($activity['object_id']);
437                 if (empty($uid)) {
438                         return;
439                 }
440
441                 $owner = User::getOwnerDataById($uid);
442
443                 $cid = Contact::getIdForURL($activity['actor'], $uid);
444                 if (!empty($cid)) {
445                         self::switchContact($cid);
446                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
447                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
448                 } else {
449                         $contact = false;
450                 }
451
452                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
453                         'author-link' => $activity['actor']];
454
455                 // Ensure that the contact has got the right network type
456                 self::switchContact($item['author-id']);
457
458                 Contact::addRelationship($owner, $contact, $item);
459                 $cid = Contact::getIdForURL($activity['actor'], $uid);
460                 if (empty($cid)) {
461                         return;
462                 }
463
464                 if (empty($contact)) {
465                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
466                 }
467
468                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
469         }
470
471         /**
472          * Update the given profile
473          *
474          * @param array $activity
475          * @throws \Exception
476          */
477         public static function updatePerson($activity)
478         {
479                 if (empty($activity['object_id'])) {
480                         return;
481                 }
482
483                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
484                 APContact::getByURL($activity['object_id'], true);
485         }
486
487         /**
488          * Delete the given profile
489          *
490          * @param array $activity
491          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
492          */
493         public static function deletePerson($activity)
494         {
495                 if (empty($activity['object_id']) || empty($activity['actor'])) {
496                         Logger::log('Empty object id or actor.', Logger::DEBUG);
497                         return;
498                 }
499
500                 if ($activity['object_id'] != $activity['actor']) {
501                         Logger::log('Object id does not match actor.', Logger::DEBUG);
502                         return;
503                 }
504
505                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
506                 while ($contact = DBA::fetch($contacts)) {
507                         Contact::remove($contact['id']);
508                 }
509                 DBA::close($contacts);
510
511                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
512         }
513
514         /**
515          * Accept a follow request
516          *
517          * @param array $activity
518          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
519          * @throws \ImagickException
520          */
521         public static function acceptFollowUser($activity)
522         {
523                 $uid = User::getIdForURL($activity['object_actor']);
524                 if (empty($uid)) {
525                         return;
526                 }
527
528                 $cid = Contact::getIdForURL($activity['actor'], $uid);
529                 if (empty($cid)) {
530                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
531                         return;
532                 }
533
534                 self::switchContact($cid);
535
536                 $fields = ['pending' => false];
537
538                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
539                 if ($contact['rel'] == Contact::FOLLOWER) {
540                         $fields['rel'] = Contact::FRIEND;
541                 }
542
543                 $condition = ['id' => $cid];
544                 DBA::update('contact', $fields, $condition);
545                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
546         }
547
548         /**
549          * Reject a follow request
550          *
551          * @param array $activity
552          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
553          * @throws \ImagickException
554          */
555         public static function rejectFollowUser($activity)
556         {
557                 $uid = User::getIdForURL($activity['object_actor']);
558                 if (empty($uid)) {
559                         return;
560                 }
561
562                 $cid = Contact::getIdForURL($activity['actor'], $uid);
563                 if (empty($cid)) {
564                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
565                         return;
566                 }
567
568                 self::switchContact($cid);
569
570                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
571                         Contact::remove($cid);
572                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
573                 } else {
574                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
575                 }
576         }
577
578         /**
579          * Undo activity like "like" or "dislike"
580          *
581          * @param array $activity
582          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
583          * @throws \ImagickException
584          */
585         public static function undoActivity($activity)
586         {
587                 if (empty($activity['object_id'])) {
588                         return;
589                 }
590
591                 if (empty($activity['object_actor'])) {
592                         return;
593                 }
594
595                 $author_id = Contact::getIdForURL($activity['object_actor']);
596                 if (empty($author_id)) {
597                         return;
598                 }
599
600                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
601         }
602
603         /**
604          * Activity to remove a follower
605          *
606          * @param array $activity
607          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
608          * @throws \ImagickException
609          */
610         public static function undoFollowUser($activity)
611         {
612                 $uid = User::getIdForURL($activity['object_object']);
613                 if (empty($uid)) {
614                         return;
615                 }
616
617                 $owner = User::getOwnerDataById($uid);
618
619                 $cid = Contact::getIdForURL($activity['actor'], $uid);
620                 if (empty($cid)) {
621                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
622                         return;
623                 }
624
625                 self::switchContact($cid);
626
627                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
628                 if (!DBA::isResult($contact)) {
629                         return;
630                 }
631
632                 Contact::removeFollower($owner, $contact);
633                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
634         }
635
636         /**
637          * Switches a contact to AP if needed
638          *
639          * @param integer $cid Contact ID
640          * @throws \Exception
641          */
642         private static function switchContact($cid)
643         {
644                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
645                 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
646                         return;
647                 }
648
649                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
650                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
651         }
652
653         /**
654          * Collects implicit mentions like:
655          * - the author of the parent item
656          * - all the mentioned conversants in the parent item
657          *
658          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
659          * @return array
660          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
661          */
662         private static function getImplicitMentionList(array $parent)
663         {
664                 if (Config::get('system', 'disable_implicit_mentions')) {
665                         return [];
666                 }
667
668                 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
669
670                 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
671
672                 $implicit_mentions = [];
673                 if (empty($parent_author)) {
674                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
675                 } else {
676                         $implicit_mentions[] = $parent_author['url'];
677                         $implicit_mentions[] = $parent_author['nurl'];
678                         $implicit_mentions[] = $parent_author['alias'];
679                 }
680
681                 if (!empty($parent['alias'])) {
682                         $implicit_mentions[] = $parent['alias'];
683                 }
684
685                 foreach ($parent_terms as $term) {
686                         $contact = Contact::getDetailsByURL($term['url'], 0);
687                         if (!empty($contact)) {
688                                 $implicit_mentions[] = $contact['url'];
689                                 $implicit_mentions[] = $contact['nurl'];
690                                 $implicit_mentions[] = $contact['alias'];
691                         }
692                 }
693
694                 return $implicit_mentions;
695         }
696
697         /**
698          * Strips from the body prepended implicit mentions
699          *
700          * @param string $body
701          * @param array $potential_mentions
702          * @return string
703          */
704         private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
705         {
706                 if (Config::get('system', 'disable_implicit_mentions')) {
707                         return $body;
708                 }
709
710                 $kept_mentions = [];
711
712                 // Extract one prepended mention at a time from the body
713                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
714                         if (!in_array($matches[2], $potential_mentions) ) {
715                                 $kept_mentions[] = $matches[1];
716                         }
717
718                         $body = $matches[3];
719                 }
720
721                 // Re-appending the kept mentions to the body after extraction
722                 $kept_mentions[] = $body;
723
724                 return implode('', $kept_mentions);
725         }
726
727         private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
728         {
729                 if (Config::get('system', 'disable_implicit_mentions')) {
730                         return $activity_tags;
731                 }
732
733                 foreach ($activity_tags as $index => $tag) {
734                         if (in_array($tag['href'], $potential_mentions)) {
735                                 $activity_tags[$index]['name'] = preg_replace(
736                                         '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
737                                         Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
738                                         $activity_tags[$index]['name'],
739                                         1
740                                 );
741                         }
742                 }
743
744                 return $activity_tags;
745         }
746 }