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)
35 * - Possibly using the LD-JSON parser
39 const PUBLIC_COLLECTION = 'as:Public';
40 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
41 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image'];
42 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
45 * Checks if the web request is done for the AP protocol
49 public static function isRequest()
51 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
52 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
56 * Checks incoming message from the inbox
60 * @param integer $uid User ID
62 public static function processInbox($body, $header, $uid)
64 $http_signer = HTTPSignature::getSigner($body, $header);
65 if (empty($http_signer)) {
66 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
69 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
72 $activity = json_decode($body, true);
74 if (empty($activity)) {
75 logger('Invalid body.', LOGGER_DEBUG);
79 $ldactivity = JsonLD::compact($activity);
81 $actor = JsonLD::fetchElement($ldactivity, 'as:actor');
83 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
85 if (LDSignature::isSigned($activity)) {
86 $ld_signer = LDSignature::getSigner($activity);
87 if (empty($ld_signer)) {
88 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
90 if (!empty($ld_signer && ($actor == $http_signer))) {
91 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
93 } elseif (!empty($ld_signer)) {
94 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
96 } elseif ($actor == $http_signer) {
97 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
100 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
101 $trust_source = false;
103 } elseif ($actor == $http_signer) {
104 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
105 $trust_source = true;
107 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
108 $trust_source = false;
111 self::processActivity($activity, $ldactivity, $body, $uid, $trust_source);
117 * @param array $activity
118 * @param integer $uid User ID
119 * @param $trust_source
123 private static function prepareObjectData($activity, $ldactivity, $uid, &$trust_source)
125 $actor = JsonLD::fetchElement($ldactivity, 'as:actor');
127 logger('Empty actor', LOGGER_DEBUG);
131 $type = JsonLD::fetchElement($ldactivity, '@type');
133 // Fetch all receivers from to, cc, bto and bcc
134 $receivers = self::getReceivers($ldactivity, $actor);
136 // When it is a delivery to a personal inbox we add that user to the receivers
138 $owner = User::getOwnerDataById($uid);
139 $additional = ['uid:' . $uid => $uid];
140 $receivers = array_merge($receivers, $additional);
143 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
145 $object_id = JsonLD::fetchElement($ldactivity, 'as:object');
146 if (empty($object_id)) {
147 logger('No object found', LOGGER_DEBUG);
151 // Fetch the content only on activities where this matters
152 if (in_array($type, ['as:Create', 'as:Announce'])) {
153 $object_data = self::fetchObject($object_id, $ldactivity['as:object'], $trust_source);
154 if (empty($object_data)) {
155 logger("Object data couldn't be processed", LOGGER_DEBUG);
158 // We had been able to retrieve the object data - so we can trust the source
159 $trust_source = true;
160 } elseif (in_array($type, ['as:Like', 'as:Dislike'])) {
161 // Create a mostly empty array out of the activity data (instead of the object).
162 // This way we later don't have to check for the existence of ech individual array element.
163 $object_data = self::processObject($ldactivity);
164 $object_data['name'] = $type;
165 $object_data['author'] = JsonLD::fetchElement($ldactivity, 'as:actor');
166 $object_data['object'] = $object_id;
167 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
170 $object_data['id'] = JsonLD::fetchElement($ldactivity, '@id');
171 $object_data['object'] = $ldactivity['as:object'];
172 $object_data['object_type'] = JsonLD::fetchElement($ldactivity, 'as:object', '@type');
175 $object_data = self::addActivityFields($object_data, $activity);
177 $object_data['type'] = $type;
178 $object_data['owner'] = $actor;
179 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
181 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
189 * @param array $activity
191 * @param integer $uid User ID
192 * @param $trust_source
194 public static function processActivity($activity, $ldactivity = '', $body = '', $uid = null, $trust_source = false)
196 if (empty($ldactivity)) {
197 $ldactivity = JsonLD::compact($activity);
200 $type = JsonLD::fetchElement($ldactivity, '@type');
202 logger('Empty type', LOGGER_DEBUG);
206 if (!JsonLD::fetchElement($ldactivity, 'as:object')) {
207 logger('Empty object', LOGGER_DEBUG);
211 if (!JsonLD::fetchElement($ldactivity, 'as:actor')) {
212 logger('Empty actor', LOGGER_DEBUG);
217 // $trust_source is called by reference and is set to true if the content was retrieved successfully
218 $object_data = self::prepareObjectData($activity, $ldactivity, $uid, $trust_source);
219 if (empty($object_data)) {
220 logger('No object data found', LOGGER_DEBUG);
224 if (!$trust_source) {
225 logger('No trust for activity type "' . $type . '", so we quit now.', LOGGER_DEBUG);
232 ActivityPub\Processor::createItem($object_data, $body);
236 ActivityPub\Processor::likeItem($object_data, $body);
240 ActivityPub\Processor::dislikeItem($object_data, $body);
244 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
246 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
247 ActivityPub\Processor::updatePerson($object_data, $body);
252 if ($object_data['object_type'] == 'as:Tombstone') {
253 ActivityPub\Processor::deleteItem($object_data, $body);
254 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
255 ActivityPub\Processor::deletePerson($object_data, $body);
260 ActivityPub\Processor::followUser($object_data);
264 if ($object_data['object_type'] == 'as:Follow') {
265 ActivityPub\Processor::acceptFollowUser($object_data);
270 if ($object_data['object_type'] == 'as:Follow') {
271 ActivityPub\Processor::rejectFollowUser($object_data);
276 if ($object_data['object_type'] == 'as:Follow') {
277 ActivityPub\Processor::undoFollowUser($object_data);
278 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
279 ActivityPub\Processor::undoActivity($object_data);
284 logger('Unknown activity: ' . $type, LOGGER_DEBUG);
290 * Fetch the receiver list from an activity array
292 * @param array $activity
293 * @param string $actor
295 * @return array with receivers (user id)
297 private static function getReceivers($activity, $actor)
301 // When it is an answer, we inherite the receivers from the parent
302 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo');
303 if (!empty($replyto)) {
304 $parents = Item::select(['uid'], ['uri' => $replyto]);
305 while ($parent = Item::fetch($parents)) {
306 $receivers['uid:' . $parent['uid']] = $parent['uid'];
310 if (!empty($actor)) {
311 $profile = APContact::getByURL($actor);
312 $followers = defaults($profile, 'followers', '');
314 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
316 logger('Empty actor', LOGGER_DEBUG);
320 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
321 $receiver_list = JsonLD::fetchElementArray($activity, $element);
322 if (empty($receiver_list)) {
326 foreach ($receiver_list as $receiver) {
327 if ($receiver == self::PUBLIC_COLLECTION) {
328 $receivers['uid:0'] = 0;
331 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
332 // This will most likely catch all OStatus connections to Mastodon
333 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
334 , 'archive' => false, 'pending' => false];
335 $contacts = DBA::select('contact', ['uid'], $condition);
336 while ($contact = DBA::fetch($contacts)) {
337 if ($contact['uid'] != 0) {
338 $receivers['uid:' . $contact['uid']] = $contact['uid'];
341 DBA::close($contacts);
344 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
345 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
346 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
347 $contacts = DBA::select('contact', ['uid'], $condition);
348 while ($contact = DBA::fetch($contacts)) {
349 if ($contact['uid'] != 0) {
350 $receivers['uid:' . $contact['uid']] = $contact['uid'];
353 DBA::close($contacts);
357 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
358 $contact = DBA::selectFirst('contact', ['uid'], $condition);
359 if (!DBA::isResult($contact)) {
362 $receivers['uid:' . $contact['uid']] = $contact['uid'];
366 self::switchContacts($receivers, $actor);
372 * Switches existing contacts to ActivityPub
374 * @param integer $cid Contact ID
375 * @param integer $uid User ID
376 * @param string $url Profile URL
378 private static function switchContact($cid, $uid, $url)
380 $profile = ActivityPub::probeProfile($url);
381 if (empty($profile)) {
385 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
387 $photo = $profile['photo'];
388 unset($profile['photo']);
389 unset($profile['baseurl']);
391 $profile['nurl'] = normalise_link($profile['url']);
392 DBA::update('contact', $profile, ['id' => $cid]);
394 Contact::updateAvatar($photo, $uid, $cid);
396 // Send a new follow request to be sure that the connection still exists
397 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
398 ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
399 logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG);
409 private static function switchContacts($receivers, $actor)
415 foreach ($receivers as $receiver) {
416 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
417 if (DBA::isResult($contact)) {
418 self::switchContact($contact['id'], $receiver, $actor);
421 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
422 if (DBA::isResult($contact)) {
423 self::switchContact($contact['id'], $receiver, $actor);
431 * @param $object_data
432 * @param array $activity
436 private static function addActivityFields($object_data, $activity)
438 if (!empty($activity['published']) && empty($object_data['published'])) {
439 $object_data['published'] = $activity['published'];
442 if (!empty($activity['updated']) && empty($object_data['updated'])) {
443 $object_data['updated'] = $activity['updated'];
446 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
447 $object_data['diaspora:guid'] = $activity['diaspora:guid'];
450 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
451 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
454 if (!empty($activity['instrument'])) {
455 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
465 * @param $trust_source
467 * @return array with object data
469 private static function fetchObject($object_id, $object = [], $trust_source = false)
471 if (!$trust_source || empty($object)) {
472 $data = ActivityPub::fetchContent($object_id);
474 $object = JsonLD::compact($data);
475 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
477 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
479 $item = Item::selectFirst([], ['uri' => $object_id]);
480 if (!DBA::isResult($item)) {
481 logger('Object with url ' . $object_id . ' was not found locally.', LOGGER_DEBUG);
484 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
485 $data = ActivityPub\Transmitter::createNote($item);
486 $object = JsonLD::compact($data);
489 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
492 $type = JsonLD::fetchElement($object, '@type');
495 logger('Empty type', LOGGER_DEBUG);
499 if (in_array($type, self::CONTENT_TYPES)) {
500 return self::processObject($object);
503 if ($type == 'as:Announce') {
504 $object_id = JsonLD::fetchElement($object, 'object');
505 if (empty($object_id)) {
508 return self::fetchObject($object_id);
511 logger('Unhandled object type: ' . $type, LOGGER_DEBUG);
515 * Convert tags from JSON-LD format into a simplified format
517 * @param array $tags Tags in JSON-LD format
519 * @return array with tags in a simplified format
521 private static function processTags($tags)
525 foreach ($tags as $tag) {
530 $taglist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
531 'href' => JsonLD::fetchElement($tag, 'as:href'),
532 'name' => JsonLD::fetchElement($tag, 'as:name')];
538 * Convert attachments from JSON-LD format into a simplified format
540 * @param array $attachments Attachments in JSON-LD format
542 * @return array with attachmants in a simplified format
544 private static function processAttachments($attachments)
548 foreach ($attachments as $attachment) {
549 if (empty($attachment)) {
553 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
554 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType'),
555 'name' => JsonLD::fetchElement($attachment, 'as:name'),
556 'url' => JsonLD::fetchElement($attachment, 'as:url')];
562 * Fetches data from the object part of an activity
564 * @param array $object
568 private static function processObject($object)
570 if (!JsonLD::fetchElement($object, '@id')) {
575 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
576 $object_data['id'] = JsonLD::fetchElement($object, '@id');
578 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo');
580 if (empty($object_data['reply-to-id'])) {
581 $object_data['reply-to-id'] = $object_data['id'];
584 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
585 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
587 if (empty($object_data['updated'])) {
588 $object_data['updated'] = $object_data['published'];
591 if (empty($object_data['published']) && !empty($object_data['updated'])) {
592 $object_data['published'] = $object_data['updated'];
595 $actor = JsonLD::fetchElement($object, 'as:attributedTo');
597 $actor = JsonLD::fetchElement($object, 'as:actor');
600 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid');
601 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment');
602 $object_data['owner'] = $object_data['author'] = $actor;
603 $object_data['context'] = JsonLD::fetchElement($object, 'as:context');
604 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation');
605 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
606 $object_data['name'] = JsonLD::fetchElement($object, 'as:name');
607 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary');
608 $object_data['content'] = JsonLD::fetchElement($object, 'as:content');
609 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
610 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
611 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
612 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
613 // $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service'); // todo
614 $object_data['service'] = null;
615 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url');
617 // Special treatment for Hubzilla links
618 if (is_array($object_data['alternate-url'])) {
619 if (!empty($object['as:url'])) {
620 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href');
622 $object_data['alternate-url'] = null;
626 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
628 // Common object data:
631 // @context, type, actor, signature, mediaType, duration, replies, icon
633 // Also missing: (Defined in the standard, but currently unused)
634 // audience, preview, endTime, startTime, generator, image
639 // contentMap, announcement_count, announcements, context_id, likes, like_count
640 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
645 // category, licence, language, commentsEnabled
648 // views, waitTranscoding, state, support, subtitleLanguage
649 // likes, dislikes, shares, comments