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