]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
e3e2e295af56580ea1252c5c7ec280761a04b102
[friendica.git] / src / Protocol / ActivityPub / Processor.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Event;
38 use Friendica\Model\GServer;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Model\Post;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\ActivityPub;
47 use Friendica\Protocol\Relay;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\HTTPSignature;
50 use Friendica\Util\JsonLD;
51 use Friendica\Util\Network;
52 use Friendica\Util\Strings;
53 use Friendica\Worker\Delivery;
54
55 /**
56  * ActivityPub Processor Protocol class
57  */
58 class Processor
59 {
60         const CACHEKEY_FETCH_ACTIVITY = 'processor:fetchMissingActivity:';
61         /**
62          * Extracts the tag character (#, @, !) from mention links
63          *
64          * @param string $body
65          * @return string
66          */
67         protected static function normalizeMentionLinks(string $body): string
68         {
69                 return preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
70         }
71
72         /**
73          * Convert the language array into a language JSON
74          *
75          * @param array $languages
76          * @return string language JSON
77          */
78         private static function processLanguages(array $languages): string
79         {
80                 $codes = array_keys($languages);
81                 $lang = [];
82                 foreach ($codes as $code) {
83                         $lang[$code] = 1;
84                 }
85
86                 if (empty($lang)) {
87                         return '';
88                 }
89
90                 return json_encode($lang);
91         }
92         /**
93          * Replaces emojis in the body
94          *
95          * @param int $uri_id
96          * @param string $body
97          * @param array $emojis
98          *
99          * @return string with replaced emojis
100          */
101         private static function replaceEmojis(int $uri_id, string $body, array $emojis): string
102         {
103                 $body = strtr($body,
104                         array_combine(
105                                 array_column($emojis, 'name'),
106                                 array_map(function ($emoji) {
107                                         return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
108                                 }, $emojis)
109                         )
110                 );
111
112                 // We store the emoji here to be able to avoid storing it in the media
113                 foreach ($emojis as $emoji) {
114                         Post\Link::getByLink($uri_id, $emoji['href']);
115                 }
116                 return $body;
117         }
118
119         /**
120          * Store attached media files in the post-media table
121          *
122          * @param int $uriid
123          * @param array $attachment
124          * @return void
125          */
126         private static function storeAttachmentAsMedia(int $uriid, array $attachment)
127         {
128                 if (empty($attachment['url'])) {
129                         return;
130                 }
131
132                 $data = ['uri-id' => $uriid];
133                 $data['type'] = Post\Media::UNKNOWN;
134                 $data['url'] = $attachment['url'];
135                 $data['mimetype'] = $attachment['mediaType'] ?? null;
136                 $data['height'] = $attachment['height'] ?? null;
137                 $data['width'] = $attachment['width'] ?? null;
138                 $data['size'] = $attachment['size'] ?? null;
139                 $data['preview'] = $attachment['image'] ?? null;
140                 $data['description'] = $attachment['name'] ?? null;
141
142                 Post\Media::insert($data);
143         }
144
145         /**
146          * Stire attachment data
147          *
148          * @param array   $activity
149          * @param array   $item
150          */
151         private static function storeAttachments(array $activity, array $item)
152         {
153                 if (empty($activity['attachments'])) {
154                         return;
155                 }
156
157                 foreach ($activity['attachments'] as $attach) {
158                         self::storeAttachmentAsMedia($item['uri-id'], $attach);
159                 }
160         }
161
162         /**
163          * Store attachment data
164          *
165          * @param array   $activity
166          * @param array   $item
167          */
168         private static function storeQuestion(array $activity, array $item)
169         {
170                 if (empty($activity['question'])) {
171                         return;
172                 }
173                 $question = ['multiple' => $activity['question']['multiple']];
174
175                 if (!empty($activity['question']['voters'])) {
176                         $question['voters'] = $activity['question']['voters'];
177                 }
178
179                 if (!empty($activity['question']['end-time'])) {
180                         $question['end-time'] = DateTimeFormat::utc($activity['question']['end-time']);
181                 }
182
183                 Post\Question::update($item['uri-id'], $question);
184
185                 foreach ($activity['question']['options'] as $key => $option) {
186                         $option = ['name' => $option['name'], 'replies' => $option['replies']];
187                         Post\QuestionOption::update($item['uri-id'], $key, $option);
188                 }
189
190                 Logger::debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]);
191         }
192
193         /**
194          * Updates a message
195          *
196          * @param array      $activity   Activity array
197          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
198          * @throws \ImagickException
199          */
200         public static function updateItem(array $activity)
201         {
202                 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type'], ['uri' => $activity['id']]);
203                 if (!DBA::isResult($item)) {
204                         Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
205                         $item = self::createItem($activity);
206                         if (empty($item)) {
207                                 return;
208                         }
209
210                         self::postItem($activity, $item);
211                         return;
212                 }
213
214                 $item['changed'] = DateTimeFormat::utcNow();
215                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
216
217                 $item = self::processContent($activity, $item);
218                 if (empty($item)) {
219                         return;
220                 }
221
222                 self::storeAttachments($activity, $item);
223                 self::storeQuestion($activity, $item);
224
225                 Post\History::add($item['uri-id'], $item);
226                 Item::update($item, ['uri' => $activity['id']]);
227
228                 Queue::remove($activity);
229
230                 if ($activity['object_type'] == 'as:Event') {
231                         $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
232                         while ($post = DBA::fetch($posts)) {
233                                 self::updateEvent($post['event-id'], $activity);
234                         }
235                 }
236         }
237
238         /**
239          * Update an existing event
240          *
241          * @param int $event_id
242          * @param array $activity
243          */
244         private static function updateEvent(int $event_id, array $activity)
245         {
246                 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
247
248                 $event['edited']   = DateTimeFormat::utc($activity['updated']);
249                 $event['summary']  = HTML::toBBCode($activity['name']);
250                 $event['desc']     = HTML::toBBCode($activity['content']);
251                 if (!empty($activity['start-time'])) {
252                         $event['start']  = DateTimeFormat::utc($activity['start-time']);
253                 }
254                 if (!empty($activity['end-time'])) {
255                         $event['finish'] = DateTimeFormat::utc($activity['end-time']);
256                 }
257                 $event['nofinish'] = empty($event['finish']);
258                 $event['location'] = $activity['location'];
259
260                 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
261                 Event::store($event);
262         }
263
264         /**
265          * Prepares data for a message
266          *
267          * @param array      $activity   Activity array
268          * @return array Internal item
269          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270          * @throws \ImagickException
271          */
272         public static function createItem(array $activity): array
273         {
274                 $item = [];
275                 $item['verb'] = Activity::POST;
276                 $item['thr-parent'] = $activity['reply-to-id'];
277
278                 if ($activity['reply-to-id'] == $activity['id']) {
279                         $item['gravity'] = GRAVITY_PARENT;
280                         $item['object-type'] = Activity\ObjectType::NOTE;
281                 } else {
282                         $item['gravity'] = GRAVITY_COMMENT;
283                         $item['object-type'] = Activity\ObjectType::COMMENT;
284                 }
285
286                 if (!empty($activity['context'])) {
287                         $item['conversation'] = $activity['context'];
288                 } elseif (!empty($activity['conversation'])) {
289                         $item['conversation'] = $activity['conversation'];
290                 }
291
292                 if (!empty($item['conversation'])) {
293                         $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]);
294                         if (!empty($conversation)) {
295                                 Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]);
296                                 $item['parent-uri'] = $conversation['uri'];
297                         }
298                 } else {
299                         $conversation = [];
300                 }
301
302                 if (empty($activity['author']) && empty($activity['actor'])) {
303                         Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]);
304                         return [];
305                 }
306
307                 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
308                         $recursion_depth = $activity['recursion-depth'] ?? 0;
309                         Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
310                         if ($recursion_depth < DI::config()->get('system', 'max_recursion_depth')) {
311                                 $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
312                                 if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
313                                         // Recursively delete this and all depending entries
314                                         Queue::deleteById($activity['entry-id']);
315                                         return [];
316                                 }
317                                 $fetch_by_worker = empty($result);
318                         } else {
319                                 Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
320                                 $fetch_by_worker = true;
321                         }
322
323                         if ($fetch_by_worker && Queue::hasWorker($activity)) {
324                                 Logger::notice('There is already a worker task to fetch the post.', ['id' => $activity['id'], 'parent' => $activity['reply-to-id']]);
325                                 $fetch_by_worker = false;
326                                 if (!empty($conversation)) {
327                                         return [];
328                                 }
329                         }
330
331                         if ($fetch_by_worker) {
332                                 Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
333                                 $activity['recursion-depth'] = 0;
334                                 $wid = Worker::add(PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
335                                 Queue::setWorkerId($activity, $wid);
336                                 if (!empty($conversation)) {
337                                         return [];
338                                 }
339                         } elseif (!empty($result)) {
340                                 if (($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
341                                         $item['thr-parent'] = $result;
342                                 }
343                         }
344                 }
345
346                 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
347
348                 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
349                         Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
350                         return [];
351                 }
352
353                 $item['network'] = Protocol::ACTIVITYPUB;
354                 $item['author-link'] = $activity['author'];
355                 $item['author-id'] = Contact::getIdForURL($activity['author']);
356                 $item['owner-link'] = $activity['actor'];
357                 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
358
359                 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
360                         $item['private'] = Item::UNLISTED;
361                 } elseif (in_array(0, $activity['receiver'])) {
362                         $item['private'] = Item::PUBLIC;
363                 } else {
364                         $item['private'] = Item::PRIVATE;
365                 }
366
367                 if (!empty($activity['raw'])) {
368                         $item['source'] = $activity['raw'];
369                         $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
370                 }
371
372                 if (isset($activity['push'])) {
373                         $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
374                 }
375
376                 if (!empty($activity['from-relay'])) {
377                         $item['direction'] = Conversation::RELAY;
378                 }
379
380                 if ($activity['object_type'] == 'as:Article') {
381                         $item['post-type'] = Item::PT_ARTICLE;
382                 } elseif ($activity['object_type'] == 'as:Audio') {
383                         $item['post-type'] = Item::PT_AUDIO;
384                 } elseif ($activity['object_type'] == 'as:Document') {
385                         $item['post-type'] = Item::PT_DOCUMENT;
386                 } elseif ($activity['object_type'] == 'as:Event') {
387                         $item['post-type'] = Item::PT_EVENT;
388                 } elseif ($activity['object_type'] == 'as:Image') {
389                         $item['post-type'] = Item::PT_IMAGE;
390                 } elseif ($activity['object_type'] == 'as:Page') {
391                         $item['post-type'] = Item::PT_PAGE;
392                 } elseif ($activity['object_type'] == 'as:Question') {
393                         $item['post-type'] = Item::PT_POLL;
394                 } elseif ($activity['object_type'] == 'as:Video') {
395                         $item['post-type'] = Item::PT_VIDEO;
396                 } else {
397                         $item['post-type'] = Item::PT_NOTE;
398                 }
399
400                 $item['isForum'] = false;
401
402                 if (!empty($activity['thread-completion'])) {
403                         if ($activity['thread-completion'] != $item['owner-id']) {
404                                 $actor = Contact::getById($activity['thread-completion'], ['url']);
405                                 $item['causer-link'] = $actor['url'];
406                                 $item['causer-id'] = $activity['thread-completion'];
407                                 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
408                         } else {
409                                 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
410                                 $item['causer-link'] = $item['owner-link'];
411                                 $item['causer-id']   = $item['owner-id'];
412                                 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
413                         }
414
415                         $item['owner-link'] = $item['author-link'];
416                         $item['owner-id'] = $item['author-id'];
417                 } else {
418                         $actor = APContact::getByURL($item['owner-link'], false);
419                         $item['isForum'] = ($actor['type'] == 'Group');
420                 }
421
422                 $item['uri'] = $activity['id'];
423
424                 if (empty($activity['published']) || empty($activity['updated'])) {
425                         DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
426                 }
427
428                 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
429                 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
430                 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
431                 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
432
433                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
434                 if (empty($item['uri-id'])) {
435                         Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
436                         return [];
437                 }
438
439                 $item = self::processContent($activity, $item);
440                 if (empty($item)) {
441                         Logger::info('Message was not processed');
442                         return [];
443                 }
444
445                 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
446
447                 self::storeAttachments($activity, $item);
448                 self::storeQuestion($activity, $item);
449
450                 // We received the post via AP, so we set the protocol of the server to AP
451                 $contact = Contact::getById($item['author-id'], ['gsid']);
452                 if (!empty($contact['gsid'])) {
453                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
454                 }
455
456                 if ($item['author-id'] != $item['owner-id']) {
457                         $contact = Contact::getById($item['owner-id'], ['gsid']);
458                         if (!empty($contact['gsid'])) {
459                                 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
460                         }
461                 }
462
463                 return $item;
464         }
465
466         /**
467          * Check if a given activity is no longer available
468          *
469          * @param string $url
470          *
471          * @return boolean
472          */
473         public static function isActivityGone(string $url): bool
474         {
475                 $curlResult = HTTPSignature::fetchRaw($url, 0);
476
477                 if (Network::isUrlBlocked($url)) {
478                         return true;
479                 }
480
481                 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
482                 if (in_array($curlResult->getReturnCode(), [404])) {
483                         return true;
484                 }
485
486                 $object = json_decode($curlResult->getBody(), true);
487                 if (!empty($object)) {
488                         $activity = JsonLD::compact($object);
489                         if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
490                                 return true;
491                         }                       
492                 }
493
494                 return false;
495         }
496         /**
497          * Delete items
498          *
499          * @param array $activity
500          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501          * @throws \ImagickException
502          */
503         public static function deleteItem(array $activity)
504         {
505                 $owner = Contact::getIdForURL($activity['actor']);
506
507                 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner'  => $owner]);
508                 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
509                 Queue::remove($activity);
510         }
511
512         /**
513          * Prepare the item array for an activity
514          *
515          * @param array $activity Activity array
516          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
517          * @throws \ImagickException
518          */
519         public static function addTag(array $activity)
520         {
521                 if (empty($activity['object_content']) || empty($activity['object_id'])) {
522                         return;
523                 }
524
525                 foreach ($activity['receiver'] as $receiver) {
526                         $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
527                         if (!DBA::isResult($item)) {
528                                 // We don't fetch missing content for this purpose
529                                 continue;
530                         }
531
532                         if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
533                                 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
534                                 continue;
535                         }
536
537                         Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
538                         Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
539                 }
540         }
541
542         /**
543          * Prepare the item array for an activity
544          *
545          * @param array      $activity   Activity array
546          * @param string     $verb       Activity verb
547          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
548          * @throws \ImagickException
549          */
550         public static function createActivity(array $activity, string $verb)
551         {
552                 $activity['reply-to-id'] = $activity['object_id'];
553                 $item = self::createItem($activity);
554                 if (empty($item)) {
555                         return;
556                 }
557
558                 $item['verb'] = $verb;
559                 $item['thr-parent'] = $activity['object_id'];
560                 $item['gravity'] = GRAVITY_ACTIVITY;
561                 unset($item['post-type']);
562                 $item['object-type'] = Activity\ObjectType::NOTE;
563
564                 if (!empty($activity['content'])) {
565                         $item['body'] = HTML::toBBCode($activity['content']);
566                 }
567
568                 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
569
570                 self::postItem($activity, $item);
571         }
572
573         /**
574          * Fetch the Uri-Id of a post for the "featured" collection
575          *
576          * @param array $activity
577          * @return null|int
578          */
579         private static function getUriIdForFeaturedCollection(array $activity)
580         {
581                 $actor = APContact::getByURL($activity['actor']);
582                 if (empty($actor)) {
583                         return null;
584                 }
585
586                 // Refetch the account when the "featured" collection is missing.
587                 // This can be removed in a future version (end of 2022 should be good).
588                 if (empty($actor['featured'])) {
589                         $actor = APContact::getByURL($activity['actor'], true);
590                         if (empty($actor)) {
591                                 return null;
592                         }
593                 }
594
595                 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
596                 if (empty($parent['uri-id'])) {
597                         if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
598                                 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
599                         }
600                 }
601
602                 if (!empty($parent['uri-id'])) {
603                         return $parent['uri-id'];
604                 }
605
606                 return null;
607         }
608
609         /**
610          * Add a post to the "Featured" collection
611          *
612          * @param array $activity
613          */
614         public static function addToFeaturedCollection(array $activity)
615         {
616                 $uriid = self::getUriIdForFeaturedCollection($activity);
617                 if (empty($uriid)) {
618                         return;
619                 }
620
621                 Logger::debug('Add post to featured collection', ['uri-id' => $uriid]);
622
623                 Post\Collection::add($uriid, Post\Collection::FEATURED);
624                 Queue::remove($activity);
625         }
626
627         /**
628          * Remove a post to the "Featured" collection
629          *
630          * @param array $activity
631          */
632         public static function removeFromFeaturedCollection(array $activity)
633         {
634                 $uriid = self::getUriIdForFeaturedCollection($activity);
635                 if (empty($uriid)) {
636                         return;
637                 }
638
639                 Logger::debug('Remove post from featured collection', ['uri-id' => $uriid]);
640
641                 Post\Collection::remove($uriid, Post\Collection::FEATURED);
642                 Queue::remove($activity);
643         }
644
645         /**
646          * Create an event
647          *
648          * @param array $activity Activity array
649          * @param array $item
650          *
651          * @return int event id
652          * @throws \Exception
653          */
654         public static function createEvent(array $activity, array $item): int
655         {
656                 $event['summary']   = HTML::toBBCode($activity['name'] ?: $activity['summary']);
657                 $event['desc']      = HTML::toBBCode($activity['content']);
658                 if (!empty($activity['start-time'])) {
659                         $event['start']  = DateTimeFormat::utc($activity['start-time']);
660                 }
661                 if (!empty($activity['end-time'])) {
662                         $event['finish'] = DateTimeFormat::utc($activity['end-time']);
663                 }
664                 $event['nofinish']  = empty($event['finish']);
665                 $event['location']  = $activity['location'];
666                 $event['cid']       = $item['contact-id'];
667                 $event['uid']       = $item['uid'];
668                 $event['uri']       = $item['uri'];
669                 $event['edited']    = $item['edited'];
670                 $event['private']   = $item['private'];
671                 $event['guid']      = $item['guid'];
672                 $event['plink']     = $item['plink'];
673                 $event['network']   = $item['network'];
674                 $event['protocol']  = $item['protocol'];
675                 $event['direction'] = $item['direction'];
676                 $event['source']    = $item['source'];
677
678                 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
679                 if (DBA::isResult($ev)) {
680                         $event['id'] = $ev['id'];
681                 }
682
683                 $event_id = Event::store($event);
684
685                 Logger::info('Event was stored', ['id' => $event_id]);
686
687                 return $event_id;
688         }
689
690         /**
691          * Process the content
692          *
693          * @param array $activity Activity array
694          * @param array $item
695          * @return array|bool Returns the item array or false if there was an unexpected occurrence
696          * @throws \Exception
697          */
698         private static function processContent(array $activity, array $item)
699         {
700                 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
701                         $item['title'] = strip_tags($activity['name']);
702                         $content = Markdown::toBBCode($activity['content']);
703                 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
704                         $item['title'] = $activity['name'];
705                         $content = $activity['content'];
706                 } else {
707                         // By default assume "text/html"
708                         $item['title'] = HTML::toBBCode($activity['name'] ?? '');
709                         $content = HTML::toBBCode($activity['content'] ?? '');
710                 }
711
712                 $item['title'] = trim(BBCode::toPlaintext($item['title']));
713
714                 if (!empty($activity['languages'])) {
715                         $item['language'] = self::processLanguages($activity['languages']);
716                 }
717
718                 if (!empty($activity['emojis'])) {
719                         $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
720                 }
721
722                 $content = self::addMentionLinks($content, $activity['tags']);
723
724                 if (!empty($activity['source'])) {
725                         $item['body'] = $activity['source'];
726                         $item['raw-body'] = $content;
727                         $item['body'] = Item::improveSharedDataInBody($item);
728                 } else {
729                         $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
730                         if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
731                                 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
732                                 if (!DBA::isResult($parent)) {
733                                         Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
734                                         return false;
735                                 }
736                                 if (($item['private'] == Item::PRIVATE) && ($parent['private'] != Item::PRIVATE)) {
737                                         Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
738                                         return false;
739                                 }
740
741                                 $content = self::removeImplicitMentionsFromBody($content, $parent);
742                         }
743                         $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
744                         $item['raw-body'] = $item['body'] = $content;
745                 }
746
747                 self::storeFromBody($item);
748                 self::storeTags($item['uri-id'], $activity['tags']);
749
750                 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
751
752                 $item['location'] = $activity['location'];
753
754                 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
755                         $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
756                 }
757
758                 $item['app'] = $activity['generator'];
759
760                 return $item;
761         }
762
763         /**
764          * Store hashtags and mentions
765          *
766          * @param array $item
767          */
768         private static function storeFromBody(array $item)
769         {
770                 // Make sure to delete all existing tags (can happen when called via the update functionality)
771                 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
772
773                 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
774         }
775
776         /**
777          * Generate a GUID out of an URL of an ActivityPub post.
778          *
779          * @param string $url message URL
780          * @return string with GUID
781          */
782         private static function getGUIDByURL(string $url): string
783         {
784                 $parsed = parse_url($url);
785
786                 $host_hash = hash('crc32', $parsed['host']);
787
788                 unset($parsed["scheme"]);
789                 unset($parsed["host"]);
790
791                 $path = implode("/", $parsed);
792
793                 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
794         }
795
796         /**
797          * Checks if an incoming message is wanted
798          *
799          * @param array $activity
800          * @param array $item
801          * @return boolean Is the message wanted?
802          */
803         private static function isSolicitedMessage(array $activity, array $item): bool
804         {
805                 // The checks are split to improve the support when searching why a message was accepted.
806                 if (count($activity['receiver']) != 1) {
807                         // The message has more than one receiver, so it is wanted.
808                         Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
809                         return true;
810                 }
811
812                 if ($item['private'] == Item::PRIVATE) {
813                         // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
814                         Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
815                         return true;
816                 }
817
818                 if (!empty($activity['from-relay'])) {
819                         // We check relay posts at another place. When it arrived here, the message is already checked.
820                         Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
821                         return true;
822                 }
823
824                 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUCE])) {
825                         // Manual completions and completions caused by reshares are allowed without any further checks.
826                         Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
827                         return true;
828                 }
829
830                 if ($item['gravity'] != GRAVITY_PARENT) {
831                         // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
832                         // This can possibly be improved in the future.
833                         Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
834                         return true;
835                 }
836
837                 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
838                 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB)) {
839                         Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
840                         return true;
841                 } else {
842                         return false;
843                 }
844         }
845
846         /**
847          * Creates an item post
848          *
849          * @param array $activity Activity data
850          * @param array $item     item array
851          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
852          * @throws \ImagickException
853          */
854         public static function postItem(array $activity, array $item)
855         {
856                 if (empty($item)) {
857                         return;
858                 }
859
860                 $stored = false;
861                 $success = false;
862                 ksort($activity['receiver']);
863
864                 if (!self::isSolicitedMessage($activity, $item)) {
865                         DBA::delete('item-uri', ['id' => $item['uri-id']]);
866                         return;
867                 }
868
869                 foreach ($activity['receiver'] as $receiver) {
870                         if ($receiver == -1) {
871                                 continue;
872                         }
873
874                         $item['uid'] = $receiver;
875
876                         $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
877                         switch($type) {
878                                 case Receiver::TARGET_TO:
879                                         $item['post-reason'] = Item::PR_TO;
880                                         break;
881                                 case Receiver::TARGET_CC:
882                                         $item['post-reason'] = Item::PR_CC;
883                                         break;
884                                 case Receiver::TARGET_BTO:
885                                         $item['post-reason'] = Item::PR_BTO;
886                                         break;
887                                 case Receiver::TARGET_BCC:
888                                         $item['post-reason'] = Item::PR_BCC;
889                                         break;
890                                 case Receiver::TARGET_FOLLOWER:
891                                         $item['post-reason'] = Item::PR_FOLLOWER;
892                                         break;
893                                 case Receiver::TARGET_ANSWER:
894                                         $item['post-reason'] = Item::PR_COMMENT;
895                                         break;
896                                 case Receiver::TARGET_GLOBAL:
897                                         $item['post-reason'] = Item::PR_GLOBAL;
898                                         break;
899                                 default:
900                                         $item['post-reason'] = Item::PR_NONE;
901                         }
902
903                         if (!empty($activity['from-relay'])) {
904                                 $item['post-reason'] = Item::PR_RELAY;
905                         } elseif (!empty($activity['thread-completion'])) {
906                                 $item['post-reason'] = Item::PR_FETCHED;
907                         } elseif (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE]) && !empty($activity['push'])) {
908                                 $item['post-reason'] = Item::PR_PUSHED;
909                         }
910
911                         if ($item['isForum'] ?? false) {
912                                 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
913                         } else {
914                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
915                         }
916
917                         if (($receiver != 0) && empty($item['contact-id'])) {
918                                 $item['contact-id'] = Contact::getIdForURL($activity['author']);
919                         }
920
921                         if (!empty($activity['directmessage'])) {
922                                 self::postMail($activity, $item);
923                                 continue;
924                         }
925
926                         if (!($item['isForum'] ?? false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT) && !Contact::isSharingByURL($activity['author'], $receiver)) {
927                                 if ($item['post-reason'] == Item::PR_BCC) {
928                                         Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id']]);
929                                         continue;
930                                 }
931
932                                 if (
933                                         !empty($activity['thread-children-type'])
934                                         && in_array($activity['thread-children-type'], Receiver::ACTIVITY_TYPES)
935                                         && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE
936                                 ) {
937                                         Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
938                                                 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
939                                         continue;
940                                 }
941                         }
942
943                         $is_forum = false;
944
945                         if ($receiver != 0) {
946                                 $user = User::getById($receiver, ['account-type']);
947                                 if (!empty($user['account-type'])) {
948                                         $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
949                                 }
950                         }
951
952                         if (!$is_forum && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
953                                 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
954
955                                 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
956                                         $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
957                                 }
958
959                                 if ($skip) {
960                                         Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
961                                         continue;
962                                 }
963
964                                 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
965                         }
966
967                         if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
968                                 $event_id = self::createEvent($activity, $item);
969
970                                 $item = Event::getItemArrayForImportedId($event_id, $item);
971                         }
972
973                         $item_id = Item::insert($item);
974                         if ($item_id) {
975                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
976                                 $success = true;
977                         } else {
978                                 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
979                         }
980
981                         if ($item['uid'] == 0) {
982                                 $stored = $item_id;
983                         }
984                 }
985
986                 Queue::remove($activity);
987
988                 if ($success && Queue::hasChildren($item['uri'])) {
989                         Worker::add(PRIORITY_HIGH, 'ProcessReplyByUri', $item['uri']);
990                 }
991
992                 // Store send a follow request for every reshare - but only when the item had been stored
993                 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
994                         $author = APContact::getByURL($item['owner-link'], false);
995                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
996                         if ($author['type'] != 'Group') {
997                                 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
998                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
999                         }
1000                 }
1001         }
1002
1003         /**
1004          * Store tags and mentions into the tag table
1005          *
1006          * @param integer $uriid
1007          * @param array $tags
1008          */
1009         private static function storeTags(int $uriid, array $tags = null)
1010         {
1011                 foreach ($tags as $tag) {
1012                         if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1013                                 continue;
1014                         }
1015
1016                         $hash = substr($tag['name'], 0, 1);
1017
1018                         if ($tag['type'] == 'Mention') {
1019                                 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1020                                         Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1021                                         Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1022                                         $tag['name'] = substr($tag['name'], 1);
1023                                 }
1024                                 $type = Tag::IMPLICIT_MENTION;
1025
1026                                 if (!empty($tag['href'])) {
1027                                         $apcontact = APContact::getByURL($tag['href']);
1028                                         if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1029                                                 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1030                                         }
1031                                 }
1032                         } elseif ($tag['type'] == 'Hashtag') {
1033                                 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1034                                         $tag['name'] = substr($tag['name'], 1);
1035                                 }
1036                                 $type = Tag::HASHTAG;
1037                         }
1038
1039                         if (empty($tag['name'])) {
1040                                 continue;
1041                         }
1042
1043                         Tag::store($uriid, $type, $tag['name'], $tag['href']);
1044                 }
1045         }
1046
1047         public static function storeReceivers(int $uriid, array $receivers)
1048         {
1049                 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
1050                         if (!empty($receivers[$element])) {
1051                                 foreach ($receivers[$element] as $receiver) {
1052                                         if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1053                                                 $name = Receiver::PUBLIC_COLLECTION;
1054                                         } else {
1055                                                 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
1056                                         }
1057
1058                                         $target = Tag::getTargetType($receiver);
1059                                         Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1060                                         Tag::store($uriid, $type, $name, $receiver, $target);
1061                                 }
1062                         }
1063                 }
1064         }
1065
1066         /**
1067          * Creates an mail post
1068          *
1069          * @param array $activity Activity data
1070          * @param array $item     item array
1071          * @return int|bool New mail table row id or false on error
1072          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1073          */
1074         private static function postMail(array $activity, array $item)
1075         {
1076                 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1077                         Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1078                         return false;
1079                 }
1080
1081                 Logger::info('Direct Message', $item);
1082
1083                 $msg = [];
1084                 $msg['uid'] = $item['uid'];
1085
1086                 $msg['contact-id'] = $item['contact-id'];
1087
1088                 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1089                 $msg['from-name'] = $contact['name'];
1090                 $msg['from-url'] = $contact['url'];
1091                 $msg['from-photo'] = $contact['photo'];
1092
1093                 $msg['uri'] = $item['uri'];
1094                 $msg['created'] = $item['created'];
1095
1096                 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1097                 if (DBA::isResult($parent)) {
1098                         $msg['parent-uri'] = $parent['parent-uri'];
1099                         $msg['title'] = $parent['title'];
1100                 } else {
1101                         $msg['parent-uri'] = $item['thr-parent'];
1102
1103                         if (!empty($item['title'])) {
1104                                 $msg['title'] = $item['title'];
1105                         } elseif (!empty($item['content-warning'])) {
1106                                 $msg['title'] = $item['content-warning'];
1107                         } else {
1108                                 // Trying to generate a title out of the body
1109                                 $title = $item['body'];
1110
1111                                 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1112                                         $title = $matches[3];
1113                                 }
1114
1115                                 $title = trim(BBCode::toPlaintext($title));
1116
1117                                 if (strlen($title) > 20) {
1118                                         $title = substr($title, 0, 20) . '...';
1119                                 }
1120
1121                                 $msg['title'] = $title;
1122                         }
1123                 }
1124                 $msg['body'] = $item['body'];
1125
1126                 return Mail::insert($msg);
1127         }
1128
1129         /**
1130          * Fetch featured posts from a contact with the given url
1131          *
1132          * @param string $url
1133          * @return void
1134          */
1135         public static function fetchFeaturedPosts(string $url)
1136         {
1137                 Logger::info('Fetch featured posts', ['contact' => $url]);
1138
1139                 $apcontact = APContact::getByURL($url);
1140                 if (empty($apcontact['featured'])) {
1141                         Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1142                         return;
1143                 }
1144
1145                 $pcid = Contact::getIdForURL($url, 0, false);
1146                 if (empty($pcid)) {
1147                         Logger::info('Contact not found', ['contact' => $url]);
1148                         return;
1149                 }
1150
1151                 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1152                 if (!empty($posts)) {
1153                         $old_featured = array_column($posts, 'uri-id');
1154                 } else {
1155                         $old_featured = [];
1156                 }
1157
1158                 $featured = ActivityPub::fetchItems($apcontact['featured']);
1159                 if (empty($featured)) {
1160                         Logger::info('Contact does not have featured posts', ['contact' => $url]);
1161
1162                         foreach ($old_featured as $uri_id) {
1163                                 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1164                                 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1165                         }
1166                         return;
1167                 }
1168
1169                 $new = 0;
1170                 $old = 0;
1171
1172                 foreach ($featured as $post) {
1173                         if (empty($post['id'])) {
1174                                 continue;
1175                         }
1176                         $id = Item::fetchByLink($post['id']);
1177                         if (!empty($id)) {
1178                                 $item = Post::selectFirst(['uri-id', 'featured'], ['id' => $id]);
1179                                 if (!empty($item['uri-id'])) {
1180                                         if (!$item['featured']) {
1181                                                 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED);
1182                                                 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1183                                                 $new++;
1184                                         } else {
1185                                                 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1186                                                 $old++;
1187                                         }
1188
1189                                         $index = array_search($item['uri-id'], $old_featured);
1190                                         if (!($index === false)) {
1191                                                 unset($old_featured[$index]);
1192                                         }
1193                                 }
1194                         }
1195                 }
1196
1197                 foreach ($old_featured as $uri_id) {
1198                         Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1199                         Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1200                 }
1201
1202                 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1203         }
1204
1205         public static function fetchCachedActivity(string $url, int $uid): array
1206         {
1207                 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . $url;
1208                 $object = DI::cache()->get($cachekey);
1209
1210                 if (!is_null($object)) {
1211                         if (!empty($object)) {
1212                                 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1213                         } else {
1214                                 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1215                         }
1216                         return $object;
1217                 }
1218
1219                 $object = ActivityPub::fetchContent($url, $uid);
1220                 if (empty($object)) {
1221                         Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1222                         // We perform negative caching.
1223                         DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1224                         return [];
1225                 }
1226
1227                 if (empty($object['id'])) {
1228                         Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1229                         return [];
1230                 }
1231                 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1232
1233                 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1234
1235                 return $object;
1236         }
1237
1238         /**
1239          * Fetches missing posts
1240          *
1241          * @param string     $url         message URL
1242          * @param array      $child       activity array with the child of this message
1243          * @param string     $relay_actor Relay actor
1244          * @param int        $completion  Completion mode, see Receiver::COMPLETION_*
1245          * @return string fetched message URL
1246          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1247          * @throws \ImagickException
1248          */
1249         public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL): string
1250         {
1251                 if (!empty($child['receiver'])) {
1252                         $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
1253                 } else {
1254                         $uid = 0;
1255                 }
1256
1257                 $object = self::fetchCachedActivity($url, $uid);
1258                 if (empty($object)) {
1259                         return '';
1260                 }
1261
1262                 $signer = [];
1263
1264                 if (!empty($object['attributedTo'])) {
1265                         $attributed_to = $object['attributedTo'];
1266                         if (is_array($attributed_to)) {
1267                                 $compacted = JsonLD::compact($object);
1268                                 $attributed_to = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1269                         }
1270                         $signer[] = $attributed_to;     
1271                 }
1272
1273                 if (!empty($object['actor'])) {
1274                         $object_actor = $object['actor'];
1275                 } elseif (!empty($attributed_to)) {
1276                         $object_actor = $attributed_to;
1277                 } else {
1278                         // Shouldn't happen
1279                         $object_actor = '';
1280                 }
1281
1282                 $signer[] = $object_actor;
1283
1284                 if (!empty($child['author'])) {
1285                         $actor = $child['author'];
1286                         $signer[] = $actor;
1287                 } else {
1288                         $actor = $object_actor;
1289                 }
1290
1291                 if (!empty($object['published'])) {
1292                         $published = $object['published'];
1293                 } elseif (!empty($child['published'])) {
1294                         $published = $child['published'];
1295                 } else {
1296                         $published = DateTimeFormat::utcNow();
1297                 }
1298
1299                 $activity = [];
1300                 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1301                 unset($object['@context']);
1302                 $activity['id'] = $object['id'];
1303                 $activity['to'] = $object['to'] ?? [];
1304                 $activity['cc'] = $object['cc'] ?? [];
1305                 $activity['actor'] = $actor;
1306                 $activity['object'] = $object;
1307                 $activity['published'] = $published;
1308                 $activity['type'] = 'Create';
1309
1310                 $ldactivity = JsonLD::compact($activity);
1311
1312                 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 1;
1313
1314                 if (!empty($relay_actor)) {
1315                         $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
1316                         $ldactivity['completion-mode']   = Receiver::COMPLETION_RELAY;
1317                 } elseif (!empty($child['thread-completion'])) {
1318                         $ldactivity['thread-completion'] = $child['thread-completion'];
1319                         $ldactivity['completion-mode']   = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1320                 } else {
1321                         $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
1322                         $ldactivity['completion-mode']   = $completion;
1323                 }
1324
1325                 if (!empty($child['type'])) {
1326                         $ldactivity['thread-children-type'] = $child['type'];
1327                 }
1328
1329                 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
1330                         return '';
1331                 }
1332
1333                 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
1334
1335                 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
1336
1337                 return $activity['id'];
1338         }
1339
1340         /**
1341          * Test if incoming relay messages should be accepted
1342          *
1343          * @param array $activity activity array
1344          * @param string $id      object ID
1345          * @return boolean true if message is accepted
1346          */
1347         private static function acceptIncomingMessage(array $activity, string $id): bool
1348         {
1349                 if (empty($activity['as:object'])) {
1350                         Logger::info('No object field in activity - accepted', ['id' => $id]);
1351                         return true;
1352                 }
1353
1354                 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1355                 $uriid = ItemURI::getIdByURI($replyto ?? '');
1356                 if (Post::exists(['uri-id' => $uriid])) {
1357                         Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1358                         return true;
1359                 }
1360
1361                 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1362                 $authorid = Contact::getIdForURL($attributed_to);
1363
1364                 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1365
1366                 $messageTags = [];
1367                 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1368                 if (!empty($tags)) {
1369                         foreach ($tags as $tag) {
1370                                 if ($tag['type'] != 'Hashtag') {
1371                                         continue;
1372                                 }
1373                                 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1374                         }
1375                 }
1376
1377                 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
1378         }
1379
1380         /**
1381          * perform a "follow" request
1382          *
1383          * @param array $activity
1384          * @return void
1385          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1386          * @throws \ImagickException
1387          */
1388         public static function followUser(array $activity)
1389         {
1390                 $uid = User::getIdForURL($activity['object_id']);
1391                 if (empty($uid)) {
1392                         Queue::remove($activity);
1393                         return;
1394                 }
1395
1396                 $owner = User::getOwnerDataById($uid);
1397                 if (empty($owner)) {
1398                         return;
1399                 }
1400
1401                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1402                 if (!empty($cid)) {
1403                         self::switchContact($cid);
1404                         Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1405                 }
1406
1407                 $item = [
1408                         'author-id' => Contact::getIdForURL($activity['actor']),
1409                         'author-link' => $activity['actor'],
1410                 ];
1411
1412                 // Ensure that the contact has got the right network type
1413                 self::switchContact($item['author-id']);
1414
1415                 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1416                 if ($result === true) {
1417                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1418                 }
1419
1420                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1421                 if (empty($cid)) {
1422                         return;
1423                 }
1424
1425                 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1426                         self::transmitPendingEvents($cid, $owner['uid']);
1427                 }
1428
1429                 if (empty($contact)) {
1430                         Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1431                 }
1432                 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1433                 Queue::remove($activity);
1434         }
1435
1436         /**
1437          * Transmit pending events to the new follower
1438          *
1439          * @param integer $cid Contact id
1440          * @param integer $uid User id
1441          * @return void
1442          */
1443         private static function transmitPendingEvents(int $cid, int $uid)
1444         {
1445                 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1446                 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1447
1448                 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1449                 while ($event = DBA::fetch($events)) {
1450                         $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1451                         if (empty($post)) {
1452                                 continue;
1453                         }
1454                         if (DI::config()->get('system', 'bulk_delivery')) {
1455                                 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1456                                 Worker::add(PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1457                         } else {
1458                                 Worker::add(PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1459                         }
1460                 }
1461         }
1462
1463         /**
1464          * Update the given profile
1465          *
1466          * @param array $activity
1467          * @throws \Exception
1468          */
1469         public static function updatePerson(array $activity)
1470         {
1471                 if (empty($activity['object_id'])) {
1472                         return;
1473                 }
1474
1475                 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1476                 Contact::updateFromProbeByURL($activity['object_id']);
1477                 Queue::remove($activity);
1478         }
1479
1480         /**
1481          * Delete the given profile
1482          *
1483          * @param array $activity
1484          * @return void
1485          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1486          */
1487         public static function deletePerson(array $activity)
1488         {
1489                 if (empty($activity['object_id']) || empty($activity['actor'])) {
1490                         Logger::info('Empty object id or actor.');
1491                         return;
1492                 }
1493
1494                 if ($activity['object_id'] != $activity['actor']) {
1495                         Logger::info('Object id does not match actor.');
1496                         return;
1497                 }
1498
1499                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1500                 while ($contact = DBA::fetch($contacts)) {
1501                         Contact::remove($contact['id']);
1502                 }
1503                 DBA::close($contacts);
1504
1505                 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1506                 Queue::remove($activity);
1507         }
1508
1509         /**
1510          * Blocks the user by the contact
1511          *
1512          * @param array $activity
1513          * @return void
1514          * @throws \Exception
1515          */
1516         public static function blockAccount(array $activity)
1517         {
1518                 $cid = Contact::getIdForURL($activity['actor']);
1519                 if (empty($cid)) {
1520                         return;
1521                 }
1522
1523                 $uid = User::getIdForURL($activity['object_id']);
1524                 if (empty($uid)) {
1525                         return;
1526                 }
1527
1528                 Contact\User::setIsBlocked($cid, $uid, true);
1529
1530                 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1531                 Queue::remove($activity);
1532         }
1533
1534         /**
1535          * Unblocks the user by the contact
1536          *
1537          * @param array $activity
1538          * @return void
1539          * @throws \Exception
1540          */
1541         public static function unblockAccount(array $activity)
1542         {
1543                 $cid = Contact::getIdForURL($activity['actor']);
1544                 if (empty($cid)) {
1545                         return;
1546                 }
1547
1548                 $uid = User::getIdForURL($activity['object_object']);
1549                 if (empty($uid)) {
1550                         return;
1551                 }
1552
1553                 Contact\User::setIsBlocked($cid, $uid, false);
1554
1555                 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1556                 Queue::remove($activity);
1557         }
1558
1559         /**
1560          * Accept a follow request
1561          *
1562          * @param array $activity
1563          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1564          * @throws \ImagickException
1565          */
1566         public static function acceptFollowUser(array $activity)
1567         {
1568                 $uid = User::getIdForURL($activity['object_actor']);
1569                 if (empty($uid)) {
1570                         return;
1571                 }
1572
1573                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1574                 if (empty($cid)) {
1575                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1576                         return;
1577                 }
1578
1579                 self::switchContact($cid);
1580
1581                 $fields = ['pending' => false];
1582
1583                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1584                 if ($contact['rel'] == Contact::FOLLOWER) {
1585                         $fields['rel'] = Contact::FRIEND;
1586                 }
1587
1588                 $condition = ['id' => $cid];
1589                 Contact::update($fields, $condition);
1590                 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1591                 Queue::remove($activity);
1592         }
1593
1594         /**
1595          * Reject a follow request
1596          *
1597          * @param array $activity
1598          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1599          * @throws \ImagickException
1600          */
1601         public static function rejectFollowUser(array $activity)
1602         {
1603                 $uid = User::getIdForURL($activity['object_actor']);
1604                 if (empty($uid)) {
1605                         return;
1606                 }
1607
1608                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1609                 if (empty($cid)) {
1610                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1611                         return;
1612                 }
1613
1614                 self::switchContact($cid);
1615
1616                 $contact = Contact::getById($cid, ['rel']);
1617                 if ($contact['rel'] == Contact::SHARING) {
1618                         Contact::remove($cid);
1619                         Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1620                 } elseif ($contact['rel'] == Contact::FRIEND) {
1621                         Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1622                 } else {
1623                         Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1624                 }
1625                 Queue::remove($activity);
1626         }
1627
1628         /**
1629          * Undo activity like "like" or "dislike"
1630          *
1631          * @param array $activity
1632          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1633          * @throws \ImagickException
1634          */
1635         public static function undoActivity(array $activity)
1636         {
1637                 if (empty($activity['object_id'])) {
1638                         return;
1639                 }
1640
1641                 if (empty($activity['object_actor'])) {
1642                         return;
1643                 }
1644
1645                 $author_id = Contact::getIdForURL($activity['object_actor']);
1646                 if (empty($author_id)) {
1647                         return;
1648                 }
1649
1650                 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1651                 Queue::remove($activity);
1652         }
1653
1654         /**
1655          * Activity to remove a follower
1656          *
1657          * @param array $activity
1658          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1659          * @throws \ImagickException
1660          */
1661         public static function undoFollowUser(array $activity)
1662         {
1663                 $uid = User::getIdForURL($activity['object_object']);
1664                 if (empty($uid)) {
1665                         return;
1666                 }
1667
1668                 $owner = User::getOwnerDataById($uid);
1669                 if (empty($owner)) {
1670                         return;
1671                 }
1672
1673                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1674                 if (empty($cid)) {
1675                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1676                         return;
1677                 }
1678
1679                 self::switchContact($cid);
1680
1681                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1682                 if (!DBA::isResult($contact)) {
1683                         return;
1684                 }
1685
1686                 Contact::removeFollower($contact);
1687                 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1688                 Queue::remove($activity);
1689         }
1690
1691         /**
1692          * Switches a contact to AP if needed
1693          *
1694          * @param integer $cid Contact ID
1695          * @return void
1696          * @throws \Exception
1697          */
1698         private static function switchContact(int $cid)
1699         {
1700                 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1701                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1702                         return;
1703                 }
1704
1705                 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1706                 Contact::updateFromProbe($cid);
1707         }
1708
1709         /**
1710          * Collects implicit mentions like:
1711          * - the author of the parent item
1712          * - all the mentioned conversants in the parent item
1713          *
1714          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1715          * @return array
1716          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1717          */
1718         private static function getImplicitMentionList(array $parent): array
1719         {
1720                 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1721
1722                 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1723
1724                 $implicit_mentions = [];
1725                 if (empty($parent_author['url'])) {
1726                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1727                 } else {
1728                         $implicit_mentions[] = $parent_author['url'];
1729                         $implicit_mentions[] = $parent_author['nurl'];
1730                         $implicit_mentions[] = $parent_author['alias'];
1731                 }
1732
1733                 if (!empty($parent['alias'])) {
1734                         $implicit_mentions[] = $parent['alias'];
1735                 }
1736
1737                 foreach ($parent_terms as $term) {
1738                         $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1739                         if (!empty($contact['url'])) {
1740                                 $implicit_mentions[] = $contact['url'];
1741                                 $implicit_mentions[] = $contact['nurl'];
1742                                 $implicit_mentions[] = $contact['alias'];
1743                         }
1744                 }
1745
1746                 return $implicit_mentions;
1747         }
1748
1749         /**
1750          * Strips from the body prepended implicit mentions
1751          *
1752          * @param string $body
1753          * @param array $parent
1754          * @return string
1755          */
1756         private static function removeImplicitMentionsFromBody(string $body, array $parent): string
1757         {
1758                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1759                         return $body;
1760                 }
1761
1762                 $potential_mentions = self::getImplicitMentionList($parent);
1763
1764                 $kept_mentions = [];
1765
1766                 // Extract one prepended mention at a time from the body
1767                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1768                         if (!in_array($matches[2], $potential_mentions)) {
1769                                 $kept_mentions[] = $matches[1];
1770                         }
1771
1772                         $body = $matches[3];
1773                 }
1774
1775                 // Re-appending the kept mentions to the body after extraction
1776                 $kept_mentions[] = $body;
1777
1778                 return implode('', $kept_mentions);
1779         }
1780
1781         /**
1782          * Adds links to string mentions
1783          *
1784          * @param string $body
1785          * @param array  $tags
1786          * @return string
1787          */
1788         protected static function addMentionLinks(string $body, array $tags): string
1789         {
1790                 // This prevents links to be added again to Pleroma-style mention links
1791                 $body = self::normalizeMentionLinks($body);
1792
1793                 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
1794                         foreach ($tags as $tag) {
1795                                 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1796                                         continue;
1797                                 }
1798
1799                                 $hash = substr($tag['name'], 0, 1);
1800                                 $name = substr($tag['name'], 1);
1801                                 if (!in_array($hash, Tag::TAG_CHARACTER)) {
1802                                         $hash = '';
1803                                         $name = $tag['name'];
1804                                 }
1805
1806                                 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);
1807                         }
1808
1809                         return $body;
1810                 });
1811
1812                 return $body;
1813         }
1814 }