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