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