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
26 * Check what this is meant to do:
35 const PUBLIC_COLLECTION = 'as:Public';
36 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
37 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event'];
38 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
41 * Checks if the web request is done for the AP protocol
45 public static function isRequest()
47 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
48 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
52 * Checks incoming message from the inbox
56 * @param integer $uid User ID
58 public static function processInbox($body, $header, $uid)
60 $http_signer = HTTPSignature::getSigner($body, $header);
61 if (empty($http_signer)) {
62 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
65 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
68 $activity = json_decode($body, true);
70 if (empty($activity)) {
71 logger('Invalid body.', LOGGER_DEBUG);
75 $ldactivity = JsonLD::compact($activity);
77 $actor = JsonLD::fetchElement($ldactivity, 'as:actor');
79 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
81 if (LDSignature::isSigned($activity)) {
82 $ld_signer = LDSignature::getSigner($activity);
83 if (empty($ld_signer)) {
84 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
86 if (!empty($ld_signer && ($actor == $http_signer))) {
87 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
89 } elseif (!empty($ld_signer)) {
90 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
92 } elseif ($actor == $http_signer) {
93 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
96 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
97 $trust_source = false;
99 } elseif ($actor == $http_signer) {
100 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
101 $trust_source = true;
103 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
104 $trust_source = false;
107 self::processActivity($ldactivity, $body, $uid, $trust_source);
111 * Fetches the object type for a given object id
113 * @param array $activity
114 * @param string $object_id Object ID of the the provided object
116 * @return string with object type
118 private static function fetchObjectType($activity, $object_id)
120 if (!empty($activity['as:object'])) {
121 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
122 if (!empty($object_type)) {
127 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
128 // We just assume "note" since it doesn't make a difference for the further processing
132 $profile = APContact::getByURL($object_id);
133 if (!empty($profile['type'])) {
134 return 'as:' . $profile['type'];
137 $data = ActivityPub::fetchContent($object_id);
139 $object = JsonLD::compact($data);
140 $type = JsonLD::fetchElement($object, '@type');
150 * Prepare the object array
152 * @param array $activity
153 * @param integer $uid User ID
154 * @param $trust_source
156 * @return array with object data
158 private static function prepareObjectData($activity, $uid, &$trust_source)
160 $actor = JsonLD::fetchElement($activity, 'as:actor');
162 logger('Empty actor', LOGGER_DEBUG);
166 $type = JsonLD::fetchElement($activity, '@type');
168 // Fetch all receivers from to, cc, bto and bcc
169 $receivers = self::getReceivers($activity, $actor);
171 // When it is a delivery to a personal inbox we add that user to the receivers
173 $owner = User::getOwnerDataById($uid);
174 $additional = ['uid:' . $uid => $uid];
175 $receivers = array_merge($receivers, $additional);
178 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
180 $object_id = JsonLD::fetchElement($activity, 'as:object');
181 if (empty($object_id)) {
182 logger('No object found', LOGGER_DEBUG);
186 $object_type = self::fetchObjectType($activity, $object_id);
188 // Fetch the content only on activities where this matters
189 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
190 if ($type == 'as:Announce') {
191 $trust_source = false;
193 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source);
194 if (empty($object_data)) {
195 logger("Object data couldn't be processed", LOGGER_DEBUG);
198 // We had been able to retrieve the object data - so we can trust the source
199 $trust_source = true;
200 } elseif (in_array($type, ['as:Like', 'as:Dislike'])) {
201 // Create a mostly empty array out of the activity data (instead of the object).
202 // This way we later don't have to check for the existence of ech individual array element.
203 $object_data = self::processObject($activity);
204 $object_data['name'] = $type;
205 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor');
206 $object_data['object_id'] = $object_id;
207 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
210 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
211 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object');
212 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor');
213 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
214 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
216 // An Undo is done on the object of an object, so we need that type as well
217 if ($type == 'as:Undo') {
218 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object']);
222 $object_data = self::addActivityFields($object_data, $activity);
224 if (empty($object_data['object_type'])) {
225 $object_data['object_type'] = $object_type;
228 $object_data['type'] = $type;
229 $object_data['actor'] = $actor;
230 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
232 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
238 * Store the unprocessed data into the conversation table
239 * This has to be done outside the regular function,
240 * since we store everything - not only item posts.
242 * @param array $activity Array with activity data
243 * @param string $body The raw message
245 private static function storeConversation($activity, $body)
247 if (empty($body) || empty($activity['id'])) {
252 'protocol' => Conversation::PARCEL_ACTIVITYPUB,
253 'item-uri' => $activity['id'],
254 'reply-to-uri' => defaults($activity, 'reply-to-id', ''),
255 'conversation-href' => defaults($activity, 'context', ''),
256 'conversation-uri' => defaults($activity, 'conversation', ''),
258 'received' => DateTimeFormat::utcNow()];
260 DBA::insert('conversation', $conversation, true);
264 * Processes the activity object
266 * @param array $activity Array with activity data
267 * @param string $body
268 * @param integer $uid User ID
269 * @param boolean $trust_source Do we trust the source?
271 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
273 $type = JsonLD::fetchElement($activity, '@type');
275 logger('Empty type', LOGGER_DEBUG);
279 if (!JsonLD::fetchElement($activity, 'as:object')) {
280 logger('Empty object', LOGGER_DEBUG);
284 if (!JsonLD::fetchElement($activity, 'as:actor')) {
285 logger('Empty actor', LOGGER_DEBUG);
290 // $trust_source is called by reference and is set to true if the content was retrieved successfully
291 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
292 if (empty($object_data)) {
293 logger('No object data found', LOGGER_DEBUG);
297 if (!$trust_source) {
298 logger('No trust for activity type "' . $type . '", so we quit now.', LOGGER_DEBUG);
302 self::storeConversation($object_data, $body);
304 // Internal flag for thread completion. See Processor.php
305 if (!empty($activity['thread-completion'])) {
306 $object_data['thread-completion'] = $activity['thread-completion'];
312 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
313 ActivityPub\Processor::createItem($object_data);
318 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
319 ActivityPub\Processor::createActivity($object_data, ACTIVITY_LIKE);
324 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
325 ActivityPub\Processor::createActivity($object_data, ACTIVITY_DISLIKE);
329 case 'as:TentativeAccept':
330 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
331 ActivityPub\Processor::createActivity($object_data, ACTIVITY_ATTENDMAYBE);
336 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
337 ActivityPub\Processor::updateItem($object_data);
338 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
339 ActivityPub\Processor::updatePerson($object_data, $body);
344 if ($object_data['object_type'] == 'as:Tombstone') {
345 ActivityPub\Processor::deleteItem($object_data, $body);
346 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
347 ActivityPub\Processor::deletePerson($object_data, $body);
352 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
353 ActivityPub\Processor::followUser($object_data);
358 if ($object_data['object_type'] == 'as:Follow') {
359 ActivityPub\Processor::acceptFollowUser($object_data);
360 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
361 ActivityPub\Processor::createActivity($object_data, ACTIVITY_ATTEND);
366 if ($object_data['object_type'] == 'as:Follow') {
367 ActivityPub\Processor::rejectFollowUser($object_data);
368 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
369 ActivityPub\Processor::createActivity($object_data, ACTIVITY_ATTENDNO);
374 if (($object_data['object_type'] == 'as:Follow') &&
375 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
376 ActivityPub\Processor::undoFollowUser($object_data);
377 } elseif (($object_data['object_type'] == 'as:Accept') &&
378 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
379 ActivityPub\Processor::rejectFollowUser($object_data);
380 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
381 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
382 ActivityPub\Processor::undoActivity($object_data);
387 logger('Unknown activity: ' . $type . ' ' . $object_data['object_type'], LOGGER_DEBUG);
393 * Fetch the receiver list from an activity array
395 * @param array $activity
396 * @param string $actor
398 * @return array with receivers (user id)
400 private static function getReceivers($activity, $actor)
404 // When it is an answer, we inherite the receivers from the parent
405 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo');
406 if (!empty($replyto)) {
407 $parents = Item::select(['uid'], ['uri' => $replyto]);
408 while ($parent = Item::fetch($parents)) {
409 $receivers['uid:' . $parent['uid']] = $parent['uid'];
413 if (!empty($actor)) {
414 $profile = APContact::getByURL($actor);
415 $followers = defaults($profile, 'followers', '');
417 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
419 logger('Empty actor', LOGGER_DEBUG);
423 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
424 $receiver_list = JsonLD::fetchElementArray($activity, $element);
425 if (empty($receiver_list)) {
429 foreach ($receiver_list as $receiver) {
430 if ($receiver == self::PUBLIC_COLLECTION) {
431 $receivers['uid:0'] = 0;
434 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
435 // This will most likely catch all OStatus connections to Mastodon
436 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
437 , 'archive' => false, 'pending' => false];
438 $contacts = DBA::select('contact', ['uid'], $condition);
439 while ($contact = DBA::fetch($contacts)) {
440 if ($contact['uid'] != 0) {
441 $receivers['uid:' . $contact['uid']] = $contact['uid'];
444 DBA::close($contacts);
447 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
448 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
449 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
450 'network' => $networks, 'archive' => false, 'pending' => false];
451 $contacts = DBA::select('contact', ['uid'], $condition);
452 while ($contact = DBA::fetch($contacts)) {
453 if ($contact['uid'] != 0) {
454 $receivers['uid:' . $contact['uid']] = $contact['uid'];
457 DBA::close($contacts);
461 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
462 $contact = DBA::selectFirst('contact', ['uid'], $condition);
463 if (!DBA::isResult($contact)) {
466 $receivers['uid:' . $contact['uid']] = $contact['uid'];
470 self::switchContacts($receivers, $actor);
476 * Switches existing contacts to ActivityPub
478 * @param integer $cid Contact ID
479 * @param integer $uid User ID
480 * @param string $url Profile URL
482 public static function switchContact($cid, $uid, $url)
484 $profile = ActivityPub::probeProfile($url);
485 if (empty($profile)) {
489 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
491 $photo = defaults($profile, 'photo', null);
492 unset($profile['photo']);
493 unset($profile['baseurl']);
495 $profile['nurl'] = normalise_link($profile['url']);
496 DBA::update('contact', $profile, ['id' => $cid]);
498 Contact::updateAvatar($photo, $uid, $cid);
500 // Send a new follow request to be sure that the connection still exists
501 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
502 ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
503 logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG);
513 private static function switchContacts($receivers, $actor)
519 foreach ($receivers as $receiver) {
520 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
521 if (DBA::isResult($contact)) {
522 self::switchContact($contact['id'], $receiver, $actor);
525 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
526 if (DBA::isResult($contact)) {
527 self::switchContact($contact['id'], $receiver, $actor);
535 * @param $object_data
536 * @param array $activity
540 private static function addActivityFields($object_data, $activity)
542 if (!empty($activity['published']) && empty($object_data['published'])) {
543 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
546 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
547 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid');
550 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
556 * Fetches the object data from external ressources if needed
558 * @param string $object_id Object ID of the the provided object
559 * @param array $object The provided object array
560 * @param boolean $trust_source Do we trust the provided object?
562 * @return array with trusted and valid object data
564 private static function fetchObject($object_id, $object = [], $trust_source = false)
566 // By fetching the type we check if the object is complete.
567 $type = JsonLD::fetchElement($object, '@type');
569 if (!$trust_source || empty($type)) {
570 $data = ActivityPub::fetchContent($object_id);
572 $object = JsonLD::compact($data);
573 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
575 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
577 $item = Item::selectFirst([], ['uri' => $object_id]);
578 if (!DBA::isResult($item)) {
579 logger('Object with url ' . $object_id . ' was not found locally.', LOGGER_DEBUG);
582 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
583 $data = ActivityPub\Transmitter::createNote($item);
584 $object = JsonLD::compact($data);
587 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
590 $type = JsonLD::fetchElement($object, '@type');
593 logger('Empty type', LOGGER_DEBUG);
597 if (in_array($type, self::CONTENT_TYPES)) {
598 return self::processObject($object);
601 if ($type == 'as:Announce') {
602 $object_id = JsonLD::fetchElement($object, 'object');
603 if (empty($object_id)) {
606 return self::fetchObject($object_id);
609 logger('Unhandled object type: ' . $type, LOGGER_DEBUG);
613 * Convert tags from JSON-LD format into a simplified format
615 * @param array $tags Tags in JSON-LD format
617 * @return array with tags in a simplified format
619 private static function processTags($tags)
627 foreach ($tags as $tag) {
632 $taglist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
633 'href' => JsonLD::fetchElement($tag, 'as:href'),
634 'name' => JsonLD::fetchElement($tag, 'as:name')];
640 * Convert attachments from JSON-LD format into a simplified format
642 * @param array $attachments Attachments in JSON-LD format
644 * @return array with attachmants in a simplified format
646 private static function processAttachments($attachments)
650 if (empty($attachments)) {
654 foreach ($attachments as $attachment) {
655 if (empty($attachment)) {
659 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
660 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType'),
661 'name' => JsonLD::fetchElement($attachment, 'as:name'),
662 'url' => JsonLD::fetchElement($attachment, 'as:url')];
668 * Fetches data from the object part of an activity
670 * @param array $object
674 private static function processObject($object)
676 if (!JsonLD::fetchElement($object, '@id')) {
681 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
682 $object_data['id'] = JsonLD::fetchElement($object, '@id');
684 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo');
686 if (empty($object_data['reply-to-id'])) {
687 $object_data['reply-to-id'] = $object_data['id'];
690 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
691 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
693 if (empty($object_data['updated'])) {
694 $object_data['updated'] = $object_data['published'];
697 if (empty($object_data['published']) && !empty($object_data['updated'])) {
698 $object_data['published'] = $object_data['updated'];
701 $actor = JsonLD::fetchElement($object, 'as:attributedTo');
703 $actor = JsonLD::fetchElement($object, 'as:actor');
706 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid');
707 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment');
708 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like');
709 $object_data['actor'] = $object_data['author'] = $actor;
710 $object_data['context'] = JsonLD::fetchElement($object, 'as:context');
711 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation');
712 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
713 $object_data['name'] = JsonLD::fetchElement($object, 'as:name');
714 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary');
715 $object_data['content'] = JsonLD::fetchElement($object, 'as:content');
716 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
717 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
718 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
719 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
720 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
721 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
722 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
723 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
724 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
725 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
726 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
727 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url');
729 // Special treatment for Hubzilla links
730 if (is_array($object_data['alternate-url'])) {
731 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href');
733 if (!is_string($object_data['alternate-url'])) {
734 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href');
738 $object_data['receiver'] = self::getReceivers($object, $object_data['actor']);
740 // Common object data:
743 // @context, type, actor, signature, mediaType, duration, replies, icon
745 // Also missing: (Defined in the standard, but currently unused)
746 // audience, preview, endTime, startTime, image
751 // contentMap, announcement_count, announcements, context_id, likes, like_count
752 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
757 // category, licence, language, commentsEnabled
760 // views, waitTranscoding, state, support, subtitleLanguage
761 // likes, dislikes, shares, comments