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