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