3 * @file src/Protocol/ActivityPub/Receiver.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Content\Text\Markdown;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Model\Contact;
13 use Friendica\Model\APContact;
14 use Friendica\Model\Conversation;
15 use Friendica\Model\Item;
16 use Friendica\Model\User;
17 use Friendica\Protocol\Activity;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\HTTPSignature;
21 use Friendica\Util\JsonLD;
22 use Friendica\Util\LDSignature;
23 use Friendica\Util\Strings;
26 * ActivityPub Receiver Protocol class
31 * Check what this is meant to do:
40 const PUBLIC_COLLECTION = 'as:Public';
41 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
42 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event'];
43 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
46 * Checks if the web request is done for the AP protocol
48 * @return bool is it AP?
50 public static function isRequest()
52 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
53 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
57 * Checks incoming message from the inbox
61 * @param integer $uid User ID
64 public static function processInbox($body, $header, $uid)
66 $http_signer = HTTPSignature::getSigner($body, $header);
67 if (empty($http_signer)) {
68 Logger::warning('Invalid HTTP signature, message will be discarded.');
71 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
74 $activity = json_decode($body, true);
76 if (empty($activity)) {
77 Logger::warning('Invalid body.');
81 $ldactivity = JsonLD::compact($activity);
83 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
85 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
87 if (LDSignature::isSigned($activity)) {
88 $ld_signer = LDSignature::getSigner($activity);
89 if (empty($ld_signer)) {
90 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
92 if (!empty($ld_signer && ($actor == $http_signer))) {
93 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
95 } elseif (!empty($ld_signer)) {
96 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
98 } elseif ($actor == $http_signer) {
99 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
100 $trust_source = true;
102 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
103 $trust_source = false;
105 } elseif ($actor == $http_signer) {
106 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
107 $trust_source = true;
109 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
110 $trust_source = false;
113 self::processActivity($ldactivity, $body, $uid, $trust_source);
117 * Fetches the object type for a given object id
119 * @param array $activity
120 * @param string $object_id Object ID of the the provided object
121 * @param integer $uid User ID
123 * @return string with object type
124 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
125 * @throws \ImagickException
127 private static function fetchObjectType($activity, $object_id, $uid = 0)
129 if (!empty($activity['as:object'])) {
130 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
131 if (!empty($object_type)) {
136 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
137 // We just assume "note" since it doesn't make a difference for the further processing
141 $profile = APContact::getByURL($object_id);
142 if (!empty($profile['type'])) {
143 return 'as:' . $profile['type'];
146 $data = ActivityPub::fetchContent($object_id, $uid);
148 $object = JsonLD::compact($data);
149 $type = JsonLD::fetchElement($object, '@type');
159 * Prepare the object array
161 * @param array $activity
162 * @param integer $uid User ID
163 * @param $trust_source
165 * @return array with object data
166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
167 * @throws \ImagickException
169 private static function prepareObjectData($activity, $uid, &$trust_source)
171 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
173 Logger::log('Empty actor', Logger::DEBUG);
177 $type = JsonLD::fetchElement($activity, '@type');
179 // Fetch all receivers from to, cc, bto and bcc
180 $receivers = self::getReceivers($activity, $actor);
182 // When it is a delivery to a personal inbox we add that user to the receivers
184 $additional = ['uid:' . $uid => $uid];
185 $receivers = array_merge($receivers, $additional);
187 // We possibly need some user to fetch private content,
188 // so we fetch the first out ot the list.
189 $uid = self::getFirstUserFromReceivers($receivers);
192 Logger::log('Receivers: ' . $uid . ' - ' . json_encode($receivers), Logger::DEBUG);
194 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
195 if (empty($object_id)) {
196 Logger::log('No object found', Logger::DEBUG);
200 if (!is_string($object_id)) {
201 Logger::info('Invalid object id', ['object' => $object_id]);
205 $object_type = self::fetchObjectType($activity, $object_id, $uid);
207 // Fetch the content only on activities where this matters
208 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
209 if ($type == 'as:Announce') {
210 $trust_source = false;
212 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $uid);
213 if (empty($object_data)) {
214 Logger::log("Object data couldn't be processed", Logger::DEBUG);
217 $object_data['object_id'] = $object_id;
219 // Test if it is an answer to a mail
220 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
221 $object_data['directmessage'] = true;
223 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
226 // We had been able to retrieve the object data - so we can trust the source
227 $trust_source = true;
228 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
229 // Create a mostly empty array out of the activity data (instead of the object).
230 // This way we later don't have to check for the existence of ech individual array element.
231 $object_data = self::processObject($activity);
232 $object_data['name'] = $type;
233 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
234 $object_data['object_id'] = $object_id;
235 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
236 } elseif (in_array($type, ['as:Add'])) {
238 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
239 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
240 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
241 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
242 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
245 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
246 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
247 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
248 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
249 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
251 // An Undo is done on the object of an object, so we need that type as well
252 if ($type == 'as:Undo') {
253 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
257 $object_data = self::addActivityFields($object_data, $activity);
259 if (empty($object_data['object_type'])) {
260 $object_data['object_type'] = $object_type;
263 $object_data['type'] = $type;
264 $object_data['actor'] = $actor;
265 $object_data['item_receiver'] = $receivers;
266 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
268 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
274 * Fetches the first user id from the receiver array
276 * @param array $receivers Array with receivers
277 * @return integer user id;
279 public static function getFirstUserFromReceivers($receivers)
281 foreach ($receivers as $receiver) {
282 if (!empty($receiver)) {
290 * Store the unprocessed data into the conversation table
291 * This has to be done outside the regular function,
292 * since we store everything - not only item posts.
294 * @param array $activity Array with activity data
295 * @param string $body The raw message
298 private static function storeConversation($activity, $body)
300 if (empty($body) || empty($activity['id'])) {
305 'protocol' => Conversation::PARCEL_ACTIVITYPUB,
306 'item-uri' => $activity['id'],
307 'reply-to-uri' => $activity['reply-to-id'] ?? '',
308 'conversation-href' => $activity['context'] ?? '',
309 'conversation-uri' => $activity['conversation'] ?? '',
311 'received' => DateTimeFormat::utcNow()];
313 DBA::insert('conversation', $conversation, true);
317 * Processes the activity object
319 * @param array $activity Array with activity data
320 * @param string $body
321 * @param integer $uid User ID
322 * @param boolean $trust_source Do we trust the source?
325 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
327 $type = JsonLD::fetchElement($activity, '@type');
329 Logger::log('Empty type', Logger::DEBUG);
333 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
334 Logger::log('Empty object', Logger::DEBUG);
338 if (!JsonLD::fetchElement($activity, 'as:actor', '@id')) {
339 Logger::log('Empty actor', Logger::DEBUG);
344 // Don't trust the source if "actor" differs from "attributedTo". The content could be forged.
345 if ($trust_source && ($type == 'as:Create') && is_array($activity['as:object'])) {
346 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
347 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
348 $trust_source = ($actor == $attributed_to);
349 if (!$trust_source) {
350 Logger::log('Not trusting actor: ' . $actor . '. It differs from attributedTo: ' . $attributed_to, Logger::DEBUG);
354 // $trust_source is called by reference and is set to true if the content was retrieved successfully
355 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
356 if (empty($object_data)) {
357 Logger::log('No object data found', Logger::DEBUG);
361 if (!$trust_source) {
362 Logger::log('No trust for activity type "' . $type . '", so we quit now.', Logger::DEBUG);
366 // Only store content related stuff - and no announces, since they possibly overwrite the original content
367 if (in_array($object_data['object_type'], self::CONTENT_TYPES) && ($type != 'as:Announce')) {
368 self::storeConversation($object_data, $body);
371 // Internal flag for thread completion. See Processor.php
372 if (!empty($activity['thread-completion'])) {
373 $object_data['thread-completion'] = $activity['thread-completion'];
378 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
379 ActivityPub\Processor::createItem($object_data);
384 if ($object_data['object_type'] == 'as:tag') {
385 ActivityPub\Processor::addTag($object_data);
390 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
391 $profile = APContact::getByURL($object_data['actor']);
392 // Reshared posts from persons appear as summary at the bottom
393 // If this isn't set, then a single reshare appears on top. This is used for groups.
394 $object_data['thread-completion'] = ($profile['type'] != 'Group');
396 ActivityPub\Processor::createItem($object_data);
398 // Add the bottom reshare information only for persons
399 if ($profile['type'] != 'Group') {
400 $announce_object_data = self::processObject($activity);
401 $announce_object_data['name'] = $type;
402 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
403 $announce_object_data['object_id'] = $object_data['object_id'];
404 $announce_object_data['object_type'] = $object_data['object_type'];
406 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
412 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
413 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
418 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
419 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
423 case 'as:TentativeAccept':
424 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
425 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
430 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
431 ActivityPub\Processor::updateItem($object_data);
432 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
433 ActivityPub\Processor::updatePerson($object_data);
438 if ($object_data['object_type'] == 'as:Tombstone') {
439 ActivityPub\Processor::deleteItem($object_data);
440 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
441 ActivityPub\Processor::deletePerson($object_data);
446 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
447 ActivityPub\Processor::followUser($object_data);
448 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
449 $object_data['reply-to-id'] = $object_data['object_id'];
450 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
455 if ($object_data['object_type'] == 'as:Follow') {
456 ActivityPub\Processor::acceptFollowUser($object_data);
457 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
458 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
463 if ($object_data['object_type'] == 'as:Follow') {
464 ActivityPub\Processor::rejectFollowUser($object_data);
465 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
466 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
471 if (($object_data['object_type'] == 'as:Follow') &&
472 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
473 ActivityPub\Processor::undoFollowUser($object_data);
474 } elseif (($object_data['object_type'] == 'as:Accept') &&
475 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
476 ActivityPub\Processor::rejectFollowUser($object_data);
477 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
478 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
479 ActivityPub\Processor::undoActivity($object_data);
484 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
490 * Fetch the receiver list from an activity array
492 * @param array $activity
493 * @param string $actor
496 * @return array with receivers (user id)
499 private static function getReceivers($activity, $actor, $tags = [])
503 // When it is an answer, we inherite the receivers from the parent
504 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
505 if (!empty($replyto)) {
506 // Fix possibly wrong item URI (could be an answer to a plink uri)
507 $fixedReplyTo = Item::getURIByLink($replyto);
508 $replyto = $fixedReplyTo ?: $replyto;
510 $parents = Item::select(['uid'], ['uri' => $replyto]);
511 while ($parent = Item::fetch($parents)) {
512 $receivers['uid:' . $parent['uid']] = $parent['uid'];
516 if (!empty($actor)) {
517 $profile = APContact::getByURL($actor);
518 $followers = $profile['followers'] ?? '';
520 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
522 Logger::log('Empty actor', Logger::DEBUG);
526 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
527 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
528 if (empty($receiver_list)) {
532 foreach ($receiver_list as $receiver) {
533 if ($receiver == self::PUBLIC_COLLECTION) {
534 $receivers['uid:0'] = 0;
537 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
538 // This will most likely catch all OStatus connections to Mastodon
539 $condition = ['alias' => [$actor, Strings::normaliseLink($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
540 , 'archive' => false, 'pending' => false];
541 $contacts = DBA::select('contact', ['uid'], $condition);
542 while ($contact = DBA::fetch($contacts)) {
543 if ($contact['uid'] != 0) {
544 $receivers['uid:' . $contact['uid']] = $contact['uid'];
547 DBA::close($contacts);
550 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
551 $receivers = array_merge($receivers, self::getReceiverForActor($actor, $tags));
555 // Fetching all directly addressed receivers
556 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
557 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
558 if (!DBA::isResult($contact)) {
562 // Check if the potential receiver is following the actor
563 // Exception: The receiver is targetted via "to" or this is a comment
564 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
565 $networks = Protocol::FEDERATED;
566 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
567 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
569 // Forum posts are only accepted from forum contacts
570 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
571 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
574 if (!DBA::exists('contact', $condition)) {
579 $receivers['uid:' . $contact['uid']] = $contact['uid'];
583 self::switchContacts($receivers, $actor);
589 * Fetch the receiver list of a given actor
591 * @param string $actor
594 * @return array with receivers (user id)
597 public static function getReceiverForActor($actor, $tags)
600 $networks = Protocol::FEDERATED;
601 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
602 'network' => $networks, 'archive' => false, 'pending' => false];
603 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
604 while ($contact = DBA::fetch($contacts)) {
605 if (self::isValidReceiverForActor($contact, $actor, $tags)) {
606 $receivers['uid:' . $contact['uid']] = $contact['uid'];
609 DBA::close($contacts);
614 * Tests if the contact is a valid receiver for this actor
616 * @param array $contact
617 * @param string $actor
620 * @return bool with receivers (user id)
623 private static function isValidReceiverForActor($contact, $actor, $tags)
625 // Public contacts are no valid receiver
626 if ($contact['uid'] == 0) {
630 // Are we following the contact? Then this is a valid receiver
631 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
635 // When the possible receiver isn't a community, then it is no valid receiver
636 $owner = User::getOwnerDataById($contact['uid']);
637 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
641 // Is the community account tagged?
642 foreach ($tags as $tag) {
643 if ($tag['type'] != 'Mention') {
647 if ($tag['href'] == $owner['url']) {
656 * Switches existing contacts to ActivityPub
658 * @param integer $cid Contact ID
659 * @param integer $uid User ID
660 * @param string $url Profile URL
661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662 * @throws \ImagickException
664 public static function switchContact($cid, $uid, $url)
666 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
667 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
671 if (Contact::updateFromProbe($cid, '', true)) {
672 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
675 // Send a new follow request to be sure that the connection still exists
676 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
677 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
678 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
687 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
688 * @throws \ImagickException
690 private static function switchContacts($receivers, $actor)
696 foreach ($receivers as $receiver) {
697 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
698 if (DBA::isResult($contact)) {
699 self::switchContact($contact['id'], $receiver, $actor);
702 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
703 if (DBA::isResult($contact)) {
704 self::switchContact($contact['id'], $receiver, $actor);
712 * @param $object_data
713 * @param array $activity
717 private static function addActivityFields($object_data, $activity)
719 if (!empty($activity['published']) && empty($object_data['published'])) {
720 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
723 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
724 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
727 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
728 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
730 if (!empty($object_data['object_id'])) {
731 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
732 $objectId = Item::getURIByLink($object_data['object_id']);
733 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
734 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
735 $object_data['object_id'] = $objectId;
743 * Fetches the object data from external ressources if needed
745 * @param string $object_id Object ID of the the provided object
746 * @param array $object The provided object array
747 * @param boolean $trust_source Do we trust the provided object?
748 * @param integer $uid User ID for the signature that we use to fetch data
750 * @return array|false with trusted and valid object data
751 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
752 * @throws \ImagickException
754 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
756 // By fetching the type we check if the object is complete.
757 $type = JsonLD::fetchElement($object, '@type');
759 if (!$trust_source || empty($type)) {
760 $data = ActivityPub::fetchContent($object_id, $uid);
762 $object = JsonLD::compact($data);
763 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
765 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
767 $item = Item::selectFirst([], ['uri' => $object_id]);
768 if (!DBA::isResult($item)) {
769 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
772 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
773 $data = ActivityPub\Transmitter::createNote($item);
774 $object = JsonLD::compact($data);
777 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
780 $type = JsonLD::fetchElement($object, '@type');
783 Logger::log('Empty type', Logger::DEBUG);
787 if (in_array($type, self::CONTENT_TYPES)) {
788 return self::processObject($object);
791 if ($type == 'as:Announce') {
792 $object_id = JsonLD::fetchElement($object, 'object', '@id');
793 if (empty($object_id) || !is_string($object_id)) {
796 return self::fetchObject($object_id, [], false, $uid);
799 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
804 * Convert tags from JSON-LD format into a simplified format
806 * @param array $tags Tags in JSON-LD format
808 * @return array with tags in a simplified format
810 private static function processTags($tags)
818 foreach ($tags as $tag) {
823 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
824 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
825 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
827 if (empty($element['type'])) {
831 $taglist[] = $element;
837 * Convert emojis from JSON-LD format into a simplified format
840 * @return array with emojis in a simplified format
842 private static function processEmojis($emojis)
846 if (empty($emojis)) {
850 foreach ($emojis as $emoji) {
851 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
855 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
856 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
859 $emojilist[] = $element;
865 * Convert attachments from JSON-LD format into a simplified format
867 * @param array $attachments Attachments in JSON-LD format
869 * @return array with attachmants in a simplified format
871 private static function processAttachments($attachments)
875 if (empty($attachments)) {
879 foreach ($attachments as $attachment) {
880 if (empty($attachment)) {
884 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
885 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
886 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
887 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')];
893 * Fetch the original source or content with the "language" Markdown or HTML
895 * @param array $object
896 * @param array $object_data
901 private static function getSource($object, $object_data)
903 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
904 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
905 if (!empty($object_data['source'])) {
909 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
910 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
911 if (!empty($object_data['source'])) {
912 $object_data['source'] = Markdown::toBBCode($object_data['source']);
916 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
917 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
918 if (!empty($object_data['source'])) {
919 $object_data['source'] = HTML::toBBCode($object_data['source']);
927 * Fetches data from the object part of an activity
929 * @param array $object
934 private static function processObject($object)
936 if (!JsonLD::fetchElement($object, '@id')) {
941 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
942 $object_data['id'] = JsonLD::fetchElement($object, '@id');
943 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
945 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
946 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
947 $object_data['reply-to-id'] = $object_data['id'];
949 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
950 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
951 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
952 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
953 $object_data['reply-to-id'] = $replyToId;
957 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
958 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
960 if (empty($object_data['updated'])) {
961 $object_data['updated'] = $object_data['published'];
964 if (empty($object_data['published']) && !empty($object_data['updated'])) {
965 $object_data['published'] = $object_data['updated'];
968 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
970 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
973 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
974 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
975 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
976 $object_data['actor'] = $object_data['author'] = $actor;
977 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
978 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
979 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
980 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
981 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
982 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
983 $object_data = self::getSource($object, $object_data);
984 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
985 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
986 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
987 $object_data['location'] = JsonLD::fetchElement($object_data, 'location', '@value');
988 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
989 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
990 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
991 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
992 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
993 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
994 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji'));
995 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
996 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
997 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
999 // Special treatment for Hubzilla links
1000 if (is_array($object_data['alternate-url'])) {
1001 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1003 if (!is_string($object_data['alternate-url'])) {
1004 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1008 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags']);
1010 // Common object data:
1013 // @context, type, actor, signature, mediaType, duration, replies, icon
1015 // Also missing: (Defined in the standard, but currently unused)
1016 // audience, preview, endTime, startTime, image
1021 // contentMap, announcement_count, announcements, context_id, likes, like_count
1022 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1027 // category, licence, language, commentsEnabled
1030 // views, waitTranscoding, state, support, subtitleLanguage
1031 // likes, dislikes, shares, comments
1033 return $object_data;