]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Issue 9264: post types should now work
[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'] ?? self::TARGET_UNKNOWN;
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];
291                         $receivers = array_replace($receivers, $additional);
292                         if (empty($activity['thread-completion']) && (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL]))) {
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_replace($object_data['receiver'] ?? [], $receivers);
376                 $object_data['reception_type'] = array_replace($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[$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                 // We have to prevent false follower assumptions upon thread completions
651                 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
652
653                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
654                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
655                         if (empty($receiver_list)) {
656                                 continue;
657                         }
658
659                         foreach ($receiver_list as $receiver) {
660                                 if ($receiver == self::PUBLIC_COLLECTION) {
661                                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
662                                 }
663
664                                 // Add receiver "-1" for unlisted posts 
665                                 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
666                                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
667                                 }
668
669                                 // Fetch the receivers for the public and the followers collection
670                                 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
671                                         $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
672                                         continue;
673                                 }
674
675                                 // Fetching all directly addressed receivers
676                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
677                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
678                                 if (!DBA::isResult($contact)) {
679                                         continue;
680                                 }
681
682                                 // Check if the potential receiver is following the actor
683                                 // Exception: The receiver is targetted via "to" or this is a comment
684                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
685                                         $networks = Protocol::FEDERATED;
686                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
687                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
688
689                                         // Forum posts are only accepted from forum contacts
690                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
691                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
692                                         }
693
694                                         if (!DBA::exists('contact', $condition)) {
695                                                 continue;
696                                         }
697                                 }
698
699                                 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
700                                 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
701                                         switch ($element) {
702                                                 case 'as:to':
703                                                         $type = self::TARGET_TO;
704                                                         break;
705                                                 case 'as:cc':
706                                                         $type = self::TARGET_CC;
707                                                         break;
708                                                 case 'as:bto':
709                                                         $type = self::TARGET_BTO;
710                                                         break;
711                                                 case 'as:bcc':
712                                                         $type = self::TARGET_BCC;
713                                                         break;
714                                         }
715
716                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
717                                 }
718                         }
719                 }
720
721                 self::switchContacts($receivers, $actor);
722
723                 return $receivers;
724         }
725
726         /**
727          * Fetch the receiver list of a given actor
728          *
729          * @param string  $actor
730          * @param array   $tags
731          * @param array   $receivers
732          * @param integer $target_type
733          *
734          * @return array with receivers (user id)
735          * @throws \Exception
736          */
737         private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
738         {
739                 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
740                         'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
741
742                 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
743                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
744                 while ($contact = DBA::fetch($contacts)) {
745                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
746                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
747                         }
748                 }
749                 DBA::close($contacts);
750
751                 // The queries are split because of performance issues
752                 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
753                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
754                 while ($contact = DBA::fetch($contacts)) {
755                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
756                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
757                         }
758                 }
759                 DBA::close($contacts);
760                 return $receivers;
761         }
762
763         /**
764          * Tests if the contact is a valid receiver for this actor
765          *
766          * @param array  $contact
767          * @param string $actor
768          * @param array  $tags
769          *
770          * @return bool with receivers (user id)
771          * @throws \Exception
772          */
773         private static function isValidReceiverForActor($contact, $tags)
774         {
775                 // Are we following the contact? Then this is a valid receiver
776                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
777                         return true;
778                 }
779
780                 // When the possible receiver isn't a community, then it is no valid receiver
781                 $owner = User::getOwnerDataById($contact['uid']);
782                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
783                         return false;
784                 }
785
786                 // Is the community account tagged?
787                 foreach ($tags as $tag) {
788                         if ($tag['type'] != 'Mention') {
789                                 continue;
790                         }
791
792                         if (Strings::compareLink($tag['href'], $owner['url'])) {
793                                 return true;
794                         }
795                 }
796
797                 return false;
798         }
799
800         /**
801          * Switches existing contacts to ActivityPub
802          *
803          * @param integer $cid Contact ID
804          * @param integer $uid User ID
805          * @param string  $url Profile URL
806          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
807          * @throws \ImagickException
808          */
809         public static function switchContact($cid, $uid, $url)
810         {
811                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
812                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
813                         return;
814                 }
815
816                 if (Contact::updateFromProbe($cid)) {
817                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
818                 }
819
820                 // Send a new follow request to be sure that the connection still exists
821                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
822                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
823                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
824                 }
825         }
826
827         /**
828          *
829          *
830          * @param $receivers
831          * @param $actor
832          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
833          * @throws \ImagickException
834          */
835         private static function switchContacts($receivers, $actor)
836         {
837                 if (empty($actor)) {
838                         return;
839                 }
840
841                 foreach ($receivers as $receiver) {
842                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
843                         if (DBA::isResult($contact)) {
844                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
845                         }
846
847                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
848                         if (DBA::isResult($contact)) {
849                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
850                         }
851                 }
852         }
853
854         /**
855          *
856          *
857          * @param       $object_data
858          * @param array $activity
859          *
860          * @return mixed
861          */
862         private static function addActivityFields($object_data, $activity)
863         {
864                 if (!empty($activity['published']) && empty($object_data['published'])) {
865                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
866                 }
867
868                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
869                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
870                 }
871
872                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
873                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
874
875                 if (!empty($object_data['object_id'])) {
876                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
877                         $objectId = Item::getURIByLink($object_data['object_id']);
878                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
879                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
880                                 $object_data['object_id'] = $objectId;
881                         }
882                 }
883
884                 return $object_data;
885         }
886
887         /**
888          * Fetches the object data from external ressources if needed
889          *
890          * @param string  $object_id    Object ID of the the provided object
891          * @param array   $object       The provided object array
892          * @param boolean $trust_source Do we trust the provided object?
893          * @param integer $uid          User ID for the signature that we use to fetch data
894          *
895          * @return array|false with trusted and valid object data
896          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
897          * @throws \ImagickException
898          */
899         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
900         {
901                 // By fetching the type we check if the object is complete.
902                 $type = JsonLD::fetchElement($object, '@type');
903
904                 if (!$trust_source || empty($type)) {
905                         $data = ActivityPub::fetchContent($object_id, $uid);
906                         if (!empty($data)) {
907                                 $object = JsonLD::compact($data);
908                                 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
909                         } else {
910                                 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
911
912                                 $item = Item::selectFirst([], ['uri' => $object_id]);
913                                 if (!DBA::isResult($item)) {
914                                         Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
915                                         return false;
916                                 }
917                                 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
918                                 $data = ActivityPub\Transmitter::createNote($item);
919                                 $object = JsonLD::compact($data);
920                         }
921
922                         $id = JsonLD::fetchElement($object, '@id');
923                         if (empty($id)) {
924                                 Logger::info('Empty id');
925                                 return false;
926                         }
927         
928                         if ($id != $object_id) {
929                                 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
930                                 return false;
931                         }
932                 } else {
933                         Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
934                 }
935
936                 $type = JsonLD::fetchElement($object, '@type');
937                 if (empty($type)) {
938                         Logger::info('Empty type');
939                         return false;
940                 }
941
942                 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
943                 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
944                         $object_data = self::processObject($object);
945
946                         if (!empty($data)) {
947                                 $object_data['raw'] = json_encode($data);
948                         }
949                         return $object_data;
950                 }
951
952                 if ($type == 'as:Announce') {
953                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
954                         if (empty($object_id) || !is_string($object_id)) {
955                                 return false;
956                         }
957                         return self::fetchObject($object_id, [], false, $uid);
958                 }
959
960                 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
961                 return false;
962         }
963
964         /**
965          * Convert tags from JSON-LD format into a simplified format
966          *
967          * @param array $tags Tags in JSON-LD format
968          *
969          * @return array with tags in a simplified format
970          */
971         public static function processTags(array $tags)
972         {
973                 $taglist = [];
974
975                 foreach ($tags as $tag) {
976                         if (empty($tag)) {
977                                 continue;
978                         }
979
980                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
981                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
982                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
983
984                         if (empty($element['type'])) {
985                                 continue;
986                         }
987
988                         if (empty($element['href'])) {
989                                 $element['href'] = $element['name'];
990                         }
991
992                         $taglist[] = $element;
993                 }
994                 return $taglist;
995         }
996
997         /**
998          * Convert emojis from JSON-LD format into a simplified format
999          *
1000          * @param array $emojis
1001          * @return array with emojis in a simplified format
1002          */
1003         private static function processEmojis(array $emojis)
1004         {
1005                 $emojilist = [];
1006
1007                 foreach ($emojis as $emoji) {
1008                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1009                                 continue;
1010                         }
1011
1012                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1013                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1014                                 'href' => $url];
1015
1016                         $emojilist[] = $element;
1017                 }
1018
1019                 return $emojilist;
1020         }
1021
1022         /**
1023          * Convert attachments from JSON-LD format into a simplified format
1024          *
1025          * @param array $attachments Attachments in JSON-LD format
1026          *
1027          * @return array Attachments in a simplified format
1028          */
1029         private static function processAttachments(array $attachments)
1030         {
1031                 $attachlist = [];
1032
1033                 // Removes empty values
1034                 $attachments = array_filter($attachments);
1035
1036                 foreach ($attachments as $attachment) {
1037                         switch (JsonLD::fetchElement($attachment, '@type')) {
1038                                 case 'as:Page':
1039                                         $pageUrl = null;
1040                                         $pageImage = null;
1041
1042                                         $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1043                                         foreach ($urls as $url) {
1044                                                 // Single scalar URL case
1045                                                 if (is_string($url)) {
1046                                                         $pageUrl = $url;
1047                                                         continue;
1048                                                 }
1049
1050                                                 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1051                                                 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1052                                                 if (Strings::startsWith($mediaType, 'image')) {
1053                                                         $pageImage = $href;
1054                                                 } else {
1055                                                         $pageUrl = $href;
1056                                                 }
1057                                         }
1058
1059                                         $attachlist[] = [
1060                                                 'type'  => 'link',
1061                                                 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1062                                                 'desc'  => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1063                                                 'url'   => $pageUrl,
1064                                                 'image' => $pageImage,
1065                                         ];
1066                                         break;
1067                                 case 'as:Link':
1068                                         $attachlist[] = [
1069                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1070                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1071                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1072                                                 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1073                                         ];
1074                                         break;
1075                                 case 'as:Image':
1076                                         $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1077                                         $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1078                                         $imagePreviewUrl = null;
1079                                         // Multiple URLs?
1080                                         if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1081                                                 $imageVariants = [];
1082                                                 $previewVariants = [];
1083                                                 foreach ($urls as $url) {
1084                                                         // Scalar URL, no discrimination possible
1085                                                         if (is_string($url)) {
1086                                                                 $imageFullUrl = $url;
1087                                                                 continue;
1088                                                         }
1089
1090                                                         // Not sure what to do with a different Link media type than the base Image, we skip
1091                                                         if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1092                                                                 continue;
1093                                                         }
1094
1095                                                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1096
1097                                                         // Default URL choice if no discriminating width is provided
1098                                                         $imageFullUrl = $href ?? $imageFullUrl;
1099
1100                                                         $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1101
1102                                                         if ($href && $width) {
1103                                                                 $imageVariants[$width] = $href;
1104                                                                 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1105                                                                 $previewVariants[abs(632 - $width)] = $href;
1106                                                         }
1107                                                 }
1108
1109                                                 if ($imageVariants) {
1110                                                         // Taking the maximum size image
1111                                                         ksort($imageVariants);
1112                                                         $imageFullUrl = array_pop($imageVariants);
1113
1114                                                         // Taking the minimum number distance to the target distance
1115                                                         ksort($previewVariants);
1116                                                         $imagePreviewUrl = array_shift($previewVariants);
1117                                                 }
1118
1119                                                 unset($imageVariants);
1120                                                 unset($previewVariants);
1121                                         }
1122
1123                                         $attachlist[] = [
1124                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1125                                                 'mediaType' => $mediaType,
1126                                                 'name'  => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1127                                                 'url'   => $imageFullUrl,
1128                                                 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1129                                         ];
1130                                         break;
1131                                 default:
1132                                         $attachlist[] = [
1133                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1134                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1135                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1136                                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1137                                         ];
1138                         }
1139                 }
1140
1141                 return $attachlist;
1142         }
1143
1144         /**
1145          * Fetch the original source or content with the "language" Markdown or HTML
1146          *
1147          * @param array $object
1148          * @param array $object_data
1149          *
1150          * @return array
1151          * @throws \Exception
1152          */
1153         private static function getSource($object, $object_data)
1154         {
1155                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1156                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1157                 if (!empty($object_data['source'])) {
1158                         return $object_data;
1159                 }
1160
1161                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1162                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1163                 if (!empty($object_data['source'])) {
1164                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
1165                         return $object_data;
1166                 }
1167
1168                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1169                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1170                 if (!empty($object_data['source'])) {
1171                         $object_data['source'] = HTML::toBBCode($object_data['source']);
1172                         return $object_data;
1173                 }
1174
1175                 return $object_data;
1176         }
1177
1178         /**
1179          * Check if the "as:url" element is an array with multiple links
1180          * This is the case with audio and video posts.
1181          * Then the links are added as attachments
1182          *
1183          * @param array $object      The raw object
1184          * @param array $object_data The parsed object data for later processing
1185          * @return array the object data
1186          */
1187         private static function processAttachmentUrls(array $object, array $object_data) {
1188                 // Check if this is some url with multiple links
1189                 if (empty($object['as:url'])) {
1190                         return $object_data;
1191                 }
1192                 
1193                 $urls = $object['as:url'];
1194                 $keys = array_keys($urls);
1195                 if (!is_numeric(array_pop($keys))) {
1196                         return $object_data;
1197                 }
1198
1199                 $attachments = [];
1200
1201                 foreach ($urls as $url) {
1202                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1203                                 continue;
1204                         }
1205
1206                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1207                         if (empty($href)) {
1208                                 continue;
1209                         }
1210
1211                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1212                         if (empty($mediatype)) {
1213                                 continue;
1214                         }
1215
1216                         if ($mediatype == 'text/html') {
1217                                 $object_data['alternate-url'] = $href;
1218                         }
1219
1220                         $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1221
1222                         if ($filetype == 'audio') {
1223                                 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1224                         } elseif ($filetype == 'video') {
1225                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1226
1227                                 // We save bandwidth by using a moderate height
1228                                 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1229                                 if (!empty($attachments[$filetype]['height']) &&
1230                                         (($height > 480) || $height < $attachments[$filetype]['height'])) {
1231                                         continue;
1232                                 }
1233
1234                                 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1235                         }
1236                 }
1237
1238                 foreach ($attachments as $type => $attachment) {
1239                         $object_data['attachments'][] = ['type' => $type,
1240                                 'mediaType' => $attachment['type'],
1241                                 'name' => '',
1242                                 'url' => $attachment['url']];
1243                 }
1244                 return $object_data;
1245         }
1246
1247         /**
1248          * Fetches data from the object part of an activity
1249          *
1250          * @param array $object
1251          *
1252          * @return array
1253          * @throws \Exception
1254          */
1255         private static function processObject($object)
1256         {
1257                 if (!JsonLD::fetchElement($object, '@id')) {
1258                         return false;
1259                 }
1260
1261                 $object_data = [];
1262                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1263                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1264                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1265
1266                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1267                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1268                         $object_data['reply-to-id'] = $object_data['id'];
1269                 } else {
1270                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1271                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1272                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1273                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1274                                 $object_data['reply-to-id'] = $replyToId;
1275                         }
1276                 }
1277
1278                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1279                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1280
1281                 if (empty($object_data['updated'])) {
1282                         $object_data['updated'] = $object_data['published'];
1283                 }
1284
1285                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1286                         $object_data['published'] = $object_data['updated'];
1287                 }
1288
1289                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1290                 if (empty($actor)) {
1291                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1292                 }
1293
1294                 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1295                 $location = JsonLD::fetchElement($location, 'location', '@value');
1296                 if ($location) {
1297                         // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1298                         // down to HTML and then finally format to plaintext.
1299                         $location = Markdown::convert($location);
1300                         $location = BBCode::convert($location);
1301                         $location = HTML::toPlaintext($location);
1302                 }
1303
1304                 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1305                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1306                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1307                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1308                 $object_data['actor'] = $object_data['author'] = $actor;
1309                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1310                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1311                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1312                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1313                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1314                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1315                 $object_data = self::getSource($object, $object_data);
1316                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1317                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1318                 $object_data['location'] = $location;
1319                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1320                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1321                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1322                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1323                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1324                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1325                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1326                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1327                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1328                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1329
1330                 // Special treatment for Hubzilla links
1331                 if (is_array($object_data['alternate-url'])) {
1332                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1333
1334                         if (!is_string($object_data['alternate-url'])) {
1335                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1336                         }
1337                 }
1338
1339                 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1340                         $object_data = self::processAttachmentUrls($object, $object_data);
1341                 }
1342
1343                 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1344                 $receivers = $reception_types = [];
1345                 foreach ($receiverdata as $key => $data) {
1346                         $receivers[$key] = $data['uid'];
1347                         $reception_types[$data['uid']] = $data['type'] ?? 0;
1348                 }
1349
1350                 $object_data['receiver'] = $receivers;
1351                 $object_data['reception_type'] = $reception_types;
1352
1353                 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1354                 unset($object_data['receiver'][-1]);
1355                 unset($object_data['reception_type'][-1]);
1356
1357                 // Common object data:
1358
1359                 // Unhandled
1360                 // @context, type, actor, signature, mediaType, duration, replies, icon
1361
1362                 // Also missing: (Defined in the standard, but currently unused)
1363                 // audience, preview, endTime, startTime, image
1364
1365                 // Data in Notes:
1366
1367                 // Unhandled
1368                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1369                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1370
1371                 // Data in video:
1372
1373                 // To-Do?
1374                 // category, licence, language, commentsEnabled
1375
1376                 // Unhandled
1377                 // views, waitTranscoding, state, support, subtitleLanguage
1378                 // likes, dislikes, shares, comments
1379
1380                 return $object_data;
1381         }
1382 }