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