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