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;
19 * @brief ActivityPub Receiver Protocol class
22 * - Update (Image, Video, Article, Note)
26 * Check what this is meant to do:
32 * - Undo Accept (Problem: This could invert a contact accept or an event accept)
36 const PUBLIC_COLLECTION = 'as:Public';
37 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
38 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image'];
39 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
42 * Checks if the web request is done for the AP protocol
46 public static function isRequest()
48 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
49 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
53 * Checks incoming message from the inbox
57 * @param integer $uid User ID
59 public static function processInbox($body, $header, $uid)
61 $http_signer = HTTPSignature::getSigner($body, $header);
62 if (empty($http_signer)) {
63 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
66 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
69 $activity = json_decode($body, true);
71 if (empty($activity)) {
72 logger('Invalid body.', LOGGER_DEBUG);
76 $ldactivity = JsonLD::compact($activity);
78 $actor = JsonLD::fetchElement($ldactivity, 'as:actor');
80 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
82 if (LDSignature::isSigned($activity)) {
83 $ld_signer = LDSignature::getSigner($activity);
84 if (empty($ld_signer)) {
85 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
87 if (!empty($ld_signer && ($actor == $http_signer))) {
88 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
90 } elseif (!empty($ld_signer)) {
91 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
93 } elseif ($actor == $http_signer) {
94 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
97 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
98 $trust_source = false;
100 } elseif ($actor == $http_signer) {
101 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
102 $trust_source = true;
104 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
105 $trust_source = false;
108 self::processActivity($ldactivity, $body, $uid, $trust_source);
112 * Fetches the object type for a given object id
114 * @param array $activity
115 * @param string $object_id Object ID of the the provided object
117 * @return string with object type
119 private static function fetchObjectType($activity, $object_id)
122 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
123 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: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');
217 $object_data = self::addActivityFields($object_data, $activity);
219 if (empty($object_data['object_type'])) {
220 $object_data['object_type'] = $object_type;
223 $object_data['type'] = $type;
224 $object_data['actor'] = $actor;
225 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
227 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
233 * Processes the activity object
235 * @param array $activity Array with activity data
236 * @param string $body
237 * @param integer $uid User ID
238 * @param boolean $trust_source Do we trust the source?
240 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
242 $type = JsonLD::fetchElement($activity, '@type');
244 logger('Empty type', LOGGER_DEBUG);
248 if (!JsonLD::fetchElement($activity, 'as:object')) {
249 logger('Empty object', LOGGER_DEBUG);
253 if (!JsonLD::fetchElement($activity, 'as:actor')) {
254 logger('Empty actor', LOGGER_DEBUG);
259 // $trust_source is called by reference and is set to true if the content was retrieved successfully
260 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
261 if (empty($object_data)) {
262 logger('No object data found', LOGGER_DEBUG);
266 if (!$trust_source) {
267 logger('No trust for activity type "' . $type . '", so we quit now.', LOGGER_DEBUG);
271 // Internal flag for thread completion. See Processor.php
272 if (!empty($activity['thread-completion'])) {
273 $object_data['thread-completion'] = $activity['thread-completion'];
279 ActivityPub\Processor::createItem($object_data, $body);
283 ActivityPub\Processor::likeItem($object_data, $body);
287 ActivityPub\Processor::dislikeItem($object_data, $body);
291 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
293 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
294 ActivityPub\Processor::updatePerson($object_data, $body);
299 if ($object_data['object_type'] == 'as:Tombstone') {
300 ActivityPub\Processor::deleteItem($object_data, $body);
301 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
302 ActivityPub\Processor::deletePerson($object_data, $body);
307 ActivityPub\Processor::followUser($object_data);
311 if ($object_data['object_type'] == 'as:Follow') {
312 ActivityPub\Processor::acceptFollowUser($object_data);
317 if ($object_data['object_type'] == 'as:Follow') {
318 ActivityPub\Processor::rejectFollowUser($object_data);
323 if ($object_data['object_type'] == 'as:Follow') {
324 ActivityPub\Processor::undoFollowUser($object_data);
325 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
326 ActivityPub\Processor::undoActivity($object_data);
331 logger('Unknown activity: ' . $type, LOGGER_DEBUG);
337 * Fetch the receiver list from an activity array
339 * @param array $activity
340 * @param string $actor
342 * @return array with receivers (user id)
344 private static function getReceivers($activity, $actor)
348 // When it is an answer, we inherite the receivers from the parent
349 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo');
350 if (!empty($replyto)) {
351 $parents = Item::select(['uid'], ['uri' => $replyto]);
352 while ($parent = Item::fetch($parents)) {
353 $receivers['uid:' . $parent['uid']] = $parent['uid'];
357 if (!empty($actor)) {
358 $profile = APContact::getByURL($actor);
359 $followers = defaults($profile, 'followers', '');
361 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
363 logger('Empty actor', LOGGER_DEBUG);
367 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
368 $receiver_list = JsonLD::fetchElementArray($activity, $element);
369 if (empty($receiver_list)) {
373 foreach ($receiver_list as $receiver) {
374 if ($receiver == self::PUBLIC_COLLECTION) {
375 $receivers['uid:0'] = 0;
378 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
379 // This will most likely catch all OStatus connections to Mastodon
380 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
381 , 'archive' => false, 'pending' => false];
382 $contacts = DBA::select('contact', ['uid'], $condition);
383 while ($contact = DBA::fetch($contacts)) {
384 if ($contact['uid'] != 0) {
385 $receivers['uid:' . $contact['uid']] = $contact['uid'];
388 DBA::close($contacts);
391 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
392 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
393 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
394 $contacts = DBA::select('contact', ['uid'], $condition);
395 while ($contact = DBA::fetch($contacts)) {
396 if ($contact['uid'] != 0) {
397 $receivers['uid:' . $contact['uid']] = $contact['uid'];
400 DBA::close($contacts);
404 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
405 $contact = DBA::selectFirst('contact', ['uid'], $condition);
406 if (!DBA::isResult($contact)) {
409 $receivers['uid:' . $contact['uid']] = $contact['uid'];
413 self::switchContacts($receivers, $actor);
419 * Switches existing contacts to ActivityPub
421 * @param integer $cid Contact ID
422 * @param integer $uid User ID
423 * @param string $url Profile URL
425 private static function switchContact($cid, $uid, $url)
427 $profile = ActivityPub::probeProfile($url);
428 if (empty($profile)) {
432 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
434 $photo = $profile['photo'];
435 unset($profile['photo']);
436 unset($profile['baseurl']);
438 $profile['nurl'] = normalise_link($profile['url']);
439 DBA::update('contact', $profile, ['id' => $cid]);
441 Contact::updateAvatar($photo, $uid, $cid);
443 // Send a new follow request to be sure that the connection still exists
444 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
445 ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
446 logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG);
456 private static function switchContacts($receivers, $actor)
462 foreach ($receivers as $receiver) {
463 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
464 if (DBA::isResult($contact)) {
465 self::switchContact($contact['id'], $receiver, $actor);
468 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
469 if (DBA::isResult($contact)) {
470 self::switchContact($contact['id'], $receiver, $actor);
478 * @param $object_data
479 * @param array $activity
483 private static function addActivityFields($object_data, $activity)
485 if (!empty($activity['published']) && empty($object_data['published'])) {
486 $object_data['published'] = JsonLD::fetchElement($activity, 'published', '@value');
489 if (!empty($activity['updated']) && empty($object_data['updated'])) {
490 $object_data['updated'] = JsonLD::fetchElement($activity, 'updated', '@value');
493 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
494 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid');
497 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
498 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo');
501 if (!empty($activity['instrument'])) {
502 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
508 * Fetches the object data from external ressources if needed
510 * @param string $object_id Object ID of the the provided object
511 * @param array $object The provided object array
512 * @param boolean $trust_source Do we trust the provided object?
514 * @return array with trusted and valid object data
516 private static function fetchObject($object_id, $object = [], $trust_source = false)
518 // By fetching the type we check if the object is complete.
519 $type = JsonLD::fetchElement($object, '@type');
521 if (!$trust_source || empty($type)) {
522 $data = ActivityPub::fetchContent($object_id);
524 $object = JsonLD::compact($data);
525 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
527 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
529 $item = Item::selectFirst([], ['uri' => $object_id]);
530 if (!DBA::isResult($item)) {
531 logger('Object with url ' . $object_id . ' was not found locally.', LOGGER_DEBUG);
534 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
535 $data = ActivityPub\Transmitter::createNote($item);
536 $object = JsonLD::compact($data);
539 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
542 $type = JsonLD::fetchElement($object, '@type');
545 logger('Empty type', LOGGER_DEBUG);
549 if (in_array($type, self::CONTENT_TYPES)) {
550 return self::processObject($object);
553 if ($type == 'as:Announce') {
554 $object_id = JsonLD::fetchElement($object, 'object');
555 if (empty($object_id)) {
558 return self::fetchObject($object_id);
561 logger('Unhandled object type: ' . $type, LOGGER_DEBUG);
565 * Convert tags from JSON-LD format into a simplified format
567 * @param array $tags Tags in JSON-LD format
569 * @return array with tags in a simplified format
571 private static function processTags($tags)
579 foreach ($tags as $tag) {
584 $taglist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
585 'href' => JsonLD::fetchElement($tag, 'as:href'),
586 'name' => JsonLD::fetchElement($tag, 'as:name')];
592 * Convert attachments from JSON-LD format into a simplified format
594 * @param array $attachments Attachments in JSON-LD format
596 * @return array with attachmants in a simplified format
598 private static function processAttachments($attachments)
602 if (empty($attachments)) {
606 foreach ($attachments as $attachment) {
607 if (empty($attachment)) {
611 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
612 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType'),
613 'name' => JsonLD::fetchElement($attachment, 'as:name'),
614 'url' => JsonLD::fetchElement($attachment, 'as:url')];
620 * Fetches data from the object part of an activity
622 * @param array $object
626 private static function processObject($object)
628 if (!JsonLD::fetchElement($object, '@id')) {
633 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
634 $object_data['id'] = JsonLD::fetchElement($object, '@id');
636 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo');
638 if (empty($object_data['reply-to-id'])) {
639 $object_data['reply-to-id'] = $object_data['id'];
642 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
643 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
645 if (empty($object_data['updated'])) {
646 $object_data['updated'] = $object_data['published'];
649 if (empty($object_data['published']) && !empty($object_data['updated'])) {
650 $object_data['published'] = $object_data['updated'];
653 $actor = JsonLD::fetchElement($object, 'as:attributedTo');
655 $actor = JsonLD::fetchElement($object, 'as:actor');
658 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid');
659 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment');
660 $object_data['actor'] = $object_data['author'] = $actor;
661 $object_data['context'] = JsonLD::fetchElement($object, 'as:context');
662 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation');
663 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
664 $object_data['name'] = JsonLD::fetchElement($object, 'as:name');
665 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary');
666 $object_data['content'] = JsonLD::fetchElement($object, 'as:content');
667 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
668 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
669 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
670 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
671 // $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service'); // todo
672 $object_data['service'] = null;
673 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url');
675 // Special treatment for Hubzilla links
676 if (is_array($object_data['alternate-url'])) {
677 if (!empty($object['as:url'])) {
678 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href');
680 $object_data['alternate-url'] = null;
684 $object_data['receiver'] = self::getReceivers($object, $object_data['actor']);
686 // Common object data:
689 // @context, type, actor, signature, mediaType, duration, replies, icon
691 // Also missing: (Defined in the standard, but currently unused)
692 // audience, preview, endTime, startTime, generator, image
697 // contentMap, announcement_count, announcements, context_id, likes, like_count
698 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
703 // category, licence, language, commentsEnabled
706 // views, waitTranscoding, state, support, subtitleLanguage
707 // likes, dislikes, shares, comments