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