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\Network\Probe;
25 * @brief ActivityPub Protocol class
26 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
27 * https://www.w3.org/TR/activitypub/
28 * https://www.w3.org/TR/activitystreams-core/
29 * https://www.w3.org/TR/activitystreams-vocabulary/
31 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
32 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
34 * Digest: https://tools.ietf.org/html/rfc5843
35 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
36 * https://github.com/digitalbazaar/php-json-ld
38 * Part of the code for HTTP signing is taken from the Osada project.
39 * https://framagit.org/macgirvin/osada
44 * - Activities: Dislike, Update, Delete
45 * - Object Types: Person, Tombstome
48 * - Activities: Like, Dislike, Update, Delete
49 * - Object Tyoes: Article, Announce, Person, Tombstone
52 * - Message distribution
53 * - Endpoints: Outbox, Object, Follower, Following
58 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
60 public static function isRequest()
62 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
63 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
66 public static function transmit($data, $target, $uid)
68 $owner = User::getOwnerDataById($uid);
74 $content = json_encode($data);
76 // Header data that is about to be signed.
77 $host = parse_url($target, PHP_URL_HOST);
78 $path = parse_url($target, PHP_URL_PATH);
79 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
80 $content_length = strlen($content);
82 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
84 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
86 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
88 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
90 $headers[] = 'Content-Type: application/activity+json';
92 Network::post($target, $content, $headers);
93 $return_code = BaseObject::getApp()->get_curl_code();
95 logger('Transmit to ' . $target . ' returned ' . $return_code);
99 * Return the ActivityPub profile of the given user
101 * @param integer $uid User ID
104 public static function profile($uid)
106 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application', 'page-flags'];
107 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
108 'account_removed' => false, 'verified' => true];
109 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
110 $user = DBA::selectFirst('user', $fields, $condition);
111 if (!DBA::isResult($user)) {
115 $fields = ['locality', 'region', 'country-name'];
116 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
117 if (!DBA::isResult($profile)) {
121 $fields = ['name', 'url', 'location', 'about', 'avatar'];
122 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
123 if (!DBA::isResult($contact)) {
127 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
128 ['uuid' => 'http://schema.org/identifier', 'sensitive' => 'as:sensitive',
129 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
130 'vcard' => 'http://www.w3.org/2006/vcard/ns#']]];
132 $data['id'] = $contact['url'];
133 $data['uuid'] = $user['guid'];
134 $data['type'] = $accounttype[$user['account-type']];
135 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
136 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
137 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
138 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
139 $data['preferredUsername'] = $user['nickname'];
140 $data['name'] = $contact['name'];
141 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
142 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
143 $data['summary'] = $contact['about'];
144 $data['url'] = $contact['url'];
145 $data['manuallyApprovesFollowers'] = in_array($profile['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
146 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
147 'owner' => $contact['url'],
148 'publicKeyPem' => $user['pubkey']];
149 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
150 $data['icon'] = ['type' => 'Image',
151 'url' => $contact['avatar']];
153 // tags: https://kitty.town/@inmysocks/100656097926961126.json
157 public static function createPermissionBlockForItem($item)
159 $data = ['to' => [], 'cc' => []];
161 $terms = Term::tagArrayFromItemId($item['id']);
163 if (!$item['private']) {
164 $data['to'][] = self::PUBLIC;
165 $data['cc'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
167 foreach ($terms as $term) {
168 if ($term['type'] != TERM_MENTION) {
171 $profile = Probe::uri($term['url'], Protocol::ACTIVITYPUB);
172 if ($profile['network'] == Protocol::ACTIVITYPUB) {
173 $data['cc'][] = $profile['url'];
177 $data['to'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
178 $receiver_list = Item::enumeratePermissions($item);
182 foreach ($terms as $term) {
183 if ($term['type'] != TERM_MENTION) {
186 $cid = Contact::getIdForURL($term['url'], $item['uid']);
187 if (!empty($cid) && in_array($cid, $receiver_list)) {
188 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
189 $data['to'][] = $contact['url'];
193 foreach ($receiver_list as $receiver) {
194 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
195 $data['cc'][] = $contact['url'];
198 if (empty($data['to'])) {
199 $data['to'] = $data['cc'];
207 public static function fetchTargetInboxes($item)
211 $terms = Term::tagArrayFromItemId($item['id']);
212 if (!$item['private']) {
213 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $item['uid'],
214 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
215 while ($contact = DBA::fetch($contacts)) {
216 $contact = defaults($contact, 'batch', $contact['notify']);
217 $inboxes[$contact] = $contact;
219 DBA::close($contacts);
221 foreach ($terms as $term) {
222 if ($term['type'] != TERM_MENTION) {
225 $profile = Probe::uri($term['url'], Protocol::ACTIVITYPUB);
226 if ($profile['network'] == Protocol::ACTIVITYPUB) {
227 $target = defaults($profile, 'batch', $profile['notify']);
228 $inboxes[$target] = $target;
232 $receiver_list = Item::enumeratePermissions($item);
236 foreach ($terms as $term) {
237 if ($term['type'] != TERM_MENTION) {
240 $cid = Contact::getIdForURL($term['url'], $item['uid']);
241 if (!empty($cid) && in_array($cid, $receiver_list)) {
242 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
243 $profile = Probe::uri($contact['url'], Protocol::ACTIVITYPUB);
244 if ($profile['network'] == Protocol::ACTIVITYPUB) {
245 //$target = defaults($profile, 'batch', $profile['notify']);
246 $target = $profile['notify'];
247 $inboxes[$target] = $target;
252 foreach ($receiver_list as $receiver) {
253 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
254 $profile = Probe::uri($contact['url'], Protocol::ACTIVITYPUB);
255 if ($profile['network'] == Protocol::ACTIVITYPUB) {
256 //$target = defaults($profile, 'batch', $profile['notify']);
257 $target = $profile['notify'];
258 $inboxes[$target] = $target;
263 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
264 if (!empty($profile['batch'])) {
265 unset($inboxes[$profile['batch']]);
268 if (!empty($profile['notify'])) {
269 unset($inboxes[$profile['notify']]);
275 public static function createActivityFromItem($item_id)
277 $item = Item::selectFirst([], ['id' => $item_id]);
279 if (!DBA::isResult($item)) {
283 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
284 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
285 if (DBA::isResult($conversation)) {
286 $data = json_decode($conversation['source']);
292 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
293 ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
294 'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
295 'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
296 'toot' => 'http://joinmastodon.org/ns#']]];
298 $data['type'] = 'Create';
299 $data['id'] = $item['uri'] . '#activity';
300 $data['actor'] = $item['author-link'];
302 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
304 if ($item["created"] != $item["edited"]) {
305 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
308 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
310 $data['object'] = self::createNote($item);
314 public static function createObjectFromItemID($item_id)
316 $item = Item::selectFirst([], ['id' => $item_id]);
318 if (!DBA::isResult($item)) {
322 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
323 ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
324 'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
325 'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
326 'toot' => 'http://joinmastodon.org/ns#']]];
328 $data = array_merge($data, self::createNote($item));
334 private static function createTagList($item)
338 $receiver_list = Item::enumeratePermissions($item);
339 foreach ($receiver_list as $receiver) {
340 $contact = DBA::selectFirst('contact', ['url', 'addr'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
341 if (!empty($contact['addr'])) {
342 $mention = '@' . $contact['addr'];
344 $mention = '@' . $term['url'];
346 $tags[] = ['type' => 'Mention', 'href' => $contact['url'], 'name' => $mention];
349 $terms = Term::tagArrayFromItemId($item['id']);
350 foreach ($terms as $term) {
351 if ($term['type'] == TERM_MENTION) {
352 $contact = Contact::getDetailsByURL($term['url']);
353 if (!empty($contact['addr'])) {
354 $mention = '@' . $contact['addr'];
356 $mention = '@' . $term['url'];
359 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
366 public static function createNote($item)
369 $data['type'] = 'Note';
370 $data['id'] = $item['uri'];
372 if ($item['uri'] != $item['thr-parent']) {
373 $data['inReplyTo'] = $item['thr-parent'];
376 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
377 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
378 $conversation_uri = $conversation['conversation-uri'];
380 $conversation_uri = $item['parent-uri'];
383 $data['context'] = $data['conversation'] = $conversation_uri;
384 $data['actor'] = $item['author-link'];
385 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
386 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
388 if ($item["created"] != $item["edited"]) {
389 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
392 $data['attributedTo'] = $item['author-link'];
393 $data['name'] = BBCode::convert($item['title'], false, 7);
394 $data['content'] = BBCode::convert($item['body'], false, 7);
395 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
396 $data['summary'] = ''; // Ignore by now
397 $data['sensitive'] = false; // - Query NSFW
398 $data['emoji'] = []; // Ignore by now
399 $data['tag'] = self::createTagList($item);
400 $data['attachment'] = []; // @ToDo
404 public static function transmitActivity($activity, $target, $uid)
406 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
408 $owner = User::getOwnerDataById($uid);
410 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
411 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
413 'actor' => $owner['url'],
414 'object' => $profile['url'],
415 'to' => $profile['url']];
417 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
418 return self::transmit($data, $profile['notify'], $uid);
421 public static function transmitContactAccept($target, $id, $uid)
423 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
425 $owner = User::getOwnerDataById($uid);
426 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
427 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
429 'actor' => $owner['url'],
430 'object' => ['id' => $id, 'type' => 'Follow',
431 'actor' => $profile['url'],
432 'object' => $owner['url']],
433 'to' => $profile['url']];
435 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
436 return self::transmit($data, $profile['notify'], $uid);
439 public static function transmitContactReject($target, $id, $uid)
441 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
443 $owner = User::getOwnerDataById($uid);
444 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
445 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
447 'actor' => $owner['url'],
448 'object' => ['id' => $id, 'type' => 'Follow',
449 'actor' => $profile['url'],
450 'object' => $owner['url']],
451 'to' => $profile['url']];
453 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
454 return self::transmit($data, $profile['notify'], $uid);
457 public static function transmitContactUndo($target, $uid)
459 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
461 $id = System::baseUrl() . '/activity/' . System::createGUID();
463 $owner = User::getOwnerDataById($uid);
464 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
467 'actor' => $owner['url'],
468 'object' => ['id' => $id, 'type' => 'Follow',
469 'actor' => $owner['url'],
470 'object' => $profile['url']],
471 'to' => $profile['url']];
473 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
474 return self::transmit($data, $profile['notify'], $uid);
478 * Fetches ActivityPub content from the given url
480 * @param string $url content url
483 public static function fetchContent($url)
485 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
486 if (!$ret['success'] || empty($ret['body'])) {
490 return json_decode($ret['body'], true);
494 * Resolves the profile url from the address by using webfinger
496 * @param string $addr profile address (user@domain.tld)
499 private static function addrToUrl($addr)
501 $addr_parts = explode('@', $addr);
502 if (count($addr_parts) != 2) {
506 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
508 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
509 if (!$ret['success'] || empty($ret['body'])) {
513 $data = json_decode($ret['body'], true);
515 if (empty($data['links'])) {
519 foreach ($data['links'] as $link) {
520 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
524 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
525 return $link['href'];
532 public static function verifySignature($content, $http_headers)
534 $object = json_decode($content, true);
536 if (empty($object)) {
540 $actor = self::processElement($object, 'actor', 'id');
543 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
545 // First take every header
546 foreach ($http_headers as $k => $v) {
547 $field = str_replace('_', '-', strtolower($k));
548 $headers[$field] = $v;
551 // Now add every http header
552 foreach ($http_headers as $k => $v) {
553 if (strpos($k, 'HTTP_') === 0) {
554 $field = str_replace('_', '-', strtolower(substr($k, 5)));
555 $headers[$field] = $v;
559 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
561 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
566 foreach ($sig_block['headers'] as $h) {
567 if (array_key_exists($h, $headers)) {
568 $signed_data .= $h . ': ' . $headers[$h] . "\n";
571 $signed_data = rtrim($signed_data, "\n");
573 if (empty($signed_data)) {
579 if ($sig_block['algorithm'] === 'rsa-sha256') {
580 $algorithm = 'sha256';
583 if ($sig_block['algorithm'] === 'rsa-sha512') {
584 $algorithm = 'sha512';
587 if (empty($algorithm)) {
591 $key = self::fetchKey($sig_block['keyId'], $actor);
597 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
601 // Check the digest when it is part of the signed data
602 if (in_array('digest', $sig_block['headers'])) {
603 $digest = explode('=', $headers['digest'], 2);
604 if ($digest[0] === 'SHA-256') {
607 if ($digest[0] === 'SHA-512') {
611 /// @todo add all hashes from the rfc
613 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
618 // Check the content-length when it is part of the signed data
619 if (in_array('content-length', $sig_block['headers'])) {
620 if (strlen($content) != $headers['content-length']) {
629 private static function fetchKey($id, $actor)
631 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
633 $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
634 if (!empty($profile)) {
635 return $profile['pubkey'];
636 } elseif ($url != $actor) {
637 $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
638 if (!empty($profile)) {
639 return $profile['pubkey'];
649 * @param string $header
650 * @return array associate array with
651 * - \e string \b keyID
652 * - \e string \b algorithm
653 * - \e array \b headers
654 * - \e string \b signature
656 private static function parseSigHeader($header)
661 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
662 $ret['keyId'] = $matches[1];
665 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
666 $ret['algorithm'] = $matches[1];
669 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
670 $ret['headers'] = explode(' ', $matches[1]);
673 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
674 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
681 * Fetches a profile from the given url
683 * @param string $url profile url
686 public static function fetchProfile($url)
688 if (empty(parse_url($url, PHP_URL_SCHEME))) {
689 $url = self::addrToUrl($url);
695 $data = self::fetchContent($url);
697 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
701 $profile = ['network' => Protocol::ACTIVITYPUB];
702 $profile['nick'] = $data['preferredUsername'];
703 $profile['name'] = defaults($data, 'name', $profile['nick']);
704 $profile['guid'] = defaults($data, 'uuid', null);
705 $profile['url'] = $data['id'];
707 $parts = parse_url($profile['url']);
708 unset($parts['scheme']);
709 unset($parts['path']);
710 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
711 $profile['alias'] = self::processElement($data, 'url', 'href');
712 $profile['photo'] = self::processElement($data, 'icon', 'url');
713 // $profile['community']
714 // $profile['keywords']
715 // $profile['location']
716 $profile['about'] = defaults($data, 'summary', '');
717 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
718 $profile['notify'] = $data['inbox'];
719 $profile['poll'] = $data['outbox'];
720 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
722 // Check if the address is resolvable
723 if (self::addrToUrl($profile['addr']) == $profile['url']) {
724 $parts = parse_url($profile['url']);
725 unset($parts['path']);
726 $profile['baseurl'] = Network::unparseURL($parts);
728 unset($profile['addr']);
731 if ($profile['url'] == $profile['alias']) {
732 unset($profile['alias']);
735 // Remove all "null" fields
736 foreach ($profile as $field => $content) {
737 if (is_null($content)) {
738 unset($profile[$field]);
743 // type, manuallyApprovesFollowers
746 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
748 // Unhandled from Misskey
749 // sharedInbox, isCat
751 // Unhandled from Kroeg
752 // kroeg:blocks, updated
757 public static function processInbox($body, $header, $uid)
759 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
761 if (!self::verifySignature($body, $header)) {
762 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
766 $activity = json_decode($body, true);
768 if (!is_array($activity)) {
769 logger('Invalid body.', LOGGER_DEBUG);
773 self::processActivity($activity, $body, $uid);
776 public static function fetchOutbox($url)
778 $data = self::fetchContent($url);
783 if (!empty($data['orderedItems'])) {
784 $items = $data['orderedItems'];
785 } elseif (!empty($data['first']['orderedItems'])) {
786 $items = $data['first']['orderedItems'];
787 } elseif (!empty($data['first'])) {
788 self::fetchOutbox($data['first']);
794 foreach ($items as $activity) {
795 self::processActivity($activity);
799 private static function prepareObjectData($activity, $uid)
801 $actor = self::processElement($activity, 'actor', 'id');
803 logger('Empty actor', LOGGER_DEBUG);
807 // Fetch all receivers from to, cc, bto and bcc
808 $receivers = self::getReceivers($activity, $actor);
810 // When it is a delivery to a personal inbox we add that user to the receivers
812 $owner = User::getOwnerDataById($uid);
813 $additional = ['uid:' . $uid => $uid];
814 $receivers = array_merge($receivers, $additional);
817 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
819 $public = in_array(0, $receivers);
821 if (is_string($activity['object'])) {
822 $object_url = $activity['object'];
823 } elseif (!empty($activity['object']['id'])) {
824 $object_url = $activity['object']['id'];
826 logger('No object found', LOGGER_DEBUG);
830 // Fetch the content only on activities where this matters
831 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
832 $object_data = self::fetchObject($object_url, $activity['object']);
833 if (empty($object_data)) {
834 logger("Object data couldn't be processed", LOGGER_DEBUG);
837 } elseif ($activity['type'] == 'Accept') {
839 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
840 $object_data['object'] = self::processElement($activity, 'object', 'actor');
841 } elseif ($activity['type'] == 'Undo') {
843 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
844 $object_data['object'] = self::processElement($activity, 'object', 'object');
845 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
846 // Create a mostly empty array out of the activity data (instead of the object).
847 // This way we later don't have to check for the existence of ech individual array element.
848 $object_data = self::processCommonData($activity);
849 $object_data['name'] = $activity['type'];
850 $object_data['author'] = $activity['actor'];
851 $object_data['object'] = $object_url;
852 } elseif ($activity['type'] == 'Follow') {
853 $object_data['id'] = $activity['id'];
854 $object_data['object'] = $object_url;
859 $object_data = self::addActivityFields($object_data, $activity);
861 $object_data['type'] = $activity['type'];
862 $object_data['owner'] = $actor;
863 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
868 private static function processActivity($activity, $body = '', $uid = null)
870 if (empty($activity['type'])) {
871 logger('Empty type', LOGGER_DEBUG);
875 if (empty($activity['object'])) {
876 logger('Empty object', LOGGER_DEBUG);
880 if (empty($activity['actor'])) {
881 logger('Empty actor', LOGGER_DEBUG);
887 // title, atomUri, context_id, statusnetConversationId
890 // context, location, signature;
892 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
894 $object_data = self::prepareObjectData($activity, $uid);
895 if (empty($object_data)) {
896 logger('No object data found', LOGGER_DEBUG);
900 switch ($activity['type']) {
903 self::createItem($object_data, $body);
907 self::likeItem($object_data, $body);
920 self::followUser($object_data);
924 if ($object_data['object_type'] == 'Follow') {
925 self::acceptFollowUser($object_data);
930 if ($object_data['object_type'] == 'Follow') {
931 self::undoFollowUser($object_data);
936 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
941 private static function getReceivers($activity, $actor)
945 if (!empty($actor)) {
946 $data = self::fetchContent($actor);
947 $followers = defaults($data, 'followers', '');
949 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
951 logger('Empty actor', LOGGER_DEBUG);
955 $elements = ['to', 'cc', 'bto', 'bcc'];
956 foreach ($elements as $element) {
957 if (empty($activity[$element])) {
961 // The receiver can be an arror or a string
962 if (is_string($activity[$element])) {
963 $activity[$element] = [$activity[$element]];
966 foreach ($activity[$element] as $receiver) {
967 if ($receiver == self::PUBLIC) {
968 $receivers['uid:0'] = 0;
971 if (($receiver == self::PUBLIC) && !empty($actor)) {
972 // This will most likely catch all OStatus connections to Mastodon
973 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
974 $contacts = DBA::select('contact', ['uid'], $condition);
975 while ($contact = DBA::fetch($contacts)) {
976 if ($contact['uid'] != 0) {
977 $receivers['uid:' . $contact['uid']] = $contact['uid'];
980 DBA::close($contacts);
983 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
984 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
985 'network' => Protocol::ACTIVITYPUB];
986 $contacts = DBA::select('contact', ['uid'], $condition);
987 while ($contact = DBA::fetch($contacts)) {
988 if ($contact['uid'] != 0) {
989 $receivers['uid:' . $contact['uid']] = $contact['uid'];
992 DBA::close($contacts);
996 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
997 $contact = DBA::selectFirst('contact', ['uid'], $condition);
998 if (!DBA::isResult($contact)) {
1001 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1007 private static function addActivityFields($object_data, $activity)
1009 if (!empty($activity['published']) && empty($object_data['published'])) {
1010 $object_data['published'] = $activity['published'];
1013 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1014 $object_data['updated'] = $activity['updated'];
1017 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1018 $object_data['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
1021 if (!empty($activity['instrument'])) {
1022 $object_data['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
1024 return $object_data;
1027 private static function fetchObject($object_url, $object = [], $public = true)
1030 $data = self::fetchContent($object_url);
1032 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1033 $data = $object_url;
1037 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1041 if (is_string($data)) {
1042 $item = Item::selectFirst([], ['uri' => $data]);
1043 if (!DBA::isResult($item)) {
1044 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1047 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1048 $data = self::createNote($item);
1051 if (empty($data['type'])) {
1052 logger('Empty type', LOGGER_DEBUG);
1055 $type = $data['type'];
1056 logger('Type ' . $type, LOGGER_DEBUG);
1059 if (in_array($type, ['Note', 'Article', 'Video'])) {
1060 $common = self::processCommonData($data);
1065 return array_merge($common, self::processNote($data));
1067 return array_merge($common, self::processArticle($data));
1069 return array_merge($common, self::processVideo($data));
1072 if (empty($data['object'])) {
1075 return self::fetchObject($data['object']);
1082 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1087 private static function processCommonData(&$object)
1089 if (empty($object['id'])) {
1094 $object_data['type'] = $object['type'];
1095 $object_data['uri'] = $object['id'];
1097 if (!empty($object['inReplyTo'])) {
1098 $object_data['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
1100 $object_data['reply-to-uri'] = $object_data['uri'];
1103 $object_data['published'] = defaults($object, 'published', null);
1104 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1106 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1107 $object_data['published'] = $object_data['updated'];
1110 $object_data['uuid'] = defaults($object, 'uuid', null);
1111 $object_data['owner'] = $object_data['author'] = self::processElement($object, 'attributedTo', 'id');
1112 $object_data['context'] = defaults($object, 'context', null);
1113 $object_data['conversation'] = defaults($object, 'conversation', null);
1114 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1115 $object_data['name'] = defaults($object, 'title', null);
1116 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1117 $object_data['summary'] = defaults($object, 'summary', null);
1118 $object_data['content'] = defaults($object, 'content', null);
1119 $object_data['source'] = defaults($object, 'source', null);
1120 $object_data['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
1121 $object_data['attachments'] = defaults($object, 'attachment', null);
1122 $object_data['tags'] = defaults($object, 'tag', null);
1123 $object_data['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
1124 $object_data['alternate-url'] = self::processElement($object, 'url', 'href');
1125 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1128 // @context, type, actor, signature, mediaType, duration, replies, icon
1130 // Also missing: (Defined in the standard, but currently unused)
1131 // audience, preview, endTime, startTime, generator, image
1133 return $object_data;
1136 private static function processNote($object)
1141 // emoji, atomUri, inReplyToAtomUri
1144 // contentMap, announcement_count, announcements, context_id, likes, like_count
1145 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1147 return $object_data;
1150 private static function processArticle($object)
1154 return $object_data;
1157 private static function processVideo($object)
1162 // category, licence, language, commentsEnabled
1165 // views, waitTranscoding, state, support, subtitleLanguage
1166 // likes, dislikes, shares, comments
1168 return $object_data;
1171 private static function processElement($array, $element, $key, $type = null, $type_value = null)
1173 if (empty($array)) {
1177 if (empty($array[$element])) {
1181 if (is_string($array[$element])) {
1182 return $array[$element];
1185 if (is_null($type_value)) {
1186 if (!empty($array[$element][$key])) {
1187 return $array[$element][$key];
1190 if (!empty($array[$element][0][$key])) {
1191 return $array[$element][0][$key];
1197 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
1198 return $array[$element][$key];
1201 /// @todo Add array search
1206 private static function convertMentions($body)
1208 $URLSearchString = "^\[\]";
1209 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1214 private static function constructTagList($tags, $sensitive)
1221 foreach ($tags as $tag) {
1222 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1223 if (!empty($tag_text)) {
1227 if (empty($tag['href'])) {
1232 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1236 /// @todo add nsfw for $sensitive
1241 private static function constructAttachList($attachments, $item)
1243 if (empty($attachments)) {
1247 foreach ($attachments as $attach) {
1248 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1249 if ($filetype == 'image') {
1250 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1252 if (!empty($item["attach"])) {
1253 $item["attach"] .= ',';
1255 $item["attach"] = '';
1257 if (!isset($attach['length'])) {
1258 $attach['length'] = "0";
1260 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1267 private static function createItem($activity, $body)
1270 $item['verb'] = ACTIVITY_POST;
1271 $item['parent-uri'] = $activity['reply-to-uri'];
1273 if ($activity['reply-to-uri'] == $activity['uri']) {
1274 $item['gravity'] = GRAVITY_PARENT;
1275 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1277 $item['gravity'] = GRAVITY_COMMENT;
1278 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1281 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1282 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1283 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1286 self::postItem($activity, $item, $body);
1289 private static function likeItem($activity, $body)
1292 $item['verb'] = ACTIVITY_LIKE;
1293 $item['parent-uri'] = $activity['object'];
1294 $item['gravity'] = GRAVITY_ACTIVITY;
1295 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1297 self::postItem($activity, $item, $body);
1300 private static function postItem($activity, $item, $body)
1302 /// @todo What to do with $activity['context']?
1304 $item['network'] = Protocol::ACTIVITYPUB;
1305 $item['private'] = !in_array(0, $activity['receiver']);
1306 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1307 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1308 $item['uri'] = $activity['uri'];
1309 $item['created'] = $activity['published'];
1310 $item['edited'] = $activity['updated'];
1311 $item['guid'] = $activity['uuid'];
1312 $item['title'] = HTML::toBBCode($activity['name']);
1313 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1314 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1315 $item['location'] = $activity['location'];
1316 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1317 $item['app'] = $activity['service'];
1318 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1320 $item = self::constructAttachList($activity['attachments'], $item);
1322 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1323 if (!empty($source)) {
1324 $item['body'] = $source;
1327 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1328 $item['source'] = $body;
1329 $item['conversation-uri'] = $activity['conversation'];
1331 foreach ($activity['receiver'] as $receiver) {
1332 $item['uid'] = $receiver;
1333 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1335 if (($receiver != 0) && empty($item['contact-id'])) {
1336 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1339 $item_id = Item::insert($item);
1340 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1344 private static function fetchMissingActivity($url, $child)
1346 $object = ActivityPub::fetchContent($url);
1347 if (empty($object)) {
1348 logger('Activity ' . $url . ' was not fetchable, aborting.');
1353 $activity['@context'] = $object['@context'];
1354 unset($object['@context']);
1355 $activity['id'] = $object['id'];
1356 $activity['to'] = defaults($object, 'to', []);
1357 $activity['cc'] = defaults($object, 'cc', []);
1358 $activity['actor'] = $activity['author'];
1359 $activity['object'] = $object;
1360 $activity['published'] = $object['published'];
1361 $activity['type'] = 'Create';
1362 self::processActivity($activity);
1363 logger('Activity ' . $url . ' had been fetched and processed.');
1366 private static function getUserOfObject($object)
1368 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1369 if (!DBA::isResult($self)) {
1372 return $self['uid'];
1376 private static function followUser($activity)
1378 $uid = self::getUserOfObject($activity['object']);
1383 $owner = User::getOwnerDataById($uid);
1385 $cid = Contact::getIdForURL($activity['owner'], $uid);
1387 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1392 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1393 'author-link' => $activity['owner']];
1395 Contact::addRelationship($owner, $contact, $item);
1396 $cid = Contact::getIdForURL($activity['owner'], $uid);
1401 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1402 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1403 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1406 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1407 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1410 private static function acceptFollowUser($activity)
1412 $uid = self::getUserOfObject($activity['object']);
1417 $owner = User::getOwnerDataById($uid);
1419 $cid = Contact::getIdForURL($activity['owner'], $uid);
1421 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1425 $fields = ['pending' => false];
1427 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1428 if ($contact['rel'] == Contact::FOLLOWER) {
1429 $fields['rel'] = Contact::FRIEND;
1432 $condition = ['id' => $cid];
1433 DBA::update('contact', $fields, $condition);
1434 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1437 private static function undoFollowUser($activity)
1439 $uid = self::getUserOfObject($activity['object']);
1444 $owner = User::getOwnerDataById($uid);
1446 $cid = Contact::getIdForURL($activity['owner'], $uid);
1448 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1452 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1453 if (!DBA::isResult($contact)) {
1457 Contact::removeFollower($owner, $contact);
1458 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);