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