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