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