]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Function is renamed
[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\Model\Post\Engagement;
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) && ($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
353                                 $item['thr-parent'] = $result;
354                         }
355                 }
356
357                 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
358
359                 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != Item::GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
360                         Logger::notice('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
361                         if (!$fetch_parents) {
362                                 Queue::remove($activity);
363                         }
364                         return [];
365                 }
366
367                 $item['network'] = Protocol::ACTIVITYPUB;
368                 $item['author-link'] = $activity['author'];
369                 $item['author-id'] = Contact::getIdForURL($activity['author']);
370                 $item['owner-link'] = $activity['actor'];
371                 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
372
373                 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
374                         $item['private'] = Item::UNLISTED;
375                 } elseif (in_array(0, $activity['receiver'])) {
376                         $item['private'] = Item::PUBLIC;
377                 } else {
378                         $item['private'] = Item::PRIVATE;
379                 }
380
381                 if (!empty($activity['raw'])) {
382                         $item['source'] = $activity['raw'];
383                 }
384
385                 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
386
387                 if (isset($activity['push'])) {
388                         $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
389                 }
390
391                 if (!empty($activity['from-relay'])) {
392                         $item['direction'] = Conversation::RELAY;
393                 }
394
395                 if ($activity['object_type'] == 'as:Article') {
396                         $item['post-type'] = Item::PT_ARTICLE;
397                 } elseif ($activity['object_type'] == 'as:Audio') {
398                         $item['post-type'] = Item::PT_AUDIO;
399                 } elseif ($activity['object_type'] == 'as:Document') {
400                         $item['post-type'] = Item::PT_DOCUMENT;
401                 } elseif ($activity['object_type'] == 'as:Event') {
402                         $item['post-type'] = Item::PT_EVENT;
403                 } elseif ($activity['object_type'] == 'as:Image') {
404                         $item['post-type'] = Item::PT_IMAGE;
405                 } elseif ($activity['object_type'] == 'as:Page') {
406                         $item['post-type'] = Item::PT_PAGE;
407                 } elseif ($activity['object_type'] == 'as:Question') {
408                         $item['post-type'] = Item::PT_POLL;
409                 } elseif ($activity['object_type'] == 'as:Video') {
410                         $item['post-type'] = Item::PT_VIDEO;
411                 } else {
412                         $item['post-type'] = Item::PT_NOTE;
413                 }
414
415                 $item['isGroup'] = false;
416
417                 if (!empty($activity['thread-completion'])) {
418                         if ($activity['thread-completion'] != $item['owner-id']) {
419                                 $actor = Contact::getById($activity['thread-completion'], ['url']);
420                                 $item['causer-link'] = $actor['url'];
421                                 $item['causer-id']   = $activity['thread-completion'];
422                                 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
423                         } else {
424                                 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
425                                 $item['causer-link'] = $item['owner-link'];
426                                 $item['causer-id']   = $item['owner-id'];
427                                 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
428                         }
429
430                         $item['owner-link'] = $item['author-link'];
431                         $item['owner-id']   = $item['author-id'];
432                 }
433
434                 if (!$item['isGroup'] && !empty($activity['receiver_urls']['as:audience'])) {
435                         foreach ($activity['receiver_urls']['as:audience'] as $audience) {
436                                 $actor = APContact::getByURL($audience, false);
437                                 if (($actor['type'] ?? 'Person') == 'Group') {
438                                         Logger::debug('Group post detected via audience.', ['audience' => $audience, 'actor' => $activity['actor'], 'author' => $activity['author']]);
439                                         $item['isGroup']    = true;
440                                         $item['group-link'] = $item['owner-link'] = $audience;
441                                         $item['owner-id']   = Contact::getIdForURL($audience);
442                                         break;
443                                 }
444                         }
445                 } else {
446                         $owner = APContact::getByURL($item['owner-link'], false);
447                 }
448
449                 if (!$item['isGroup'] && (($owner['type'] ?? 'Person') == 'Group')) {
450                         Logger::debug('Group post detected via owner.', ['actor' => $activity['actor'], 'author' => $activity['author']]);
451                         $item['isGroup']    = true;
452                         $item['group-link'] = $item['owner-link'];
453                 } elseif (!empty($item['causer-link'])) {
454                         $causer = APContact::getByURL($item['causer-link'], false);
455                 }
456
457                 if (!$item['isGroup'] && (($causer['type'] ?? 'Person') == 'Group')) {
458                         Logger::debug('Group post detected via causer.', ['actor' => $activity['actor'], 'author' => $activity['author'], 'causer' => $item['causer-link']]);
459                         $item['isGroup']    = true;
460                         $item['group-link'] = $item['causer-link'];
461                 }
462
463                 if (!empty($item['group-link']) && empty($item['causer-link'])) {
464                         $item['causer-link'] = $item['group-link'];
465                         $item['causer-id']   = Contact::getIdForURL($item['causer-link']);
466                 }
467
468                 $item['uri'] = $activity['id'];
469
470                 if (empty($activity['published']) || empty($activity['updated'])) {
471                         DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity]);
472                 }
473
474                 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
475                 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
476                 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
477                 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
478
479                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
480                 if (empty($item['uri-id'])) {
481                         Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
482                         return [];
483                 }
484
485                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
486
487                 $item = self::processContent($activity, $item);
488                 if (empty($item)) {
489                         Logger::info('Message was not processed');
490                         Queue::remove($activity);
491                         return [];
492                 }
493
494                 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
495
496                 self::storeAttachments($activity, $item);
497                 self::storeQuestion($activity, $item);
498
499                 // We received the post via AP, so we set the protocol of the server to AP
500                 $contact = Contact::getById($item['author-id'], ['gsid']);
501                 if (!empty($contact['gsid'])) {
502                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
503                 }
504
505                 if ($item['author-id'] != $item['owner-id']) {
506                         $contact = Contact::getById($item['owner-id'], ['gsid']);
507                         if (!empty($contact['gsid'])) {
508                                 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
509                         }
510                 }
511
512                 return $item;
513         }
514
515         /**
516          * Fetch and process parent posts for the given activity
517          *
518          * @param array $activity
519          * @param bool  $in_background
520          *
521          * @return string
522          */
523         private static function fetchParent(array $activity, bool $in_background = false): string
524         {
525                 if (self::isFetched($activity['reply-to-id'])) {
526                         Logger::info('Id is already fetched', ['id' => $activity['reply-to-id']]);
527                         return '';
528                 }
529
530                 self::addActivityId($activity['reply-to-id']);
531
532                 $completion = $activity['completion-mode'] ?? Receiver::COMPLETION_NONE;
533
534                 if (DI::config()->get('system', 'decoupled_receiver') && ($completion != Receiver::COMPLETION_MANUAL)) {
535                         $in_background = true;
536                 }
537
538                 $recursion_depth = $activity['recursion-depth'] ?? 0;
539
540                 if (!$in_background && ($recursion_depth < DI::config()->get('system', 'max_recursion_depth'))) {
541                         Logger::info('Parent not found. Try to refetch it.', ['completion' => $completion, 'recursion-depth' => $recursion_depth, 'parent' => $activity['reply-to-id']]);
542                         $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
543                         if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
544                                 Logger::notice('The activity is gone, the queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
545                                 if (!empty($activity['entry-id'])) {
546                                         Queue::deleteById($activity['entry-id']);
547                                 }
548                         } elseif (!empty($result)) {
549                                 $post = Post::selectFirstPost(['uri'], ['uri' => [$result, $activity['reply-to-id']]]);
550                                 if (!empty($post['uri'])) {
551                                         Logger::info('The activity has been fetched and created.', ['result' => $result, 'uri' => $post['uri']]);
552                                         return $post['uri'];
553                                 } else {
554                                         Logger::notice('The activity exists but has not been created, the queue entry will be deleted.', ['parent' => $result]);
555                                         if (!empty($activity['entry-id'])) {
556                                                 Queue::deleteById($activity['entry-id']);
557                                         }
558                                 }
559                         }
560                         return '';
561                 } elseif (self::isActivityGone($activity['reply-to-id'])) {
562                         Logger::notice('The activity is gone. We will not spawn a worker. The queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
563                         if ($in_background) {
564                                 // fetching in background is done for all activities where we have got the conversation
565                                 // There we only delete the single activity and not the whole thread since we can store the
566                                 // other posts in the thread even with missing posts.
567                                 Queue::remove($activity);
568                         } elseif (!empty($activity['entry-id'])) {
569                                 Queue::deleteById($activity['entry-id']);
570                         }
571                         return '';
572                 } elseif ($in_background) {
573                         Logger::notice('Fetching is done in the background.', ['parent' => $activity['reply-to-id']]);
574                 } else {
575                         Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
576                 }
577
578                 if (!Fetch::hasWorker($activity['reply-to-id'])) {
579                         Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
580                         Fetch::add($activity['reply-to-id']);
581                         $activity['recursion-depth'] = 0;
582                         $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_ASYNC);
583                         Fetch::setWorkerId($activity['reply-to-id'], $wid);
584                 } else {
585                         Logger::debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]);
586                 }
587
588                 return '';
589         }
590
591         /**
592          * Check if a given activity is no longer available
593          *
594          * @param string $url
595          *
596          * @return boolean
597          */
598         public static function isActivityGone(string $url): bool
599         {
600                 if (Network::isUrlBlocked($url)) {
601                         return true;
602                 }
603
604                 try {
605                         $curlResult = HTTPSignature::fetchRaw($url, 0);
606                 } catch (\Exception $exception) {
607                         Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
608                         return true;
609                 }       
610
611                 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
612                 if (in_array($curlResult->getReturnCode(), [401, 404])) {
613                         return true;
614                 }
615
616                 if ($curlResult->isSuccess()) {
617                         $object = json_decode($curlResult->getBody(), true);
618                         if (!empty($object)) {
619                                 $activity = JsonLD::compact($object);
620                                 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
621                                         return true;
622                                 }
623                         }
624                 } elseif ($curlResult->getReturnCode() == 0) {
625                         $host = parse_url($url, PHP_URL_HOST);
626                         if (!(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) {
627                                 return true;
628                         }
629                 }
630
631                 return false;
632         }
633         /**
634          * Delete items
635          *
636          * @param array $activity
637          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
638          * @throws \ImagickException
639          */
640         public static function deleteItem(array $activity)
641         {
642                 $owner = Contact::getIdForURL($activity['actor']);
643
644                 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner'  => $owner]);
645                 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
646                 Queue::remove($activity);
647         }
648
649         /**
650          * Prepare the item array for an activity
651          *
652          * @param array $activity Activity array
653          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
654          * @throws \ImagickException
655          */
656         public static function addTag(array $activity)
657         {
658                 if (empty($activity['object_content']) || empty($activity['object_id'])) {
659                         return;
660                 }
661
662                 foreach ($activity['receiver'] as $receiver) {
663                         $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
664                         if (!DBA::isResult($item)) {
665                                 // We don't fetch missing content for this purpose
666                                 continue;
667                         }
668
669                         if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
670                                 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
671                                 continue;
672                         }
673
674                         Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
675                         Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
676                 }
677         }
678
679         /**
680          * Prepare the item array for an activity
681          *
682          * @param array      $activity   Activity array
683          * @param string     $verb       Activity verb
684          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
685          * @throws \ImagickException
686          */
687         public static function createActivity(array $activity, string $verb)
688         {
689                 $activity['reply-to-id'] = $activity['object_id'];
690                 $item = self::createItem($activity, false);
691                 if (empty($item)) {
692                         Logger::debug('Activity was not prepared', ['id' => $activity['object_id']]);
693                         return;
694                 }
695
696                 $item['verb'] = $verb;
697                 $item['thr-parent'] = $activity['object_id'];
698                 $item['gravity'] = Item::GRAVITY_ACTIVITY;
699                 unset($item['post-type']);
700                 $item['object-type'] = Activity\ObjectType::NOTE;
701
702                 if (!empty($activity['content'])) {
703                         $item['body'] = HTML::toBBCode($activity['content']);
704                 }
705
706                 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
707
708                 self::postItem($activity, $item);
709         }
710
711         /**
712          * Fetch the Uri-Id of a post for the "featured" collection
713          *
714          * @param array $activity
715          * @return null|array
716          */
717         private static function getUriIdForFeaturedCollection(array $activity)
718         {
719                 $actor = APContact::getByURL($activity['actor']);
720                 if (empty($actor)) {
721                         return null;
722                 }
723
724                 // Refetch the account when the "featured" collection is missing.
725                 // This can be removed in a future version (end of 2022 should be good).
726                 if (empty($actor['featured'])) {
727                         $actor = APContact::getByURL($activity['actor'], true);
728                         if (empty($actor)) {
729                                 return null;
730                         }
731                 }
732
733                 $parent = Post::selectFirst(['uri-id', 'author-id'], ['uri' => $activity['object_id']]);
734                 if (empty($parent['uri-id'])) {
735                         if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
736                                 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
737                         }
738                 }
739
740                 if (!empty($parent['uri-id'])) {
741                         return $parent;
742                 }
743
744                 return null;
745         }
746
747         /**
748          * Add a post to the "Featured" collection
749          *
750          * @param array $activity
751          */
752         public static function addToFeaturedCollection(array $activity)
753         {
754                 $post = self::getUriIdForFeaturedCollection($activity);
755                 if (empty($post) || empty($post['author-id'])) {
756                         Queue::remove($activity);
757                         return;
758                 }
759
760                 Logger::debug('Add post to featured collection', ['post' => $post]);
761
762                 Post\Collection::add($post['uri-id'], Post\Collection::FEATURED, $post['author-id']);
763                 Queue::remove($activity);
764         }
765
766         /**
767          * Remove a post to the "Featured" collection
768          *
769          * @param array $activity
770          */
771         public static function removeFromFeaturedCollection(array $activity)
772         {
773                 $post = self::getUriIdForFeaturedCollection($activity);
774                 if (empty($post)) {
775                         Queue::remove($activity);
776                         return;
777                 }
778
779                 Logger::debug('Remove post from featured collection', ['post' => $post]);
780
781                 Post\Collection::remove($post['uri-id'], Post\Collection::FEATURED);
782                 Queue::remove($activity);
783         }
784
785         /**
786          * Create an event
787          *
788          * @param array $activity Activity array
789          * @param array $item
790          *
791          * @return int event id
792          * @throws \Exception
793          */
794         public static function createEvent(array $activity, array $item): int
795         {
796                 $event['summary']   = HTML::toBBCode($activity['name'] ?: $activity['summary']);
797                 $event['desc']      = HTML::toBBCode($activity['content'] ?? '');
798                 if (!empty($activity['start-time'])) {
799                         $event['start']  = DateTimeFormat::utc($activity['start-time']);
800                 }
801                 if (!empty($activity['end-time'])) {
802                         $event['finish'] = DateTimeFormat::utc($activity['end-time']);
803                 }
804                 $event['nofinish']  = empty($event['finish']);
805                 $event['location']  = $activity['location'];
806                 $event['cid']       = $item['contact-id'];
807                 $event['uid']       = $item['uid'];
808                 $event['uri']       = $item['uri'];
809                 $event['edited']    = $item['edited'];
810                 $event['private']   = $item['private'];
811                 $event['guid']      = $item['guid'];
812                 $event['plink']     = $item['plink'];
813                 $event['network']   = $item['network'];
814                 $event['protocol']  = $item['protocol'];
815                 $event['direction'] = $item['direction'];
816                 $event['source']    = $item['source'];
817
818                 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
819                 if (DBA::isResult($ev)) {
820                         $event['id'] = $ev['id'];
821                 }
822
823                 $event_id = Event::store($event);
824
825                 Logger::info('Event was stored', ['id' => $event_id]);
826
827                 return $event_id;
828         }
829
830         /**
831          * Process the content
832          *
833          * @param array $activity Activity array
834          * @param array $item
835          * @return array|bool Returns the item array or false if there was an unexpected occurrence
836          * @throws \Exception
837          */
838         private static function processContent(array $activity, array $item)
839         {
840                 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
841                         $item['title'] = strip_tags($activity['name'] ?? '');
842                         $content = Markdown::toBBCode($activity['content']);
843                 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
844                         $item['title'] = $activity['name'];
845                         $content = $activity['content'];
846                 } else {
847                         // By default assume "text/html"
848                         $item['title'] = HTML::toBBCode($activity['name'] ?? '');
849                         $content = HTML::toBBCode($activity['content'] ?? '');
850                 }
851
852                 $item['title'] = trim(BBCode::toPlaintext($item['title']));
853
854                 if (!empty($activity['languages'])) {
855                         $item['language'] = self::processLanguages($activity['languages']);
856                 }
857
858                 $item['transmitted-languages'] = $activity['transmitted-languages'];
859
860                 if (!empty($activity['emojis'])) {
861                         $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
862                 }
863
864                 $content = self::addMentionLinks($content, $activity['tags']);
865
866                 if (!empty($activity['quote-url'])) {
867                         $id = Item::fetchByLink($activity['quote-url'], 0, ActivityPub\Receiver::COMPLETION_ASYNC);
868                         if ($id) {
869                                 $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
870                                 $item['quote-uri-id'] = $shared_item['uri-id'];
871                         } elseif ($uri_id = ItemURI::getIdByURI($activity['quote-url'], false)) {
872                                 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]);
873                                 $item['quote-uri-id'] = $uri_id;
874                         } else {
875                                 Logger::info('Quote was not fetched', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url']]);
876                         }
877                 }
878
879                 if (!empty($activity['source'])) {
880                         $item['body'] = $activity['source'];
881                         $item['raw-body'] = $content;
882
883                         $quote_uri_id = Item::getQuoteUriId($item['body']);
884                         if (empty($item['quote-uri-id']) && !empty($quote_uri_id)) {
885                                 $item['quote-uri-id'] = $quote_uri_id;
886                         }
887
888                         $item['body'] = BBCode::removeSharedData($item['body']);
889                 } else {
890                         $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
891                         if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == Item::GRAVITY_COMMENT)) {
892                                 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
893                                 if (!DBA::isResult($parent)) {
894                                         Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
895                                         return false;
896                                 }
897                                 $content = self::removeImplicitMentionsFromBody($content, $parent);
898                         }
899                         $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
900                         $item['raw-body'] = $item['body'] = $content;
901                 }
902
903                 if (!empty($item['author-id']) && ($item['author-id'] == $item['owner-id'])) {
904                         foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
905                                 $actor = APContact::getByURL($tag[2], false);
906                                 if (($actor['type'] ?? 'Person') == 'Group') {
907                                         Logger::debug('Group post detected via exclusive mention.', ['mention' => $actor['url'], 'actor' => $activity['actor'], 'author' => $activity['author']]);
908                                         $item['isGroup']    = true;
909                                         $item['group-link'] = $item['owner-link'] = $actor['url'];
910                                         $item['owner-id']   = Contact::getIdForURL($actor['url']);
911                                         break;
912                                 }
913                         }
914                 }
915
916                 self::storeFromBody($item);
917                 self::storeTags($item['uri-id'], $activity['tags']);
918
919                 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
920
921                 $item['location'] = $activity['location'];
922
923                 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
924                         $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
925                 }
926
927                 $item['app'] = $activity['generator'];
928
929                 return $item;
930         }
931
932         /**
933          * Store hashtags and mentions
934          *
935          * @param array $item
936          */
937         private static function storeFromBody(array $item)
938         {
939                 // Make sure to delete all existing tags (can happen when called via the update functionality)
940                 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
941
942                 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
943         }
944
945         /**
946          * Generate a GUID out of an URL of an ActivityPub post.
947          *
948          * @param string $url message URL
949          * @return string with GUID
950          */
951         private static function getGUIDByURL(string $url): string
952         {
953                 $parsed = parse_url($url);
954
955                 $host_hash = hash('crc32', $parsed['host']);
956
957                 unset($parsed["scheme"]);
958                 unset($parsed["host"]);
959
960                 $path = implode("/", $parsed);
961
962                 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
963         }
964
965         /**
966          * Checks if an incoming message is wanted
967          *
968          * @param array $activity
969          * @param array $item
970          * @return boolean Is the message wanted?
971          */
972         private static function isSolicitedMessage(array $activity, array $item): bool
973         {
974                 // The checks are split to improve the support when searching why a message was accepted.
975                 if (count($activity['receiver']) != 1) {
976                         // The message has more than one receiver, so it is wanted.
977                         Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
978                         return true;
979                 }
980
981                 if ($item['private'] == Item::PRIVATE) {
982                         // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
983                         Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
984                         return true;
985                 }
986
987                 if (!empty($activity['from-relay'])) {
988                         // We check relay posts at another place. When it arrived here, the message is already checked.
989                         Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
990                         return true;
991                 }
992
993                 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUNCE])) {
994                         // Manual completions and completions caused by reshares are allowed without any further checks.
995                         Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
996                         return true;
997                 }
998
999                 if ($item['gravity'] != Item::GRAVITY_PARENT) {
1000                         // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
1001                         // This can possibly be improved in the future.
1002                         Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
1003                         return true;
1004                 }
1005
1006                 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
1007                 if (Relay::isSolicitedPost($tags, $item['title'] . ' ' . ($item['content-warning'] ?? '') . ' ' . $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB, $activity['thread-completion'] ?? 0)) {
1008                         Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
1009                         return true;
1010                 } else {
1011                         return false;
1012                 }
1013         }
1014
1015         /**
1016          * Creates an item post
1017          *
1018          * @param array $activity Activity data
1019          * @param array $item     item array
1020          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1021          * @throws \ImagickException
1022          */
1023         public static function postItem(array $activity, array $item)
1024         {
1025                 if (empty($item)) {
1026                         return;
1027                 }
1028
1029                 $stored = false;
1030                 $success = false;
1031                 ksort($activity['receiver']);
1032
1033                 if (!self::isSolicitedMessage($activity, $item)) {
1034                         DBA::delete('item-uri', ['id' => $item['uri-id']]);
1035                         if (!empty($activity['entry-id'])) {
1036                                 Queue::deleteById($activity['entry-id']);
1037                         }
1038                         return;
1039                 }
1040
1041                 foreach ($activity['receiver'] as $receiver) {
1042                         if ($receiver == -1) {
1043                                 continue;
1044                         }
1045
1046                         if (($receiver != 0) && empty($item['parent-uri-id']) && !empty($item['thr-parent-id'])) {
1047                                 $parent = Post::selectFirst(['parent-uri-id', 'parent-uri'], ['uri-id' => $item['thr-parent-id'], 'uid' => [0, $receiver]]);
1048                                 if (!empty($parent['parent-uri-id'])) {
1049                                         $item['parent-uri-id'] = $parent['parent-uri-id'];
1050                                         $item['parent-uri']    = $parent['parent-uri'];
1051                                 }
1052                         }
1053
1054                         $item['uid'] = $receiver;
1055
1056                         $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
1057                         switch($type) {
1058                                 case Receiver::TARGET_TO:
1059                                         $item['post-reason'] = Item::PR_TO;
1060                                         break;
1061                                 case Receiver::TARGET_CC:
1062                                         $item['post-reason'] = Item::PR_CC;
1063                                         break;
1064                                 case Receiver::TARGET_BTO:
1065                                         $item['post-reason'] = Item::PR_BTO;
1066                                         break;
1067                                 case Receiver::TARGET_BCC:
1068                                         $item['post-reason'] = Item::PR_BCC;
1069                                         break;
1070                                 case Receiver::TARGET_AUDIENCE:
1071                                         $item['post-reason'] = Item::PR_AUDIENCE;
1072                                         break;
1073                                 case Receiver::TARGET_FOLLOWER:
1074                                         $item['post-reason'] = Item::PR_FOLLOWER;
1075                                         break;
1076                                 case Receiver::TARGET_ANSWER:
1077                                         $item['post-reason'] = Item::PR_COMMENT;
1078                                         break;
1079                                 case Receiver::TARGET_GLOBAL:
1080                                         $item['post-reason'] = Item::PR_GLOBAL;
1081                                         break;
1082                                 default:
1083                                         $item['post-reason'] = Item::PR_NONE;
1084                         }
1085
1086                         $item['post-reason'] = Item::getPostReason($item);
1087
1088                         if (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE])) {
1089                                 if (!empty($activity['from-relay'])) {
1090                                         $item['post-reason'] = Item::PR_RELAY;
1091                                 } elseif (!empty($activity['thread-completion'])) {
1092                                         $item['post-reason'] = Item::PR_FETCHED;
1093                                 } elseif (!empty($activity['push'])) {
1094                                         $item['post-reason'] = Item::PR_PUSHED;
1095                                 }
1096                         } elseif (($item['post-reason'] == Item::PR_FOLLOWER) && !empty($activity['from-relay'])) {
1097                                 // When a post arrives via a relay and we follow the author, we have to override the causer.
1098                                 // Otherwise the system assumes that we follow the relay. (See "addRowInformation")
1099                                 Logger::debug('Relay post for follower', ['receiver' => $receiver, 'guid' => $item['guid'], 'relay' => $activity['from-relay']]);
1100                                 $item['causer-id'] = ($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1101                         }
1102
1103                         if ($item['isGroup']) {
1104                                 $item['contact-id'] = Contact::getIdForURL($item['group-link'], $receiver);
1105                         } else {
1106                                 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $receiver);
1107                         }
1108
1109                         if (($receiver != 0) && empty($item['contact-id'])) {
1110                                 $item['contact-id'] = Contact::getIdForURL($activity['author']);
1111                         }
1112
1113                         if (!empty($activity['directmessage']) && self::postMail($item)) {
1114                                 if (!empty($item['source']) && DI::config()->get('debug', 'store_source')) {
1115                                         Post\Activity::insert($item['uri-id'], $item['source']);
1116                                 }
1117                 
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'], 0, ActivityPub\Receiver::COMPLETION_ASYNC);
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 = HTTPSignature::fetch($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. An empty string indicates a temporary error, null indicates a permament error,
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                 if (Network::isUrlBlocked($url)) {
1537                         return null;
1538                 }
1539
1540                 try {
1541                         $curlResult = HTTPSignature::fetchRaw($url, $uid);
1542                 } catch (\Exception $exception) {
1543                         Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
1544                         return '';
1545                 }
1546
1547                 if (empty($curlResult)) {
1548                         return '';
1549                 }
1550
1551                 $body = $curlResult->getBody();
1552                 if (!$curlResult->isSuccess() || empty($body)) {
1553                         if (in_array($curlResult->getReturnCode(), [403, 404, 406, 410])) {
1554                                 return null;
1555                         }
1556                         return '';
1557                 }
1558
1559                 $object = json_decode($body, true);
1560                 if (empty($object) || !is_array($object)) {
1561                         $element = explode(';', $curlResult->getContentType());
1562                         if (!in_array($element[0], ['application/activity+json', 'application/ld+json', 'application/json'])) {
1563                                 Logger::debug('Unexpected content-type', ['url' => $url, 'content-type' => $curlResult->getContentType()]);
1564                                 return null;
1565                         }
1566                         Logger::notice('Invalid JSON data', ['url' => $url, 'content-type' => $curlResult->getContentType(), 'body' => $body]);
1567                         return '';
1568                 }
1569
1570                 $ldobject = JsonLD::compact($object);
1571
1572                 $signer = [];
1573
1574                 $attributed_to = JsonLD::fetchElement($ldobject, 'as:attributedTo', '@id');
1575                 if (!empty($attributed_to)) {
1576                         $signer[] = $attributed_to;
1577                 }
1578
1579                 $object_actor = JsonLD::fetchElement($ldobject, 'as:actor', '@id');
1580                 if (!empty($attributed_to)) {
1581                         $object_actor = $attributed_to;
1582                 } else {
1583                         // Shouldn't happen
1584                         $object_actor = '';
1585                 }
1586
1587                 $signer[] = $object_actor;
1588
1589                 if (!empty($child['author'])) {
1590                         $actor = $child['author'];
1591                         $signer[] = $actor;
1592                 } else {
1593                         $actor = $object_actor;
1594                 }
1595
1596                 $type      = JsonLD::fetchElement($ldobject, '@type');
1597                 $object_id = JsonLD::fetchElement($ldobject, 'as:object', '@id');
1598
1599                 if (!in_array($type, Receiver::CONTENT_TYPES) && !empty($object_id)) {
1600                         if (($type == 'as:Announce') && !empty($relay_actor) && ($completion = Receiver::COMPLETION_RELAY)) {
1601                                 if (Item::searchByLink($object_id)) {
1602                                         return $object_id;
1603                                 }
1604                                 Logger::debug('Fetch announced activity', ['type' => $type, 'id' => $object_id, 'actor' => $relay_actor, 'signer' => $signer]);
1605
1606                                 return self::fetchMissingActivity($object_id, $child, $relay_actor, $completion, $uid);
1607                         }
1608                         $activity   = $object;
1609                         $ldactivity = $ldobject;
1610                 } elseif (!empty($object['id'])) {
1611                         $activity   = self::getActivityForObject($object, $actor);
1612                         $ldactivity = JsonLD::compact($activity);
1613                 } else {
1614                         return null;
1615                 }
1616         
1617                 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 0;
1618
1619                 if ($object_actor != $actor) {
1620                         Contact::updateByUrlIfNeeded($object_actor);
1621                 }
1622
1623                 Contact::updateByUrlIfNeeded($actor);
1624
1625                 if (!empty($child['thread-completion'])) {
1626                         $ldactivity['thread-completion'] = $child['thread-completion'];
1627                         $ldactivity['completion-mode']   = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1628                 } else {
1629                         $ldactivity['thread-completion'] = Contact::getIdForURL($relay_actor ?: $actor);
1630                         $ldactivity['completion-mode']   = $completion;
1631                 }
1632
1633                 if ($completion == Receiver::COMPLETION_RELAY) {
1634                         $ldactivity['from-relay'] = $ldactivity['thread-completion'];
1635                         if (in_array($type, Receiver::CONTENT_TYPES) && !self::acceptIncomingMessage($ldactivity)) {
1636                                 return null;
1637                         }
1638                 }
1639
1640                 if (!empty($child['thread-children-type'])) {
1641                         $ldactivity['thread-children-type'] = $child['thread-children-type'];
1642                 } elseif (!empty($child['type'])) {
1643                         $ldactivity['thread-children-type'] = $child['type'];
1644                 } else {
1645                         $ldactivity['thread-children-type'] = 'as:Create';
1646                 }
1647
1648                 if (($completion == Receiver::COMPLETION_RELAY) && Queue::exists($url, 'as:Create')) {
1649                         Logger::info('Activity has already been queued.', ['url' => $url, 'object' => $activity['id']]);
1650                 } elseif (ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer, '', $completion)) {
1651                         Logger::info('Activity had been fetched and processed.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1652                 } else {
1653                         Logger::info('Activity had been fetched and will be processed later.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1654                 }
1655
1656                 return $activity['id'];
1657         }
1658
1659         private static function getActivityForObject(array $object, string $actor): array
1660         {
1661                 if (!empty($object['published'])) {
1662                         $published = $object['published'];
1663                 } elseif (!empty($child['published'])) {
1664                         $published = $child['published'];
1665                 } else {
1666                         $published = DateTimeFormat::utcNow();
1667                 }
1668
1669                 $activity = [];
1670                 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1671                 unset($object['@context']);
1672                 $activity['id'] = $object['id'];
1673                 $activity['to'] = $object['to'] ?? [];
1674                 $activity['cc'] = $object['cc'] ?? [];
1675                 $activity['audience'] = $object['audience'] ?? [];
1676                 $activity['actor'] = $actor;
1677                 $activity['object'] = $object;
1678                 $activity['published'] = $published;
1679                 $activity['type'] = 'Create';
1680
1681                 return $activity;
1682         }
1683
1684         /**
1685          * Test if incoming relay messages should be accepted
1686          *
1687          * @param array $activity activity array
1688          * @return boolean true if message is accepted
1689          */
1690         private static function acceptIncomingMessage(array $activity): bool
1691         {
1692                 if (empty($activity['as:object'])) {
1693                         $id = JsonLD::fetchElement($activity, '@id');
1694                         Logger::info('No object field in activity - accepted', ['id' => $id]);
1695                         return true;
1696                 }
1697
1698                 $id = JsonLD::fetchElement($activity, 'as:object', '@id');
1699
1700                 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1701                 $uriid = ItemURI::getIdByURI($replyto ?? '');
1702                 if (Post::exists(['uri-id' => $uriid])) {
1703                         Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1704                         return true;
1705                 }
1706
1707                 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1708                 $authorid = Contact::getIdForURL($attributed_to);
1709
1710                 $content = JsonLD::fetchElement($activity['as:object'], 'as:name', '@value') ?? '';
1711                 $content .= ' ' . JsonLD::fetchElement($activity['as:object'], 'as:summary', '@value') ?? '';
1712                 $content .= ' ' . HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1713
1714                 $attachments = JsonLD::fetchElementArray($activity['as:object'], 'as:attachment') ?? [];
1715                 foreach ($attachments as $media) {
1716                         if (!empty($media['as:summary'])) {
1717                                 $content .= ' ' . JsonLD::fetchElement($media, 'as:summary', '@value');
1718                         }
1719                         if (!empty($media['as:name'])) {
1720                                 $content .= ' ' . JsonLD::fetchElement($media, 'as:name', '@value');
1721                         }
1722                 }
1723
1724                 $messageTags = [];
1725                 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1726                 if (!empty($tags)) {
1727                         foreach ($tags as $tag) {
1728                                 if (($tag['type'] != 'Hashtag') && !strpos($tag['type'], ':Hashtag')) {
1729                                         continue;
1730                                 }
1731                                 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1732                         }
1733                 }
1734
1735                 $languages = self::getPostLanguages($activity['as:object'] ?? '');
1736
1737                 $wanted = Relay::isSolicitedPost($messageTags, $content, $authorid, $id, Protocol::ACTIVITYPUB, $activity['from-relay'], $languages);
1738                 if ($wanted) {
1739                         return true;
1740                 }
1741
1742                 $receivers = [];
1743                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience'] as $element) {
1744                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1745                         if (empty($receiver_list)) {
1746                                 continue;
1747                         }
1748                         $receivers = array_merge($receivers, $receiver_list);
1749                 }
1750
1751                 $searchtext = Engagement::getSearchTextForActivity($content, $authorid, $messageTags, $receivers);
1752                 $language   = array_key_first(Item::getLanguageArray($content, 1, 0, $authorid));
1753                 return DI::userDefinedChannel()->match($searchtext, $language);
1754         }
1755
1756         /**
1757          * Fetch the post language from the content
1758          *
1759          * @param array $activity
1760          * @return array
1761          */
1762         public static function getPostLanguages(array $activity): array
1763         {
1764                 $content   = JsonLD::fetchElement($activity, 'as:content') ?? '';
1765                 $languages = JsonLD::fetchElementArray($activity, 'as:content', '@language') ?? [];
1766                 if (empty($languages)) {
1767                         return [];
1768                 }
1769
1770                 $iso639 = new \Matriphe\ISO639\ISO639;
1771
1772                 $result = [];
1773                 foreach ($languages as $language) {
1774                         if ($language == $content) {
1775                                 continue;
1776                         }
1777                         $language = DI::l10n()->toISO6391($language);
1778                         if (!in_array($language, array_column($iso639->allLanguages(), 0))) {
1779                                 continue;
1780                         }
1781                         $result[] = $language;
1782                 }
1783                 return $result;
1784         }
1785
1786         /**
1787          * perform a "follow" request
1788          *
1789          * @param array $activity
1790          * @return void
1791          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1792          * @throws \ImagickException
1793          */
1794         public static function followUser(array $activity)
1795         {
1796                 $uid = User::getIdForURL($activity['object_id']);
1797                 if (empty($uid)) {
1798                         Queue::remove($activity);
1799                         return;
1800                 }
1801
1802                 $owner = User::getOwnerDataById($uid);
1803                 if (empty($owner)) {
1804                         return;
1805                 }
1806
1807                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1808                 if (!empty($cid)) {
1809                         self::switchContact($cid);
1810                         Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1811                 }
1812
1813                 $item = [
1814                         'author-id' => Contact::getIdForURL($activity['actor']),
1815                         'author-link' => $activity['actor'],
1816                 ];
1817
1818                 // Ensure that the contact has got the right network type
1819                 self::switchContact($item['author-id']);
1820
1821                 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1822                 if ($result === true) {
1823                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1824                 }
1825
1826                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1827                 if (empty($cid)) {
1828                         return;
1829                 }
1830
1831                 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1832                         self::transmitPendingEvents($cid, $owner['uid']);
1833                 }
1834
1835                 if (empty($contact)) {
1836                         Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1837                 }
1838                 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1839                 Queue::remove($activity);
1840         }
1841
1842         /**
1843          * Transmit pending events to the new follower
1844          *
1845          * @param integer $cid Contact id
1846          * @param integer $uid User id
1847          * @return void
1848          */
1849         private static function transmitPendingEvents(int $cid, int $uid)
1850         {
1851                 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1852                 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1853
1854                 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1855                 while ($event = DBA::fetch($events)) {
1856                         $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1857                         if (empty($post)) {
1858                                 continue;
1859                         }
1860                         if (DI::config()->get('system', 'bulk_delivery')) {
1861                                 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1862                                 Worker::add(Worker::PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1863                         } else {
1864                                 Worker::add(Worker::PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1865                         }
1866                 }
1867         }
1868
1869         /**
1870          * Update the given profile
1871          *
1872          * @param array $activity
1873          * @throws \Exception
1874          */
1875         public static function updatePerson(array $activity)
1876         {
1877                 if (empty($activity['object_id'])) {
1878                         return;
1879                 }
1880
1881                 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1882                 Contact::updateFromProbeByURL($activity['object_id']);
1883                 Queue::remove($activity);
1884         }
1885
1886         /**
1887          * Delete the given profile
1888          *
1889          * @param array $activity
1890          * @return void
1891          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1892          */
1893         public static function deletePerson(array $activity)
1894         {
1895                 if (empty($activity['object_id']) || empty($activity['actor'])) {
1896                         Logger::info('Empty object id or actor.');
1897                         Queue::remove($activity);
1898                         return;
1899                 }
1900
1901                 if ($activity['object_id'] != $activity['actor']) {
1902                         Logger::info('Object id does not match actor.');
1903                         Queue::remove($activity);
1904                         return;
1905                 }
1906
1907                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1908                 while ($contact = DBA::fetch($contacts)) {
1909                         Contact::remove($contact['id']);
1910                 }
1911                 DBA::close($contacts);
1912
1913                 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1914                 Queue::remove($activity);
1915         }
1916
1917         /**
1918          * Add moved contacts as followers for all subscribers of the old contact
1919          *
1920          * @param array $activity
1921          * @return void
1922          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1923          */
1924         public static function movePerson(array $activity)
1925         {
1926                 if (empty($activity['target_id']) || empty($activity['object_id'])) {
1927                         Queue::remove($activity);
1928                         return;
1929                 }
1930
1931                 if ($activity['object_id'] != $activity['actor']) {
1932                         Logger::notice('Object is not the actor', ['activity' => $activity]);
1933                         Queue::remove($activity);
1934                         return;
1935                 }
1936
1937                 $from = Contact::getByURL($activity['object_id'], false, ['uri-id']);
1938                 if (empty($from['uri-id'])) {
1939                         Logger::info('Object not found', ['activity' => $activity]);
1940                         Queue::remove($activity);
1941                         return;
1942                 }
1943
1944                 $contacts = DBA::select('contact', ['uid', 'url'], ["`uri-id` = ? AND `uid` != ? AND `rel` IN (?, ?)", $from['uri-id'], 0, Contact::FRIEND, Contact::SHARING]);
1945                 while ($from_contact = DBA::fetch($contacts)) {
1946                         $result = Contact::createFromProbeForUser($from_contact['uid'], $activity['target_id']);
1947                         Logger::debug('Follower added', ['from' => $from_contact, 'result' => $result]);
1948                 }
1949                 DBA::close($contacts);
1950                 Queue::remove($activity);
1951         }
1952
1953         /**
1954          * Blocks the user by the contact
1955          *
1956          * @param array $activity
1957          * @return void
1958          * @throws \Exception
1959          */
1960         public static function blockAccount(array $activity)
1961         {
1962                 $cid = Contact::getIdForURL($activity['actor']);
1963                 if (empty($cid)) {
1964                         return;
1965                 }
1966
1967                 $uid = User::getIdForURL($activity['object_id']);
1968                 if (empty($uid)) {
1969                         return;
1970                 }
1971
1972                 Contact\User::setIsBlocked($cid, $uid, true);
1973
1974                 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1975                 Queue::remove($activity);
1976         }
1977
1978         /**
1979          * Unblocks the user by the contact
1980          *
1981          * @param array $activity
1982          * @return void
1983          * @throws \Exception
1984          */
1985         public static function unblockAccount(array $activity)
1986         {
1987                 $cid = Contact::getIdForURL($activity['actor']);
1988                 if (empty($cid)) {
1989                         return;
1990                 }
1991
1992                 $uid = User::getIdForURL($activity['object_object']);
1993                 if (empty($uid)) {
1994                         return;
1995                 }
1996
1997                 Contact\User::setIsBlocked($cid, $uid, false);
1998
1999                 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
2000                 Queue::remove($activity);
2001         }
2002
2003         /**
2004          * Report a user
2005          *
2006          * @param array $activity
2007          * @return void
2008          * @throws \Exception
2009          */
2010         public static function ReportAccount(array $activity)
2011         {
2012                 $account = Contact::getByURL($activity['object_id'], null, ['id', 'gsid']);
2013                 if (empty($account)) {
2014                         Logger::info('Unknown account', ['activity' => $activity]);
2015                         Queue::remove($activity);
2016                         return;
2017                 }
2018
2019                 $reporter_id = Contact::getIdForURL($activity['actor']);
2020                 if (empty($reporter_id)) {
2021                         Logger::info('Unknown actor', ['activity' => $activity]);
2022                         Queue::remove($activity);
2023                         return;
2024                 }
2025
2026                 $uri_ids = [];
2027                 foreach ($activity['object_ids'] as $status_id) {
2028                         $post = Post::selectFirst(['uri-id'], ['uri' => $status_id]);
2029                         if (!empty($post['uri-id'])) {
2030                                 $uri_ids[] = $post['uri-id'];
2031                         }
2032                 }
2033
2034                 $report = DI::reportFactory()->createFromReportsRequest(System::getRules(true), $reporter_id, $account['id'], $account['gsid'], $activity['content'], 'other', false, $uri_ids);
2035                 DI::report()->save($report);
2036
2037                 Logger::info('Stored report', ['reporter' => $reporter_id, 'account' => $account, 'comment' => $activity['content'], 'object_ids' => $activity['object_ids']]);
2038         }
2039
2040         /**
2041          * Accept a follow request
2042          *
2043          * @param array $activity
2044          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2045          * @throws \ImagickException
2046          */
2047         public static function acceptFollowUser(array $activity)
2048         {
2049                 if (!empty($activity['object_actor'])) {
2050                         $uid      = User::getIdForURL($activity['object_actor']);
2051                         $check_id = false;
2052                 } elseif (!empty($activity['receiver']) && (count($activity['receiver']) == 1)) {
2053                         $uid      = array_shift($activity['receiver']);
2054                         $check_id = true;
2055                 }
2056
2057                 if (empty($uid)) {
2058                         Logger::notice('User could not be detected', ['activity' => $activity]);
2059                         Queue::remove($activity);
2060                         return;
2061                 }
2062
2063                 $cid = Contact::getIdForURL($activity['actor'], $uid);
2064                 if (empty($cid)) {
2065                         Logger::notice('No contact found', ['actor' => $activity['actor']]);
2066                         Queue::remove($activity);
2067                         return;
2068                 }
2069
2070                 $id = Transmitter::activityIDFromContact($cid);
2071                 if ($id == $activity['object_id']) {
2072                         Logger::info('Successful id check', ['uid' => $uid, 'cid' => $cid]);
2073                 } else {
2074                         Logger::info('Unsuccessful id check', ['uid' => $uid, 'cid' => $cid, 'id' => $id, 'object_id' => $activity['object_id']]);
2075                         if ($check_id) {
2076                                 Queue::remove($activity);
2077                                 return;
2078                         }
2079                 }
2080
2081                 self::switchContact($cid);
2082
2083                 $fields = ['pending' => false];
2084
2085                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
2086                 if ($contact['rel'] == Contact::FOLLOWER) {
2087                         $fields['rel'] = Contact::FRIEND;
2088                 }
2089
2090                 $condition = ['id' => $cid];
2091                 Contact::update($fields, $condition);
2092                 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
2093                 Queue::remove($activity);
2094         }
2095
2096         /**
2097          * Reject a follow request
2098          *
2099          * @param array $activity
2100          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2101          * @throws \ImagickException
2102          */
2103         public static function rejectFollowUser(array $activity)
2104         {
2105                 $uid = User::getIdForURL($activity['object_actor']);
2106                 if (empty($uid)) {
2107                         return;
2108                 }
2109
2110                 $cid = Contact::getIdForURL($activity['actor'], $uid);
2111                 if (empty($cid)) {
2112                         Logger::info('No contact found', ['actor' => $activity['actor']]);
2113                         return;
2114                 }
2115
2116                 self::switchContact($cid);
2117
2118                 $contact = Contact::getById($cid, ['rel']);
2119                 if ($contact['rel'] == Contact::SHARING) {
2120                         Contact::remove($cid);
2121                         Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
2122                 } elseif ($contact['rel'] == Contact::FRIEND) {
2123                         Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
2124                 } else {
2125                         Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
2126                 }
2127                 Queue::remove($activity);
2128         }
2129
2130         /**
2131          * Undo activity like "like" or "dislike"
2132          *
2133          * @param array $activity
2134          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2135          * @throws \ImagickException
2136          */
2137         public static function undoActivity(array $activity)
2138         {
2139                 if (empty($activity['object_id'])) {
2140                         return;
2141                 }
2142
2143                 if (empty($activity['object_actor'])) {
2144                         return;
2145                 }
2146
2147                 $author_id = Contact::getIdForURL($activity['object_actor']);
2148                 if (empty($author_id)) {
2149                         return;
2150                 }
2151
2152                 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => Item::GRAVITY_ACTIVITY]);
2153                 Queue::remove($activity);
2154         }
2155
2156         /**
2157          * Activity to remove a follower
2158          *
2159          * @param array $activity
2160          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2161          * @throws \ImagickException
2162          */
2163         public static function undoFollowUser(array $activity)
2164         {
2165                 $uid = User::getIdForURL($activity['object_object']);
2166                 if (empty($uid)) {
2167                         return;
2168                 }
2169
2170                 $owner = User::getOwnerDataById($uid);
2171                 if (empty($owner)) {
2172                         return;
2173                 }
2174
2175                 $cid = Contact::getIdForURL($activity['actor'], $uid);
2176                 if (empty($cid)) {
2177                         Logger::info('No contact found', ['actor' => $activity['actor']]);
2178                         return;
2179                 }
2180
2181                 self::switchContact($cid);
2182
2183                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2184                 if (!DBA::isResult($contact)) {
2185                         return;
2186                 }
2187
2188                 Contact::removeFollower($contact);
2189                 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
2190                 Queue::remove($activity);
2191         }
2192
2193         /**
2194          * Switches a contact to AP if needed
2195          *
2196          * @param integer $cid Contact ID
2197          * @return void
2198          * @throws \Exception
2199          */
2200         private static function switchContact(int $cid)
2201         {
2202                 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
2203                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
2204                         return;
2205                 }
2206
2207                 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
2208                 Contact::updateFromProbe($cid);
2209         }
2210
2211         /**
2212          * Collects implicit mentions like:
2213          * - the author of the parent item
2214          * - all the mentioned conversants in the parent item
2215          *
2216          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
2217          * @return array
2218          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2219          */
2220         private static function getImplicitMentionList(array $parent): array
2221         {
2222                 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
2223
2224                 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
2225
2226                 $implicit_mentions = [];
2227                 if (empty($parent_author['url'])) {
2228                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
2229                 } else {
2230                         $implicit_mentions[] = $parent_author['url'];
2231                         $implicit_mentions[] = $parent_author['nurl'];
2232                         $implicit_mentions[] = $parent_author['alias'];
2233                 }
2234
2235                 if (!empty($parent['alias'])) {
2236                         $implicit_mentions[] = $parent['alias'];
2237                 }
2238
2239                 foreach ($parent_terms as $term) {
2240                         $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
2241                         if (!empty($contact['url'])) {
2242                                 $implicit_mentions[] = $contact['url'];
2243                                 $implicit_mentions[] = $contact['nurl'];
2244                                 $implicit_mentions[] = $contact['alias'];
2245                         }
2246                 }
2247
2248                 return $implicit_mentions;
2249         }
2250
2251         /**
2252          * Strips from the body prepended implicit mentions
2253          *
2254          * @param string $body
2255          * @param array $parent
2256          * @return string
2257          */
2258         private static function removeImplicitMentionsFromBody(string $body, array $parent): string
2259         {
2260                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
2261                         return $body;
2262                 }
2263
2264                 $potential_mentions = self::getImplicitMentionList($parent);
2265
2266                 $kept_mentions = [];
2267
2268                 // Extract one prepended mention at a time from the body
2269                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
2270                         if (!in_array($matches[2], $potential_mentions)) {
2271                                 $kept_mentions[] = $matches[1];
2272                         }
2273
2274                         $body = $matches[3];
2275                 }
2276
2277                 // Re-appending the kept mentions to the body after extraction
2278                 $kept_mentions[] = $body;
2279
2280                 return implode('', $kept_mentions);
2281         }
2282
2283         /**
2284          * Adds links to string mentions
2285          *
2286          * @param string $body
2287          * @param array  $tags
2288          * @return string
2289          */
2290         protected static function addMentionLinks(string $body, array $tags): string
2291         {
2292                 // This prevents links to be added again to Pleroma-style mention links
2293                 $body = self::normalizeMentionLinks($body);
2294
2295                 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
2296                         foreach ($tags as $tag) {
2297                                 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
2298                                         continue;
2299                                 }
2300
2301                                 $hash = substr($tag['name'], 0, 1);
2302                                 $name = substr($tag['name'], 1);
2303                                 if (!in_array($hash, Tag::TAG_CHARACTER)) {
2304                                         $hash = '';
2305                                         $name = $tag['name'];
2306                                 }
2307
2308                                 if (Network::isValidHttpUrl($tag['href'])) {
2309                                         $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);
2310                                 }
2311                         }
2312
2313                         return $body;
2314                 });
2315
2316                 return $body;
2317         }
2318 }