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