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