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