3 * @file src/Protocol/ActivityPub.php
5 namespace Friendica\Protocol;
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\Item;
16 use Friendica\Model\Term;
17 use Friendica\Model\User;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Crypto;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Content\Text\HTML;
22 use Friendica\Core\Cache;
23 use digitalbazaar\jsonld;
26 * @brief ActivityPub Protocol class
27 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
28 * https://www.w3.org/TR/activitypub/
29 * https://www.w3.org/TR/activitystreams-core/
30 * https://www.w3.org/TR/activitystreams-vocabulary/
32 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
33 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
35 * Digest: https://tools.ietf.org/html/rfc5843
36 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
37 * https://github.com/digitalbazaar/php-json-ld
39 * Part of the code for HTTP signing is taken from the Osada project.
40 * https://framagit.org/macgirvin/osada
45 * - Activities: Dislike, Update, Delete
46 * - Object Types: Person, Tombstome
49 * - Activities: Like, Dislike, Update, Delete
50 * - Object Tyoes: Article, Announce, Person, Tombstone
53 * - Message distribution
54 * - Endpoints: Outbox, Object, Follower, Following
59 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
61 public static function jsonld_document_loader($url)
65 $x = debug_backtrace();
68 if ($n['function'] === __FUNCTION__) {
75 logger('jsonld bomb detected at: ' . $url);
79 $result = Cache::get('jsonld_document_loader:' . $url);
80 if (!is_null($result)) {
84 $data = jsonld_default_document_loader($url);
85 Cache::set('jsonld_document_loader:' . $url, $data, CACHE_DAY);
89 public static function compactJsonLD($json)
91 jsonld_set_document_loader('Friendica\Protocol\ActivityPub::jsonld_document_loader');
93 $context = (object)['as' => 'https://www.w3.org/ns/activitystreams',
94 'w3sec' => 'https://w3id.org/security',
95 'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'],
96 'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'],
97 'uuid' => (object)['@id' => 'http://schema.org/identifier', '@type' => '@id']];
99 $jsonobj = json_decode(json_encode($json));
101 $compacted = jsonld_compact($jsonobj, $context);
103 return json_decode(json_encode($compacted), true);
106 public static function isRequest()
108 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
109 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
112 public static function transmit($data, $target, $uid)
114 $owner = User::getOwnerDataById($uid);
120 $content = json_encode($data);
122 // Header data that is about to be signed.
123 $host = parse_url($target, PHP_URL_HOST);
124 $path = parse_url($target, PHP_URL_PATH);
125 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
126 $content_length = strlen($content);
128 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
130 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
132 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
134 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
136 $headers[] = 'Content-Type: application/activity+json';
138 Network::post($target, $content, $headers);
139 $return_code = BaseObject::getApp()->get_curl_code();
141 logger('Transmit to ' . $target . ' returned ' . $return_code);
145 * Return the ActivityPub profile of the given user
147 * @param integer $uid User ID
150 public static function profile($uid)
152 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application', 'page-flags'];
153 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
154 'account_removed' => false, 'verified' => true];
155 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
156 $user = DBA::selectFirst('user', $fields, $condition);
157 if (!DBA::isResult($user)) {
161 $fields = ['locality', 'region', 'country-name'];
162 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
163 if (!DBA::isResult($profile)) {
167 $fields = ['name', 'url', 'location', 'about', 'avatar'];
168 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
169 if (!DBA::isResult($contact)) {
173 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
174 ['vcard' => 'http://www.w3.org/2006/vcard/ns#', 'uuid' => 'http://schema.org/identifier',
175 'sensitive' => 'as:sensitive', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers']]];
177 $data['id'] = $contact['url'];
178 $data['uuid'] = $user['guid'];
179 $data['type'] = $accounttype[$user['account-type']];
180 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
181 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
182 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
183 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
184 $data['preferredUsername'] = $user['nickname'];
185 $data['name'] = $contact['name'];
186 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
187 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
188 $data['summary'] = $contact['about'];
189 $data['url'] = $contact['url'];
190 $data['manuallyApprovesFollowers'] = in_array($profile['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
191 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
192 'owner' => $contact['url'],
193 'publicKeyPem' => $user['pubkey']];
194 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
195 $data['icon'] = ['type' => 'Image',
196 'url' => $contact['avatar']];
198 // tags: https://kitty.town/@inmysocks/100656097926961126.json
202 public static function createPermissionBlockForItem($item)
204 $data = ['to' => [], 'cc' => []];
206 $terms = Term::tagArrayFromItemId($item['id']);
208 if (!$item['private']) {
209 $data['to'][] = self::PUBLIC;
210 $data['cc'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
212 foreach ($terms as $term) {
213 if ($term['type'] != TERM_MENTION) {
216 $profile = self::fetchprofile($term['url']);
217 if (!empty($profile)) {
218 $data['cc'][] = $profile['url'];
222 //$data['cc'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
223 $receiver_list = Item::enumeratePermissions($item);
227 foreach ($terms as $term) {
228 if ($term['type'] != TERM_MENTION) {
231 $cid = Contact::getIdForURL($term['url'], $item['uid']);
232 if (!empty($cid) && in_array($cid, $receiver_list)) {
233 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
234 $data['to'][] = $contact['url'];
238 foreach ($receiver_list as $receiver) {
239 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
240 $data['cc'][] = $contact['url'];
243 if (empty($data['to'])) {
244 $data['to'] = $data['cc'];
252 public static function fetchTargetInboxes($item)
256 $terms = Term::tagArrayFromItemId($item['id']);
257 if (!$item['private']) {
258 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $item['uid'],
259 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
260 while ($contact = DBA::fetch($contacts)) {
261 $contact = defaults($contact, 'batch', $contact['notify']);
262 $inboxes[$contact] = $contact;
264 DBA::close($contacts);
266 foreach ($terms as $term) {
267 if ($term['type'] != TERM_MENTION) {
270 $profile = self::fetchprofile($term['url']);
271 if (!empty($profile)) {
272 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
273 $inboxes[$target] = $target;
277 $receiver_list = Item::enumeratePermissions($item);
281 foreach ($terms as $term) {
282 if ($term['type'] != TERM_MENTION) {
285 $cid = Contact::getIdForURL($term['url'], $item['uid']);
286 if (!empty($cid) && in_array($cid, $receiver_list)) {
287 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
288 $profile = self::fetchprofile($contact['url']);
289 if (!empty($profile['network'])) {
290 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
291 $inboxes[$target] = $target;
296 foreach ($receiver_list as $receiver) {
297 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
298 $profile = self::fetchprofile($contact['url']);
299 if (!empty($profile['network'])) {
300 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
301 $inboxes[$target] = $target;
306 $profile = self::fetchprofile($item['author-link']);
307 if (!empty($profile['sharedinbox'])) {
308 unset($inboxes[$profile['sharedinbox']]);
311 if (!empty($profile['inbox'])) {
312 unset($inboxes[$profile['inbox']]);
318 public static function createActivityFromItem($item_id)
320 $item = Item::selectFirst([], ['id' => $item_id]);
322 if (!DBA::isResult($item)) {
326 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
327 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
328 if (DBA::isResult($conversation)) {
329 $data = json_decode($conversation['source']);
335 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
336 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
337 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
338 'conversation' => 'ostatus:conversation',
339 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
341 $data['type'] = 'Create';
342 $data['id'] = $item['uri'] . '#activity';
343 $data['actor'] = $item['author-link'];
345 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
347 if ($item["created"] != $item["edited"]) {
348 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
351 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
353 $data['object'] = self::createNote($item);
357 public static function createObjectFromItemID($item_id)
359 $item = Item::selectFirst([], ['id' => $item_id]);
361 if (!DBA::isResult($item)) {
365 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
366 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
367 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
368 'conversation' => 'ostatus:conversation',
369 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
371 $data = array_merge($data, self::createNote($item));
377 private static function createTagList($item)
381 $terms = Term::tagArrayFromItemId($item['id']);
382 foreach ($terms as $term) {
383 if ($term['type'] == TERM_MENTION) {
384 $contact = Contact::getDetailsByURL($term['url']);
385 if (!empty($contact['addr'])) {
386 $mention = '@' . $contact['addr'];
388 $mention = '@' . $term['url'];
391 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
398 public static function createNote($item)
401 $data['type'] = 'Note';
402 $data['id'] = $item['uri'];
404 if ($item['uri'] != $item['thr-parent']) {
405 $data['inReplyTo'] = $item['thr-parent'];
408 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
409 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
410 $conversation_uri = $conversation['conversation-uri'];
412 $conversation_uri = $item['parent-uri'];
415 $data['context'] = $data['conversation'] = $conversation_uri;
416 $data['actor'] = $item['author-link'];
417 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
418 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
420 if ($item["created"] != $item["edited"]) {
421 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
424 $data['attributedTo'] = $item['author-link'];
425 $data['name'] = BBCode::convert($item['title'], false, 7);
426 $data['content'] = BBCode::convert($item['body'], false, 7);
427 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
428 $data['summary'] = ''; // Ignore by now
429 $data['sensitive'] = false; // - Query NSFW
430 //$data['emoji'] = []; // Ignore by now
431 $data['tag'] = self::createTagList($item);
432 $data['attachment'] = []; // @ToDo
436 public static function transmitActivity($activity, $target, $uid)
438 $profile = self::fetchprofile($target);
440 $owner = User::getOwnerDataById($uid);
442 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
443 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
445 'actor' => $owner['url'],
446 'object' => $profile['url'],
447 'to' => $profile['url']];
449 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
450 return self::transmit($data, $profile['inbox'], $uid);
453 public static function transmitContactAccept($target, $id, $uid)
455 $profile = self::fetchprofile($target);
457 $owner = User::getOwnerDataById($uid);
458 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
459 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
461 'actor' => $owner['url'],
462 'object' => ['id' => $id, 'type' => 'Follow',
463 'actor' => $profile['url'],
464 'object' => $owner['url']],
465 'to' => $profile['url']];
467 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
468 return self::transmit($data, $profile['inbox'], $uid);
471 public static function transmitContactReject($target, $id, $uid)
473 $profile = self::fetchprofile($target);
475 $owner = User::getOwnerDataById($uid);
476 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
477 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
479 'actor' => $owner['url'],
480 'object' => ['id' => $id, 'type' => 'Follow',
481 'actor' => $profile['url'],
482 'object' => $owner['url']],
483 'to' => $profile['url']];
485 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
486 return self::transmit($data, $profile['inbox'], $uid);
489 public static function transmitContactUndo($target, $uid)
491 $profile = self::fetchprofile($target);
493 $id = System::baseUrl() . '/activity/' . System::createGUID();
495 $owner = User::getOwnerDataById($uid);
496 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
499 'actor' => $owner['url'],
500 'object' => ['id' => $id, 'type' => 'Follow',
501 'actor' => $owner['url'],
502 'object' => $profile['url']],
503 'to' => $profile['url']];
505 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
506 return self::transmit($data, $profile['inbox'], $uid);
510 * Fetches ActivityPub content from the given url
512 * @param string $url content url
515 public static function fetchContent($url)
517 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
518 if (!$ret['success'] || empty($ret['body'])) {
522 return json_decode($ret['body'], true);
526 * Resolves the profile url from the address by using webfinger
528 * @param string $addr profile address (user@domain.tld)
531 private static function addrToUrl($addr)
533 $addr_parts = explode('@', $addr);
534 if (count($addr_parts) != 2) {
538 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
540 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
541 if (!$ret['success'] || empty($ret['body'])) {
545 $data = json_decode($ret['body'], true);
547 if (empty($data['links'])) {
551 foreach ($data['links'] as $link) {
552 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
556 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
557 return $link['href'];
564 public static function verifySignature($content, $http_headers)
566 $object = json_decode($content, true);
568 if (empty($object)) {
572 $actor = self::processElement($object, 'actor', 'id');
575 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
577 // First take every header
578 foreach ($http_headers as $k => $v) {
579 $field = str_replace('_', '-', strtolower($k));
580 $headers[$field] = $v;
583 // Now add every http header
584 foreach ($http_headers as $k => $v) {
585 if (strpos($k, 'HTTP_') === 0) {
586 $field = str_replace('_', '-', strtolower(substr($k, 5)));
587 $headers[$field] = $v;
591 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
593 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
598 foreach ($sig_block['headers'] as $h) {
599 if (array_key_exists($h, $headers)) {
600 $signed_data .= $h . ': ' . $headers[$h] . "\n";
603 $signed_data = rtrim($signed_data, "\n");
605 if (empty($signed_data)) {
611 if ($sig_block['algorithm'] === 'rsa-sha256') {
612 $algorithm = 'sha256';
615 if ($sig_block['algorithm'] === 'rsa-sha512') {
616 $algorithm = 'sha512';
619 if (empty($algorithm)) {
623 $key = self::fetchKey($sig_block['keyId'], $actor);
629 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
633 // Check the digest when it is part of the signed data
634 if (in_array('digest', $sig_block['headers'])) {
635 $digest = explode('=', $headers['digest'], 2);
636 if ($digest[0] === 'SHA-256') {
639 if ($digest[0] === 'SHA-512') {
643 /// @todo add all hashes from the rfc
645 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
650 // Check the content-length when it is part of the signed data
651 if (in_array('content-length', $sig_block['headers'])) {
652 if (strlen($content) != $headers['content-length']) {
661 private static function fetchKey($id, $actor)
663 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
665 $profile = self::fetchprofile($url);
666 if (!empty($profile)) {
667 return $profile['pubkey'];
668 } elseif ($url != $actor) {
669 $profile = self::fetchprofile($actor);
670 if (!empty($profile)) {
671 return $profile['pubkey'];
681 * @param string $header
682 * @return array associate array with
683 * - \e string \b keyID
684 * - \e string \b algorithm
685 * - \e array \b headers
686 * - \e string \b signature
688 private static function parseSigHeader($header)
693 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
694 $ret['keyId'] = $matches[1];
697 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
698 $ret['algorithm'] = $matches[1];
701 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
702 $ret['headers'] = explode(' ', $matches[1]);
705 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
706 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
712 public static function fetchprofile($url, $update = false)
719 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
720 if (DBA::isResult($apcontact)) {
724 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
725 if (DBA::isResult($apcontact)) {
729 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
730 if (DBA::isResult($apcontact)) {
735 if (empty(parse_url($url, PHP_URL_SCHEME))) {
736 $url = self::addrToUrl($url);
742 $data = self::fetchContent($url);
744 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
749 $apcontact['url'] = $data['id'];
750 $apcontact['uuid'] = defaults($data, 'uuid', null);
751 $apcontact['type'] = defaults($data, 'type', null);
752 $apcontact['following'] = defaults($data, 'following', null);
753 $apcontact['followers'] = defaults($data, 'followers', null);
754 $apcontact['inbox'] = defaults($data, 'inbox', null);
755 $apcontact['outbox'] = defaults($data, 'outbox', null);
756 $apcontact['sharedinbox'] = self::processElement($data, 'endpoints', 'sharedInbox');
757 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
758 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
759 $apcontact['about'] = defaults($data, 'summary', '');
760 $apcontact['photo'] = self::processElement($data, 'icon', 'url');
761 $apcontact['alias'] = self::processElement($data, 'url', 'href');
763 $parts = parse_url($apcontact['url']);
764 unset($parts['scheme']);
765 unset($parts['path']);
766 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
768 $apcontact['pubkey'] = trim(self::processElement($data, 'publicKey', 'publicKeyPem'));
771 // manuallyApprovesFollowers
774 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
776 // Unhandled from Misskey
777 // sharedInbox, isCat
779 // Unhandled from Kroeg
780 // kroeg:blocks, updated
782 // Check if the address is resolvable
783 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
784 $parts = parse_url($apcontact['url']);
785 unset($parts['path']);
786 $apcontact['baseurl'] = Network::unparseURL($parts);
788 $apcontact['addr'] = null;
791 if ($apcontact['url'] == $apcontact['alias']) {
792 $apcontact['alias'] = null;
795 $apcontact['updated'] = DateTimeFormat::utcNow();
797 DBA::update('apcontact', $apcontact, ['url' => $url], true);
803 * Fetches a profile from the given url into an array that is compatible to Probe::uri
805 * @param string $url profile url
808 public static function probeProfile($url)
810 $apcontact = self::fetchprofile($url, true);
811 if (empty($apcontact)) {
815 $profile = ['network' => Protocol::ACTIVITYPUB];
816 $profile['nick'] = $apcontact['nick'];
817 $profile['name'] = $apcontact['name'];
818 $profile['guid'] = $apcontact['uuid'];
819 $profile['url'] = $apcontact['url'];
820 $profile['addr'] = $apcontact['addr'];
821 $profile['alias'] = $apcontact['alias'];
822 $profile['photo'] = $apcontact['photo'];
823 // $profile['community']
824 // $profile['keywords']
825 // $profile['location']
826 $profile['about'] = $apcontact['about'];
827 $profile['batch'] = $apcontact['sharedinbox'];
828 $profile['notify'] = $apcontact['inbox'];
829 $profile['poll'] = $apcontact['outbox'];
830 $profile['pubkey'] = $apcontact['pubkey'];
831 $profile['baseurl'] = $apcontact['baseurl'];
833 // Remove all "null" fields
834 foreach ($profile as $field => $content) {
835 if (is_null($content)) {
836 unset($profile[$field]);
843 public static function processInbox($body, $header, $uid)
845 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
847 if (!self::verifySignature($body, $header)) {
848 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
852 $activity = json_decode($body, true);
854 if (!is_array($activity)) {
855 logger('Invalid body.', LOGGER_DEBUG);
859 self::processActivity($activity, $body, $uid);
862 public static function fetchOutbox($url)
864 $data = self::fetchContent($url);
869 if (!empty($data['orderedItems'])) {
870 $items = $data['orderedItems'];
871 } elseif (!empty($data['first']['orderedItems'])) {
872 $items = $data['first']['orderedItems'];
873 } elseif (!empty($data['first'])) {
874 self::fetchOutbox($data['first']);
880 foreach ($items as $activity) {
881 self::processActivity($activity);
885 private static function prepareObjectData($activity, $uid)
887 $actor = self::processElement($activity, 'actor', 'id');
889 logger('Empty actor', LOGGER_DEBUG);
893 // Fetch all receivers from to, cc, bto and bcc
894 $receivers = self::getReceivers($activity, $actor);
896 // When it is a delivery to a personal inbox we add that user to the receivers
898 $owner = User::getOwnerDataById($uid);
899 $additional = ['uid:' . $uid => $uid];
900 $receivers = array_merge($receivers, $additional);
903 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
905 $public = in_array(0, $receivers);
907 if (is_string($activity['object'])) {
908 $object_url = $activity['object'];
909 } elseif (!empty($activity['object']['id'])) {
910 $object_url = $activity['object']['id'];
912 logger('No object found', LOGGER_DEBUG);
916 // Fetch the content only on activities where this matters
917 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
918 $object_data = self::fetchObject($object_url, $activity['object']);
919 if (empty($object_data)) {
920 logger("Object data couldn't be processed", LOGGER_DEBUG);
923 } elseif ($activity['type'] == 'Accept') {
925 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
926 $object_data['object'] = self::processElement($activity, 'object', 'actor');
927 } elseif ($activity['type'] == 'Undo') {
929 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
930 $object_data['object'] = self::processElement($activity, 'object', 'object');
931 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
932 // Create a mostly empty array out of the activity data (instead of the object).
933 // This way we later don't have to check for the existence of ech individual array element.
934 $object_data = self::processCommonData($activity);
935 $object_data['name'] = $activity['type'];
936 $object_data['author'] = $activity['actor'];
937 $object_data['object'] = $object_url;
938 } elseif ($activity['type'] == 'Follow') {
939 $object_data['id'] = $activity['id'];
940 $object_data['object'] = $object_url;
945 $object_data = self::addActivityFields($object_data, $activity);
947 $object_data['type'] = $activity['type'];
948 $object_data['owner'] = $actor;
949 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
954 private static function processActivity($activity, $body = '', $uid = null)
956 if (empty($activity['type'])) {
957 logger('Empty type', LOGGER_DEBUG);
961 if (empty($activity['object'])) {
962 logger('Empty object', LOGGER_DEBUG);
966 if (empty($activity['actor'])) {
967 logger('Empty actor', LOGGER_DEBUG);
973 // title, atomUri, context_id, statusnetConversationId
976 // context, location, signature;
978 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
980 $object_data = self::prepareObjectData($activity, $uid);
981 if (empty($object_data)) {
982 logger('No object data found', LOGGER_DEBUG);
986 switch ($activity['type']) {
989 self::createItem($object_data, $body);
993 self::likeItem($object_data, $body);
1006 self::followUser($object_data);
1010 if ($object_data['object_type'] == 'Follow') {
1011 self::acceptFollowUser($object_data);
1016 if ($object_data['object_type'] == 'Follow') {
1017 self::undoFollowUser($object_data);
1022 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
1027 private static function getReceivers($activity, $actor)
1031 if (!empty($actor)) {
1032 $profile = self::fetchprofile($actor);
1033 $followers = defaults($profile, 'followers', '');
1035 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
1037 logger('Empty actor', LOGGER_DEBUG);
1041 $elements = ['to', 'cc', 'bto', 'bcc'];
1042 foreach ($elements as $element) {
1043 if (empty($activity[$element])) {
1047 // The receiver can be an arror or a string
1048 if (is_string($activity[$element])) {
1049 $activity[$element] = [$activity[$element]];
1052 foreach ($activity[$element] as $receiver) {
1053 if ($receiver == self::PUBLIC) {
1054 $receivers['uid:0'] = 0;
1057 if (($receiver == self::PUBLIC) && !empty($actor)) {
1058 // This will most likely catch all OStatus connections to Mastodon
1059 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1060 $contacts = DBA::select('contact', ['uid'], $condition);
1061 while ($contact = DBA::fetch($contacts)) {
1062 if ($contact['uid'] != 0) {
1063 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1066 DBA::close($contacts);
1069 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1070 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1071 'network' => Protocol::ACTIVITYPUB];
1072 $contacts = DBA::select('contact', ['uid'], $condition);
1073 while ($contact = DBA::fetch($contacts)) {
1074 if ($contact['uid'] != 0) {
1075 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1078 DBA::close($contacts);
1082 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1083 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1084 if (!DBA::isResult($contact)) {
1087 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1093 private static function addActivityFields($object_data, $activity)
1095 if (!empty($activity['published']) && empty($object_data['published'])) {
1096 $object_data['published'] = $activity['published'];
1099 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1100 $object_data['updated'] = $activity['updated'];
1103 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1104 $object_data['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
1107 if (!empty($activity['instrument'])) {
1108 $object_data['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
1110 return $object_data;
1113 private static function fetchObject($object_url, $object = [], $public = true)
1116 $data = self::fetchContent($object_url);
1118 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1119 $data = $object_url;
1123 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1127 if (is_string($data)) {
1128 $item = Item::selectFirst([], ['uri' => $data]);
1129 if (!DBA::isResult($item)) {
1130 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1133 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1134 $data = self::createNote($item);
1137 if (empty($data['type'])) {
1138 logger('Empty type', LOGGER_DEBUG);
1141 $type = $data['type'];
1142 logger('Type ' . $type, LOGGER_DEBUG);
1145 if (in_array($type, ['Note', 'Article', 'Video'])) {
1146 $common = self::processCommonData($data);
1151 return array_merge($common, self::processNote($data));
1153 return array_merge($common, self::processArticle($data));
1155 return array_merge($common, self::processVideo($data));
1158 if (empty($data['object'])) {
1161 return self::fetchObject($data['object']);
1168 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1173 private static function processCommonData(&$object)
1175 if (empty($object['id'])) {
1180 $object_data['type'] = $object['type'];
1181 $object_data['uri'] = $object['id'];
1183 if (!empty($object['inReplyTo'])) {
1184 $object_data['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
1186 $object_data['reply-to-uri'] = $object_data['uri'];
1189 $object_data['published'] = defaults($object, 'published', null);
1190 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1192 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1193 $object_data['published'] = $object_data['updated'];
1196 $object_data['uuid'] = defaults($object, 'uuid', null);
1197 $object_data['owner'] = $object_data['author'] = self::processElement($object, 'attributedTo', 'id');
1198 $object_data['context'] = defaults($object, 'context', null);
1199 $object_data['conversation'] = defaults($object, 'conversation', null);
1200 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1201 $object_data['name'] = defaults($object, 'title', null);
1202 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1203 $object_data['summary'] = defaults($object, 'summary', null);
1204 $object_data['content'] = defaults($object, 'content', null);
1205 $object_data['source'] = defaults($object, 'source', null);
1206 $object_data['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
1207 $object_data['attachments'] = defaults($object, 'attachment', null);
1208 $object_data['tags'] = defaults($object, 'tag', null);
1209 $object_data['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
1210 $object_data['alternate-url'] = self::processElement($object, 'url', 'href');
1211 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1214 // @context, type, actor, signature, mediaType, duration, replies, icon
1216 // Also missing: (Defined in the standard, but currently unused)
1217 // audience, preview, endTime, startTime, generator, image
1219 return $object_data;
1222 private static function processNote($object)
1227 // emoji, atomUri, inReplyToAtomUri
1230 // contentMap, announcement_count, announcements, context_id, likes, like_count
1231 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1233 return $object_data;
1236 private static function processArticle($object)
1240 return $object_data;
1243 private static function processVideo($object)
1248 // category, licence, language, commentsEnabled
1251 // views, waitTranscoding, state, support, subtitleLanguage
1252 // likes, dislikes, shares, comments
1254 return $object_data;
1257 private static function processElement($array, $element, $key, $type = null, $type_value = null)
1259 if (empty($array)) {
1263 if (empty($array[$element])) {
1267 if (is_string($array[$element])) {
1268 return $array[$element];
1271 if (is_null($type_value)) {
1272 if (!empty($array[$element][$key])) {
1273 return $array[$element][$key];
1276 if (!empty($array[$element][0][$key])) {
1277 return $array[$element][0][$key];
1283 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
1284 return $array[$element][$key];
1287 /// @todo Add array search
1292 private static function convertMentions($body)
1294 $URLSearchString = "^\[\]";
1295 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1300 private static function constructTagList($tags, $sensitive)
1307 foreach ($tags as $tag) {
1308 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1309 if (!empty($tag_text)) {
1313 if (empty($tag['href'])) {
1318 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1322 /// @todo add nsfw for $sensitive
1327 private static function constructAttachList($attachments, $item)
1329 if (empty($attachments)) {
1333 foreach ($attachments as $attach) {
1334 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1335 if ($filetype == 'image') {
1336 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1338 if (!empty($item["attach"])) {
1339 $item["attach"] .= ',';
1341 $item["attach"] = '';
1343 if (!isset($attach['length'])) {
1344 $attach['length'] = "0";
1346 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1353 private static function createItem($activity, $body)
1356 $item['verb'] = ACTIVITY_POST;
1357 $item['parent-uri'] = $activity['reply-to-uri'];
1359 if ($activity['reply-to-uri'] == $activity['uri']) {
1360 $item['gravity'] = GRAVITY_PARENT;
1361 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1363 $item['gravity'] = GRAVITY_COMMENT;
1364 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1367 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1368 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1369 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1372 self::postItem($activity, $item, $body);
1375 private static function likeItem($activity, $body)
1378 $item['verb'] = ACTIVITY_LIKE;
1379 $item['parent-uri'] = $activity['object'];
1380 $item['gravity'] = GRAVITY_ACTIVITY;
1381 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1383 self::postItem($activity, $item, $body);
1386 private static function postItem($activity, $item, $body)
1388 /// @todo What to do with $activity['context']?
1390 $item['network'] = Protocol::ACTIVITYPUB;
1391 $item['private'] = !in_array(0, $activity['receiver']);
1392 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1393 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1394 $item['uri'] = $activity['uri'];
1395 $item['created'] = $activity['published'];
1396 $item['edited'] = $activity['updated'];
1397 $item['guid'] = $activity['uuid'];
1398 $item['title'] = HTML::toBBCode($activity['name']);
1399 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1400 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1401 $item['location'] = $activity['location'];
1402 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1403 $item['app'] = $activity['service'];
1404 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1406 $item = self::constructAttachList($activity['attachments'], $item);
1408 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1409 if (!empty($source)) {
1410 $item['body'] = $source;
1413 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1414 $item['source'] = $body;
1415 $item['conversation-uri'] = $activity['conversation'];
1417 foreach ($activity['receiver'] as $receiver) {
1418 $item['uid'] = $receiver;
1419 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1421 if (($receiver != 0) && empty($item['contact-id'])) {
1422 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1425 $item_id = Item::insert($item);
1426 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1430 private static function fetchMissingActivity($url, $child)
1432 $object = ActivityPub::fetchContent($url);
1433 if (empty($object)) {
1434 logger('Activity ' . $url . ' was not fetchable, aborting.');
1439 $activity['@context'] = $object['@context'];
1440 unset($object['@context']);
1441 $activity['id'] = $object['id'];
1442 $activity['to'] = defaults($object, 'to', []);
1443 $activity['cc'] = defaults($object, 'cc', []);
1444 $activity['actor'] = $child['author'];
1445 $activity['object'] = $object;
1446 $activity['published'] = $object['published'];
1447 $activity['type'] = 'Create';
1448 self::processActivity($activity);
1449 logger('Activity ' . $url . ' had been fetched and processed.');
1452 private static function getUserOfObject($object)
1454 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1455 if (!DBA::isResult($self)) {
1458 return $self['uid'];
1462 private static function followUser($activity)
1464 $uid = self::getUserOfObject($activity['object']);
1469 $owner = User::getOwnerDataById($uid);
1471 $cid = Contact::getIdForURL($activity['owner'], $uid);
1473 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1478 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1479 'author-link' => $activity['owner']];
1481 Contact::addRelationship($owner, $contact, $item);
1482 $cid = Contact::getIdForURL($activity['owner'], $uid);
1487 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1488 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1489 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1492 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1493 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1496 private static function acceptFollowUser($activity)
1498 $uid = self::getUserOfObject($activity['object']);
1503 $owner = User::getOwnerDataById($uid);
1505 $cid = Contact::getIdForURL($activity['owner'], $uid);
1507 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1511 $fields = ['pending' => false];
1513 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1514 if ($contact['rel'] == Contact::FOLLOWER) {
1515 $fields['rel'] = Contact::FRIEND;
1518 $condition = ['id' => $cid];
1519 DBA::update('contact', $fields, $condition);
1520 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1523 private static function undoFollowUser($activity)
1525 $uid = self::getUserOfObject($activity['object']);
1530 $owner = User::getOwnerDataById($uid);
1532 $cid = Contact::getIdForURL($activity['owner'], $uid);
1534 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1538 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1539 if (!DBA::isResult($contact)) {
1543 Contact::removeFollower($owner, $contact);
1544 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);