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