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