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