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