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