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