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 $receiver_list = Item::enumeratePermissions($item);
181 foreach ($terms as $term) {
182 if ($term['type'] != TERM_MENTION) {
185 $cid = Contact::getIdForURL($term['url'], $item['uid']);
186 if (!empty($cid) && in_array($cid, $receiver_list)) {
187 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
188 $data['to'][] = $contact['url'];
192 foreach ($receiver_list as $receiver) {
193 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
194 $data['cc'][] = $contact['url'];
197 if (empty($data['to'])) {
198 $data['to'] = $data['cc'];
206 public static function fetchTargetInboxes($item)
210 $terms = Term::tagArrayFromItemId($item['id']);
211 if (!$item['private']) {
212 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $item['uid'], 'network' => Protocol::ACTIVITYPUB]);
213 while ($contact = DBA::fetch($contacts)) {
214 $contact = defaults($contact, 'batch', $contact['notify']);
215 $inboxes[$contact] = $contact;
217 DBA::close($contacts);
219 foreach ($terms as $term) {
220 if ($term['type'] != TERM_MENTION) {
223 $profile = Probe::uri($term['url'], Protocol::ACTIVITYPUB);
224 if ($profile['network'] == Protocol::ACTIVITYPUB) {
225 $target = defaults($profile, 'batch', $profile['notify']);
226 $inboxes[$target] = $target;
230 $receiver_list = Item::enumeratePermissions($item);
234 foreach ($terms as $term) {
235 if ($term['type'] != TERM_MENTION) {
238 $cid = Contact::getIdForURL($term['url'], $item['uid']);
239 if (!empty($cid) && in_array($cid, $receiver_list)) {
240 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
241 $profile = Probe::uri($contact['url'], Protocol::ACTIVITYPUB);
242 if ($profile['network'] == Protocol::ACTIVITYPUB) {
243 $target = defaults($profile, 'batch', $profile['notify']);
244 $inboxes[$target] = $target;
249 foreach ($receiver_list as $receiver) {
250 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
251 $profile = Probe::uri($contact['url'], Protocol::ACTIVITYPUB);
252 if ($profile['network'] == Protocol::ACTIVITYPUB) {
253 $target = defaults($profile, 'batch', $profile['notify']);
254 $inboxes[$target] = $target;
262 public static function createActivityFromItem($item_id)
264 $item = Item::selectFirst([], ['id' => $item_id]);
266 if (!DBA::isResult($item)) {
270 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
271 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
272 if (DBA::isResult($conversation)) {
273 $data = json_decode($conversation['source']);
279 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
280 ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
281 'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
282 'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
283 'toot' => 'http://joinmastodon.org/ns#']]];
285 $data['type'] = 'Create';
286 $data['id'] = $item['uri'] . '#activity';
287 $data['actor'] = $item['author-link'];
288 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
290 $data['object'] = self::createNote($item);
294 public static function createObjectFromItemID($item_id)
296 $item = Item::selectFirst([], ['id' => $item_id]);
298 if (!DBA::isResult($item)) {
302 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
303 ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
304 'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
305 'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
306 'toot' => 'http://joinmastodon.org/ns#']]];
308 $data = array_merge($data, self::createNote($item));
314 public static function createNote($item)
317 $data['type'] = 'Note';
318 $data['id'] = $item['uri'];
320 if ($item['uri'] != $item['thr-parent']) {
321 $data['inReplyTo'] = $item['thr-parent'];
324 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
325 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
326 $conversation_uri = $conversation['conversation-uri'];
328 $conversation_uri = $item['parent-uri'];
331 $data['context'] = $data['conversation'] = $conversation_uri;
332 $data['actor'] = $item['author-link'];
333 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
334 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
335 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
336 $data['attributedTo'] = $item['author-link'];
337 $data['name'] = BBCode::convert($item['title'], false, 7);
338 $data['content'] = BBCode::convert($item['body'], false, 7);
339 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
340 //$data['summary'] = ''; // Ignore by now
341 //$data['sensitive'] = false; // - Query NSFW
342 //$data['emoji'] = []; // Ignore by now
343 //$data['tag'] = []; /// @ToDo
344 //$data['attachment'] = []; // @ToDo
348 public static function transmitActivity($activity, $target, $uid)
350 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
352 $owner = User::getOwnerDataById($uid);
354 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
355 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
357 'actor' => $owner['url'],
358 'object' => $profile['url'],
359 'to' => $profile['url']];
361 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
362 return self::transmit($data, $profile['notify'], $uid);
365 public static function transmitContactAccept($target, $id, $uid)
367 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
369 $owner = User::getOwnerDataById($uid);
370 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
371 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
373 'actor' => $owner['url'],
374 'object' => ['id' => $id, 'type' => 'Follow',
375 'actor' => $profile['url'],
376 'object' => $owner['url']],
377 'to' => $profile['url']];
379 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
380 return self::transmit($data, $profile['notify'], $uid);
383 public static function transmitContactReject($target, $id, $uid)
385 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
387 $owner = User::getOwnerDataById($uid);
388 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
389 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
391 'actor' => $owner['url'],
392 'object' => ['id' => $id, 'type' => 'Follow',
393 'actor' => $profile['url'],
394 'object' => $owner['url']],
395 'to' => $profile['url']];
397 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
398 return self::transmit($data, $profile['notify'], $uid);
401 public static function transmitContactUndo($target, $uid)
403 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
405 $id = System::baseUrl() . '/activity/' . System::createGUID();
407 $owner = User::getOwnerDataById($uid);
408 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
411 'actor' => $owner['url'],
412 'object' => ['id' => $id, 'type' => 'Follow',
413 'actor' => $owner['url'],
414 'object' => $profile['url']],
415 'to' => $profile['url']];
417 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
418 return self::transmit($data, $profile['notify'], $uid);
422 * Fetches ActivityPub content from the given url
424 * @param string $url content url
427 public static function fetchContent($url)
429 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
430 if (!$ret['success'] || empty($ret['body'])) {
434 return json_decode($ret['body'], true);
438 * Resolves the profile url from the address by using webfinger
440 * @param string $addr profile address (user@domain.tld)
443 private static function addrToUrl($addr)
445 $addr_parts = explode('@', $addr);
446 if (count($addr_parts) != 2) {
450 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
452 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
453 if (!$ret['success'] || empty($ret['body'])) {
457 $data = json_decode($ret['body'], true);
459 if (empty($data['links'])) {
463 foreach ($data['links'] as $link) {
464 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
468 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
469 return $link['href'];
476 public static function verifySignature($content, $http_headers)
478 $object = json_decode($content, true);
480 if (empty($object)) {
484 $actor = self::processElement($object, 'actor', 'id');
487 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
489 // First take every header
490 foreach ($http_headers as $k => $v) {
491 $field = str_replace('_', '-', strtolower($k));
492 $headers[$field] = $v;
495 // Now add every http header
496 foreach ($http_headers as $k => $v) {
497 if (strpos($k, 'HTTP_') === 0) {
498 $field = str_replace('_', '-', strtolower(substr($k, 5)));
499 $headers[$field] = $v;
503 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
505 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
510 foreach ($sig_block['headers'] as $h) {
511 if (array_key_exists($h, $headers)) {
512 $signed_data .= $h . ': ' . $headers[$h] . "\n";
515 $signed_data = rtrim($signed_data, "\n");
517 if (empty($signed_data)) {
523 if ($sig_block['algorithm'] === 'rsa-sha256') {
524 $algorithm = 'sha256';
527 if ($sig_block['algorithm'] === 'rsa-sha512') {
528 $algorithm = 'sha512';
531 if (empty($algorithm)) {
535 $key = self::fetchKey($sig_block['keyId'], $actor);
541 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
545 // Check the digest when it is part of the signed data
546 if (in_array('digest', $sig_block['headers'])) {
547 $digest = explode('=', $headers['digest'], 2);
548 if ($digest[0] === 'SHA-256') {
551 if ($digest[0] === 'SHA-512') {
555 /// @todo add all hashes from the rfc
557 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
562 // Check the content-length when it is part of the signed data
563 if (in_array('content-length', $sig_block['headers'])) {
564 if (strlen($content) != $headers['content-length']) {
573 private static function fetchKey($id, $actor)
575 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
577 $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
578 if (!empty($profile)) {
579 return $profile['pubkey'];
580 } elseif ($url != $actor) {
581 $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
582 if (!empty($profile)) {
583 return $profile['pubkey'];
593 * @param string $header
594 * @return array associate array with
595 * - \e string \b keyID
596 * - \e string \b algorithm
597 * - \e array \b headers
598 * - \e string \b signature
600 private static function parseSigHeader($header)
605 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
606 $ret['keyId'] = $matches[1];
609 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
610 $ret['algorithm'] = $matches[1];
613 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
614 $ret['headers'] = explode(' ', $matches[1]);
617 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
618 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
625 * Fetches a profile from the given url
627 * @param string $url profile url
630 public static function fetchProfile($url)
632 if (empty(parse_url($url, PHP_URL_SCHEME))) {
633 $url = self::addrToUrl($url);
639 $data = self::fetchContent($url);
641 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
645 $profile = ['network' => Protocol::ACTIVITYPUB];
646 $profile['nick'] = $data['preferredUsername'];
647 $profile['name'] = defaults($data, 'name', $profile['nick']);
648 $profile['guid'] = defaults($data, 'uuid', null);
649 $profile['url'] = $data['id'];
651 $parts = parse_url($profile['url']);
652 unset($parts['scheme']);
653 unset($parts['path']);
654 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
655 $profile['alias'] = self::processElement($data, 'url', 'href');
656 $profile['photo'] = self::processElement($data, 'icon', 'url');
657 // $profile['community']
658 // $profile['keywords']
659 // $profile['location']
660 $profile['about'] = defaults($data, 'summary', '');
661 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
662 $profile['notify'] = $data['inbox'];
663 $profile['poll'] = $data['outbox'];
664 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
666 // Check if the address is resolvable
667 if (self::addrToUrl($profile['addr']) == $profile['url']) {
668 $parts = parse_url($profile['url']);
669 unset($parts['path']);
670 $profile['baseurl'] = Network::unparseURL($parts);
672 unset($profile['addr']);
675 if ($profile['url'] == $profile['alias']) {
676 unset($profile['alias']);
679 // Remove all "null" fields
680 foreach ($profile as $field => $content) {
681 if (is_null($content)) {
682 unset($profile[$field]);
687 // type, manuallyApprovesFollowers
690 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
692 // Unhandled from Misskey
693 // sharedInbox, isCat
695 // Unhandled from Kroeg
696 // kroeg:blocks, updated
701 public static function processInbox($body, $header, $uid)
703 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
705 if (!self::verifySignature($body, $header)) {
706 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
710 $activity = json_decode($body, true);
712 if (!is_array($activity)) {
713 logger('Invalid body.', LOGGER_DEBUG);
717 self::processActivity($activity, $body, $uid);
720 public static function fetchOutbox($url)
722 $data = self::fetchContent($url);
727 if (!empty($data['orderedItems'])) {
728 $items = $data['orderedItems'];
729 } elseif (!empty($data['first']['orderedItems'])) {
730 $items = $data['first']['orderedItems'];
731 } elseif (!empty($data['first'])) {
732 self::fetchOutbox($data['first']);
738 foreach ($items as $activity) {
739 self::processActivity($activity);
743 private static function prepareObjectData($activity, $uid)
745 $actor = self::processElement($activity, 'actor', 'id');
747 logger('Empty actor', LOGGER_DEBUG);
751 // Fetch all receivers from to, cc, bto and bcc
752 $receivers = self::getReceivers($activity, $actor);
754 // When it is a delivery to a personal inbox we add that user to the receivers
756 $owner = User::getOwnerDataById($uid);
757 $additional = ['uid:' . $uid => $uid];
758 $receivers = array_merge($receivers, $additional);
761 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
763 $public = in_array(0, $receivers);
765 if (is_string($activity['object'])) {
766 $object_url = $activity['object'];
767 } elseif (!empty($activity['object']['id'])) {
768 $object_url = $activity['object']['id'];
770 logger('No object found', LOGGER_DEBUG);
774 // Fetch the content only on activities where this matters
775 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
776 $object_data = self::fetchObject($object_url, $activity['object']);
777 if (empty($object_data)) {
778 logger("Object data couldn't be processed", LOGGER_DEBUG);
781 } elseif ($activity['type'] == 'Accept') {
783 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
784 $object_data['object'] = self::processElement($activity, 'object', 'actor');
785 } elseif ($activity['type'] == 'Undo') {
787 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
788 $object_data['object'] = self::processElement($activity, 'object', 'object');
789 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
790 // Create a mostly empty array out of the activity data (instead of the object).
791 // This way we later don't have to check for the existence of ech individual array element.
792 $object_data = self::processCommonData($activity);
793 $object_data['name'] = $activity['type'];
794 $object_data['author'] = $activity['actor'];
795 $object_data['object'] = $object_url;
796 } elseif ($activity['type'] == 'Follow') {
797 $object_data['id'] = $activity['id'];
798 $object_data['object'] = $object_url;
803 $object_data = self::addActivityFields($object_data, $activity);
805 $object_data['type'] = $activity['type'];
806 $object_data['owner'] = $actor;
807 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
812 private static function processActivity($activity, $body = '', $uid = null)
814 if (empty($activity['type'])) {
815 logger('Empty type', LOGGER_DEBUG);
819 if (empty($activity['object'])) {
820 logger('Empty object', LOGGER_DEBUG);
824 if (empty($activity['actor'])) {
825 logger('Empty actor', LOGGER_DEBUG);
831 // title, atomUri, context_id, statusnetConversationId
834 // context, location, signature;
836 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
838 $object_data = self::prepareObjectData($activity, $uid);
839 if (empty($object_data)) {
840 logger('No object data found', LOGGER_DEBUG);
844 switch ($activity['type']) {
847 self::createItem($object_data, $body);
851 self::likeItem($object_data, $body);
864 self::followUser($object_data);
868 if ($object_data['object_type'] == 'Follow') {
869 self::acceptFollowUser($object_data);
874 if ($object_data['object_type'] == 'Follow') {
875 self::undoFollowUser($object_data);
880 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
885 private static function getReceivers($activity, $actor)
889 if (!empty($actor)) {
890 $data = self::fetchContent($actor);
891 $followers = defaults($data, 'followers', '');
893 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
895 logger('Empty actor', LOGGER_DEBUG);
899 $elements = ['to', 'cc', 'bto', 'bcc'];
900 foreach ($elements as $element) {
901 if (empty($activity[$element])) {
905 // The receiver can be an arror or a string
906 if (is_string($activity[$element])) {
907 $activity[$element] = [$activity[$element]];
910 foreach ($activity[$element] as $receiver) {
911 if ($receiver == self::PUBLIC) {
912 $receivers['uid:0'] = 0;
915 if (($receiver == self::PUBLIC) && !empty($actor)) {
916 // This will most likely catch all OStatus connections to Mastodon
917 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
918 $contacts = DBA::select('contact', ['uid'], $condition);
919 while ($contact = DBA::fetch($contacts)) {
920 if ($contact['uid'] != 0) {
921 $receivers['uid:' . $contact['uid']] = $contact['uid'];
924 DBA::close($contacts);
927 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
928 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
929 'network' => Protocol::ACTIVITYPUB];
930 $contacts = DBA::select('contact', ['uid'], $condition);
931 while ($contact = DBA::fetch($contacts)) {
932 if ($contact['uid'] != 0) {
933 $receivers['uid:' . $contact['uid']] = $contact['uid'];
936 DBA::close($contacts);
940 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
941 $contact = DBA::selectFirst('contact', ['uid'], $condition);
942 if (!DBA::isResult($contact)) {
945 $receivers['uid:' . $contact['uid']] = $contact['uid'];
951 private static function addActivityFields($object_data, $activity)
953 if (!empty($activity['published']) && empty($object_data['published'])) {
954 $object_data['published'] = $activity['published'];
957 if (!empty($activity['updated']) && empty($object_data['updated'])) {
958 $object_data['updated'] = $activity['updated'];
961 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
962 $object_data['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
965 if (!empty($activity['instrument'])) {
966 $object_data['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
971 private static function fetchObject($object_url, $object = [], $public = true)
974 $data = self::fetchContent($object_url);
976 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
981 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
985 if (is_string($data)) {
986 $item = Item::selectFirst([], ['uri' => $data]);
987 if (!DBA::isResult($item)) {
988 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
991 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
992 $data = self::createNote($item);
995 if (empty($data['type'])) {
996 logger('Empty type', LOGGER_DEBUG);
999 $type = $data['type'];
1000 logger('Type ' . $type, LOGGER_DEBUG);
1003 if (in_array($type, ['Note', 'Article', 'Video'])) {
1004 $common = self::processCommonData($data);
1009 return array_merge($common, self::processNote($data));
1011 return array_merge($common, self::processArticle($data));
1013 return array_merge($common, self::processVideo($data));
1016 if (empty($data['object'])) {
1019 return self::fetchObject($data['object']);
1026 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1031 private static function processCommonData(&$object)
1033 if (empty($object['id'])) {
1038 $object_data['type'] = $object['type'];
1039 $object_data['uri'] = $object['id'];
1041 if (!empty($object['inReplyTo'])) {
1042 $object_data['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
1044 $object_data['reply-to-uri'] = $object_data['uri'];
1047 $object_data['published'] = defaults($object, 'published', null);
1048 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1050 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1051 $object_data['published'] = $object_data['updated'];
1054 $object_data['uuid'] = defaults($object, 'uuid', null);
1055 $object_data['owner'] = $object_data['author'] = self::processElement($object, 'attributedTo', 'id');
1056 $object_data['context'] = defaults($object, 'context', null);
1057 $object_data['conversation'] = defaults($object, 'conversation', null);
1058 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1059 $object_data['name'] = defaults($object, 'title', null);
1060 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1061 $object_data['summary'] = defaults($object, 'summary', null);
1062 $object_data['content'] = defaults($object, 'content', null);
1063 $object_data['source'] = defaults($object, 'source', null);
1064 $object_data['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
1065 $object_data['attachments'] = defaults($object, 'attachment', null);
1066 $object_data['tags'] = defaults($object, 'tag', null);
1067 $object_data['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
1068 $object_data['alternate-url'] = self::processElement($object, 'url', 'href');
1069 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1072 // @context, type, actor, signature, mediaType, duration, replies, icon
1074 // Also missing: (Defined in the standard, but currently unused)
1075 // audience, preview, endTime, startTime, generator, image
1077 return $object_data;
1080 private static function processNote($object)
1085 // emoji, atomUri, inReplyToAtomUri
1088 // contentMap, announcement_count, announcements, context_id, likes, like_count
1089 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1091 return $object_data;
1094 private static function processArticle($object)
1098 return $object_data;
1101 private static function processVideo($object)
1106 // category, licence, language, commentsEnabled
1109 // views, waitTranscoding, state, support, subtitleLanguage
1110 // likes, dislikes, shares, comments
1112 return $object_data;
1115 private static function processElement($array, $element, $key, $type = null, $type_value = null)
1117 if (empty($array)) {
1121 if (empty($array[$element])) {
1125 if (is_string($array[$element])) {
1126 return $array[$element];
1129 if (is_null($type_value)) {
1130 if (!empty($array[$element][$key])) {
1131 return $array[$element][$key];
1134 if (!empty($array[$element][0][$key])) {
1135 return $array[$element][0][$key];
1141 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
1142 return $array[$element][$key];
1145 /// @todo Add array search
1150 private static function convertMentions($body)
1152 $URLSearchString = "^\[\]";
1153 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1158 private static function constructTagList($tags, $sensitive)
1165 foreach ($tags as $tag) {
1166 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1167 if (!empty($tag_text)) {
1171 if (empty($tag['href'])) {
1176 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1180 /// @todo add nsfw for $sensitive
1185 private static function constructAttachList($attachments, $item)
1187 if (empty($attachments)) {
1191 foreach ($attachments as $attach) {
1192 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1193 if ($filetype == 'image') {
1194 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1196 if (!empty($item["attach"])) {
1197 $item["attach"] .= ',';
1199 $item["attach"] = '';
1201 if (!isset($attach['length'])) {
1202 $attach['length'] = "0";
1204 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1211 private static function createItem($activity, $body)
1214 $item['verb'] = ACTIVITY_POST;
1215 $item['parent-uri'] = $activity['reply-to-uri'];
1217 if ($activity['reply-to-uri'] == $activity['uri']) {
1218 $item['gravity'] = GRAVITY_PARENT;
1219 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1221 $item['gravity'] = GRAVITY_COMMENT;
1222 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1225 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1226 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1227 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1230 self::postItem($activity, $item, $body);
1233 private static function likeItem($activity, $body)
1236 $item['verb'] = ACTIVITY_LIKE;
1237 $item['parent-uri'] = $activity['object'];
1238 $item['gravity'] = GRAVITY_ACTIVITY;
1239 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1241 self::postItem($activity, $item, $body);
1244 private static function postItem($activity, $item, $body)
1246 /// @todo What to do with $activity['context']?
1248 $item['network'] = Protocol::ACTIVITYPUB;
1249 $item['private'] = !in_array(0, $activity['receiver']);
1250 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1251 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1252 $item['uri'] = $activity['uri'];
1253 $item['created'] = $activity['published'];
1254 $item['edited'] = $activity['updated'];
1255 $item['guid'] = $activity['uuid'];
1256 $item['title'] = HTML::toBBCode($activity['name']);
1257 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1258 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1259 $item['location'] = $activity['location'];
1260 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1261 $item['app'] = $activity['service'];
1262 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1264 $item = self::constructAttachList($activity['attachments'], $item);
1266 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1267 if (!empty($source)) {
1268 $item['body'] = $source;
1271 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1272 $item['source'] = $body;
1273 $item['conversation-uri'] = $activity['conversation'];
1275 foreach ($activity['receiver'] as $receiver) {
1276 $item['uid'] = $receiver;
1277 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1279 if (($receiver != 0) && empty($item['contact-id'])) {
1280 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1283 $item_id = Item::insert($item);
1284 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1288 private static function fetchMissingActivity($url, $child)
1290 $object = ActivityPub::fetchContent($url);
1291 if (empty($object)) {
1292 logger('Activity ' . $url . ' was not fetchable, aborting.');
1297 $activity['@context'] = $object['@context'];
1298 unset($object['@context']);
1299 $activity['id'] = $object['id'];
1300 $activity['to'] = defaults($object, 'to', []);
1301 $activity['cc'] = defaults($object, 'cc', []);
1302 $activity['actor'] = $activity['author'];
1303 $activity['object'] = $object;
1304 $activity['published'] = $object['published'];
1305 $activity['type'] = 'Create';
1306 self::processActivity($activity);
1307 logger('Activity ' . $url . ' had been fetched and processed.');
1310 private static function getUserOfObject($object)
1312 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1313 if (!DBA::isResult($self)) {
1316 return $self['uid'];
1320 private static function followUser($activity)
1322 $uid = self::getUserOfObject($activity['object']);
1327 $owner = User::getOwnerDataById($uid);
1329 $cid = Contact::getIdForURL($activity['owner'], $uid);
1331 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1336 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1337 'author-link' => $activity['owner']];
1339 Contact::addRelationship($owner, $contact, $item);
1340 $cid = Contact::getIdForURL($activity['owner'], $uid);
1345 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1346 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1347 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1350 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1351 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1354 private static function acceptFollowUser($activity)
1356 $uid = self::getUserOfObject($activity['object']);
1361 $owner = User::getOwnerDataById($uid);
1363 $cid = Contact::getIdForURL($activity['owner'], $uid);
1365 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1369 $fields = ['pending' => false];
1371 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1372 if ($contact['rel'] == Contact::FOLLOWER) {
1373 $fields['rel'] = Contact::FRIEND;
1376 $condition = ['id' => $cid];
1377 DBA::update('contact', $fields, $condition);
1378 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1381 private static function undoFollowUser($activity)
1383 $uid = self::getUserOfObject($activity['object']);
1388 $owner = User::getOwnerDataById($uid);
1390 $cid = Contact::getIdForURL($activity['owner'], $uid);
1392 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1396 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1397 if (!DBA::isResult($contact)) {
1401 Contact::removeFollower($owner, $contact);
1402 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);