]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Merge branch '2021.03-rc' into copyright-2021
[friendica.git] / src / Protocol / ActivityPub / Processor.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
24 use Friendica\Content\PageInfo;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Model\APContact;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\Event;
36 use Friendica\Model\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Model\Post;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\ActivityPub;
45 use Friendica\Protocol\Relay;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\Strings;
49
50 /**
51  * ActivityPub Processor Protocol class
52  */
53 class Processor
54 {
55         /**
56          * Converts mentions from Pleroma into the Friendica format
57          *
58          * @param string $body
59          *
60          * @return string converted body
61          */
62         private static function convertMentions($body)
63         {
64                 $URLSearchString = "^\[\]";
65                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
66
67                 return $body;
68         }
69
70         /**
71          * Convert the language array into a language JSON
72          *
73          * @param array $languages
74          * @return string language JSON
75          */
76         private static function processLanguages(array $languages)
77         {
78                 $codes = array_keys($languages);
79                 $lang = [];
80                 foreach ($codes as $code) {
81                         $lang[$code] = 1;
82                 }
83
84                 if (empty($lang)) {
85                         return '';
86                 }
87
88                 return json_encode($lang);
89         }
90         /**
91          * Replaces emojis in the body
92          *
93          * @param array $emojis
94          * @param string $body
95          *
96          * @return string with replaced emojis
97          */
98         private static function replaceEmojis($body, array $emojis)
99         {
100                 $body = strtr($body,
101                         array_combine(
102                                 array_column($emojis, 'name'),
103                                 array_map(function ($emoji) {
104                                         return '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
105                                 }, $emojis)
106                         )
107                 );
108
109                 return $body;
110         }
111
112         /**
113          * Store attached media files in the post-media table
114          *
115          * @param int $uriid
116          * @param array $attachment
117          * @return void
118          */
119         private static function storeAttachmentAsMedia(int $uriid, array $attachment)
120         {
121                 if (empty($attachment['url'])) {
122                         return;
123                 }
124
125                 $data = ['uri-id' => $uriid];
126
127                 $filetype = strtolower(substr($attachment['mediaType'], 0, strpos($attachment['mediaType'], '/')));
128                 if ($filetype == 'image') {
129                         $data['type'] = Post\Media::IMAGE;
130                 } elseif ($filetype == 'video') {
131                         $data['type'] = Post\Media::VIDEO;
132                 } elseif ($filetype == 'audio') {
133                         $data['type'] = Post\Media::AUDIO;
134                 } elseif (in_array($attachment['mediaType'], ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
135                         $data['type'] = Post\Media::TORRENT;
136                 } else {
137                         Logger::info('Unknown type', ['attachment' => $attachment]);
138                         return;
139                 }
140
141                 $data['url'] = $attachment['url'];
142                 $data['mimetype'] = $attachment['mediaType'];
143                 $data['height'] = $attachment['height'] ?? null;
144                 $data['size'] = $attachment['size'] ?? null;
145                 $data['preview'] = $attachment['image'] ?? null;
146                 $data['description'] = $attachment['name'] ?? null;
147
148                 Post\Media::insert($data);
149         }
150
151         /**
152          * Add attachment data to the item array
153          *
154          * @param array   $activity
155          * @param array   $item
156          *
157          * @return array array
158          */
159         private static function constructAttachList($activity, $item)
160         {
161                 if (empty($activity['attachments'])) {
162                         return $item;
163                 }
164
165                 foreach ($activity['attachments'] as $attach) {
166                         switch ($attach['type']) {
167                                 case 'link':
168                                         $data = [
169                                                 'url'      => $attach['url'],
170                                                 'type'     => $attach['type'],
171                                                 'title'    => $attach['title'] ?? '',
172                                                 'text'     => $attach['desc']  ?? '',
173                                                 'image'    => $attach['image'] ?? '',
174                                                 'images'   => [],
175                                                 'keywords' => [],
176                                         ];
177                                         $item['body'] = PageInfo::appendDataToBody($item['body'], $data);
178                                         break;
179                                 default:
180                                         self::storeAttachmentAsMedia($item['uri-id'], $attach);
181
182                                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
183                                         if ($filetype == 'image') {
184                                                 if (!empty($activity['source'])) {
185                                                         foreach ([0, 1, 2] as $size) {
186                                                                 if (preg_match('#/photo/.*-' . $size . '\.#ism', $attach['url']) && 
187                                                                         strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $activity['source']), $attach['url'])) {
188                                                                         continue 3;
189                                                                 }
190                                                         }
191                                                         if (strpos($activity['source'], $attach['url'])) {
192                                                                 continue 2;
193                                                         }
194                                                 }
195
196                                                 $item['body'] .= "\n";
197
198                                                 // image is the preview/thumbnail URL
199                                                 if (!empty($attach['image'])) {
200                                                         $item['body'] .= '[url=' . $attach['url'] . ']';
201                                                         $attach['url'] = $attach['image'];
202                                                 }
203
204                                                 if (empty($attach['name'])) {
205                                                         $item['body'] .= '[img]' . $attach['url'] . '[/img]';
206                                                 } else {
207                                                         $item['body'] .= '[img=' . $attach['url'] . ']' . $attach['name'] . '[/img]';
208                                                 }
209
210                                                 if (!empty($attach['image'])) {
211                                                         $item['body'] .= '[/url]';
212                                                 }
213                                         } elseif ($filetype == 'audio') {
214                                                 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
215                                                         continue 2;
216                                                 }
217
218                                                 $item['body'] = '[audio]' . $attach['url'] . "[/audio]\n" . $item['body'];
219                                         } elseif ($filetype == 'video') {
220                                                 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
221                                                         continue 2;
222                                                 }
223
224                                                 $item['body'] = '[video]' . $attach['url'] . "[/video]\n" . $item['body'];
225                                         }
226                         }
227                 }
228
229                 return $item;
230         }
231
232         /**
233          * Updates a message
234          *
235          * @param array $activity Activity array
236          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
237          */
238         public static function updateItem($activity)
239         {
240                 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
241                 if (!DBA::isResult($item)) {
242                         Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
243                         $item = self::createItem($activity);
244                         self::postItem($activity, $item);
245                         return;
246                 }
247
248                 $item['changed'] = DateTimeFormat::utcNow();
249                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
250
251                 $item = self::processContent($activity, $item);
252
253                 $item = self::constructAttachList($activity, $item);
254
255                 if (empty($item)) {
256                         return;
257                 }
258
259                 Item::update($item, ['uri' => $activity['id']]);
260         }
261
262         /**
263          * Prepares data for a message
264          *
265          * @param array $activity Activity array
266          * @return array Internal item
267          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268          * @throws \ImagickException
269          */
270         public static function createItem($activity)
271         {
272                 $item = [];
273                 $item['verb'] = Activity::POST;
274                 $item['thr-parent'] = $activity['reply-to-id'];
275
276                 if ($activity['reply-to-id'] == $activity['id']) {
277                         $item['gravity'] = GRAVITY_PARENT;
278                         $item['object-type'] = Activity\ObjectType::NOTE;
279                 } else {
280                         $item['gravity'] = GRAVITY_COMMENT;
281                         $item['object-type'] = Activity\ObjectType::COMMENT;
282                 }
283
284                 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
285                         Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
286                         self::fetchMissingActivity($activity['reply-to-id'], $activity);
287                 }
288
289                 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
290
291                 /// @todo What to do with $activity['context']?
292                 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
293                         Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
294                         return [];
295                 }
296
297                 $item['network'] = Protocol::ACTIVITYPUB;
298                 $item['author-link'] = $activity['author'];
299                 $item['author-id'] = Contact::getIdForURL($activity['author']);
300                 $item['owner-link'] = $activity['actor'];
301                 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
302
303                 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
304                         $item['private'] = Item::UNLISTED;
305                 } elseif (in_array(0, $activity['receiver'])) {
306                         $item['private'] = Item::PUBLIC;
307                 } else {
308                         $item['private'] = Item::PRIVATE;
309                 }
310
311                 if (!empty($activity['raw'])) {
312                         $item['source'] = $activity['raw'];
313                         $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
314                         $item['conversation-href'] = $activity['context'] ?? '';
315                         $item['conversation-uri'] = $activity['conversation'] ?? '';
316
317                         if (isset($activity['push'])) {
318                                 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
319                         }
320                 }
321
322                 if (!empty($activity['from-relay'])) {
323                         $item['direction'] = Conversation::RELAY;
324                 }
325
326                 $item['isForum'] = false;
327
328                 if (!empty($activity['thread-completion'])) {
329                         if ($activity['thread-completion'] != $item['owner-id']) {
330                                 $actor = Contact::getById($activity['thread-completion'], ['url']);
331                                 $item['causer-link'] = $actor['url'];
332                                 $item['causer-id'] = $activity['thread-completion'];
333                                 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
334                         } else {
335                                 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
336                                 $item['causer-link'] = $item['owner-link'];
337                                 $item['causer-id'] = $item['owner-id'];
338                                 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
339                         }
340
341                         $item['owner-link'] = $item['author-link'];
342                         $item['owner-id'] = $item['author-id'];
343                 } else {
344                         $actor = APContact::getByURL($item['owner-link'], false);
345                         $item['isForum'] = ($actor['type'] == 'Group');
346                 }
347
348                 $item['uri'] = $activity['id'];
349
350                 $item['created'] = DateTimeFormat::utc($activity['published']);
351                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
352                 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
353                 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
354
355                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
356                 if (empty($item['uri-id'])) {
357                         Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
358                         return [];
359                 }
360
361                 $item = self::processContent($activity, $item);
362                 if (empty($item)) {
363                         Logger::info('Message was not processed');
364                         return [];
365                 }
366
367                 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
368
369                 $item = self::constructAttachList($activity, $item);
370
371                 // We received the post via AP, so we set the protocol of the server to AP
372                 $contact = Contact::getById($item['author-id'], ['gsid']);
373                 if (!empty($contact['gsid'])) {
374                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
375                 }
376
377                 if ($item['author-id'] != $item['owner-id']) {
378                         $contact = Contact::getById($item['owner-id'], ['gsid']);
379                         if (!empty($contact['gsid'])) {
380                                 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
381                         }
382                 }
383
384                 return $item;
385         }
386
387         /**
388          * Delete items
389          *
390          * @param array $activity
391          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
392          * @throws \ImagickException
393          */
394         public static function deleteItem($activity)
395         {
396                 $owner = Contact::getIdForURL($activity['actor']);
397
398                 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner'  => $owner]);
399                 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
400         }
401
402         /**
403          * Prepare the item array for an activity
404          *
405          * @param array $activity Activity array
406          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
407          * @throws \ImagickException
408          */
409         public static function addTag($activity)
410         {
411                 if (empty($activity['object_content']) || empty($activity['object_id'])) {
412                         return;
413                 }
414
415                 foreach ($activity['receiver'] as $receiver) {
416                         $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
417                         if (!DBA::isResult($item)) {
418                                 // We don't fetch missing content for this purpose
419                                 continue;
420                         }
421
422                         if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
423                                 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
424                                 continue;
425                         }
426
427                         Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
428                         Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
429                 }
430         }
431
432         /**
433          * Prepare the item array for an activity
434          *
435          * @param array  $activity Activity array
436          * @param string $verb     Activity verb
437          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
438          * @throws \ImagickException
439          */
440         public static function createActivity($activity, $verb)
441         {
442                 $item = self::createItem($activity);
443                 $item['verb'] = $verb;
444                 $item['thr-parent'] = $activity['object_id'];
445                 $item['gravity'] = GRAVITY_ACTIVITY;
446                 $item['object-type'] = Activity\ObjectType::NOTE;
447
448                 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
449
450                 self::postItem($activity, $item);
451         }
452
453         /**
454          * Create an event
455          *
456          * @param array $activity Activity array
457          * @param array $item
458          * @throws \Exception
459          */
460         public static function createEvent($activity, $item)
461         {
462                 $event['summary']   = HTML::toBBCode($activity['name']);
463                 $event['desc']      = HTML::toBBCode($activity['content']);
464                 $event['start']     = $activity['start-time'];
465                 $event['finish']    = $activity['end-time'];
466                 $event['nofinish']  = empty($event['finish']);
467                 $event['location']  = $activity['location'];
468                 $event['adjust']    = true;
469                 $event['cid']       = $item['contact-id'];
470                 $event['uid']       = $item['uid'];
471                 $event['uri']       = $item['uri'];
472                 $event['edited']    = $item['edited'];
473                 $event['private']   = $item['private'];
474                 $event['guid']      = $item['guid'];
475                 $event['plink']     = $item['plink'];
476                 $event['network']   = $item['network'];
477                 $event['protocol']  = $item['protocol'];
478                 $event['direction'] = $item['direction'];
479                 $event['source']    = $item['source'];
480
481                 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
482                 $ev = DBA::selectFirst('event', ['id'], $condition);
483                 if (DBA::isResult($ev)) {
484                         $event['id'] = $ev['id'];
485                 }
486
487                 $event_id = Event::store($event);
488                 Logger::info('Event was stored', ['id' => $event_id]);
489         }
490
491         /**
492          * Process the content
493          *
494          * @param array $activity Activity array
495          * @param array $item
496          * @return array|bool Returns the item array or false if there was an unexpected occurrence
497          * @throws \Exception
498          */
499         private static function processContent($activity, $item)
500         {
501                 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
502                         $item['title'] = Markdown::toBBCode($activity['name']);
503                         $content = Markdown::toBBCode($activity['content']);
504                 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
505                         $item['title'] = $activity['name'];
506                         $content = $activity['content'];
507                 } else {
508                         // By default assume "text/html"
509                         $item['title'] = HTML::toBBCode($activity['name']);
510                         $content = HTML::toBBCode($activity['content']);
511                 }
512
513                 if (!empty($activity['languages'])) {
514                         $item['language'] = self::processLanguages($activity['languages']);
515                 }
516
517                 if (!empty($activity['emojis'])) {
518                         $content = self::replaceEmojis($content, $activity['emojis']);
519                 }
520
521                 $content = self::convertMentions($content);
522
523                 if (!empty($activity['source'])) {
524                         $item['body'] = $activity['source'];
525                         $item['raw-body'] = $content;
526                 } else {
527                         if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
528                                 $item_private = !in_array(0, $activity['item_receiver']);
529                                 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
530                                 if (!DBA::isResult($parent)) {
531                                         Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
532                                         return false;
533                                 }
534                                 if ($item_private && ($parent['private'] != Item::PRIVATE)) {
535                                         Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
536                                         return false;
537                                 }
538
539                                 $content = self::removeImplicitMentionsFromBody($content, $parent);
540                         }
541                         $item['content-warning'] = HTML::toBBCode($activity['summary']);
542                         $item['raw-body'] = $item['body'] = $content;
543                 }
544
545                 self::storeFromBody($item);
546                 self::storeTags($item['uri-id'], $activity['tags']);
547
548                 $item['location'] = $activity['location'];
549
550                 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
551                         $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
552                 }
553
554                 $item['app'] = $activity['generator'];
555
556                 return $item;
557         }
558
559         /**
560          * Store hashtags and mentions
561          *
562          * @param array $item
563          */
564         private static function storeFromBody(array $item)
565         {
566                 // Make sure to delete all existing tags (can happen when called via the update functionality)
567                 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
568
569                 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
570         }
571
572         /**
573          * Generate a GUID out of an URL
574          *
575          * @param string $url message URL
576          * @return string with GUID
577          */
578         private static function getGUIDByURL(string $url)
579         {
580                 $parsed = parse_url($url);
581
582                 $host_hash = hash('crc32', $parsed['host']);
583
584                 unset($parsed["scheme"]);
585                 unset($parsed["host"]);
586
587                 $path = implode("/", $parsed);
588
589                 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
590         }
591
592         /**
593          * Creates an item post
594          *
595          * @param array $activity Activity data
596          * @param array $item     item array
597          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
598          * @throws \ImagickException
599          */
600         public static function postItem(array $activity, array $item)
601         {
602                 if (empty($item)) {
603                         return;
604                 }
605
606                 $stored = false;
607                 ksort($activity['receiver']);
608
609                 foreach ($activity['receiver'] as $receiver) {
610                         if ($receiver == -1) {
611                                 continue;
612                         }
613
614                         $item['uid'] = $receiver;
615
616                         $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
617                         switch($type) {
618                                 case Receiver::TARGET_TO:
619                                         $item['post-type'] = Item::PT_TO;
620                                         break;
621                                 case Receiver::TARGET_CC:
622                                         $item['post-type'] = Item::PT_CC;
623                                         break;
624                                 case Receiver::TARGET_BTO:
625                                         $item['post-type'] = Item::PT_BTO;
626                                         break;
627                                 case Receiver::TARGET_BCC:
628                                         $item['post-type'] = Item::PT_BCC;
629                                         break;
630                                 case Receiver::TARGET_FOLLOWER:
631                                         $item['post-type'] = Item::PT_FOLLOWER;
632                                         break;
633                                 case Receiver::TARGET_ANSWER:
634                                         $item['post-type'] = Item::PT_COMMENT;
635                                         break;
636                                 case Receiver::TARGET_GLOBAL:
637                                         $item['post-type'] = Item::PT_GLOBAL;
638                                         break;
639                                 default:
640                                         $item['post-type'] = Item::PT_ARTICLE;
641                         }
642
643                         if (!empty($activity['from-relay'])) {
644                                 $item['post-type'] = Item::PT_RELAY;
645                         } elseif (!empty($activity['thread-completion'])) {
646                                 $item['post-type'] = Item::PT_FETCHED;
647                         }
648
649                         if ($item['isForum'] ?? false) {
650                                 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
651                         } else {
652                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
653                         }
654
655                         if (($receiver != 0) && empty($item['contact-id'])) {
656                                 $item['contact-id'] = Contact::getIdForURL($activity['author']);
657                         }
658
659                         if (!empty($activity['directmessage'])) {
660                                 self::postMail($activity, $item);
661                                 continue;
662                         }
663
664                         if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
665                                 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
666
667                                 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
668                                         $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
669                                 }
670
671                                 if ($skip) {
672                                         Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
673                                         continue;
674                                 }
675
676                                 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
677                         }
678
679                         if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
680                                 self::createEvent($activity, $item);
681                         }
682
683                         $item_id = Item::insert($item);
684                         if ($item_id) {
685                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
686                         } else {
687                                 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
688                         }
689
690                         if ($item['uid'] == 0) {
691                                 $stored = $item_id;
692                         }
693                 }
694
695                 // Store send a follow request for every reshare - but only when the item had been stored
696                 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
697                         $author = APContact::getByURL($item['owner-link'], false);
698                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
699                         if ($author['type'] != 'Group') {
700                                 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
701                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
702                         }
703                 }
704         }
705
706         /**
707          * Store tags and mentions into the tag table
708          *
709          * @param integer $uriid
710          * @param array $tags
711          */
712         private static function storeTags(int $uriid, array $tags = null)
713         {
714                 foreach ($tags as $tag) {
715                         if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
716                                 continue;
717                         }
718
719                         $hash = substr($tag['name'], 0, 1);
720
721                         if ($tag['type'] == 'Mention') {
722                                 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
723                                         Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
724                                         Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
725                                         $tag['name'] = substr($tag['name'], 1);
726                                 }
727                                 $type = Tag::IMPLICIT_MENTION;
728
729                                 if (!empty($tag['href'])) {
730                                         $apcontact = APContact::getByURL($tag['href']);
731                                         if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
732                                                 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
733                                         }
734                                 }
735                         } elseif ($tag['type'] == 'Hashtag') {
736                                 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
737                                         $tag['name'] = substr($tag['name'], 1);
738                                 }
739                                 $type = Tag::HASHTAG;
740                         }
741
742                         if (empty($tag['name'])) {
743                                 continue;
744                         }
745
746                         Tag::store($uriid, $type, $tag['name'], $tag['href']);
747                 }
748         }
749
750         /**
751          * Creates an mail post
752          *
753          * @param array $activity Activity data
754          * @param array $item     item array
755          * @return int|bool New mail table row id or false on error
756          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
757          */
758         private static function postMail($activity, $item)
759         {
760                 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
761                         Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
762                         return false;
763                 }
764
765                 Logger::info('Direct Message', $item);
766
767                 $msg = [];
768                 $msg['uid'] = $item['uid'];
769
770                 $msg['contact-id'] = $item['contact-id'];
771
772                 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
773                 $msg['from-name'] = $contact['name'];
774                 $msg['from-url'] = $contact['url'];
775                 $msg['from-photo'] = $contact['photo'];
776
777                 $msg['uri'] = $item['uri'];
778                 $msg['created'] = $item['created'];
779
780                 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
781                 if (DBA::isResult($parent)) {
782                         $msg['parent-uri'] = $parent['parent-uri'];
783                         $msg['title'] = $parent['title'];
784                 } else {
785                         $msg['parent-uri'] = $item['thr-parent'];
786
787                         if (!empty($item['title'])) {
788                                 $msg['title'] = $item['title'];
789                         } elseif (!empty($item['content-warning'])) {
790                                 $msg['title'] = $item['content-warning'];
791                         } else {
792                                 // Trying to generate a title out of the body
793                                 $title = $item['body'];
794
795                                 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
796                                         $title = $matches[3];
797                                 }
798
799                                 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, BBCode::API, true), 0));
800
801                                 if (strlen($title) > 20) {
802                                         $title = substr($title, 0, 20) . '...';
803                                 }
804
805                                 $msg['title'] = $title;
806                         }
807                 }
808                 $msg['body'] = $item['body'];
809
810                 return Mail::insert($msg);
811         }
812
813         /**
814          * Fetches missing posts
815          *
816          * @param string $url         message URL
817          * @param array  $child       activity array with the child of this message
818          * @param string $relay_actor Relay actor
819          * @return string fetched message URL
820          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
821          */
822         public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '')
823         {
824                 if (!empty($child['receiver'])) {
825                         $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
826                 } else {
827                         $uid = 0;
828                 }
829
830                 $object = ActivityPub::fetchContent($url, $uid);
831                 if (empty($object)) {
832                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
833                         return '';
834                 }
835
836                 if (empty($object['id'])) {
837                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
838                         return '';
839                 }
840
841                 if (!empty($object['actor'])) {
842                         $object_actor = $object['actor'];
843                 } elseif (!empty($object['attributedTo'])) {
844                         $object_actor = $object['attributedTo'];
845                         if (is_array($object_actor)) {
846                                 $compacted = JsonLD::compact($object);
847                                 $object_actor = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
848                         }
849                 } else {
850                         // Shouldn't happen
851                         $object_actor = '';
852                 }
853
854                 $signer = [$object_actor];
855
856                 if (!empty($child['author'])) {
857                         $actor = $child['author'];
858                         $signer[] = $actor;
859                 } else {
860                         $actor = $object_actor;
861                 }
862
863                 if (!empty($object['published'])) {
864                         $published = $object['published'];
865                 } elseif (!empty($child['published'])) {
866                         $published = $child['published'];
867                 } else {
868                         $published = DateTimeFormat::utcNow();
869                 }
870
871                 $activity = [];
872                 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
873                 unset($object['@context']);
874                 $activity['id'] = $object['id'];
875                 $activity['to'] = $object['to'] ?? [];
876                 $activity['cc'] = $object['cc'] ?? [];
877                 $activity['actor'] = $actor;
878                 $activity['object'] = $object;
879                 $activity['published'] = $published;
880                 $activity['type'] = 'Create';
881
882                 $ldactivity = JsonLD::compact($activity);
883
884                 if (!empty($relay_actor)) {
885                         $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
886                 } elseif (!empty($child['thread-completion'])) {
887                         $ldactivity['thread-completion'] = $child['thread-completion'];
888                 } else {
889                         $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
890                 }
891
892                 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
893                         return '';
894                 }
895
896                 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
897
898                 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
899
900                 return $activity['id'];
901         }
902
903         /**
904          * Test if incoming relay messages should be accepted
905          *
906          * @param array $activity activity array
907          * @param string $id      object ID
908          * @return boolean true if message is accepted
909          */
910         private static function acceptIncomingMessage(array $activity, string $id)
911         {
912                 if (empty($activity['as:object'])) {
913                         Logger::info('No object field in activity - accepted', ['id' => $id]);
914                         return true;
915                 }
916
917                 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
918                 $uriid = ItemURI::getIdByURI($replyto);
919                 if (Post::exists(['uri-id' => $uriid])) {
920                         Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
921                         return true;
922                 }
923
924                 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
925                 $authorid = Contact::getIdForURL($attributed_to);
926
927                 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value'));
928
929                 $messageTags = [];
930                 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
931                 if (!empty($tags)) {
932                         foreach ($tags as $tag) {
933                                 if ($tag['type'] != 'Hashtag') {
934                                         continue;
935                                 }
936                                 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
937                         }
938                 }
939
940                 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
941         }
942
943         /**
944          * perform a "follow" request
945          *
946          * @param array $activity
947          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
948          * @throws \ImagickException
949          */
950         public static function followUser($activity)
951         {
952                 $uid = User::getIdForURL($activity['object_id']);
953                 if (empty($uid)) {
954                         return;
955                 }
956
957                 $owner = User::getOwnerDataById($uid);
958                 if (empty($owner)) {
959                         return;
960                 }
961
962                 $cid = Contact::getIdForURL($activity['actor'], $uid);
963                 if (!empty($cid)) {
964                         self::switchContact($cid);
965                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
966                 }
967
968                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
969                         'author-link' => $activity['actor']];
970
971                 // Ensure that the contact has got the right network type
972                 self::switchContact($item['author-id']);
973
974                 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
975                 if ($result === true) {
976                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
977                 }
978
979                 $cid = Contact::getIdForURL($activity['actor'], $uid);
980                 if (empty($cid)) {
981                         return;
982                 }
983
984                 if (empty($contact)) {
985                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
986                 }
987
988                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
989         }
990
991         /**
992          * Update the given profile
993          *
994          * @param array $activity
995          * @throws \Exception
996          */
997         public static function updatePerson($activity)
998         {
999                 if (empty($activity['object_id'])) {
1000                         return;
1001                 }
1002
1003                 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1004                 Contact::updateFromProbeByURL($activity['object_id']);
1005         }
1006
1007         /**
1008          * Delete the given profile
1009          *
1010          * @param array $activity
1011          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1012          */
1013         public static function deletePerson($activity)
1014         {
1015                 if (empty($activity['object_id']) || empty($activity['actor'])) {
1016                         Logger::info('Empty object id or actor.');
1017                         return;
1018                 }
1019
1020                 if ($activity['object_id'] != $activity['actor']) {
1021                         Logger::info('Object id does not match actor.');
1022                         return;
1023                 }
1024
1025                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1026                 while ($contact = DBA::fetch($contacts)) {
1027                         Contact::remove($contact['id']);
1028                 }
1029                 DBA::close($contacts);
1030
1031                 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1032         }
1033
1034         /**
1035          * Accept a follow request
1036          *
1037          * @param array $activity
1038          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1039          * @throws \ImagickException
1040          */
1041         public static function acceptFollowUser($activity)
1042         {
1043                 $uid = User::getIdForURL($activity['object_actor']);
1044                 if (empty($uid)) {
1045                         return;
1046                 }
1047
1048                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1049                 if (empty($cid)) {
1050                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1051                         return;
1052                 }
1053
1054                 self::switchContact($cid);
1055
1056                 $fields = ['pending' => false];
1057
1058                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1059                 if ($contact['rel'] == Contact::FOLLOWER) {
1060                         $fields['rel'] = Contact::FRIEND;
1061                 }
1062
1063                 $condition = ['id' => $cid];
1064                 DBA::update('contact', $fields, $condition);
1065                 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1066         }
1067
1068         /**
1069          * Reject a follow request
1070          *
1071          * @param array $activity
1072          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1073          * @throws \ImagickException
1074          */
1075         public static function rejectFollowUser($activity)
1076         {
1077                 $uid = User::getIdForURL($activity['object_actor']);
1078                 if (empty($uid)) {
1079                         return;
1080                 }
1081
1082                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1083                 if (empty($cid)) {
1084                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1085                         return;
1086                 }
1087
1088                 self::switchContact($cid);
1089
1090                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
1091                         Contact::remove($cid);
1092                         Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1093                 } else {
1094                         Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1095                 }
1096         }
1097
1098         /**
1099          * Undo activity like "like" or "dislike"
1100          *
1101          * @param array $activity
1102          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1103          * @throws \ImagickException
1104          */
1105         public static function undoActivity($activity)
1106         {
1107                 if (empty($activity['object_id'])) {
1108                         return;
1109                 }
1110
1111                 if (empty($activity['object_actor'])) {
1112                         return;
1113                 }
1114
1115                 $author_id = Contact::getIdForURL($activity['object_actor']);
1116                 if (empty($author_id)) {
1117                         return;
1118                 }
1119
1120                 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1121         }
1122
1123         /**
1124          * Activity to remove a follower
1125          *
1126          * @param array $activity
1127          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1128          * @throws \ImagickException
1129          */
1130         public static function undoFollowUser($activity)
1131         {
1132                 $uid = User::getIdForURL($activity['object_object']);
1133                 if (empty($uid)) {
1134                         return;
1135                 }
1136
1137                 $owner = User::getOwnerDataById($uid);
1138                 if (empty($owner)) {
1139                         return;
1140                 }
1141
1142                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1143                 if (empty($cid)) {
1144                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1145                         return;
1146                 }
1147
1148                 self::switchContact($cid);
1149
1150                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1151                 if (!DBA::isResult($contact)) {
1152                         return;
1153                 }
1154
1155                 Contact::removeFollower($owner, $contact);
1156                 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1157         }
1158
1159         /**
1160          * Switches a contact to AP if needed
1161          *
1162          * @param integer $cid Contact ID
1163          * @throws \Exception
1164          */
1165         private static function switchContact($cid)
1166         {
1167                 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1168                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1169                         return;
1170                 }
1171
1172                 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1173                 Contact::updateFromProbe($cid);
1174         }
1175
1176         /**
1177          * Collects implicit mentions like:
1178          * - the author of the parent item
1179          * - all the mentioned conversants in the parent item
1180          *
1181          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1182          * @return array
1183          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1184          */
1185         private static function getImplicitMentionList(array $parent)
1186         {
1187                 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1188
1189                 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1190
1191                 $implicit_mentions = [];
1192                 if (empty($parent_author['url'])) {
1193                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1194                 } else {
1195                         $implicit_mentions[] = $parent_author['url'];
1196                         $implicit_mentions[] = $parent_author['nurl'];
1197                         $implicit_mentions[] = $parent_author['alias'];
1198                 }
1199
1200                 if (!empty($parent['alias'])) {
1201                         $implicit_mentions[] = $parent['alias'];
1202                 }
1203
1204                 foreach ($parent_terms as $term) {
1205                         $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1206                         if (!empty($contact['url'])) {
1207                                 $implicit_mentions[] = $contact['url'];
1208                                 $implicit_mentions[] = $contact['nurl'];
1209                                 $implicit_mentions[] = $contact['alias'];
1210                         }
1211                 }
1212
1213                 return $implicit_mentions;
1214         }
1215
1216         /**
1217          * Strips from the body prepended implicit mentions
1218          *
1219          * @param string $body
1220          * @param array $parent
1221          * @return string
1222          */
1223         private static function removeImplicitMentionsFromBody(string $body, array $parent)
1224         {
1225                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1226                         return $body;
1227                 }
1228
1229                 $potential_mentions = self::getImplicitMentionList($parent);
1230
1231                 $kept_mentions = [];
1232
1233                 // Extract one prepended mention at a time from the body
1234                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1235                         if (!in_array($matches[2], $potential_mentions)) {
1236                                 $kept_mentions[] = $matches[1];
1237                         }
1238
1239                         $body = $matches[3];
1240                 }
1241
1242                 // Re-appending the kept mentions to the body after extraction
1243                 $kept_mentions[] = $body;
1244
1245                 return implode('', $kept_mentions);
1246         }
1247 }