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
40 * @brief Checks if the web request is done for the AP protocol
44 public static function isRequest()
46 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
47 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
55 * @param integer $uid User ID
57 public static function processInbox($body, $header, $uid)
59 $http_signer = HTTPSignature::getSigner($body, $header);
60 if (empty($http_signer)) {
61 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
64 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
67 $activity = json_decode($body, true);
69 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
70 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
72 if (empty($activity)) {
73 logger('Invalid body.', LOGGER_DEBUG);
77 if (LDSignature::isSigned($activity)) {
78 $ld_signer = LDSignature::getSigner($activity);
79 if (empty($ld_signer)) {
80 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
82 if (!empty($ld_signer && ($actor == $http_signer))) {
83 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
85 } elseif (!empty($ld_signer)) {
86 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
88 } elseif ($actor == $http_signer) {
89 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
92 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
93 $trust_source = false;
95 } elseif ($actor == $http_signer) {
96 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
99 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
100 $trust_source = false;
103 self::processActivity($activity, $body, $uid, $trust_source);
109 * @param array $activity
110 * @param integer $uid User ID
111 * @param $trust_source
115 private static function prepareObjectData($activity, $uid, &$trust_source)
117 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
119 logger('Empty actor', LOGGER_DEBUG);
123 // Fetch all receivers from to, cc, bto and bcc
124 $receivers = self::getReceivers($activity, $actor);
126 // When it is a delivery to a personal inbox we add that user to the receivers
128 $owner = User::getOwnerDataById($uid);
129 $additional = ['uid:' . $uid => $uid];
130 $receivers = array_merge($receivers, $additional);
133 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
135 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
136 if (empty($object_id)) {
137 logger('No object found', LOGGER_DEBUG);
141 // Fetch the content only on activities where this matters
142 if (in_array($activity['type'], ['Create', 'Announce'])) {
143 $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
144 if (empty($object_data)) {
145 logger("Object data couldn't be processed", LOGGER_DEBUG);
148 // We had been able to retrieve the object data - so we can trust the source
149 $trust_source = true;
150 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
151 // Create a mostly empty array out of the activity data (instead of the object).
152 // This way we later don't have to check for the existence of ech individual array element.
153 $object_data = self::processObject($activity);
154 $object_data['name'] = $activity['type'];
155 $object_data['author'] = $activity['actor'];
156 $object_data['object'] = $object_id;
157 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
160 $object_data['id'] = $activity['id'];
161 $object_data['object'] = $activity['object'];
162 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
165 $object_data = self::addActivityFields($object_data, $activity);
167 $object_data['type'] = $activity['type'];
168 $object_data['owner'] = $actor;
169 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
171 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
179 * @param array $activity
181 * @param integer $uid User ID
182 * @param $trust_source
184 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
186 if (empty($activity['type'])) {
187 logger('Empty type', LOGGER_DEBUG);
191 if (empty($activity['object'])) {
192 logger('Empty object', LOGGER_DEBUG);
196 if (empty($activity['actor'])) {
197 logger('Empty actor', LOGGER_DEBUG);
202 // $trust_source is called by reference and is set to true if the content was retrieved successfully
203 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
204 if (empty($object_data)) {
205 logger('No object data found', LOGGER_DEBUG);
209 if (!$trust_source) {
210 logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
213 switch ($activity['type']) {
216 ActivityPub\Processor::createItem($object_data, $body);
220 ActivityPub\Processor::likeItem($object_data, $body);
224 ActivityPub\Processor::dislikeItem($object_data, $body);
228 if (in_array($object_data['object_type'], ActivityPub::CONTENT_TYPES)) {
230 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
231 ActivityPub\Processor::updatePerson($object_data, $body);
236 if ($object_data['object_type'] == 'Tombstone') {
237 ActivityPub\Processor::deleteItem($object_data, $body);
238 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
239 ActivityPub\Processor::deletePerson($object_data, $body);
244 ActivityPub\Processor::followUser($object_data);
248 if ($object_data['object_type'] == 'Follow') {
249 ActivityPub\Processor::acceptFollowUser($object_data);
254 if ($object_data['object_type'] == 'Follow') {
255 ActivityPub\Processor::rejectFollowUser($object_data);
260 if ($object_data['object_type'] == 'Follow') {
261 ActivityPub\Processor::undoFollowUser($object_data);
262 } elseif (in_array($object_data['object_type'], ActivityPub::ACTIVITY_TYPES)) {
263 ActivityPub\Processor::undoActivity($object_data);
268 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
276 * @param array $activity
281 private static function getReceivers($activity, $actor)
285 // When it is an answer, we inherite the receivers from the parent
286 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
287 if (!empty($replyto)) {
288 $parents = Item::select(['uid'], ['uri' => $replyto]);
289 while ($parent = Item::fetch($parents)) {
290 $receivers['uid:' . $parent['uid']] = $parent['uid'];
294 if (!empty($actor)) {
295 $profile = APContact::getByURL($actor);
296 $followers = defaults($profile, 'followers', '');
298 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
300 logger('Empty actor', LOGGER_DEBUG);
304 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
305 if (empty($activity[$element])) {
309 // The receiver can be an array or a string
310 if (is_string($activity[$element])) {
311 $activity[$element] = [$activity[$element]];
314 foreach ($activity[$element] as $receiver) {
315 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
316 $receivers['uid:0'] = 0;
319 if (($receiver == ActivityPub::PUBLIC_COLLECTION) && !empty($actor)) {
320 // This will most likely catch all OStatus connections to Mastodon
321 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
322 , 'archive' => false, 'pending' => false];
323 $contacts = DBA::select('contact', ['uid'], $condition);
324 while ($contact = DBA::fetch($contacts)) {
325 if ($contact['uid'] != 0) {
326 $receivers['uid:' . $contact['uid']] = $contact['uid'];
329 DBA::close($contacts);
332 if (in_array($receiver, [$followers, ActivityPub::PUBLIC_COLLECTION]) && !empty($actor)) {
333 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
334 'network' => Protocol::ACTIVITYPUB, '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);
345 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
346 $contact = DBA::selectFirst('contact', ['uid'], $condition);
347 if (!DBA::isResult($contact)) {
350 $receivers['uid:' . $contact['uid']] = $contact['uid'];
354 self::switchContacts($receivers, $actor);
363 * @param integer $uid User ID
366 private static function switchContact($cid, $uid, $url)
368 $profile = ActivityPub::probeProfile($url);
369 if (empty($profile)) {
373 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
375 $photo = $profile['photo'];
376 unset($profile['photo']);
377 unset($profile['baseurl']);
379 $profile['nurl'] = normalise_link($profile['url']);
380 DBA::update('contact', $profile, ['id' => $cid]);
382 Contact::updateAvatar($photo, $uid, $cid);
391 private static function switchContacts($receivers, $actor)
397 foreach ($receivers as $receiver) {
398 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
399 if (DBA::isResult($contact)) {
400 self::switchContact($contact['id'], $receiver, $actor);
403 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
404 if (DBA::isResult($contact)) {
405 self::switchContact($contact['id'], $receiver, $actor);
413 * @param $object_data
414 * @param array $activity
418 private static function addActivityFields($object_data, $activity)
420 if (!empty($activity['published']) && empty($object_data['published'])) {
421 $object_data['published'] = $activity['published'];
424 if (!empty($activity['updated']) && empty($object_data['updated'])) {
425 $object_data['updated'] = $activity['updated'];
428 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
429 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
432 if (!empty($activity['instrument'])) {
433 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
443 * @param $trust_source
447 private static function fetchObject($object_id, $object = [], $trust_source = false)
449 if (!$trust_source || is_string($object)) {
450 $data = ActivityPub::fetchContent($object_id);
452 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
455 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
458 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
462 if (is_string($data)) {
463 $item = Item::selectFirst([], ['uri' => $data]);
464 if (!DBA::isResult($item)) {
465 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
468 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
469 $data = ActivityPub\Transmitter::createNote($item);
472 if (empty($data['type'])) {
473 logger('Empty type', LOGGER_DEBUG);
477 if (in_array($data['type'], ActivityPub::CONTENT_TYPES)) {
478 return self::processObject($data);
481 if ($data['type'] == 'Announce') {
482 if (empty($data['object'])) {
485 return self::fetchObject($data['object']);
488 logger('Unhandled object type: ' . $data['type'], LOGGER_DEBUG);
498 private static function processObject($object)
500 if (empty($object['id'])) {
505 $object_data['object_type'] = $object['type'];
506 $object_data['id'] = $object['id'];
508 if (!empty($object['inReplyTo'])) {
509 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
511 $object_data['reply-to-id'] = $object_data['id'];
514 $object_data['published'] = defaults($object, 'published', null);
515 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
517 if (empty($object_data['published']) && !empty($object_data['updated'])) {
518 $object_data['published'] = $object_data['updated'];
521 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
523 $actor = defaults($object, 'actor', null);
526 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
527 $object_data['owner'] = $object_data['author'] = $actor;
528 $object_data['context'] = defaults($object, 'context', null);
529 $object_data['conversation'] = defaults($object, 'conversation', null);
530 $object_data['sensitive'] = defaults($object, 'sensitive', null);
531 $object_data['name'] = defaults($object, 'title', null);
532 $object_data['name'] = defaults($object, 'name', $object_data['name']);
533 $object_data['summary'] = defaults($object, 'summary', null);
534 $object_data['content'] = defaults($object, 'content', null);
535 $object_data['source'] = defaults($object, 'source', null);
536 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
537 $object_data['attachments'] = defaults($object, 'attachment', null);
538 $object_data['tags'] = defaults($object, 'tag', null);
539 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
540 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
541 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
543 // Common object data:
546 // @context, type, actor, signature, mediaType, duration, replies, icon
548 // Also missing: (Defined in the standard, but currently unused)
549 // audience, preview, endTime, startTime, generator, image
554 // contentMap, announcement_count, announcements, context_id, likes, like_count
555 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
560 // category, licence, language, commentsEnabled
563 // views, waitTranscoding, state, support, subtitleLanguage
564 // likes, dislikes, shares, comments