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