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