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