]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
9e7921699676172a8de596f8658f474612b12490
[friendica.git] / src / Protocol / ActivityPub / Receiver.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\DI;
32 use Friendica\Model\Contact;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Util\HTTPSignature;
40 use Friendica\Util\JsonLD;
41 use Friendica\Util\LDSignature;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
44
45 /**
46  * ActivityPub Receiver Protocol class
47  *
48  * To-Do:
49  * @todo Undo Announce
50  *
51  * Check what this is meant to do:
52  * - Add
53  * - Block
54  * - Flag
55  * - Remove
56  * - Undo Block
57  */
58 class Receiver
59 {
60         const PUBLIC_COLLECTION = 'as:Public';
61         const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
62         const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
63         const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
64
65         const TARGET_UNKNOWN = 0;
66         const TARGET_TO = 1;
67         const TARGET_CC = 2;
68         const TARGET_BTO = 3;
69         const TARGET_BCC = 4;
70         const TARGET_FOLLOWER = 5;
71         const TARGET_ANSWER = 6;
72         const TARGET_GLOBAL = 7;
73
74         const COMPLETION_NONE    = 0;
75         const COMPLETION_ANNOUCE = 1;
76         const COMPLETION_RELAY   = 2;
77         const COMPLETION_MANUAL  = 3;
78         const COMPLETION_AUTO    = 4;
79
80         /**
81          * Checks incoming message from the inbox
82          *
83          * @param string  $body Body string
84          * @param array   $header Header lines
85          * @param integer $uid User ID
86          * @return void
87          * @throws \Exception
88          */
89         public static function processInbox(string $body, array $header, int $uid)
90         {
91                 $activity = json_decode($body, true);
92                 if (empty($activity)) {
93                         Logger::warning('Invalid body.');
94                         return;
95                 }
96
97                 $ldactivity = JsonLD::compact($activity);
98
99                 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
100
101                 $apcontact = APContact::getByURL($actor);
102
103                 if (empty($apcontact)) {
104                         Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
105                         return;
106                 } elseif (APContact::isRelay($apcontact)) {
107                         self::processRelayPost($ldactivity, $actor);
108                         return;
109                 } else {
110                         APContact::unmarkForArchival($apcontact);
111                 }
112
113                 $http_signer = HTTPSignature::getSigner($body, $header);
114                 if ($http_signer === false) {
115                         Logger::warning('Invalid HTTP signature, message will be discarded.');
116                         return;
117                 } elseif (empty($http_signer)) {
118                         Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
119                         return;
120                 } else {
121                         Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
122                 }
123
124                 $signer = [$http_signer];
125
126                 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
127
128                 if (LDSignature::isSigned($activity)) {
129                         $ld_signer = LDSignature::getSigner($activity);
130                         if (empty($ld_signer)) {
131                                 Logger::info('Invalid JSON-LD signature from ' . $actor);
132                         } elseif ($ld_signer != $http_signer) {
133                                 $signer[] = $ld_signer;
134                         }
135                         if (!empty($ld_signer && ($actor == $http_signer))) {
136                                 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
137                                 $trust_source = true;
138                         } elseif (!empty($ld_signer)) {
139                                 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
140                                 $trust_source = true;
141                         } elseif ($actor == $http_signer) {
142                                 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
143                                 $trust_source = true;
144                         } else {
145                                 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
146                                 $trust_source = false;
147                         }
148                 } elseif ($actor == $http_signer) {
149                         Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
150                         $trust_source = true;
151                 } else {
152                         Logger::info('No JSON-LD signature, different actor.');
153                         $trust_source = false;
154                 }
155
156                 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
157         }
158
159         /**
160          * Process incoming posts from relays
161          *
162          * @param array  $activity
163          * @param string $actor
164          * @return void
165          */
166         private static function processRelayPost(array $activity, string $actor)
167         {
168                 $type = JsonLD::fetchElement($activity, '@type');
169                 if (!$type) {
170                         Logger::info('Empty type', ['activity' => $activity, 'actor' => $actor]);
171                         return;
172                 }
173
174                 if ($type != 'as:Announce') {
175                         Logger::info('Not an announcement', ['activity' => $activity, 'actor' => $actor]);
176                         return;
177                 }
178
179                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
180                 if (empty($object_id)) {
181                         Logger::info('No object id found', ['activity' => $activity, 'actor' => $actor]);
182                         return;
183                 }
184
185                 $contact = Contact::getByURL($actor);
186                 if (empty($contact)) {
187                         Logger::info('Relay contact not found', ['actor' => $actor]);
188                         return;
189                 }
190
191                 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
192                         Logger::notice('Relay is no sharer', ['actor' => $actor]);
193                         return;
194                 }
195
196                 Logger::info('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
197
198                 $item_id = Item::searchByLink($object_id);
199                 if ($item_id) {
200                         Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
201                         return;
202                 }
203
204                 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
205                 if (empty($id)) {
206                         Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
207                         return;
208                 }
209
210                 $item_id = Item::searchByLink($object_id);
211                 if ($item_id) {
212                         Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
213                 } else {
214                         Logger::notice('Relayed message had not been stored', ['id' => $object_id, 'actor' => $actor]);
215                 }
216         }
217
218         /**
219          * Fetches the object type for a given object id
220          *
221          * @param array   $activity
222          * @param string  $object_id Object ID of the the provided object
223          * @param integer $uid       User ID
224          *
225          * @return string with object type or NULL
226          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227          * @throws \ImagickException
228          */
229         private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
230         {
231                 if (!empty($activity['as:object'])) {
232                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
233                         if (!empty($object_type)) {
234                                 return $object_type;
235                         }
236                 }
237
238                 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
239                         // We just assume "note" since it doesn't make a difference for the further processing
240                         return 'as:Note';
241                 }
242
243                 $profile = APContact::getByURL($object_id);
244                 if (!empty($profile['type'])) {
245                         APContact::unmarkForArchival($profile);
246                         return 'as:' . $profile['type'];
247                 }
248
249                 $data = ActivityPub::fetchContent($object_id, $uid);
250                 if (!empty($data)) {
251                         $object = JsonLD::compact($data);
252                         $type = JsonLD::fetchElement($object, '@type');
253                         if (!empty($type)) {
254                                 return $type;
255                         }
256                 }
257
258                 return null;
259         }
260
261         /**
262          * Prepare the object array
263          *
264          * @param array   $activity     Array with activity data
265          * @param integer $uid          User ID
266          * @param boolean $push         Message had been pushed to our system
267          * @param boolean $trust_source Do we trust the source?
268          *
269          * @return array with object data
270          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271          * @throws \ImagickException
272          */
273         public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
274         {
275                 $id        = JsonLD::fetchElement($activity, '@id');
276                 $type      = JsonLD::fetchElement($activity, '@type');
277                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
278
279                 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
280                         $fetch_id = $object_id;
281                 } else {
282                         $fetch_id = $id;
283                 }
284
285                 if (!empty($activity['as:object'])) {
286                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
287                 }
288
289                 if (!empty($id) && !$trust_source) {
290                         $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
291
292                         $fetched_activity = ActivityPub::fetchContent($fetch_id, $fetch_uid);
293                         if (!empty($fetched_activity)) {
294                                 $object = JsonLD::compact($fetched_activity);
295
296                                 $fetched_id   = JsonLD::fetchElement($object, '@id');
297                                 $fetched_type = JsonLD::fetchElement($object, '@type');
298
299                                 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
300                                         Logger::info('Activity had been fetched successfully', ['id' => $id]);
301                                         $trust_source = true;
302                                         $activity = $object;
303                                 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
304                                         Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
305                                         $trust_source = true;
306                                         unset($object['@context']);
307                                         $activity['as:object'] = $object;
308                                 } else {
309                                         Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
310                                 }
311                         } else {
312                                 Logger::info('Activity could not been fetched', ['id' => $id]);
313                         }
314                 }
315
316                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
317                 if (empty($actor)) {
318                         Logger::info('Empty actor', ['activity' => $activity]);
319                         return [];
320                 }
321
322                 $type = JsonLD::fetchElement($activity, '@type');
323
324                 // Fetch all receivers from to, cc, bto and bcc
325                 $receiverdata = self::getReceivers($activity, $actor);
326                 $receivers = $reception_types = [];
327                 foreach ($receiverdata as $key => $data) {
328                         $receivers[$key] = $data['uid'];
329                         $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
330                 }
331
332                 $urls = self::getReceiverURL($activity);
333
334                 // When it is a delivery to a personal inbox we add that user to the receivers
335                 if (!empty($uid)) {
336                         $additional = [$uid => $uid];
337                         $receivers = array_replace($receivers, $additional);
338                         if (empty($activity['thread-completion']) && (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL]))) {
339                                 $reception_types[$uid] = self::TARGET_BCC;
340                                 $owner = User::getOwnerDataById($uid);
341                                 if (!empty($owner['url'])) {
342                                         $urls['as:bcc'][] = $owner['url'];
343                                 }
344                         }
345                 }
346
347                 // We possibly need some user to fetch private content,
348                 // so we fetch one out of the receivers if no uid is provided.
349                 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
350
351                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
352                 if (empty($object_id)) {
353                         Logger::info('No object found');
354                         return [];
355                 }
356
357                 if (!is_string($object_id)) {
358                         Logger::info('Invalid object id', ['object' => $object_id]);
359                         return [];
360                 }
361
362                 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
363
364                 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
365                 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
366                         $data = ActivityPub::fetchContent($object_id, $fetch_uid);
367                         if (!empty($data)) {
368                                 $type = $object_type;
369                                 $activity = JsonLD::compact($data);
370
371                                 // Some variables need to be refetched since the activity changed
372                                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
373                                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
374                                 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
375                         }
376                 }
377
378                 // Any activities on account types must not be altered
379                 if (in_array($object_type, self::ACCOUNT_TYPES)) {
380                         $object_data = [];
381                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
382                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
383                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
384                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
385                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
386                         $object_data['push'] = $push;
387                         if (!$trust_source && ($type == 'as:Delete')) {
388                                 $apcontact = APContact::getByURL($object_data['object_id'], true);
389                                 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
390                         }
391                 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
392                         // Fetch the content only on activities where this matters
393                         // We can receive "#emojiReaction" when fetching content from Hubzilla systems
394                         // Always fetch on "Announce"
395                         $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
396                         if (empty($object_data)) {
397                                 Logger::info("Object data couldn't be processed");
398                                 return [];
399                         }
400
401                         $object_data['object_id'] = $object_id;
402
403                         if ($type == 'as:Announce') {
404                                 $object_data['push'] = false;
405                         } else {
406                                 $object_data['push'] = $push;
407                         }
408
409                         // Test if it is an answer to a mail
410                         if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
411                                 $object_data['directmessage'] = true;
412                         } else {
413                                 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
414                         }
415                 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
416                         // Create a mostly empty array out of the activity data (instead of the object).
417                         // This way we later don't have to check for the existence of each individual array element.
418                         $object_data = self::processObject($activity);
419                         $object_data['name'] = $type;
420                         $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
421                         $object_data['object_id'] = $object_id;
422                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
423                         $object_data['push'] = $push;
424                 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
425                         $object_data = [];
426                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
427                         $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
428                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
429                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
430                         $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
431                         $object_data['push'] = $push;
432                 } else {
433                         $object_data = [];
434                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
435                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
436                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
437                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
438                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
439                         $object_data['push'] = $push;
440
441                         // An Undo is done on the object of an object, so we need that type as well
442                         if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
443                                 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
444                         }
445
446                         if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
447                                 $trust_source = Processor::isActivityGone($object_data['object_id']);
448                                 if (!$trust_source) {
449                                         $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
450                                 }
451                         }
452                 }
453
454                 $object_data = self::addActivityFields($object_data, $activity);
455
456                 if (empty($object_data['object_type'])) {
457                         $object_data['object_type'] = $object_type;
458                 }
459
460                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
461                         if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
462                                 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
463                         }
464                 }
465
466                 $object_data['type'] = $type;
467                 $object_data['actor'] = $actor;
468                 $object_data['item_receiver'] = $receivers;
469                 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
470                 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
471
472 //              This check here interferes with Hubzilla posts where the author host differs from the host the post was created
473 //              $author = $object_data['author'] ?? $actor;
474 //              if (!empty($author) && !empty($object_data['id'])) {
475 //                      $author_host = parse_url($author, PHP_URL_HOST);
476 //                      $id_host = parse_url($object_data['id'], PHP_URL_HOST);
477 //                      if ($author_host == $id_host) {
478 //                              Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
479 //                      } else {
480 //                              Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
481 //                              $trust_source = false;
482 //                      }
483 //              }
484
485                 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
486
487                 return $object_data;
488         }
489
490         /**
491          * Fetches the first user id from the receiver array
492          *
493          * @param array $receivers Array with receivers
494          * @return integer user id;
495          */
496         public static function getFirstUserFromReceivers(array $receivers): int
497         {
498                 foreach ($receivers as $receiver) {
499                         if (!empty($receiver)) {
500                                 return $receiver;
501                         }
502                 }
503                 return 0;
504         }
505
506         /**
507          * Processes the activity object
508          *
509          * @param array      $activity     Array with activity data
510          * @param string     $body         The unprocessed body
511          * @param int|null   $uid          User ID
512          * @param boolean    $trust_source Do we trust the source?
513          * @param boolean    $push         Message had been pushed to our system
514          * @param array      $signer       The signer of the post
515          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
516          * @throws \ImagickException
517          */
518         public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '')
519         {
520                 $type = JsonLD::fetchElement($activity, '@type');
521                 if (!$type) {
522                         Logger::info('Empty type', ['activity' => $activity]);
523                         return;
524                 }
525
526                 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
527                         Logger::info('Empty object', ['activity' => $activity]);
528                         return;
529                 }
530
531                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
532                 if (empty($actor)) {
533                         Logger::info('Empty actor', ['activity' => $activity]);
534                         return;
535                 }
536
537                 if (is_array($activity['as:object'])) {
538                         $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
539                 } else {
540                         $attributed_to = '';
541                 }
542
543                 // Test the provided signatures against the actor and "attributedTo"
544                 if ($trust_source) {
545                         if (!empty($attributed_to) && !empty($actor)) {
546                                 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
547                         } else {
548                                 $trust_source = in_array($actor, $signer);
549                         }
550                 }
551
552                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
553                 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
554                 if (empty($object_data)) {
555                         Logger::info('No object data found', ['activity' => $activity]);
556                         return;
557                 }
558
559                 // Lemmy is announcing activities.
560                 // We are changing the announces into regular activities.
561                 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
562                         $type = $object_data['type'];
563                 }
564
565                 if (!empty($body) && empty($object_data['raw'])) {
566                         $object_data['raw'] = $body;
567                 }
568
569                 // Internal flag for thread completion. See Processor.php
570                 if (!empty($activity['thread-completion'])) {
571                         $object_data['thread-completion'] = $activity['thread-completion'];
572                 }
573
574                 if (!empty($activity['completion-mode'])) {
575                         $object_data['completion-mode'] = $activity['completion-mode'];
576                 }
577
578                 if (!empty($activity['thread-children-type'])) {
579                         $object_data['thread-children-type'] = $activity['thread-children-type'];
580                 }
581
582                 // Internal flag for posts that arrived via relay
583                 if (!empty($activity['from-relay'])) {
584                         $object_data['from-relay'] = $activity['from-relay'];
585                 }
586
587                 if ($type == 'as:Announce') {
588                         $object_data['object_activity'] = $activity;
589                 }
590
591                 if ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted')) {
592                         $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
593                 }
594
595                 if (!$trust_source) {
596                         Logger::info('Activity trust could not be achieved.',  ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
597                         return;
598                 }
599
600                 if (!empty($activity['recursion-depth'])) {
601                         $object_data['recursion-depth'] = $activity['recursion-depth'];
602                 }
603
604                 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
605                         self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
606                 }
607
608                 if (!self::routeActivities($object_data, $type, $push)) {
609                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
610                         Queue::remove($object_data);
611                 }
612         }
613
614         /**
615          * Route activities
616          *
617          * @param array   $object_data
618          * @param string  $type
619          * @param boolean $push
620          *
621          * @return boolean Could the activity be routed?
622          */
623         public static function routeActivities(array $object_data, string $type, bool $push): bool
624         {
625                 $activity = $object_data['object_activity']     ?? [];
626
627                 switch ($type) {
628                         case 'as:Create':
629                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
630                                         $item = ActivityPub\Processor::createItem($object_data);
631                                         ActivityPub\Processor::postItem($object_data, $item);
632                                 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
633                                         // Unhandled Peertube activity
634                                         Queue::remove($object_data);
635                                 } else {
636                                         return false;
637                                 }
638                                 break;
639
640                         case 'as:Invite':
641                                 if (in_array($object_data['object_type'], ['as:Event'])) {
642                                         $item = ActivityPub\Processor::createItem($object_data);
643                                         ActivityPub\Processor::postItem($object_data, $item);
644                                 } else {
645                                         return false;
646                                 }
647                                 break;
648
649                         case 'as:Add':
650                                 if ($object_data['object_type'] == 'as:tag') {
651                                         ActivityPub\Processor::addTag($object_data);
652                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
653                                         ActivityPub\Processor::addToFeaturedCollection($object_data);
654                                 } elseif ($object_data['object_type'] == '') {
655                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
656                                         Queue::remove($object_data);
657                                 } else {
658                                         return false;
659                                 }
660                                 break;
661
662                         case 'as:Announce':
663                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
664                                         $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
665                                         $object_data['thread-completion'] = Contact::getIdForURL($actor);
666                                         $object_data['completion-mode']   = self::COMPLETION_ANNOUCE;
667
668                                         $item = ActivityPub\Processor::createItem($object_data);
669                                         if (empty($item)) {
670                                                 return false;
671                                         }
672
673                                         $item['post-reason'] = Item::PR_ANNOUNCEMENT;
674                                         ActivityPub\Processor::postItem($object_data, $item);
675
676                                         if (!empty($activity)) {
677                                                 $announce_object_data = self::processObject($activity);
678                                                 $announce_object_data['name'] = $type;
679                                                 $announce_object_data['author'] = $actor;
680                                                 $announce_object_data['object_id'] = $object_data['object_id'];
681                                                 $announce_object_data['object_type'] = $object_data['object_type'];
682                                                 $announce_object_data['push'] = $push;
683
684                                                 if (!empty($object_data['raw'])) {
685                                                         $announce_object_data['raw'] = $object_data['raw'];
686                                                 }
687                                                 if (!empty($object_data['raw-object'])) {
688                                                         $announce_object_data['raw-object'] = $object_data['raw-object'];
689                                                 }
690                                                 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
691                                         }
692                                 } else {
693                                         return false;
694                                 }
695                                 break;
696
697                         case 'as:Like':
698                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
699                                         ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
700                                 } elseif ($object_data['object_type'] == '') {
701                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
702                                         Queue::remove($object_data);
703                                 } else {
704                                         return false;
705                                 }
706                                 break;
707
708                         case 'as:Dislike':
709                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
710                                         ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
711                                 } elseif ($object_data['object_type'] == '') {
712                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
713                                         Queue::remove($object_data);
714                                 } else {
715                                         return false;
716                                 }
717                                 break;
718
719                         case 'as:TentativeAccept':
720                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
721                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
722                                 } else {
723                                         return false;
724                                 }
725                                 break;
726
727                         case 'as:Update':
728                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
729                                         ActivityPub\Processor::updateItem($object_data);
730                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
731                                         ActivityPub\Processor::updatePerson($object_data);
732                                 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
733                                         // Unhandled Peertube activity
734                                         Queue::remove($object_data);
735                                 } else {
736                                         return false;
737                                 }
738                                 break;
739
740                         case 'as:Delete':
741                                 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
742                                         ActivityPub\Processor::deleteItem($object_data);
743                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
744                                         ActivityPub\Processor::deletePerson($object_data);
745                                 } elseif ($object_data['object_type'] == '') {
746                                         // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
747                                         Queue::remove($object_data);
748                                 } else {
749                                         return false;
750                                 }
751                                 break;
752
753                         case 'as:Block':
754                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
755                                         ActivityPub\Processor::blockAccount($object_data);
756                                 } else {
757                                         return false;
758                                 }
759                                 break;
760
761                         case 'as:Remove':
762                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
763                                         ActivityPub\Processor::removeFromFeaturedCollection($object_data);
764                                 } elseif ($object_data['object_type'] == '') {
765                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
766                                         Queue::remove($object_data);
767                                 } else {
768                                         return false;
769                                 }
770                                 break;
771
772                         case 'as:Follow':
773                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
774                                         ActivityPub\Processor::followUser($object_data);
775                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
776                                         $object_data['reply-to-id'] = $object_data['object_id'];
777                                         ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
778                                 } else {
779                                         return false;
780                                 }
781                                 break;
782
783                         case 'as:Accept':
784                                 if ($object_data['object_type'] == 'as:Follow') {
785                                         ActivityPub\Processor::acceptFollowUser($object_data);
786                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
787                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
788                                 } else {
789                                         return false;
790                                 }
791                                 break;
792
793                         case 'as:Reject':
794                                 if ($object_data['object_type'] == 'as:Follow') {
795                                         ActivityPub\Processor::rejectFollowUser($object_data);
796                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
797                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
798                                 } else {
799                                         return false;
800                                 }
801                                 break;
802
803                         case 'as:Undo':
804                                 if (($object_data['object_type'] == 'as:Follow') &&
805                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
806                                         ActivityPub\Processor::undoFollowUser($object_data);
807                                 } elseif (($object_data['object_type'] == 'as:Follow') &&
808                                         in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
809                                         ActivityPub\Processor::undoActivity($object_data);
810                                 } elseif (($object_data['object_type'] == 'as:Accept') &&
811                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
812                                         ActivityPub\Processor::rejectFollowUser($object_data);
813                                 } elseif (($object_data['object_type'] == 'as:Block') &&
814                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
815                                         ActivityPub\Processor::unblockAccount($object_data);
816                                 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
817                                         in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
818                                         ActivityPub\Processor::undoActivity($object_data);
819                                 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
820                                         empty($object_data['object_object_type'])) {
821                                         // We cannot detect the target object. So we can ignore it.
822                                         Queue::remove($object_data);
823                                 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
824                                         in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
825                                         // Unhandled Peertube activity
826                                         Queue::remove($object_data);
827                                 } else {
828                                         return false;
829                                 }
830                                 break;
831
832                         case 'as:View':
833                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
834                                         ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
835                                 } elseif ($object_data['object_type'] == '') {
836                                         // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
837                                         Queue::remove($object_data);
838                                 } else {
839                                         return false;
840                                 }
841                                 break;
842
843                         case 'litepub:EmojiReact':
844                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
845                                         ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
846                                 } elseif ($object_data['object_type'] == '') {
847                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
848                                         Queue::remove($object_data);
849                                 } else {
850                                         return false;
851                                 }
852                                 break;
853
854                         default:
855                                 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
856                                 return false;
857                 }
858                 return true;
859         }
860
861         /**
862          * Stores unhandled or unknown Activities as a file
863          *
864          * @param boolean $unknown      "true" if the activity is unknown, "false" if it is unhandled
865          * @param string  $type         Activity type
866          * @param array   $object_data  Preprocessed array that is generated out of the received activity
867          * @param array   $activity     Array with activity data
868          * @param string  $body         The unprocessed body
869          * @param integer $uid          User ID
870          * @param boolean $trust_source Do we trust the source?
871          * @param boolean $push         Message had been pushed to our system
872          * @param array   $signer       The signer of the post
873          * @return void
874          */
875         private static function storeUnhandledActivity(bool $unknown, string $type, array $object_data, array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
876         {
877                 if (!DI::config()->get('debug', 'ap_log_unknown')) {
878                         return;
879                 }
880
881                 $file = ($unknown  ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
882
883                 if (!empty($object_data['object_type'])) {
884                         $file .= str_replace(':', '-', $object_data['object_type']) . '-';
885                 }
886
887                 if (!empty($object_data['object_object_type'])) {
888                         $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
889                 }
890
891                 $tempfile = tempnam(System::getTempPath(), $file);
892                 file_put_contents($tempfile, json_encode(['activity' => $activity, 'body' => $body, 'uid' => $uid, 'trust_source' => $trust_source, 'push' => $push, 'signer' => $signer, 'object_data' => $object_data], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
893                 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
894         }
895
896         /**
897          * Fetch a user id from an activity array
898          *
899          * @param array  $activity
900          * @param string $actor
901          *
902          * @return int   user id
903          */
904         public static function getBestUserForActivity(array $activity): int
905         {
906                 $uid = 0;
907                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
908
909                 $receivers = self::getReceivers($activity, $actor);
910                 foreach ($receivers as $receiver) {
911                         if ($receiver['type'] == self::TARGET_GLOBAL) {
912                                 return 0;
913                         }
914                         if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
915                                 $uid = $receiver['uid'];
916                         }
917                 }
918
919                 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
920                 if (empty($uid)) {
921                         $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
922                         if (!empty($contact['uid'])) {
923                                 $uid = $contact['uid'];
924                         }
925                 }
926
927                 return $uid;
928         }
929
930         // @TODO Missing documentation
931         public static function getReceiverURL(array $activity): array
932         {
933                 $urls = [];
934
935                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
936                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
937                         if (empty($receiver_list)) {
938                                 continue;
939                         }
940
941                         foreach ($receiver_list as $receiver) {
942                                 if ($receiver == self::PUBLIC_COLLECTION) {
943                                         $receiver = ActivityPub::PUBLIC_COLLECTION;
944                                 }
945                                 $urls[$element][] = $receiver;
946                         }
947                 }
948
949                 return $urls;
950         }
951
952         /**
953          * Fetch the receiver list from an activity array
954          *
955          * @param array   $activity
956          * @param string  $actor
957          * @param array   $tags
958          * @param boolean $fetch_unlisted
959          *
960          * @return array with receivers (user id)
961          * @throws \Exception
962          */
963         private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
964         {
965                 $reply = $receivers = $profile = [];
966
967                 // When it is an answer, we inherite the receivers from the parent
968                 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
969                 if (!empty($replyto)) {
970                         $reply = [$replyto];
971
972                         // Fix possibly wrong item URI (could be an answer to a plink uri)
973                         $fixedReplyTo = Item::getURIByLink($replyto);
974                         if (!empty($fixedReplyTo)) {
975                                 $reply[] = $fixedReplyTo;
976                         }
977                 }
978
979                 // Fetch all posts that refer to the object id
980                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
981                 if (!empty($object_id)) {
982                         $reply[] = $object_id;
983                 }
984
985                 if (!empty($reply)) {
986                         $parents = Post::select(['uid'], ['uri' => $reply]);
987                         while ($parent = Post::fetch($parents)) {
988                                 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
989                         }
990                         DBA::close($parents);
991                 }
992
993                 if (!empty($actor)) {
994                         $profile   = APContact::getByURL($actor);
995                         $followers = $profile['followers'] ?? '';
996                         $is_forum  = ($actor['type'] ?? '') == 'Group';
997                         Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
998                 } else {
999                         Logger::info('Empty actor', ['activity' => $activity]);
1000                         $followers = '';
1001                         $is_forum  = false;
1002                 }
1003
1004                 // We have to prevent false follower assumptions upon thread completions
1005                 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1006
1007                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1008                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1009                         if (empty($receiver_list)) {
1010                                 continue;
1011                         }
1012
1013                         foreach ($receiver_list as $receiver) {
1014                                 if ($receiver == self::PUBLIC_COLLECTION) {
1015                                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1016                                 }
1017
1018                                 // Add receiver "-1" for unlisted posts
1019                                 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1020                                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1021                                 }
1022
1023                                 // Fetch the receivers for the public and the followers collection
1024                                 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1025                                         $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1026                                         continue;
1027                                 }
1028
1029                                 // Fetching all directly addressed receivers
1030                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1031                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1032                                 if (!DBA::isResult($contact)) {
1033                                         continue;
1034                                 }
1035
1036                                 // Check if the potential receiver is following the actor
1037                                 // Exception: The receiver is targetted via "to" or this is a comment
1038                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1039                                         $networks = Protocol::FEDERATED;
1040                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1041                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1042
1043                                         // Forum posts are only accepted from forum contacts
1044                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1045                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1046                                         }
1047
1048                                         if (!DBA::exists('contact', $condition)) {
1049                                                 continue;
1050                                         }
1051                                 }
1052
1053                                 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1054                                 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1055                                         switch ($element) {
1056                                                 case 'as:to':
1057                                                         $type = self::TARGET_TO;
1058                                                         break;
1059                                                 case 'as:cc':
1060                                                         $type = self::TARGET_CC;
1061                                                         break;
1062                                                 case 'as:bto':
1063                                                         $type = self::TARGET_BTO;
1064                                                         break;
1065                                                 case 'as:bcc':
1066                                                         $type = self::TARGET_BCC;
1067                                                         break;
1068                                         }
1069
1070                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1071                                 }
1072                         }
1073                 }
1074
1075                 self::switchContacts($receivers, $actor);
1076
1077                 return $receivers;
1078         }
1079
1080         /**
1081          * Fetch the receiver list of a given actor
1082          *
1083          * @param string  $actor
1084          * @param array   $tags
1085          * @param array   $receivers
1086          * @param integer $target_type
1087          * @param array   $profile
1088          *
1089          * @return array with receivers (user id)
1090          * @throws \Exception
1091          */
1092         private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1093         {
1094                 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1095                         'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1096
1097                 if (!empty($profile['uri-id'])) {
1098                         $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1099                         $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1100                         while ($contact = DBA::fetch($contacts)) {
1101                                 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1102                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1103                                 }
1104                         }
1105                         DBA::close($contacts);
1106                 } else {
1107                         // This part will only be called while post update 1426 wasn't finished
1108                         $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1109                         $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1110                         while ($contact = DBA::fetch($contacts)) {
1111                                 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1112                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1113                                 }
1114                         }
1115                         DBA::close($contacts);
1116
1117                         // The queries are split because of performance issues
1118                         $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1119                         $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1120                         while ($contact = DBA::fetch($contacts)) {
1121                                 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1122                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1123                                 }
1124                         }
1125                         DBA::close($contacts);
1126                 }
1127                 return $receivers;
1128         }
1129
1130         /**
1131          * Tests if the contact is a valid receiver for this actor
1132          *
1133          * @param array  $contact
1134          * @param array  $tags
1135          *
1136          * @return bool with receivers (user id)
1137          * @throws \Exception
1138          */
1139         private static function isValidReceiverForActor(array $contact, array $tags): bool
1140         {
1141                 // Are we following the contact? Then this is a valid receiver
1142                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1143                         return true;
1144                 }
1145
1146                 // When the possible receiver isn't a community, then it is no valid receiver
1147                 $owner = User::getOwnerDataById($contact['uid']);
1148                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1149                         return false;
1150                 }
1151
1152                 // Is the community account tagged?
1153                 foreach ($tags as $tag) {
1154                         if ($tag['type'] != 'Mention') {
1155                                 continue;
1156                         }
1157
1158                         if (Strings::compareLink($tag['href'], $owner['url'])) {
1159                                 return true;
1160                         }
1161                 }
1162
1163                 return false;
1164         }
1165
1166         /**
1167          * Switches existing contacts to ActivityPub
1168          *
1169          * @param integer $cid Contact ID
1170          * @param integer $uid User ID
1171          * @param string  $url Profile URL
1172          * @return void
1173          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1174          * @throws \ImagickException
1175          */
1176         public static function switchContact(int $cid, int $uid, string $url)
1177         {
1178                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1179                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1180                         return;
1181                 }
1182
1183                 if (Contact::updateFromProbe($cid)) {
1184                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1185                 }
1186
1187                 // Send a new follow request to be sure that the connection still exists
1188                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1189                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1190                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1191                 }
1192         }
1193
1194         /**
1195          * @TODO Fix documentation and type-hints
1196          *
1197          * @param $receivers
1198          * @param $actor
1199          * @return void
1200          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1201          * @throws \ImagickException
1202          */
1203         private static function switchContacts($receivers, $actor)
1204         {
1205                 if (empty($actor)) {
1206                         return;
1207                 }
1208
1209                 foreach ($receivers as $receiver) {
1210                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1211                         if (DBA::isResult($contact)) {
1212                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
1213                         }
1214
1215                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1216                         if (DBA::isResult($contact)) {
1217                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
1218                         }
1219                 }
1220         }
1221
1222         /**
1223          * @TODO Fix documentation and type-hints
1224          *
1225          * @param       $object_data
1226          * @param array $activity
1227          *
1228          * @return mixed
1229          */
1230         private static function addActivityFields($object_data, array $activity)
1231         {
1232                 if (!empty($activity['published']) && empty($object_data['published'])) {
1233                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1234                 }
1235
1236                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1237                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1238                 }
1239
1240                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1241                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1242
1243                 if (!empty($object_data['object_id'])) {
1244                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1245                         $objectId = Item::getURIByLink($object_data['object_id']);
1246                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1247                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1248                                 $object_data['object_id'] = $objectId;
1249                         }
1250                 }
1251
1252                 return $object_data;
1253         }
1254
1255         /**
1256          * Fetches the object data from external ressources if needed
1257          *
1258          * @param string  $object_id    Object ID of the the provided object
1259          * @param array   $object       The provided object array
1260          * @param boolean $trust_source Do we trust the provided object?
1261          * @param integer $uid          User ID for the signature that we use to fetch data
1262          *
1263          * @return array|false with trusted and valid object data
1264          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1265          * @throws \ImagickException
1266          */
1267         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1268         {
1269                 // By fetching the type we check if the object is complete.
1270                 $type = JsonLD::fetchElement($object, '@type');
1271
1272                 if (!$trust_source || empty($type)) {
1273                         $data = ActivityPub::fetchContent($object_id, $uid);
1274                         if (!empty($data)) {
1275                                 $object = JsonLD::compact($data);
1276                                 Logger::info('Fetched content for ' . $object_id);
1277                         } else {
1278                                 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1279
1280                                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1281                                 if (!DBA::isResult($item)) {
1282                                         Logger::info('Object with url ' . $object_id . ' was not found locally.');
1283                                         return false;
1284                                 }
1285                                 Logger::info('Using already stored item for url ' . $object_id);
1286                                 $data = ActivityPub\Transmitter::createNote($item);
1287                                 $object = JsonLD::compact($data);
1288                         }
1289
1290                         $id = JsonLD::fetchElement($object, '@id');
1291                         if (empty($id)) {
1292                                 Logger::info('Empty id');
1293                                 return false;
1294                         }
1295
1296                         if ($id != $object_id) {
1297                                 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1298                                 return false;
1299                         }
1300                 } else {
1301                         Logger::info('Using original object for url ' . $object_id);
1302                 }
1303
1304                 $type = JsonLD::fetchElement($object, '@type');
1305                 if (empty($type)) {
1306                         Logger::info('Empty type');
1307                         return false;
1308                 }
1309
1310                 // Lemmy is resharing "create" activities instead of content
1311                 // We fetch the content from the activity.
1312                 if (in_array($type, ['as:Create'])) {
1313                         $object = $object['as:object'];
1314                         $type = JsonLD::fetchElement($object, '@type');
1315                         if (empty($type)) {
1316                                 Logger::info('Empty type');
1317                                 return false;
1318                         }
1319                         $object_data = self::processObject($object);
1320                 }
1321
1322                 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1323                 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1324                         $object_data = self::processObject($object);
1325
1326                         if (!empty($data)) {
1327                                 $object_data['raw-object'] = json_encode($data);
1328                         }
1329                         return $object_data;
1330                 }
1331
1332                 if ($type == 'as:Announce') {
1333                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
1334                         if (empty($object_id) || !is_string($object_id)) {
1335                                 return false;
1336                         }
1337                         return self::fetchObject($object_id, [], false, $uid);
1338                 }
1339
1340                 Logger::info('Unhandled object type: ' . $type);
1341                 return false;
1342         }
1343
1344         /**
1345          * Converts the language element (Used by Peertube)
1346          *
1347          * @param array $languages
1348          * @return array Languages
1349          */
1350         public static function processLanguages(array $languages): array
1351         {
1352                 if (empty($languages)) {
1353                         return [];
1354                 }
1355
1356                 $language_list = [];
1357
1358                 foreach ($languages as $language) {
1359                         if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1360                                 $language_list[$language['_:identifier']] = $language['as:name'];
1361                         }
1362                 }
1363                 return $language_list;
1364         }
1365
1366         /**
1367          * Convert tags from JSON-LD format into a simplified format
1368          *
1369          * @param array $tags Tags in JSON-LD format
1370          *
1371          * @return array with tags in a simplified format
1372          */
1373         public static function processTags(array $tags): array
1374         {
1375                 $taglist = [];
1376
1377                 foreach ($tags as $tag) {
1378                         if (empty($tag)) {
1379                                 continue;
1380                         }
1381
1382                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1383                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1384                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1385
1386                         if (empty($element['type'])) {
1387                                 continue;
1388                         }
1389
1390                         if (empty($element['href'])) {
1391                                 $element['href'] = $element['name'];
1392                         }
1393
1394                         $taglist[] = $element;
1395                 }
1396                 return $taglist;
1397         }
1398
1399         /**
1400          * Convert emojis from JSON-LD format into a simplified format
1401          *
1402          * @param array $emojis
1403          * @return array with emojis in a simplified format
1404          */
1405         private static function processEmojis(array $emojis): array
1406         {
1407                 $emojilist = [];
1408
1409                 foreach ($emojis as $emoji) {
1410                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1411                                 continue;
1412                         }
1413
1414                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1415                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1416                                 'href' => $url];
1417
1418                         $emojilist[] = $element;
1419                 }
1420
1421                 return $emojilist;
1422         }
1423
1424         /**
1425          * Convert attachments from JSON-LD format into a simplified format
1426          *
1427          * @param array $attachments Attachments in JSON-LD format
1428          *
1429          * @return array Attachments in a simplified format
1430          */
1431         private static function processAttachments(array $attachments): array
1432         {
1433                 $attachlist = [];
1434
1435                 // Removes empty values
1436                 $attachments = array_filter($attachments);
1437
1438                 foreach ($attachments as $attachment) {
1439                         switch (JsonLD::fetchElement($attachment, '@type')) {
1440                                 case 'as:Page':
1441                                         $pageUrl = null;
1442                                         $pageImage = null;
1443
1444                                         $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1445                                         foreach ($urls as $url) {
1446                                                 // Single scalar URL case
1447                                                 if (is_string($url)) {
1448                                                         $pageUrl = $url;
1449                                                         continue;
1450                                                 }
1451
1452                                                 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1453                                                 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1454                                                 if (Strings::startsWith($mediaType, 'image')) {
1455                                                         $pageImage = $href;
1456                                                 } else {
1457                                                         $pageUrl = $href;
1458                                                 }
1459                                         }
1460
1461                                         $attachlist[] = [
1462                                                 'type'  => 'link',
1463                                                 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1464                                                 'desc'  => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1465                                                 'url'   => $pageUrl,
1466                                                 'image' => $pageImage,
1467                                         ];
1468                                         break;
1469                                 case 'as:Image':
1470                                         $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1471                                         $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1472                                         $imagePreviewUrl = null;
1473                                         // Multiple URLs?
1474                                         if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1475                                                 $imageVariants = [];
1476                                                 $previewVariants = [];
1477                                                 foreach ($urls as $url) {
1478                                                         // Scalar URL, no discrimination possible
1479                                                         if (is_string($url)) {
1480                                                                 $imageFullUrl = $url;
1481                                                                 continue;
1482                                                         }
1483
1484                                                         // Not sure what to do with a different Link media type than the base Image, we skip
1485                                                         if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1486                                                                 continue;
1487                                                         }
1488
1489                                                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1490
1491                                                         // Default URL choice if no discriminating width is provided
1492                                                         $imageFullUrl = $href ?? $imageFullUrl;
1493
1494                                                         $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1495
1496                                                         if ($href && $width) {
1497                                                                 $imageVariants[$width] = $href;
1498                                                                 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1499                                                                 $previewVariants[abs(632 - $width)] = $href;
1500                                                         }
1501                                                 }
1502
1503                                                 if ($imageVariants) {
1504                                                         // Taking the maximum size image
1505                                                         ksort($imageVariants);
1506                                                         $imageFullUrl = array_pop($imageVariants);
1507
1508                                                         // Taking the minimum number distance to the target distance
1509                                                         ksort($previewVariants);
1510                                                         $imagePreviewUrl = array_shift($previewVariants);
1511                                                 }
1512
1513                                                 unset($imageVariants);
1514                                                 unset($previewVariants);
1515                                         }
1516
1517                                         $attachlist[] = [
1518                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1519                                                 'mediaType' => $mediaType,
1520                                                 'name'  => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1521                                                 'url'   => $imageFullUrl,
1522                                                 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1523                                         ];
1524                                         break;
1525                                 default:
1526                                         $attachlist[] = [
1527                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1528                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1529                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1530                                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1531                                                 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1532                                                 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1533                                                 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1534                                         ];
1535                         }
1536                 }
1537
1538                 return $attachlist;
1539         }
1540
1541         /**
1542          * Convert questions from JSON-LD format into a simplified format
1543          *
1544          * @param array $object
1545          *
1546          * @return array Questions in a simplified format
1547          */
1548         private static function processQuestion(array $object): array
1549         {
1550                 $question = [];
1551
1552                 if (!empty($object['as:oneOf'])) {
1553                         $question['multiple'] = false;
1554                         $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1555                 } elseif (!empty($object['as:anyOf'])) {
1556                         $question['multiple'] = true;
1557                         $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1558                 } else {
1559                         return [];
1560                 }
1561
1562                 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1563                 if (!empty($closed)) {
1564                         $question['end-time'] = $closed;
1565                 } else {
1566                         $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1567                 }
1568
1569                 $question['voters']  = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1570                 $question['options'] = [];
1571
1572                 $voters = 0;
1573
1574                 foreach ($options as $option) {
1575                         if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1576                                 continue;
1577                         }
1578
1579                         $name = JsonLD::fetchElement($option, 'as:name', '@value');
1580
1581                         if (empty($option['as:replies'])) {
1582                                 continue;
1583                         }
1584
1585                         $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1586
1587                         $question['options'][] = ['name' => $name, 'replies' => $replies];
1588
1589                         $voters += (int)$replies;
1590                 }
1591
1592                 // For single choice question we can count the number of voters if not provided (like with Misskey)
1593                 if (empty($question['voters']) && !$question['multiple']) {
1594                         $question['voters'] = $voters;
1595                 }
1596
1597                 return $question;
1598         }
1599
1600         /**
1601          * Fetch the original source or content with the "language" Markdown or HTML
1602          *
1603          * @param array $object
1604          * @param array $object_data
1605          *
1606          * @return array Object data (?)
1607          * @throws \Exception
1608          */
1609         private static function getSource(array $object, array $object_data): array
1610         {
1611                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1612                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1613                 if (!empty($object_data['source'])) {
1614                         return $object_data;
1615                 }
1616
1617                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1618                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1619                 if (!empty($object_data['source'])) {
1620                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
1621                         return $object_data;
1622                 }
1623
1624                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1625                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1626                 if (!empty($object_data['source'])) {
1627                         $object_data['source'] = HTML::toBBCode($object_data['source']);
1628                         return $object_data;
1629                 }
1630
1631                 return $object_data;
1632         }
1633
1634         /**
1635          * Extracts a potential alternate URL from a list of additional URL elements
1636          *
1637          * @param array $urls
1638          * @return string
1639          */
1640         private static function extractAlternateUrl(array $urls): string
1641         {
1642                 $alternateUrl = '';
1643                 foreach ($urls as $key => $url) {
1644                         // Not a list but a single URL element
1645                         if (!is_numeric($key)) {
1646                                 continue;
1647                         }
1648
1649                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1650                                 continue;
1651                         }
1652
1653                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1654                         if (empty($href)) {
1655                                 continue;
1656                         }
1657
1658                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1659                         if (empty($mediatype)) {
1660                                 continue;
1661                         }
1662
1663                         if ($mediatype == 'text/html') {
1664                                 $alternateUrl = $href;
1665                         }
1666                 }
1667
1668                 return $alternateUrl;
1669         }
1670
1671         /**
1672          * Check if the "as:url" element is an array with multiple links
1673          * This is the case with audio and video posts.
1674          * Then the links are added as attachments
1675          *
1676          * @param array $urls The object URL list
1677          * @return array an array of attachments
1678          */
1679         private static function processAttachmentUrls(array $urls): array
1680         {
1681                 $attachments = [];
1682                 foreach ($urls as $key => $url) {
1683                         // Not a list but a single URL element
1684                         if (!is_numeric($key)) {
1685                                 continue;
1686                         }
1687
1688                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1689                                 continue;
1690                         }
1691
1692                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1693                         if (empty($href)) {
1694                                 continue;
1695                         }
1696
1697                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1698                         if (empty($mediatype)) {
1699                                 continue;
1700                         }
1701
1702                         $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1703
1704                         if ($filetype == 'audio') {
1705                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1706                         } elseif ($filetype == 'video') {
1707                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1708                                 // PeerTube audio-only track
1709                                 if ($height === 0) {
1710                                         continue;
1711                                 }
1712
1713                                 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1714                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1715                         } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1716                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1717
1718                                 // For Torrent links we always store the highest resolution
1719                                 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1720                                         continue;
1721                                 }
1722
1723                                 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1724                         } elseif ($mediatype == 'application/x-mpegURL') {
1725                                 // PeerTube exception, actual video link is in the tags of this URL element
1726                                 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1727                         }
1728                 }
1729
1730                 return array_values($attachments);
1731         }
1732
1733         /**
1734          * Fetches data from the object part of an activity
1735          *
1736          * @param array $object
1737          *
1738          * @return array|bool Object data or FALSE if $object does not contain @id element
1739          * @throws \Exception
1740          */
1741         private static function processObject(array $object)
1742         {
1743                 if (!JsonLD::fetchElement($object, '@id')) {
1744                         return false;
1745                 }
1746
1747                 $object_data = [];
1748                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1749                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1750                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1751
1752                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1753                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1754                         $object_data['reply-to-id'] = $object_data['id'];
1755
1756                         // On activities the "reply to" is the id of the object it refers to
1757                         if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1758                                 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1759                                 if (!empty($object_id)) {
1760                                         $object_data['reply-to-id'] = $object_id;
1761                                 }
1762                         }
1763                 } else {
1764                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1765                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1766                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1767                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1768                                 $object_data['reply-to-id'] = $replyToId;
1769                         }
1770                 }
1771
1772                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1773                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1774
1775                 if (empty($object_data['updated'])) {
1776                         $object_data['updated'] = $object_data['published'];
1777                 }
1778
1779                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1780                         $object_data['published'] = $object_data['updated'];
1781                 }
1782
1783                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1784                 if (empty($actor)) {
1785                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1786                 }
1787
1788                 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1789                 $location = JsonLD::fetchElement($location, 'location', '@value');
1790                 if ($location) {
1791                         // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1792                         // down to HTML and then finally format to plaintext.
1793                         $location = Markdown::convert($location);
1794                         $location = BBCode::toPlaintext($location);
1795                 }
1796
1797                 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1798                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1799                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1800                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1801                 $object_data['actor'] = $object_data['author'] = $actor;
1802                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1803                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1804                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1805                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1806                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1807                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1808                 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1809                 $object_data = self::getSource($object, $object_data);
1810                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1811                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1812                 $object_data['location'] = $location;
1813                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1814                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1815                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1816                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1817                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1818                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1819                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1820                 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1821                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1822                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1823                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1824
1825                 // Special treatment for Hubzilla links
1826                 if (is_array($object_data['alternate-url'])) {
1827                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1828
1829                         if (!is_string($object_data['alternate-url'])) {
1830                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1831                         }
1832                 }
1833
1834                 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1835                         $object_data['alternate-url'] = null;
1836                 }
1837
1838                 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1839                         $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1840                         $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1841                 }
1842
1843                 // For page types we expect that the alternate url posts to some page.
1844                 // So we add this to the attachments if it differs from the id.
1845                 // Currently only Lemmy is using the page type.
1846                 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1847                         $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1848                         $object_data['alternate-url'] = null;
1849                 }
1850
1851                 if ($object_data['object_type'] == 'as:Question') {
1852                         $object_data['question'] = self::processQuestion($object);
1853                 }
1854
1855                 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1856                 $receivers = $reception_types = [];
1857                 foreach ($receiverdata as $key => $data) {
1858                         $receivers[$key] = $data['uid'];
1859                         $reception_types[$data['uid']] = $data['type'] ?? 0;
1860                 }
1861
1862                 $object_data['receiver_urls']  = self::getReceiverURL($object);
1863                 $object_data['receiver']       = $receivers;
1864                 $object_data['reception_type'] = $reception_types;
1865
1866                 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1867                 unset($object_data['receiver'][-1]);
1868                 unset($object_data['reception_type'][-1]);
1869
1870                 return $object_data;
1871         }
1872 }