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