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