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