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