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