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