]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
11e7151e1e9f57e7bff9b0cd1d86390bce6a8d12
[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['type'] == 'Application' && $apcontact['nick'] == 'relay') {
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]);
212                         return;
213                 }
214
215                 if ($type != 'as:Announce') {
216                         Logger::info('Not an announcement', ['activity' => $activity]);
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]);
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]);
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]);
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]);
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]);
258                 } else {
259                         Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
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                                 } else {
619                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
620                                 }
621                                 break;
622
623                         case 'as:Invite':
624                                 if (in_array($object_data['object_type'], ['as:Event'])) {
625                                         $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
626                                         ActivityPub\Processor::postItem($object_data, $item);
627                                 } else {
628                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
629                                 }
630                                 break;
631
632                         case 'as:Add':
633                                 if ($object_data['object_type'] == 'as:tag') {
634                                         ActivityPub\Processor::addTag($object_data);
635                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
636                                         ActivityPub\Processor::addToFeaturedCollection($object_data);
637                                 } elseif ($object_data['object_type'] == '') {
638                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
639                                 } else {
640                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
641                                 }
642                                 break;
643
644                         case 'as:Announce':
645                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
646                                         $object_data['thread-completion'] = Contact::getIdForURL($actor);
647                                         $object_data['completion-mode']   = self::COMPLETION_ANNOUCE;
648
649                                         $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
650                                         if (empty($item)) {
651                                                 return;
652                                         }
653
654                                         $item['post-reason'] = Item::PR_ANNOUNCEMENT;
655                                         ActivityPub\Processor::postItem($object_data, $item);
656
657                                         $announce_object_data = self::processObject($activity);
658                                         $announce_object_data['name'] = $type;
659                                         $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
660                                         $announce_object_data['object_id'] = $object_data['object_id'];
661                                         $announce_object_data['object_type'] = $object_data['object_type'];
662                                         $announce_object_data['push'] = $push;
663
664                                         if (!empty($body)) {
665                                                 $announce_object_data['raw'] = $body;
666                                         }
667
668                                         ActivityPub\Processor::createActivity($fetchQueue, $announce_object_data, Activity::ANNOUNCE);
669                                 } else {
670                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
671                                 }
672                                 break;
673
674                         case 'as:Like':
675                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
676                                         ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::LIKE);
677                                 } elseif ($object_data['object_type'] == '') {
678                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
679                                 } else {
680                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
681                                 }
682                                 break;
683
684                         case 'as:Dislike':
685                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
686                                         ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::DISLIKE);
687                                 } elseif ($object_data['object_type'] == '') {
688                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
689                                 } else {
690                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
691                                 }
692                                 break;
693
694                         case 'as:TentativeAccept':
695                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
696                                         ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTENDMAYBE);
697                                 } else {
698                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
699                                 }
700                                 break;
701
702                         case 'as:Update':
703                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
704                                         ActivityPub\Processor::updateItem($fetchQueue, $object_data);
705                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
706                                         ActivityPub\Processor::updatePerson($object_data);
707                                 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
708                                         // Unhandled Peertube activity
709                                 } else {
710                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
711                                 }
712                                 break;
713
714                         case 'as:Delete':
715                                 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
716                                         ActivityPub\Processor::deleteItem($object_data);
717                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
718                                         ActivityPub\Processor::deletePerson($object_data);
719                                 } elseif ($object_data['object_type'] == '') {
720                                         // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
721                                 } else {
722                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
723                                 }
724                                 break;
725
726                         case 'as:Block':
727                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
728                                         ActivityPub\Processor::blockAccount($object_data);
729                                 } else {
730                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
731                                 }
732                                 break;
733
734                         case 'as:Remove':
735                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
736                                         ActivityPub\Processor::removeFromFeaturedCollection($object_data);                                      
737                                 } elseif ($object_data['object_type'] == '') {
738                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
739                                 } else {
740                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
741                                 }
742                                 break;
743
744                         case 'as:Follow':
745                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
746                                         ActivityPub\Processor::followUser($object_data);
747                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
748                                         $object_data['reply-to-id'] = $object_data['object_id'];
749                                         ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::FOLLOW);
750                                 } else {
751                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
752                                 }
753                                 break;
754
755                         case 'as:Accept':
756                                 if ($object_data['object_type'] == 'as:Follow') {
757                                         ActivityPub\Processor::acceptFollowUser($object_data);
758                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
759                                         ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTEND);
760                                 } else {
761                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
762                                 }
763                                 break;
764
765                         case 'as:Reject':
766                                 if ($object_data['object_type'] == 'as:Follow') {
767                                         ActivityPub\Processor::rejectFollowUser($object_data);
768                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
769                                         ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTENDNO);
770                                 } else {
771                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
772                                 }
773                                 break;
774
775                         case 'as:Undo':
776                                 if (($object_data['object_type'] == 'as:Follow') &&
777                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
778                                         ActivityPub\Processor::undoFollowUser($object_data);
779                                 } elseif (($object_data['object_type'] == 'as:Follow') &&
780                                         in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
781                                         ActivityPub\Processor::undoActivity($object_data);
782                                 } elseif (($object_data['object_type'] == 'as:Accept') &&
783                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
784                                         ActivityPub\Processor::rejectFollowUser($object_data);
785                                 } elseif (($object_data['object_type'] == 'as:Block') &&
786                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
787                                         ActivityPub\Processor::unblockAccount($object_data);
788                                 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
789                                         in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
790                                         ActivityPub\Processor::undoActivity($object_data);
791                                 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
792                                         empty($object_data['object_object_type'])) {
793                                         // We cannot detect the target object. So we can ignore it.
794                                 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
795                                         in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
796                                         // Unhandled Peertube activity
797                                 } else {
798                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
799                                 }
800                                 break;
801
802                         case 'as:View':
803                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
804                                         ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::VIEW);
805                                 } elseif ($object_data['object_type'] == '') {
806                                         // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
807                                 } else {
808                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
809                                 }
810                                 break;
811
812                         case 'litepub:EmojiReact':
813                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
814                                         ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::EMOJIREACT);
815                                 } elseif ($object_data['object_type'] == '') {
816                                         // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
817                                 } else {
818                                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
819                                 }
820                                 break;
821         
822                         default:
823                                 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
824                                 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
825                                 break;
826                 }
827         }
828
829         /**
830          * Stores unhandled or unknown Activities as a file
831          *
832          * @param boolean $unknown      "true" if the activity is unknown, "false" if it is unhandled
833          * @param string  $type         Activity type
834          * @param array   $object_data  Preprocessed array that is generated out of the received activity
835          * @param array   $activity     Array with activity data
836          * @param string  $body         The unprocessed body
837          * @param integer $uid          User ID
838          * @param boolean $trust_source Do we trust the source?
839          * @param boolean $push         Message had been pushed to our system
840          * @param array   $signer       The signer of the post
841          * @return void
842          */
843         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 = [])
844         {
845                 if (!DI::config()->get('debug', 'ap_log_unknown')) {
846                         return;
847                 }
848
849                 $file = ($unknown  ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
850         
851                 if (!empty($object_data['object_type'])) {
852                         $file .= str_replace(':', '-', $object_data['object_type']) . '-';
853                 }
854
855                 if (!empty($object_data['object_object_type'])) {
856                         $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
857                 }
858
859                 $tempfile = tempnam(System::getTempPath(), $file);
860                 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));
861                 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
862         }
863
864         /**
865          * Fetch a user id from an activity array
866          *
867          * @param array  $activity
868          * @param string $actor
869          *
870          * @return int   user id
871          */
872         public static function getBestUserForActivity(array $activity): int
873         {
874                 $uid = 0;
875                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
876
877                 $receivers = self::getReceivers($activity, $actor);
878                 foreach ($receivers as $receiver) {
879                         if ($receiver['type'] == self::TARGET_GLOBAL) {
880                                 return 0;
881                         }
882                         if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
883                                 $uid = $receiver['uid'];
884                         }
885                 }
886
887                 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
888                 if (empty($uid)) {
889                         $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
890                         if (!empty($contact['uid'])) {
891                                 $uid = $contact['uid'];
892                         }
893                 }
894
895                 return $uid;
896         }
897
898         // @TODO Missing documentation
899         public static function getReceiverURL(array $activity): array
900         {
901                 $urls = [];
902
903                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
904                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
905                         if (empty($receiver_list)) {
906                                 continue;
907                         }
908
909                         foreach ($receiver_list as $receiver) {
910                                 if ($receiver == self::PUBLIC_COLLECTION) {
911                                         $receiver = ActivityPub::PUBLIC_COLLECTION;
912                                 }
913                                 $urls[$element][] = $receiver;
914                         }
915                 }
916
917                 return $urls;
918         }
919
920         /**
921          * Fetch the receiver list from an activity array
922          *
923          * @param array   $activity
924          * @param string  $actor
925          * @param array   $tags
926          * @param boolean $fetch_unlisted
927          *
928          * @return array with receivers (user id)
929          * @throws \Exception
930          */
931         private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
932         {
933                 $reply = $receivers = $profile = [];
934
935                 // When it is an answer, we inherite the receivers from the parent
936                 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
937                 if (!empty($replyto)) {
938                         $reply = [$replyto];
939
940                         // Fix possibly wrong item URI (could be an answer to a plink uri)
941                         $fixedReplyTo = Item::getURIByLink($replyto);
942                         if (!empty($fixedReplyTo)) {
943                                 $reply[] = $fixedReplyTo;
944                         }
945                 }
946
947                 // Fetch all posts that refer to the object id
948                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
949                 if (!empty($object_id)) {
950                         $reply[] = $object_id;
951                 }
952
953                 if (!empty($reply)) {
954                         $parents = Post::select(['uid'], ['uri' => $reply]);
955                         while ($parent = Post::fetch($parents)) {
956                                 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
957                         }
958                         DBA::close($parents);
959                 }
960
961                 if (!empty($actor)) {
962                         $profile   = APContact::getByURL($actor);
963                         $followers = $profile['followers'] ?? '';
964                         $is_forum  = ($actor['type'] ?? '') == 'Group';
965                         Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
966                 } else {
967                         Logger::info('Empty actor', ['activity' => $activity]);
968                         $followers = '';
969                         $is_forum  = false;
970                 }
971
972                 // We have to prevent false follower assumptions upon thread completions
973                 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
974
975                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
976                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
977                         if (empty($receiver_list)) {
978                                 continue;
979                         }
980
981                         foreach ($receiver_list as $receiver) {
982                                 if ($receiver == self::PUBLIC_COLLECTION) {
983                                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
984                                 }
985
986                                 // Add receiver "-1" for unlisted posts
987                                 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
988                                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
989                                 }
990
991                                 // Fetch the receivers for the public and the followers collection
992                                 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
993                                         $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
994                                         continue;
995                                 }
996
997                                 // Fetching all directly addressed receivers
998                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
999                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1000                                 if (!DBA::isResult($contact)) {
1001                                         continue;
1002                                 }
1003
1004                                 // Check if the potential receiver is following the actor
1005                                 // Exception: The receiver is targetted via "to" or this is a comment
1006                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1007                                         $networks = Protocol::FEDERATED;
1008                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1009                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1010
1011                                         // Forum posts are only accepted from forum contacts
1012                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1013                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1014                                         }
1015
1016                                         if (!DBA::exists('contact', $condition)) {
1017                                                 continue;
1018                                         }
1019                                 }
1020
1021                                 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1022                                 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1023                                         switch ($element) {
1024                                                 case 'as:to':
1025                                                         $type = self::TARGET_TO;
1026                                                         break;
1027                                                 case 'as:cc':
1028                                                         $type = self::TARGET_CC;
1029                                                         break;
1030                                                 case 'as:bto':
1031                                                         $type = self::TARGET_BTO;
1032                                                         break;
1033                                                 case 'as:bcc':
1034                                                         $type = self::TARGET_BCC;
1035                                                         break;
1036                                         }
1037
1038                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1039                                 }
1040                         }
1041                 }
1042
1043                 self::switchContacts($receivers, $actor);
1044
1045                 return $receivers;
1046         }
1047
1048         /**
1049          * Fetch the receiver list of a given actor
1050          *
1051          * @param string  $actor
1052          * @param array   $tags
1053          * @param array   $receivers
1054          * @param integer $target_type
1055          * @param array   $profile
1056          *
1057          * @return array with receivers (user id)
1058          * @throws \Exception
1059          */
1060         private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1061         {
1062                 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1063                         'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1064
1065                 if (!empty($profile['uri-id'])) {
1066                         $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1067                         $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1068                         while ($contact = DBA::fetch($contacts)) {
1069                                 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1070                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1071                                 }
1072                         }
1073                         DBA::close($contacts);
1074                 } else {
1075                         // This part will only be called while post update 1426 wasn't finished
1076                         $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1077                         $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1078                         while ($contact = DBA::fetch($contacts)) {
1079                                 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1080                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1081                                 }
1082                         }
1083                         DBA::close($contacts);
1084
1085                         // The queries are split because of performance issues
1086                         $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1087                         $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1088                         while ($contact = DBA::fetch($contacts)) {
1089                                 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1090                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1091                                 }
1092                         }
1093                         DBA::close($contacts);
1094                 }
1095                 return $receivers;
1096         }
1097
1098         /**
1099          * Tests if the contact is a valid receiver for this actor
1100          *
1101          * @param array  $contact
1102          * @param array  $tags
1103          *
1104          * @return bool with receivers (user id)
1105          * @throws \Exception
1106          */
1107         private static function isValidReceiverForActor(array $contact, array $tags): bool
1108         {
1109                 // Are we following the contact? Then this is a valid receiver
1110                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1111                         return true;
1112                 }
1113
1114                 // When the possible receiver isn't a community, then it is no valid receiver
1115                 $owner = User::getOwnerDataById($contact['uid']);
1116                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1117                         return false;
1118                 }
1119
1120                 // Is the community account tagged?
1121                 foreach ($tags as $tag) {
1122                         if ($tag['type'] != 'Mention') {
1123                                 continue;
1124                         }
1125
1126                         if (Strings::compareLink($tag['href'], $owner['url'])) {
1127                                 return true;
1128                         }
1129                 }
1130
1131                 return false;
1132         }
1133
1134         /**
1135          * Switches existing contacts to ActivityPub
1136          *
1137          * @param integer $cid Contact ID
1138          * @param integer $uid User ID
1139          * @param string  $url Profile URL
1140          * @return void
1141          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1142          * @throws \ImagickException
1143          */
1144         public static function switchContact(int $cid, int $uid, string $url)
1145         {
1146                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1147                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1148                         return;
1149                 }
1150
1151                 if (Contact::updateFromProbe($cid)) {
1152                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1153                 }
1154
1155                 // Send a new follow request to be sure that the connection still exists
1156                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1157                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1158                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1159                 }
1160         }
1161
1162         /**
1163          * @TODO Fix documentation and type-hints
1164          *
1165          * @param $receivers
1166          * @param $actor
1167          * @return void
1168          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1169          * @throws \ImagickException
1170          */
1171         private static function switchContacts($receivers, $actor)
1172         {
1173                 if (empty($actor)) {
1174                         return;
1175                 }
1176
1177                 foreach ($receivers as $receiver) {
1178                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1179                         if (DBA::isResult($contact)) {
1180                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
1181                         }
1182
1183                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1184                         if (DBA::isResult($contact)) {
1185                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
1186                         }
1187                 }
1188         }
1189
1190         /**
1191          * @TODO Fix documentation and type-hints
1192          *
1193          * @param       $object_data
1194          * @param array $activity
1195          *
1196          * @return mixed
1197          */
1198         private static function addActivityFields($object_data, array $activity)
1199         {
1200                 if (!empty($activity['published']) && empty($object_data['published'])) {
1201                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1202                 }
1203
1204                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1205                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1206                 }
1207
1208                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1209                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1210
1211                 if (!empty($object_data['object_id'])) {
1212                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1213                         $objectId = Item::getURIByLink($object_data['object_id']);
1214                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1215                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1216                                 $object_data['object_id'] = $objectId;
1217                         }
1218                 }
1219
1220                 return $object_data;
1221         }
1222
1223         /**
1224          * Fetches the object data from external ressources if needed
1225          *
1226          * @param string  $object_id    Object ID of the the provided object
1227          * @param array   $object       The provided object array
1228          * @param boolean $trust_source Do we trust the provided object?
1229          * @param integer $uid          User ID for the signature that we use to fetch data
1230          *
1231          * @return array|false with trusted and valid object data
1232          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1233          * @throws \ImagickException
1234          */
1235         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1236         {
1237                 // By fetching the type we check if the object is complete.
1238                 $type = JsonLD::fetchElement($object, '@type');
1239
1240                 if (!$trust_source || empty($type)) {
1241                         $data = ActivityPub::fetchContent($object_id, $uid);
1242                         if (!empty($data)) {
1243                                 $object = JsonLD::compact($data);
1244                                 Logger::info('Fetched content for ' . $object_id);
1245                         } else {
1246                                 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1247
1248                                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1249                                 if (!DBA::isResult($item)) {
1250                                         Logger::info('Object with url ' . $object_id . ' was not found locally.');
1251                                         return false;
1252                                 }
1253                                 Logger::info('Using already stored item for url ' . $object_id);
1254                                 $data = ActivityPub\Transmitter::createNote($item);
1255                                 $object = JsonLD::compact($data);
1256                         }
1257
1258                         $id = JsonLD::fetchElement($object, '@id');
1259                         if (empty($id)) {
1260                                 Logger::info('Empty id');
1261                                 return false;
1262                         }
1263
1264                         if ($id != $object_id) {
1265                                 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1266                                 return false;
1267                         }
1268                 } else {
1269                         Logger::info('Using original object for url ' . $object_id);
1270                 }
1271
1272                 $type = JsonLD::fetchElement($object, '@type');
1273                 if (empty($type)) {
1274                         Logger::info('Empty type');
1275                         return false;
1276                 }
1277
1278                 // Lemmy is resharing "create" activities instead of content
1279                 // We fetch the content from the activity.
1280                 if (in_array($type, ['as:Create'])) {
1281                         $object = $object['as:object'];
1282                         $type = JsonLD::fetchElement($object, '@type');
1283                         if (empty($type)) {
1284                                 Logger::info('Empty type');
1285                                 return false;
1286                         }
1287                         $object_data = self::processObject($object);
1288                 }
1289
1290                 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1291                 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1292                         $object_data = self::processObject($object);
1293
1294                         if (!empty($data)) {
1295                                 $object_data['raw'] = json_encode($data);
1296                         }
1297                         return $object_data;
1298                 }
1299
1300                 if ($type == 'as:Announce') {
1301                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
1302                         if (empty($object_id) || !is_string($object_id)) {
1303                                 return false;
1304                         }
1305                         return self::fetchObject($object_id, [], false, $uid);
1306                 }
1307
1308                 Logger::info('Unhandled object type: ' . $type);
1309                 return false;
1310         }
1311
1312         /**
1313          * Converts the language element (Used by Peertube)
1314          *
1315          * @param array $languages
1316          * @return array Languages
1317          */
1318         public static function processLanguages(array $languages): array
1319         {
1320                 if (empty($languages)) {
1321                         return [];
1322                 }
1323
1324                 $language_list = [];
1325
1326                 foreach ($languages as $language) {
1327                         if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1328                                 $language_list[$language['_:identifier']] = $language['as:name'];
1329                         }
1330                 }
1331                 return $language_list;
1332         }
1333
1334         /**
1335          * Convert tags from JSON-LD format into a simplified format
1336          *
1337          * @param array $tags Tags in JSON-LD format
1338          *
1339          * @return array with tags in a simplified format
1340          */
1341         public static function processTags(array $tags): array
1342         {
1343                 $taglist = [];
1344
1345                 foreach ($tags as $tag) {
1346                         if (empty($tag)) {
1347                                 continue;
1348                         }
1349
1350                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1351                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1352                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1353
1354                         if (empty($element['type'])) {
1355                                 continue;
1356                         }
1357
1358                         if (empty($element['href'])) {
1359                                 $element['href'] = $element['name'];
1360                         }
1361
1362                         $taglist[] = $element;
1363                 }
1364                 return $taglist;
1365         }
1366
1367         /**
1368          * Convert emojis from JSON-LD format into a simplified format
1369          *
1370          * @param array $emojis
1371          * @return array with emojis in a simplified format
1372          */
1373         private static function processEmojis(array $emojis): array
1374         {
1375                 $emojilist = [];
1376
1377                 foreach ($emojis as $emoji) {
1378                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1379                                 continue;
1380                         }
1381
1382                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1383                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1384                                 'href' => $url];
1385
1386                         $emojilist[] = $element;
1387                 }
1388
1389                 return $emojilist;
1390         }
1391
1392         /**
1393          * Convert attachments from JSON-LD format into a simplified format
1394          *
1395          * @param array $attachments Attachments in JSON-LD format
1396          *
1397          * @return array Attachments in a simplified format
1398          */
1399         private static function processAttachments(array $attachments): array
1400         {
1401                 $attachlist = [];
1402
1403                 // Removes empty values
1404                 $attachments = array_filter($attachments);
1405
1406                 foreach ($attachments as $attachment) {
1407                         switch (JsonLD::fetchElement($attachment, '@type')) {
1408                                 case 'as:Page':
1409                                         $pageUrl = null;
1410                                         $pageImage = null;
1411
1412                                         $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1413                                         foreach ($urls as $url) {
1414                                                 // Single scalar URL case
1415                                                 if (is_string($url)) {
1416                                                         $pageUrl = $url;
1417                                                         continue;
1418                                                 }
1419
1420                                                 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1421                                                 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1422                                                 if (Strings::startsWith($mediaType, 'image')) {
1423                                                         $pageImage = $href;
1424                                                 } else {
1425                                                         $pageUrl = $href;
1426                                                 }
1427                                         }
1428
1429                                         $attachlist[] = [
1430                                                 'type'  => 'link',
1431                                                 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1432                                                 'desc'  => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1433                                                 'url'   => $pageUrl,
1434                                                 'image' => $pageImage,
1435                                         ];
1436                                         break;
1437                                 case 'as:Image':
1438                                         $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1439                                         $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1440                                         $imagePreviewUrl = null;
1441                                         // Multiple URLs?
1442                                         if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1443                                                 $imageVariants = [];
1444                                                 $previewVariants = [];
1445                                                 foreach ($urls as $url) {
1446                                                         // Scalar URL, no discrimination possible
1447                                                         if (is_string($url)) {
1448                                                                 $imageFullUrl = $url;
1449                                                                 continue;
1450                                                         }
1451
1452                                                         // Not sure what to do with a different Link media type than the base Image, we skip
1453                                                         if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1454                                                                 continue;
1455                                                         }
1456
1457                                                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1458
1459                                                         // Default URL choice if no discriminating width is provided
1460                                                         $imageFullUrl = $href ?? $imageFullUrl;
1461
1462                                                         $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1463
1464                                                         if ($href && $width) {
1465                                                                 $imageVariants[$width] = $href;
1466                                                                 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1467                                                                 $previewVariants[abs(632 - $width)] = $href;
1468                                                         }
1469                                                 }
1470
1471                                                 if ($imageVariants) {
1472                                                         // Taking the maximum size image
1473                                                         ksort($imageVariants);
1474                                                         $imageFullUrl = array_pop($imageVariants);
1475
1476                                                         // Taking the minimum number distance to the target distance
1477                                                         ksort($previewVariants);
1478                                                         $imagePreviewUrl = array_shift($previewVariants);
1479                                                 }
1480
1481                                                 unset($imageVariants);
1482                                                 unset($previewVariants);
1483                                         }
1484
1485                                         $attachlist[] = [
1486                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1487                                                 'mediaType' => $mediaType,
1488                                                 'name'  => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1489                                                 'url'   => $imageFullUrl,
1490                                                 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1491                                         ];
1492                                         break;
1493                                 default:
1494                                         $attachlist[] = [
1495                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1496                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1497                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1498                                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1499                                                 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1500                                                 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1501                                                 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1502                                         ];
1503                         }
1504                 }
1505
1506                 return $attachlist;
1507         }
1508
1509         /**
1510          * Convert questions from JSON-LD format into a simplified format
1511          *
1512          * @param array $object
1513          *
1514          * @return array Questions in a simplified format
1515          */
1516         private static function processQuestion(array $object): array
1517         {
1518                 $question = [];
1519
1520                 if (!empty($object['as:oneOf'])) {
1521                         $question['multiple'] = false;
1522                         $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1523                 } elseif (!empty($object['as:anyOf'])) {
1524                         $question['multiple'] = true;
1525                         $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1526                 } else {
1527                         return [];
1528                 }
1529
1530                 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1531                 if (!empty($closed)) {
1532                         $question['end-time'] = $closed;
1533                 } else {
1534                         $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1535                 }
1536
1537                 $question['voters']  = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1538                 $question['options'] = [];
1539
1540                 $voters = 0;
1541
1542                 foreach ($options as $option) {
1543                         if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1544                                 continue;
1545                         }
1546
1547                         $name = JsonLD::fetchElement($option, 'as:name', '@value');
1548
1549                         if (empty($option['as:replies'])) {
1550                                 continue;
1551                         }
1552
1553                         $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1554
1555                         $question['options'][] = ['name' => $name, 'replies' => $replies];
1556
1557                         $voters += (int)$replies;
1558                 }
1559
1560                 // For single choice question we can count the number of voters if not provided (like with Misskey)
1561                 if (empty($question['voters']) && !$question['multiple']) {
1562                         $question['voters'] = $voters;
1563                 }
1564
1565                 return $question;
1566         }
1567
1568         /**
1569          * Fetch the original source or content with the "language" Markdown or HTML
1570          *
1571          * @param array $object
1572          * @param array $object_data
1573          *
1574          * @return array Object data (?)
1575          * @throws \Exception
1576          */
1577         private static function getSource(array $object, array $object_data): array
1578         {
1579                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1580                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1581                 if (!empty($object_data['source'])) {
1582                         return $object_data;
1583                 }
1584
1585                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1586                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1587                 if (!empty($object_data['source'])) {
1588                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
1589                         return $object_data;
1590                 }
1591
1592                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1593                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1594                 if (!empty($object_data['source'])) {
1595                         $object_data['source'] = HTML::toBBCode($object_data['source']);
1596                         return $object_data;
1597                 }
1598
1599                 return $object_data;
1600         }
1601
1602         /**
1603          * Extracts a potential alternate URL from a list of additional URL elements
1604          *
1605          * @param array $urls
1606          * @return string
1607          */
1608         private static function extractAlternateUrl(array $urls): string
1609         {
1610                 $alternateUrl = '';
1611                 foreach ($urls as $key => $url) {
1612                         // Not a list but a single URL element
1613                         if (!is_numeric($key)) {
1614                                 continue;
1615                         }
1616
1617                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1618                                 continue;
1619                         }
1620
1621                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1622                         if (empty($href)) {
1623                                 continue;
1624                         }
1625
1626                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1627                         if (empty($mediatype)) {
1628                                 continue;
1629                         }
1630
1631                         if ($mediatype == 'text/html') {
1632                                 $alternateUrl = $href;
1633                         }
1634                 }
1635
1636                 return $alternateUrl;
1637         }
1638
1639         /**
1640          * Check if the "as:url" element is an array with multiple links
1641          * This is the case with audio and video posts.
1642          * Then the links are added as attachments
1643          *
1644          * @param array $urls The object URL list
1645          * @return array an array of attachments
1646          */
1647         private static function processAttachmentUrls(array $urls): array
1648         {
1649                 $attachments = [];
1650                 foreach ($urls as $key => $url) {
1651                         // Not a list but a single URL element
1652                         if (!is_numeric($key)) {
1653                                 continue;
1654                         }
1655
1656                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1657                                 continue;
1658                         }
1659
1660                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1661                         if (empty($href)) {
1662                                 continue;
1663                         }
1664
1665                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1666                         if (empty($mediatype)) {
1667                                 continue;
1668                         }
1669
1670                         $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1671
1672                         if ($filetype == 'audio') {
1673                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1674                         } elseif ($filetype == 'video') {
1675                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1676                                 // PeerTube audio-only track
1677                                 if ($height === 0) {
1678                                         continue;
1679                                 }
1680
1681                                 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1682                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1683                         } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1684                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1685
1686                                 // For Torrent links we always store the highest resolution
1687                                 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1688                                         continue;
1689                                 }
1690
1691                                 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1692                         } elseif ($mediatype == 'application/x-mpegURL') {
1693                                 // PeerTube exception, actual video link is in the tags of this URL element
1694                                 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1695                         }
1696                 }
1697
1698                 return array_values($attachments);
1699         }
1700
1701         /**
1702          * Fetches data from the object part of an activity
1703          *
1704          * @param array $object
1705          *
1706          * @return array|bool Object data or FALSE if $object does not contain @id element
1707          * @throws \Exception
1708          */
1709         private static function processObject(array $object)
1710         {
1711                 if (!JsonLD::fetchElement($object, '@id')) {
1712                         return false;
1713                 }
1714
1715                 $object_data = [];
1716                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1717                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1718                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1719
1720                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1721                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1722                         $object_data['reply-to-id'] = $object_data['id'];
1723
1724                         // On activities the "reply to" is the id of the object it refers to
1725                         if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1726                                 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1727                                 if (!empty($object_id)) {
1728                                         $object_data['reply-to-id'] = $object_id;
1729                                 }
1730                         }
1731                 } else {
1732                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1733                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1734                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1735                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1736                                 $object_data['reply-to-id'] = $replyToId;
1737                         }
1738                 }
1739
1740                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1741                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1742
1743                 if (empty($object_data['updated'])) {
1744                         $object_data['updated'] = $object_data['published'];
1745                 }
1746
1747                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1748                         $object_data['published'] = $object_data['updated'];
1749                 }
1750
1751                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1752                 if (empty($actor)) {
1753                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1754                 }
1755
1756                 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1757                 $location = JsonLD::fetchElement($location, 'location', '@value');
1758                 if ($location) {
1759                         // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1760                         // down to HTML and then finally format to plaintext.
1761                         $location = Markdown::convert($location);
1762                         $location = BBCode::toPlaintext($location);
1763                 }
1764
1765                 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1766                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1767                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1768                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1769                 $object_data['actor'] = $object_data['author'] = $actor;
1770                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1771                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1772                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1773                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1774                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1775                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1776                 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1777                 $object_data = self::getSource($object, $object_data);
1778                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1779                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1780                 $object_data['location'] = $location;
1781                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1782                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1783                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1784                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1785                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1786                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1787                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1788                 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1789                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1790                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1791                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1792
1793                 // Special treatment for Hubzilla links
1794                 if (is_array($object_data['alternate-url'])) {
1795                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1796
1797                         if (!is_string($object_data['alternate-url'])) {
1798                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1799                         }
1800                 }
1801
1802                 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1803                         $object_data['alternate-url'] = null;
1804                 }
1805
1806                 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1807                         $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1808                         $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1809                 }
1810
1811                 // For page types we expect that the alternate url posts to some page.
1812                 // So we add this to the attachments if it differs from the id.
1813                 // Currently only Lemmy is using the page type.
1814                 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1815                         $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1816                         $object_data['alternate-url'] = null;
1817                 }
1818
1819                 if ($object_data['object_type'] == 'as:Question') {
1820                         $object_data['question'] = self::processQuestion($object);
1821                 }
1822
1823                 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1824                 $receivers = $reception_types = [];
1825                 foreach ($receiverdata as $key => $data) {
1826                         $receivers[$key] = $data['uid'];
1827                         $reception_types[$data['uid']] = $data['type'] ?? 0;
1828                 }
1829
1830                 $object_data['receiver_urls']  = self::getReceiverURL($object);
1831                 $object_data['receiver']       = $receivers;
1832                 $object_data['reception_type'] = $reception_types;
1833
1834                 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1835                 unset($object_data['receiver'][-1]);
1836                 unset($object_data['reception_type'][-1]);
1837
1838                 // Common object data:
1839
1840                 // Unhandled
1841                 // @context, type, actor, signature, mediaType, duration, replies, icon
1842
1843                 // Also missing: (Defined in the standard, but currently unused)
1844                 // audience, preview, endTime, startTime, image
1845
1846                 // Data in Notes:
1847
1848                 // Unhandled
1849                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1850                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1851
1852                 // Data in video:
1853
1854                 // To-Do?
1855                 // category, licence, language, commentsEnabled
1856
1857                 // Unhandled
1858                 // views, waitTranscoding, state, support, subtitleLanguage
1859                 // likes, dislikes, shares, comments
1860
1861                 return $object_data;
1862         }
1863 }