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