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