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 * 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);
360 * Switches existing contacts to ActivityPub
362 * @param integer $cid Contact ID
363 * @param integer $uid User ID
364 * @param string $url Profile URL
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 . ' 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);
384 // Send a new follow request to be sure that the connection still exists
385 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
386 ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
387 logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG);
397 private static function switchContacts($receivers, $actor)
403 foreach ($receivers as $receiver) {
404 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
405 if (DBA::isResult($contact)) {
406 self::switchContact($contact['id'], $receiver, $actor);
409 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
410 if (DBA::isResult($contact)) {
411 self::switchContact($contact['id'], $receiver, $actor);
419 * @param $object_data
420 * @param array $activity
424 private static function addActivityFields($object_data, $activity)
426 if (!empty($activity['published']) && empty($object_data['published'])) {
427 $object_data['published'] = $activity['published'];
430 if (!empty($activity['updated']) && empty($object_data['updated'])) {
431 $object_data['updated'] = $activity['updated'];
434 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
435 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
438 if (!empty($activity['instrument'])) {
439 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
449 * @param $trust_source
453 private static function fetchObject($object_id, $object = [], $trust_source = false)
455 if (!$trust_source || is_string($object)) {
456 $data = ActivityPub::fetchContent($object_id);
458 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
461 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
464 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
468 if (is_string($data)) {
469 $item = Item::selectFirst([], ['uri' => $data]);
470 if (!DBA::isResult($item)) {
471 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
474 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
475 $data = ActivityPub\Transmitter::createNote($item);
478 if (empty($data['type'])) {
479 logger('Empty type', LOGGER_DEBUG);
483 if (in_array($data['type'], ActivityPub::CONTENT_TYPES)) {
484 return self::processObject($data);
487 if ($data['type'] == 'Announce') {
488 if (empty($data['object'])) {
491 return self::fetchObject($data['object']);
494 logger('Unhandled object type: ' . $data['type'], LOGGER_DEBUG);
504 private static function processObject($object)
506 if (empty($object['id'])) {
511 $object_data['object_type'] = $object['type'];
512 $object_data['id'] = $object['id'];
514 if (!empty($object['inReplyTo'])) {
515 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
517 $object_data['reply-to-id'] = $object_data['id'];
520 $object_data['published'] = defaults($object, 'published', null);
521 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
523 if (empty($object_data['published']) && !empty($object_data['updated'])) {
524 $object_data['published'] = $object_data['updated'];
527 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
529 $actor = defaults($object, 'actor', null);
532 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
533 $object_data['owner'] = $object_data['author'] = $actor;
534 $object_data['context'] = defaults($object, 'context', null);
535 $object_data['conversation'] = defaults($object, 'conversation', null);
536 $object_data['sensitive'] = defaults($object, 'sensitive', null);
537 $object_data['name'] = defaults($object, 'title', null);
538 $object_data['name'] = defaults($object, 'name', $object_data['name']);
539 $object_data['summary'] = defaults($object, 'summary', null);
540 $object_data['content'] = defaults($object, 'content', null);
541 $object_data['source'] = defaults($object, 'source', null);
542 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
543 $object_data['attachments'] = defaults($object, 'attachment', null);
544 $object_data['tags'] = defaults($object, 'tag', null);
545 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
546 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
547 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
549 // Common object data:
552 // @context, type, actor, signature, mediaType, duration, replies, icon
554 // Also missing: (Defined in the standard, but currently unused)
555 // audience, preview, endTime, startTime, generator, image
560 // contentMap, announcement_count, announcements, context_id, likes, like_count
561 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
566 // category, licence, language, commentsEnabled
569 // views, waitTranscoding, state, support, subtitleLanguage
570 // likes, dislikes, shares, comments