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