3 * @file src/Protocol/ActivityPub/Receiver.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Util\HTTPSignature;
9 use Friendica\Core\Protocol;
10 use Friendica\Model\Contact;
11 use Friendica\Model\APContact;
12 use Friendica\Model\Item;
13 use Friendica\Model\User;
14 use Friendica\Util\JsonLD;
15 use Friendica\Util\LDSignature;
16 use Friendica\Protocol\ActivityPub;
17 use Friendica\Model\Conversation;
18 use Friendica\Util\DateTimeFormat;
21 * @brief ActivityPub Receiver Protocol class
24 * - Update (Image, Video, Article, Note)
28 * - TentativeAccept Even
31 * - Undo TentativeAccept Event
33 * Check what this is meant to do:
39 * - Undo Accept Person
43 const PUBLIC_COLLECTION = 'as:Public';
44 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
45 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event'];
46 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
49 * Checks if the web request is done for the AP protocol
53 public static function isRequest()
55 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
56 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
60 * Checks incoming message from the inbox
64 * @param integer $uid User ID
66 public static function processInbox($body, $header, $uid)
68 $http_signer = HTTPSignature::getSigner($body, $header);
69 if (empty($http_signer)) {
70 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
73 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
76 $activity = json_decode($body, true);
78 if (empty($activity)) {
79 logger('Invalid body.', LOGGER_DEBUG);
83 $ldactivity = JsonLD::compact($activity);
85 $actor = JsonLD::fetchElement($ldactivity, 'as:actor');
87 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
89 if (LDSignature::isSigned($activity)) {
90 $ld_signer = LDSignature::getSigner($activity);
91 if (empty($ld_signer)) {
92 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
94 if (!empty($ld_signer && ($actor == $http_signer))) {
95 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
97 } elseif (!empty($ld_signer)) {
98 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
100 } elseif ($actor == $http_signer) {
101 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
102 $trust_source = true;
104 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
105 $trust_source = false;
107 } elseif ($actor == $http_signer) {
108 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
109 $trust_source = true;
111 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
112 $trust_source = false;
115 self::processActivity($ldactivity, $body, $uid, $trust_source);
119 * Fetches the object type for a given object id
121 * @param array $activity
122 * @param string $object_id Object ID of the the provided object
124 * @return string with object type
126 private static function fetchObjectType($activity, $object_id)
129 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
130 if (!empty($object_type)) {
134 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
135 // We just assume "note" since it doesn't make a difference for the further processing
139 $profile = APContact::getByURL($object_id);
140 if (!empty($profile['type'])) {
141 return 'as:' . $profile['type'];
144 $data = ActivityPub::fetchContent($object_id);
146 $object = JsonLD::compact($data);
147 $type = JsonLD::fetchElement($object, '@type');
157 * Prepare the object array
159 * @param array $activity
160 * @param integer $uid User ID
161 * @param $trust_source
163 * @return array with object data
165 private static function prepareObjectData($activity, $uid, &$trust_source)
167 $actor = JsonLD::fetchElement($activity, 'as:actor');
169 logger('Empty actor', LOGGER_DEBUG);
173 $type = JsonLD::fetchElement($activity, '@type');
175 // Fetch all receivers from to, cc, bto and bcc
176 $receivers = self::getReceivers($activity, $actor);
178 // When it is a delivery to a personal inbox we add that user to the receivers
180 $owner = User::getOwnerDataById($uid);
181 $additional = ['uid:' . $uid => $uid];
182 $receivers = array_merge($receivers, $additional);
185 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
187 $object_id = JsonLD::fetchElement($activity, 'as:object');
188 if (empty($object_id)) {
189 logger('No object found', LOGGER_DEBUG);
193 $object_type = self::fetchObjectType($activity, $object_id);
195 // Fetch the content only on activities where this matters
196 if (in_array($type, ['as:Create', 'as:Announce'])) {
197 if ($type == 'as:Announce') {
198 $trust_source = false;
200 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source);
201 if (empty($object_data)) {
202 logger("Object data couldn't be processed", LOGGER_DEBUG);
205 // We had been able to retrieve the object data - so we can trust the source
206 $trust_source = true;
207 } elseif (in_array($type, ['as:Like', 'as:Dislike'])) {
208 // Create a mostly empty array out of the activity data (instead of the object).
209 // This way we later don't have to check for the existence of ech individual array element.
210 $object_data = self::processObject($activity);
211 $object_data['name'] = $type;
212 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor');
213 $object_data['object_id'] = $object_id;
214 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
217 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
218 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object');
219 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor');
220 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
221 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
224 $object_data = self::addActivityFields($object_data, $activity);
226 if (empty($object_data['object_type'])) {
227 $object_data['object_type'] = $object_type;
230 $object_data['type'] = $type;
231 $object_data['actor'] = $actor;
232 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
234 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
240 * Store the unprocessed data into the conversation table
241 * This has to be done outside the regular function,
242 * since we store everything - not only item posts.
244 * @param array $activity Array with activity data
245 * @param string $body The raw message
247 private static function storeConversation($activity, $body)
249 if (empty($body) || empty($activity['id'])) {
254 'protocol' => Conversation::PARCEL_ACTIVITYPUB,
255 'item-uri' => $activity['id'],
256 'reply-to-uri' => defaults($activity, 'reply-to-id', ''),
257 'conversation-href' => defaults($activity, 'context', ''),
258 'conversation-uri' => defaults($activity, 'conversation', ''),
260 'received' => DateTimeFormat::utcNow()];
262 DBA::insert('conversation', $conversation, true);
266 * Processes the activity object
268 * @param array $activity Array with activity data
269 * @param string $body
270 * @param integer $uid User ID
271 * @param boolean $trust_source Do we trust the source?
273 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
275 $type = JsonLD::fetchElement($activity, '@type');
277 logger('Empty type', LOGGER_DEBUG);
281 if (!JsonLD::fetchElement($activity, 'as:object')) {
282 logger('Empty object', LOGGER_DEBUG);
286 if (!JsonLD::fetchElement($activity, 'as:actor')) {
287 logger('Empty actor', LOGGER_DEBUG);
292 // $trust_source is called by reference and is set to true if the content was retrieved successfully
293 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
294 if (empty($object_data)) {
295 logger('No object data found', LOGGER_DEBUG);
299 if (!$trust_source) {
300 logger('No trust for activity type "' . $type . '", so we quit now.', LOGGER_DEBUG);
304 self::storeConversation($object_data, $body);
306 // Internal flag for thread completion. See Processor.php
307 if (!empty($activity['thread-completion'])) {
308 $object_data['thread-completion'] = $activity['thread-completion'];
314 ActivityPub\Processor::createItem($object_data);
318 ActivityPub\Processor::likeItem($object_data);
322 ActivityPub\Processor::dislikeItem($object_data);
326 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
328 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
329 ActivityPub\Processor::updatePerson($object_data, $body);
334 if ($object_data['object_type'] == 'as:Tombstone') {
335 ActivityPub\Processor::deleteItem($object_data, $body);
336 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
337 ActivityPub\Processor::deletePerson($object_data, $body);
342 ActivityPub\Processor::followUser($object_data);
346 if ($object_data['object_type'] == 'as:Follow') {
347 ActivityPub\Processor::acceptFollowUser($object_data);
352 if ($object_data['object_type'] == 'as:Follow') {
353 ActivityPub\Processor::rejectFollowUser($object_data);
358 if ($object_data['object_type'] == 'as:Follow') {
359 ActivityPub\Processor::undoFollowUser($object_data);
360 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
361 ActivityPub\Processor::undoActivity($object_data);
366 logger('Unknown activity: ' . $type, LOGGER_DEBUG);
372 * Fetch the receiver list from an activity array
374 * @param array $activity
375 * @param string $actor
377 * @return array with receivers (user id)
379 private static function getReceivers($activity, $actor)
383 // When it is an answer, we inherite the receivers from the parent
384 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo');
385 if (!empty($replyto)) {
386 $parents = Item::select(['uid'], ['uri' => $replyto]);
387 while ($parent = Item::fetch($parents)) {
388 $receivers['uid:' . $parent['uid']] = $parent['uid'];
392 if (!empty($actor)) {
393 $profile = APContact::getByURL($actor);
394 $followers = defaults($profile, 'followers', '');
396 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
398 logger('Empty actor', LOGGER_DEBUG);
402 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
403 $receiver_list = JsonLD::fetchElementArray($activity, $element);
404 if (empty($receiver_list)) {
408 foreach ($receiver_list as $receiver) {
409 if ($receiver == self::PUBLIC_COLLECTION) {
410 $receivers['uid:0'] = 0;
413 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
414 // This will most likely catch all OStatus connections to Mastodon
415 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
416 , 'archive' => false, 'pending' => false];
417 $contacts = DBA::select('contact', ['uid'], $condition);
418 while ($contact = DBA::fetch($contacts)) {
419 if ($contact['uid'] != 0) {
420 $receivers['uid:' . $contact['uid']] = $contact['uid'];
423 DBA::close($contacts);
426 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
427 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
428 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
429 'network' => $networks, 'archive' => false, 'pending' => false];
430 $contacts = DBA::select('contact', ['uid'], $condition);
431 while ($contact = DBA::fetch($contacts)) {
432 if ($contact['uid'] != 0) {
433 $receivers['uid:' . $contact['uid']] = $contact['uid'];
436 DBA::close($contacts);
440 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
441 $contact = DBA::selectFirst('contact', ['uid'], $condition);
442 if (!DBA::isResult($contact)) {
445 $receivers['uid:' . $contact['uid']] = $contact['uid'];
449 self::switchContacts($receivers, $actor);
455 * Switches existing contacts to ActivityPub
457 * @param integer $cid Contact ID
458 * @param integer $uid User ID
459 * @param string $url Profile URL
461 public static function switchContact($cid, $uid, $url)
463 $profile = ActivityPub::probeProfile($url);
464 if (empty($profile)) {
468 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
470 $photo = defaults($profile, 'photo', null);
471 unset($profile['photo']);
472 unset($profile['baseurl']);
474 $profile['nurl'] = normalise_link($profile['url']);
475 DBA::update('contact', $profile, ['id' => $cid]);
477 Contact::updateAvatar($photo, $uid, $cid);
479 // Send a new follow request to be sure that the connection still exists
480 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
481 ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
482 logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG);
492 private static function switchContacts($receivers, $actor)
498 foreach ($receivers as $receiver) {
499 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
500 if (DBA::isResult($contact)) {
501 self::switchContact($contact['id'], $receiver, $actor);
504 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
505 if (DBA::isResult($contact)) {
506 self::switchContact($contact['id'], $receiver, $actor);
514 * @param $object_data
515 * @param array $activity
519 private static function addActivityFields($object_data, $activity)
521 if (!empty($activity['published']) && empty($object_data['published'])) {
522 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
525 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
526 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid');
529 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
535 * Fetches the object data from external ressources if needed
537 * @param string $object_id Object ID of the the provided object
538 * @param array $object The provided object array
539 * @param boolean $trust_source Do we trust the provided object?
541 * @return array with trusted and valid object data
543 private static function fetchObject($object_id, $object = [], $trust_source = false)
545 // By fetching the type we check if the object is complete.
546 $type = JsonLD::fetchElement($object, '@type');
548 if (!$trust_source || empty($type)) {
549 $data = ActivityPub::fetchContent($object_id);
551 $object = JsonLD::compact($data);
552 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
554 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
556 $item = Item::selectFirst([], ['uri' => $object_id]);
557 if (!DBA::isResult($item)) {
558 logger('Object with url ' . $object_id . ' was not found locally.', LOGGER_DEBUG);
561 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
562 $data = ActivityPub\Transmitter::createNote($item);
563 $object = JsonLD::compact($data);
566 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
569 $type = JsonLD::fetchElement($object, '@type');
572 logger('Empty type', LOGGER_DEBUG);
576 if (in_array($type, self::CONTENT_TYPES)) {
577 return self::processObject($object);
580 if ($type == 'as:Announce') {
581 $object_id = JsonLD::fetchElement($object, 'object');
582 if (empty($object_id)) {
585 return self::fetchObject($object_id);
588 logger('Unhandled object type: ' . $type, LOGGER_DEBUG);
592 * Convert tags from JSON-LD format into a simplified format
594 * @param array $tags Tags in JSON-LD format
596 * @return array with tags in a simplified format
598 private static function processTags($tags)
606 foreach ($tags as $tag) {
611 $taglist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
612 'href' => JsonLD::fetchElement($tag, 'as:href'),
613 'name' => JsonLD::fetchElement($tag, 'as:name')];
619 * Convert attachments from JSON-LD format into a simplified format
621 * @param array $attachments Attachments in JSON-LD format
623 * @return array with attachmants in a simplified format
625 private static function processAttachments($attachments)
629 if (empty($attachments)) {
633 foreach ($attachments as $attachment) {
634 if (empty($attachment)) {
638 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
639 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType'),
640 'name' => JsonLD::fetchElement($attachment, 'as:name'),
641 'url' => JsonLD::fetchElement($attachment, 'as:url')];
647 * Fetches data from the object part of an activity
649 * @param array $object
653 private static function processObject($object)
655 if (!JsonLD::fetchElement($object, '@id')) {
660 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
661 $object_data['id'] = JsonLD::fetchElement($object, '@id');
663 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo');
665 if (empty($object_data['reply-to-id'])) {
666 $object_data['reply-to-id'] = $object_data['id'];
669 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
670 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
672 if (empty($object_data['updated'])) {
673 $object_data['updated'] = $object_data['published'];
676 if (empty($object_data['published']) && !empty($object_data['updated'])) {
677 $object_data['published'] = $object_data['updated'];
680 $actor = JsonLD::fetchElement($object, 'as:attributedTo');
682 $actor = JsonLD::fetchElement($object, 'as:actor');
685 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid');
686 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment');
687 $object_data['actor'] = $object_data['author'] = $actor;
688 $object_data['context'] = JsonLD::fetchElement($object, 'as:context');
689 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation');
690 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
691 $object_data['name'] = JsonLD::fetchElement($object, 'as:name');
692 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary');
693 $object_data['content'] = JsonLD::fetchElement($object, 'as:content');
694 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
695 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
696 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
697 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
698 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
699 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
700 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
701 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
702 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
703 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
704 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
705 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url');
707 // Special treatment for Hubzilla links
708 if (is_array($object_data['alternate-url'])) {
709 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href');
711 if (!is_string($object_data['alternate-url'])) {
712 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href');
716 $object_data['receiver'] = self::getReceivers($object, $object_data['actor']);
718 // Common object data:
721 // @context, type, actor, signature, mediaType, duration, replies, icon
723 // Also missing: (Defined in the standard, but currently unused)
724 // audience, preview, endTime, startTime, image
729 // contentMap, announcement_count, announcements, context_id, likes, like_count
730 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
735 // category, licence, language, commentsEnabled
738 // views, waitTranscoding, state, support, subtitleLanguage
739 // likes, dislikes, shares, comments