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