3 * @file src/Protocol/ActivityPub.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Core\System;
9 use Friendica\BaseObject;
10 use Friendica\Util\Network;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\APContact;
16 use Friendica\Model\Item;
17 use Friendica\Model\Profile;
18 use Friendica\Model\Term;
19 use Friendica\Model\User;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Crypto;
22 use Friendica\Content\Text\BBCode;
23 use Friendica\Content\Text\HTML;
24 use Friendica\Util\JsonLD;
25 use Friendica\Util\LDSignature;
26 use Friendica\Core\Config;
27 use Friendica\Protocol\ActivityPub;
30 * @brief ActivityPub Receiver Protocol class
33 * - Update (Image, Video, Article, Note)
37 * Check what this is meant to do:
43 * - Undo Accept (Problem: This could invert a contact accept or an event accept)
46 * - Possibly using the LD-JSON parser
51 * @brief Checks if the web request is done for the AP protocol
55 public static function isRequest()
57 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
58 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
66 * @param integer $uid User ID
68 public static function processInbox($body, $header, $uid)
70 $http_signer = HTTPSignature::getSigner($body, $header);
71 if (empty($http_signer)) {
72 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
75 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
78 $activity = json_decode($body, true);
80 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
81 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
83 if (empty($activity)) {
84 logger('Invalid body.', LOGGER_DEBUG);
88 if (LDSignature::isSigned($activity)) {
89 $ld_signer = LDSignature::getSigner($activity);
90 if (empty($ld_signer)) {
91 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
93 if (!empty($ld_signer && ($actor == $http_signer))) {
94 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
96 } elseif (!empty($ld_signer)) {
97 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
99 } elseif ($actor == $http_signer) {
100 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
101 $trust_source = true;
103 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
104 $trust_source = false;
106 } elseif ($actor == $http_signer) {
107 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
108 $trust_source = true;
110 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
111 $trust_source = false;
114 self::processActivity($activity, $body, $uid, $trust_source);
120 * @param array $activity
121 * @param integer $uid User ID
122 * @param $trust_source
126 private static function prepareObjectData($activity, $uid, &$trust_source)
128 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
130 logger('Empty actor', LOGGER_DEBUG);
134 // Fetch all receivers from to, cc, bto and bcc
135 $receivers = self::getReceivers($activity, $actor);
137 // When it is a delivery to a personal inbox we add that user to the receivers
139 $owner = User::getOwnerDataById($uid);
140 $additional = ['uid:' . $uid => $uid];
141 $receivers = array_merge($receivers, $additional);
144 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
146 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
147 if (empty($object_id)) {
148 logger('No object found', LOGGER_DEBUG);
152 // Fetch the content only on activities where this matters
153 if (in_array($activity['type'], ['Create', 'Announce'])) {
154 $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
155 if (empty($object_data)) {
156 logger("Object data couldn't be processed", LOGGER_DEBUG);
159 // We had been able to retrieve the object data - so we can trust the source
160 $trust_source = true;
161 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
162 // Create a mostly empty array out of the activity data (instead of the object).
163 // This way we later don't have to check for the existence of ech individual array element.
164 $object_data = self::processObject($activity);
165 $object_data['name'] = $activity['type'];
166 $object_data['author'] = $activity['actor'];
167 $object_data['object'] = $object_id;
168 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
171 $object_data['id'] = $activity['id'];
172 $object_data['object'] = $activity['object'];
173 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
176 $object_data = self::addActivityFields($object_data, $activity);
178 $object_data['type'] = $activity['type'];
179 $object_data['owner'] = $actor;
180 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
182 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
190 * @param array $activity
192 * @param integer $uid User ID
193 * @param $trust_source
195 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
197 if (empty($activity['type'])) {
198 logger('Empty type', LOGGER_DEBUG);
202 if (empty($activity['object'])) {
203 logger('Empty object', LOGGER_DEBUG);
207 if (empty($activity['actor'])) {
208 logger('Empty actor', LOGGER_DEBUG);
213 // $trust_source is called by reference and is set to true if the content was retrieved successfully
214 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
215 if (empty($object_data)) {
216 logger('No object data found', LOGGER_DEBUG);
220 if (!$trust_source) {
221 logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
224 switch ($activity['type']) {
227 ActivityPub\Processor::createItem($object_data, $body);
231 ActivityPub\Processor::likeItem($object_data, $body);
235 ActivityPub\Processor::dislikeItem($object_data, $body);
239 if (in_array($object_data['object_type'], ActivityPub::CONTENT_TYPES)) {
241 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
242 ActivityPub\Processor::updatePerson($object_data, $body);
247 if ($object_data['object_type'] == 'Tombstone') {
248 ActivityPub\Processor::deleteItem($object_data, $body);
249 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
250 ActivityPub\Processor::deletePerson($object_data, $body);
255 ActivityPub\Processor::followUser($object_data);
259 if ($object_data['object_type'] == 'Follow') {
260 ActivityPub\Processor::acceptFollowUser($object_data);
265 if ($object_data['object_type'] == 'Follow') {
266 ActivityPub\Processor::rejectFollowUser($object_data);
271 if ($object_data['object_type'] == 'Follow') {
272 ActivityPub\Processor::undoFollowUser($object_data);
273 } elseif (in_array($object_data['object_type'], ActivityPub::ACTIVITY_TYPES)) {
274 ActivityPub\Processor::undoActivity($object_data);
279 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
287 * @param array $activity
292 private static function getReceivers($activity, $actor)
296 // When it is an answer, we inherite the receivers from the parent
297 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
298 if (!empty($replyto)) {
299 $parents = Item::select(['uid'], ['uri' => $replyto]);
300 while ($parent = Item::fetch($parents)) {
301 $receivers['uid:' . $parent['uid']] = $parent['uid'];
305 if (!empty($actor)) {
306 $profile = APContact::getByURL($actor);
307 $followers = defaults($profile, 'followers', '');
309 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
311 logger('Empty actor', LOGGER_DEBUG);
315 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
316 if (empty($activity[$element])) {
320 // The receiver can be an array or a string
321 if (is_string($activity[$element])) {
322 $activity[$element] = [$activity[$element]];
325 foreach ($activity[$element] as $receiver) {
326 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
327 $receivers['uid:0'] = 0;
330 if (($receiver == ActivityPub::PUBLIC_COLLECTION) && !empty($actor)) {
331 // This will most likely catch all OStatus connections to Mastodon
332 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
333 , 'archive' => false, 'pending' => false];
334 $contacts = DBA::select('contact', ['uid'], $condition);
335 while ($contact = DBA::fetch($contacts)) {
336 if ($contact['uid'] != 0) {
337 $receivers['uid:' . $contact['uid']] = $contact['uid'];
340 DBA::close($contacts);
343 if (in_array($receiver, [$followers, ActivityPub::PUBLIC_COLLECTION]) && !empty($actor)) {
344 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
345 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
346 $contacts = DBA::select('contact', ['uid'], $condition);
347 while ($contact = DBA::fetch($contacts)) {
348 if ($contact['uid'] != 0) {
349 $receivers['uid:' . $contact['uid']] = $contact['uid'];
352 DBA::close($contacts);
356 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
357 $contact = DBA::selectFirst('contact', ['uid'], $condition);
358 if (!DBA::isResult($contact)) {
361 $receivers['uid:' . $contact['uid']] = $contact['uid'];
365 self::switchContacts($receivers, $actor);
374 * @param integer $uid User ID
377 private static function switchContact($cid, $uid, $url)
379 $profile = ActivityPub::probeProfile($url);
380 if (empty($profile)) {
384 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
386 $photo = $profile['photo'];
387 unset($profile['photo']);
388 unset($profile['baseurl']);
390 $profile['nurl'] = normalise_link($profile['url']);
391 DBA::update('contact', $profile, ['id' => $cid]);
393 Contact::updateAvatar($photo, $uid, $cid);
402 private static function switchContacts($receivers, $actor)
408 foreach ($receivers as $receiver) {
409 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
410 if (DBA::isResult($contact)) {
411 self::switchContact($contact['id'], $receiver, $actor);
414 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
415 if (DBA::isResult($contact)) {
416 self::switchContact($contact['id'], $receiver, $actor);
424 * @param $object_data
425 * @param array $activity
429 private static function addActivityFields($object_data, $activity)
431 if (!empty($activity['published']) && empty($object_data['published'])) {
432 $object_data['published'] = $activity['published'];
435 if (!empty($activity['updated']) && empty($object_data['updated'])) {
436 $object_data['updated'] = $activity['updated'];
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