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);
214 switch ($activity['type']) {
217 ActivityPub\Processor::createItem($object_data, $body);
221 ActivityPub\Processor::likeItem($object_data, $body);
225 ActivityPub\Processor::dislikeItem($object_data, $body);
229 if (in_array($object_data['object_type'], ActivityPub::CONTENT_TYPES)) {
231 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
232 ActivityPub\Processor::updatePerson($object_data, $body);
237 if ($object_data['object_type'] == 'Tombstone') {
238 ActivityPub\Processor::deleteItem($object_data, $body);
239 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
240 ActivityPub\Processor::deletePerson($object_data, $body);
245 ActivityPub\Processor::followUser($object_data);
249 if ($object_data['object_type'] == 'Follow') {
250 ActivityPub\Processor::acceptFollowUser($object_data);
255 if ($object_data['object_type'] == 'Follow') {
256 ActivityPub\Processor::rejectFollowUser($object_data);
261 if ($object_data['object_type'] == 'Follow') {
262 ActivityPub\Processor::undoFollowUser($object_data);
263 } elseif (in_array($object_data['object_type'], ActivityPub::ACTIVITY_TYPES)) {
264 ActivityPub\Processor::undoActivity($object_data);
269 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
277 * @param array $activity
282 private static function getReceivers($activity, $actor)
286 // When it is an answer, we inherite the receivers from the parent
287 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
288 if (!empty($replyto)) {
289 $parents = Item::select(['uid'], ['uri' => $replyto]);
290 while ($parent = Item::fetch($parents)) {
291 $receivers['uid:' . $parent['uid']] = $parent['uid'];
295 if (!empty($actor)) {
296 $profile = APContact::getByURL($actor);
297 $followers = defaults($profile, 'followers', '');
299 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
301 logger('Empty actor', LOGGER_DEBUG);
305 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
306 if (empty($activity[$element])) {
310 // The receiver can be an array or a string
311 if (is_string($activity[$element])) {
312 $activity[$element] = [$activity[$element]];
315 foreach ($activity[$element] as $receiver) {
316 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
317 $receivers['uid:0'] = 0;
320 if (($receiver == ActivityPub::PUBLIC_COLLECTION) && !empty($actor)) {
321 // This will most likely catch all OStatus connections to Mastodon
322 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
323 , 'archive' => false, 'pending' => false];
324 $contacts = DBA::select('contact', ['uid'], $condition);
325 while ($contact = DBA::fetch($contacts)) {
326 if ($contact['uid'] != 0) {
327 $receivers['uid:' . $contact['uid']] = $contact['uid'];
330 DBA::close($contacts);
333 if (in_array($receiver, [$followers, ActivityPub::PUBLIC_COLLECTION]) && !empty($actor)) {
334 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
335 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
336 $contacts = DBA::select('contact', ['uid'], $condition);
337 while ($contact = DBA::fetch($contacts)) {
338 if ($contact['uid'] != 0) {
339 $receivers['uid:' . $contact['uid']] = $contact['uid'];
342 DBA::close($contacts);
346 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
347 $contact = DBA::selectFirst('contact', ['uid'], $condition);
348 if (!DBA::isResult($contact)) {
351 $receivers['uid:' . $contact['uid']] = $contact['uid'];
355 self::switchContacts($receivers, $actor);
361 * Switches existing contacts to ActivityPub
363 * @param integer $cid Contact ID
364 * @param integer $uid User ID
365 * @param string $url Profile URL
367 private static function switchContact($cid, $uid, $url)
369 $profile = ActivityPub::probeProfile($url);
370 if (empty($profile)) {
374 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
376 $photo = $profile['photo'];
377 unset($profile['photo']);
378 unset($profile['baseurl']);
380 $profile['nurl'] = normalise_link($profile['url']);
381 DBA::update('contact', $profile, ['id' => $cid]);
383 Contact::updateAvatar($photo, $uid, $cid);
385 // Send a new follow request to be sure that the connection still exists
386 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
387 ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
388 logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG);
398 private static function switchContacts($receivers, $actor)
404 foreach ($receivers as $receiver) {
405 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
406 if (DBA::isResult($contact)) {
407 self::switchContact($contact['id'], $receiver, $actor);
410 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
411 if (DBA::isResult($contact)) {
412 self::switchContact($contact['id'], $receiver, $actor);
420 * @param $object_data
421 * @param array $activity
425 private static function addActivityFields($object_data, $activity)
427 if (!empty($activity['published']) && empty($object_data['published'])) {
428 $object_data['published'] = $activity['published'];
431 if (!empty($activity['updated']) && empty($object_data['updated'])) {
432 $object_data['updated'] = $activity['updated'];
435 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
436 $object_data['diaspora:guid'] = $activity['diaspora:guid'];
439 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
440 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
443 if (!empty($activity['instrument'])) {
444 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
454 * @param $trust_source
458 private static function fetchObject($object_id, $object = [], $trust_source = false)
460 if (!$trust_source || is_string($object)) {
461 $data = ActivityPub::fetchContent($object_id);
463 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
466 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
469 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
473 if (is_string($data)) {
474 $item = Item::selectFirst([], ['uri' => $data]);
475 if (!DBA::isResult($item)) {
476 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
479 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
480 $data = ActivityPub\Transmitter::createNote($item);
483 if (empty($data['type'])) {
484 logger('Empty type', LOGGER_DEBUG);
488 if (in_array($data['type'], ActivityPub::CONTENT_TYPES)) {
489 return self::processObject($data);
492 if ($data['type'] == 'Announce') {
493 if (empty($data['object'])) {
496 return self::fetchObject($data['object']);
499 logger('Unhandled object type: ' . $data['type'], LOGGER_DEBUG);
509 private static function processObject($object)
511 if (empty($object['id'])) {
516 $object_data['object_type'] = $object['type'];
517 $object_data['id'] = $object['id'];
519 if (!empty($object['inReplyTo'])) {
520 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
522 $object_data['reply-to-id'] = $object_data['id'];
525 $object_data['published'] = defaults($object, 'published', null);
526 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
528 if (empty($object_data['published']) && !empty($object_data['updated'])) {
529 $object_data['published'] = $object_data['updated'];
532 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
534 $actor = defaults($object, 'actor', null);
537 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
538 $object_data['owner'] = $object_data['author'] = $actor;
539 $object_data['context'] = defaults($object, 'context', null);
540 $object_data['conversation'] = defaults($object, 'conversation', null);
541 $object_data['sensitive'] = defaults($object, 'sensitive', null);
542 $object_data['name'] = defaults($object, 'title', null);
543 $object_data['name'] = defaults($object, 'name', $object_data['name']);
544 $object_data['summary'] = defaults($object, 'summary', null);
545 $object_data['content'] = defaults($object, 'content', null);
546 $object_data['source'] = defaults($object, 'source', null);
547 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
548 $object_data['attachments'] = defaults($object, 'attachment', null);
549 $object_data['tags'] = defaults($object, 'tag', null);
550 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
551 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
552 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
554 // Common object data:
557 // @context, type, actor, signature, mediaType, duration, replies, icon
559 // Also missing: (Defined in the standard, but currently unused)
560 // audience, preview, endTime, startTime, generator, image
565 // contentMap, announcement_count, announcements, context_id, likes, like_count
566 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
571 // category, licence, language, commentsEnabled
574 // views, waitTranscoding, state, support, subtitleLanguage
575 // likes, dislikes, shares, comments