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