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