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