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