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