]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Merge branch 'develop' of github.com:annando/friendica into develop
[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\Model\Contact;
31 use Friendica\Model\APContact;
32 use Friendica\Model\Item;
33 use Friendica\Model\Post;
34 use Friendica\Model\User;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Util\HTTPSignature;
38 use Friendica\Util\JsonLD;
39 use Friendica\Util\LDSignature;
40 use Friendica\Util\Strings;
41
42 /**
43  * ActivityPub Receiver Protocol class
44  *
45  * To-Do:
46  * @todo Undo Announce
47  *
48  * Check what this is meant to do:
49  * - Add
50  * - Block
51  * - Flag
52  * - Remove
53  * - Undo Block
54  */
55 class Receiver
56 {
57         const PUBLIC_COLLECTION = 'as:Public';
58         const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
59         const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
60         const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
61
62         const TARGET_UNKNOWN = 0;
63         const TARGET_TO = 1;
64         const TARGET_CC = 2;
65         const TARGET_BTO = 3;
66         const TARGET_BCC = 4;
67         const TARGET_FOLLOWER = 5;
68         const TARGET_ANSWER = 6;
69         const TARGET_GLOBAL = 7;
70
71         const COMPLETION_NONE    = 0;
72         const COMPLETION_ANNOUCE = 1;
73         const COMPLETION_RELAY   = 2;
74         const COMPLETION_MANUAL  = 3;
75         const COMPLETION_AUTO    = 4;
76
77         /**
78          * Checks incoming message from the inbox
79          *
80          * @param         $body
81          * @param         $header
82          * @param integer $uid User ID
83          * @throws \Exception
84          */
85         public static function processInbox($body, $header, $uid)
86         {
87                 $activity = json_decode($body, true);
88                 if (empty($activity)) {
89                         Logger::warning('Invalid body.');
90                         return;
91                 }
92
93                 $ldactivity = JsonLD::compact($activity);
94
95                 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
96
97                 $apcontact = APContact::getByURL($actor);
98                 if (empty($apcontact)) {
99                         Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
100                         return;
101                 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
102                         self::processRelayPost($ldactivity, $actor);
103                         return;
104                 } else {
105                         APContact::unmarkForArchival($apcontact);
106                 }
107
108                 $http_signer = HTTPSignature::getSigner($body, $header);
109                 if ($http_signer === false) {
110                         Logger::warning('Invalid HTTP signature, message will be discarded.');
111                         return;
112                 } elseif (empty($http_signer)) {
113                         Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
114                         return;
115                 } else {
116                         Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
117                 }
118
119                 $signer = [$http_signer];
120
121                 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
122
123                 if (LDSignature::isSigned($activity)) {
124                         $ld_signer = LDSignature::getSigner($activity);
125                         if (empty($ld_signer)) {
126                                 Logger::info('Invalid JSON-LD signature from ' . $actor);
127                         } elseif ($ld_signer != $http_signer) {
128                                 $signer[] = $ld_signer;
129                         }
130                         if (!empty($ld_signer && ($actor == $http_signer))) {
131                                 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
132                                 $trust_source = true;
133                         } elseif (!empty($ld_signer)) {
134                                 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
135                                 $trust_source = true;
136                         } elseif ($actor == $http_signer) {
137                                 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
138                                 $trust_source = true;
139                         } else {
140                                 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
141                                 $trust_source = false;
142                         }
143                 } elseif ($actor == $http_signer) {
144                         Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
145                         $trust_source = true;
146                 } else {
147                         Logger::info('No JSON-LD signature, different actor.');
148                         $trust_source = false;
149                 }
150
151                 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
152         }
153
154         /**
155          * Process incoming posts from relays
156          *
157          * @param array  $activity
158          * @param string $actor
159          * @return void
160          */
161         private static function processRelayPost(array $activity, string $actor)
162         {
163                 $type = JsonLD::fetchElement($activity, '@type');
164                 if (!$type) {
165                         Logger::info('Empty type', ['activity' => $activity]);
166                         return;
167                 }
168
169                 if ($type != 'as:Announce') {
170                         Logger::info('Not an announcement', ['activity' => $activity]);
171                         return;
172                 }
173
174                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
175                 if (empty($object_id)) {
176                         Logger::info('No object id found', ['activity' => $activity]);
177                         return;
178                 }
179
180                 $contact = Contact::getByURL($actor);
181                 if (empty($contact)) {
182                         Logger::info('Relay contact not found', ['actor' => $actor]);
183                         return;
184                 }
185
186                 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
187                         Logger::notice('Relay is no sharer', ['actor' => $actor]);
188                         return;
189                 }
190
191                 Logger::info('Got relayed message id', ['id' => $object_id]);
192
193                 $item_id = Item::searchByLink($object_id);
194                 if ($item_id) {
195                         Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
196                         return;
197                 }
198
199                 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
200                 if (empty($id)) {
201                         Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
202                         return;
203                 }
204
205                 $item_id = Item::searchByLink($object_id);
206                 if ($item_id) {
207                         Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
208                 } else {
209                         Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
210                 }
211         }
212
213         /**
214          * Fetches the object type for a given object id
215          *
216          * @param array   $activity
217          * @param string  $object_id Object ID of the the provided object
218          * @param integer $uid       User ID
219          *
220          * @return string with object type
221          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
222          * @throws \ImagickException
223          */
224         private static function fetchObjectType($activity, $object_id, $uid = 0)
225         {
226                 if (!empty($activity['as:object'])) {
227                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
228                         if (!empty($object_type)) {
229                                 return $object_type;
230                         }
231                 }
232
233                 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
234                         // We just assume "note" since it doesn't make a difference for the further processing
235                         return 'as:Note';
236                 }
237
238                 $profile = APContact::getByURL($object_id);
239                 if (!empty($profile['type'])) {
240                         APContact::unmarkForArchival($profile);
241                         return 'as:' . $profile['type'];
242                 }
243
244                 $data = ActivityPub::fetchContent($object_id, $uid);
245                 if (!empty($data)) {
246                         $object = JsonLD::compact($data);
247                         $type = JsonLD::fetchElement($object, '@type');
248                         if (!empty($type)) {
249                                 return $type;
250                         }
251                 }
252
253                 return null;
254         }
255
256         /**
257          * Prepare the object array
258          *
259          * @param array   $activity     Array with activity data
260          * @param integer $uid          User ID
261          * @param boolean $push         Message had been pushed to our system
262          * @param boolean $trust_source Do we trust the source?
263          *
264          * @return array with object data
265          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266          * @throws \ImagickException
267          */
268         public static function prepareObjectData($activity, $uid, $push, &$trust_source)
269         {
270                 $id = JsonLD::fetchElement($activity, '@id');
271                 if (!empty($id) && !$trust_source) {
272                         $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
273
274                         $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
275                         if (!empty($fetched_activity)) {
276                                 $object = JsonLD::compact($fetched_activity);
277                                 $fetched_id = JsonLD::fetchElement($object, '@id');
278                                 if ($fetched_id == $id) {
279                                         Logger::info('Activity had been fetched successfully', ['id' => $id]);
280                                         $trust_source = true;
281                                         $activity = $object;
282                                 } else {
283                                         Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
284                                 }
285                         } else {
286                                 Logger::info('Activity could not been fetched', ['id' => $id]);
287                         }
288                 }
289
290                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
291                 if (empty($actor)) {
292                         Logger::info('Empty actor', ['activity' => $activity]);
293                         return [];
294                 }
295
296                 $type = JsonLD::fetchElement($activity, '@type');
297
298                 // Fetch all receivers from to, cc, bto and bcc
299                 $receiverdata = self::getReceivers($activity, $actor);
300                 $receivers = $reception_types = [];
301                 foreach ($receiverdata as $key => $data) {
302                         $receivers[$key] = $data['uid'];
303                         $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
304                 }
305
306                 $urls = self::getReceiverURL($activity);
307
308                 // When it is a delivery to a personal inbox we add that user to the receivers
309                 if (!empty($uid)) {
310                         $additional = [$uid => $uid];
311                         $receivers = array_replace($receivers, $additional);
312                         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]))) {
313                                 $reception_types[$uid] = self::TARGET_BCC;
314                                 $owner = User::getOwnerDataById($uid);
315                                 if (!empty($owner['url'])) {
316                                         $urls['as:bcc'][] = $owner['url'];
317                                 }
318                         }
319                 }
320
321                 // We possibly need some user to fetch private content,
322                 // so we fetch one out of the receivers if no uid is provided.
323                 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
324
325                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
326                 if (empty($object_id)) {
327                         Logger::info('No object found');
328                         return [];
329                 }
330
331                 if (!is_string($object_id)) {
332                         Logger::info('Invalid object id', ['object' => $object_id]);
333                         return [];
334                 }
335
336                 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
337
338                 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
339                 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
340                         $data = ActivityPub::fetchContent($object_id, $fetch_uid);
341                         if (!empty($data)) {
342                                 $type = $object_type;
343                                 $activity = JsonLD::compact($data);
344
345                                 // Some variables need to be refetched since the activity changed
346                                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
347                                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
348                                 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
349                         }
350                 }
351
352                 // Any activities on account types must not be altered
353                 if (in_array($object_type, self::ACCOUNT_TYPES)) {
354                         $object_data = [];
355                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
356                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
357                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
358                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
359                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
360                         $object_data['push'] = $push;
361                 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce']) || strpos($type, '#emojiReaction')) {
362                 // Fetch the content only on activities where this matters
363                 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
364                         // Always fetch on "Announce"
365                         $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
366                         if (empty($object_data)) {
367                                 Logger::info("Object data couldn't be processed");
368                                 return [];
369                         }
370
371                         $object_data['object_id'] = $object_id;
372
373                         if ($type == 'as:Announce') {
374                                 $object_data['push'] = false;
375                         } else {
376                                 $object_data['push'] = $push;
377                         }
378
379                         // Test if it is an answer to a mail
380                         if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
381                                 $object_data['directmessage'] = true;
382                         } else {
383                                 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
384                         }
385                 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
386                         // Create a mostly empty array out of the activity data (instead of the object).
387                         // This way we later don't have to check for the existence of each individual array element.
388                         $object_data = self::processObject($activity);
389                         $object_data['name'] = $type;
390                         $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
391                         $object_data['object_id'] = $object_id;
392                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
393                         $object_data['push'] = $push;
394                 } elseif (in_array($type, ['as:Add'])) {
395                         $object_data = [];
396                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
397                         $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
398                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
399                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
400                         $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
401                         $object_data['push'] = $push;
402                 } else {
403                         $object_data = [];
404                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
405                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
406                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
407                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
408                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
409                         $object_data['push'] = $push;
410
411                         // An Undo is done on the object of an object, so we need that type as well
412                         if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
413                                 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
414                         }
415                 }
416
417                 $object_data = self::addActivityFields($object_data, $activity);
418
419                 if (empty($object_data['object_type'])) {
420                         $object_data['object_type'] = $object_type;
421                 }
422
423                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
424                         if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
425                                 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
426                         }
427                 }
428
429                 $object_data['type'] = $type;
430                 $object_data['actor'] = $actor;
431                 $object_data['item_receiver'] = $receivers;
432                 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
433                 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
434
435                 $author = $object_data['author'] ?? $actor;
436                 if (!empty($author) && !empty($object_data['id'])) {
437                         $author_host = parse_url($author, PHP_URL_HOST);
438                         $id_host = parse_url($object_data['id'], PHP_URL_HOST);
439                         if ($author_host == $id_host) {
440                                 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
441                         } else {
442                                 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
443                                 $trust_source = false;
444                         }
445                 }
446
447                 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
448
449                 return $object_data;
450         }
451
452         /**
453          * Fetches the first user id from the receiver array
454          *
455          * @param array $receivers Array with receivers
456          * @return integer user id;
457          */
458         public static function getFirstUserFromReceivers($receivers)
459         {
460                 foreach ($receivers as $receiver) {
461                         if (!empty($receiver)) {
462                                 return $receiver;
463                         }
464                 }
465                 return 0;
466         }
467
468         /**
469          * Processes the activity object
470          *
471          * @param array   $activity     Array with activity data
472          * @param string  $body
473          * @param integer $uid          User ID
474          * @param boolean $trust_source Do we trust the source?
475          * @param boolean $push         Message had been pushed to our system
476          * @throws \Exception
477          */
478         public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
479         {
480                 $type = JsonLD::fetchElement($activity, '@type');
481                 if (!$type) {
482                         Logger::info('Empty type', ['activity' => $activity]);
483                         return;
484                 }
485
486                 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
487                         Logger::info('Empty object', ['activity' => $activity]);
488                         return;
489                 }
490
491                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
492                 if (empty($actor)) {
493                         Logger::info('Empty actor', ['activity' => $activity]);
494                         return;
495                 }
496
497                 if (is_array($activity['as:object'])) {
498                         $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
499                 } else {
500                         $attributed_to = '';
501                 }
502
503                 // Test the provided signatures against the actor and "attributedTo"
504                 if ($trust_source) {
505                         if (!empty($attributed_to) && !empty($actor)) {
506                                 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
507                         } else {
508                                 $trust_source = in_array($actor, $signer);
509                         }
510                 }
511
512                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
513                 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
514                 if (empty($object_data)) {
515                         Logger::info('No object data found', ['activity' => $activity]);
516                         return;
517                 }
518
519                 // Lemmy is announcing activities.
520                 // We are changing the announces into regular activities.
521                 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
522                         $type = $object_data['type'];
523                 }
524
525                 if (!$trust_source) {
526                         Logger::info('Activity trust could not be achieved.',  ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
527                         return;
528                 }
529
530                 if (!empty($body) && empty($object_data['raw'])) {
531                         $object_data['raw'] = $body;
532                 }
533
534                 // Internal flag for thread completion. See Processor.php
535                 if (!empty($activity['thread-completion'])) {
536                         $object_data['thread-completion'] = $activity['thread-completion'];
537                 }
538
539                 if (!empty($activity['completion-mode'])) {
540                         $object_data['completion-mode'] = $activity['completion-mode'];
541                 }
542
543                 if (!empty($activity['thread-children-type'])) {
544                         $object_data['thread-children-type'] = $activity['thread-children-type'];
545                 }
546
547                 // Internal flag for posts that arrived via relay
548                 if (!empty($activity['from-relay'])) {
549                         $object_data['from-relay'] = $activity['from-relay'];
550                 }
551
552                 switch ($type) {
553                         case 'as:Create':
554                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
555                                         $item = ActivityPub\Processor::createItem($object_data);
556                                         ActivityPub\Processor::postItem($object_data, $item);
557                                 }
558                                 break;
559
560                         case 'as:Add':
561                                 if ($object_data['object_type'] == 'as:tag') {
562                                         ActivityPub\Processor::addTag($object_data);
563                                 }
564                                 break;
565
566                         case 'as:Announce':
567                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
568                                         $object_data['thread-completion'] = Contact::getIdForURL($actor);
569                                         $object_data['completion-mode']   = self::COMPLETION_ANNOUCE;
570
571                                         $item = ActivityPub\Processor::createItem($object_data);
572                                         if (empty($item)) {
573                                                 return;
574                                         }
575
576                                         $item['post-reason'] = Item::PR_ANNOUNCEMENT;
577                                         ActivityPub\Processor::postItem($object_data, $item);
578
579                                         $announce_object_data = self::processObject($activity);
580                                         $announce_object_data['name'] = $type;
581                                         $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
582                                         $announce_object_data['object_id'] = $object_data['object_id'];
583                                         $announce_object_data['object_type'] = $object_data['object_type'];
584                                         $announce_object_data['push'] = $push;
585
586                                         if (!empty($body)) {
587                                                 $announce_object_data['raw'] = $body;
588                                         }
589
590                                         ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
591                                 }
592                                 break;
593
594                         case 'as:Like':
595                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
596                                         ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
597                                 }
598                                 break;
599
600                         case 'as:Dislike':
601                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
602                                         ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
603                                 }
604                                 break;
605
606                         case 'as:TentativeAccept':
607                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
608                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
609                                 }
610                                 break;
611
612                         case 'as:Update':
613                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
614                                         ActivityPub\Processor::updateItem($object_data);
615                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
616                                         ActivityPub\Processor::updatePerson($object_data);
617                                 }
618                                 break;
619
620                         case 'as:Delete':
621                                 if ($object_data['object_type'] == 'as:Tombstone') {
622                                         ActivityPub\Processor::deleteItem($object_data);
623                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
624                                         ActivityPub\Processor::deletePerson($object_data);
625                                 }
626                                 break;
627
628                         case 'as:Follow':
629                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
630                                         ActivityPub\Processor::followUser($object_data);
631                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
632                                         $object_data['reply-to-id'] = $object_data['object_id'];
633                                         ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
634                                 }
635                                 break;
636
637                         case 'as:Accept':
638                                 if ($object_data['object_type'] == 'as:Follow') {
639                                         ActivityPub\Processor::acceptFollowUser($object_data);
640                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
641                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
642                                 }
643                                 break;
644
645                         case 'as:Reject':
646                                 if ($object_data['object_type'] == 'as:Follow') {
647                                         ActivityPub\Processor::rejectFollowUser($object_data);
648                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
649                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
650                                 }
651                                 break;
652
653                         case 'as:Undo':
654                                 if (($object_data['object_type'] == 'as:Follow') &&
655                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
656                                         ActivityPub\Processor::undoFollowUser($object_data);
657                                 } elseif (($object_data['object_type'] == 'as:Accept') &&
658                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
659                                         ActivityPub\Processor::rejectFollowUser($object_data);
660                                 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
661                                         in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
662                                         ActivityPub\Processor::undoActivity($object_data);
663                                 }
664                                 break;
665
666                         default:
667                                 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
668                                 break;
669                 }
670         }
671
672         /**
673          * Fetch a user id from an activity array
674          *
675          * @param array  $activity
676          * @param string $actor
677          *
678          * @return int   user id
679          */
680         public static function getBestUserForActivity(array $activity)
681         {
682                 $uid = 0;
683                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
684
685                 $receivers = self::getReceivers($activity, $actor);
686                 foreach ($receivers as $receiver) {
687                         if ($receiver['type'] == self::TARGET_GLOBAL) {
688                                 return 0;
689                         }
690                         if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
691                                 $uid = $receiver['uid'];
692                         }
693                 }
694
695                 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
696                 if (empty($uid)) {
697                         $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
698                         if (!empty($contact['uid'])) {
699                                 $uid = $contact['uid'];
700                         }
701                 }
702
703                 return $uid;
704         }
705
706         public static function getReceiverURL($activity)
707         {
708                 $urls = [];
709
710                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
711                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
712                         if (empty($receiver_list)) {
713                                 continue;
714                         }
715
716                         foreach ($receiver_list as $receiver) {
717                                 if ($receiver == self::PUBLIC_COLLECTION) {
718                                         $receiver = ActivityPub::PUBLIC_COLLECTION;
719                                 }
720                                 $urls[$element][] = $receiver;
721                         }
722                 }
723
724                 return $urls;
725         }
726
727         /**
728          * Fetch the receiver list from an activity array
729          *
730          * @param array   $activity
731          * @param string  $actor
732          * @param array   $tags
733          * @param boolean $fetch_unlisted
734          *
735          * @return array with receivers (user id)
736          * @throws \Exception
737          */
738         private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
739         {
740                 $reply = $receivers = [];
741
742                 // When it is an answer, we inherite the receivers from the parent
743                 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
744                 if (!empty($replyto)) {
745                         $reply = [$replyto];
746
747                         // Fix possibly wrong item URI (could be an answer to a plink uri)
748                         $fixedReplyTo = Item::getURIByLink($replyto);
749                         if (!empty($fixedReplyTo)) {
750                                 $reply[] = $fixedReplyTo;
751                         }
752                 }
753
754                 // Fetch all posts that refer to the object id
755                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
756                 if (!empty($object_id)) {
757                         $reply[] = $object_id;
758                 }
759
760                 if (!empty($reply)) {
761                         $parents = Post::select(['uid'], ['uri' => $reply]);
762                         while ($parent = Post::fetch($parents)) {
763                                 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
764                         }
765                         DBA::close($parents);
766                 }
767
768                 if (!empty($actor)) {
769                         $profile   = APContact::getByURL($actor);
770                         $followers = $profile['followers'] ?? '';
771                         $is_forum  = ($actor['type'] ?? '') == 'Group';
772                         Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
773                 } else {
774                         Logger::info('Empty actor', ['activity' => $activity]);
775                         $followers = '';
776                         $is_forum  = false;
777                 }
778
779                 // We have to prevent false follower assumptions upon thread completions
780                 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
781
782                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
783                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
784                         if (empty($receiver_list)) {
785                                 continue;
786                         }
787
788                         foreach ($receiver_list as $receiver) {
789                                 if ($receiver == self::PUBLIC_COLLECTION) {
790                                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
791                                 }
792
793                                 // Add receiver "-1" for unlisted posts
794                                 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
795                                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
796                                 }
797
798                                 // Fetch the receivers for the public and the followers collection
799                                 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
800                                         $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
801                                         continue;
802                                 }
803
804                                 // Fetching all directly addressed receivers
805                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
806                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
807                                 if (!DBA::isResult($contact)) {
808                                         continue;
809                                 }
810
811                                 // Check if the potential receiver is following the actor
812                                 // Exception: The receiver is targetted via "to" or this is a comment
813                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
814                                         $networks = Protocol::FEDERATED;
815                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
816                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
817
818                                         // Forum posts are only accepted from forum contacts
819                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
820                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
821                                         }
822
823                                         if (!DBA::exists('contact', $condition)) {
824                                                 continue;
825                                         }
826                                 }
827
828                                 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
829                                 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
830                                         switch ($element) {
831                                                 case 'as:to':
832                                                         $type = self::TARGET_TO;
833                                                         break;
834                                                 case 'as:cc':
835                                                         $type = self::TARGET_CC;
836                                                         break;
837                                                 case 'as:bto':
838                                                         $type = self::TARGET_BTO;
839                                                         break;
840                                                 case 'as:bcc':
841                                                         $type = self::TARGET_BCC;
842                                                         break;
843                                         }
844
845                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
846                                 }
847                         }
848                 }
849
850                 self::switchContacts($receivers, $actor);
851
852                 return $receivers;
853         }
854
855         /**
856          * Fetch the receiver list of a given actor
857          *
858          * @param string  $actor
859          * @param array   $tags
860          * @param array   $receivers
861          * @param integer $target_type
862          *
863          * @return array with receivers (user id)
864          * @throws \Exception
865          */
866         private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
867         {
868                 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
869                         'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
870
871                 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
872                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
873                 while ($contact = DBA::fetch($contacts)) {
874                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
875                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
876                         }
877                 }
878                 DBA::close($contacts);
879
880                 // The queries are split because of performance issues
881                 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
882                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
883                 while ($contact = DBA::fetch($contacts)) {
884                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
885                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
886                         }
887                 }
888                 DBA::close($contacts);
889                 return $receivers;
890         }
891
892         /**
893          * Tests if the contact is a valid receiver for this actor
894          *
895          * @param array  $contact
896          * @param string $actor
897          * @param array  $tags
898          *
899          * @return bool with receivers (user id)
900          * @throws \Exception
901          */
902         private static function isValidReceiverForActor($contact, $tags)
903         {
904                 // Are we following the contact? Then this is a valid receiver
905                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
906                         return true;
907                 }
908
909                 // When the possible receiver isn't a community, then it is no valid receiver
910                 $owner = User::getOwnerDataById($contact['uid']);
911                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
912                         return false;
913                 }
914
915                 // Is the community account tagged?
916                 foreach ($tags as $tag) {
917                         if ($tag['type'] != 'Mention') {
918                                 continue;
919                         }
920
921                         if (Strings::compareLink($tag['href'], $owner['url'])) {
922                                 return true;
923                         }
924                 }
925
926                 return false;
927         }
928
929         /**
930          * Switches existing contacts to ActivityPub
931          *
932          * @param integer $cid Contact ID
933          * @param integer $uid User ID
934          * @param string  $url Profile URL
935          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
936          * @throws \ImagickException
937          */
938         public static function switchContact($cid, $uid, $url)
939         {
940                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
941                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
942                         return;
943                 }
944
945                 if (Contact::updateFromProbe($cid)) {
946                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
947                 }
948
949                 // Send a new follow request to be sure that the connection still exists
950                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
951                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
952                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
953                 }
954         }
955
956         /**
957          *
958          *
959          * @param $receivers
960          * @param $actor
961          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
962          * @throws \ImagickException
963          */
964         private static function switchContacts($receivers, $actor)
965         {
966                 if (empty($actor)) {
967                         return;
968                 }
969
970                 foreach ($receivers as $receiver) {
971                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
972                         if (DBA::isResult($contact)) {
973                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
974                         }
975
976                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
977                         if (DBA::isResult($contact)) {
978                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
979                         }
980                 }
981         }
982
983         /**
984          *
985          *
986          * @param       $object_data
987          * @param array $activity
988          *
989          * @return mixed
990          */
991         private static function addActivityFields($object_data, $activity)
992         {
993                 if (!empty($activity['published']) && empty($object_data['published'])) {
994                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
995                 }
996
997                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
998                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
999                 }
1000
1001                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1002                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1003
1004                 if (!empty($object_data['object_id'])) {
1005                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1006                         $objectId = Item::getURIByLink($object_data['object_id']);
1007                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1008                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1009                                 $object_data['object_id'] = $objectId;
1010                         }
1011                 }
1012
1013                 return $object_data;
1014         }
1015
1016         /**
1017          * Fetches the object data from external ressources if needed
1018          *
1019          * @param string  $object_id    Object ID of the the provided object
1020          * @param array   $object       The provided object array
1021          * @param boolean $trust_source Do we trust the provided object?
1022          * @param integer $uid          User ID for the signature that we use to fetch data
1023          *
1024          * @return array|false with trusted and valid object data
1025          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1026          * @throws \ImagickException
1027          */
1028         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1029         {
1030                 // By fetching the type we check if the object is complete.
1031                 $type = JsonLD::fetchElement($object, '@type');
1032
1033                 if (!$trust_source || empty($type)) {
1034                         $data = ActivityPub::fetchContent($object_id, $uid);
1035                         if (!empty($data)) {
1036                                 $object = JsonLD::compact($data);
1037                                 Logger::info('Fetched content for ' . $object_id);
1038                         } else {
1039                                 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1040
1041                                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1042                                 if (!DBA::isResult($item)) {
1043                                         Logger::info('Object with url ' . $object_id . ' was not found locally.');
1044                                         return false;
1045                                 }
1046                                 Logger::info('Using already stored item for url ' . $object_id);
1047                                 $data = ActivityPub\Transmitter::createNote($item);
1048                                 $object = JsonLD::compact($data);
1049                         }
1050
1051                         $id = JsonLD::fetchElement($object, '@id');
1052                         if (empty($id)) {
1053                                 Logger::info('Empty id');
1054                                 return false;
1055                         }
1056
1057                         if ($id != $object_id) {
1058                                 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1059                                 return false;
1060                         }
1061                 } else {
1062                         Logger::info('Using original object for url ' . $object_id);
1063                 }
1064
1065                 $type = JsonLD::fetchElement($object, '@type');
1066                 if (empty($type)) {
1067                         Logger::info('Empty type');
1068                         return false;
1069                 }
1070
1071                 // Lemmy is resharing "create" activities instead of content
1072                 // We fetch the content from the activity.
1073                 if (in_array($type, ['as:Create'])) {
1074                         $object = $object['as:object'];
1075                         $type = JsonLD::fetchElement($object, '@type');
1076                         if (empty($type)) {
1077                                 Logger::info('Empty type');
1078                                 return false;
1079                         }
1080                         $object_data = self::processObject($object);
1081                 }
1082
1083                 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1084                 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1085                         $object_data = self::processObject($object);
1086
1087                         if (!empty($data)) {
1088                                 $object_data['raw'] = json_encode($data);
1089                         }
1090                         return $object_data;
1091                 }
1092
1093                 if ($type == 'as:Announce') {
1094                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
1095                         if (empty($object_id) || !is_string($object_id)) {
1096                                 return false;
1097                         }
1098                         return self::fetchObject($object_id, [], false, $uid);
1099                 }
1100
1101                 Logger::info('Unhandled object type: ' . $type);
1102                 return false;
1103         }
1104
1105         /**
1106          * Converts the language element (Used by Peertube)
1107          *
1108          * @param array $languages
1109          * @return array Languages
1110          */
1111         public static function processLanguages(array $languages)
1112         {
1113                 if (empty($languages)) {
1114                         return [];
1115                 }
1116
1117                 $language_list = [];
1118
1119                 foreach ($languages as $language) {
1120                         if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1121                                 $language_list[$language['_:identifier']] = $language['as:name'];
1122                         }
1123                 }
1124                 return $language_list;
1125         }
1126
1127         /**
1128          * Convert tags from JSON-LD format into a simplified format
1129          *
1130          * @param array $tags Tags in JSON-LD format
1131          *
1132          * @return array with tags in a simplified format
1133          */
1134         public static function processTags(array $tags)
1135         {
1136                 $taglist = [];
1137
1138                 foreach ($tags as $tag) {
1139                         if (empty($tag)) {
1140                                 continue;
1141                         }
1142
1143                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1144                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1145                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1146
1147                         if (empty($element['type'])) {
1148                                 continue;
1149                         }
1150
1151                         if (empty($element['href'])) {
1152                                 $element['href'] = $element['name'];
1153                         }
1154
1155                         $taglist[] = $element;
1156                 }
1157                 return $taglist;
1158         }
1159
1160         /**
1161          * Convert emojis from JSON-LD format into a simplified format
1162          *
1163          * @param array $emojis
1164          * @return array with emojis in a simplified format
1165          */
1166         private static function processEmojis(array $emojis)
1167         {
1168                 $emojilist = [];
1169
1170                 foreach ($emojis as $emoji) {
1171                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1172                                 continue;
1173                         }
1174
1175                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1176                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1177                                 'href' => $url];
1178
1179                         $emojilist[] = $element;
1180                 }
1181
1182                 return $emojilist;
1183         }
1184
1185         /**
1186          * Convert attachments from JSON-LD format into a simplified format
1187          *
1188          * @param array $attachments Attachments in JSON-LD format
1189          *
1190          * @return array Attachments in a simplified format
1191          */
1192         private static function processAttachments(array $attachments)
1193         {
1194                 $attachlist = [];
1195
1196                 // Removes empty values
1197                 $attachments = array_filter($attachments);
1198
1199                 foreach ($attachments as $attachment) {
1200                         switch (JsonLD::fetchElement($attachment, '@type')) {
1201                                 case 'as:Page':
1202                                         $pageUrl = null;
1203                                         $pageImage = null;
1204
1205                                         $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1206                                         foreach ($urls as $url) {
1207                                                 // Single scalar URL case
1208                                                 if (is_string($url)) {
1209                                                         $pageUrl = $url;
1210                                                         continue;
1211                                                 }
1212
1213                                                 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1214                                                 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1215                                                 if (Strings::startsWith($mediaType, 'image')) {
1216                                                         $pageImage = $href;
1217                                                 } else {
1218                                                         $pageUrl = $href;
1219                                                 }
1220                                         }
1221
1222                                         $attachlist[] = [
1223                                                 'type'  => 'link',
1224                                                 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1225                                                 'desc'  => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1226                                                 'url'   => $pageUrl,
1227                                                 'image' => $pageImage,
1228                                         ];
1229                                         break;
1230                                 case 'as:Image':
1231                                         $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1232                                         $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1233                                         $imagePreviewUrl = null;
1234                                         // Multiple URLs?
1235                                         if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1236                                                 $imageVariants = [];
1237                                                 $previewVariants = [];
1238                                                 foreach ($urls as $url) {
1239                                                         // Scalar URL, no discrimination possible
1240                                                         if (is_string($url)) {
1241                                                                 $imageFullUrl = $url;
1242                                                                 continue;
1243                                                         }
1244
1245                                                         // Not sure what to do with a different Link media type than the base Image, we skip
1246                                                         if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1247                                                                 continue;
1248                                                         }
1249
1250                                                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1251
1252                                                         // Default URL choice if no discriminating width is provided
1253                                                         $imageFullUrl = $href ?? $imageFullUrl;
1254
1255                                                         $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1256
1257                                                         if ($href && $width) {
1258                                                                 $imageVariants[$width] = $href;
1259                                                                 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1260                                                                 $previewVariants[abs(632 - $width)] = $href;
1261                                                         }
1262                                                 }
1263
1264                                                 if ($imageVariants) {
1265                                                         // Taking the maximum size image
1266                                                         ksort($imageVariants);
1267                                                         $imageFullUrl = array_pop($imageVariants);
1268
1269                                                         // Taking the minimum number distance to the target distance
1270                                                         ksort($previewVariants);
1271                                                         $imagePreviewUrl = array_shift($previewVariants);
1272                                                 }
1273
1274                                                 unset($imageVariants);
1275                                                 unset($previewVariants);
1276                                         }
1277
1278                                         $attachlist[] = [
1279                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1280                                                 'mediaType' => $mediaType,
1281                                                 'name'  => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1282                                                 'url'   => $imageFullUrl,
1283                                                 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1284                                         ];
1285                                         break;
1286                                 default:
1287                                         $attachlist[] = [
1288                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1289                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1290                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1291                                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1292                                                 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1293                                                 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1294                                                 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1295                                         ];
1296                         }
1297                 }
1298
1299                 return $attachlist;
1300         }
1301
1302         /**
1303          * Fetch the original source or content with the "language" Markdown or HTML
1304          *
1305          * @param array $object
1306          * @param array $object_data
1307          *
1308          * @return array
1309          * @throws \Exception
1310          */
1311         private static function getSource($object, $object_data)
1312         {
1313                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1314                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1315                 if (!empty($object_data['source'])) {
1316                         return $object_data;
1317                 }
1318
1319                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1320                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1321                 if (!empty($object_data['source'])) {
1322                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
1323                         return $object_data;
1324                 }
1325
1326                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1327                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1328                 if (!empty($object_data['source'])) {
1329                         $object_data['source'] = HTML::toBBCode($object_data['source']);
1330                         return $object_data;
1331                 }
1332
1333                 return $object_data;
1334         }
1335
1336         /**
1337          * Extracts a potential alternate URL from a list of additional URL elements
1338          *
1339          * @param array $urls
1340          * @return string
1341          */
1342         private static function extractAlternateUrl(array $urls): string
1343         {
1344                 $alternateUrl = '';
1345                 foreach ($urls as $key => $url) {
1346                         // Not a list but a single URL element
1347                         if (!is_numeric($key)) {
1348                                 continue;
1349                         }
1350
1351                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1352                                 continue;
1353                         }
1354
1355                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1356                         if (empty($href)) {
1357                                 continue;
1358                         }
1359
1360                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1361                         if (empty($mediatype)) {
1362                                 continue;
1363                         }
1364
1365                         if ($mediatype == 'text/html') {
1366                                 $alternateUrl = $href;
1367                         }
1368                 }
1369
1370                 return $alternateUrl;
1371         }
1372
1373         /**
1374          * Check if the "as:url" element is an array with multiple links
1375          * This is the case with audio and video posts.
1376          * Then the links are added as attachments
1377          *
1378          * @param array $urls The object URL list
1379          * @return array an array of attachments
1380          */
1381         private static function processAttachmentUrls(array $urls): array
1382         {
1383                 $attachments = [];
1384                 foreach ($urls as $key => $url) {
1385                         // Not a list but a single URL element
1386                         if (!is_numeric($key)) {
1387                                 continue;
1388                         }
1389
1390                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1391                                 continue;
1392                         }
1393
1394                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1395                         if (empty($href)) {
1396                                 continue;
1397                         }
1398
1399                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1400                         if (empty($mediatype)) {
1401                                 continue;
1402                         }
1403
1404                         $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1405
1406                         if ($filetype == 'audio') {
1407                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1408                         } elseif ($filetype == 'video') {
1409                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1410                                 // PeerTube audio-only track
1411                                 if ($height === 0) {
1412                                         continue;
1413                                 }
1414
1415                                 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1416                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1417                         } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1418                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1419
1420                                 // For Torrent links we always store the highest resolution
1421                                 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1422                                         continue;
1423                                 }
1424
1425                                 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1426                         } elseif ($mediatype == 'application/x-mpegURL') {
1427                                 // PeerTube exception, actual video link is in the tags of this URL element
1428                                 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1429                         }
1430                 }
1431
1432                 return array_values($attachments);
1433         }
1434
1435         /**
1436          * Fetches data from the object part of an activity
1437          *
1438          * @param array $object
1439          *
1440          * @return array
1441          * @throws \Exception
1442          */
1443         private static function processObject($object)
1444         {
1445                 if (!JsonLD::fetchElement($object, '@id')) {
1446                         return false;
1447                 }
1448
1449                 $object_data = [];
1450                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1451                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1452                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1453
1454                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1455                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1456                         $object_data['reply-to-id'] = $object_data['id'];
1457
1458                         // On activities the "reply to" is the id of the object it refers to
1459                         if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1460                                 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1461                                 if (!empty($object_id)) {
1462                                         $object_data['reply-to-id'] = $object_id;
1463                                 }
1464                         }
1465                 } else {
1466                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1467                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1468                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1469                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1470                                 $object_data['reply-to-id'] = $replyToId;
1471                         }
1472                 }
1473
1474                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1475                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1476
1477                 if (empty($object_data['updated'])) {
1478                         $object_data['updated'] = $object_data['published'];
1479                 }
1480
1481                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1482                         $object_data['published'] = $object_data['updated'];
1483                 }
1484
1485                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1486                 if (empty($actor)) {
1487                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1488                 }
1489
1490                 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1491                 $location = JsonLD::fetchElement($location, 'location', '@value');
1492                 if ($location) {
1493                         // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1494                         // down to HTML and then finally format to plaintext.
1495                         $location = Markdown::convert($location);
1496                         $location = BBCode::toPlaintext($location);
1497                 }
1498
1499                 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1500                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1501                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1502                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1503                 $object_data['actor'] = $object_data['author'] = $actor;
1504                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1505                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1506                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1507                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1508                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1509                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1510                 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1511                 $object_data = self::getSource($object, $object_data);
1512                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1513                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1514                 $object_data['location'] = $location;
1515                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1516                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1517                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1518                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1519                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1520                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1521                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1522                 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1523                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1524                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1525                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1526
1527                 // Special treatment for Hubzilla links
1528                 if (is_array($object_data['alternate-url'])) {
1529                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1530
1531                         if (!is_string($object_data['alternate-url'])) {
1532                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1533                         }
1534                 }
1535
1536                 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1537                         $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1538                         $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1539                 }
1540
1541                 // For page types we expect that the alternate url posts to some page.
1542                 // So we add this to the attachments if it differs from the id.
1543                 // Currently only Lemmy is using the page type.
1544                 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1545                         $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1546                         $object_data['alternate-url'] = null;
1547                 }
1548
1549                 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1550                 $receivers = $reception_types = [];
1551                 foreach ($receiverdata as $key => $data) {
1552                         $receivers[$key] = $data['uid'];
1553                         $reception_types[$data['uid']] = $data['type'] ?? 0;
1554                 }
1555
1556                 $object_data['receiver_urls']  = self::getReceiverURL($object);
1557                 $object_data['receiver']       = $receivers;
1558                 $object_data['reception_type'] = $reception_types;
1559
1560                 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1561                 unset($object_data['receiver'][-1]);
1562                 unset($object_data['reception_type'][-1]);
1563
1564                 // Common object data:
1565
1566                 // Unhandled
1567                 // @context, type, actor, signature, mediaType, duration, replies, icon
1568
1569                 // Also missing: (Defined in the standard, but currently unused)
1570                 // audience, preview, endTime, startTime, image
1571
1572                 // Data in Notes:
1573
1574                 // Unhandled
1575                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1576                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1577
1578                 // Data in video:
1579
1580                 // To-Do?
1581                 // category, licence, language, commentsEnabled
1582
1583                 // Unhandled
1584                 // views, waitTranscoding, state, support, subtitleLanguage
1585                 // likes, dislikes, shares, comments
1586
1587                 return $object_data;
1588         }
1589 }