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