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