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