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