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 Protocol class
35 * @brief Checks if the web request is done for the AP protocol
39 public static function isRequest()
41 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
42 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
50 * @param integer $uid User ID
52 public static function processInbox($body, $header, $uid)
54 $http_signer = HTTPSignature::getSigner($body, $header);
55 if (empty($http_signer)) {
56 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
59 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
62 $activity = json_decode($body, true);
64 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
65 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
67 if (empty($activity)) {
68 logger('Invalid body.', LOGGER_DEBUG);
72 if (LDSignature::isSigned($activity)) {
73 $ld_signer = LDSignature::getSigner($activity);
74 if (empty($ld_signer)) {
75 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
77 if (!empty($ld_signer && ($actor == $http_signer))) {
78 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
80 } elseif (!empty($ld_signer)) {
81 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
83 } elseif ($actor == $http_signer) {
84 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
87 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
88 $trust_source = false;
90 } elseif ($actor == $http_signer) {
91 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
94 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
95 $trust_source = false;
98 self::processActivity($activity, $body, $uid, $trust_source);
104 * @param array $activity
105 * @param integer $uid User ID
106 * @param $trust_source
110 private static function prepareObjectData($activity, $uid, &$trust_source)
112 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
114 logger('Empty actor', LOGGER_DEBUG);
118 // Fetch all receivers from to, cc, bto and bcc
119 $receivers = self::getReceivers($activity, $actor);
121 // When it is a delivery to a personal inbox we add that user to the receivers
123 $owner = User::getOwnerDataById($uid);
124 $additional = ['uid:' . $uid => $uid];
125 $receivers = array_merge($receivers, $additional);
128 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
130 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
131 if (empty($object_id)) {
132 logger('No object found', LOGGER_DEBUG);
136 // Fetch the content only on activities where this matters
137 if (in_array($activity['type'], ['Create', 'Announce'])) {
138 $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
139 if (empty($object_data)) {
140 logger("Object data couldn't be processed", LOGGER_DEBUG);
143 // We had been able to retrieve the object data - so we can trust the source
144 $trust_source = true;
145 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
146 // Create a mostly empty array out of the activity data (instead of the object).
147 // This way we later don't have to check for the existence of ech individual array element.
148 $object_data = self::processObject($activity);
149 $object_data['name'] = $activity['type'];
150 $object_data['author'] = $activity['actor'];
151 $object_data['object'] = $object_id;
152 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
155 $object_data['id'] = $activity['id'];
156 $object_data['object'] = $activity['object'];
157 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
160 $object_data = self::addActivityFields($object_data, $activity);
162 $object_data['type'] = $activity['type'];
163 $object_data['owner'] = $actor;
164 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
166 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
174 * @param array $activity
176 * @param integer $uid User ID
177 * @param $trust_source
179 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
181 if (empty($activity['type'])) {
182 logger('Empty type', LOGGER_DEBUG);
186 if (empty($activity['object'])) {
187 logger('Empty object', LOGGER_DEBUG);
191 if (empty($activity['actor'])) {
192 logger('Empty actor', LOGGER_DEBUG);
197 // $trust_source is called by reference and is set to true if the content was retrieved successfully
198 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
199 if (empty($object_data)) {
200 logger('No object data found', LOGGER_DEBUG);
204 if (!$trust_source) {
205 logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
208 switch ($activity['type']) {
211 ActivityPub\Processor::createItem($object_data, $body);
215 ActivityPub\Processor::likeItem($object_data, $body);
219 ActivityPub\Processor::dislikeItem($object_data, $body);
223 if (in_array($object_data['object_type'], ActivityPub::CONTENT_TYPES)) {
225 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
226 ActivityPub\Processor::updatePerson($object_data, $body);
231 if ($object_data['object_type'] == 'Tombstone') {
232 ActivityPub\Processor::deleteItem($object_data, $body);
233 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
234 ActivityPub\Processor::deletePerson($object_data, $body);
239 ActivityPub\Processor::followUser($object_data);
243 if ($object_data['object_type'] == 'Follow') {
244 ActivityPub\Processor::acceptFollowUser($object_data);
249 if ($object_data['object_type'] == 'Follow') {
250 ActivityPub\Processor::rejectFollowUser($object_data);
255 if ($object_data['object_type'] == 'Follow') {
256 ActivityPub\Processor::undoFollowUser($object_data);
257 } elseif (in_array($object_data['object_type'], ActivityPub::ACTIVITY_TYPES)) {
258 ActivityPub\Processor::undoActivity($object_data);
263 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
271 * @param array $activity
276 private static function getReceivers($activity, $actor)
280 // When it is an answer, we inherite the receivers from the parent
281 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
282 if (!empty($replyto)) {
283 $parents = Item::select(['uid'], ['uri' => $replyto]);
284 while ($parent = Item::fetch($parents)) {
285 $receivers['uid:' . $parent['uid']] = $parent['uid'];
289 if (!empty($actor)) {
290 $profile = APContact::getByURL($actor);
291 $followers = defaults($profile, 'followers', '');
293 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
295 logger('Empty actor', LOGGER_DEBUG);
299 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
300 if (empty($activity[$element])) {
304 // The receiver can be an array or a string
305 if (is_string($activity[$element])) {
306 $activity[$element] = [$activity[$element]];
309 foreach ($activity[$element] as $receiver) {
310 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
311 $receivers['uid:0'] = 0;
314 if (($receiver == ActivityPub::PUBLIC_COLLECTION) && !empty($actor)) {
315 // This will most likely catch all OStatus connections to Mastodon
316 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
317 , 'archive' => false, 'pending' => false];
318 $contacts = DBA::select('contact', ['uid'], $condition);
319 while ($contact = DBA::fetch($contacts)) {
320 if ($contact['uid'] != 0) {
321 $receivers['uid:' . $contact['uid']] = $contact['uid'];
324 DBA::close($contacts);
327 if (in_array($receiver, [$followers, ActivityPub::PUBLIC_COLLECTION]) && !empty($actor)) {
328 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
329 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
330 $contacts = DBA::select('contact', ['uid'], $condition);
331 while ($contact = DBA::fetch($contacts)) {
332 if ($contact['uid'] != 0) {
333 $receivers['uid:' . $contact['uid']] = $contact['uid'];
336 DBA::close($contacts);
340 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
341 $contact = DBA::selectFirst('contact', ['uid'], $condition);
342 if (!DBA::isResult($contact)) {
345 $receivers['uid:' . $contact['uid']] = $contact['uid'];
349 self::switchContacts($receivers, $actor);
358 * @param integer $uid User ID
361 private static function switchContact($cid, $uid, $url)
363 $profile = ActivityPub::probeProfile($url);
364 if (empty($profile)) {
368 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
370 $photo = $profile['photo'];
371 unset($profile['photo']);
372 unset($profile['baseurl']);
374 $profile['nurl'] = normalise_link($profile['url']);
375 DBA::update('contact', $profile, ['id' => $cid]);
377 Contact::updateAvatar($photo, $uid, $cid);
386 private static function switchContacts($receivers, $actor)
392 foreach ($receivers as $receiver) {
393 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
394 if (DBA::isResult($contact)) {
395 self::switchContact($contact['id'], $receiver, $actor);
398 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
399 if (DBA::isResult($contact)) {
400 self::switchContact($contact['id'], $receiver, $actor);
408 * @param $object_data
409 * @param array $activity
413 private static function addActivityFields($object_data, $activity)
415 if (!empty($activity['published']) && empty($object_data['published'])) {
416 $object_data['published'] = $activity['published'];
419 if (!empty($activity['updated']) && empty($object_data['updated'])) {
420 $object_data['updated'] = $activity['updated'];
423 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
424 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
427 if (!empty($activity['instrument'])) {
428 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
438 * @param $trust_source
442 private static function fetchObject($object_id, $object = [], $trust_source = false)
444 if (!$trust_source || is_string($object)) {
445 $data = ActivityPub::fetchContent($object_id);
447 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
450 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
453 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
457 if (is_string($data)) {
458 $item = Item::selectFirst([], ['uri' => $data]);
459 if (!DBA::isResult($item)) {
460 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
463 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
464 $data = ActivityPub\Transmitter::createNote($item);
467 if (empty($data['type'])) {
468 logger('Empty type', LOGGER_DEBUG);
472 if (in_array($data['type'], ActivityPub::CONTENT_TYPES)) {
473 return self::processObject($data);
476 if ($data['type'] == 'Announce') {
477 if (empty($data['object'])) {
480 return self::fetchObject($data['object']);
483 logger('Unhandled object type: ' . $data['type'], LOGGER_DEBUG);
493 private static function processObject($object)
495 if (empty($object['id'])) {
500 $object_data['object_type'] = $object['type'];
501 $object_data['id'] = $object['id'];
503 if (!empty($object['inReplyTo'])) {
504 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
506 $object_data['reply-to-id'] = $object_data['id'];
509 $object_data['published'] = defaults($object, 'published', null);
510 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
512 if (empty($object_data['published']) && !empty($object_data['updated'])) {
513 $object_data['published'] = $object_data['updated'];
516 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
518 $actor = defaults($object, 'actor', null);
521 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
522 $object_data['owner'] = $object_data['author'] = $actor;
523 $object_data['context'] = defaults($object, 'context', null);
524 $object_data['conversation'] = defaults($object, 'conversation', null);
525 $object_data['sensitive'] = defaults($object, 'sensitive', null);
526 $object_data['name'] = defaults($object, 'title', null);
527 $object_data['name'] = defaults($object, 'name', $object_data['name']);
528 $object_data['summary'] = defaults($object, 'summary', null);
529 $object_data['content'] = defaults($object, 'content', null);
530 $object_data['source'] = defaults($object, 'source', null);
531 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
532 $object_data['attachments'] = defaults($object, 'attachment', null);
533 $object_data['tags'] = defaults($object, 'tag', null);
534 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
535 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
536 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
538 // Common object data:
541 // @context, type, actor, signature, mediaType, duration, replies, icon
543 // Also missing: (Defined in the standard, but currently unused)
544 // audience, preview, endTime, startTime, generator, image
549 // contentMap, announcement_count, announcements, context_id, likes, like_count
550 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
555 // category, licence, language, commentsEnabled
558 // views, waitTranscoding, state, support, subtitleLanguage
559 // likes, dislikes, shares, comments