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