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