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